CGameState.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  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. initGrailPosition();
  463. initRandomFactionsForPlayers();
  464. randomizeMapObjects();
  465. placeStartingHeroes();
  466. initStartingResources();
  467. initHeroes();
  468. initStartingBonus();
  469. initTowns();
  470. placeHeroesInTowns();
  471. initMapObjects();
  472. buildBonusSystemTree();
  473. initVisitingAndGarrisonedHeroes();
  474. initFogOfWar();
  475. // Explicitly initialize static variables
  476. for(auto & elem : players)
  477. {
  478. CGKeys::playerKeyMap[elem.first] = std::set<ui8>();
  479. }
  480. for(auto & elem : teams)
  481. {
  482. CGObelisk::visited[elem.first] = 0;
  483. }
  484. logGlobal->debug("\tChecking objectives");
  485. map->checkForObjectives(); //needs to be run when all objects are properly placed
  486. auto seedAfterInit = getRandomGenerator().nextInt();
  487. logGlobal->info("Seed after init is %d (before was %d)", seedAfterInit, scenarioOps->seedToBeUsed);
  488. if(scenarioOps->seedPostInit > 0)
  489. {
  490. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  491. assert(scenarioOps->seedPostInit == seedAfterInit);
  492. }
  493. else
  494. {
  495. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  496. }
  497. }
  498. void CGameState::updateEntity(Metatype metatype, int32_t index, const JsonNode & data)
  499. {
  500. switch(metatype)
  501. {
  502. case Metatype::ARTIFACT_INSTANCE:
  503. logGlobal->error("Artifact instance update is not implemented");
  504. break;
  505. case Metatype::CREATURE_INSTANCE:
  506. logGlobal->error("Creature instance update is not implemented");
  507. break;
  508. case Metatype::HERO_INSTANCE:
  509. //index is hero type
  510. if(index >= 0 && index < map->allHeroes.size())
  511. {
  512. CGHeroInstance * hero = map->allHeroes.at(index);
  513. hero->updateFrom(data);
  514. }
  515. else
  516. {
  517. logGlobal->error("Update entity: hero index %s is out of range [%d,%d]", index, 0, map->allHeroes.size());
  518. }
  519. break;
  520. case Metatype::MAP_OBJECT_INSTANCE:
  521. if(index >= 0 && index < map->objects.size())
  522. {
  523. CGObjectInstance * obj = getObjInstance(ObjectInstanceID(index));
  524. obj->updateFrom(data);
  525. }
  526. else
  527. {
  528. logGlobal->error("Update entity: object index %s is out of range [%d,%d]", index, 0, map->objects.size());
  529. }
  530. break;
  531. default:
  532. services->updateEntity(metatype, index, data);
  533. break;
  534. }
  535. }
  536. void CGameState::updateOnLoad(StartInfo * si)
  537. {
  538. preInitAuto();
  539. scenarioOps->playerInfos = si->playerInfos;
  540. for(auto & i : si->playerInfos)
  541. gs->players[i.first].human = i.second.isControlledByHuman();
  542. }
  543. void CGameState::preInitAuto()
  544. {
  545. if(services == nullptr)
  546. {
  547. logGlobal->error("Game state preinit missing");
  548. preInit(VLC);
  549. }
  550. }
  551. void CGameState::initNewGame(const IMapService * mapService, bool allowSavingRandomMap)
  552. {
  553. if(scenarioOps->createRandomMap())
  554. {
  555. logGlobal->info("Create random map.");
  556. CStopWatch sw;
  557. // Gen map
  558. CMapGenerator mapGenerator(*scenarioOps->mapGenOptions, scenarioOps->seedToBeUsed);
  559. std::unique_ptr<CMap> randomMap = mapGenerator.generate();
  560. if(allowSavingRandomMap)
  561. {
  562. try
  563. {
  564. auto path = VCMIDirs::get().userCachePath() / "RandomMaps";
  565. boost::filesystem::create_directories(path);
  566. std::shared_ptr<CMapGenOptions> options = scenarioOps->mapGenOptions;
  567. const std::string templateName = options->getMapTemplate()->getName();
  568. const ui32 seed = scenarioOps->seedToBeUsed;
  569. const std::string fileName = boost::str(boost::format("%s_%d.vmap") % templateName % seed );
  570. const auto fullPath = path / fileName;
  571. mapService->saveMap(randomMap, fullPath);
  572. logGlobal->info("Random map has been saved to:");
  573. logGlobal->info(fullPath.string());
  574. }
  575. catch(...)
  576. {
  577. logGlobal->error("Saving random map failed with exception");
  578. handleException();
  579. }
  580. }
  581. map = randomMap.release();
  582. // Update starting options
  583. for(int i = 0; i < map->players.size(); ++i)
  584. {
  585. const auto & playerInfo = map->players[i];
  586. if(playerInfo.canAnyonePlay())
  587. {
  588. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  589. playerSettings.compOnly = !playerInfo.canHumanPlay;
  590. playerSettings.team = playerInfo.team;
  591. playerSettings.castle = playerInfo.defaultCastle();
  592. if(playerSettings.isControlledByAI() && playerSettings.name.empty())
  593. {
  594. playerSettings.name = VLC->generaltexth->allTexts[468];
  595. }
  596. playerSettings.color = PlayerColor(i);
  597. }
  598. else
  599. {
  600. scenarioOps->playerInfos.erase(PlayerColor(i));
  601. }
  602. }
  603. logGlobal->info("Generated random map in %i ms.", sw.getDiff());
  604. }
  605. else
  606. {
  607. logGlobal->info("Open map file: %s", scenarioOps->mapname);
  608. const ResourceID mapURI(scenarioOps->mapname, EResType::MAP);
  609. map = mapService->loadMap(mapURI).release();
  610. }
  611. }
  612. void CGameState::initCampaign()
  613. {
  614. campaign = std::make_unique<CGameStateCampaign>(this);
  615. map = campaign->getCurrentMap();
  616. }
  617. void CGameState::checkMapChecksum()
  618. {
  619. logGlobal->info("\tOur checksum for the map: %d", map->checksum);
  620. if(scenarioOps->mapfileChecksum)
  621. {
  622. logGlobal->info("\tServer checksum for %s: %d", scenarioOps->mapname, scenarioOps->mapfileChecksum);
  623. if(map->checksum != scenarioOps->mapfileChecksum)
  624. {
  625. logGlobal->error("Wrong map checksum!!!");
  626. throw std::runtime_error("Wrong checksum");
  627. }
  628. }
  629. else
  630. {
  631. scenarioOps->mapfileChecksum = map->checksum;
  632. }
  633. }
  634. void CGameState::initGlobalBonuses()
  635. {
  636. const JsonNode & baseBonuses = VLC->settings()->getValue(EGameSettings::BONUSES_GLOBAL);
  637. logGlobal->debug("\tLoading global bonuses");
  638. for(const auto & b : baseBonuses.Struct())
  639. {
  640. auto bonus = JsonUtils::parseBonus(b.second);
  641. bonus->source = BonusSource::GLOBAL;//for all
  642. bonus->sid = -1; //there is one global object
  643. globalEffects.addNewBonus(bonus);
  644. }
  645. VLC->creh->loadCrExpBon(globalEffects);
  646. }
  647. void CGameState::initGrailPosition()
  648. {
  649. logGlobal->debug("\tPicking grail position");
  650. //pick grail location
  651. if(map->grailPos.x < 0 || map->grailRadius) //grail not set or set within a radius around some place
  652. {
  653. if(!map->grailRadius) //radius not given -> anywhere on map
  654. map->grailRadius = map->width * 2;
  655. std::vector<int3> allowedPos;
  656. static const int BORDER_WIDTH = 9; // grail must be at least 9 tiles away from border
  657. // add all not blocked tiles in range
  658. for (int z = 0; z < map->levels(); z++)
  659. {
  660. for(int x = BORDER_WIDTH; x < map->width - BORDER_WIDTH ; x++)
  661. {
  662. for(int y = BORDER_WIDTH; y < map->height - BORDER_WIDTH; y++)
  663. {
  664. const TerrainTile &t = map->getTile(int3(x, y, z));
  665. if(!t.blocked
  666. && !t.visitable
  667. && t.terType->isLand()
  668. && t.terType->isPassable()
  669. && (int)map->grailPos.dist2dSQ(int3(x, y, z)) <= (map->grailRadius * map->grailRadius))
  670. allowedPos.emplace_back(x, y, z);
  671. }
  672. }
  673. }
  674. //remove tiles with holes
  675. for(auto & elem : map->objects)
  676. if(elem && elem->ID == Obj::HOLE)
  677. allowedPos -= elem->pos;
  678. if(!allowedPos.empty())
  679. {
  680. map->grailPos = *RandomGeneratorUtil::nextItem(allowedPos, getRandomGenerator());
  681. }
  682. else
  683. {
  684. logGlobal->warn("Grail cannot be placed, no appropriate tile found!");
  685. }
  686. }
  687. }
  688. void CGameState::initRandomFactionsForPlayers()
  689. {
  690. logGlobal->debug("\tPicking random factions for players");
  691. for(auto & elem : scenarioOps->playerInfos)
  692. {
  693. if(elem.second.castle==-1)
  694. {
  695. auto randomID = getRandomGenerator().nextInt((int)map->players[elem.first.getNum()].allowedFactions.size() - 1);
  696. auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
  697. std::advance(iter, randomID);
  698. elem.second.castle = *iter;
  699. }
  700. }
  701. }
  702. void CGameState::randomizeMapObjects()
  703. {
  704. logGlobal->debug("\tRandomizing objects");
  705. for(CGObjectInstance *obj : map->objects)
  706. {
  707. if(!obj) continue;
  708. randomizeObject(obj);
  709. //handle Favouring Winds - mark tiles under it
  710. if(obj->ID == Obj::FAVORABLE_WINDS)
  711. {
  712. for (int i = 0; i < obj->getWidth() ; i++)
  713. {
  714. for (int j = 0; j < obj->getHeight() ; j++)
  715. {
  716. int3 pos = obj->pos - int3(i,j,0);
  717. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  718. }
  719. }
  720. }
  721. }
  722. }
  723. void CGameState::initPlayerStates()
  724. {
  725. logGlobal->debug("\tCreating player entries in gs");
  726. for(auto & elem : scenarioOps->playerInfos)
  727. {
  728. PlayerState & p = players[elem.first];
  729. p.color=elem.first;
  730. p.human = elem.second.isControlledByHuman();
  731. p.team = map->players[elem.first.getNum()].team;
  732. teams[p.team].id = p.team;//init team
  733. teams[p.team].players.insert(elem.first);//add player to team
  734. }
  735. }
  736. void CGameState::placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos)
  737. {
  738. for(auto town : map->towns)
  739. {
  740. if(town->getPosition() == townPos)
  741. {
  742. townPos = town->visitablePos();
  743. break;
  744. }
  745. }
  746. CGObjectInstance * hero = createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor);
  747. hero->pos += hero->getVisitableOffset();
  748. map->getEditManager()->insertObject(hero);
  749. }
  750. void CGameState::placeStartingHeroes()
  751. {
  752. logGlobal->debug("\tGiving starting hero");
  753. for(auto & playerSettingPair : scenarioOps->playerInfos)
  754. {
  755. auto playerColor = playerSettingPair.first;
  756. auto & playerInfo = map->players[playerColor.getNum()];
  757. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  758. {
  759. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  760. if (campaign && campaign->playerHasStartingHero(playerColor))
  761. continue;
  762. int heroTypeId = pickNextHeroType(playerColor);
  763. if(playerSettingPair.second.hero == -1)
  764. playerSettingPair.second.hero = heroTypeId;
  765. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  766. }
  767. }
  768. }
  769. void CGameState::initStartingResources()
  770. {
  771. logGlobal->debug("\tSetting up resources");
  772. const JsonNode config(ResourceID("config/startres.json"));
  773. const JsonVector &vector = config["difficulty"].Vector();
  774. const JsonNode &level = vector[scenarioOps->difficulty];
  775. TResources startresAI(level["ai"]);
  776. TResources startresHuman(level["human"]);
  777. for (auto & elem : players)
  778. {
  779. PlayerState &p = elem.second;
  780. if (p.human)
  781. p.resources = startresHuman;
  782. else
  783. p.resources = startresAI;
  784. }
  785. if (campaign)
  786. campaign->initStartingResources();
  787. }
  788. void CGameState::initHeroes()
  789. {
  790. for(auto hero : map->heroesOnMap) //heroes instances initialization
  791. {
  792. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  793. {
  794. logGlobal->warn("Hero with uninitialized owner!");
  795. continue;
  796. }
  797. hero->initHero(getRandomGenerator());
  798. getPlayerState(hero->getOwner())->heroes.push_back(hero);
  799. map->allHeroes[hero->type->getIndex()] = hero;
  800. }
  801. // generate boats for all heroes on water
  802. for(auto hero : map->heroesOnMap)
  803. {
  804. assert(map->isInTheMap(hero->visitablePos()));
  805. const auto & tile = map->getTile(hero->visitablePos());
  806. if (tile.terType->isWater())
  807. {
  808. auto handler = VLC->objtypeh->getHandlerFor(Obj::BOAT, hero->getBoatType().getNum());
  809. CGBoat * boat = dynamic_cast<CGBoat*>(handler->create());
  810. handler->configureObject(boat, gs->getRandomGenerator());
  811. boat->ID = Obj::BOAT;
  812. boat->subID = hero->getBoatType().getNum();
  813. boat->pos = hero->pos;
  814. boat->appearance = handler->getTemplates().front();
  815. boat->id = ObjectInstanceID(static_cast<si32>(gs->map->objects.size()));
  816. map->objects.emplace_back(boat);
  817. map->addBlockVisTiles(boat);
  818. boat->hero = hero;
  819. hero->boat = boat;
  820. }
  821. }
  822. for(auto obj : map->objects) //prisons
  823. {
  824. if(obj && obj->ID == Obj::PRISON)
  825. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  826. }
  827. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  828. for(auto ph : map->predefinedHeroes)
  829. {
  830. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  831. continue;
  832. ph->initHero(getRandomGenerator());
  833. hpool.heroesPool[ph->subID] = ph;
  834. hpool.pavailable[ph->subID] = 0xff;
  835. heroesToCreate.erase(ph->type->getId());
  836. map->allHeroes[ph->subID] = ph;
  837. }
  838. for(const HeroTypeID & htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  839. {
  840. auto * vhi = new CGHeroInstance();
  841. vhi->initHero(getRandomGenerator(), htype);
  842. int typeID = htype.getNum();
  843. map->allHeroes[typeID] = vhi;
  844. hpool.heroesPool[typeID] = vhi;
  845. hpool.pavailable[typeID] = 0xff;
  846. }
  847. for(auto & elem : map->disposedHeroes)
  848. {
  849. hpool.pavailable[elem.heroId] = elem.players;
  850. }
  851. if (campaign)
  852. campaign->initHeroes();
  853. }
  854. void CGameState::initFogOfWar()
  855. {
  856. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  857. int layers = map->levels();
  858. for(auto & elem : teams)
  859. {
  860. auto fow = elem.second.fogOfWarMap;
  861. fow->resize(boost::extents[layers][map->width][map->height]);
  862. std::fill(fow->data(), fow->data() + fow->num_elements(), 0);
  863. for(CGObjectInstance *obj : map->objects)
  864. {
  865. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  866. std::unordered_set<int3> tiles;
  867. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius(), obj->tempOwner, 1);
  868. for(const int3 & tile : tiles)
  869. {
  870. (*elem.second.fogOfWarMap)[tile.z][tile.x][tile.y] = 1;
  871. }
  872. }
  873. }
  874. }
  875. void CGameState::initStartingBonus()
  876. {
  877. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  878. return;
  879. // These are the single scenario bonuses; predefined
  880. // campaign bonuses are spread out over other init* functions.
  881. logGlobal->debug("\tStarting bonuses");
  882. for(auto & elem : players)
  883. {
  884. //starting bonus
  885. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  886. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(getRandomGenerator().nextInt(2));
  887. switch(scenarioOps->playerInfos[elem.first].bonus)
  888. {
  889. case PlayerSettings::GOLD:
  890. elem.second.resources[EGameResID::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  891. break;
  892. case PlayerSettings::RESOURCE:
  893. {
  894. auto res = (*VLC->townh)[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  895. if(res == EGameResID::WOOD_AND_ORE)
  896. {
  897. int amount = getRandomGenerator().nextInt(5, 10);
  898. elem.second.resources[EGameResID::WOOD] += amount;
  899. elem.second.resources[EGameResID::ORE] += amount;
  900. }
  901. else
  902. {
  903. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  904. }
  905. break;
  906. }
  907. case PlayerSettings::ARTIFACT:
  908. {
  909. if(elem.second.heroes.empty())
  910. {
  911. logGlobal->error("Cannot give starting artifact - no heroes!");
  912. break;
  913. }
  914. const Artifact * toGive = VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE).toArtifact(VLC->artifacts());
  915. CGHeroInstance *hero = elem.second.heroes[0];
  916. if(!giveHeroArtifact(hero, toGive->getId()))
  917. logGlobal->error("Cannot give starting artifact - no free slots!");
  918. }
  919. break;
  920. }
  921. }
  922. }
  923. void CGameState::initTowns()
  924. {
  925. logGlobal->debug("\tTowns");
  926. if (campaign)
  927. campaign->initTowns();
  928. CGTownInstance::universitySkills.clear();
  929. for ( int i=0; i<4; i++)
  930. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  931. for (auto & elem : map->towns)
  932. {
  933. CGTownInstance * vti =(elem);
  934. if(!vti->town)
  935. {
  936. vti->town = (*VLC->townh)[vti->subID]->town;
  937. }
  938. if(vti->getNameTranslated().empty())
  939. {
  940. size_t nameID = getRandomGenerator().nextInt(vti->getTown()->getRandomNamesCount() - 1);
  941. vti->setNameTranslated(vti->getTown()->getRandomNameTranslated(nameID));
  942. }
  943. 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 };
  944. 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 };
  945. 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 };
  946. //init buildings
  947. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  948. {
  949. vti->builtBuildings.erase(BuildingID::DEFAULT);
  950. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  951. if(vti->tempOwner != PlayerColor::NEUTRAL)
  952. vti->builtBuildings.insert(BuildingID::TAVERN);
  953. auto definesBuildingsChances = VLC->settings()->getVector(EGameSettings::TOWNS_STARTING_DWELLING_CHANCES);
  954. for(int i = 0; i < definesBuildingsChances.size(); i++)
  955. {
  956. if((getRandomGenerator().nextInt(1,100) <= definesBuildingsChances[i]))
  957. {
  958. vti->builtBuildings.insert(basicDwellings[i]);
  959. }
  960. }
  961. }
  962. // village hall must always exist
  963. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  964. //init hordes
  965. for (int i = 0; i < GameConstants::CREATURES_PER_TOWN; i++)
  966. {
  967. if (vstd::contains(vti->builtBuildings, hordes[i])) //if we have horde for this level
  968. {
  969. vti->builtBuildings.erase(hordes[i]);//remove old ID
  970. if (vti->getTown()->hordeLvl.at(0) == i)//if town first horde is this one
  971. {
  972. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  973. //if we have upgraded dwelling as well
  974. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  975. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  976. }
  977. if (vti->getTown()->hordeLvl.at(1) == i)//if town second horde is this one
  978. {
  979. vti->builtBuildings.insert(BuildingID::HORDE_2);
  980. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  981. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  982. }
  983. }
  984. }
  985. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  986. //But DO NOT remove horde placeholders before they are replaced
  987. vstd::erase_if(vti->builtBuildings, [vti](const BuildingID & bid)
  988. {
  989. return !vti->getTown()->buildings.count(bid) || !vti->getTown()->buildings.at(bid);
  990. });
  991. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  992. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  993. //Early check for #1444-like problems
  994. for([[maybe_unused]] const auto & building : vti->builtBuildings)
  995. {
  996. assert(vti->getTown()->buildings.at(building) != nullptr);
  997. }
  998. //town events
  999. for(CCastleEvent &ev : vti->events)
  1000. {
  1001. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1002. if (vstd::contains(ev.buildings,hordes[i])) //if we have horde for this level
  1003. {
  1004. ev.buildings.erase(hordes[i]);
  1005. if (vti->getTown()->hordeLvl.at(0) == i)
  1006. ev.buildings.insert(BuildingID::HORDE_1);
  1007. if (vti->getTown()->hordeLvl.at(1) == i)
  1008. ev.buildings.insert(BuildingID::HORDE_2);
  1009. }
  1010. }
  1011. //init spells
  1012. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1013. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1014. {
  1015. const auto * s = vti->obligatorySpells[z].toSpell();
  1016. vti->spells[s->level-1].push_back(s->id);
  1017. vti->possibleSpells -= s->id;
  1018. }
  1019. while(!vti->possibleSpells.empty())
  1020. {
  1021. ui32 total=0;
  1022. int sel = -1;
  1023. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1024. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  1025. if (total == 0) // remaining spells have 0 probability
  1026. break;
  1027. auto r = getRandomGenerator().nextInt(total - 1);
  1028. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1029. {
  1030. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  1031. if(r<0)
  1032. {
  1033. sel = ps;
  1034. break;
  1035. }
  1036. }
  1037. if(sel<0)
  1038. sel=0;
  1039. const auto * s = vti->possibleSpells[sel].toSpell();
  1040. vti->spells[s->level-1].push_back(s->id);
  1041. vti->possibleSpells -= s->id;
  1042. }
  1043. vti->possibleSpells.clear();
  1044. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1045. getPlayerState(vti->getOwner())->towns.emplace_back(vti);
  1046. }
  1047. }
  1048. void CGameState::initMapObjects()
  1049. {
  1050. logGlobal->debug("\tObject initialization");
  1051. // objCaller->preInit();
  1052. for(CGObjectInstance *obj : map->objects)
  1053. {
  1054. if(obj)
  1055. {
  1056. logGlobal->trace("Calling Init for object %d, %s, %s", obj->id.getNum(), obj->typeName, obj->subTypeName);
  1057. obj->initObj(getRandomGenerator());
  1058. }
  1059. }
  1060. for(CGObjectInstance *obj : map->objects)
  1061. {
  1062. if(!obj)
  1063. continue;
  1064. switch (obj->ID)
  1065. {
  1066. case Obj::QUEST_GUARD:
  1067. case Obj::SEER_HUT:
  1068. {
  1069. auto * q = dynamic_cast<CGSeerHut *>(obj);
  1070. assert (q);
  1071. q->setObjToKill();
  1072. }
  1073. }
  1074. }
  1075. CGSubterraneanGate::postInit(); //pairing subterranean gates
  1076. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  1077. }
  1078. void CGameState::placeHeroesInTowns()
  1079. {
  1080. for(auto & player : players)
  1081. {
  1082. if(player.first == PlayerColor::NEUTRAL)
  1083. continue;
  1084. for(CGHeroInstance * h : player.second.heroes)
  1085. {
  1086. for(CGTownInstance * t : player.second.towns)
  1087. {
  1088. if(h->visitablePos().z != t->visitablePos().z)
  1089. continue;
  1090. bool heroOnTownBlockableTile = t->blockingAt(h->visitablePos().x, h->visitablePos().y);
  1091. // current hero position is at one of blocking tiles of current town
  1092. // assume that this hero should be visiting the town (H3M format quirk) and move hero to correct position
  1093. if (heroOnTownBlockableTile)
  1094. {
  1095. int3 correctedPos = h->convertFromVisitablePos(t->visitablePos());
  1096. map->removeBlockVisTiles(h);
  1097. h->pos = correctedPos;
  1098. map->addBlockVisTiles(h);
  1099. assert(t->visitableAt(h->visitablePos().x, h->visitablePos().y));
  1100. }
  1101. }
  1102. }
  1103. }
  1104. }
  1105. void CGameState::initVisitingAndGarrisonedHeroes()
  1106. {
  1107. for(auto & player : players)
  1108. {
  1109. if(player.first == PlayerColor::NEUTRAL)
  1110. continue;
  1111. //init visiting and garrisoned heroes
  1112. for(CGHeroInstance * h : player.second.heroes)
  1113. {
  1114. for(CGTownInstance * t : player.second.towns)
  1115. {
  1116. if(h->visitablePos().z != t->visitablePos().z)
  1117. continue;
  1118. if (t->visitableAt(h->visitablePos().x, h->visitablePos().y))
  1119. {
  1120. assert(t->visitingHero == nullptr);
  1121. t->setVisitingHero(h);
  1122. }
  1123. }
  1124. }
  1125. }
  1126. for (auto hero : map->heroesOnMap)
  1127. {
  1128. if (hero->visitedTown)
  1129. {
  1130. assert (hero->visitedTown->visitingHero == hero);
  1131. }
  1132. }
  1133. }
  1134. BattleField CGameState::battleGetBattlefieldType(int3 tile, CRandomGenerator & rand)
  1135. {
  1136. if(!tile.valid() && curB)
  1137. tile = curB->tile;
  1138. else if(!tile.valid() && !curB)
  1139. return BattleField::NONE;
  1140. const TerrainTile &t = map->getTile(tile);
  1141. auto * topObject = t.visitableObjects.front();
  1142. if(topObject && topObject->getBattlefield() != BattleField::NONE)
  1143. {
  1144. return topObject->getBattlefield();
  1145. }
  1146. for(auto &obj : map->objects)
  1147. {
  1148. //look only for objects covering given tile
  1149. if( !obj || obj->pos.z != tile.z || !obj->coveringAt(tile.x, tile.y))
  1150. continue;
  1151. auto customBattlefield = obj->getBattlefield();
  1152. if(customBattlefield != BattleField::NONE)
  1153. return customBattlefield;
  1154. }
  1155. if(map->isCoastalTile(tile)) //coastal tile is always ground
  1156. return BattleField::fromString("sand_shore");
  1157. return BattleField(*RandomGeneratorUtil::nextItem(t.terType->battleFields, rand));
  1158. }
  1159. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  1160. {
  1161. assert(obj);
  1162. assert(obj->hasStackAtSlot(stackPos));
  1163. out = fillUpgradeInfo(obj->getStack(stackPos));
  1164. }
  1165. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance &stack) const
  1166. {
  1167. UpgradeInfo ret;
  1168. const CCreature *base = stack.type;
  1169. if (stack.armyObj->ID == Obj::HERO)
  1170. {
  1171. auto hero = dynamic_cast<const CGHeroInstance *>(stack.armyObj);
  1172. hero->fillUpgradeInfo(ret, stack);
  1173. if (hero->visitedTown)
  1174. {
  1175. hero->visitedTown->fillUpgradeInfo(ret, stack);
  1176. }
  1177. else
  1178. {
  1179. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  1180. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  1181. if (object != hero && upgradeSource != nullptr)
  1182. upgradeSource->fillUpgradeInfo(ret, stack);
  1183. }
  1184. }
  1185. if (stack.armyObj->ID == Obj::TOWN)
  1186. {
  1187. auto town = dynamic_cast<const CGTownInstance *>(stack.armyObj);
  1188. town->fillUpgradeInfo(ret, stack);
  1189. }
  1190. if(!ret.newID.empty())
  1191. ret.oldID = base->getId();
  1192. for (ResourceSet &cost : ret.cost)
  1193. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1194. return ret;
  1195. }
  1196. PlayerRelations::PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  1197. {
  1198. if ( color1 == color2 )
  1199. return PlayerRelations::SAME_PLAYER;
  1200. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1201. return PlayerRelations::ENEMIES;
  1202. const TeamState * ts = getPlayerTeam(color1);
  1203. if (ts && vstd::contains(ts->players, color2))
  1204. return PlayerRelations::ALLIES;
  1205. return PlayerRelations::ENEMIES;
  1206. }
  1207. void CGameState::apply(CPack *pack)
  1208. {
  1209. ui16 typ = typeList.getTypeID(pack);
  1210. applier->getApplier(typ)->applyOnGS(this, pack);
  1211. }
  1212. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  1213. {
  1214. calculatePaths(std::make_shared<SingleHeroPathfinderConfig>(out, this, hero));
  1215. }
  1216. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config)
  1217. {
  1218. //FIXME: creating pathfinder is costly, maybe reset / clear is enough?
  1219. CPathfinder pathfinder(this, config);
  1220. pathfinder.calculatePaths();
  1221. }
  1222. /**
  1223. * Tells if the tile is guarded by a monster as well as the position
  1224. * of the monster that will attack on it.
  1225. *
  1226. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1227. * the monster guarding the tile.
  1228. */
  1229. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1230. {
  1231. std::vector<CGObjectInstance*> guards;
  1232. const int3 originalPos = pos;
  1233. if (!map->isInTheMap(pos))
  1234. return guards;
  1235. const TerrainTile &posTile = map->getTile(pos);
  1236. if (posTile.visitable)
  1237. {
  1238. for (CGObjectInstance* obj : posTile.visitableObjects)
  1239. {
  1240. if(obj->isBlockedVisitable())
  1241. {
  1242. if (obj->ID == Obj::MONSTER) // Monster
  1243. guards.push_back(obj);
  1244. }
  1245. }
  1246. }
  1247. pos -= int3(1, 1, 0); // Start with top left.
  1248. for (int dx = 0; dx < 3; dx++)
  1249. {
  1250. for (int dy = 0; dy < 3; dy++)
  1251. {
  1252. if (map->isInTheMap(pos))
  1253. {
  1254. const auto & tile = map->getTile(pos);
  1255. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1256. {
  1257. for (CGObjectInstance* obj : tile.visitableObjects)
  1258. {
  1259. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1260. {
  1261. guards.push_back(obj);
  1262. }
  1263. }
  1264. }
  1265. }
  1266. pos.y++;
  1267. }
  1268. pos.y -= 3;
  1269. pos.x++;
  1270. }
  1271. return guards;
  1272. }
  1273. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1274. {
  1275. return gs->map->guardingCreaturePositions[pos.z][pos.x][pos.y];
  1276. }
  1277. void CGameState::updateRumor()
  1278. {
  1279. static std::vector<RumorState::ERumorType> rumorTypes = {RumorState::TYPE_MAP, RumorState::TYPE_SPECIAL, RumorState::TYPE_RAND, RumorState::TYPE_RAND};
  1280. std::vector<RumorState::ERumorTypeSpecial> sRumorTypes = {
  1281. RumorState::RUMOR_OBELISKS, RumorState::RUMOR_ARTIFACTS, RumorState::RUMOR_ARMY, RumorState::RUMOR_INCOME};
  1282. if(map->grailPos.valid()) // Grail should always be on map, but I had related crash I didn't manage to reproduce
  1283. sRumorTypes.push_back(RumorState::RUMOR_GRAIL);
  1284. int rumorId = -1;
  1285. int rumorExtra = -1;
  1286. auto & rand = getRandomGenerator();
  1287. rumor.type = *RandomGeneratorUtil::nextItem(rumorTypes, rand);
  1288. do
  1289. {
  1290. switch(rumor.type)
  1291. {
  1292. case RumorState::TYPE_SPECIAL:
  1293. {
  1294. SThievesGuildInfo tgi;
  1295. obtainPlayersStats(tgi, 20);
  1296. rumorId = *RandomGeneratorUtil::nextItem(sRumorTypes, rand);
  1297. if(rumorId == RumorState::RUMOR_GRAIL)
  1298. {
  1299. rumorExtra = getTile(map->grailPos)->terType->getIndex();
  1300. break;
  1301. }
  1302. std::vector<PlayerColor> players = {};
  1303. switch(rumorId)
  1304. {
  1305. case RumorState::RUMOR_OBELISKS:
  1306. players = tgi.obelisks[0];
  1307. break;
  1308. case RumorState::RUMOR_ARTIFACTS:
  1309. players = tgi.artifacts[0];
  1310. break;
  1311. case RumorState::RUMOR_ARMY:
  1312. players = tgi.army[0];
  1313. break;
  1314. case RumorState::RUMOR_INCOME:
  1315. players = tgi.income[0];
  1316. break;
  1317. }
  1318. rumorExtra = RandomGeneratorUtil::nextItem(players, rand)->getNum();
  1319. break;
  1320. }
  1321. case RumorState::TYPE_MAP:
  1322. // Makes sure that map rumors only used if there enough rumors too choose from
  1323. if(!map->rumors.empty() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
  1324. {
  1325. rumorId = rand.nextInt((int)map->rumors.size() - 1);
  1326. break;
  1327. }
  1328. else
  1329. rumor.type = RumorState::TYPE_RAND;
  1330. [[fallthrough]];
  1331. case RumorState::TYPE_RAND:
  1332. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randtvrn");
  1333. rumorId = rand.nextInt((int)vector.size() - 1);
  1334. break;
  1335. }
  1336. }
  1337. while(!rumor.update(rumorId, rumorExtra));
  1338. }
  1339. bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
  1340. {
  1341. if (!map->isInTheMap(pos))
  1342. return false;
  1343. if (!player)
  1344. return true;
  1345. if(player == PlayerColor::NEUTRAL)
  1346. return false;
  1347. if(player->isSpectator())
  1348. return true;
  1349. return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y];
  1350. }
  1351. bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
  1352. {
  1353. if(!player)
  1354. return true;
  1355. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1356. if (player == obj->tempOwner)
  1357. return true;
  1358. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1359. return false;
  1360. //object is visible when at least one blocked tile is visible
  1361. for(int fy=0; fy < obj->getHeight(); ++fy)
  1362. {
  1363. for(int fx=0; fx < obj->getWidth(); ++fx)
  1364. {
  1365. int3 pos = obj->pos + int3(-fx, -fy, 0);
  1366. if ( map->isInTheMap(pos) &&
  1367. obj->coveringAt(pos.x, pos.y) &&
  1368. isVisible(pos, *player))
  1369. return true;
  1370. }
  1371. }
  1372. return false;
  1373. }
  1374. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1375. {
  1376. const TerrainTile * pom = &map->getTile(dst);
  1377. return map->checkForVisitableDir(src, pom, dst);
  1378. }
  1379. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  1380. {
  1381. const MetaString messageWonSelf = MetaString::createFromTextID("core.genrltxt.659");
  1382. const MetaString messageWonOther = MetaString::createFromTextID("core.genrltxt.5");
  1383. const MetaString messageLostSelf = MetaString::createFromTextID("core.genrltxt.7");
  1384. const MetaString messageLostOther = MetaString::createFromTextID("core.genrltxt.8");
  1385. auto evaluateEvent = [=](const EventCondition & condition)
  1386. {
  1387. return this->checkForVictory(player, condition);
  1388. };
  1389. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1390. //cheater or tester, but has entered the code...
  1391. if (p->enteredWinningCheatCode)
  1392. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1393. if (p->enteredLosingCheatCode)
  1394. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1395. for (const TriggeredEvent & event : map->triggeredEvents)
  1396. {
  1397. if (event.trigger.test(evaluateEvent))
  1398. {
  1399. if (event.effect.type == EventEffect::VICTORY)
  1400. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1401. if (event.effect.type == EventEffect::DEFEAT)
  1402. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1403. }
  1404. }
  1405. if (checkForStandardLoss(player))
  1406. {
  1407. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1408. }
  1409. return EVictoryLossCheckResult();
  1410. }
  1411. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  1412. {
  1413. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1414. switch (condition.condition)
  1415. {
  1416. case EventCondition::STANDARD_WIN:
  1417. {
  1418. return player == checkForStandardWin();
  1419. }
  1420. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1421. {
  1422. for(const auto & elem : p->heroes)
  1423. if(elem->hasArt(ArtifactID(condition.objectType)))
  1424. return true;
  1425. return false;
  1426. }
  1427. case EventCondition::HAVE_CREATURES:
  1428. {
  1429. //check if in players armies there is enough creatures
  1430. int total = 0; //creature counter
  1431. for(auto object : map->objects)
  1432. {
  1433. const CArmedInstance *ai = nullptr;
  1434. if(object
  1435. && object->tempOwner == player //object controlled by player
  1436. && (ai = dynamic_cast<const CArmedInstance *>(object.get()))) //contains army
  1437. {
  1438. for(const auto & elem : ai->Slots()) //iterate through army
  1439. if(elem.second->type->getId() == condition.objectType) //it's searched creature
  1440. total += elem.second->count;
  1441. }
  1442. }
  1443. return total >= condition.value;
  1444. }
  1445. case EventCondition::HAVE_RESOURCES:
  1446. {
  1447. return p->resources[condition.objectType] >= condition.value;
  1448. }
  1449. case EventCondition::HAVE_BUILDING:
  1450. {
  1451. if (condition.object) // specific town
  1452. {
  1453. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1454. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  1455. }
  1456. else // any town
  1457. {
  1458. for (const CGTownInstance * t : p->towns)
  1459. {
  1460. if (t->hasBuilt(BuildingID(condition.objectType)))
  1461. return true;
  1462. }
  1463. return false;
  1464. }
  1465. }
  1466. case EventCondition::DESTROY:
  1467. {
  1468. if (condition.object) // mode A - destroy specific object of this type
  1469. {
  1470. if(const auto * hero = dynamic_cast<const CGHeroInstance *>(condition.object))
  1471. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  1472. else
  1473. return getObj(condition.object->id) == nullptr;
  1474. }
  1475. else
  1476. {
  1477. for(const auto & elem : map->objects) // mode B - destroy all objects of this type
  1478. {
  1479. if(elem && elem->ID == condition.objectType)
  1480. return false;
  1481. }
  1482. return true;
  1483. }
  1484. }
  1485. case EventCondition::CONTROL:
  1486. {
  1487. // list of players that need to control object to fulfull condition
  1488. // NOTE: cgameinfocallback specified explicitly in order to get const version
  1489. const auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  1490. if (condition.object) // mode A - flag one specific object, like town
  1491. {
  1492. return team.count(condition.object->tempOwner) != 0;
  1493. }
  1494. else
  1495. {
  1496. for(const auto & elem : map->objects) // mode B - flag all objects of this type
  1497. {
  1498. //check not flagged objs
  1499. if ( elem && elem->ID == condition.objectType && team.count(elem->tempOwner) == 0 )
  1500. return false;
  1501. }
  1502. return true;
  1503. }
  1504. }
  1505. case EventCondition::TRANSPORT:
  1506. {
  1507. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1508. return (t->visitingHero && t->visitingHero->hasArt(ArtifactID(condition.objectType))) ||
  1509. (t->garrisonHero && t->garrisonHero->hasArt(ArtifactID(condition.objectType)));
  1510. }
  1511. case EventCondition::DAYS_PASSED:
  1512. {
  1513. return (si32)gs->day > condition.value;
  1514. }
  1515. case EventCondition::IS_HUMAN:
  1516. {
  1517. return p->human ? condition.value == 1 : condition.value == 0;
  1518. }
  1519. case EventCondition::DAYS_WITHOUT_TOWN:
  1520. {
  1521. if (p->daysWithoutCastle)
  1522. return p->daysWithoutCastle >= condition.value;
  1523. else
  1524. return false;
  1525. }
  1526. case EventCondition::CONST_VALUE:
  1527. {
  1528. return condition.value; // just convert to bool
  1529. }
  1530. case EventCondition::HAVE_0:
  1531. {
  1532. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1533. //TODO: support new condition format
  1534. return false;
  1535. }
  1536. case EventCondition::HAVE_BUILDING_0:
  1537. {
  1538. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1539. //TODO: support new condition format
  1540. return false;
  1541. }
  1542. case EventCondition::DESTROY_0:
  1543. {
  1544. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1545. //TODO: support new condition format
  1546. return false;
  1547. }
  1548. default:
  1549. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1550. return false;
  1551. }
  1552. }
  1553. PlayerColor CGameState::checkForStandardWin() const
  1554. {
  1555. //std victory condition is:
  1556. //all enemies lost
  1557. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  1558. TeamID winnerTeam = TeamID::NO_TEAM;
  1559. for(const auto & elem : players)
  1560. {
  1561. if(elem.second.status == EPlayerStatus::INGAME && elem.first < PlayerColor::PLAYER_LIMIT)
  1562. {
  1563. if(supposedWinner == PlayerColor::NEUTRAL)
  1564. {
  1565. //first player remaining ingame - candidate for victory
  1566. supposedWinner = elem.second.color;
  1567. winnerTeam = elem.second.team;
  1568. }
  1569. else if(winnerTeam != elem.second.team)
  1570. {
  1571. //current candidate has enemy remaining in game -> no vicotry
  1572. return PlayerColor::NEUTRAL;
  1573. }
  1574. }
  1575. }
  1576. return supposedWinner;
  1577. }
  1578. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  1579. {
  1580. //std loss condition is: player lost all towns and heroes
  1581. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  1582. return pState.checkVanquished();
  1583. }
  1584. struct statsHLP
  1585. {
  1586. using TStat = std::pair<PlayerColor, si64>;
  1587. //converts [<player's color, value>] to vec[place] -> platers
  1588. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  1589. {
  1590. std::sort(stats.begin(), stats.end(), statsHLP());
  1591. //put first element
  1592. std::vector< std::vector<PlayerColor> > ret;
  1593. std::vector<PlayerColor> tmp;
  1594. tmp.push_back( stats[0].first );
  1595. ret.push_back( tmp );
  1596. //the rest of elements
  1597. for(int g=1; g<stats.size(); ++g)
  1598. {
  1599. if(stats[g].second == stats[g-1].second)
  1600. {
  1601. (ret.end()-1)->push_back( stats[g].first );
  1602. }
  1603. else
  1604. {
  1605. //create next occupied rank
  1606. std::vector<PlayerColor> tmp;
  1607. tmp.push_back(stats[g].first);
  1608. ret.push_back(tmp);
  1609. }
  1610. }
  1611. return ret;
  1612. }
  1613. bool operator()(const TStat & a, const TStat & b) const
  1614. {
  1615. return a.second > b.second;
  1616. }
  1617. static const CGHeroInstance * findBestHero(CGameState * gs, const PlayerColor & color)
  1618. {
  1619. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  1620. if(h.empty())
  1621. return nullptr;
  1622. //best hero will be that with highest exp
  1623. int best = 0;
  1624. for(int b=1; b<h.size(); ++b)
  1625. {
  1626. if(h[b]->exp > h[best]->exp)
  1627. {
  1628. best = b;
  1629. }
  1630. }
  1631. return h[best];
  1632. }
  1633. //calculates total number of artifacts that belong to given player
  1634. static int getNumberOfArts(const PlayerState * ps)
  1635. {
  1636. int ret = 0;
  1637. for(auto h : ps->heroes)
  1638. {
  1639. ret += (int)h->artifactsInBackpack.size() + (int)h->artifactsWorn.size();
  1640. }
  1641. return ret;
  1642. }
  1643. // get total strength of player army
  1644. static si64 getArmyStrength(const PlayerState * ps)
  1645. {
  1646. si64 str = 0;
  1647. for(auto h : ps->heroes)
  1648. {
  1649. if(!h->inTownGarrison) //original h3 behavior
  1650. str += h->getArmyStrength();
  1651. }
  1652. return str;
  1653. }
  1654. // get total gold income
  1655. static int getIncome(const PlayerState * ps)
  1656. {
  1657. int totalIncome = 0;
  1658. const CGObjectInstance * heroOrTown = nullptr;
  1659. //Heroes can produce gold as well - skill, specialty or arts
  1660. for(const auto & h : ps->heroes)
  1661. {
  1662. totalIncome += h->valOfBonuses(Selector::typeSubtype(BonusType::GENERATE_RESOURCE, GameResID(EGameResID::GOLD)));
  1663. if(!heroOrTown)
  1664. heroOrTown = h;
  1665. }
  1666. //Add town income of all towns
  1667. for(const auto & t : ps->towns)
  1668. {
  1669. totalIncome += t->dailyIncome()[EGameResID::GOLD];
  1670. if(!heroOrTown)
  1671. heroOrTown = t;
  1672. }
  1673. /// FIXME: Dirty dirty hack
  1674. /// Stats helper need some access to gamestate.
  1675. std::vector<const CGObjectInstance *> ownedObjects;
  1676. for(const CGObjectInstance * obj : heroOrTown->cb->gameState()->map->objects)
  1677. {
  1678. if(obj && obj->tempOwner == ps->color)
  1679. ownedObjects.push_back(obj);
  1680. }
  1681. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  1682. /// I'm really need to find out about callback interface design...
  1683. for(const auto * object : ownedObjects)
  1684. {
  1685. //Mines
  1686. if ( object->ID == Obj::MINE )
  1687. {
  1688. const auto * mine = dynamic_cast<const CGMine *>(object);
  1689. assert(mine);
  1690. if (mine->producedResource == EGameResID::GOLD)
  1691. totalIncome += mine->producedQuantity;
  1692. }
  1693. }
  1694. return totalIncome;
  1695. }
  1696. };
  1697. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  1698. {
  1699. auto playerInactive = [&](const PlayerColor & color)
  1700. {
  1701. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  1702. };
  1703. #define FILL_FIELD(FIELD, VAL_GETTER) \
  1704. { \
  1705. std::vector< std::pair< PlayerColor, si64 > > stats; \
  1706. for(auto g = players.begin(); g != players.end(); ++g) \
  1707. { \
  1708. if(playerInactive(g->second.color)) \
  1709. continue; \
  1710. std::pair< PlayerColor, si64 > stat; \
  1711. stat.first = g->second.color; \
  1712. stat.second = VAL_GETTER; \
  1713. stats.push_back(stat); \
  1714. } \
  1715. tgi.FIELD = statsHLP::getRank(stats); \
  1716. }
  1717. for(auto & elem : players)
  1718. {
  1719. if(!playerInactive(elem.second.color))
  1720. tgi.playerColors.push_back(elem.second.color);
  1721. }
  1722. if(level >= 0) //num of towns & num of heroes
  1723. {
  1724. //num of towns
  1725. FILL_FIELD(numOfTowns, g->second.towns.size())
  1726. //num of heroes
  1727. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  1728. }
  1729. if(level >= 1) //best hero's portrait
  1730. {
  1731. for(const auto & player : players)
  1732. {
  1733. if(playerInactive(player.second.color))
  1734. continue;
  1735. const CGHeroInstance * best = statsHLP::findBestHero(this, player.second.color);
  1736. InfoAboutHero iah;
  1737. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  1738. iah.army.clear();
  1739. tgi.colorToBestHero[player.second.color] = iah;
  1740. }
  1741. }
  1742. if(level >= 2) //gold
  1743. {
  1744. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  1745. }
  1746. if(level >= 2) //wood & ore
  1747. {
  1748. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  1749. }
  1750. if(level >= 3) //mercury, sulfur, crystal, gems
  1751. {
  1752. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  1753. }
  1754. if(level >= 3) //obelisks found
  1755. {
  1756. auto getObeliskVisited = [](const TeamID & t)
  1757. {
  1758. if(CGObelisk::visited.count(t))
  1759. return CGObelisk::visited[t];
  1760. else
  1761. return ui8(0);
  1762. };
  1763. FILL_FIELD(obelisks, getObeliskVisited(gs->getPlayerTeam(g->second.color)->id))
  1764. }
  1765. if(level >= 4) //artifacts
  1766. {
  1767. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  1768. }
  1769. if(level >= 4) //army strength
  1770. {
  1771. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  1772. }
  1773. if(level >= 5) //income
  1774. {
  1775. FILL_FIELD(income, statsHLP::getIncome(&g->second))
  1776. }
  1777. if(level >= 2) //best hero's stats
  1778. {
  1779. //already set in lvl 1 handling
  1780. }
  1781. if(level >= 3) //personality
  1782. {
  1783. for(const auto & player : players)
  1784. {
  1785. if(playerInactive(player.second.color)) //do nothing for neutral player
  1786. continue;
  1787. if(player.second.human)
  1788. {
  1789. tgi.personality[player.second.color] = EAiTactic::NONE;
  1790. }
  1791. else //AI
  1792. {
  1793. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  1794. }
  1795. }
  1796. }
  1797. if(level >= 4) //best creature
  1798. {
  1799. //best creatures belonging to player (highest AI value)
  1800. for(const auto & player : players)
  1801. {
  1802. if(playerInactive(player.second.color)) //do nothing for neutral player
  1803. continue;
  1804. int bestCre = -1; //best creature's ID
  1805. for(const auto & elem : player.second.heroes)
  1806. {
  1807. for(const auto & it : elem->Slots())
  1808. {
  1809. int toCmp = it.second->type->getId(); //ID of creature we should compare with the best one
  1810. if(bestCre == -1 || VLC->creh->objects[bestCre]->getAIValue() < VLC->creh->objects[toCmp]->getAIValue())
  1811. {
  1812. bestCre = toCmp;
  1813. }
  1814. }
  1815. }
  1816. tgi.bestCreature[player.second.color] = bestCre;
  1817. }
  1818. }
  1819. #undef FILL_FIELD
  1820. }
  1821. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  1822. {
  1823. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  1824. for(const auto & player : players)
  1825. for(auto availableHero : player.second.availableHeroes)
  1826. if(availableHero)
  1827. pool.erase((*availableHero).subID);
  1828. return pool;
  1829. }
  1830. void CGameState::buildBonusSystemTree()
  1831. {
  1832. buildGlobalTeamPlayerTree();
  1833. attachArmedObjects();
  1834. for(CGTownInstance *t : map->towns)
  1835. {
  1836. t->deserializationFix();
  1837. }
  1838. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  1839. // are provided on initializing / deserializing
  1840. // NOTE: calling deserializationFix() might be more correct option, but might lead to side effects
  1841. for (auto hero : map->heroesOnMap)
  1842. hero->boatDeserializationFix();
  1843. }
  1844. void CGameState::deserializationFix()
  1845. {
  1846. buildGlobalTeamPlayerTree();
  1847. attachArmedObjects();
  1848. }
  1849. void CGameState::buildGlobalTeamPlayerTree()
  1850. {
  1851. for(auto & team : teams)
  1852. {
  1853. TeamState * t = &team.second;
  1854. t->attachTo(globalEffects);
  1855. for(const PlayerColor & teamMember : team.second.players)
  1856. {
  1857. PlayerState *p = getPlayerState(teamMember);
  1858. assert(p);
  1859. p->attachTo(*t);
  1860. }
  1861. }
  1862. }
  1863. void CGameState::attachArmedObjects()
  1864. {
  1865. for(CGObjectInstance *obj : map->objects)
  1866. {
  1867. if(auto * armed = dynamic_cast<CArmedInstance *>(obj))
  1868. {
  1869. armed->whatShouldBeAttached().attachTo(armed->whereShouldBeAttached(this));
  1870. }
  1871. }
  1872. }
  1873. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  1874. {
  1875. CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  1876. CArtifactInstance * ai = ArtifactUtils::createNewArtifactInstance(artifact);
  1877. map->addNewArtifactInstance(ai);
  1878. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  1879. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1880. {
  1881. ai->putAt(ArtifactLocation(h, slot));
  1882. return true;
  1883. }
  1884. else
  1885. {
  1886. return false;
  1887. }
  1888. }
  1889. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  1890. {
  1891. std::set<HeroTypeID> ret;
  1892. for(int i = 0; i < map->allowedHeroes.size(); i++)
  1893. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  1894. ret.insert(HeroTypeID(i));
  1895. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  1896. {
  1897. if(playerSettingPair.second.hero != PlayerSettings::RANDOM)
  1898. ret -= HeroTypeID(playerSettingPair.second.hero);
  1899. }
  1900. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1901. {
  1902. if(hero->type)
  1903. ret -= hero->type->getId();
  1904. else
  1905. ret -= HeroTypeID(hero->subID);
  1906. }
  1907. for(auto obj : map->objects) //prisons
  1908. if(obj && obj->ID == Obj::PRISON)
  1909. ret -= HeroTypeID(obj->subID);
  1910. return ret;
  1911. }
  1912. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  1913. {
  1914. return getUsedHero(hid);
  1915. }
  1916. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  1917. {
  1918. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1919. {
  1920. if(hero->type && hero->type->getId() == hid)
  1921. {
  1922. return hero;
  1923. }
  1924. }
  1925. for(auto obj : map->objects) //prisons
  1926. {
  1927. if(obj && obj->ID == Obj::PRISON )
  1928. {
  1929. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  1930. assert(hero);
  1931. if ( hero->type && hero->type->getId() == hid )
  1932. return hero;
  1933. }
  1934. }
  1935. return nullptr;
  1936. }
  1937. bool RumorState::update(int id, int extra)
  1938. {
  1939. if(vstd::contains(last, type))
  1940. {
  1941. if(last[type].first != id)
  1942. {
  1943. last[type].first = id;
  1944. last[type].second = extra;
  1945. }
  1946. else
  1947. return false;
  1948. }
  1949. else
  1950. last[type] = std::make_pair(id, extra);
  1951. return true;
  1952. }
  1953. TeamState::TeamState()
  1954. {
  1955. setNodeType(TEAM);
  1956. fogOfWarMap = std::make_shared<boost::multi_array<ui8, 3>>();
  1957. }
  1958. TeamState::TeamState(TeamState && other) noexcept:
  1959. CBonusSystemNode(std::move(other)),
  1960. id(other.id)
  1961. {
  1962. std::swap(players, other.players);
  1963. std::swap(fogOfWarMap, other.fogOfWarMap);
  1964. }
  1965. CRandomGenerator & CGameState::getRandomGenerator()
  1966. {
  1967. return rand;
  1968. }
  1969. VCMI_LIB_NAMESPACE_END