CGameState.cpp 56 KB

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