2
0

CGameState.cpp 56 KB

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