CGameState.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  1. /*
  2. * CGameState.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CGameState.h"
  12. #include "EVictoryLossCheckResult.h"
  13. #include "InfoAboutArmy.h"
  14. #include "CGameStateCampaign.h"
  15. #include "../ArtifactUtils.h"
  16. #include "../CBuildingHandler.h"
  17. #include "../CGeneralTextHandler.h"
  18. #include "../CHeroHandler.h"
  19. #include "../CPlayerState.h"
  20. #include "../CStopWatch.h"
  21. #include "../GameSettings.h"
  22. #include "../StartInfo.h"
  23. #include "../TerrainHandler.h"
  24. #include "../VCMIDirs.h"
  25. #include "../VCMI_Lib.h"
  26. #include "../battle/BattleInfo.h"
  27. #include "../filesystem/ResourceID.h"
  28. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  29. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  30. #include "../mapObjectConstructors/DwellingInstanceConstructor.h"
  31. #include "../mapObjects/CGHeroInstance.h"
  32. #include "../mapObjects/CGTownInstance.h"
  33. #include "../mapping/CCampaignHandler.h"
  34. #include "../mapping/CMap.h"
  35. #include "../mapping/CMapEditManager.h"
  36. #include "../mapping/CMapService.h"
  37. #include "../pathfinder/CPathfinder.h"
  38. #include "../pathfinder/PathfinderOptions.h"
  39. #include "../registerTypes/RegisterTypes.h"
  40. #include "../rmg/CMapGenerator.h"
  41. #include "../serializer/CMemorySerializer.h"
  42. #include "../serializer/CTypeList.h"
  43. #include "../spells/CSpellHandler.h"
  44. VCMI_LIB_NAMESPACE_BEGIN
  45. boost::shared_mutex CGameState::mutex;
  46. template <typename T> class CApplyOnGS;
  47. class CBaseForGSApply
  48. {
  49. public:
  50. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  51. virtual ~CBaseForGSApply() = default;
  52. template<typename U> static CBaseForGSApply *getApplier(const U * t=nullptr)
  53. {
  54. return new CApplyOnGS<U>();
  55. }
  56. };
  57. template <typename T> class CApplyOnGS : public CBaseForGSApply
  58. {
  59. public:
  60. void applyOnGS(CGameState *gs, void *pack) const override
  61. {
  62. T *ptr = static_cast<T*>(pack);
  63. boost::unique_lock<boost::shared_mutex> lock(CGameState::mutex);
  64. ptr->applyGs(gs);
  65. }
  66. };
  67. static CGObjectInstance * createObject(const Obj & id, int subid, const int3 & pos, const PlayerColor & owner)
  68. {
  69. CGObjectInstance * nobj;
  70. switch(id)
  71. {
  72. case Obj::HERO:
  73. {
  74. auto handler = VLC->objtypeh->getHandlerFor(id, VLC->heroh->objects[subid]->heroClass->getIndex());
  75. nobj = handler->create(handler->getTemplates().front());
  76. break;
  77. }
  78. case Obj::TOWN:
  79. nobj = new CGTownInstance();
  80. break;
  81. default: //rest of objects
  82. nobj = new CGObjectInstance();
  83. break;
  84. }
  85. nobj->ID = id;
  86. nobj->subID = subid;
  87. nobj->pos = pos;
  88. nobj->tempOwner = owner;
  89. if (id != Obj::HERO)
  90. nobj->appearance = VLC->objtypeh->getHandlerFor(id, subid)->getTemplates().front();
  91. return nobj;
  92. }
  93. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native,
  94. const PlayerColor & player,
  95. const CTown * town,
  96. std::map<ui32, ConstTransitivePtr<CGHeroInstance>> & available,
  97. CRandomGenerator & rand,
  98. const CHeroClass * bannedClass) const
  99. {
  100. CGHeroInstance *ret = nullptr;
  101. if(player>=PlayerColor::PLAYER_LIMIT)
  102. {
  103. logGlobal->error("Cannot pick hero for faction %s. Wrong owner!", town->faction->getJsonKey());
  104. return nullptr;
  105. }
  106. std::vector<CGHeroInstance *> pool;
  107. if(native)
  108. {
  109. for(auto & elem : available)
  110. {
  111. if(pavailable.find(elem.first)->second & 1<<player.getNum()
  112. && elem.second->type->heroClass->faction == town->faction->getIndex())
  113. {
  114. pool.push_back(elem.second); //get all available heroes
  115. }
  116. }
  117. if(pool.empty())
  118. {
  119. logGlobal->error("Cannot pick native hero for %s. Picking any...", player.getStr());
  120. return pickHeroFor(false, player, town, available, rand);
  121. }
  122. else
  123. {
  124. ret = *RandomGeneratorUtil::nextItem(pool, rand);
  125. }
  126. }
  127. else
  128. {
  129. int sum = 0;
  130. int r;
  131. for(auto & elem : available)
  132. {
  133. if (pavailable.find(elem.first)->second & (1<<player.getNum()) && // hero is available
  134. ( !bannedClass || elem.second->type->heroClass != bannedClass) ) // and his class is not same as other hero
  135. {
  136. pool.push_back(elem.second);
  137. sum += elem.second->type->heroClass->selectionProbability[town->faction->getId()]; //total weight
  138. }
  139. }
  140. if(pool.empty() || sum == 0)
  141. {
  142. logGlobal->error("There are no heroes available for player %s!", player.getStr());
  143. return nullptr;
  144. }
  145. r = rand.nextInt(sum - 1);
  146. for (auto & elem : pool)
  147. {
  148. r -= elem->type->heroClass->selectionProbability[town->faction->getId()];
  149. if(r < 0)
  150. {
  151. ret = elem;
  152. break;
  153. }
  154. }
  155. if(!ret)
  156. ret = pool.back();
  157. }
  158. available.erase(ret->subID);
  159. return ret;
  160. }
  161. int CGameState::pickNextHeroType(const PlayerColor & owner)
  162. {
  163. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  164. if(ps.hero >= 0 && !isUsedHero(HeroTypeID(ps.hero))) //we haven't used selected hero
  165. {
  166. return ps.hero;
  167. }
  168. return pickUnusedHeroTypeRandomly(owner);
  169. }
  170. int CGameState::pickUnusedHeroTypeRandomly(const PlayerColor & owner)
  171. {
  172. //list of available heroes for this faction and others
  173. std::vector<HeroTypeID> factionHeroes;
  174. std::vector<HeroTypeID> otherHeroes;
  175. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  176. for(const HeroTypeID & hid : getUnusedAllowedHeroes())
  177. {
  178. if(VLC->heroh->objects[hid.getNum()]->heroClass->faction == ps.castle)
  179. factionHeroes.push_back(hid);
  180. else
  181. otherHeroes.push_back(hid);
  182. }
  183. // select random hero native to "our" faction
  184. if(!factionHeroes.empty())
  185. {
  186. return RandomGeneratorUtil::nextItem(factionHeroes, getRandomGenerator())->getNum();
  187. }
  188. logGlobal->warn("Cannot find free hero of appropriate faction for player %s - trying to get first available...", owner.getStr());
  189. if(!otherHeroes.empty())
  190. {
  191. return RandomGeneratorUtil::nextItem(otherHeroes, getRandomGenerator())->getNum();
  192. }
  193. logGlobal->error("No free allowed heroes!");
  194. auto notAllowedHeroesButStillBetterThanCrash = getUnusedAllowedHeroes(true);
  195. if(!notAllowedHeroesButStillBetterThanCrash.empty())
  196. return notAllowedHeroesButStillBetterThanCrash.begin()->getNum();
  197. logGlobal->error("No free heroes at all!");
  198. assert(0); //current code can't handle this situation
  199. return -1; // no available heroes at all
  200. }
  201. std::pair<Obj,int> CGameState::pickObject (CGObjectInstance *obj)
  202. {
  203. switch(obj->ID)
  204. {
  205. case Obj::RANDOM_ART:
  206. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  207. case Obj::RANDOM_TREASURE_ART:
  208. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE));
  209. case Obj::RANDOM_MINOR_ART:
  210. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MINOR));
  211. case Obj::RANDOM_MAJOR_ART:
  212. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MAJOR));
  213. case Obj::RANDOM_RELIC_ART:
  214. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_RELIC));
  215. case Obj::RANDOM_HERO:
  216. return std::make_pair(Obj::HERO, pickNextHeroType(obj->tempOwner));
  217. case Obj::RANDOM_MONSTER:
  218. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator()));
  219. case Obj::RANDOM_MONSTER_L1:
  220. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 1));
  221. case Obj::RANDOM_MONSTER_L2:
  222. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 2));
  223. case Obj::RANDOM_MONSTER_L3:
  224. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 3));
  225. case Obj::RANDOM_MONSTER_L4:
  226. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 4));
  227. case Obj::RANDOM_RESOURCE:
  228. return std::make_pair(Obj::RESOURCE,getRandomGenerator().nextInt(6)); //now it's OH3 style, use %8 for mithril
  229. case Obj::RANDOM_TOWN:
  230. {
  231. PlayerColor align = (dynamic_cast<CGTownInstance *>(obj))->alignmentToPlayer;
  232. si32 f; // can be negative (for random)
  233. if(align >= PlayerColor::PLAYER_LIMIT) //same as owner / random
  234. {
  235. if(obj->tempOwner >= PlayerColor::PLAYER_LIMIT)
  236. f = -1; //random
  237. else
  238. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  239. }
  240. else
  241. {
  242. f = scenarioOps->getIthPlayersSettings(align).castle;
  243. }
  244. if(f<0)
  245. {
  246. do
  247. {
  248. f = getRandomGenerator().nextInt((int)VLC->townh->size() - 1);
  249. }
  250. while ((*VLC->townh)[f]->town == nullptr); // find playable faction
  251. }
  252. return std::make_pair(Obj::TOWN,f);
  253. }
  254. case Obj::RANDOM_MONSTER_L5:
  255. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 5));
  256. case Obj::RANDOM_MONSTER_L6:
  257. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 6));
  258. case Obj::RANDOM_MONSTER_L7:
  259. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 7));
  260. case Obj::RANDOM_DWELLING:
  261. case Obj::RANDOM_DWELLING_LVL:
  262. case Obj::RANDOM_DWELLING_FACTION:
  263. {
  264. auto * dwl = dynamic_cast<CGDwelling *>(obj);
  265. int faction;
  266. //if castle alignment available
  267. if(auto * info = dynamic_cast<CCreGenAsCastleInfo *>(dwl->info))
  268. {
  269. faction = getRandomGenerator().nextInt((int)VLC->townh->size() - 1);
  270. if(info->asCastle && !info->instanceId.empty())
  271. {
  272. auto iter = map->instanceNames.find(info->instanceId);
  273. if(iter == map->instanceNames.end())
  274. logGlobal->error("Map object not found: %s", info->instanceId);
  275. else
  276. {
  277. auto elem = iter->second;
  278. if(elem->ID==Obj::RANDOM_TOWN)
  279. {
  280. randomizeObject(elem.get()); //we have to randomize the castle first
  281. faction = elem->subID;
  282. }
  283. else if(elem->ID==Obj::TOWN)
  284. faction = elem->subID;
  285. else
  286. logGlobal->error("Map object must be town: %s", info->instanceId);
  287. }
  288. }
  289. else if(info->asCastle)
  290. {
  291. for(auto & elem : map->objects)
  292. {
  293. if(!elem)
  294. continue;
  295. if(elem->ID==Obj::RANDOM_TOWN
  296. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  297. {
  298. randomizeObject(elem); //we have to randomize the castle first
  299. faction = elem->subID;
  300. break;
  301. }
  302. else if(elem->ID==Obj::TOWN
  303. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  304. {
  305. faction = elem->subID;
  306. break;
  307. }
  308. }
  309. }
  310. else
  311. {
  312. std::set<int> temp;
  313. for(int i = 0; i < info->allowedFactions.size(); i++)
  314. if(info->allowedFactions[i])
  315. temp.insert(i);
  316. if(temp.empty())
  317. logGlobal->error("Random faction selection failed. Nothing is allowed. Fall back to random.");
  318. else
  319. faction = *RandomGeneratorUtil::nextItem(temp, getRandomGenerator());
  320. }
  321. }
  322. else // castle alignment fixed
  323. faction = obj->subID;
  324. int level;
  325. //if level set to range
  326. if(auto * info = dynamic_cast<CCreGenLeveledInfo *>(dwl->info))
  327. {
  328. level = getRandomGenerator().nextInt(info->minLevel, info->maxLevel);
  329. }
  330. else // fixed level
  331. {
  332. level = obj->subID;
  333. }
  334. delete dwl->info;
  335. dwl->info = nullptr;
  336. std::pair<Obj, int> result(Obj::NO_OBJ, -1);
  337. CreatureID cid = (*VLC->townh)[faction]->town->creatures[level][0];
  338. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  339. //check for block map equality is better but more complex solution
  340. auto testID = [&](const Obj & primaryID) -> void
  341. {
  342. auto dwellingIDs = VLC->objtypeh->knownSubObjects(primaryID);
  343. for (si32 entry : dwellingIDs)
  344. {
  345. const auto * handler = dynamic_cast<const DwellingInstanceConstructor *>(VLC->objtypeh->getHandlerFor(primaryID, entry).get());
  346. if (handler->producesCreature(VLC->creh->objects[cid]))
  347. result = std::make_pair(primaryID, entry);
  348. }
  349. };
  350. testID(Obj::CREATURE_GENERATOR1);
  351. if (result.first == Obj::NO_OBJ)
  352. testID(Obj::CREATURE_GENERATOR4);
  353. if (result.first == Obj::NO_OBJ)
  354. {
  355. logGlobal->error("Error: failed to find dwelling for %s of level %d", (*VLC->townh)[faction]->getNameTranslated(), int(level));
  356. result = std::make_pair(Obj::CREATURE_GENERATOR1, *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1), getRandomGenerator()));
  357. }
  358. return result;
  359. }
  360. }
  361. return std::make_pair(Obj::NO_OBJ,-1);
  362. }
  363. void CGameState::randomizeObject(CGObjectInstance *cur)
  364. {
  365. std::pair<Obj,int> ran = pickObject(cur);
  366. if(ran.first == Obj::NO_OBJ || ran.second<0) //this is not a random object, or we couldn't find anything
  367. {
  368. if(cur->ID==Obj::TOWN || cur->ID==Obj::MONSTER)
  369. cur->setType(cur->ID, cur->subID); // update def, if necessary
  370. }
  371. else if(ran.first==Obj::HERO)//special code for hero
  372. {
  373. auto * h = dynamic_cast<CGHeroInstance *>(cur);
  374. cur->setType(ran.first, ran.second);
  375. map->heroesOnMap.emplace_back(h);
  376. }
  377. else if(ran.first==Obj::TOWN)//special code for town
  378. {
  379. auto * t = dynamic_cast<CGTownInstance *>(cur);
  380. cur->setType(ran.first, ran.second);
  381. map->towns.emplace_back(t);
  382. }
  383. else
  384. {
  385. cur->setType(ran.first, ran.second);
  386. }
  387. }
  388. int CGameState::getDate(Date::EDateType mode) const
  389. {
  390. int temp;
  391. switch (mode)
  392. {
  393. case Date::DAY:
  394. return day;
  395. case Date::DAY_OF_WEEK: //day of week
  396. temp = (day)%7; // 1 - Monday, 7 - Sunday
  397. return temp ? temp : 7;
  398. case Date::WEEK: //current week
  399. temp = ((day-1)/7)+1;
  400. if (!(temp%4))
  401. return 4;
  402. else
  403. return (temp%4);
  404. case Date::MONTH: //current month
  405. return ((day-1)/28)+1;
  406. case Date::DAY_OF_MONTH: //day of month
  407. temp = (day)%28;
  408. if (temp)
  409. return temp;
  410. else return 28;
  411. }
  412. return 0;
  413. }
  414. CGameState::CGameState()
  415. {
  416. gs = this;
  417. applier = std::make_shared<CApplier<CBaseForGSApply>>();
  418. registerTypesClientPacks1(*applier);
  419. registerTypesClientPacks2(*applier);
  420. globalEffects.setNodeType(CBonusSystemNode::GLOBAL_EFFECTS);
  421. }
  422. CGameState::~CGameState()
  423. {
  424. map.dellNull();
  425. curB.dellNull();
  426. for(auto ptr : hpool.heroesPool) // clean hero pool
  427. ptr.second.dellNull();
  428. }
  429. void CGameState::preInit(Services * services)
  430. {
  431. this->services = services;
  432. }
  433. void CGameState::init(const IMapService * mapService, StartInfo * si, bool allowSavingRandomMap)
  434. {
  435. preInitAuto();
  436. logGlobal->info("\tUsing random seed: %d", si->seedToBeUsed);
  437. getRandomGenerator().setSeed(si->seedToBeUsed);
  438. scenarioOps = CMemorySerializer::deepCopy(*si).release();
  439. initialOpts = CMemorySerializer::deepCopy(*si).release();
  440. si = nullptr;
  441. switch(scenarioOps->mode)
  442. {
  443. case StartInfo::NEW_GAME:
  444. initNewGame(mapService, allowSavingRandomMap);
  445. break;
  446. case StartInfo::CAMPAIGN:
  447. initCampaign();
  448. break;
  449. default:
  450. logGlobal->error("Wrong mode: %d", static_cast<int>(scenarioOps->mode));
  451. return;
  452. }
  453. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  454. logGlobal->info("Map loaded!");
  455. checkMapChecksum();
  456. day = 0;
  457. logGlobal->debug("Initialization:");
  458. initGlobalBonuses();
  459. initPlayerStates();
  460. if (campaign)
  461. campaign->placeCampaignHeroes();
  462. removeHeroPlaceholders();
  463. initGrailPosition();
  464. initRandomFactionsForPlayers();
  465. randomizeMapObjects();
  466. placeStartingHeroes();
  467. initStartingResources();
  468. initHeroes();
  469. initStartingBonus();
  470. initTowns();
  471. placeHeroesInTowns();
  472. initMapObjects();
  473. buildBonusSystemTree();
  474. initVisitingAndGarrisonedHeroes();
  475. initFogOfWar();
  476. // Explicitly initialize static variables
  477. for(auto & elem : players)
  478. {
  479. CGKeys::playerKeyMap[elem.first] = std::set<ui8>();
  480. }
  481. for(auto & elem : teams)
  482. {
  483. CGObelisk::visited[elem.first] = 0;
  484. }
  485. logGlobal->debug("\tChecking objectives");
  486. map->checkForObjectives(); //needs to be run when all objects are properly placed
  487. auto seedAfterInit = getRandomGenerator().nextInt();
  488. logGlobal->info("Seed after init is %d (before was %d)", seedAfterInit, scenarioOps->seedToBeUsed);
  489. if(scenarioOps->seedPostInit > 0)
  490. {
  491. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  492. assert(scenarioOps->seedPostInit == seedAfterInit);
  493. }
  494. else
  495. {
  496. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  497. }
  498. }
  499. void CGameState::updateEntity(Metatype metatype, int32_t index, const JsonNode & data)
  500. {
  501. switch(metatype)
  502. {
  503. case Metatype::ARTIFACT_INSTANCE:
  504. logGlobal->error("Artifact instance update is not implemented");
  505. break;
  506. case Metatype::CREATURE_INSTANCE:
  507. logGlobal->error("Creature instance update is not implemented");
  508. break;
  509. case Metatype::HERO_INSTANCE:
  510. //index is hero type
  511. if(index >= 0 && index < map->allHeroes.size())
  512. {
  513. CGHeroInstance * hero = map->allHeroes.at(index);
  514. hero->updateFrom(data);
  515. }
  516. else
  517. {
  518. logGlobal->error("Update entity: hero index %s is out of range [%d,%d]", index, 0, map->allHeroes.size());
  519. }
  520. break;
  521. case Metatype::MAP_OBJECT_INSTANCE:
  522. if(index >= 0 && index < map->objects.size())
  523. {
  524. CGObjectInstance * obj = getObjInstance(ObjectInstanceID(index));
  525. obj->updateFrom(data);
  526. }
  527. else
  528. {
  529. logGlobal->error("Update entity: object index %s is out of range [%d,%d]", index, 0, map->objects.size());
  530. }
  531. break;
  532. default:
  533. services->updateEntity(metatype, index, data);
  534. break;
  535. }
  536. }
  537. void CGameState::updateOnLoad(StartInfo * si)
  538. {
  539. preInitAuto();
  540. scenarioOps->playerInfos = si->playerInfos;
  541. for(auto & i : si->playerInfos)
  542. gs->players[i.first].human = i.second.isControlledByHuman();
  543. }
  544. void CGameState::preInitAuto()
  545. {
  546. if(services == nullptr)
  547. {
  548. logGlobal->error("Game state preinit missing");
  549. preInit(VLC);
  550. }
  551. }
  552. void CGameState::initNewGame(const IMapService * mapService, bool allowSavingRandomMap)
  553. {
  554. if(scenarioOps->createRandomMap())
  555. {
  556. logGlobal->info("Create random map.");
  557. CStopWatch sw;
  558. // Gen map
  559. CMapGenerator mapGenerator(*scenarioOps->mapGenOptions, scenarioOps->seedToBeUsed);
  560. std::unique_ptr<CMap> randomMap = mapGenerator.generate();
  561. if(allowSavingRandomMap)
  562. {
  563. try
  564. {
  565. auto path = VCMIDirs::get().userCachePath() / "RandomMaps";
  566. boost::filesystem::create_directories(path);
  567. std::shared_ptr<CMapGenOptions> options = scenarioOps->mapGenOptions;
  568. const std::string templateName = options->getMapTemplate()->getName();
  569. const ui32 seed = scenarioOps->seedToBeUsed;
  570. const std::string fileName = boost::str(boost::format("%s_%d.vmap") % templateName % seed );
  571. const auto fullPath = path / fileName;
  572. mapService->saveMap(randomMap, fullPath);
  573. logGlobal->info("Random map has been saved to:");
  574. logGlobal->info(fullPath.string());
  575. }
  576. catch(...)
  577. {
  578. logGlobal->error("Saving random map failed with exception");
  579. handleException();
  580. }
  581. }
  582. map = randomMap.release();
  583. // Update starting options
  584. for(int i = 0; i < map->players.size(); ++i)
  585. {
  586. const auto & playerInfo = map->players[i];
  587. if(playerInfo.canAnyonePlay())
  588. {
  589. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  590. playerSettings.compOnly = !playerInfo.canHumanPlay;
  591. playerSettings.team = playerInfo.team;
  592. playerSettings.castle = playerInfo.defaultCastle();
  593. if(playerSettings.isControlledByAI() && playerSettings.name.empty())
  594. {
  595. playerSettings.name = VLC->generaltexth->allTexts[468];
  596. }
  597. playerSettings.color = PlayerColor(i);
  598. }
  599. else
  600. {
  601. scenarioOps->playerInfos.erase(PlayerColor(i));
  602. }
  603. }
  604. logGlobal->info("Generated random map in %i ms.", sw.getDiff());
  605. }
  606. else
  607. {
  608. logGlobal->info("Open map file: %s", scenarioOps->mapname);
  609. const ResourceID mapURI(scenarioOps->mapname, EResType::MAP);
  610. map = mapService->loadMap(mapURI).release();
  611. }
  612. }
  613. void CGameState::initCampaign()
  614. {
  615. campaign = std::make_unique<CGameStateCampaign>(this);
  616. map = campaign->getCurrentMap().release();
  617. }
  618. void CGameState::checkMapChecksum()
  619. {
  620. logGlobal->info("\tOur checksum for the map: %d", map->checksum);
  621. if(scenarioOps->mapfileChecksum)
  622. {
  623. logGlobal->info("\tServer checksum for %s: %d", scenarioOps->mapname, scenarioOps->mapfileChecksum);
  624. if(map->checksum != scenarioOps->mapfileChecksum)
  625. {
  626. logGlobal->error("Wrong map checksum!!!");
  627. throw std::runtime_error("Wrong checksum");
  628. }
  629. }
  630. else
  631. {
  632. scenarioOps->mapfileChecksum = map->checksum;
  633. }
  634. }
  635. void CGameState::initGlobalBonuses()
  636. {
  637. const JsonNode & baseBonuses = VLC->settings()->getValue(EGameSettings::BONUSES_GLOBAL);
  638. logGlobal->debug("\tLoading global bonuses");
  639. for(const auto & b : baseBonuses.Struct())
  640. {
  641. auto bonus = JsonUtils::parseBonus(b.second);
  642. bonus->source = BonusSource::GLOBAL;//for all
  643. bonus->sid = -1; //there is one global object
  644. globalEffects.addNewBonus(bonus);
  645. }
  646. VLC->creh->loadCrExpBon(globalEffects);
  647. }
  648. void CGameState::initGrailPosition()
  649. {
  650. logGlobal->debug("\tPicking grail position");
  651. //pick grail location
  652. if(map->grailPos.x < 0 || map->grailRadius) //grail not set or set within a radius around some place
  653. {
  654. if(!map->grailRadius) //radius not given -> anywhere on map
  655. map->grailRadius = map->width * 2;
  656. std::vector<int3> allowedPos;
  657. static const int BORDER_WIDTH = 9; // grail must be at least 9 tiles away from border
  658. // add all not blocked tiles in range
  659. for (int z = 0; z < map->levels(); z++)
  660. {
  661. for(int x = BORDER_WIDTH; x < map->width - BORDER_WIDTH ; x++)
  662. {
  663. for(int y = BORDER_WIDTH; y < map->height - BORDER_WIDTH; y++)
  664. {
  665. const TerrainTile &t = map->getTile(int3(x, y, z));
  666. if(!t.blocked
  667. && !t.visitable
  668. && t.terType->isLand()
  669. && t.terType->isPassable()
  670. && (int)map->grailPos.dist2dSQ(int3(x, y, z)) <= (map->grailRadius * map->grailRadius))
  671. allowedPos.emplace_back(x, y, z);
  672. }
  673. }
  674. }
  675. //remove tiles with holes
  676. for(auto & elem : map->objects)
  677. if(elem && elem->ID == Obj::HOLE)
  678. allowedPos -= elem->pos;
  679. if(!allowedPos.empty())
  680. {
  681. map->grailPos = *RandomGeneratorUtil::nextItem(allowedPos, getRandomGenerator());
  682. }
  683. else
  684. {
  685. logGlobal->warn("Grail cannot be placed, no appropriate tile found!");
  686. }
  687. }
  688. }
  689. void CGameState::initRandomFactionsForPlayers()
  690. {
  691. logGlobal->debug("\tPicking random factions for players");
  692. for(auto & elem : scenarioOps->playerInfos)
  693. {
  694. if(elem.second.castle==-1)
  695. {
  696. auto randomID = getRandomGenerator().nextInt((int)map->players[elem.first.getNum()].allowedFactions.size() - 1);
  697. auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
  698. std::advance(iter, randomID);
  699. elem.second.castle = *iter;
  700. }
  701. }
  702. }
  703. void CGameState::randomizeMapObjects()
  704. {
  705. logGlobal->debug("\tRandomizing objects");
  706. for(CGObjectInstance *obj : map->objects)
  707. {
  708. if(!obj) continue;
  709. randomizeObject(obj);
  710. //handle Favouring Winds - mark tiles under it
  711. if(obj->ID == Obj::FAVORABLE_WINDS)
  712. {
  713. for (int i = 0; i < obj->getWidth() ; i++)
  714. {
  715. for (int j = 0; j < obj->getHeight() ; j++)
  716. {
  717. int3 pos = obj->pos - int3(i,j,0);
  718. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  719. }
  720. }
  721. }
  722. }
  723. }
  724. void CGameState::initPlayerStates()
  725. {
  726. logGlobal->debug("\tCreating player entries in gs");
  727. for(auto & elem : scenarioOps->playerInfos)
  728. {
  729. PlayerState & p = players[elem.first];
  730. p.color=elem.first;
  731. p.human = elem.second.isControlledByHuman();
  732. p.team = map->players[elem.first.getNum()].team;
  733. teams[p.team].id = p.team;//init team
  734. teams[p.team].players.insert(elem.first);//add player to team
  735. }
  736. }
  737. void CGameState::placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos)
  738. {
  739. for(auto town : map->towns)
  740. {
  741. if(town->getPosition() == townPos)
  742. {
  743. townPos = town->visitablePos();
  744. break;
  745. }
  746. }
  747. CGObjectInstance * hero = createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor);
  748. hero->pos += hero->getVisitableOffset();
  749. map->getEditManager()->insertObject(hero);
  750. }
  751. void CGameState::placeStartingHeroes()
  752. {
  753. logGlobal->debug("\tGiving starting hero");
  754. for(auto & playerSettingPair : scenarioOps->playerInfos)
  755. {
  756. auto playerColor = playerSettingPair.first;
  757. auto & playerInfo = map->players[playerColor.getNum()];
  758. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  759. {
  760. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  761. if (campaign && campaign->playerHasStartingHero(playerColor))
  762. continue;
  763. int heroTypeId = pickNextHeroType(playerColor);
  764. if(playerSettingPair.second.hero == -1)
  765. playerSettingPair.second.hero = heroTypeId;
  766. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  767. }
  768. }
  769. }
  770. void CGameState::removeHeroPlaceholders()
  771. {
  772. // remove any hero placeholders that remain on map after (potential) campaign heroes placement
  773. for(auto obj : map->objects)
  774. {
  775. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  776. {
  777. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  778. map->removeBlockVisTiles(heroPlaceholder, true);
  779. map->instanceNames.erase(obj->instanceName);
  780. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  781. delete heroPlaceholder;
  782. }
  783. }
  784. }
  785. void CGameState::initStartingResources()
  786. {
  787. logGlobal->debug("\tSetting up resources");
  788. const JsonNode config(ResourceID("config/startres.json"));
  789. const JsonVector &vector = config["difficulty"].Vector();
  790. const JsonNode &level = vector[scenarioOps->difficulty];
  791. TResources startresAI(level["ai"]);
  792. TResources startresHuman(level["human"]);
  793. for (auto & elem : players)
  794. {
  795. PlayerState &p = elem.second;
  796. if (p.human)
  797. p.resources = startresHuman;
  798. else
  799. p.resources = startresAI;
  800. }
  801. if (campaign)
  802. campaign->initStartingResources();
  803. }
  804. void CGameState::initHeroes()
  805. {
  806. for(auto hero : map->heroesOnMap) //heroes instances initialization
  807. {
  808. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  809. {
  810. logGlobal->warn("Hero with uninitialized owner!");
  811. continue;
  812. }
  813. hero->initHero(getRandomGenerator());
  814. getPlayerState(hero->getOwner())->heroes.push_back(hero);
  815. map->allHeroes[hero->type->getIndex()] = hero;
  816. }
  817. // generate boats for all heroes on water
  818. for(auto hero : map->heroesOnMap)
  819. {
  820. assert(map->isInTheMap(hero->visitablePos()));
  821. const auto & tile = map->getTile(hero->visitablePos());
  822. if (tile.terType->isWater())
  823. {
  824. auto handler = VLC->objtypeh->getHandlerFor(Obj::BOAT, hero->getBoatType().getNum());
  825. CGBoat * boat = dynamic_cast<CGBoat*>(handler->create());
  826. handler->configureObject(boat, gs->getRandomGenerator());
  827. boat->ID = Obj::BOAT;
  828. boat->subID = hero->getBoatType().getNum();
  829. boat->pos = hero->pos;
  830. boat->appearance = handler->getTemplates().front();
  831. boat->id = ObjectInstanceID(static_cast<si32>(gs->map->objects.size()));
  832. map->objects.emplace_back(boat);
  833. map->addBlockVisTiles(boat);
  834. boat->hero = hero;
  835. hero->boat = boat;
  836. }
  837. }
  838. for(auto obj : map->objects) //prisons
  839. {
  840. if(obj && obj->ID == Obj::PRISON)
  841. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  842. }
  843. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  844. for(auto ph : map->predefinedHeroes)
  845. {
  846. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  847. continue;
  848. ph->initHero(getRandomGenerator());
  849. hpool.heroesPool[ph->subID] = ph;
  850. hpool.pavailable[ph->subID] = 0xff;
  851. heroesToCreate.erase(ph->type->getId());
  852. map->allHeroes[ph->subID] = ph;
  853. }
  854. for(const HeroTypeID & htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  855. {
  856. auto * vhi = new CGHeroInstance();
  857. vhi->initHero(getRandomGenerator(), htype);
  858. int typeID = htype.getNum();
  859. map->allHeroes[typeID] = vhi;
  860. hpool.heroesPool[typeID] = vhi;
  861. hpool.pavailable[typeID] = 0xff;
  862. }
  863. for(auto & elem : map->disposedHeroes)
  864. {
  865. hpool.pavailable[elem.heroId] = elem.players;
  866. }
  867. if (campaign)
  868. campaign->initHeroes();
  869. }
  870. void CGameState::initFogOfWar()
  871. {
  872. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  873. int layers = map->levels();
  874. for(auto & elem : teams)
  875. {
  876. auto fow = elem.second.fogOfWarMap;
  877. fow->resize(boost::extents[layers][map->width][map->height]);
  878. std::fill(fow->data(), fow->data() + fow->num_elements(), 0);
  879. for(CGObjectInstance *obj : map->objects)
  880. {
  881. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  882. std::unordered_set<int3> tiles;
  883. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius(), obj->tempOwner, 1);
  884. for(const int3 & tile : tiles)
  885. {
  886. (*elem.second.fogOfWarMap)[tile.z][tile.x][tile.y] = 1;
  887. }
  888. }
  889. }
  890. }
  891. void CGameState::initStartingBonus()
  892. {
  893. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  894. return;
  895. // These are the single scenario bonuses; predefined
  896. // campaign bonuses are spread out over other init* functions.
  897. logGlobal->debug("\tStarting bonuses");
  898. for(auto & elem : players)
  899. {
  900. //starting bonus
  901. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  902. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(getRandomGenerator().nextInt(2));
  903. switch(scenarioOps->playerInfos[elem.first].bonus)
  904. {
  905. case PlayerSettings::GOLD:
  906. elem.second.resources[EGameResID::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  907. break;
  908. case PlayerSettings::RESOURCE:
  909. {
  910. auto res = (*VLC->townh)[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  911. if(res == EGameResID::WOOD_AND_ORE)
  912. {
  913. int amount = getRandomGenerator().nextInt(5, 10);
  914. elem.second.resources[EGameResID::WOOD] += amount;
  915. elem.second.resources[EGameResID::ORE] += amount;
  916. }
  917. else
  918. {
  919. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  920. }
  921. break;
  922. }
  923. case PlayerSettings::ARTIFACT:
  924. {
  925. if(elem.second.heroes.empty())
  926. {
  927. logGlobal->error("Cannot give starting artifact - no heroes!");
  928. break;
  929. }
  930. const Artifact * toGive = VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE).toArtifact(VLC->artifacts());
  931. CGHeroInstance *hero = elem.second.heroes[0];
  932. if(!giveHeroArtifact(hero, toGive->getId()))
  933. logGlobal->error("Cannot give starting artifact - no free slots!");
  934. }
  935. break;
  936. }
  937. }
  938. }
  939. void CGameState::initTowns()
  940. {
  941. logGlobal->debug("\tTowns");
  942. if (campaign)
  943. campaign->initTowns();
  944. CGTownInstance::universitySkills.clear();
  945. for ( int i=0; i<4; i++)
  946. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  947. for (auto & elem : map->towns)
  948. {
  949. CGTownInstance * vti =(elem);
  950. if(!vti->town)
  951. {
  952. vti->town = (*VLC->townh)[vti->subID]->town;
  953. }
  954. if(vti->getNameTranslated().empty())
  955. {
  956. size_t nameID = getRandomGenerator().nextInt(vti->getTown()->getRandomNamesCount() - 1);
  957. vti->setNameTranslated(vti->getTown()->getRandomNameTranslated(nameID));
  958. }
  959. static const BuildingID basicDwellings[] = { BuildingID::DWELL_FIRST, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3, BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7 };
  960. static const BuildingID upgradedDwellings[] = { BuildingID::DWELL_UP_FIRST, BuildingID::DWELL_LVL_2_UP, BuildingID::DWELL_LVL_3_UP, BuildingID::DWELL_LVL_4_UP, BuildingID::DWELL_LVL_5_UP, BuildingID::DWELL_LVL_6_UP, BuildingID::DWELL_LVL_7_UP };
  961. static const BuildingID hordes[] = { BuildingID::HORDE_PLACEHOLDER1, BuildingID::HORDE_PLACEHOLDER2, BuildingID::HORDE_PLACEHOLDER3, BuildingID::HORDE_PLACEHOLDER4, BuildingID::HORDE_PLACEHOLDER5, BuildingID::HORDE_PLACEHOLDER6, BuildingID::HORDE_PLACEHOLDER7 };
  962. //init buildings
  963. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  964. {
  965. vti->builtBuildings.erase(BuildingID::DEFAULT);
  966. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  967. if(vti->tempOwner != PlayerColor::NEUTRAL)
  968. vti->builtBuildings.insert(BuildingID::TAVERN);
  969. auto definesBuildingsChances = VLC->settings()->getVector(EGameSettings::TOWNS_STARTING_DWELLING_CHANCES);
  970. for(int i = 0; i < definesBuildingsChances.size(); i++)
  971. {
  972. if((getRandomGenerator().nextInt(1,100) <= definesBuildingsChances[i]))
  973. {
  974. vti->builtBuildings.insert(basicDwellings[i]);
  975. }
  976. }
  977. }
  978. // village hall must always exist
  979. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  980. //init hordes
  981. for (int i = 0; i < GameConstants::CREATURES_PER_TOWN; i++)
  982. {
  983. if (vstd::contains(vti->builtBuildings, hordes[i])) //if we have horde for this level
  984. {
  985. vti->builtBuildings.erase(hordes[i]);//remove old ID
  986. if (vti->getTown()->hordeLvl.at(0) == i)//if town first horde is this one
  987. {
  988. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  989. //if we have upgraded dwelling as well
  990. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  991. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  992. }
  993. if (vti->getTown()->hordeLvl.at(1) == i)//if town second horde is this one
  994. {
  995. vti->builtBuildings.insert(BuildingID::HORDE_2);
  996. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  997. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  998. }
  999. }
  1000. }
  1001. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  1002. //But DO NOT remove horde placeholders before they are replaced
  1003. vstd::erase_if(vti->builtBuildings, [vti](const BuildingID & bid)
  1004. {
  1005. return !vti->getTown()->buildings.count(bid) || !vti->getTown()->buildings.at(bid);
  1006. });
  1007. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  1008. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1009. //Early check for #1444-like problems
  1010. for([[maybe_unused]] const auto & building : vti->builtBuildings)
  1011. {
  1012. assert(vti->getTown()->buildings.at(building) != nullptr);
  1013. }
  1014. //town events
  1015. for(CCastleEvent &ev : vti->events)
  1016. {
  1017. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1018. if (vstd::contains(ev.buildings,hordes[i])) //if we have horde for this level
  1019. {
  1020. ev.buildings.erase(hordes[i]);
  1021. if (vti->getTown()->hordeLvl.at(0) == i)
  1022. ev.buildings.insert(BuildingID::HORDE_1);
  1023. if (vti->getTown()->hordeLvl.at(1) == i)
  1024. ev.buildings.insert(BuildingID::HORDE_2);
  1025. }
  1026. }
  1027. //init spells
  1028. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1029. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1030. {
  1031. const auto * s = vti->obligatorySpells[z].toSpell();
  1032. vti->spells[s->level-1].push_back(s->id);
  1033. vti->possibleSpells -= s->id;
  1034. }
  1035. while(!vti->possibleSpells.empty())
  1036. {
  1037. ui32 total=0;
  1038. int sel = -1;
  1039. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1040. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  1041. if (total == 0) // remaining spells have 0 probability
  1042. break;
  1043. auto r = getRandomGenerator().nextInt(total - 1);
  1044. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1045. {
  1046. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  1047. if(r<0)
  1048. {
  1049. sel = ps;
  1050. break;
  1051. }
  1052. }
  1053. if(sel<0)
  1054. sel=0;
  1055. const auto * s = vti->possibleSpells[sel].toSpell();
  1056. vti->spells[s->level-1].push_back(s->id);
  1057. vti->possibleSpells -= s->id;
  1058. }
  1059. vti->possibleSpells.clear();
  1060. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1061. getPlayerState(vti->getOwner())->towns.emplace_back(vti);
  1062. }
  1063. }
  1064. void CGameState::initMapObjects()
  1065. {
  1066. logGlobal->debug("\tObject initialization");
  1067. // objCaller->preInit();
  1068. for(CGObjectInstance *obj : map->objects)
  1069. {
  1070. if(obj)
  1071. {
  1072. logGlobal->trace("Calling Init for object %d, %s, %s", obj->id.getNum(), obj->typeName, obj->subTypeName);
  1073. obj->initObj(getRandomGenerator());
  1074. }
  1075. }
  1076. for(CGObjectInstance *obj : map->objects)
  1077. {
  1078. if(!obj)
  1079. continue;
  1080. switch (obj->ID)
  1081. {
  1082. case Obj::QUEST_GUARD:
  1083. case Obj::SEER_HUT:
  1084. {
  1085. auto * q = dynamic_cast<CGSeerHut *>(obj);
  1086. assert (q);
  1087. q->setObjToKill();
  1088. }
  1089. }
  1090. }
  1091. CGSubterraneanGate::postInit(); //pairing subterranean gates
  1092. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  1093. }
  1094. void CGameState::placeHeroesInTowns()
  1095. {
  1096. for(auto & player : players)
  1097. {
  1098. if(player.first == PlayerColor::NEUTRAL)
  1099. continue;
  1100. for(CGHeroInstance * h : player.second.heroes)
  1101. {
  1102. for(CGTownInstance * t : player.second.towns)
  1103. {
  1104. if(h->visitablePos().z != t->visitablePos().z)
  1105. continue;
  1106. bool heroOnTownBlockableTile = t->blockingAt(h->visitablePos().x, h->visitablePos().y);
  1107. // current hero position is at one of blocking tiles of current town
  1108. // assume that this hero should be visiting the town (H3M format quirk) and move hero to correct position
  1109. if (heroOnTownBlockableTile)
  1110. {
  1111. int3 correctedPos = h->convertFromVisitablePos(t->visitablePos());
  1112. map->removeBlockVisTiles(h);
  1113. h->pos = correctedPos;
  1114. map->addBlockVisTiles(h);
  1115. assert(t->visitableAt(h->visitablePos().x, h->visitablePos().y));
  1116. }
  1117. }
  1118. }
  1119. }
  1120. }
  1121. void CGameState::initVisitingAndGarrisonedHeroes()
  1122. {
  1123. for(auto & player : players)
  1124. {
  1125. if(player.first == PlayerColor::NEUTRAL)
  1126. continue;
  1127. //init visiting and garrisoned heroes
  1128. for(CGHeroInstance * h : player.second.heroes)
  1129. {
  1130. for(CGTownInstance * t : player.second.towns)
  1131. {
  1132. if(h->visitablePos().z != t->visitablePos().z)
  1133. continue;
  1134. if (t->visitableAt(h->visitablePos().x, h->visitablePos().y))
  1135. {
  1136. assert(t->visitingHero == nullptr);
  1137. t->setVisitingHero(h);
  1138. }
  1139. }
  1140. }
  1141. }
  1142. for (auto hero : map->heroesOnMap)
  1143. {
  1144. if (hero->visitedTown)
  1145. {
  1146. assert (hero->visitedTown->visitingHero == hero);
  1147. }
  1148. }
  1149. }
  1150. BattleField CGameState::battleGetBattlefieldType(int3 tile, CRandomGenerator & rand)
  1151. {
  1152. if(!tile.valid() && curB)
  1153. tile = curB->tile;
  1154. else if(!tile.valid() && !curB)
  1155. return BattleField::NONE;
  1156. const TerrainTile &t = map->getTile(tile);
  1157. auto * topObject = t.visitableObjects.front();
  1158. if(topObject && topObject->getBattlefield() != BattleField::NONE)
  1159. {
  1160. return topObject->getBattlefield();
  1161. }
  1162. for(auto &obj : map->objects)
  1163. {
  1164. //look only for objects covering given tile
  1165. if( !obj || obj->pos.z != tile.z || !obj->coveringAt(tile.x, tile.y))
  1166. continue;
  1167. auto customBattlefield = obj->getBattlefield();
  1168. if(customBattlefield != BattleField::NONE)
  1169. return customBattlefield;
  1170. }
  1171. if(map->isCoastalTile(tile)) //coastal tile is always ground
  1172. return BattleField::fromString("sand_shore");
  1173. return BattleField(*RandomGeneratorUtil::nextItem(t.terType->battleFields, rand));
  1174. }
  1175. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  1176. {
  1177. assert(obj);
  1178. assert(obj->hasStackAtSlot(stackPos));
  1179. out = fillUpgradeInfo(obj->getStack(stackPos));
  1180. }
  1181. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance &stack) const
  1182. {
  1183. UpgradeInfo ret;
  1184. const CCreature *base = stack.type;
  1185. if (stack.armyObj->ID == Obj::HERO)
  1186. {
  1187. auto hero = dynamic_cast<const CGHeroInstance *>(stack.armyObj);
  1188. hero->fillUpgradeInfo(ret, stack);
  1189. if (hero->visitedTown)
  1190. {
  1191. hero->visitedTown->fillUpgradeInfo(ret, stack);
  1192. }
  1193. else
  1194. {
  1195. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  1196. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  1197. if (object != hero && upgradeSource != nullptr)
  1198. upgradeSource->fillUpgradeInfo(ret, stack);
  1199. }
  1200. }
  1201. if (stack.armyObj->ID == Obj::TOWN)
  1202. {
  1203. auto town = dynamic_cast<const CGTownInstance *>(stack.armyObj);
  1204. town->fillUpgradeInfo(ret, stack);
  1205. }
  1206. if(!ret.newID.empty())
  1207. ret.oldID = base->getId();
  1208. for (ResourceSet &cost : ret.cost)
  1209. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1210. return ret;
  1211. }
  1212. PlayerRelations::PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  1213. {
  1214. if ( color1 == color2 )
  1215. return PlayerRelations::SAME_PLAYER;
  1216. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1217. return PlayerRelations::ENEMIES;
  1218. const TeamState * ts = getPlayerTeam(color1);
  1219. if (ts && vstd::contains(ts->players, color2))
  1220. return PlayerRelations::ALLIES;
  1221. return PlayerRelations::ENEMIES;
  1222. }
  1223. void CGameState::apply(CPack *pack)
  1224. {
  1225. ui16 typ = typeList.getTypeID(pack);
  1226. applier->getApplier(typ)->applyOnGS(this, pack);
  1227. }
  1228. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  1229. {
  1230. calculatePaths(std::make_shared<SingleHeroPathfinderConfig>(out, this, hero));
  1231. }
  1232. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config)
  1233. {
  1234. //FIXME: creating pathfinder is costly, maybe reset / clear is enough?
  1235. CPathfinder pathfinder(this, config);
  1236. pathfinder.calculatePaths();
  1237. }
  1238. /**
  1239. * Tells if the tile is guarded by a monster as well as the position
  1240. * of the monster that will attack on it.
  1241. *
  1242. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1243. * the monster guarding the tile.
  1244. */
  1245. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1246. {
  1247. std::vector<CGObjectInstance*> guards;
  1248. const int3 originalPos = pos;
  1249. if (!map->isInTheMap(pos))
  1250. return guards;
  1251. const TerrainTile &posTile = map->getTile(pos);
  1252. if (posTile.visitable)
  1253. {
  1254. for (CGObjectInstance* obj : posTile.visitableObjects)
  1255. {
  1256. if(obj->isBlockedVisitable())
  1257. {
  1258. if (obj->ID == Obj::MONSTER) // Monster
  1259. guards.push_back(obj);
  1260. }
  1261. }
  1262. }
  1263. pos -= int3(1, 1, 0); // Start with top left.
  1264. for (int dx = 0; dx < 3; dx++)
  1265. {
  1266. for (int dy = 0; dy < 3; dy++)
  1267. {
  1268. if (map->isInTheMap(pos))
  1269. {
  1270. const auto & tile = map->getTile(pos);
  1271. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1272. {
  1273. for (CGObjectInstance* obj : tile.visitableObjects)
  1274. {
  1275. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1276. {
  1277. guards.push_back(obj);
  1278. }
  1279. }
  1280. }
  1281. }
  1282. pos.y++;
  1283. }
  1284. pos.y -= 3;
  1285. pos.x++;
  1286. }
  1287. return guards;
  1288. }
  1289. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1290. {
  1291. return gs->map->guardingCreaturePositions[pos.z][pos.x][pos.y];
  1292. }
  1293. void CGameState::updateRumor()
  1294. {
  1295. static std::vector<RumorState::ERumorType> rumorTypes = {RumorState::TYPE_MAP, RumorState::TYPE_SPECIAL, RumorState::TYPE_RAND, RumorState::TYPE_RAND};
  1296. std::vector<RumorState::ERumorTypeSpecial> sRumorTypes = {
  1297. RumorState::RUMOR_OBELISKS, RumorState::RUMOR_ARTIFACTS, RumorState::RUMOR_ARMY, RumorState::RUMOR_INCOME};
  1298. if(map->grailPos.valid()) // Grail should always be on map, but I had related crash I didn't manage to reproduce
  1299. sRumorTypes.push_back(RumorState::RUMOR_GRAIL);
  1300. int rumorId = -1;
  1301. int rumorExtra = -1;
  1302. auto & rand = getRandomGenerator();
  1303. rumor.type = *RandomGeneratorUtil::nextItem(rumorTypes, rand);
  1304. do
  1305. {
  1306. switch(rumor.type)
  1307. {
  1308. case RumorState::TYPE_SPECIAL:
  1309. {
  1310. SThievesGuildInfo tgi;
  1311. obtainPlayersStats(tgi, 20);
  1312. rumorId = *RandomGeneratorUtil::nextItem(sRumorTypes, rand);
  1313. if(rumorId == RumorState::RUMOR_GRAIL)
  1314. {
  1315. rumorExtra = getTile(map->grailPos)->terType->getIndex();
  1316. break;
  1317. }
  1318. std::vector<PlayerColor> players = {};
  1319. switch(rumorId)
  1320. {
  1321. case RumorState::RUMOR_OBELISKS:
  1322. players = tgi.obelisks[0];
  1323. break;
  1324. case RumorState::RUMOR_ARTIFACTS:
  1325. players = tgi.artifacts[0];
  1326. break;
  1327. case RumorState::RUMOR_ARMY:
  1328. players = tgi.army[0];
  1329. break;
  1330. case RumorState::RUMOR_INCOME:
  1331. players = tgi.income[0];
  1332. break;
  1333. }
  1334. rumorExtra = RandomGeneratorUtil::nextItem(players, rand)->getNum();
  1335. break;
  1336. }
  1337. case RumorState::TYPE_MAP:
  1338. // Makes sure that map rumors only used if there enough rumors too choose from
  1339. if(!map->rumors.empty() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
  1340. {
  1341. rumorId = rand.nextInt((int)map->rumors.size() - 1);
  1342. break;
  1343. }
  1344. else
  1345. rumor.type = RumorState::TYPE_RAND;
  1346. [[fallthrough]];
  1347. case RumorState::TYPE_RAND:
  1348. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randtvrn");
  1349. rumorId = rand.nextInt((int)vector.size() - 1);
  1350. break;
  1351. }
  1352. }
  1353. while(!rumor.update(rumorId, rumorExtra));
  1354. }
  1355. bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
  1356. {
  1357. if (!map->isInTheMap(pos))
  1358. return false;
  1359. if (!player)
  1360. return true;
  1361. if(player == PlayerColor::NEUTRAL)
  1362. return false;
  1363. if(player->isSpectator())
  1364. return true;
  1365. return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y];
  1366. }
  1367. bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
  1368. {
  1369. if(!player)
  1370. return true;
  1371. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1372. if (player == obj->tempOwner)
  1373. return true;
  1374. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1375. return false;
  1376. //object is visible when at least one blocked tile is visible
  1377. for(int fy=0; fy < obj->getHeight(); ++fy)
  1378. {
  1379. for(int fx=0; fx < obj->getWidth(); ++fx)
  1380. {
  1381. int3 pos = obj->pos + int3(-fx, -fy, 0);
  1382. if ( map->isInTheMap(pos) &&
  1383. obj->coveringAt(pos.x, pos.y) &&
  1384. isVisible(pos, *player))
  1385. return true;
  1386. }
  1387. }
  1388. return false;
  1389. }
  1390. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1391. {
  1392. const TerrainTile * pom = &map->getTile(dst);
  1393. return map->checkForVisitableDir(src, pom, dst);
  1394. }
  1395. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  1396. {
  1397. const MetaString messageWonSelf = MetaString::createFromTextID("core.genrltxt.659");
  1398. const MetaString messageWonOther = MetaString::createFromTextID("core.genrltxt.5");
  1399. const MetaString messageLostSelf = MetaString::createFromTextID("core.genrltxt.7");
  1400. const MetaString messageLostOther = MetaString::createFromTextID("core.genrltxt.8");
  1401. auto evaluateEvent = [=](const EventCondition & condition)
  1402. {
  1403. return this->checkForVictory(player, condition);
  1404. };
  1405. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1406. //cheater or tester, but has entered the code...
  1407. if (p->enteredWinningCheatCode)
  1408. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1409. if (p->enteredLosingCheatCode)
  1410. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1411. for (const TriggeredEvent & event : map->triggeredEvents)
  1412. {
  1413. if (event.trigger.test(evaluateEvent))
  1414. {
  1415. if (event.effect.type == EventEffect::VICTORY)
  1416. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1417. if (event.effect.type == EventEffect::DEFEAT)
  1418. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1419. }
  1420. }
  1421. if (checkForStandardLoss(player))
  1422. {
  1423. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1424. }
  1425. return EVictoryLossCheckResult();
  1426. }
  1427. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  1428. {
  1429. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1430. switch (condition.condition)
  1431. {
  1432. case EventCondition::STANDARD_WIN:
  1433. {
  1434. return player == checkForStandardWin();
  1435. }
  1436. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1437. {
  1438. for(const auto & elem : p->heroes)
  1439. if(elem->hasArt(ArtifactID(condition.objectType)))
  1440. return true;
  1441. return false;
  1442. }
  1443. case EventCondition::HAVE_CREATURES:
  1444. {
  1445. //check if in players armies there is enough creatures
  1446. int total = 0; //creature counter
  1447. for(auto object : map->objects)
  1448. {
  1449. const CArmedInstance *ai = nullptr;
  1450. if(object
  1451. && object->tempOwner == player //object controlled by player
  1452. && (ai = dynamic_cast<const CArmedInstance *>(object.get()))) //contains army
  1453. {
  1454. for(const auto & elem : ai->Slots()) //iterate through army
  1455. if(elem.second->type->getId() == condition.objectType) //it's searched creature
  1456. total += elem.second->count;
  1457. }
  1458. }
  1459. return total >= condition.value;
  1460. }
  1461. case EventCondition::HAVE_RESOURCES:
  1462. {
  1463. return p->resources[condition.objectType] >= condition.value;
  1464. }
  1465. case EventCondition::HAVE_BUILDING:
  1466. {
  1467. if (condition.object) // specific town
  1468. {
  1469. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1470. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  1471. }
  1472. else // any town
  1473. {
  1474. for (const CGTownInstance * t : p->towns)
  1475. {
  1476. if (t->hasBuilt(BuildingID(condition.objectType)))
  1477. return true;
  1478. }
  1479. return false;
  1480. }
  1481. }
  1482. case EventCondition::DESTROY:
  1483. {
  1484. if (condition.object) // mode A - destroy specific object of this type
  1485. {
  1486. if(const auto * hero = dynamic_cast<const CGHeroInstance *>(condition.object))
  1487. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  1488. else
  1489. return getObj(condition.object->id) == nullptr;
  1490. }
  1491. else
  1492. {
  1493. for(const auto & elem : map->objects) // mode B - destroy all objects of this type
  1494. {
  1495. if(elem && elem->ID == condition.objectType)
  1496. return false;
  1497. }
  1498. return true;
  1499. }
  1500. }
  1501. case EventCondition::CONTROL:
  1502. {
  1503. // list of players that need to control object to fulfull condition
  1504. // NOTE: cgameinfocallback specified explicitly in order to get const version
  1505. const auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  1506. if (condition.object) // mode A - flag one specific object, like town
  1507. {
  1508. return team.count(condition.object->tempOwner) != 0;
  1509. }
  1510. else
  1511. {
  1512. for(const auto & elem : map->objects) // mode B - flag all objects of this type
  1513. {
  1514. //check not flagged objs
  1515. if ( elem && elem->ID == condition.objectType && team.count(elem->tempOwner) == 0 )
  1516. return false;
  1517. }
  1518. return true;
  1519. }
  1520. }
  1521. case EventCondition::TRANSPORT:
  1522. {
  1523. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1524. return (t->visitingHero && t->visitingHero->hasArt(ArtifactID(condition.objectType))) ||
  1525. (t->garrisonHero && t->garrisonHero->hasArt(ArtifactID(condition.objectType)));
  1526. }
  1527. case EventCondition::DAYS_PASSED:
  1528. {
  1529. return (si32)gs->day > condition.value;
  1530. }
  1531. case EventCondition::IS_HUMAN:
  1532. {
  1533. return p->human ? condition.value == 1 : condition.value == 0;
  1534. }
  1535. case EventCondition::DAYS_WITHOUT_TOWN:
  1536. {
  1537. if (p->daysWithoutCastle)
  1538. return p->daysWithoutCastle >= condition.value;
  1539. else
  1540. return false;
  1541. }
  1542. case EventCondition::CONST_VALUE:
  1543. {
  1544. return condition.value; // just convert to bool
  1545. }
  1546. case EventCondition::HAVE_0:
  1547. {
  1548. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1549. //TODO: support new condition format
  1550. return false;
  1551. }
  1552. case EventCondition::HAVE_BUILDING_0:
  1553. {
  1554. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1555. //TODO: support new condition format
  1556. return false;
  1557. }
  1558. case EventCondition::DESTROY_0:
  1559. {
  1560. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1561. //TODO: support new condition format
  1562. return false;
  1563. }
  1564. default:
  1565. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1566. return false;
  1567. }
  1568. }
  1569. PlayerColor CGameState::checkForStandardWin() const
  1570. {
  1571. //std victory condition is:
  1572. //all enemies lost
  1573. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  1574. TeamID winnerTeam = TeamID::NO_TEAM;
  1575. for(const auto & elem : players)
  1576. {
  1577. if(elem.second.status == EPlayerStatus::INGAME && elem.first < PlayerColor::PLAYER_LIMIT)
  1578. {
  1579. if(supposedWinner == PlayerColor::NEUTRAL)
  1580. {
  1581. //first player remaining ingame - candidate for victory
  1582. supposedWinner = elem.second.color;
  1583. winnerTeam = elem.second.team;
  1584. }
  1585. else if(winnerTeam != elem.second.team)
  1586. {
  1587. //current candidate has enemy remaining in game -> no vicotry
  1588. return PlayerColor::NEUTRAL;
  1589. }
  1590. }
  1591. }
  1592. return supposedWinner;
  1593. }
  1594. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  1595. {
  1596. //std loss condition is: player lost all towns and heroes
  1597. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  1598. return pState.checkVanquished();
  1599. }
  1600. struct statsHLP
  1601. {
  1602. using TStat = std::pair<PlayerColor, si64>;
  1603. //converts [<player's color, value>] to vec[place] -> platers
  1604. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  1605. {
  1606. std::sort(stats.begin(), stats.end(), statsHLP());
  1607. //put first element
  1608. std::vector< std::vector<PlayerColor> > ret;
  1609. std::vector<PlayerColor> tmp;
  1610. tmp.push_back( stats[0].first );
  1611. ret.push_back( tmp );
  1612. //the rest of elements
  1613. for(int g=1; g<stats.size(); ++g)
  1614. {
  1615. if(stats[g].second == stats[g-1].second)
  1616. {
  1617. (ret.end()-1)->push_back( stats[g].first );
  1618. }
  1619. else
  1620. {
  1621. //create next occupied rank
  1622. std::vector<PlayerColor> tmp;
  1623. tmp.push_back(stats[g].first);
  1624. ret.push_back(tmp);
  1625. }
  1626. }
  1627. return ret;
  1628. }
  1629. bool operator()(const TStat & a, const TStat & b) const
  1630. {
  1631. return a.second > b.second;
  1632. }
  1633. static const CGHeroInstance * findBestHero(CGameState * gs, const PlayerColor & color)
  1634. {
  1635. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  1636. if(h.empty())
  1637. return nullptr;
  1638. //best hero will be that with highest exp
  1639. int best = 0;
  1640. for(int b=1; b<h.size(); ++b)
  1641. {
  1642. if(h[b]->exp > h[best]->exp)
  1643. {
  1644. best = b;
  1645. }
  1646. }
  1647. return h[best];
  1648. }
  1649. //calculates total number of artifacts that belong to given player
  1650. static int getNumberOfArts(const PlayerState * ps)
  1651. {
  1652. int ret = 0;
  1653. for(auto h : ps->heroes)
  1654. {
  1655. ret += (int)h->artifactsInBackpack.size() + (int)h->artifactsWorn.size();
  1656. }
  1657. return ret;
  1658. }
  1659. // get total strength of player army
  1660. static si64 getArmyStrength(const PlayerState * ps)
  1661. {
  1662. si64 str = 0;
  1663. for(auto h : ps->heroes)
  1664. {
  1665. if(!h->inTownGarrison) //original h3 behavior
  1666. str += h->getArmyStrength();
  1667. }
  1668. return str;
  1669. }
  1670. // get total gold income
  1671. static int getIncome(const PlayerState * ps)
  1672. {
  1673. int totalIncome = 0;
  1674. const CGObjectInstance * heroOrTown = nullptr;
  1675. //Heroes can produce gold as well - skill, specialty or arts
  1676. for(const auto & h : ps->heroes)
  1677. {
  1678. totalIncome += h->valOfBonuses(Selector::typeSubtype(BonusType::GENERATE_RESOURCE, GameResID(EGameResID::GOLD)));
  1679. if(!heroOrTown)
  1680. heroOrTown = h;
  1681. }
  1682. //Add town income of all towns
  1683. for(const auto & t : ps->towns)
  1684. {
  1685. totalIncome += t->dailyIncome()[EGameResID::GOLD];
  1686. if(!heroOrTown)
  1687. heroOrTown = t;
  1688. }
  1689. /// FIXME: Dirty dirty hack
  1690. /// Stats helper need some access to gamestate.
  1691. std::vector<const CGObjectInstance *> ownedObjects;
  1692. for(const CGObjectInstance * obj : heroOrTown->cb->gameState()->map->objects)
  1693. {
  1694. if(obj && obj->tempOwner == ps->color)
  1695. ownedObjects.push_back(obj);
  1696. }
  1697. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  1698. /// I'm really need to find out about callback interface design...
  1699. for(const auto * object : ownedObjects)
  1700. {
  1701. //Mines
  1702. if ( object->ID == Obj::MINE )
  1703. {
  1704. const auto * mine = dynamic_cast<const CGMine *>(object);
  1705. assert(mine);
  1706. if (mine->producedResource == EGameResID::GOLD)
  1707. totalIncome += mine->producedQuantity;
  1708. }
  1709. }
  1710. return totalIncome;
  1711. }
  1712. };
  1713. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  1714. {
  1715. auto playerInactive = [&](const PlayerColor & color)
  1716. {
  1717. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  1718. };
  1719. #define FILL_FIELD(FIELD, VAL_GETTER) \
  1720. { \
  1721. std::vector< std::pair< PlayerColor, si64 > > stats; \
  1722. for(auto g = players.begin(); g != players.end(); ++g) \
  1723. { \
  1724. if(playerInactive(g->second.color)) \
  1725. continue; \
  1726. std::pair< PlayerColor, si64 > stat; \
  1727. stat.first = g->second.color; \
  1728. stat.second = VAL_GETTER; \
  1729. stats.push_back(stat); \
  1730. } \
  1731. tgi.FIELD = statsHLP::getRank(stats); \
  1732. }
  1733. for(auto & elem : players)
  1734. {
  1735. if(!playerInactive(elem.second.color))
  1736. tgi.playerColors.push_back(elem.second.color);
  1737. }
  1738. if(level >= 0) //num of towns & num of heroes
  1739. {
  1740. //num of towns
  1741. FILL_FIELD(numOfTowns, g->second.towns.size())
  1742. //num of heroes
  1743. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  1744. }
  1745. if(level >= 1) //best hero's portrait
  1746. {
  1747. for(const auto & player : players)
  1748. {
  1749. if(playerInactive(player.second.color))
  1750. continue;
  1751. const CGHeroInstance * best = statsHLP::findBestHero(this, player.second.color);
  1752. InfoAboutHero iah;
  1753. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  1754. iah.army.clear();
  1755. tgi.colorToBestHero[player.second.color] = iah;
  1756. }
  1757. }
  1758. if(level >= 2) //gold
  1759. {
  1760. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  1761. }
  1762. if(level >= 2) //wood & ore
  1763. {
  1764. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  1765. }
  1766. if(level >= 3) //mercury, sulfur, crystal, gems
  1767. {
  1768. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  1769. }
  1770. if(level >= 3) //obelisks found
  1771. {
  1772. auto getObeliskVisited = [](const TeamID & t)
  1773. {
  1774. if(CGObelisk::visited.count(t))
  1775. return CGObelisk::visited[t];
  1776. else
  1777. return ui8(0);
  1778. };
  1779. FILL_FIELD(obelisks, getObeliskVisited(gs->getPlayerTeam(g->second.color)->id))
  1780. }
  1781. if(level >= 4) //artifacts
  1782. {
  1783. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  1784. }
  1785. if(level >= 4) //army strength
  1786. {
  1787. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  1788. }
  1789. if(level >= 5) //income
  1790. {
  1791. FILL_FIELD(income, statsHLP::getIncome(&g->second))
  1792. }
  1793. if(level >= 2) //best hero's stats
  1794. {
  1795. //already set in lvl 1 handling
  1796. }
  1797. if(level >= 3) //personality
  1798. {
  1799. for(const auto & player : players)
  1800. {
  1801. if(playerInactive(player.second.color)) //do nothing for neutral player
  1802. continue;
  1803. if(player.second.human)
  1804. {
  1805. tgi.personality[player.second.color] = EAiTactic::NONE;
  1806. }
  1807. else //AI
  1808. {
  1809. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  1810. }
  1811. }
  1812. }
  1813. if(level >= 4) //best creature
  1814. {
  1815. //best creatures belonging to player (highest AI value)
  1816. for(const auto & player : players)
  1817. {
  1818. if(playerInactive(player.second.color)) //do nothing for neutral player
  1819. continue;
  1820. int bestCre = -1; //best creature's ID
  1821. for(const auto & elem : player.second.heroes)
  1822. {
  1823. for(const auto & it : elem->Slots())
  1824. {
  1825. int toCmp = it.second->type->getId(); //ID of creature we should compare with the best one
  1826. if(bestCre == -1 || VLC->creh->objects[bestCre]->getAIValue() < VLC->creh->objects[toCmp]->getAIValue())
  1827. {
  1828. bestCre = toCmp;
  1829. }
  1830. }
  1831. }
  1832. tgi.bestCreature[player.second.color] = bestCre;
  1833. }
  1834. }
  1835. #undef FILL_FIELD
  1836. }
  1837. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  1838. {
  1839. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  1840. for(const auto & player : players)
  1841. for(auto availableHero : player.second.availableHeroes)
  1842. if(availableHero)
  1843. pool.erase((*availableHero).subID);
  1844. return pool;
  1845. }
  1846. void CGameState::buildBonusSystemTree()
  1847. {
  1848. buildGlobalTeamPlayerTree();
  1849. attachArmedObjects();
  1850. for(CGTownInstance *t : map->towns)
  1851. {
  1852. t->deserializationFix();
  1853. }
  1854. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  1855. // are provided on initializing / deserializing
  1856. // NOTE: calling deserializationFix() might be more correct option, but might lead to side effects
  1857. for (auto hero : map->heroesOnMap)
  1858. hero->boatDeserializationFix();
  1859. }
  1860. void CGameState::deserializationFix()
  1861. {
  1862. buildGlobalTeamPlayerTree();
  1863. attachArmedObjects();
  1864. }
  1865. void CGameState::buildGlobalTeamPlayerTree()
  1866. {
  1867. for(auto & team : teams)
  1868. {
  1869. TeamState * t = &team.second;
  1870. t->attachTo(globalEffects);
  1871. for(const PlayerColor & teamMember : team.second.players)
  1872. {
  1873. PlayerState *p = getPlayerState(teamMember);
  1874. assert(p);
  1875. p->attachTo(*t);
  1876. }
  1877. }
  1878. }
  1879. void CGameState::attachArmedObjects()
  1880. {
  1881. for(CGObjectInstance *obj : map->objects)
  1882. {
  1883. if(auto * armed = dynamic_cast<CArmedInstance *>(obj))
  1884. {
  1885. armed->whatShouldBeAttached().attachTo(armed->whereShouldBeAttached(this));
  1886. }
  1887. }
  1888. }
  1889. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  1890. {
  1891. CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  1892. CArtifactInstance * ai = ArtifactUtils::createNewArtifactInstance(artifact);
  1893. map->addNewArtifactInstance(ai);
  1894. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  1895. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1896. {
  1897. ai->putAt(ArtifactLocation(h, slot));
  1898. return true;
  1899. }
  1900. else
  1901. {
  1902. return false;
  1903. }
  1904. }
  1905. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  1906. {
  1907. std::set<HeroTypeID> ret;
  1908. for(int i = 0; i < map->allowedHeroes.size(); i++)
  1909. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  1910. ret.insert(HeroTypeID(i));
  1911. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  1912. {
  1913. if(playerSettingPair.second.hero != PlayerSettings::RANDOM)
  1914. ret -= HeroTypeID(playerSettingPair.second.hero);
  1915. }
  1916. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1917. {
  1918. if(hero->type)
  1919. ret -= hero->type->getId();
  1920. else
  1921. ret -= HeroTypeID(hero->subID);
  1922. }
  1923. for(auto obj : map->objects) //prisons
  1924. if(obj && obj->ID == Obj::PRISON)
  1925. ret -= HeroTypeID(obj->subID);
  1926. return ret;
  1927. }
  1928. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  1929. {
  1930. return getUsedHero(hid);
  1931. }
  1932. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  1933. {
  1934. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1935. {
  1936. if(hero->type && hero->type->getId() == hid)
  1937. {
  1938. return hero;
  1939. }
  1940. }
  1941. for(auto obj : map->objects) //prisons
  1942. {
  1943. if(obj && obj->ID == Obj::PRISON )
  1944. {
  1945. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  1946. assert(hero);
  1947. if ( hero->type && hero->type->getId() == hid )
  1948. return hero;
  1949. }
  1950. }
  1951. return nullptr;
  1952. }
  1953. bool RumorState::update(int id, int extra)
  1954. {
  1955. if(vstd::contains(last, type))
  1956. {
  1957. if(last[type].first != id)
  1958. {
  1959. last[type].first = id;
  1960. last[type].second = extra;
  1961. }
  1962. else
  1963. return false;
  1964. }
  1965. else
  1966. last[type] = std::make_pair(id, extra);
  1967. return true;
  1968. }
  1969. TeamState::TeamState()
  1970. {
  1971. setNodeType(TEAM);
  1972. fogOfWarMap = std::make_shared<boost::multi_array<ui8, 3>>();
  1973. }
  1974. TeamState::TeamState(TeamState && other) noexcept:
  1975. CBonusSystemNode(std::move(other)),
  1976. id(other.id)
  1977. {
  1978. std::swap(players, other.players);
  1979. std::swap(fogOfWarMap, other.fogOfWarMap);
  1980. }
  1981. CRandomGenerator & CGameState::getRandomGenerator()
  1982. {
  1983. return rand;
  1984. }
  1985. VCMI_LIB_NAMESPACE_END