CGameState.cpp 52 KB

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