CGameState.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  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/CPrivilegedInfoCallback.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(CPrivilegedInfoCallback * 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. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  914. {
  915. assert(obj);
  916. assert(obj->hasStackAtSlot(stackPos));
  917. out = fillUpgradeInfo(obj->getStack(stackPos));
  918. }
  919. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance & stack) const
  920. {
  921. const CCreature *base = stack.getCreature();
  922. UpgradeInfo ret(base->getId());
  923. if (stack.getArmy()->ID == Obj::HERO)
  924. {
  925. auto hero = dynamic_cast<const CGHeroInstance *>(stack.getArmy());
  926. hero->fillUpgradeInfo(ret, stack);
  927. if (hero->getVisitedTown())
  928. {
  929. hero->getVisitedTown()->fillUpgradeInfo(ret, stack);
  930. }
  931. else
  932. {
  933. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  934. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  935. if (object != hero && upgradeSource != nullptr)
  936. upgradeSource->fillUpgradeInfo(ret, stack);
  937. }
  938. }
  939. if (stack.getArmy()->ID == Obj::TOWN)
  940. {
  941. auto town = dynamic_cast<const CGTownInstance *>(stack.getArmy());
  942. town->fillUpgradeInfo(ret, stack);
  943. }
  944. return ret;
  945. }
  946. PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  947. {
  948. if ( color1 == color2 )
  949. return PlayerRelations::SAME_PLAYER;
  950. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  951. return PlayerRelations::ENEMIES;
  952. const TeamState * ts = getPlayerTeam(color1);
  953. if (ts && vstd::contains(ts->players, color2))
  954. return PlayerRelations::ALLIES;
  955. return PlayerRelations::ENEMIES;
  956. }
  957. void CGameState::apply(CPackForClient & pack)
  958. {
  959. GameStatePackVisitor visitor(*this);
  960. pack.visit(visitor);
  961. }
  962. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config) const
  963. {
  964. CPathfinder pathfinder(*const_cast<CGameState*>(this), config);
  965. pathfinder.calculatePaths();
  966. }
  967. /**
  968. * Tells if the tile is guarded by a monster as well as the position
  969. * of the monster that will attack on it.
  970. *
  971. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  972. * the monster guarding the tile.
  973. */
  974. std::vector<const CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  975. {
  976. std::vector<const CGObjectInstance*> guards;
  977. const int3 originalPos = pos;
  978. if (!map->isInTheMap(pos))
  979. return guards;
  980. const TerrainTile &posTile = map->getTile(pos);
  981. if (posTile.visitable())
  982. {
  983. for (ObjectInstanceID objectID : posTile.visitableObjects)
  984. {
  985. const CGObjectInstance * object = getObjInstance(objectID);
  986. if(object->isBlockedVisitable())
  987. {
  988. if (object->ID == Obj::MONSTER) // Monster
  989. guards.push_back(object);
  990. }
  991. }
  992. }
  993. pos -= int3(1, 1, 0); // Start with top left.
  994. for (int dx = 0; dx < 3; dx++)
  995. {
  996. for (int dy = 0; dy < 3; dy++)
  997. {
  998. if (map->isInTheMap(pos))
  999. {
  1000. const auto & tile = map->getTile(pos);
  1001. if (tile.visitable() && (tile.isWater() == posTile.isWater()))
  1002. {
  1003. for (ObjectInstanceID objectID : tile.visitableObjects)
  1004. {
  1005. const CGObjectInstance * object = getObjInstance(objectID);
  1006. if (object->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1007. {
  1008. guards.push_back(object);
  1009. }
  1010. }
  1011. }
  1012. }
  1013. pos.y++;
  1014. }
  1015. pos.y -= 3;
  1016. pos.x++;
  1017. }
  1018. return guards;
  1019. }
  1020. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1021. {
  1022. return getMap().guardingCreaturePositions[pos.z][pos.x][pos.y];
  1023. }
  1024. bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
  1025. {
  1026. if (!map->isInTheMap(pos))
  1027. return false;
  1028. if (!player)
  1029. return true;
  1030. if(player == PlayerColor::NEUTRAL)
  1031. return false;
  1032. if(player->isSpectator())
  1033. return true;
  1034. return getPlayerTeam(*player)->fogOfWarMap[pos.z][pos.x][pos.y];
  1035. }
  1036. bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
  1037. {
  1038. if(!player)
  1039. return true;
  1040. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1041. if (player == obj->tempOwner)
  1042. return true;
  1043. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1044. return false;
  1045. //object is visible when at least one blocked tile is visible
  1046. for(int fy=0; fy < obj->getHeight(); ++fy)
  1047. {
  1048. for(int fx=0; fx < obj->getWidth(); ++fx)
  1049. {
  1050. int3 pos = obj->anchorPos() + int3(-fx, -fy, 0);
  1051. if ( map->isInTheMap(pos) &&
  1052. obj->coveringAt(pos) &&
  1053. isVisible(pos, *player))
  1054. return true;
  1055. }
  1056. }
  1057. return false;
  1058. }
  1059. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1060. {
  1061. const TerrainTile * pom = &map->getTile(dst);
  1062. return map->checkForVisitableDir(src, pom, dst);
  1063. }
  1064. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  1065. {
  1066. const MetaString messageWonSelf = MetaString::createFromTextID("core.genrltxt.659");
  1067. const MetaString messageWonOther = MetaString::createFromTextID("core.genrltxt.5");
  1068. const MetaString messageLostSelf = MetaString::createFromTextID("core.genrltxt.7");
  1069. const MetaString messageLostOther = MetaString::createFromTextID("core.genrltxt.8");
  1070. auto evaluateEvent = [this, player](const EventCondition & condition)
  1071. {
  1072. return this->checkForVictory(player, condition);
  1073. };
  1074. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1075. //cheater or tester, but has entered the code...
  1076. if (p->enteredWinningCheatCode)
  1077. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1078. if (p->enteredLosingCheatCode)
  1079. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1080. for (const TriggeredEvent & event : map->triggeredEvents)
  1081. {
  1082. if (event.trigger.test(evaluateEvent))
  1083. {
  1084. if (event.effect.type == EventEffect::VICTORY)
  1085. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1086. if (event.effect.type == EventEffect::DEFEAT)
  1087. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1088. }
  1089. }
  1090. if (checkForStandardLoss(player))
  1091. {
  1092. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1093. }
  1094. return EVictoryLossCheckResult();
  1095. }
  1096. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  1097. {
  1098. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1099. switch (condition.condition)
  1100. {
  1101. case EventCondition::STANDARD_WIN:
  1102. {
  1103. return player == checkForStandardWin();
  1104. }
  1105. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1106. {
  1107. for(const auto & elem : p->getHeroes())
  1108. if(elem->hasArt(condition.objectType.as<ArtifactID>()))
  1109. return true;
  1110. return false;
  1111. }
  1112. case EventCondition::HAVE_CREATURES:
  1113. {
  1114. //check if in players armies there is enough creatures
  1115. int total = 0; //creature counter
  1116. for(auto ai : map->getObjects<CArmedInstance>())
  1117. {
  1118. if(ai->getOwner() == player)
  1119. {
  1120. for(const auto & elem : ai->Slots()) //iterate through army
  1121. if(elem.second->getId() == condition.objectType.as<CreatureID>()) //it's searched creature
  1122. total += elem.second->getCount();
  1123. }
  1124. }
  1125. return total >= condition.value;
  1126. }
  1127. case EventCondition::HAVE_RESOURCES:
  1128. {
  1129. return p->resources[condition.objectType.as<GameResID>()] >= condition.value;
  1130. }
  1131. case EventCondition::HAVE_BUILDING:
  1132. {
  1133. if (condition.objectID != ObjectInstanceID::NONE) // specific town
  1134. {
  1135. const auto * t = getTown(condition.objectID);
  1136. return (t->tempOwner == player && t->hasBuilt(condition.objectType.as<BuildingID>()));
  1137. }
  1138. else // any town
  1139. {
  1140. for (const CGTownInstance * t : p->getTowns())
  1141. {
  1142. if (t->hasBuilt(condition.objectType.as<BuildingID>()))
  1143. return true;
  1144. }
  1145. return false;
  1146. }
  1147. }
  1148. case EventCondition::DESTROY:
  1149. {
  1150. if (condition.objectID != ObjectInstanceID::NONE) // mode A - destroy specific object of this type
  1151. {
  1152. return p->destroyedObjects.count(condition.objectID);
  1153. }
  1154. else
  1155. {
  1156. for(const auto & elem : map->getObjects()) // mode B - destroy all objects of this type
  1157. {
  1158. if(elem && elem->ID == condition.objectType.as<MapObjectID>())
  1159. return false;
  1160. }
  1161. return true;
  1162. }
  1163. }
  1164. case EventCondition::CONTROL:
  1165. {
  1166. // list of players that need to control object to fulfull condition
  1167. // NOTE: cgameinfocallback specified explicitly in order to get const version
  1168. const auto * team = CGameInfoCallback::getPlayerTeam(player);
  1169. if (condition.objectID != ObjectInstanceID::NONE) // mode A - flag one specific object, like town
  1170. {
  1171. const auto * object = getObjInstance(condition.objectID);
  1172. if (!object)
  1173. return false;
  1174. return team->players.count(object->getOwner()) != 0;
  1175. }
  1176. else
  1177. {
  1178. for(const auto & elem : map->getObjects()) // mode B - flag all objects of this type
  1179. {
  1180. //check not flagged objs
  1181. if ( elem && elem->ID == condition.objectType.as<MapObjectID>() && team->players.count(elem->getOwner()) == 0 )
  1182. return false;
  1183. }
  1184. return true;
  1185. }
  1186. }
  1187. case EventCondition::TRANSPORT:
  1188. {
  1189. const auto * t = getTown(condition.objectID);
  1190. bool garrisonedWon = t->getGarrisonHero() && t->getGarrisonHero()->getOwner() == player && t->getGarrisonHero()->hasArt(condition.objectType.as<ArtifactID>());
  1191. bool visitingWon = t->getVisitingHero() && t->getVisitingHero()->getOwner() == player && t->getVisitingHero()->hasArt(condition.objectType.as<ArtifactID>());
  1192. return garrisonedWon || visitingWon;
  1193. }
  1194. case EventCondition::DAYS_PASSED:
  1195. {
  1196. return day > condition.value;
  1197. }
  1198. case EventCondition::IS_HUMAN:
  1199. {
  1200. return p->human ? condition.value == 1 : condition.value == 0;
  1201. }
  1202. case EventCondition::DAYS_WITHOUT_TOWN:
  1203. {
  1204. if (p->daysWithoutCastle)
  1205. return p->daysWithoutCastle >= condition.value;
  1206. else
  1207. return false;
  1208. }
  1209. case EventCondition::CONST_VALUE:
  1210. {
  1211. return condition.value; // just convert to bool
  1212. }
  1213. default:
  1214. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1215. return false;
  1216. }
  1217. }
  1218. PlayerColor CGameState::checkForStandardWin() const
  1219. {
  1220. //std victory condition is:
  1221. //all enemies lost
  1222. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  1223. TeamID winnerTeam = TeamID::NO_TEAM;
  1224. for(const auto & elem : players)
  1225. {
  1226. if(elem.second.status == EPlayerStatus::WINNER)
  1227. return elem.second.color;
  1228. if(elem.second.status == EPlayerStatus::INGAME && elem.first.isValidPlayer())
  1229. {
  1230. if(supposedWinner == PlayerColor::NEUTRAL)
  1231. {
  1232. //first player remaining ingame - candidate for victory
  1233. supposedWinner = elem.second.color;
  1234. winnerTeam = elem.second.team;
  1235. }
  1236. else if(winnerTeam != elem.second.team)
  1237. {
  1238. //current candidate has enemy remaining in game -> no vicotry
  1239. return PlayerColor::NEUTRAL;
  1240. }
  1241. }
  1242. }
  1243. return supposedWinner;
  1244. }
  1245. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  1246. {
  1247. //std loss condition is: player lost all towns and heroes
  1248. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  1249. return pState.checkVanquished();
  1250. }
  1251. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  1252. {
  1253. auto playerInactive = [&](const PlayerColor & color)
  1254. {
  1255. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  1256. };
  1257. #define FILL_FIELD(FIELD, VAL_GETTER) \
  1258. { \
  1259. std::vector< std::pair< PlayerColor, si64 > > stats; \
  1260. for(auto g = players.begin(); g != players.end(); ++g) \
  1261. { \
  1262. if(playerInactive(g->second.color)) \
  1263. continue; \
  1264. std::pair< PlayerColor, si64 > stat; \
  1265. stat.first = g->second.color; \
  1266. stat.second = VAL_GETTER; \
  1267. stats.push_back(stat); \
  1268. } \
  1269. tgi.FIELD = Statistic::getRank(stats); \
  1270. }
  1271. for(auto & elem : players)
  1272. {
  1273. if(!playerInactive(elem.second.color))
  1274. tgi.playerColors.push_back(elem.second.color);
  1275. }
  1276. if(level >= 0) //num of towns & num of heroes
  1277. {
  1278. //num of towns
  1279. FILL_FIELD(numOfTowns, g->second.getTowns().size())
  1280. //num of heroes
  1281. FILL_FIELD(numOfHeroes, g->second.getHeroes().size())
  1282. }
  1283. if(level >= 1) //best hero's portrait
  1284. {
  1285. for(const auto & player : players)
  1286. {
  1287. if(playerInactive(player.second.color))
  1288. continue;
  1289. const CGHeroInstance * best = Statistic::findBestHero(this, player.second.color);
  1290. InfoAboutHero iah;
  1291. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  1292. iah.army.clear();
  1293. tgi.colorToBestHero[player.second.color] = iah;
  1294. }
  1295. }
  1296. if(level >= 2) //gold
  1297. {
  1298. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  1299. }
  1300. if(level >= 2) //wood & ore
  1301. {
  1302. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  1303. }
  1304. if(level >= 3) //mercury, sulfur, crystal, gems
  1305. {
  1306. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  1307. }
  1308. if(level >= 3) //obelisks found
  1309. {
  1310. FILL_FIELD(obelisks, Statistic::getObeliskVisited(this, getPlayerTeam(g->second.color)->id))
  1311. }
  1312. if(level >= 4) //artifacts
  1313. {
  1314. FILL_FIELD(artifacts, Statistic::getNumberOfArts(&g->second))
  1315. }
  1316. if(level >= 4) //army strength
  1317. {
  1318. FILL_FIELD(army, Statistic::getArmyStrength(&g->second))
  1319. }
  1320. if(level >= 5) //income
  1321. {
  1322. FILL_FIELD(income, Statistic::getIncome(this, &g->second))
  1323. }
  1324. if(level >= 2) //best hero's stats
  1325. {
  1326. //already set in lvl 1 handling
  1327. }
  1328. if(level >= 3) //personality
  1329. {
  1330. for(const auto & player : players)
  1331. {
  1332. if(playerInactive(player.second.color)) //do nothing for neutral player
  1333. continue;
  1334. if(player.second.human)
  1335. {
  1336. tgi.personality[player.second.color] = EAiTactic::NONE;
  1337. }
  1338. else //AI
  1339. {
  1340. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  1341. }
  1342. }
  1343. }
  1344. if(level >= 4) //best creature
  1345. {
  1346. //best creatures belonging to player (highest AI value)
  1347. for(const auto & player : players)
  1348. {
  1349. if(playerInactive(player.second.color)) //do nothing for neutral player
  1350. continue;
  1351. CreatureID bestCre; //best creature's ID
  1352. for(const auto & elem : player.second.getHeroes())
  1353. {
  1354. for(const auto & it : elem->Slots())
  1355. {
  1356. CreatureID toCmp = it.second->getId(); //ID of creature we should compare with the best one
  1357. if(bestCre == CreatureID::NONE || bestCre.toEntity(LIBRARY)->getAIValue() < toCmp.toEntity(LIBRARY)->getAIValue())
  1358. {
  1359. bestCre = toCmp;
  1360. }
  1361. }
  1362. }
  1363. tgi.bestCreature[player.second.color] = bestCre;
  1364. }
  1365. }
  1366. #undef FILL_FIELD
  1367. }
  1368. void CGameState::buildBonusSystemTree()
  1369. {
  1370. buildGlobalTeamPlayerTree();
  1371. for(auto & armed : map->getObjects<CArmedInstance>())
  1372. armed->attachToBonusSystem(*this);
  1373. }
  1374. void CGameState::restoreBonusSystemTree()
  1375. {
  1376. heroesPool->setGameState(this);
  1377. buildGlobalTeamPlayerTree();
  1378. for(auto & armed : map->getObjects<CArmedInstance>())
  1379. armed->restoreBonusSystem(*this);
  1380. for(auto & art : map->getArtifacts())
  1381. art->attachToBonusSystem(*this);
  1382. for(auto & heroID : map->getHeroesInPool())
  1383. map->tryGetFromHeroPool(heroID)->artDeserializationFix(*this, map->tryGetFromHeroPool(heroID));
  1384. if (campaign)
  1385. campaign->setGamestate(this);
  1386. }
  1387. void CGameState::buildGlobalTeamPlayerTree()
  1388. {
  1389. for(auto & team : teams)
  1390. {
  1391. TeamState * t = &team.second;
  1392. t->attachTo(globalEffects);
  1393. for(const PlayerColor & teamMember : team.second.players)
  1394. {
  1395. PlayerState *p = getPlayerState(teamMember);
  1396. assert(p);
  1397. p->attachTo(*t);
  1398. }
  1399. }
  1400. }
  1401. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  1402. {
  1403. CArtifactInstance * ai = createArtifact(aid);
  1404. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  1405. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1406. {
  1407. map->putArtifactInstance(*h, ai->getId(), slot);
  1408. return true;
  1409. }
  1410. else
  1411. {
  1412. return false;
  1413. }
  1414. }
  1415. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  1416. {
  1417. std::set<HeroTypeID> ret = map->allowedHeroes;
  1418. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  1419. {
  1420. if(playerSettingPair.second.hero != HeroTypeID::RANDOM)
  1421. ret -= HeroTypeID(playerSettingPair.second.hero);
  1422. }
  1423. for (auto heroID : map->getHeroesOnMap())
  1424. ret -= getHero(heroID)->getHeroTypeID();
  1425. return ret;
  1426. }
  1427. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  1428. {
  1429. return getUsedHero(hid);
  1430. }
  1431. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  1432. {
  1433. for(auto hero : map->getObjects<CGHeroInstance>()) //prisons
  1434. {
  1435. if (hero->getHeroTypeID() == hid)
  1436. return hero;
  1437. }
  1438. return nullptr;
  1439. }
  1440. TeamState::TeamState()
  1441. {
  1442. setNodeType(TEAM);
  1443. }
  1444. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & randomGenerator, std::optional<EArtifactClass> type, std::function<bool(ArtifactID)> accepts)
  1445. {
  1446. std::set<ArtifactID> potentialPicks;
  1447. // Select artifacts that satisfy provided criteria
  1448. for (auto const & artifactID : map->allowedArtifact)
  1449. {
  1450. if (!LIBRARY->arth->legalArtifact(artifactID))
  1451. continue;
  1452. auto const * artifact = artifactID.toArtifact();
  1453. assert(artifact->aClass != EArtifactClass::ART_SPECIAL); // should be filtered out when allowedArtifacts is initialized
  1454. if (type.has_value() && *type != artifact->aClass)
  1455. continue;
  1456. if (!accepts(artifact->getId()))
  1457. continue;
  1458. potentialPicks.insert(artifact->getId());
  1459. }
  1460. return pickRandomArtifact(randomGenerator, potentialPicks);
  1461. }
  1462. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & randomGenerator, std::set<ArtifactID> potentialPicks)
  1463. {
  1464. // No allowed artifacts at all - give Grail - this can't be banned (hopefully)
  1465. // FIXME: investigate how such cases are handled by H3 - some heavily customized user-made maps likely rely on H3 behavior
  1466. if (potentialPicks.empty())
  1467. {
  1468. logGlobal->warn("Failed to find artifact that matches requested parameters!");
  1469. return ArtifactID::GRAIL;
  1470. }
  1471. // Find how many times least used artifacts were picked by randomizer
  1472. int leastUsedTimes = std::numeric_limits<int>::max();
  1473. for (auto const & artifact : potentialPicks)
  1474. if (allocatedArtifacts[artifact] < leastUsedTimes)
  1475. leastUsedTimes = allocatedArtifacts[artifact];
  1476. // Pick all artifacts that were used least number of times
  1477. std::set<ArtifactID> preferredPicks;
  1478. for (auto const & artifact : potentialPicks)
  1479. if (allocatedArtifacts[artifact] == leastUsedTimes)
  1480. preferredPicks.insert(artifact);
  1481. assert(!preferredPicks.empty());
  1482. ArtifactID artID = *RandomGeneratorUtil::nextItem(preferredPicks, randomGenerator);
  1483. allocatedArtifacts[artID] += 1; // record +1 more usage
  1484. return artID;
  1485. }
  1486. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & randomGenerator, std::function<bool(ArtifactID)> accepts)
  1487. {
  1488. return pickRandomArtifact(randomGenerator, std::nullopt, std::move(accepts));
  1489. }
  1490. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & randomGenerator, std::optional<EArtifactClass> type)
  1491. {
  1492. return pickRandomArtifact(randomGenerator, type, [](const ArtifactID &) { return true; });
  1493. }
  1494. CArtifactInstance * CGameState::createScroll(const SpellID & spellId)
  1495. {
  1496. return map->createScroll(spellId);
  1497. }
  1498. CArtifactInstance * CGameState::createArtifact(const ArtifactID & artID, const SpellID & spellId)
  1499. {
  1500. return map->createArtifact(artID, spellId);
  1501. }
  1502. void CGameState::saveGame(CSaveFile & file) const
  1503. {
  1504. ActiveModsInSaveList activeModsDummy;
  1505. logGlobal->info("Saving game state");
  1506. file.save(*getMapHeader());
  1507. file.save(*getStartInfo());
  1508. file.save(activeModsDummy);
  1509. file.save(*this);
  1510. }
  1511. void CGameState::loadGame(CLoadFile & file)
  1512. {
  1513. logGlobal->info("Loading game state...");
  1514. CMapHeader dummyHeader;
  1515. StartInfo dummyStartInfo;
  1516. ActiveModsInSaveList dummyActiveMods;
  1517. file.load(dummyHeader);
  1518. if (file.hasFeature(ESerializationVersion::NO_RAW_POINTERS_IN_SERIALIZER))
  1519. {
  1520. file.load(dummyStartInfo);
  1521. file.load(dummyActiveMods);
  1522. file.load(*this);
  1523. }
  1524. else
  1525. {
  1526. bool dummyA = false;
  1527. uint32_t dummyB = 0;
  1528. uint16_t dummyC = 0;
  1529. file.load(dummyStartInfo);
  1530. file.load(dummyActiveMods);
  1531. file.load(dummyA);
  1532. file.load(dummyB);
  1533. file.load(dummyC);
  1534. file.load(*this);
  1535. }
  1536. }
  1537. #if SCRIPTING_ENABLED
  1538. scripting::Pool * CGameState::getGlobalContextPool() const
  1539. {
  1540. return nullptr; // TODO
  1541. }
  1542. #endif
  1543. void CGameState::saveCompatibilityRegisterMissingArtifacts()
  1544. {
  1545. for( const auto & newArtifact : saveCompatibilityUnregisteredArtifacts)
  1546. map->saveCompatibilityAddMissingArtifact(newArtifact);
  1547. saveCompatibilityUnregisteredArtifacts.clear();
  1548. }
  1549. VCMI_LIB_NAMESPACE_END