CGameState.cpp 51 KB

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