CGameState.cpp 49 KB

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