CGameState.cpp 74 KB

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