CGameState.cpp 54 KB

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