CGameState.cpp 59 KB

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