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