CGameState.cpp 50 KB

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