CGameState.cpp 59 KB

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