CGameState.cpp 61 KB

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