CGameState.cpp 55 KB

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