CGameState.cpp 55 KB

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