CGameState.cpp 48 KB

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