CGameState.cpp 59 KB

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