CGameState.cpp 61 KB

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