CGameState.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  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/CCastleEvent.h"
  52. #include "../mapping/CMap.h"
  53. #include "../mapping/CMapEditManager.h"
  54. #include "../mapping/CMapService.h"
  55. #include "../modding/ActiveModsInSaveList.h"
  56. #include "../modding/IdentifierStorage.h"
  57. #include "../modding/ModScope.h"
  58. #include "../networkPacks/NetPacksBase.h"
  59. #include "../pathfinder/CPathfinder.h"
  60. #include "../pathfinder/PathfinderOptions.h"
  61. #include "../rmg/CMapGenerator.h"
  62. #include "../serializer/CMemorySerializer.h"
  63. #include "../serializer/CLoadFile.h"
  64. #include "../serializer/CSaveFile.h"
  65. #include "../spells/CSpellHandler.h"
  66. #include "UpgradeInfo.h"
  67. #include <vstd/RNG.h>
  68. VCMI_LIB_NAMESPACE_BEGIN
  69. std::shared_mutex CGameState::mutex;
  70. HeroTypeID CGameState::pickNextHeroType(vstd::RNG & randomGenerator, const PlayerColor & owner)
  71. {
  72. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  73. if(ps.hero.isValid() && !isUsedHero(HeroTypeID(ps.hero))) //we haven't used selected hero
  74. {
  75. return HeroTypeID(ps.hero);
  76. }
  77. return pickUnusedHeroTypeRandomly(randomGenerator, owner);
  78. }
  79. HeroTypeID CGameState::pickUnusedHeroTypeRandomly(vstd::RNG & randomGenerator, const PlayerColor & owner)
  80. {
  81. //list of available heroes for this faction and others
  82. std::vector<HeroTypeID> factionHeroes;
  83. std::vector<HeroTypeID> otherHeroes;
  84. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  85. for(const HeroTypeID & hid : getUnusedAllowedHeroes())
  86. {
  87. if(hid.toHeroType()->heroClass->faction == ps.castle)
  88. factionHeroes.push_back(hid);
  89. else
  90. otherHeroes.push_back(hid);
  91. }
  92. // select random hero native to "our" faction
  93. if(!factionHeroes.empty())
  94. {
  95. return *RandomGeneratorUtil::nextItem(factionHeroes, randomGenerator);
  96. }
  97. logGlobal->warn("Cannot find free hero of appropriate faction for player %s - trying to get first available...", owner.toString());
  98. if(!otherHeroes.empty())
  99. {
  100. return *RandomGeneratorUtil::nextItem(otherHeroes, randomGenerator);
  101. }
  102. logGlobal->error("No free allowed heroes!");
  103. auto notAllowedHeroesButStillBetterThanCrash = getUnusedAllowedHeroes(true);
  104. if(!notAllowedHeroesButStillBetterThanCrash.empty())
  105. return *notAllowedHeroesButStillBetterThanCrash.begin();
  106. logGlobal->error("No free heroes at all!");
  107. throw std::runtime_error("Can not allocate hero. All heroes are already used.");
  108. }
  109. int CGameState::getDate(int d, Date mode)
  110. {
  111. int temp;
  112. switch (mode)
  113. {
  114. case Date::DAY:
  115. return d;
  116. case Date::DAY_OF_WEEK: //day of week
  117. temp = (d)%7; // 1 - Monday, 7 - Sunday
  118. return temp ? temp : 7;
  119. case Date::WEEK: //current week
  120. temp = ((d-1)/7)+1;
  121. if (!(temp%4))
  122. return 4;
  123. else
  124. return (temp%4);
  125. case Date::MONTH: //current month
  126. return ((d-1)/28)+1;
  127. case Date::DAY_OF_MONTH: //day of month
  128. temp = (d)%28;
  129. if (temp)
  130. return temp;
  131. else return 28;
  132. }
  133. return 0;
  134. }
  135. int CGameState::getDate(Date mode) const
  136. {
  137. return getDate(day, mode);
  138. }
  139. CGameState::CGameState()
  140. :globalEffects(BonusNodeType::GLOBAL_EFFECTS)
  141. {
  142. heroesPool = std::make_unique<TavernHeroesPool>(this);
  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. scenarioOps = CMemorySerializer::deepCopy(*si);
  161. initialOpts = CMemorySerializer::deepCopy(*si);
  162. si = nullptr;
  163. auto & randomGenerator = gameRandomizer.getDefault();
  164. switch(scenarioOps->mode)
  165. {
  166. case EStartMode::NEW_GAME:
  167. initNewGame(mapService, randomGenerator, allowSavingRandomMap, progressTracking);
  168. break;
  169. case EStartMode::CAMPAIGN:
  170. initCampaign();
  171. break;
  172. default:
  173. logGlobal->error("Wrong mode: %d", static_cast<int>(scenarioOps->mode));
  174. return;
  175. }
  176. logGlobal->info("Map loaded!");
  177. day = 0;
  178. logGlobal->debug("Initialization:");
  179. initGlobalBonuses();
  180. initPlayerStates();
  181. if (campaign)
  182. campaign->placeCampaignHeroes(randomGenerator);
  183. removeHeroPlaceholders();
  184. initGrailPosition(randomGenerator);
  185. initRandomFactionsForPlayers(randomGenerator);
  186. randomizeMapObjects(gameRandomizer);
  187. placeStartingHeroes(randomGenerator);
  188. initOwnedObjects();
  189. initDifficulty();
  190. initHeroes(gameRandomizer);
  191. initStartingBonus(gameRandomizer);
  192. initTowns(randomGenerator);
  193. initTownNames(randomGenerator);
  194. placeHeroesInTowns();
  195. initMapObjects(gameRandomizer);
  196. buildBonusSystemTree();
  197. initVisitingAndGarrisonedHeroes();
  198. initFogOfWar();
  199. for(auto & elem : teams)
  200. {
  201. map->obelisksVisited[elem.first] = 0;
  202. }
  203. logGlobal->debug("\tChecking objectives");
  204. map->checkForObjectives(); //needs to be run when all objects are properly placed
  205. }
  206. void CGameState::updateEntity(Metatype metatype, int32_t index, const JsonNode & data)
  207. {
  208. switch(metatype)
  209. {
  210. case Metatype::ARTIFACT_INSTANCE:
  211. logGlobal->error("Artifact instance update is not implemented");
  212. break;
  213. case Metatype::CREATURE_INSTANCE:
  214. logGlobal->error("Creature instance update is not implemented");
  215. break;
  216. case Metatype::HERO_INSTANCE:
  217. {
  218. //index is hero type
  219. HeroTypeID heroID(index);
  220. auto heroOnMap = map->getHero(heroID);
  221. auto heroInPool = map->tryGetFromHeroPool(heroID);
  222. if(heroOnMap)
  223. {
  224. heroOnMap->updateFrom(data);
  225. }
  226. else if (heroInPool)
  227. {
  228. heroInPool->updateFrom(data);
  229. }
  230. else
  231. {
  232. logGlobal->error("Update entity: hero index %s is out of range", index);
  233. }
  234. break;
  235. }
  236. case Metatype::MAP_OBJECT_INSTANCE:
  237. {
  238. CGObjectInstance * obj = getObjInstance(ObjectInstanceID(index));
  239. if(obj)
  240. {
  241. obj->updateFrom(data);
  242. }
  243. else
  244. {
  245. logGlobal->error("Update entity: object index %s is out of range", index);
  246. }
  247. break;
  248. }
  249. default:
  250. logGlobal->error("This metatype update is not implemented");
  251. break;
  252. }
  253. }
  254. void CGameState::updateOnLoad(const StartInfo & si)
  255. {
  256. assert(services);
  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, this, 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, this);
  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.resolveFromJson(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(IGameRandomizer & gameRandomizer)
  430. {
  431. logGlobal->debug("\tRandomizing objects");
  432. for(const auto & object : map->getObjects())
  433. {
  434. object->pickRandomObject(gameRandomizer);
  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, this);
  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(this, handler->getTemplates().front());
  487. hero = std::dynamic_pointer_cast<CGHeroInstance>(object);
  488. hero->ID = Obj::HERO;
  489. hero->setHeroType(heroTypeId);
  490. assert(hero->appearance != nullptr);
  491. }
  492. hero->tempOwner = playerColor;
  493. hero->setAnchorPos(townPos + hero->getVisitableOffset());
  494. map->getEditManager()->insertObject(hero);
  495. }
  496. void CGameState::placeStartingHeroes(vstd::RNG & randomGenerator)
  497. {
  498. logGlobal->debug("\tGiving starting hero");
  499. for(auto & playerSettingPair : scenarioOps->playerInfos)
  500. {
  501. auto playerColor = playerSettingPair.first;
  502. auto & playerInfo = map->players[playerColor.getNum()];
  503. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  504. {
  505. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  506. if (campaign && campaign->playerHasStartingHero(playerColor))
  507. continue;
  508. HeroTypeID heroTypeId = pickNextHeroType(randomGenerator, playerColor);
  509. if(playerSettingPair.second.hero == HeroTypeID::NONE || playerSettingPair.second.hero == HeroTypeID::RANDOM)
  510. playerSettingPair.second.hero = heroTypeId;
  511. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  512. }
  513. }
  514. }
  515. void CGameState::removeHeroPlaceholders()
  516. {
  517. // remove any hero placeholders that remain on map after (potential) campaign heroes placement
  518. for(auto obj : map->getObjects<CGHeroPlaceholder>())
  519. {
  520. map->eraseObject(obj->id);
  521. }
  522. }
  523. void CGameState::initHeroes(IGameRandomizer & gameRandomizer)
  524. {
  525. //heroes instances initialization
  526. for (auto heroID : map->getHeroesOnMap())
  527. {
  528. auto hero = getHero(heroID);
  529. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  530. {
  531. logGlobal->warn("Hero with uninitialized owner!");
  532. continue;
  533. }
  534. hero->initHero(gameRandomizer);
  535. hero->armyChanged();
  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(this, 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>(this);
  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. FowTilesType 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. for (const auto & townID : map->getAllTowns())
  690. {
  691. auto vti = getTown(townID);
  692. assert(vti->getTown()->creatures.size() <= GameConstants::CREATURES_PER_TOWN);
  693. constexpr std::array basicDwellings = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3, BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7, BuildingID::DWELL_LVL_8 };
  694. constexpr std::array upgradedDwellings = { BuildingID::DWELL_LVL_1_UP, BuildingID::DWELL_LVL_2_UP, BuildingID::DWELL_LVL_3_UP, BuildingID::DWELL_LVL_4_UP, BuildingID::DWELL_LVL_5_UP, BuildingID::DWELL_LVL_6_UP, BuildingID::DWELL_LVL_7_UP, BuildingID::DWELL_LVL_8_UP };
  695. constexpr std::array hordes = { BuildingID::HORDE_PLACEHOLDER1, BuildingID::HORDE_PLACEHOLDER2, BuildingID::HORDE_PLACEHOLDER3, BuildingID::HORDE_PLACEHOLDER4, BuildingID::HORDE_PLACEHOLDER5, BuildingID::HORDE_PLACEHOLDER6, BuildingID::HORDE_PLACEHOLDER7, BuildingID::HORDE_PLACEHOLDER8 };
  696. //init buildings
  697. if(vti->hasBuilt(BuildingID::DEFAULT)) //give standard set of buildings
  698. {
  699. vti->removeBuilding(BuildingID::DEFAULT);
  700. vti->addBuilding(BuildingID::VILLAGE_HALL);
  701. if(vti->tempOwner != PlayerColor::NEUTRAL)
  702. vti->addBuilding(BuildingID::TAVERN);
  703. auto definesBuildingsChances = getSettings().getVector(EGameSettings::TOWNS_STARTING_DWELLING_CHANCES);
  704. for(int i = 0; i < definesBuildingsChances.size(); i++)
  705. {
  706. if((randomGenerator.nextInt(1,100) <= definesBuildingsChances[i]))
  707. {
  708. vti->addBuilding(basicDwellings[i]);
  709. }
  710. }
  711. }
  712. // village hall must always exist
  713. vti->addBuilding(BuildingID::VILLAGE_HALL);
  714. //init hordes
  715. for (int i = 0; i < vti->getTown()->creatures.size(); i++)
  716. {
  717. if(vti->hasBuilt(hordes[i])) //if we have horde for this level
  718. {
  719. vti->removeBuilding(hordes[i]);//remove old ID
  720. if (vti->getTown()->hordeLvl.at(0) == i)//if town first horde is this one
  721. {
  722. vti->addBuilding(BuildingID::HORDE_1);//add it
  723. //if we have upgraded dwelling as well
  724. if(vti->hasBuilt(upgradedDwellings[i]))
  725. vti->addBuilding(BuildingID::HORDE_1_UPGR);//add it as well
  726. }
  727. if (vti->getTown()->hordeLvl.at(1) == i)//if town second horde is this one
  728. {
  729. vti->addBuilding(BuildingID::HORDE_2);
  730. if(vti->hasBuilt(upgradedDwellings[i]))
  731. vti->addBuilding(BuildingID::HORDE_2_UPGR);
  732. }
  733. }
  734. }
  735. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  736. //But DO NOT remove horde placeholders before they are replaced
  737. for(const auto & building : vti->getBuildings())
  738. {
  739. if(!vti->getTown()->buildings.count(building) || !vti->getTown()->buildings.at(building))
  740. vti->removeBuilding(building);
  741. }
  742. if(vti->hasBuilt(BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  743. vti->removeBuilding(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  744. //Early check for #1444-like problems
  745. for([[maybe_unused]] const auto & building : vti->getBuildings())
  746. {
  747. assert(vti->getTown()->buildings.at(building) != nullptr);
  748. }
  749. //town events
  750. for(CCastleEvent &ev : vti->events)
  751. {
  752. for (int i = 0; i<vti->getTown()->creatures.size(); i++)
  753. if (vstd::contains(ev.buildings,hordes[i])) //if we have horde for this level
  754. {
  755. ev.buildings.erase(hordes[i]);
  756. if (vti->getTown()->hordeLvl.at(0) == i)
  757. ev.buildings.insert(BuildingID::HORDE_1);
  758. if (vti->getTown()->hordeLvl.at(1) == i)
  759. ev.buildings.insert(BuildingID::HORDE_2);
  760. }
  761. }
  762. //init spells
  763. vti->spells.resize(GameConstants::SPELL_LEVELS);
  764. vti->possibleSpells -= SpellID::PRESET;
  765. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  766. {
  767. const auto * s = vti->obligatorySpells[z].toSpell();
  768. vti->spells[s->getLevel()-1].push_back(s->id);
  769. vti->possibleSpells -= s->id;
  770. }
  771. vstd::erase_if(vti->possibleSpells, [&](const SpellID & spellID)
  772. {
  773. const auto * spell = spellID.toSpell();
  774. if (spell->getProbability(vti->getFactionID()) == 0)
  775. return true;
  776. if (spell->isSpecial() || spell->isCreatureAbility())
  777. return true;
  778. if (!isAllowed(spellID))
  779. return true;
  780. return false;
  781. });
  782. std::vector<int> spellWeights;
  783. for (auto & spellID : vti->possibleSpells)
  784. spellWeights.push_back(spellID.toSpell()->getProbability(vti->getFactionID()));
  785. while(!vti->possibleSpells.empty())
  786. {
  787. size_t index = RandomGeneratorUtil::nextItemWeighted(spellWeights, randomGenerator);
  788. const auto * s = vti->possibleSpells[index].toSpell();
  789. vti->spells[s->getLevel()-1].push_back(s->id);
  790. vti->possibleSpells.erase(vti->possibleSpells.begin() + index);
  791. spellWeights.erase(spellWeights.begin() + index);
  792. }
  793. }
  794. }
  795. void CGameState::initMapObjects(IGameRandomizer & gameRandomizer)
  796. {
  797. logGlobal->debug("\tObject initialization");
  798. for(auto & obj : map->getObjects())
  799. obj->initObj(gameRandomizer);
  800. logGlobal->debug("\tObject initialization done");
  801. for(auto & q : map->getObjects<CGSeerHut>())
  802. {
  803. if (q->ID ==Obj::QUEST_GUARD || q->ID ==Obj::SEER_HUT)
  804. q->setObjToKill();
  805. }
  806. CGSubterraneanGate::postInit(this); //pairing subterranean gates
  807. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  808. }
  809. void CGameState::placeHeroesInTowns()
  810. {
  811. for(auto & player : players)
  812. {
  813. if(player.first == PlayerColor::NEUTRAL)
  814. continue;
  815. for(CGHeroInstance * h : player.second.getHeroes())
  816. {
  817. for(CGTownInstance * t : player.second.getTowns())
  818. {
  819. bool heroOnTownBlockableTile = t->blockingAt(h->visitablePos());
  820. // current hero position is at one of blocking tiles of current town
  821. // assume that this hero should be visiting the town (H3M format quirk) and move hero to correct position
  822. if (heroOnTownBlockableTile)
  823. {
  824. int3 correctedPos = h->convertFromVisitablePos(t->visitablePos());
  825. map->moveObject(h->id, correctedPos);
  826. assert(t->visitableAt(h->visitablePos()));
  827. }
  828. }
  829. }
  830. }
  831. }
  832. void CGameState::initVisitingAndGarrisonedHeroes()
  833. {
  834. for(auto & player : players)
  835. {
  836. if(player.first == PlayerColor::NEUTRAL)
  837. continue;
  838. //init visiting and garrisoned heroes
  839. for(CGHeroInstance * h : player.second.getHeroes())
  840. {
  841. for(CGTownInstance * t : player.second.getTowns())
  842. {
  843. if(h->visitablePos().z != t->visitablePos().z)
  844. continue;
  845. if (t->visitableAt(h->visitablePos()))
  846. {
  847. assert(t->getVisitingHero() == nullptr);
  848. t->setVisitingHero(h);
  849. }
  850. }
  851. }
  852. }
  853. for (auto heroID : map->getHeroesOnMap())
  854. {
  855. auto hero = getHero(heroID);
  856. if (hero->getVisitedTown())
  857. assert(hero->getVisitedTown()->getVisitingHero() == hero);
  858. }
  859. }
  860. const BattleInfo * CGameState::getBattle(const PlayerColor & player) const
  861. {
  862. if (!player.isValidPlayer())
  863. return nullptr;
  864. for (const auto & battlePtr : currentBattles)
  865. if (battlePtr->getSide(BattleSide::ATTACKER).color == player || battlePtr->getSide(BattleSide::DEFENDER).color == player)
  866. return battlePtr.get();
  867. return nullptr;
  868. }
  869. const BattleInfo * CGameState::getBattle(const BattleID & battle) const
  870. {
  871. for (const auto & battlePtr : currentBattles)
  872. if (battlePtr->battleID == battle)
  873. return battlePtr.get();
  874. return nullptr;
  875. }
  876. BattleInfo * CGameState::getBattle(const BattleID & battle)
  877. {
  878. for (const auto & battlePtr : currentBattles)
  879. if (battlePtr->battleID == battle)
  880. return battlePtr.get();
  881. return nullptr;
  882. }
  883. BattleField CGameState::battleGetBattlefieldType(int3 tile, vstd::RNG & randomGenerator) const
  884. {
  885. assert(tile.isValid());
  886. if(!tile.isValid())
  887. return BattleField::NONE;
  888. const TerrainTile &t = map->getTile(tile);
  889. ObjectInstanceID topObjectID = t.visitableObjects.front();
  890. const CGObjectInstance * topObject = getObjInstance(topObjectID);
  891. if(topObject && topObject->getBattlefield() != BattleField::NONE)
  892. {
  893. return topObject->getBattlefield();
  894. }
  895. for(auto & obj : map->getObjects())
  896. {
  897. //look only for objects covering given tile
  898. if( !obj->coveringAt(tile))
  899. continue;
  900. auto customBattlefield = obj->getBattlefield();
  901. if(customBattlefield != BattleField::NONE)
  902. return customBattlefield;
  903. }
  904. if(map->isCoastalTile(tile)) //coastal tile is always ground
  905. return BattleField(*LIBRARY->identifiers()->getIdentifier("core", "battlefield.sand_shore"));
  906. if (t.getTerrain()->battleFields.empty())
  907. throw std::runtime_error("Failed to find battlefield for terrain " + t.getTerrain()->getJsonKey());
  908. return BattleField(*RandomGeneratorUtil::nextItem(t.getTerrain()->battleFields, randomGenerator));
  909. }
  910. PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  911. {
  912. if ( color1 == color2 )
  913. return PlayerRelations::SAME_PLAYER;
  914. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  915. return PlayerRelations::ENEMIES;
  916. const TeamState * ts = getPlayerTeam(color1);
  917. if (ts && vstd::contains(ts->players, color2))
  918. return PlayerRelations::ALLIES;
  919. return PlayerRelations::ENEMIES;
  920. }
  921. void CGameState::apply(CPackForClient & pack)
  922. {
  923. GameStatePackVisitor visitor(*this);
  924. pack.visit(visitor);
  925. }
  926. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config) const
  927. {
  928. CPathfinder pathfinder(*this, config);
  929. pathfinder.calculatePaths();
  930. }
  931. /**
  932. * Tells if the tile is guarded by a monster as well as the position
  933. * of the monster that will attack on it.
  934. *
  935. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  936. * the monster guarding the tile.
  937. */
  938. std::vector<const CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  939. {
  940. std::vector<const CGObjectInstance*> guards;
  941. const int3 originalPos = pos;
  942. if (!map->isInTheMap(pos))
  943. return guards;
  944. const TerrainTile &posTile = map->getTile(pos);
  945. if (posTile.visitable())
  946. {
  947. for (ObjectInstanceID objectID : posTile.visitableObjects)
  948. {
  949. const CGObjectInstance * object = getObjInstance(objectID);
  950. if(object->isBlockedVisitable())
  951. {
  952. if (object->ID == Obj::MONSTER) // Monster
  953. guards.push_back(object);
  954. }
  955. }
  956. }
  957. pos -= int3(1, 1, 0); // Start with top left.
  958. for (int dx = 0; dx < 3; dx++)
  959. {
  960. for (int dy = 0; dy < 3; dy++)
  961. {
  962. if (map->isInTheMap(pos))
  963. {
  964. const auto & tile = map->getTile(pos);
  965. if (tile.visitable() && (tile.isWater() == posTile.isWater()))
  966. {
  967. for (ObjectInstanceID objectID : tile.visitableObjects)
  968. {
  969. const CGObjectInstance * object = getObjInstance(objectID);
  970. if (object->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  971. {
  972. guards.push_back(object);
  973. }
  974. }
  975. }
  976. }
  977. pos.y++;
  978. }
  979. pos.y -= 3;
  980. pos.x++;
  981. }
  982. return guards;
  983. }
  984. bool CGameState::isVisibleFor(int3 pos, PlayerColor player) const
  985. {
  986. if (!map->isInTheMap(pos))
  987. return false;
  988. if(player == PlayerColor::NEUTRAL)
  989. return false;
  990. if(player.isSpectator())
  991. return true;
  992. return getPlayerTeam(player)->fogOfWarMap[pos.z][pos.x][pos.y];
  993. }
  994. bool CGameState::isVisibleFor(const CGObjectInstance * obj, PlayerColor player) const
  995. {
  996. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  997. if (player == obj->tempOwner)
  998. return true;
  999. if(player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1000. return false;
  1001. //object is visible when at least one blocked tile is visible
  1002. for(int fy=0; fy < obj->getHeight(); ++fy)
  1003. {
  1004. for(int fx=0; fx < obj->getWidth(); ++fx)
  1005. {
  1006. int3 pos = obj->anchorPos() + int3(-fx, -fy, 0);
  1007. if ( map->isInTheMap(pos) &&
  1008. obj->coveringAt(pos) &&
  1009. isVisibleFor(pos, player))
  1010. return true;
  1011. }
  1012. }
  1013. return false;
  1014. }
  1015. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  1016. {
  1017. const MetaString messageWonSelf = MetaString::createFromTextID("core.genrltxt.659");
  1018. const MetaString messageWonOther = MetaString::createFromTextID("core.genrltxt.5");
  1019. const MetaString messageLostSelf = MetaString::createFromTextID("core.genrltxt.7");
  1020. const MetaString messageLostOther = MetaString::createFromTextID("core.genrltxt.8");
  1021. auto evaluateEvent = [this, player](const EventCondition & condition)
  1022. {
  1023. return this->checkForVictory(player, condition);
  1024. };
  1025. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1026. //cheater or tester, but has entered the code...
  1027. if (p->enteredWinningCheatCode)
  1028. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1029. if (p->enteredLosingCheatCode)
  1030. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1031. for (const TriggeredEvent & event : map->triggeredEvents)
  1032. {
  1033. if (event.trigger.test(evaluateEvent))
  1034. {
  1035. if (event.effect.type == EventEffect::VICTORY)
  1036. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1037. if (event.effect.type == EventEffect::DEFEAT)
  1038. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1039. }
  1040. }
  1041. if (checkForStandardLoss(player))
  1042. {
  1043. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1044. }
  1045. return EVictoryLossCheckResult();
  1046. }
  1047. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  1048. {
  1049. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1050. switch (condition.condition)
  1051. {
  1052. case EventCondition::STANDARD_WIN:
  1053. {
  1054. return player == checkForStandardWin();
  1055. }
  1056. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1057. {
  1058. for(const auto & elem : p->getHeroes())
  1059. if(elem->hasArt(condition.objectType.as<ArtifactID>()))
  1060. return true;
  1061. return false;
  1062. }
  1063. case EventCondition::HAVE_CREATURES:
  1064. {
  1065. //check if in players armies there is enough creatures
  1066. int total = 0; //creature counter
  1067. for(auto ai : map->getObjects<CArmedInstance>())
  1068. {
  1069. if(ai->getOwner() == player)
  1070. {
  1071. for(const auto & elem : ai->Slots()) //iterate through army
  1072. if(elem.second->getId() == condition.objectType.as<CreatureID>()) //it's searched creature
  1073. total += elem.second->getCount();
  1074. }
  1075. }
  1076. return total >= condition.value;
  1077. }
  1078. case EventCondition::HAVE_RESOURCES:
  1079. {
  1080. return p->resources[condition.objectType.as<GameResID>()] >= condition.value;
  1081. }
  1082. case EventCondition::HAVE_BUILDING:
  1083. {
  1084. if (condition.objectID != ObjectInstanceID::NONE) // specific town
  1085. {
  1086. const auto * t = getTown(condition.objectID);
  1087. return (t->tempOwner == player && t->hasBuilt(condition.objectType.as<BuildingID>()));
  1088. }
  1089. else // any town
  1090. {
  1091. for (const CGTownInstance * t : p->getTowns())
  1092. {
  1093. if (t->hasBuilt(condition.objectType.as<BuildingID>()))
  1094. return true;
  1095. }
  1096. return false;
  1097. }
  1098. }
  1099. case EventCondition::DESTROY:
  1100. {
  1101. if (condition.objectID != ObjectInstanceID::NONE) // mode A - destroy specific object of this type
  1102. {
  1103. return p->destroyedObjects.count(condition.objectID);
  1104. }
  1105. else
  1106. {
  1107. for(const auto & elem : map->getObjects()) // mode B - destroy all objects of this type
  1108. {
  1109. if(elem && elem->ID == condition.objectType.as<MapObjectID>())
  1110. return false;
  1111. }
  1112. return true;
  1113. }
  1114. }
  1115. case EventCondition::CONTROL:
  1116. {
  1117. // list of players that need to control object to fulfull condition
  1118. // NOTE: CGameInfoCallback specified explicitly in order to get const version
  1119. const auto * team = CGameInfoCallback::getPlayerTeam(player);
  1120. if (condition.objectID != ObjectInstanceID::NONE) // mode A - flag one specific object, like town
  1121. {
  1122. const auto * object = getObjInstance(condition.objectID);
  1123. if (!object)
  1124. return false;
  1125. return team->players.count(object->getOwner()) != 0;
  1126. }
  1127. else
  1128. {
  1129. for(const auto & elem : map->getObjects()) // mode B - flag all objects of this type
  1130. {
  1131. //check not flagged objs
  1132. if ( elem && elem->ID == condition.objectType.as<MapObjectID>() && team->players.count(elem->getOwner()) == 0 )
  1133. return false;
  1134. }
  1135. return true;
  1136. }
  1137. }
  1138. case EventCondition::TRANSPORT:
  1139. {
  1140. const auto * t = getTown(condition.objectID);
  1141. bool garrisonedWon = t->getGarrisonHero() && t->getGarrisonHero()->getOwner() == player && t->getGarrisonHero()->hasArt(condition.objectType.as<ArtifactID>());
  1142. bool visitingWon = t->getVisitingHero() && t->getVisitingHero()->getOwner() == player && t->getVisitingHero()->hasArt(condition.objectType.as<ArtifactID>());
  1143. return garrisonedWon || visitingWon;
  1144. }
  1145. case EventCondition::DAYS_PASSED:
  1146. {
  1147. return day > condition.value;
  1148. }
  1149. case EventCondition::IS_HUMAN:
  1150. {
  1151. return p->human ? condition.value == 1 : condition.value == 0;
  1152. }
  1153. case EventCondition::DAYS_WITHOUT_TOWN:
  1154. {
  1155. if (p->daysWithoutCastle)
  1156. return p->daysWithoutCastle >= condition.value;
  1157. else
  1158. return false;
  1159. }
  1160. case EventCondition::CONST_VALUE:
  1161. {
  1162. return condition.value; // just convert to bool
  1163. }
  1164. default:
  1165. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1166. return false;
  1167. }
  1168. }
  1169. PlayerColor CGameState::checkForStandardWin() const
  1170. {
  1171. //std victory condition is:
  1172. //all enemies lost
  1173. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  1174. TeamID winnerTeam = TeamID::NO_TEAM;
  1175. for(const auto & elem : players)
  1176. {
  1177. if(elem.second.status == EPlayerStatus::WINNER)
  1178. return elem.second.color;
  1179. if(elem.second.status == EPlayerStatus::INGAME && elem.first.isValidPlayer())
  1180. {
  1181. if(supposedWinner == PlayerColor::NEUTRAL)
  1182. {
  1183. //first player remaining ingame - candidate for victory
  1184. supposedWinner = elem.second.color;
  1185. winnerTeam = elem.second.team;
  1186. }
  1187. else if(winnerTeam != elem.second.team)
  1188. {
  1189. //current candidate has enemy remaining in game -> no vicotry
  1190. return PlayerColor::NEUTRAL;
  1191. }
  1192. }
  1193. }
  1194. return supposedWinner;
  1195. }
  1196. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  1197. {
  1198. //std loss condition is: player lost all towns and heroes
  1199. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  1200. return pState.checkVanquished();
  1201. }
  1202. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level) const
  1203. {
  1204. auto playerInactive = [&](const PlayerColor & color)
  1205. {
  1206. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  1207. };
  1208. #define FILL_FIELD(FIELD, VAL_GETTER) \
  1209. { \
  1210. std::vector< std::pair< PlayerColor, si64 > > stats; \
  1211. for(auto g = players.begin(); g != players.end(); ++g) \
  1212. { \
  1213. if(playerInactive(g->second.color)) \
  1214. continue; \
  1215. std::pair< PlayerColor, si64 > stat; \
  1216. stat.first = g->second.color; \
  1217. stat.second = VAL_GETTER; \
  1218. stats.push_back(stat); \
  1219. } \
  1220. tgi.FIELD = Statistic::getRank(stats); \
  1221. }
  1222. for(auto & elem : players)
  1223. {
  1224. if(!playerInactive(elem.second.color))
  1225. tgi.playerColors.push_back(elem.second.color);
  1226. }
  1227. if(level >= 0) //num of towns & num of heroes
  1228. {
  1229. //num of towns
  1230. FILL_FIELD(numOfTowns, g->second.getTowns().size())
  1231. //num of heroes
  1232. FILL_FIELD(numOfHeroes, g->second.getHeroes().size())
  1233. }
  1234. if(level >= 1) //best hero's portrait
  1235. {
  1236. for(const auto & player : players)
  1237. {
  1238. if(playerInactive(player.second.color))
  1239. continue;
  1240. const CGHeroInstance * best = Statistic::findBestHero(this, player.second.color);
  1241. InfoAboutHero iah;
  1242. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  1243. iah.army.clear();
  1244. tgi.colorToBestHero[player.second.color] = iah;
  1245. }
  1246. }
  1247. if(level >= 2) //gold
  1248. {
  1249. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  1250. }
  1251. if(level >= 2) //wood & ore
  1252. {
  1253. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  1254. }
  1255. if(level >= 3) //mercury, sulfur, crystal, gems
  1256. {
  1257. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  1258. }
  1259. if(level >= 3) //obelisks found
  1260. {
  1261. FILL_FIELD(obelisks, Statistic::getObeliskVisited(this, getPlayerTeam(g->second.color)->id))
  1262. }
  1263. if(level >= 4) //artifacts
  1264. {
  1265. FILL_FIELD(artifacts, Statistic::getNumberOfArts(&g->second))
  1266. }
  1267. if(level >= 4) //army strength
  1268. {
  1269. FILL_FIELD(army, Statistic::getArmyStrength(&g->second))
  1270. }
  1271. if(level >= 5) //income
  1272. {
  1273. FILL_FIELD(income, Statistic::getIncome(this, &g->second))
  1274. }
  1275. if(level >= 2) //best hero's stats
  1276. {
  1277. //already set in lvl 1 handling
  1278. }
  1279. if(level >= 3) //personality
  1280. {
  1281. for(const auto & player : players)
  1282. {
  1283. if(playerInactive(player.second.color)) //do nothing for neutral player
  1284. continue;
  1285. if(player.second.human)
  1286. {
  1287. tgi.personality[player.second.color] = EAiTactic::NONE;
  1288. }
  1289. else //AI
  1290. {
  1291. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  1292. }
  1293. }
  1294. }
  1295. if(level >= 4) //best creature
  1296. {
  1297. //best creatures belonging to player (highest AI value)
  1298. for(const auto & player : players)
  1299. {
  1300. if(playerInactive(player.second.color)) //do nothing for neutral player
  1301. continue;
  1302. CreatureID bestCre; //best creature's ID
  1303. for(const auto & elem : player.second.getHeroes())
  1304. {
  1305. for(const auto & it : elem->Slots())
  1306. {
  1307. CreatureID toCmp = it.second->getId(); //ID of creature we should compare with the best one
  1308. if(bestCre == CreatureID::NONE || bestCre.toEntity(LIBRARY)->getAIValue() < toCmp.toEntity(LIBRARY)->getAIValue())
  1309. {
  1310. bestCre = toCmp;
  1311. }
  1312. }
  1313. }
  1314. tgi.bestCreature[player.second.color] = bestCre;
  1315. }
  1316. }
  1317. #undef FILL_FIELD
  1318. }
  1319. void CGameState::buildBonusSystemTree()
  1320. {
  1321. buildGlobalTeamPlayerTree();
  1322. for(auto & armed : map->getObjects<CGObjectInstance>())
  1323. armed->attachToBonusSystem(*this);
  1324. }
  1325. void CGameState::restoreBonusSystemTree()
  1326. {
  1327. heroesPool->setGameState(this);
  1328. buildGlobalTeamPlayerTree();
  1329. for(auto & armed : map->getObjects<CGObjectInstance>())
  1330. armed->restoreBonusSystem(*this);
  1331. for(auto & art : map->getArtifacts())
  1332. art->attachToBonusSystem(*this);
  1333. for(auto & heroID : map->getHeroesInPool())
  1334. map->tryGetFromHeroPool(heroID)->artDeserializationFix(*this, map->tryGetFromHeroPool(heroID));
  1335. if (campaign)
  1336. campaign->setGamestate(this);
  1337. }
  1338. void CGameState::buildGlobalTeamPlayerTree()
  1339. {
  1340. for(auto & team : teams)
  1341. {
  1342. TeamState * t = &team.second;
  1343. t->attachTo(globalEffects);
  1344. for(const PlayerColor & teamMember : team.second.players)
  1345. {
  1346. PlayerState *p = getPlayerState(teamMember);
  1347. assert(p);
  1348. p->attachTo(*t);
  1349. }
  1350. }
  1351. }
  1352. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  1353. {
  1354. CArtifactInstance * ai = createArtifact(aid);
  1355. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  1356. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1357. {
  1358. map->putArtifactInstance(*h, ai->getId(), slot);
  1359. return true;
  1360. }
  1361. else
  1362. {
  1363. return false;
  1364. }
  1365. }
  1366. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  1367. {
  1368. std::set<HeroTypeID> ret = map->allowedHeroes;
  1369. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  1370. {
  1371. if(playerSettingPair.second.hero != HeroTypeID::RANDOM)
  1372. ret -= HeroTypeID(playerSettingPair.second.hero);
  1373. }
  1374. for (auto heroID : map->getHeroesOnMap())
  1375. ret -= getHero(heroID)->getHeroTypeID();
  1376. return ret;
  1377. }
  1378. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  1379. {
  1380. return getUsedHero(hid);
  1381. }
  1382. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  1383. {
  1384. for(auto hero : map->getObjects<CGHeroInstance>()) //prisons
  1385. {
  1386. if (hero->getHeroTypeID() == hid)
  1387. return hero;
  1388. }
  1389. return nullptr;
  1390. }
  1391. TeamState::TeamState()
  1392. :CBonusSystemNode(BonusNodeType::TEAM)
  1393. {}
  1394. CArtifactInstance * CGameState::createScroll(const SpellID & spellId)
  1395. {
  1396. return map->createScroll(spellId);
  1397. }
  1398. CArtifactInstance * CGameState::createArtifact(const ArtifactID & artID, const SpellID & spellId)
  1399. {
  1400. return map->createArtifact(artID, spellId);
  1401. }
  1402. void CGameState::saveGame(CSaveFile & file) const
  1403. {
  1404. ActiveModsInSaveList activeModsDummy;
  1405. logGlobal->info("Saving game state");
  1406. file.save(*getMapHeader());
  1407. file.save(*getStartInfo());
  1408. file.save(activeModsDummy);
  1409. file.save(*this);
  1410. }
  1411. void CGameState::loadGame(CLoadFile & file)
  1412. {
  1413. logGlobal->info("Loading game state...");
  1414. CMapHeader dummyHeader;
  1415. StartInfo dummyStartInfo;
  1416. ActiveModsInSaveList dummyActiveMods;
  1417. file.load(dummyHeader);
  1418. if (file.hasFeature(ESerializationVersion::NO_RAW_POINTERS_IN_SERIALIZER))
  1419. {
  1420. file.load(dummyStartInfo);
  1421. file.load(dummyActiveMods);
  1422. file.load(*this);
  1423. }
  1424. else
  1425. {
  1426. bool dummyA = false;
  1427. uint32_t dummyB = 0;
  1428. uint16_t dummyC = 0;
  1429. file.load(dummyStartInfo);
  1430. file.load(dummyActiveMods);
  1431. file.load(dummyA);
  1432. file.load(dummyB);
  1433. file.load(dummyC);
  1434. file.load(*this);
  1435. }
  1436. }
  1437. #if SCRIPTING_ENABLED
  1438. scripting::Pool * CGameState::getGlobalContextPool() const
  1439. {
  1440. return nullptr; // TODO
  1441. }
  1442. #endif
  1443. void CGameState::saveCompatibilityRegisterMissingArtifacts()
  1444. {
  1445. for( const auto & newArtifact : saveCompatibilityUnregisteredArtifacts)
  1446. map->saveCompatibilityAddMissingArtifact(newArtifact);
  1447. saveCompatibilityUnregisteredArtifacts.clear();
  1448. }
  1449. VCMI_LIB_NAMESPACE_END