CGameState.cpp 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987
  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 "mapping/CCampaignHandler.h"
  13. #include "ArtifactUtils.h"
  14. #include "CArtHandler.h"
  15. #include "CBuildingHandler.h"
  16. #include "CGeneralTextHandler.h"
  17. #include "CTownHandler.h"
  18. #include "spells/CSpellHandler.h"
  19. #include "CHeroHandler.h"
  20. #include "CModHandler.h"
  21. #include "GameSettings.h"
  22. #include "TerrainHandler.h"
  23. #include "CSkillHandler.h"
  24. #include "mapping/CMap.h"
  25. #include "mapping/CMapService.h"
  26. #include "mapObjectConstructors/CObjectClassesHandler.h"
  27. #include "StartInfo.h"
  28. #include "NetPacks.h"
  29. #include "pathfinder/CPathfinder.h"
  30. #include "pathfinder/PathfinderOptions.h"
  31. #include "registerTypes/RegisterTypes.h"
  32. #include "battle/BattleInfo.h"
  33. #include "JsonNode.h"
  34. #include "filesystem/Filesystem.h"
  35. #include "GameConstants.h"
  36. #include "rmg/CMapGenerator.h"
  37. #include "CStopWatch.h"
  38. #include "mapping/CMapEditManager.h"
  39. #include "serializer/CTypeList.h"
  40. #include "serializer/CMemorySerializer.h"
  41. #include "VCMIDirs.h"
  42. VCMI_LIB_NAMESPACE_BEGIN
  43. boost::shared_mutex CGameState::mutex;
  44. template <typename T> class CApplyOnGS;
  45. class CBaseForGSApply
  46. {
  47. public:
  48. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  49. virtual ~CBaseForGSApply() = default;
  50. template<typename U> static CBaseForGSApply *getApplier(const U * t=nullptr)
  51. {
  52. return new CApplyOnGS<U>();
  53. }
  54. };
  55. template <typename T> class CApplyOnGS : public CBaseForGSApply
  56. {
  57. public:
  58. void applyOnGS(CGameState *gs, void *pack) const override
  59. {
  60. T *ptr = static_cast<T*>(pack);
  61. boost::unique_lock<boost::shared_mutex> lock(CGameState::mutex);
  62. ptr->applyGs(gs);
  63. }
  64. };
  65. static CGObjectInstance * createObject(const Obj & id, int subid, const int3 & pos, const PlayerColor & owner)
  66. {
  67. CGObjectInstance * nobj;
  68. switch(id)
  69. {
  70. case Obj::HERO:
  71. {
  72. auto handler = VLC->objtypeh->getHandlerFor(id, VLC->heroh->objects[subid]->heroClass->getIndex());
  73. nobj = handler->create(handler->getTemplates().front());
  74. break;
  75. }
  76. case Obj::TOWN:
  77. nobj = new CGTownInstance();
  78. break;
  79. default: //rest of objects
  80. nobj = new CGObjectInstance();
  81. break;
  82. }
  83. nobj->ID = id;
  84. nobj->subID = subid;
  85. nobj->pos = pos;
  86. nobj->tempOwner = owner;
  87. if (id != Obj::HERO)
  88. nobj->appearance = VLC->objtypeh->getHandlerFor(id, subid)->getTemplates().front();
  89. return nobj;
  90. }
  91. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native,
  92. const PlayerColor & player,
  93. const CTown * town,
  94. std::map<ui32, ConstTransitivePtr<CGHeroInstance>> & available,
  95. CRandomGenerator & rand,
  96. const CHeroClass * bannedClass) const
  97. {
  98. CGHeroInstance *ret = nullptr;
  99. if(player>=PlayerColor::PLAYER_LIMIT)
  100. {
  101. logGlobal->error("Cannot pick hero for faction %s. Wrong owner!", town->faction->getJsonKey());
  102. return nullptr;
  103. }
  104. std::vector<CGHeroInstance *> pool;
  105. if(native)
  106. {
  107. for(auto & elem : available)
  108. {
  109. if(pavailable.find(elem.first)->second & 1<<player.getNum()
  110. && elem.second->type->heroClass->faction == town->faction->getIndex())
  111. {
  112. pool.push_back(elem.second); //get all available heroes
  113. }
  114. }
  115. if(pool.empty())
  116. {
  117. logGlobal->error("Cannot pick native hero for %s. Picking any...", player.getStr());
  118. return pickHeroFor(false, player, town, available, rand);
  119. }
  120. else
  121. {
  122. ret = *RandomGeneratorUtil::nextItem(pool, rand);
  123. }
  124. }
  125. else
  126. {
  127. int sum = 0;
  128. int r;
  129. for(auto & elem : available)
  130. {
  131. if (pavailable.find(elem.first)->second & (1<<player.getNum()) && // hero is available
  132. ( !bannedClass || elem.second->type->heroClass != bannedClass) ) // and his class is not same as other hero
  133. {
  134. pool.push_back(elem.second);
  135. sum += elem.second->type->heroClass->selectionProbability[town->faction->getId()]; //total weight
  136. }
  137. }
  138. if(pool.empty() || sum == 0)
  139. {
  140. logGlobal->error("There are no heroes available for player %s!", player.getStr());
  141. return nullptr;
  142. }
  143. r = rand.nextInt(sum - 1);
  144. for (auto & elem : pool)
  145. {
  146. r -= elem->type->heroClass->selectionProbability[town->faction->getId()];
  147. if(r < 0)
  148. {
  149. ret = elem;
  150. break;
  151. }
  152. }
  153. if(!ret)
  154. ret = pool.back();
  155. }
  156. available.erase(ret->subID);
  157. return ret;
  158. }
  159. void CGameState::CrossoverHeroesList::addHeroToBothLists(CGHeroInstance * hero)
  160. {
  161. heroesFromPreviousScenario.push_back(hero);
  162. heroesFromAnyPreviousScenarios.push_back(hero);
  163. }
  164. void CGameState::CrossoverHeroesList::removeHeroFromBothLists(CGHeroInstance * hero)
  165. {
  166. heroesFromPreviousScenario -= hero;
  167. heroesFromAnyPreviousScenarios -= hero;
  168. }
  169. CGameState::CampaignHeroReplacement::CampaignHeroReplacement(CGHeroInstance * hero, const ObjectInstanceID & heroPlaceholderId):
  170. hero(hero),
  171. heroPlaceholderId(heroPlaceholderId)
  172. {
  173. }
  174. int CGameState::pickNextHeroType(const PlayerColor & owner)
  175. {
  176. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  177. if(ps.hero >= 0 && !isUsedHero(HeroTypeID(ps.hero))) //we haven't used selected hero
  178. {
  179. return ps.hero;
  180. }
  181. return pickUnusedHeroTypeRandomly(owner);
  182. }
  183. int CGameState::pickUnusedHeroTypeRandomly(const PlayerColor & owner)
  184. {
  185. //list of available heroes for this faction and others
  186. std::vector<HeroTypeID> factionHeroes;
  187. std::vector<HeroTypeID> otherHeroes;
  188. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  189. for(const HeroTypeID & hid : getUnusedAllowedHeroes())
  190. {
  191. if(VLC->heroh->objects[hid.getNum()]->heroClass->faction == ps.castle)
  192. factionHeroes.push_back(hid);
  193. else
  194. otherHeroes.push_back(hid);
  195. }
  196. // select random hero native to "our" faction
  197. if(!factionHeroes.empty())
  198. {
  199. return RandomGeneratorUtil::nextItem(factionHeroes, getRandomGenerator())->getNum();
  200. }
  201. logGlobal->warn("Cannot find free hero of appropriate faction for player %s - trying to get first available...", owner.getStr());
  202. if(!otherHeroes.empty())
  203. {
  204. return RandomGeneratorUtil::nextItem(otherHeroes, getRandomGenerator())->getNum();
  205. }
  206. logGlobal->error("No free allowed heroes!");
  207. auto notAllowedHeroesButStillBetterThanCrash = getUnusedAllowedHeroes(true);
  208. if(!notAllowedHeroesButStillBetterThanCrash.empty())
  209. return notAllowedHeroesButStillBetterThanCrash.begin()->getNum();
  210. logGlobal->error("No free heroes at all!");
  211. assert(0); //current code can't handle this situation
  212. return -1; // no available heroes at all
  213. }
  214. std::pair<Obj,int> CGameState::pickObject (CGObjectInstance *obj)
  215. {
  216. switch(obj->ID)
  217. {
  218. case Obj::RANDOM_ART:
  219. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  220. case Obj::RANDOM_TREASURE_ART:
  221. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE));
  222. case Obj::RANDOM_MINOR_ART:
  223. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MINOR));
  224. case Obj::RANDOM_MAJOR_ART:
  225. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MAJOR));
  226. case Obj::RANDOM_RELIC_ART:
  227. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_RELIC));
  228. case Obj::RANDOM_HERO:
  229. return std::make_pair(Obj::HERO, pickNextHeroType(obj->tempOwner));
  230. case Obj::RANDOM_MONSTER:
  231. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator()));
  232. case Obj::RANDOM_MONSTER_L1:
  233. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 1));
  234. case Obj::RANDOM_MONSTER_L2:
  235. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 2));
  236. case Obj::RANDOM_MONSTER_L3:
  237. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 3));
  238. case Obj::RANDOM_MONSTER_L4:
  239. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 4));
  240. case Obj::RANDOM_RESOURCE:
  241. return std::make_pair(Obj::RESOURCE,getRandomGenerator().nextInt(6)); //now it's OH3 style, use %8 for mithril
  242. case Obj::RANDOM_TOWN:
  243. {
  244. PlayerColor align = (dynamic_cast<CGTownInstance *>(obj))->alignmentToPlayer;
  245. si32 f; // can be negative (for random)
  246. if(align >= PlayerColor::PLAYER_LIMIT) //same as owner / random
  247. {
  248. if(obj->tempOwner >= PlayerColor::PLAYER_LIMIT)
  249. f = -1; //random
  250. else
  251. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  252. }
  253. else
  254. {
  255. f = scenarioOps->getIthPlayersSettings(align).castle;
  256. }
  257. if(f<0)
  258. {
  259. do
  260. {
  261. f = getRandomGenerator().nextInt((int)VLC->townh->size() - 1);
  262. }
  263. while ((*VLC->townh)[f]->town == nullptr); // find playable faction
  264. }
  265. return std::make_pair(Obj::TOWN,f);
  266. }
  267. case Obj::RANDOM_MONSTER_L5:
  268. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 5));
  269. case Obj::RANDOM_MONSTER_L6:
  270. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 6));
  271. case Obj::RANDOM_MONSTER_L7:
  272. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 7));
  273. case Obj::RANDOM_DWELLING:
  274. case Obj::RANDOM_DWELLING_LVL:
  275. case Obj::RANDOM_DWELLING_FACTION:
  276. {
  277. auto * dwl = dynamic_cast<CGDwelling *>(obj);
  278. int faction;
  279. //if castle alignment available
  280. if(auto * info = dynamic_cast<CCreGenAsCastleInfo *>(dwl->info))
  281. {
  282. faction = getRandomGenerator().nextInt((int)VLC->townh->size() - 1);
  283. if(info->asCastle && !info->instanceId.empty())
  284. {
  285. auto iter = map->instanceNames.find(info->instanceId);
  286. if(iter == map->instanceNames.end())
  287. logGlobal->error("Map object not found: %s", info->instanceId);
  288. else
  289. {
  290. auto elem = iter->second;
  291. if(elem->ID==Obj::RANDOM_TOWN)
  292. {
  293. randomizeObject(elem.get()); //we have to randomize the castle first
  294. faction = elem->subID;
  295. }
  296. else if(elem->ID==Obj::TOWN)
  297. faction = elem->subID;
  298. else
  299. logGlobal->error("Map object must be town: %s", info->instanceId);
  300. }
  301. }
  302. else if(info->asCastle)
  303. {
  304. for(auto & elem : map->objects)
  305. {
  306. if(!elem)
  307. continue;
  308. if(elem->ID==Obj::RANDOM_TOWN
  309. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  310. {
  311. randomizeObject(elem); //we have to randomize the castle first
  312. faction = elem->subID;
  313. break;
  314. }
  315. else if(elem->ID==Obj::TOWN
  316. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  317. {
  318. faction = elem->subID;
  319. break;
  320. }
  321. }
  322. }
  323. else
  324. {
  325. std::set<int> temp;
  326. for(int i = 0; i < info->allowedFactions.size(); i++)
  327. if(info->allowedFactions[i])
  328. temp.insert(i);
  329. if(temp.empty())
  330. logGlobal->error("Random faction selection failed. Nothing is allowed. Fall back to random.");
  331. else
  332. faction = *RandomGeneratorUtil::nextItem(temp, getRandomGenerator());
  333. }
  334. }
  335. else // castle alignment fixed
  336. faction = obj->subID;
  337. int level;
  338. //if level set to range
  339. if(auto * info = dynamic_cast<CCreGenLeveledInfo *>(dwl->info))
  340. {
  341. level = getRandomGenerator().nextInt(info->minLevel, info->maxLevel);
  342. }
  343. else // fixed level
  344. {
  345. level = obj->subID;
  346. }
  347. delete dwl->info;
  348. dwl->info = nullptr;
  349. std::pair<Obj, int> result(Obj::NO_OBJ, -1);
  350. CreatureID cid = (*VLC->townh)[faction]->town->creatures[level][0];
  351. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  352. //check for block map equality is better but more complex solution
  353. auto testID = [&](const Obj & primaryID) -> void
  354. {
  355. auto dwellingIDs = VLC->objtypeh->knownSubObjects(primaryID);
  356. for (si32 entry : dwellingIDs)
  357. {
  358. const auto * handler = dynamic_cast<const DwellingInstanceConstructor *>(VLC->objtypeh->getHandlerFor(primaryID, entry).get());
  359. if (handler->producesCreature(VLC->creh->objects[cid]))
  360. result = std::make_pair(primaryID, entry);
  361. }
  362. };
  363. testID(Obj::CREATURE_GENERATOR1);
  364. if (result.first == Obj::NO_OBJ)
  365. testID(Obj::CREATURE_GENERATOR4);
  366. if (result.first == Obj::NO_OBJ)
  367. {
  368. logGlobal->error("Error: failed to find dwelling for %s of level %d", (*VLC->townh)[faction]->getNameTranslated(), int(level));
  369. result = std::make_pair(Obj::CREATURE_GENERATOR1, *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1), getRandomGenerator()));
  370. }
  371. return result;
  372. }
  373. }
  374. return std::make_pair(Obj::NO_OBJ,-1);
  375. }
  376. void CGameState::randomizeObject(CGObjectInstance *cur)
  377. {
  378. std::pair<Obj,int> ran = pickObject(cur);
  379. if(ran.first == Obj::NO_OBJ || ran.second<0) //this is not a random object, or we couldn't find anything
  380. {
  381. if(cur->ID==Obj::TOWN || cur->ID==Obj::MONSTER)
  382. cur->setType(cur->ID, cur->subID); // update def, if necessary
  383. }
  384. else if(ran.first==Obj::HERO)//special code for hero
  385. {
  386. auto * h = dynamic_cast<CGHeroInstance *>(cur);
  387. cur->setType(ran.first, ran.second);
  388. map->heroesOnMap.emplace_back(h);
  389. }
  390. else if(ran.first==Obj::TOWN)//special code for town
  391. {
  392. auto * t = dynamic_cast<CGTownInstance *>(cur);
  393. cur->setType(ran.first, ran.second);
  394. map->towns.emplace_back(t);
  395. }
  396. else
  397. {
  398. cur->setType(ran.first, ran.second);
  399. }
  400. }
  401. int CGameState::getDate(Date::EDateType mode) const
  402. {
  403. int temp;
  404. switch (mode)
  405. {
  406. case Date::DAY:
  407. return day;
  408. case Date::DAY_OF_WEEK: //day of week
  409. temp = (day)%7; // 1 - Monday, 7 - Sunday
  410. return temp ? temp : 7;
  411. case Date::WEEK: //current week
  412. temp = ((day-1)/7)+1;
  413. if (!(temp%4))
  414. return 4;
  415. else
  416. return (temp%4);
  417. case Date::MONTH: //current month
  418. return ((day-1)/28)+1;
  419. case Date::DAY_OF_MONTH: //day of month
  420. temp = (day)%28;
  421. if (temp)
  422. return temp;
  423. else return 28;
  424. }
  425. return 0;
  426. }
  427. CGameState::CGameState()
  428. {
  429. gs = this;
  430. applier = std::make_shared<CApplier<CBaseForGSApply>>();
  431. registerTypesClientPacks1(*applier);
  432. registerTypesClientPacks2(*applier);
  433. globalEffects.setNodeType(CBonusSystemNode::GLOBAL_EFFECTS);
  434. }
  435. CGameState::~CGameState()
  436. {
  437. map.dellNull();
  438. curB.dellNull();
  439. for(auto ptr : hpool.heroesPool) // clean hero pool
  440. ptr.second.dellNull();
  441. }
  442. void CGameState::preInit(Services * services)
  443. {
  444. this->services = services;
  445. }
  446. void CGameState::init(const IMapService * mapService, StartInfo * si, bool allowSavingRandomMap)
  447. {
  448. preInitAuto();
  449. logGlobal->info("\tUsing random seed: %d", si->seedToBeUsed);
  450. getRandomGenerator().setSeed(si->seedToBeUsed);
  451. scenarioOps = CMemorySerializer::deepCopy(*si).release();
  452. initialOpts = CMemorySerializer::deepCopy(*si).release();
  453. si = nullptr;
  454. switch(scenarioOps->mode)
  455. {
  456. case StartInfo::NEW_GAME:
  457. initNewGame(mapService, allowSavingRandomMap);
  458. break;
  459. case StartInfo::CAMPAIGN:
  460. initCampaign();
  461. break;
  462. default:
  463. logGlobal->error("Wrong mode: %d", static_cast<int>(scenarioOps->mode));
  464. return;
  465. }
  466. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  467. logGlobal->info("Map loaded!");
  468. checkMapChecksum();
  469. day = 0;
  470. logGlobal->debug("Initialization:");
  471. initGlobalBonuses();
  472. initPlayerStates();
  473. placeCampaignHeroes();
  474. initGrailPosition();
  475. initRandomFactionsForPlayers();
  476. randomizeMapObjects();
  477. placeStartingHeroes();
  478. initStartingResources();
  479. initHeroes();
  480. initStartingBonus();
  481. initTowns();
  482. placeHeroesInTowns();
  483. initMapObjects();
  484. buildBonusSystemTree();
  485. initVisitingAndGarrisonedHeroes();
  486. initFogOfWar();
  487. // Explicitly initialize static variables
  488. for(auto & elem : players)
  489. {
  490. CGKeys::playerKeyMap[elem.first] = std::set<ui8>();
  491. }
  492. for(auto & elem : teams)
  493. {
  494. CGObelisk::visited[elem.first] = 0;
  495. }
  496. logGlobal->debug("\tChecking objectives");
  497. map->checkForObjectives(); //needs to be run when all objects are properly placed
  498. auto seedAfterInit = getRandomGenerator().nextInt();
  499. logGlobal->info("Seed after init is %d (before was %d)", seedAfterInit, scenarioOps->seedToBeUsed);
  500. if(scenarioOps->seedPostInit > 0)
  501. {
  502. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  503. assert(scenarioOps->seedPostInit == seedAfterInit);
  504. }
  505. else
  506. {
  507. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  508. }
  509. }
  510. void CGameState::updateEntity(Metatype metatype, int32_t index, const JsonNode & data)
  511. {
  512. switch(metatype)
  513. {
  514. case Metatype::ARTIFACT_INSTANCE:
  515. logGlobal->error("Artifact instance update is not implemented");
  516. break;
  517. case Metatype::CREATURE_INSTANCE:
  518. logGlobal->error("Creature instance update is not implemented");
  519. break;
  520. case Metatype::HERO_INSTANCE:
  521. //index is hero type
  522. if(index >= 0 && index < map->allHeroes.size())
  523. {
  524. CGHeroInstance * hero = map->allHeroes.at(index);
  525. hero->updateFrom(data);
  526. }
  527. else
  528. {
  529. logGlobal->error("Update entity: hero index %s is out of range [%d,%d]", index, 0, map->allHeroes.size());
  530. }
  531. break;
  532. case Metatype::MAP_OBJECT_INSTANCE:
  533. if(index >= 0 && index < map->objects.size())
  534. {
  535. CGObjectInstance * obj = getObjInstance(ObjectInstanceID(index));
  536. obj->updateFrom(data);
  537. }
  538. else
  539. {
  540. logGlobal->error("Update entity: object index %s is out of range [%d,%d]", index, 0, map->objects.size());
  541. }
  542. break;
  543. default:
  544. services->updateEntity(metatype, index, data);
  545. break;
  546. }
  547. }
  548. void CGameState::updateOnLoad(StartInfo * si)
  549. {
  550. preInitAuto();
  551. scenarioOps->playerInfos = si->playerInfos;
  552. for(auto & i : si->playerInfos)
  553. gs->players[i.first].human = i.second.isControlledByHuman();
  554. }
  555. void CGameState::preInitAuto()
  556. {
  557. if(services == nullptr)
  558. {
  559. logGlobal->error("Game state preinit missing");
  560. preInit(VLC);
  561. }
  562. }
  563. void CGameState::initNewGame(const IMapService * mapService, bool allowSavingRandomMap)
  564. {
  565. if(scenarioOps->createRandomMap())
  566. {
  567. logGlobal->info("Create random map.");
  568. CStopWatch sw;
  569. // Gen map
  570. CMapGenerator mapGenerator(*scenarioOps->mapGenOptions, scenarioOps->seedToBeUsed);
  571. std::unique_ptr<CMap> randomMap = mapGenerator.generate();
  572. if(allowSavingRandomMap)
  573. {
  574. try
  575. {
  576. auto path = VCMIDirs::get().userCachePath() / "RandomMaps";
  577. boost::filesystem::create_directories(path);
  578. std::shared_ptr<CMapGenOptions> options = scenarioOps->mapGenOptions;
  579. const std::string templateName = options->getMapTemplate()->getName();
  580. const ui32 seed = scenarioOps->seedToBeUsed;
  581. const std::string fileName = boost::str(boost::format("%s_%d.vmap") % templateName % seed );
  582. const auto fullPath = path / fileName;
  583. mapService->saveMap(randomMap, fullPath);
  584. logGlobal->info("Random map has been saved to:");
  585. logGlobal->info(fullPath.string());
  586. }
  587. catch(...)
  588. {
  589. logGlobal->error("Saving random map failed with exception");
  590. handleException();
  591. }
  592. }
  593. map = randomMap.release();
  594. // Update starting options
  595. for(int i = 0; i < map->players.size(); ++i)
  596. {
  597. const auto & playerInfo = map->players[i];
  598. if(playerInfo.canAnyonePlay())
  599. {
  600. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  601. playerSettings.compOnly = !playerInfo.canHumanPlay;
  602. playerSettings.team = playerInfo.team;
  603. playerSettings.castle = playerInfo.defaultCastle();
  604. if(playerSettings.isControlledByAI() && playerSettings.name.empty())
  605. {
  606. playerSettings.name = VLC->generaltexth->allTexts[468];
  607. }
  608. playerSettings.color = PlayerColor(i);
  609. }
  610. else
  611. {
  612. scenarioOps->playerInfos.erase(PlayerColor(i));
  613. }
  614. }
  615. logGlobal->info("Generated random map in %i ms.", sw.getDiff());
  616. }
  617. else
  618. {
  619. logGlobal->info("Open map file: %s", scenarioOps->mapname);
  620. const ResourceID mapURI(scenarioOps->mapname, EResType::MAP);
  621. map = mapService->loadMap(mapURI).release();
  622. }
  623. }
  624. void CGameState::initCampaign()
  625. {
  626. logGlobal->info("Open campaign map file: %d", scenarioOps->campState->currentMap.value());
  627. map = scenarioOps->campState->getMap();
  628. }
  629. void CGameState::checkMapChecksum()
  630. {
  631. logGlobal->info("\tOur checksum for the map: %d", map->checksum);
  632. if(scenarioOps->mapfileChecksum)
  633. {
  634. logGlobal->info("\tServer checksum for %s: %d", scenarioOps->mapname, scenarioOps->mapfileChecksum);
  635. if(map->checksum != scenarioOps->mapfileChecksum)
  636. {
  637. logGlobal->error("Wrong map checksum!!!");
  638. throw std::runtime_error("Wrong checksum");
  639. }
  640. }
  641. else
  642. {
  643. scenarioOps->mapfileChecksum = map->checksum;
  644. }
  645. }
  646. void CGameState::initGlobalBonuses()
  647. {
  648. const JsonNode & baseBonuses = VLC->settings()->getValue(EGameSettings::BONUSES_GLOBAL);
  649. logGlobal->debug("\tLoading global bonuses");
  650. for(const auto & b : baseBonuses.Struct())
  651. {
  652. auto bonus = JsonUtils::parseBonus(b.second);
  653. bonus->source = BonusSource::GLOBAL;//for all
  654. bonus->sid = -1; //there is one global object
  655. globalEffects.addNewBonus(bonus);
  656. }
  657. VLC->creh->loadCrExpBon(globalEffects);
  658. }
  659. void CGameState::initGrailPosition()
  660. {
  661. logGlobal->debug("\tPicking grail position");
  662. //pick grail location
  663. if(map->grailPos.x < 0 || map->grailRadius) //grail not set or set within a radius around some place
  664. {
  665. if(!map->grailRadius) //radius not given -> anywhere on map
  666. map->grailRadius = map->width * 2;
  667. std::vector<int3> allowedPos;
  668. static const int BORDER_WIDTH = 9; // grail must be at least 9 tiles away from border
  669. // add all not blocked tiles in range
  670. for (int z = 0; z < map->levels(); z++)
  671. {
  672. for(int x = BORDER_WIDTH; x < map->width - BORDER_WIDTH ; x++)
  673. {
  674. for(int y = BORDER_WIDTH; y < map->height - BORDER_WIDTH; y++)
  675. {
  676. const TerrainTile &t = map->getTile(int3(x, y, z));
  677. if(!t.blocked
  678. && !t.visitable
  679. && t.terType->isLand()
  680. && t.terType->isPassable()
  681. && (int)map->grailPos.dist2dSQ(int3(x, y, z)) <= (map->grailRadius * map->grailRadius))
  682. allowedPos.emplace_back(x, y, z);
  683. }
  684. }
  685. }
  686. //remove tiles with holes
  687. for(auto & elem : map->objects)
  688. if(elem && elem->ID == Obj::HOLE)
  689. allowedPos -= elem->pos;
  690. if(!allowedPos.empty())
  691. {
  692. map->grailPos = *RandomGeneratorUtil::nextItem(allowedPos, getRandomGenerator());
  693. }
  694. else
  695. {
  696. logGlobal->warn("Grail cannot be placed, no appropriate tile found!");
  697. }
  698. }
  699. }
  700. void CGameState::initRandomFactionsForPlayers()
  701. {
  702. logGlobal->debug("\tPicking random factions for players");
  703. for(auto & elem : scenarioOps->playerInfos)
  704. {
  705. if(elem.second.castle==-1)
  706. {
  707. auto randomID = getRandomGenerator().nextInt((int)map->players[elem.first.getNum()].allowedFactions.size() - 1);
  708. auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
  709. std::advance(iter, randomID);
  710. elem.second.castle = *iter;
  711. }
  712. }
  713. }
  714. void CGameState::randomizeMapObjects()
  715. {
  716. logGlobal->debug("\tRandomizing objects");
  717. for(CGObjectInstance *obj : map->objects)
  718. {
  719. if(!obj) continue;
  720. randomizeObject(obj);
  721. //handle Favouring Winds - mark tiles under it
  722. if(obj->ID == Obj::FAVORABLE_WINDS)
  723. {
  724. for (int i = 0; i < obj->getWidth() ; i++)
  725. {
  726. for (int j = 0; j < obj->getHeight() ; j++)
  727. {
  728. int3 pos = obj->pos - int3(i,j,0);
  729. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  730. }
  731. }
  732. }
  733. }
  734. }
  735. void CGameState::initPlayerStates()
  736. {
  737. logGlobal->debug("\tCreating player entries in gs");
  738. for(auto & elem : scenarioOps->playerInfos)
  739. {
  740. PlayerState & p = players[elem.first];
  741. p.color=elem.first;
  742. p.human = elem.second.isControlledByHuman();
  743. p.team = map->players[elem.first.getNum()].team;
  744. teams[p.team].id = p.team;//init team
  745. teams[p.team].players.insert(elem.first);//add player to team
  746. }
  747. }
  748. void CGameState::placeCampaignHeroes()
  749. {
  750. if (scenarioOps->campState)
  751. {
  752. // place bonus hero
  753. auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap();
  754. bool campaignGiveHero = campaignBonus && campaignBonus->type == CScenarioTravel::STravelBonus::HERO;
  755. if(campaignGiveHero)
  756. {
  757. auto playerColor = PlayerColor(campaignBonus->info1);
  758. auto it = scenarioOps->playerInfos.find(playerColor);
  759. if(it != scenarioOps->playerInfos.end())
  760. {
  761. auto heroTypeId = campaignBonus->info2;
  762. if(heroTypeId == 0xffff) // random bonus hero
  763. {
  764. heroTypeId = pickUnusedHeroTypeRandomly(playerColor);
  765. }
  766. placeStartingHero(playerColor, HeroTypeID(heroTypeId), map->players[playerColor.getNum()].posOfMainTown);
  767. }
  768. }
  769. // replace heroes placeholders
  770. auto crossoverHeroes = getCrossoverHeroesFromPreviousScenarios();
  771. if(!crossoverHeroes.heroesFromAnyPreviousScenarios.empty())
  772. {
  773. logGlobal->debug("\tGenerate list of hero placeholders");
  774. auto campaignHeroReplacements = generateCampaignHeroesToReplace(crossoverHeroes);
  775. logGlobal->debug("\tPrepare crossover heroes");
  776. prepareCrossoverHeroes(campaignHeroReplacements, scenarioOps->campState->getCurrentScenario().travelOptions);
  777. // remove same heroes on the map which will be added through crossover heroes
  778. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  779. // with the same hero type id
  780. std::vector<CGHeroInstance *> removedHeroes;
  781. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  782. {
  783. auto * hero = getUsedHero(HeroTypeID(campaignHeroReplacement.hero->subID));
  784. if(hero)
  785. {
  786. removedHeroes.push_back(hero);
  787. map->heroesOnMap -= hero;
  788. map->objects[hero->id.getNum()] = nullptr;
  789. map->removeBlockVisTiles(hero, true);
  790. }
  791. }
  792. logGlobal->debug("\tReplace placeholders with heroes");
  793. replaceHeroesPlaceholders(campaignHeroReplacements);
  794. // now add removed heroes again with unused type ID
  795. for(auto * hero : removedHeroes)
  796. {
  797. si32 heroTypeId = 0;
  798. if(hero->ID == Obj::HERO)
  799. {
  800. heroTypeId = pickUnusedHeroTypeRandomly(hero->tempOwner);
  801. }
  802. else if(hero->ID == Obj::PRISON)
  803. {
  804. auto unusedHeroTypeIds = getUnusedAllowedHeroes();
  805. if(!unusedHeroTypeIds.empty())
  806. {
  807. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, getRandomGenerator())).getNum();
  808. }
  809. else
  810. {
  811. logGlobal->error("No free hero type ID found to replace prison.");
  812. assert(0);
  813. }
  814. }
  815. else
  816. {
  817. assert(0); // should not happen
  818. }
  819. hero->subID = heroTypeId;
  820. hero->portrait = hero->subID;
  821. map->getEditManager()->insertObject(hero);
  822. }
  823. }
  824. }
  825. // remove hero placeholders on map
  826. for(auto obj : map->objects)
  827. {
  828. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  829. {
  830. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  831. map->removeBlockVisTiles(heroPlaceholder, true);
  832. map->instanceNames.erase(obj->instanceName);
  833. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  834. delete heroPlaceholder;
  835. }
  836. }
  837. }
  838. void CGameState::placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos)
  839. {
  840. for(auto town : map->towns)
  841. {
  842. if(town->getPosition() == townPos)
  843. {
  844. townPos = town->visitablePos();
  845. break;
  846. }
  847. }
  848. CGObjectInstance * hero = createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor);
  849. hero->pos += hero->getVisitableOffset();
  850. map->getEditManager()->insertObject(hero);
  851. }
  852. CGameState::CrossoverHeroesList CGameState::getCrossoverHeroesFromPreviousScenarios() const
  853. {
  854. CrossoverHeroesList crossoverHeroes;
  855. auto campaignState = scenarioOps->campState;
  856. auto bonus = campaignState->getBonusForCurrentMap();
  857. if(bonus && bonus->type == CScenarioTravel::STravelBonus::HEROES_FROM_PREVIOUS_SCENARIO)
  858. {
  859. std::vector<CGHeroInstance *> heroes;
  860. for(auto & node : campaignState->camp->scenarios[bonus->info2].crossoverHeroes)
  861. {
  862. auto * h = CCampaignState::crossoverDeserialize(node);
  863. heroes.push_back(h);
  864. }
  865. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = heroes;
  866. }
  867. else
  868. {
  869. if(!campaignState->mapsConquered.empty())
  870. {
  871. std::vector<CGHeroInstance *> heroes = {};
  872. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = heroes;
  873. crossoverHeroes.heroesFromPreviousScenario = heroes;
  874. for(auto mapNr : campaignState->mapsConquered)
  875. {
  876. // create a list of deleted heroes
  877. auto & scenario = campaignState->camp->scenarios[mapNr];
  878. auto lostCrossoverHeroes = scenario.getLostCrossoverHeroes();
  879. // remove heroes which didn't reached the end of the scenario, but were available at the start
  880. for(auto * hero : lostCrossoverHeroes)
  881. {
  882. // auto hero = CCampaignState::crossoverDeserialize(node);
  883. vstd::erase_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [hero](CGHeroInstance * h)
  884. {
  885. return hero->subID == h->subID;
  886. });
  887. }
  888. // now add heroes which completed the scenario
  889. for(auto node : scenario.crossoverHeroes)
  890. {
  891. auto * hero = CCampaignState::crossoverDeserialize(node);
  892. // add new heroes and replace old heroes with newer ones
  893. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [hero](CGHeroInstance * h)
  894. {
  895. return hero->subID == h->subID;
  896. });
  897. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  898. {
  899. // replace old hero with newer one
  900. crossoverHeroes.heroesFromAnyPreviousScenarios[it - crossoverHeroes.heroesFromAnyPreviousScenarios.begin()] = hero;
  901. }
  902. else
  903. {
  904. // add new hero
  905. crossoverHeroes.heroesFromAnyPreviousScenarios.push_back(hero);
  906. }
  907. if(mapNr == campaignState->mapsConquered.back())
  908. {
  909. crossoverHeroes.heroesFromPreviousScenario.push_back(hero);
  910. }
  911. }
  912. }
  913. }
  914. }
  915. return crossoverHeroes;
  916. }
  917. void CGameState::prepareCrossoverHeroes(std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions)
  918. {
  919. // create heroes list for convenience iterating
  920. std::vector<CGHeroInstance *> crossoverHeroes;
  921. crossoverHeroes.reserve(campaignHeroReplacements.size());
  922. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  923. {
  924. crossoverHeroes.push_back(campaignHeroReplacement.hero);
  925. }
  926. // TODO replace magic numbers with named constants
  927. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  928. if(!travelOptions.whatHeroKeeps.experience)
  929. {
  930. //trimming experience
  931. for(CGHeroInstance * cgh : crossoverHeroes)
  932. {
  933. cgh->initExp(getRandomGenerator());
  934. }
  935. }
  936. if(!travelOptions.whatHeroKeeps.primarySkills)
  937. {
  938. //trimming prim skills
  939. for(CGHeroInstance * cgh : crossoverHeroes)
  940. {
  941. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  942. {
  943. auto sel = Selector::type()(BonusType::PRIMARY_SKILL)
  944. .And(Selector::subtype()(g))
  945. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  946. cgh->getBonusLocalFirst(sel)->val = cgh->type->heroClass->primarySkillInitial[g];
  947. }
  948. }
  949. }
  950. if(!travelOptions.whatHeroKeeps.secondarySkills)
  951. {
  952. //trimming sec skills
  953. for(CGHeroInstance * cgh : crossoverHeroes)
  954. {
  955. cgh->secSkills = cgh->type->secSkillsInit;
  956. cgh->recreateSecondarySkillsBonuses();
  957. }
  958. }
  959. if(!travelOptions.whatHeroKeeps.spells)
  960. {
  961. for(CGHeroInstance * cgh : crossoverHeroes)
  962. {
  963. cgh->removeSpellbook();
  964. }
  965. }
  966. if(!travelOptions.whatHeroKeeps.artifacts)
  967. {
  968. //trimming artifacts
  969. for(CGHeroInstance * hero : crossoverHeroes)
  970. {
  971. size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
  972. for (size_t i = 0; i < totalArts; i++ )
  973. {
  974. auto artifactPosition = ArtifactPosition((si32)i);
  975. if(artifactPosition == ArtifactPosition::SPELLBOOK) continue; // do not handle spellbook this way
  976. const ArtSlotInfo *info = hero->getSlot(artifactPosition);
  977. if(!info)
  978. continue;
  979. // TODO: why would there be nullptr artifacts?
  980. const CArtifactInstance *art = info->artifact;
  981. if(!art)
  982. continue;
  983. bool takeable = travelOptions.artifactsKeptByHero.count(art->artType->getId());
  984. ArtifactLocation al(hero, artifactPosition);
  985. if(!takeable && !al.getSlot()->locked) //don't try removing locked artifacts -> it crashes #1719
  986. al.removeArtifact();
  987. }
  988. }
  989. }
  990. //trimming creatures
  991. for(CGHeroInstance * cgh : crossoverHeroes)
  992. {
  993. auto shouldSlotBeErased = [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  994. {
  995. CreatureID::ECreatureID crid = j.second->getCreatureID().toEnum();
  996. return !travelOptions.monstersKeptByHero.count(crid);
  997. };
  998. auto stacksCopy = cgh->stacks; //copy of the map, so we can iterate iover it and remove stacks
  999. for(auto &slotPair : stacksCopy)
  1000. if(shouldSlotBeErased(slotPair))
  1001. cgh->eraseStack(slotPair.first);
  1002. }
  1003. // Removing short-term bonuses
  1004. for(CGHeroInstance * cgh : crossoverHeroes)
  1005. {
  1006. cgh->removeBonusesRecursive(CSelector(Bonus::OneDay)
  1007. .Or(CSelector(Bonus::OneWeek))
  1008. .Or(CSelector(Bonus::NTurns))
  1009. .Or(CSelector(Bonus::NDays))
  1010. .Or(CSelector(Bonus::OneBattle)));
  1011. }
  1012. }
  1013. void CGameState::placeStartingHeroes()
  1014. {
  1015. logGlobal->debug("\tGiving starting hero");
  1016. for(auto & playerSettingPair : scenarioOps->playerInfos)
  1017. {
  1018. auto playerColor = playerSettingPair.first;
  1019. auto & playerInfo = map->players[playerColor.getNum()];
  1020. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  1021. {
  1022. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  1023. if(scenarioOps->campState)
  1024. {
  1025. if(auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap())
  1026. {
  1027. if(campaignBonus->type == CScenarioTravel::STravelBonus::HERO && playerColor == PlayerColor(campaignBonus->info1))
  1028. continue;
  1029. }
  1030. }
  1031. int heroTypeId = pickNextHeroType(playerColor);
  1032. if(playerSettingPair.second.hero == -1)
  1033. playerSettingPair.second.hero = heroTypeId;
  1034. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  1035. }
  1036. }
  1037. }
  1038. void CGameState::initStartingResources()
  1039. {
  1040. logGlobal->debug("\tSetting up resources");
  1041. const JsonNode config(ResourceID("config/startres.json"));
  1042. const JsonVector &vector = config["difficulty"].Vector();
  1043. const JsonNode &level = vector[scenarioOps->difficulty];
  1044. TResources startresAI(level["ai"]);
  1045. TResources startresHuman(level["human"]);
  1046. for (auto & elem : players)
  1047. {
  1048. PlayerState &p = elem.second;
  1049. if (p.human)
  1050. p.resources = startresHuman;
  1051. else
  1052. p.resources = startresAI;
  1053. }
  1054. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  1055. {
  1056. std::vector<const PlayerSettings *> ret;
  1057. for(const auto & playerInfo : scenarioOps->playerInfos)
  1058. {
  1059. if(playerInfo.second.isControlledByHuman())
  1060. ret.push_back(&playerInfo.second);
  1061. }
  1062. return ret;
  1063. };
  1064. //give start resource bonus in case of campaign
  1065. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1066. {
  1067. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1068. if(chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1069. {
  1070. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1071. for(const PlayerSettings *ps : people)
  1072. {
  1073. std::vector<int> res; //resources we will give
  1074. switch (chosenBonus->info1)
  1075. {
  1076. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1077. res.push_back(chosenBonus->info1);
  1078. break;
  1079. case 0xFD: //wood+ore
  1080. res.push_back(GameResID(EGameResID::WOOD));
  1081. res.push_back(GameResID(EGameResID::ORE));
  1082. break;
  1083. case 0xFE: //rare
  1084. res.push_back(GameResID(EGameResID::MERCURY));
  1085. res.push_back(GameResID(EGameResID::SULFUR));
  1086. res.push_back(GameResID(EGameResID::CRYSTAL));
  1087. res.push_back(GameResID(EGameResID::GEMS));
  1088. break;
  1089. default:
  1090. assert(0);
  1091. break;
  1092. }
  1093. //increasing resource quantity
  1094. for (auto & re : res)
  1095. {
  1096. players[ps->color].resources[re] += chosenBonus->info2;
  1097. }
  1098. }
  1099. }
  1100. }
  1101. }
  1102. void CGameState::initHeroes()
  1103. {
  1104. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1105. {
  1106. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  1107. {
  1108. logGlobal->warn("Hero with uninitialized owner!");
  1109. continue;
  1110. }
  1111. hero->initHero(getRandomGenerator());
  1112. getPlayerState(hero->getOwner())->heroes.push_back(hero);
  1113. map->allHeroes[hero->type->getIndex()] = hero;
  1114. }
  1115. // generate boats for all heroes on water
  1116. for(auto hero : map->heroesOnMap)
  1117. {
  1118. assert(map->isInTheMap(hero->visitablePos()));
  1119. const auto & tile = map->getTile(hero->visitablePos());
  1120. if (tile.terType->isWater())
  1121. {
  1122. auto handler = VLC->objtypeh->getHandlerFor(Obj::BOAT, hero->getBoatType().getNum());
  1123. CGBoat * boat = dynamic_cast<CGBoat*>(handler->create());
  1124. handler->configureObject(boat, gs->getRandomGenerator());
  1125. boat->ID = Obj::BOAT;
  1126. boat->subID = hero->getBoatType().getNum();
  1127. boat->pos = hero->pos;
  1128. boat->appearance = handler->getTemplates().front();
  1129. boat->id = ObjectInstanceID(static_cast<si32>(gs->map->objects.size()));
  1130. map->objects.emplace_back(boat);
  1131. map->addBlockVisTiles(boat);
  1132. boat->hero = hero;
  1133. hero->boat = boat;
  1134. }
  1135. }
  1136. for(auto obj : map->objects) //prisons
  1137. {
  1138. if(obj && obj->ID == Obj::PRISON)
  1139. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  1140. }
  1141. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  1142. for(auto ph : map->predefinedHeroes)
  1143. {
  1144. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  1145. continue;
  1146. ph->initHero(getRandomGenerator());
  1147. hpool.heroesPool[ph->subID] = ph;
  1148. hpool.pavailable[ph->subID] = 0xff;
  1149. heroesToCreate.erase(ph->type->getId());
  1150. map->allHeroes[ph->subID] = ph;
  1151. }
  1152. for(const HeroTypeID & htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  1153. {
  1154. auto * vhi = new CGHeroInstance();
  1155. vhi->initHero(getRandomGenerator(), htype);
  1156. int typeID = htype.getNum();
  1157. map->allHeroes[typeID] = vhi;
  1158. hpool.heroesPool[typeID] = vhi;
  1159. hpool.pavailable[typeID] = 0xff;
  1160. }
  1161. for(auto & elem : map->disposedHeroes)
  1162. {
  1163. hpool.pavailable[elem.heroId] = elem.players;
  1164. }
  1165. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1166. {
  1167. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1168. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1169. {
  1170. //find human player
  1171. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  1172. for (auto & elem : players)
  1173. {
  1174. if(elem.second.human)
  1175. {
  1176. humanPlayer = elem.first;
  1177. break;
  1178. }
  1179. }
  1180. assert(humanPlayer != PlayerColor::NEUTRAL);
  1181. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1182. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1183. {
  1184. int maxB = -1;
  1185. for (int b=0; b<heroes.size(); ++b)
  1186. {
  1187. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1188. {
  1189. maxB = b;
  1190. }
  1191. }
  1192. if(maxB < 0)
  1193. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  1194. else
  1195. giveCampaignBonusToHero(heroes[maxB]);
  1196. }
  1197. else //specific hero
  1198. {
  1199. for (auto & heroe : heroes)
  1200. {
  1201. if (heroe->subID == chosenBonus->info1)
  1202. {
  1203. giveCampaignBonusToHero(heroe);
  1204. break;
  1205. }
  1206. }
  1207. }
  1208. }
  1209. }
  1210. }
  1211. void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero)
  1212. {
  1213. const std::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap();
  1214. if(!curBonus)
  1215. return;
  1216. if(curBonus->isBonusForHero())
  1217. {
  1218. //apply bonus
  1219. switch (curBonus->type)
  1220. {
  1221. case CScenarioTravel::STravelBonus::SPELL:
  1222. hero->addSpellToSpellbook(SpellID(curBonus->info2));
  1223. break;
  1224. case CScenarioTravel::STravelBonus::MONSTER:
  1225. {
  1226. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  1227. {
  1228. if(hero->slotEmpty(SlotID(i)))
  1229. {
  1230. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  1231. break;
  1232. }
  1233. }
  1234. }
  1235. break;
  1236. case CScenarioTravel::STravelBonus::ARTIFACT:
  1237. if(!gs->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2)))
  1238. logGlobal->error("Cannot give starting artifact - no free slots!");
  1239. break;
  1240. case CScenarioTravel::STravelBonus::SPELL_SCROLL:
  1241. {
  1242. CArtifactInstance * scroll = ArtifactUtils::createScroll(SpellID(curBonus->info2));
  1243. const auto slot = ArtifactUtils::getArtAnyPosition(hero, scroll->getTypeId());
  1244. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1245. scroll->putAt(ArtifactLocation(hero, slot));
  1246. else
  1247. logGlobal->error("Cannot give starting scroll - no free slots!");
  1248. }
  1249. break;
  1250. case CScenarioTravel::STravelBonus::PRIMARY_SKILL:
  1251. {
  1252. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus->info2);
  1253. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1254. {
  1255. int val = ptr[g];
  1256. if (val == 0)
  1257. {
  1258. continue;
  1259. }
  1260. auto bb = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::CAMPAIGN_BONUS, val, *scenarioOps->campState->currentMap, g);
  1261. hero->addNewBonus(bb);
  1262. }
  1263. }
  1264. break;
  1265. case CScenarioTravel::STravelBonus::SECONDARY_SKILL:
  1266. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  1267. break;
  1268. }
  1269. }
  1270. }
  1271. void CGameState::initFogOfWar()
  1272. {
  1273. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  1274. int layers = map->levels();
  1275. for(auto & elem : teams)
  1276. {
  1277. auto fow = elem.second.fogOfWarMap;
  1278. fow->resize(boost::extents[layers][map->width][map->height]);
  1279. std::fill(fow->data(), fow->data() + fow->num_elements(), 0);
  1280. for(CGObjectInstance *obj : map->objects)
  1281. {
  1282. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  1283. std::unordered_set<int3> tiles;
  1284. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius(), obj->tempOwner, 1);
  1285. for(const int3 & tile : tiles)
  1286. {
  1287. (*elem.second.fogOfWarMap)[tile.z][tile.x][tile.y] = 1;
  1288. }
  1289. }
  1290. }
  1291. }
  1292. void CGameState::initStartingBonus()
  1293. {
  1294. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1295. return;
  1296. // These are the single scenario bonuses; predefined
  1297. // campaign bonuses are spread out over other init* functions.
  1298. logGlobal->debug("\tStarting bonuses");
  1299. for(auto & elem : players)
  1300. {
  1301. //starting bonus
  1302. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  1303. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(getRandomGenerator().nextInt(2));
  1304. switch(scenarioOps->playerInfos[elem.first].bonus)
  1305. {
  1306. case PlayerSettings::GOLD:
  1307. elem.second.resources[EGameResID::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  1308. break;
  1309. case PlayerSettings::RESOURCE:
  1310. {
  1311. auto res = (*VLC->townh)[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  1312. if(res == EGameResID::WOOD_AND_ORE)
  1313. {
  1314. int amount = getRandomGenerator().nextInt(5, 10);
  1315. elem.second.resources[EGameResID::WOOD] += amount;
  1316. elem.second.resources[EGameResID::ORE] += amount;
  1317. }
  1318. else
  1319. {
  1320. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  1321. }
  1322. break;
  1323. }
  1324. case PlayerSettings::ARTIFACT:
  1325. {
  1326. if(elem.second.heroes.empty())
  1327. {
  1328. logGlobal->error("Cannot give starting artifact - no heroes!");
  1329. break;
  1330. }
  1331. const Artifact * toGive = VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE).toArtifact(VLC->artifacts());
  1332. CGHeroInstance *hero = elem.second.heroes[0];
  1333. if(!giveHeroArtifact(hero, toGive->getId()))
  1334. logGlobal->error("Cannot give starting artifact - no free slots!");
  1335. }
  1336. break;
  1337. }
  1338. }
  1339. }
  1340. void CGameState::initTowns()
  1341. {
  1342. logGlobal->debug("\tTowns");
  1343. //campaign bonuses for towns
  1344. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1345. {
  1346. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1347. if (chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1348. {
  1349. for (int g=0; g<map->towns.size(); ++g)
  1350. {
  1351. PlayerState * owner = getPlayerState(map->towns[g]->getOwner());
  1352. if (owner)
  1353. {
  1354. PlayerInfo & pi = map->players[owner->color.getNum()];
  1355. if (owner->human && //human-owned
  1356. map->towns[g]->pos == pi.posOfMainTown)
  1357. {
  1358. BuildingID buildingId;
  1359. if(scenarioOps->campState->camp->header.version == CampaignVersion::VCMI)
  1360. buildingId = BuildingID(chosenBonus->info1);
  1361. else
  1362. buildingId = CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->subID, map->towns[g]->builtBuildings);
  1363. map->towns[g]->builtBuildings.insert(buildingId);
  1364. break;
  1365. }
  1366. }
  1367. }
  1368. }
  1369. }
  1370. CGTownInstance::universitySkills.clear();
  1371. for ( int i=0; i<4; i++)
  1372. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1373. for (auto & elem : map->towns)
  1374. {
  1375. CGTownInstance * vti =(elem);
  1376. if(!vti->town)
  1377. {
  1378. vti->town = (*VLC->townh)[vti->subID]->town;
  1379. }
  1380. if(vti->getNameTranslated().empty())
  1381. {
  1382. size_t nameID = getRandomGenerator().nextInt(vti->getTown()->getRandomNamesCount() - 1);
  1383. vti->setNameTranslated(vti->getTown()->getRandomNameTranslated(nameID));
  1384. }
  1385. 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 };
  1386. 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 };
  1387. 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 };
  1388. //init buildings
  1389. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  1390. {
  1391. vti->builtBuildings.erase(BuildingID::DEFAULT);
  1392. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1393. if(vti->tempOwner != PlayerColor::NEUTRAL)
  1394. vti->builtBuildings.insert(BuildingID::TAVERN);
  1395. auto definesBuildingsChances = VLC->settings()->getVector(EGameSettings::TOWNS_STARTING_DWELLING_CHANCES);
  1396. for(int i = 0; i < definesBuildingsChances.size(); i++)
  1397. {
  1398. if((getRandomGenerator().nextInt(1,100) <= definesBuildingsChances[i]))
  1399. {
  1400. vti->builtBuildings.insert(basicDwellings[i]);
  1401. }
  1402. }
  1403. }
  1404. // village hall must always exist
  1405. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1406. //init hordes
  1407. for (int i = 0; i < GameConstants::CREATURES_PER_TOWN; i++)
  1408. {
  1409. if (vstd::contains(vti->builtBuildings, hordes[i])) //if we have horde for this level
  1410. {
  1411. vti->builtBuildings.erase(hordes[i]);//remove old ID
  1412. if (vti->getTown()->hordeLvl.at(0) == i)//if town first horde is this one
  1413. {
  1414. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  1415. //if we have upgraded dwelling as well
  1416. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  1417. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  1418. }
  1419. if (vti->getTown()->hordeLvl.at(1) == i)//if town second horde is this one
  1420. {
  1421. vti->builtBuildings.insert(BuildingID::HORDE_2);
  1422. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  1423. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  1424. }
  1425. }
  1426. }
  1427. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  1428. //But DO NOT remove horde placeholders before they are replaced
  1429. vstd::erase_if(vti->builtBuildings, [vti](const BuildingID & bid)
  1430. {
  1431. return !vti->getTown()->buildings.count(bid) || !vti->getTown()->buildings.at(bid);
  1432. });
  1433. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  1434. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1435. //Early check for #1444-like problems
  1436. for([[maybe_unused]] const auto & building : vti->builtBuildings)
  1437. {
  1438. assert(vti->getTown()->buildings.at(building) != nullptr);
  1439. }
  1440. //town events
  1441. for(CCastleEvent &ev : vti->events)
  1442. {
  1443. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1444. if (vstd::contains(ev.buildings,hordes[i])) //if we have horde for this level
  1445. {
  1446. ev.buildings.erase(hordes[i]);
  1447. if (vti->getTown()->hordeLvl.at(0) == i)
  1448. ev.buildings.insert(BuildingID::HORDE_1);
  1449. if (vti->getTown()->hordeLvl.at(1) == i)
  1450. ev.buildings.insert(BuildingID::HORDE_2);
  1451. }
  1452. }
  1453. //init spells
  1454. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1455. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1456. {
  1457. const auto * s = vti->obligatorySpells[z].toSpell();
  1458. vti->spells[s->level-1].push_back(s->id);
  1459. vti->possibleSpells -= s->id;
  1460. }
  1461. while(!vti->possibleSpells.empty())
  1462. {
  1463. ui32 total=0;
  1464. int sel = -1;
  1465. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1466. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  1467. if (total == 0) // remaining spells have 0 probability
  1468. break;
  1469. auto r = getRandomGenerator().nextInt(total - 1);
  1470. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1471. {
  1472. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  1473. if(r<0)
  1474. {
  1475. sel = ps;
  1476. break;
  1477. }
  1478. }
  1479. if(sel<0)
  1480. sel=0;
  1481. const auto * s = vti->possibleSpells[sel].toSpell();
  1482. vti->spells[s->level-1].push_back(s->id);
  1483. vti->possibleSpells -= s->id;
  1484. }
  1485. vti->possibleSpells.clear();
  1486. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1487. getPlayerState(vti->getOwner())->towns.emplace_back(vti);
  1488. }
  1489. }
  1490. void CGameState::initMapObjects()
  1491. {
  1492. logGlobal->debug("\tObject initialization");
  1493. // objCaller->preInit();
  1494. for(CGObjectInstance *obj : map->objects)
  1495. {
  1496. if(obj)
  1497. {
  1498. logGlobal->trace("Calling Init for object %d, %s, %s", obj->id.getNum(), obj->typeName, obj->subTypeName);
  1499. obj->initObj(getRandomGenerator());
  1500. }
  1501. }
  1502. for(CGObjectInstance *obj : map->objects)
  1503. {
  1504. if(!obj)
  1505. continue;
  1506. switch (obj->ID)
  1507. {
  1508. case Obj::QUEST_GUARD:
  1509. case Obj::SEER_HUT:
  1510. {
  1511. auto * q = dynamic_cast<CGSeerHut *>(obj);
  1512. assert (q);
  1513. q->setObjToKill();
  1514. }
  1515. }
  1516. }
  1517. CGSubterraneanGate::postInit(); //pairing subterranean gates
  1518. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  1519. }
  1520. void CGameState::placeHeroesInTowns()
  1521. {
  1522. for(auto & player : players)
  1523. {
  1524. if(player.first == PlayerColor::NEUTRAL)
  1525. continue;
  1526. for(CGHeroInstance * h : player.second.heroes)
  1527. {
  1528. for(CGTownInstance * t : player.second.towns)
  1529. {
  1530. if(h->visitablePos().z != t->visitablePos().z)
  1531. continue;
  1532. bool heroOnTownBlockableTile = t->blockingAt(h->visitablePos().x, h->visitablePos().y);
  1533. // current hero position is at one of blocking tiles of current town
  1534. // assume that this hero should be visiting the town (H3M format quirk) and move hero to correct position
  1535. if (heroOnTownBlockableTile)
  1536. {
  1537. int3 correctedPos = h->convertFromVisitablePos(t->visitablePos());
  1538. map->removeBlockVisTiles(h);
  1539. h->pos = correctedPos;
  1540. map->addBlockVisTiles(h);
  1541. assert(t->visitableAt(h->visitablePos().x, h->visitablePos().y));
  1542. }
  1543. }
  1544. }
  1545. }
  1546. }
  1547. void CGameState::initVisitingAndGarrisonedHeroes()
  1548. {
  1549. for(auto & player : players)
  1550. {
  1551. if(player.first == PlayerColor::NEUTRAL)
  1552. continue;
  1553. //init visiting and garrisoned heroes
  1554. for(CGHeroInstance * h : player.second.heroes)
  1555. {
  1556. for(CGTownInstance * t : player.second.towns)
  1557. {
  1558. if(h->visitablePos().z != t->visitablePos().z)
  1559. continue;
  1560. if (t->visitableAt(h->visitablePos().x, h->visitablePos().y))
  1561. {
  1562. assert(t->visitingHero == nullptr);
  1563. t->setVisitingHero(h);
  1564. }
  1565. }
  1566. }
  1567. }
  1568. for (auto hero : map->heroesOnMap)
  1569. {
  1570. if (hero->visitedTown)
  1571. {
  1572. assert (hero->visitedTown->visitingHero == hero);
  1573. }
  1574. }
  1575. }
  1576. BattleField CGameState::battleGetBattlefieldType(int3 tile, CRandomGenerator & rand)
  1577. {
  1578. if(!tile.valid() && curB)
  1579. tile = curB->tile;
  1580. else if(!tile.valid() && !curB)
  1581. return BattleField::NONE;
  1582. const TerrainTile &t = map->getTile(tile);
  1583. auto * topObject = t.visitableObjects.front();
  1584. if(topObject && topObject->getBattlefield() != BattleField::NONE)
  1585. {
  1586. return topObject->getBattlefield();
  1587. }
  1588. for(auto &obj : map->objects)
  1589. {
  1590. //look only for objects covering given tile
  1591. if( !obj || obj->pos.z != tile.z || !obj->coveringAt(tile.x, tile.y))
  1592. continue;
  1593. auto customBattlefield = obj->getBattlefield();
  1594. if(customBattlefield != BattleField::NONE)
  1595. return customBattlefield;
  1596. }
  1597. if(map->isCoastalTile(tile)) //coastal tile is always ground
  1598. return BattleField::fromString("sand_shore");
  1599. return BattleField(*RandomGeneratorUtil::nextItem(t.terType->battleFields, rand));
  1600. }
  1601. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  1602. {
  1603. assert(obj);
  1604. assert(obj->hasStackAtSlot(stackPos));
  1605. out = fillUpgradeInfo(obj->getStack(stackPos));
  1606. }
  1607. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance &stack) const
  1608. {
  1609. UpgradeInfo ret;
  1610. const CCreature *base = stack.type;
  1611. if (stack.armyObj->ID == Obj::HERO)
  1612. {
  1613. auto hero = dynamic_cast<const CGHeroInstance *>(stack.armyObj);
  1614. hero->fillUpgradeInfo(ret, stack);
  1615. if (hero->visitedTown)
  1616. {
  1617. hero->visitedTown->fillUpgradeInfo(ret, stack);
  1618. }
  1619. else
  1620. {
  1621. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  1622. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  1623. if (object != hero && upgradeSource != nullptr)
  1624. upgradeSource->fillUpgradeInfo(ret, stack);
  1625. }
  1626. }
  1627. if (stack.armyObj->ID == Obj::TOWN)
  1628. {
  1629. auto town = dynamic_cast<const CGTownInstance *>(stack.armyObj);
  1630. town->fillUpgradeInfo(ret, stack);
  1631. }
  1632. if(!ret.newID.empty())
  1633. ret.oldID = base->getId();
  1634. for (ResourceSet &cost : ret.cost)
  1635. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1636. return ret;
  1637. }
  1638. PlayerRelations::PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  1639. {
  1640. if ( color1 == color2 )
  1641. return PlayerRelations::SAME_PLAYER;
  1642. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1643. return PlayerRelations::ENEMIES;
  1644. const TeamState * ts = getPlayerTeam(color1);
  1645. if (ts && vstd::contains(ts->players, color2))
  1646. return PlayerRelations::ALLIES;
  1647. return PlayerRelations::ENEMIES;
  1648. }
  1649. void CGameState::apply(CPack *pack)
  1650. {
  1651. ui16 typ = typeList.getTypeID(pack);
  1652. applier->getApplier(typ)->applyOnGS(this, pack);
  1653. }
  1654. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  1655. {
  1656. calculatePaths(std::make_shared<SingleHeroPathfinderConfig>(out, this, hero));
  1657. }
  1658. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config)
  1659. {
  1660. //FIXME: creating pathfinder is costly, maybe reset / clear is enough?
  1661. CPathfinder pathfinder(this, config);
  1662. pathfinder.calculatePaths();
  1663. }
  1664. /**
  1665. * Tells if the tile is guarded by a monster as well as the position
  1666. * of the monster that will attack on it.
  1667. *
  1668. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1669. * the monster guarding the tile.
  1670. */
  1671. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1672. {
  1673. std::vector<CGObjectInstance*> guards;
  1674. const int3 originalPos = pos;
  1675. if (!map->isInTheMap(pos))
  1676. return guards;
  1677. const TerrainTile &posTile = map->getTile(pos);
  1678. if (posTile.visitable)
  1679. {
  1680. for (CGObjectInstance* obj : posTile.visitableObjects)
  1681. {
  1682. if(obj->isBlockedVisitable())
  1683. {
  1684. if (obj->ID == Obj::MONSTER) // Monster
  1685. guards.push_back(obj);
  1686. }
  1687. }
  1688. }
  1689. pos -= int3(1, 1, 0); // Start with top left.
  1690. for (int dx = 0; dx < 3; dx++)
  1691. {
  1692. for (int dy = 0; dy < 3; dy++)
  1693. {
  1694. if (map->isInTheMap(pos))
  1695. {
  1696. const auto & tile = map->getTile(pos);
  1697. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1698. {
  1699. for (CGObjectInstance* obj : tile.visitableObjects)
  1700. {
  1701. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1702. {
  1703. guards.push_back(obj);
  1704. }
  1705. }
  1706. }
  1707. }
  1708. pos.y++;
  1709. }
  1710. pos.y -= 3;
  1711. pos.x++;
  1712. }
  1713. return guards;
  1714. }
  1715. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1716. {
  1717. return gs->map->guardingCreaturePositions[pos.z][pos.x][pos.y];
  1718. }
  1719. void CGameState::updateRumor()
  1720. {
  1721. static std::vector<RumorState::ERumorType> rumorTypes = {RumorState::TYPE_MAP, RumorState::TYPE_SPECIAL, RumorState::TYPE_RAND, RumorState::TYPE_RAND};
  1722. std::vector<RumorState::ERumorTypeSpecial> sRumorTypes = {
  1723. RumorState::RUMOR_OBELISKS, RumorState::RUMOR_ARTIFACTS, RumorState::RUMOR_ARMY, RumorState::RUMOR_INCOME};
  1724. if(map->grailPos.valid()) // Grail should always be on map, but I had related crash I didn't manage to reproduce
  1725. sRumorTypes.push_back(RumorState::RUMOR_GRAIL);
  1726. int rumorId = -1;
  1727. int rumorExtra = -1;
  1728. auto & rand = getRandomGenerator();
  1729. rumor.type = *RandomGeneratorUtil::nextItem(rumorTypes, rand);
  1730. do
  1731. {
  1732. switch(rumor.type)
  1733. {
  1734. case RumorState::TYPE_SPECIAL:
  1735. {
  1736. SThievesGuildInfo tgi;
  1737. obtainPlayersStats(tgi, 20);
  1738. rumorId = *RandomGeneratorUtil::nextItem(sRumorTypes, rand);
  1739. if(rumorId == RumorState::RUMOR_GRAIL)
  1740. {
  1741. rumorExtra = getTile(map->grailPos)->terType->getIndex();
  1742. break;
  1743. }
  1744. std::vector<PlayerColor> players = {};
  1745. switch(rumorId)
  1746. {
  1747. case RumorState::RUMOR_OBELISKS:
  1748. players = tgi.obelisks[0];
  1749. break;
  1750. case RumorState::RUMOR_ARTIFACTS:
  1751. players = tgi.artifacts[0];
  1752. break;
  1753. case RumorState::RUMOR_ARMY:
  1754. players = tgi.army[0];
  1755. break;
  1756. case RumorState::RUMOR_INCOME:
  1757. players = tgi.income[0];
  1758. break;
  1759. }
  1760. rumorExtra = RandomGeneratorUtil::nextItem(players, rand)->getNum();
  1761. break;
  1762. }
  1763. case RumorState::TYPE_MAP:
  1764. // Makes sure that map rumors only used if there enough rumors too choose from
  1765. if(!map->rumors.empty() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
  1766. {
  1767. rumorId = rand.nextInt((int)map->rumors.size() - 1);
  1768. break;
  1769. }
  1770. else
  1771. rumor.type = RumorState::TYPE_RAND;
  1772. [[fallthrough]];
  1773. case RumorState::TYPE_RAND:
  1774. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randtvrn");
  1775. rumorId = rand.nextInt((int)vector.size() - 1);
  1776. break;
  1777. }
  1778. }
  1779. while(!rumor.update(rumorId, rumorExtra));
  1780. }
  1781. bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
  1782. {
  1783. if (!map->isInTheMap(pos))
  1784. return false;
  1785. if (!player)
  1786. return true;
  1787. if(player == PlayerColor::NEUTRAL)
  1788. return false;
  1789. if(player->isSpectator())
  1790. return true;
  1791. return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y];
  1792. }
  1793. bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
  1794. {
  1795. if(!player)
  1796. return true;
  1797. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1798. if (player == obj->tempOwner)
  1799. return true;
  1800. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1801. return false;
  1802. //object is visible when at least one blocked tile is visible
  1803. for(int fy=0; fy < obj->getHeight(); ++fy)
  1804. {
  1805. for(int fx=0; fx < obj->getWidth(); ++fx)
  1806. {
  1807. int3 pos = obj->pos + int3(-fx, -fy, 0);
  1808. if ( map->isInTheMap(pos) &&
  1809. obj->coveringAt(pos.x, pos.y) &&
  1810. isVisible(pos, *player))
  1811. return true;
  1812. }
  1813. }
  1814. return false;
  1815. }
  1816. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1817. {
  1818. const TerrainTile * pom = &map->getTile(dst);
  1819. return map->checkForVisitableDir(src, pom, dst);
  1820. }
  1821. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  1822. {
  1823. const MetaString messageWonSelf = MetaString::createFromTextID("core.genrltxt.659");
  1824. const MetaString messageWonOther = MetaString::createFromTextID("core.genrltxt.5");
  1825. const MetaString messageLostSelf = MetaString::createFromTextID("core.genrltxt.7");
  1826. const MetaString messageLostOther = MetaString::createFromTextID("core.genrltxt.8");
  1827. auto evaluateEvent = [=](const EventCondition & condition)
  1828. {
  1829. return this->checkForVictory(player, condition);
  1830. };
  1831. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1832. //cheater or tester, but has entered the code...
  1833. if (p->enteredWinningCheatCode)
  1834. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1835. if (p->enteredLosingCheatCode)
  1836. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1837. for (const TriggeredEvent & event : map->triggeredEvents)
  1838. {
  1839. if (event.trigger.test(evaluateEvent))
  1840. {
  1841. if (event.effect.type == EventEffect::VICTORY)
  1842. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1843. if (event.effect.type == EventEffect::DEFEAT)
  1844. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1845. }
  1846. }
  1847. if (checkForStandardLoss(player))
  1848. {
  1849. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1850. }
  1851. return EVictoryLossCheckResult();
  1852. }
  1853. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  1854. {
  1855. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1856. switch (condition.condition)
  1857. {
  1858. case EventCondition::STANDARD_WIN:
  1859. {
  1860. return player == checkForStandardWin();
  1861. }
  1862. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1863. {
  1864. for(const auto & elem : p->heroes)
  1865. if(elem->hasArt(ArtifactID(condition.objectType)))
  1866. return true;
  1867. return false;
  1868. }
  1869. case EventCondition::HAVE_CREATURES:
  1870. {
  1871. //check if in players armies there is enough creatures
  1872. int total = 0; //creature counter
  1873. for(auto object : map->objects)
  1874. {
  1875. const CArmedInstance *ai = nullptr;
  1876. if(object
  1877. && object->tempOwner == player //object controlled by player
  1878. && (ai = dynamic_cast<const CArmedInstance *>(object.get()))) //contains army
  1879. {
  1880. for(const auto & elem : ai->Slots()) //iterate through army
  1881. if(elem.second->type->getId() == condition.objectType) //it's searched creature
  1882. total += elem.second->count;
  1883. }
  1884. }
  1885. return total >= condition.value;
  1886. }
  1887. case EventCondition::HAVE_RESOURCES:
  1888. {
  1889. return p->resources[condition.objectType] >= condition.value;
  1890. }
  1891. case EventCondition::HAVE_BUILDING:
  1892. {
  1893. if (condition.object) // specific town
  1894. {
  1895. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1896. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  1897. }
  1898. else // any town
  1899. {
  1900. for (const CGTownInstance * t : p->towns)
  1901. {
  1902. if (t->hasBuilt(BuildingID(condition.objectType)))
  1903. return true;
  1904. }
  1905. return false;
  1906. }
  1907. }
  1908. case EventCondition::DESTROY:
  1909. {
  1910. if (condition.object) // mode A - destroy specific object of this type
  1911. {
  1912. if(const auto * hero = dynamic_cast<const CGHeroInstance *>(condition.object))
  1913. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  1914. else
  1915. return getObj(condition.object->id) == nullptr;
  1916. }
  1917. else
  1918. {
  1919. for(const auto & elem : map->objects) // mode B - destroy all objects of this type
  1920. {
  1921. if(elem && elem->ID == condition.objectType)
  1922. return false;
  1923. }
  1924. return true;
  1925. }
  1926. }
  1927. case EventCondition::CONTROL:
  1928. {
  1929. // list of players that need to control object to fulfull condition
  1930. // NOTE: cgameinfocallback specified explicitly in order to get const version
  1931. const auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  1932. if (condition.object) // mode A - flag one specific object, like town
  1933. {
  1934. return team.count(condition.object->tempOwner) != 0;
  1935. }
  1936. else
  1937. {
  1938. for(const auto & elem : map->objects) // mode B - flag all objects of this type
  1939. {
  1940. //check not flagged objs
  1941. if ( elem && elem->ID == condition.objectType && team.count(elem->tempOwner) == 0 )
  1942. return false;
  1943. }
  1944. return true;
  1945. }
  1946. }
  1947. case EventCondition::TRANSPORT:
  1948. {
  1949. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1950. return (t->visitingHero && t->visitingHero->hasArt(ArtifactID(condition.objectType))) ||
  1951. (t->garrisonHero && t->garrisonHero->hasArt(ArtifactID(condition.objectType)));
  1952. }
  1953. case EventCondition::DAYS_PASSED:
  1954. {
  1955. return (si32)gs->day > condition.value;
  1956. }
  1957. case EventCondition::IS_HUMAN:
  1958. {
  1959. return p->human ? condition.value == 1 : condition.value == 0;
  1960. }
  1961. case EventCondition::DAYS_WITHOUT_TOWN:
  1962. {
  1963. if (p->daysWithoutCastle)
  1964. return p->daysWithoutCastle >= condition.value;
  1965. else
  1966. return false;
  1967. }
  1968. case EventCondition::CONST_VALUE:
  1969. {
  1970. return condition.value; // just convert to bool
  1971. }
  1972. case EventCondition::HAVE_0:
  1973. {
  1974. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1975. //TODO: support new condition format
  1976. return false;
  1977. }
  1978. case EventCondition::HAVE_BUILDING_0:
  1979. {
  1980. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1981. //TODO: support new condition format
  1982. return false;
  1983. }
  1984. case EventCondition::DESTROY_0:
  1985. {
  1986. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1987. //TODO: support new condition format
  1988. return false;
  1989. }
  1990. default:
  1991. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1992. return false;
  1993. }
  1994. }
  1995. PlayerColor CGameState::checkForStandardWin() const
  1996. {
  1997. //std victory condition is:
  1998. //all enemies lost
  1999. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  2000. TeamID winnerTeam = TeamID::NO_TEAM;
  2001. for(const auto & elem : players)
  2002. {
  2003. if(elem.second.status == EPlayerStatus::INGAME && elem.first < PlayerColor::PLAYER_LIMIT)
  2004. {
  2005. if(supposedWinner == PlayerColor::NEUTRAL)
  2006. {
  2007. //first player remaining ingame - candidate for victory
  2008. supposedWinner = elem.second.color;
  2009. winnerTeam = elem.second.team;
  2010. }
  2011. else if(winnerTeam != elem.second.team)
  2012. {
  2013. //current candidate has enemy remaining in game -> no vicotry
  2014. return PlayerColor::NEUTRAL;
  2015. }
  2016. }
  2017. }
  2018. return supposedWinner;
  2019. }
  2020. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  2021. {
  2022. //std loss condition is: player lost all towns and heroes
  2023. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  2024. return pState.checkVanquished();
  2025. }
  2026. struct statsHLP
  2027. {
  2028. using TStat = std::pair<PlayerColor, si64>;
  2029. //converts [<player's color, value>] to vec[place] -> platers
  2030. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  2031. {
  2032. std::sort(stats.begin(), stats.end(), statsHLP());
  2033. //put first element
  2034. std::vector< std::vector<PlayerColor> > ret;
  2035. std::vector<PlayerColor> tmp;
  2036. tmp.push_back( stats[0].first );
  2037. ret.push_back( tmp );
  2038. //the rest of elements
  2039. for(int g=1; g<stats.size(); ++g)
  2040. {
  2041. if(stats[g].second == stats[g-1].second)
  2042. {
  2043. (ret.end()-1)->push_back( stats[g].first );
  2044. }
  2045. else
  2046. {
  2047. //create next occupied rank
  2048. std::vector<PlayerColor> tmp;
  2049. tmp.push_back(stats[g].first);
  2050. ret.push_back(tmp);
  2051. }
  2052. }
  2053. return ret;
  2054. }
  2055. bool operator()(const TStat & a, const TStat & b) const
  2056. {
  2057. return a.second > b.second;
  2058. }
  2059. static const CGHeroInstance * findBestHero(CGameState * gs, const PlayerColor & color)
  2060. {
  2061. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2062. if(h.empty())
  2063. return nullptr;
  2064. //best hero will be that with highest exp
  2065. int best = 0;
  2066. for(int b=1; b<h.size(); ++b)
  2067. {
  2068. if(h[b]->exp > h[best]->exp)
  2069. {
  2070. best = b;
  2071. }
  2072. }
  2073. return h[best];
  2074. }
  2075. //calculates total number of artifacts that belong to given player
  2076. static int getNumberOfArts(const PlayerState * ps)
  2077. {
  2078. int ret = 0;
  2079. for(auto h : ps->heroes)
  2080. {
  2081. ret += (int)h->artifactsInBackpack.size() + (int)h->artifactsWorn.size();
  2082. }
  2083. return ret;
  2084. }
  2085. // get total strength of player army
  2086. static si64 getArmyStrength(const PlayerState * ps)
  2087. {
  2088. si64 str = 0;
  2089. for(auto h : ps->heroes)
  2090. {
  2091. if(!h->inTownGarrison) //original h3 behavior
  2092. str += h->getArmyStrength();
  2093. }
  2094. return str;
  2095. }
  2096. // get total gold income
  2097. static int getIncome(const PlayerState * ps)
  2098. {
  2099. int totalIncome = 0;
  2100. const CGObjectInstance * heroOrTown = nullptr;
  2101. //Heroes can produce gold as well - skill, specialty or arts
  2102. for(const auto & h : ps->heroes)
  2103. {
  2104. totalIncome += h->valOfBonuses(Selector::typeSubtype(BonusType::GENERATE_RESOURCE, GameResID(EGameResID::GOLD)));
  2105. if(!heroOrTown)
  2106. heroOrTown = h;
  2107. }
  2108. //Add town income of all towns
  2109. for(const auto & t : ps->towns)
  2110. {
  2111. totalIncome += t->dailyIncome()[EGameResID::GOLD];
  2112. if(!heroOrTown)
  2113. heroOrTown = t;
  2114. }
  2115. /// FIXME: Dirty dirty hack
  2116. /// Stats helper need some access to gamestate.
  2117. std::vector<const CGObjectInstance *> ownedObjects;
  2118. for(const CGObjectInstance * obj : heroOrTown->cb->gameState()->map->objects)
  2119. {
  2120. if(obj && obj->tempOwner == ps->color)
  2121. ownedObjects.push_back(obj);
  2122. }
  2123. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  2124. /// I'm really need to find out about callback interface design...
  2125. for(const auto * object : ownedObjects)
  2126. {
  2127. //Mines
  2128. if ( object->ID == Obj::MINE )
  2129. {
  2130. const auto * mine = dynamic_cast<const CGMine *>(object);
  2131. assert(mine);
  2132. if (mine->producedResource == EGameResID::GOLD)
  2133. totalIncome += mine->producedQuantity;
  2134. }
  2135. }
  2136. return totalIncome;
  2137. }
  2138. };
  2139. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2140. {
  2141. auto playerInactive = [&](const PlayerColor & color)
  2142. {
  2143. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  2144. };
  2145. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2146. { \
  2147. std::vector< std::pair< PlayerColor, si64 > > stats; \
  2148. for(auto g = players.begin(); g != players.end(); ++g) \
  2149. { \
  2150. if(playerInactive(g->second.color)) \
  2151. continue; \
  2152. std::pair< PlayerColor, si64 > stat; \
  2153. stat.first = g->second.color; \
  2154. stat.second = VAL_GETTER; \
  2155. stats.push_back(stat); \
  2156. } \
  2157. tgi.FIELD = statsHLP::getRank(stats); \
  2158. }
  2159. for(auto & elem : players)
  2160. {
  2161. if(!playerInactive(elem.second.color))
  2162. tgi.playerColors.push_back(elem.second.color);
  2163. }
  2164. if(level >= 0) //num of towns & num of heroes
  2165. {
  2166. //num of towns
  2167. FILL_FIELD(numOfTowns, g->second.towns.size())
  2168. //num of heroes
  2169. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2170. }
  2171. if(level >= 1) //best hero's portrait
  2172. {
  2173. for(const auto & player : players)
  2174. {
  2175. if(playerInactive(player.second.color))
  2176. continue;
  2177. const CGHeroInstance * best = statsHLP::findBestHero(this, player.second.color);
  2178. InfoAboutHero iah;
  2179. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  2180. iah.army.clear();
  2181. tgi.colorToBestHero[player.second.color] = iah;
  2182. }
  2183. }
  2184. if(level >= 2) //gold
  2185. {
  2186. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  2187. }
  2188. if(level >= 2) //wood & ore
  2189. {
  2190. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  2191. }
  2192. if(level >= 3) //mercury, sulfur, crystal, gems
  2193. {
  2194. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  2195. }
  2196. if(level >= 3) //obelisks found
  2197. {
  2198. auto getObeliskVisited = [](const TeamID & t)
  2199. {
  2200. if(CGObelisk::visited.count(t))
  2201. return CGObelisk::visited[t];
  2202. else
  2203. return ui8(0);
  2204. };
  2205. FILL_FIELD(obelisks, getObeliskVisited(gs->getPlayerTeam(g->second.color)->id))
  2206. }
  2207. if(level >= 4) //artifacts
  2208. {
  2209. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2210. }
  2211. if(level >= 4) //army strength
  2212. {
  2213. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  2214. }
  2215. if(level >= 5) //income
  2216. {
  2217. FILL_FIELD(income, statsHLP::getIncome(&g->second))
  2218. }
  2219. if(level >= 2) //best hero's stats
  2220. {
  2221. //already set in lvl 1 handling
  2222. }
  2223. if(level >= 3) //personality
  2224. {
  2225. for(const auto & player : players)
  2226. {
  2227. if(playerInactive(player.second.color)) //do nothing for neutral player
  2228. continue;
  2229. if(player.second.human)
  2230. {
  2231. tgi.personality[player.second.color] = EAiTactic::NONE;
  2232. }
  2233. else //AI
  2234. {
  2235. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  2236. }
  2237. }
  2238. }
  2239. if(level >= 4) //best creature
  2240. {
  2241. //best creatures belonging to player (highest AI value)
  2242. for(const auto & player : players)
  2243. {
  2244. if(playerInactive(player.second.color)) //do nothing for neutral player
  2245. continue;
  2246. int bestCre = -1; //best creature's ID
  2247. for(const auto & elem : player.second.heroes)
  2248. {
  2249. for(const auto & it : elem->Slots())
  2250. {
  2251. int toCmp = it.second->type->getId(); //ID of creature we should compare with the best one
  2252. if(bestCre == -1 || VLC->creh->objects[bestCre]->getAIValue() < VLC->creh->objects[toCmp]->getAIValue())
  2253. {
  2254. bestCre = toCmp;
  2255. }
  2256. }
  2257. }
  2258. tgi.bestCreature[player.second.color] = bestCre;
  2259. }
  2260. }
  2261. #undef FILL_FIELD
  2262. }
  2263. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2264. {
  2265. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2266. for(const auto & player : players)
  2267. for(auto availableHero : player.second.availableHeroes)
  2268. if(availableHero)
  2269. pool.erase((*availableHero).subID);
  2270. return pool;
  2271. }
  2272. void CGameState::buildBonusSystemTree()
  2273. {
  2274. buildGlobalTeamPlayerTree();
  2275. attachArmedObjects();
  2276. for(CGTownInstance *t : map->towns)
  2277. {
  2278. t->deserializationFix();
  2279. }
  2280. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2281. // are provided on initializing / deserializing
  2282. // NOTE: calling deserializationFix() might be more correct option, but might lead to side effects
  2283. for (auto hero : map->heroesOnMap)
  2284. hero->boatDeserializationFix();
  2285. }
  2286. void CGameState::deserializationFix()
  2287. {
  2288. buildGlobalTeamPlayerTree();
  2289. attachArmedObjects();
  2290. }
  2291. void CGameState::buildGlobalTeamPlayerTree()
  2292. {
  2293. for(auto & team : teams)
  2294. {
  2295. TeamState * t = &team.second;
  2296. t->attachTo(globalEffects);
  2297. for(const PlayerColor & teamMember : team.second.players)
  2298. {
  2299. PlayerState *p = getPlayerState(teamMember);
  2300. assert(p);
  2301. p->attachTo(*t);
  2302. }
  2303. }
  2304. }
  2305. void CGameState::attachArmedObjects()
  2306. {
  2307. for(CGObjectInstance *obj : map->objects)
  2308. {
  2309. if(auto * armed = dynamic_cast<CArmedInstance *>(obj))
  2310. {
  2311. armed->whatShouldBeAttached().attachTo(armed->whereShouldBeAttached(this));
  2312. }
  2313. }
  2314. }
  2315. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  2316. {
  2317. CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  2318. CArtifactInstance * ai = ArtifactUtils::createNewArtifactInstance(artifact);
  2319. map->addNewArtifactInstance(ai);
  2320. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  2321. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  2322. {
  2323. ai->putAt(ArtifactLocation(h, slot));
  2324. return true;
  2325. }
  2326. else
  2327. {
  2328. return false;
  2329. }
  2330. }
  2331. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  2332. {
  2333. std::set<HeroTypeID> ret;
  2334. for(int i = 0; i < map->allowedHeroes.size(); i++)
  2335. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  2336. ret.insert(HeroTypeID(i));
  2337. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  2338. {
  2339. if(playerSettingPair.second.hero != PlayerSettings::RANDOM)
  2340. ret -= HeroTypeID(playerSettingPair.second.hero);
  2341. }
  2342. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2343. {
  2344. if(hero->type)
  2345. ret -= hero->type->getId();
  2346. else
  2347. ret -= HeroTypeID(hero->subID);
  2348. }
  2349. for(auto obj : map->objects) //prisons
  2350. if(obj && obj->ID == Obj::PRISON)
  2351. ret -= HeroTypeID(obj->subID);
  2352. return ret;
  2353. }
  2354. std::vector<CGameState::CampaignHeroReplacement> CGameState::generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes)
  2355. {
  2356. std::vector<CampaignHeroReplacement> campaignHeroReplacements;
  2357. //selecting heroes by type
  2358. for(auto obj : map->objects)
  2359. {
  2360. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2361. {
  2362. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2363. if(heroPlaceholder->subID != 0xFF) //select by type
  2364. {
  2365. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [heroPlaceholder](CGHeroInstance * hero)
  2366. {
  2367. return hero->subID == heroPlaceholder->subID;
  2368. });
  2369. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  2370. {
  2371. auto * hero = *it;
  2372. crossoverHeroes.removeHeroFromBothLists(hero);
  2373. campaignHeroReplacements.emplace_back(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id);
  2374. }
  2375. }
  2376. }
  2377. }
  2378. //selecting heroes by power
  2379. range::sort(crossoverHeroes.heroesFromPreviousScenario, [](const CGHeroInstance * a, const CGHeroInstance * b)
  2380. {
  2381. return a->getHeroStrength() > b->getHeroStrength();
  2382. }); //sort, descending strength
  2383. // sort hero placeholders descending power
  2384. std::vector<CGHeroPlaceholder *> heroPlaceholders;
  2385. for(auto obj : map->objects)
  2386. {
  2387. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2388. {
  2389. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2390. if(heroPlaceholder->subID == 0xFF) //select by power
  2391. {
  2392. heroPlaceholders.push_back(heroPlaceholder);
  2393. }
  2394. }
  2395. }
  2396. range::sort(heroPlaceholders, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  2397. {
  2398. return a->power > b->power;
  2399. });
  2400. for(int i = 0; i < heroPlaceholders.size(); ++i)
  2401. {
  2402. auto * heroPlaceholder = heroPlaceholders[i];
  2403. if(crossoverHeroes.heroesFromPreviousScenario.size() > i)
  2404. {
  2405. auto * hero = crossoverHeroes.heroesFromPreviousScenario[i];
  2406. campaignHeroReplacements.emplace_back(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id);
  2407. }
  2408. }
  2409. return campaignHeroReplacements;
  2410. }
  2411. void CGameState::replaceHeroesPlaceholders(const std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements)
  2412. {
  2413. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  2414. {
  2415. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(getObjInstance(campaignHeroReplacement.heroPlaceholderId));
  2416. CGHeroInstance *heroToPlace = campaignHeroReplacement.hero;
  2417. heroToPlace->id = campaignHeroReplacement.heroPlaceholderId;
  2418. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  2419. heroToPlace->pos = heroPlaceholder->pos;
  2420. heroToPlace->type = VLC->heroh->objects[heroToPlace->subID];
  2421. heroToPlace->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO,
  2422. heroToPlace->type->heroClass->getIndex())->getTemplates().front();
  2423. for(auto &&i : heroToPlace->stacks)
  2424. i.second->type = VLC->creh->objects[i.second->getCreatureID()];
  2425. auto fixArtifact = [&](CArtifactInstance * art)
  2426. {
  2427. art->artType = VLC->arth->objects[art->artType->getId()];
  2428. gs->map->artInstances.emplace_back(art);
  2429. art->id = ArtifactInstanceID((si32)gs->map->artInstances.size() - 1);
  2430. };
  2431. for(auto &&i : heroToPlace->artifactsWorn)
  2432. fixArtifact(i.second.artifact);
  2433. for(auto &&i : heroToPlace->artifactsInBackpack)
  2434. fixArtifact(i.artifact);
  2435. map->removeBlockVisTiles(heroPlaceholder, true);
  2436. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  2437. map->instanceNames.erase(heroPlaceholder->instanceName);
  2438. map->heroesOnMap.emplace_back(heroToPlace);
  2439. map->objects[heroToPlace->id.getNum()] = heroToPlace;
  2440. map->addBlockVisTiles(heroToPlace);
  2441. map->instanceNames[heroToPlace->instanceName] = heroToPlace;
  2442. delete heroPlaceholder;
  2443. scenarioOps->campState->getCurrentScenario().placedCrossoverHeroes.push_back(CCampaignState::crossoverSerialize(heroToPlace));
  2444. }
  2445. }
  2446. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  2447. {
  2448. return getUsedHero(hid);
  2449. }
  2450. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  2451. {
  2452. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2453. {
  2454. if(hero->type && hero->type->getId() == hid)
  2455. {
  2456. return hero;
  2457. }
  2458. }
  2459. for(auto obj : map->objects) //prisons
  2460. {
  2461. if(obj && obj->ID == Obj::PRISON )
  2462. {
  2463. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  2464. assert(hero);
  2465. if ( hero->type && hero->type->getId() == hid )
  2466. return hero;
  2467. }
  2468. }
  2469. return nullptr;
  2470. }
  2471. bool RumorState::update(int id, int extra)
  2472. {
  2473. if(vstd::contains(last, type))
  2474. {
  2475. if(last[type].first != id)
  2476. {
  2477. last[type].first = id;
  2478. last[type].second = extra;
  2479. }
  2480. else
  2481. return false;
  2482. }
  2483. else
  2484. last[type] = std::make_pair(id, extra);
  2485. return true;
  2486. }
  2487. InfoAboutArmy::InfoAboutArmy():
  2488. owner(PlayerColor::NEUTRAL)
  2489. {}
  2490. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2491. {
  2492. initFromArmy(Army, detailed);
  2493. }
  2494. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2495. {
  2496. army = ArmyDescriptor(Army, detailed);
  2497. owner = Army->tempOwner;
  2498. name = Army->getObjectName();
  2499. }
  2500. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2501. {
  2502. vstd::clear_pointer(details);
  2503. InfoAboutArmy::operator = (iah);
  2504. details = (iah.details ? new Details(*iah.details) : nullptr);
  2505. hclass = iah.hclass;
  2506. portrait = iah.portrait;
  2507. }
  2508. InfoAboutHero::InfoAboutHero(): portrait(-1) {}
  2509. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah): InfoAboutArmy(iah)
  2510. {
  2511. assign(iah);
  2512. }
  2513. InfoAboutHero::InfoAboutHero(const CGHeroInstance * h, InfoAboutHero::EInfoLevel infoLevel):
  2514. portrait(-1)
  2515. {
  2516. initFromHero(h, infoLevel);
  2517. }
  2518. InfoAboutHero::~InfoAboutHero()
  2519. {
  2520. vstd::clear_pointer(details);
  2521. }
  2522. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2523. {
  2524. assign(iah);
  2525. return *this;
  2526. }
  2527. void InfoAboutHero::initFromHero(const CGHeroInstance *h, InfoAboutHero::EInfoLevel infoLevel)
  2528. {
  2529. vstd::clear_pointer(details);
  2530. if(!h)
  2531. return;
  2532. bool detailed = ( (infoLevel == EInfoLevel::DETAILED) || (infoLevel == EInfoLevel::INBATTLE) );
  2533. initFromArmy(h, detailed);
  2534. hclass = h->type->heroClass;
  2535. name = h->getNameTranslated();
  2536. portrait = h->portrait;
  2537. if(detailed)
  2538. {
  2539. //include details about hero
  2540. details = new Details();
  2541. details->luck = h->luckVal();
  2542. details->morale = h->moraleVal();
  2543. details->mana = h->mana;
  2544. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2545. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2546. {
  2547. details->primskills[i] = h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i));
  2548. }
  2549. if (infoLevel == EInfoLevel::INBATTLE)
  2550. details->manaLimit = h->manaLimit();
  2551. else
  2552. details->manaLimit = -1; //we do not want to leak max mana info outside battle so set to meaningless value
  2553. }
  2554. }
  2555. InfoAboutTown::InfoAboutTown():
  2556. details(nullptr),
  2557. tType(nullptr),
  2558. built(0),
  2559. fortLevel(0)
  2560. {
  2561. }
  2562. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed):
  2563. details(nullptr),
  2564. tType(nullptr),
  2565. built(0),
  2566. fortLevel(0)
  2567. {
  2568. initFromTown(t, detailed);
  2569. }
  2570. InfoAboutTown::~InfoAboutTown()
  2571. {
  2572. vstd::clear_pointer(details);
  2573. }
  2574. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2575. {
  2576. initFromArmy(t, detailed);
  2577. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2578. built = t->builded;
  2579. fortLevel = t->fortLevel();
  2580. name = t->getNameTranslated();
  2581. tType = t->getTown();
  2582. vstd::clear_pointer(details);
  2583. if(detailed)
  2584. {
  2585. //include details about hero
  2586. details = new Details();
  2587. TResources income = t->dailyIncome();
  2588. details->goldIncome = income[EGameResID::GOLD];
  2589. details->customRes = t->hasBuilt(BuildingID::RESOURCE_SILO);
  2590. details->hallLevel = t->hallLevel();
  2591. details->garrisonedHero = t->garrisonHero;
  2592. }
  2593. }
  2594. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2595. : isDetailed(detailed)
  2596. {
  2597. for(const auto & elem : army->Slots())
  2598. {
  2599. if(detailed)
  2600. (*this)[elem.first] = *elem.second;
  2601. else
  2602. (*this)[elem.first] = CStackBasicDescriptor(elem.second->type, (int)elem.second->getQuantityID());
  2603. }
  2604. }
  2605. ArmyDescriptor::ArmyDescriptor()
  2606. : isDetailed(false)
  2607. {
  2608. }
  2609. int ArmyDescriptor::getStrength() const
  2610. {
  2611. ui64 ret = 0;
  2612. if(isDetailed)
  2613. {
  2614. for(const auto & elem : *this)
  2615. ret += elem.second.type->getAIValue() * elem.second.count;
  2616. }
  2617. else
  2618. {
  2619. for(const auto & elem : *this)
  2620. ret += elem.second.type->getAIValue() * CCreature::estimateCreatureCount(elem.second.count);
  2621. }
  2622. return static_cast<int>(ret);
  2623. }
  2624. TeamState::TeamState()
  2625. {
  2626. setNodeType(TEAM);
  2627. fogOfWarMap = std::make_shared<boost::multi_array<ui8, 3>>();
  2628. }
  2629. TeamState::TeamState(TeamState && other) noexcept:
  2630. CBonusSystemNode(std::move(other)),
  2631. id(other.id)
  2632. {
  2633. std::swap(players, other.players);
  2634. std::swap(fogOfWarMap, other.fogOfWarMap);
  2635. }
  2636. CRandomGenerator & CGameState::getRandomGenerator()
  2637. {
  2638. return rand;
  2639. }
  2640. VCMI_LIB_NAMESPACE_END