CGameState.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
  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. // NOTE: only heroes & towns are checked, in line with H3.
  1067. // Garrisons, mines, and guards of owned dwellings(!) are excluded
  1068. int totalCreatures = 0;
  1069. for (const auto & hero : p->getHeroes())
  1070. for(const auto & elem : hero->Slots()) //iterate through army
  1071. if(elem.second->getId() == condition.objectType.as<CreatureID>()) //it's searched creature
  1072. totalCreatures += elem.second->getCount();
  1073. for (const auto & town : p->getTowns())
  1074. for(const auto & elem : town->Slots()) //iterate through army
  1075. if(elem.second->getId() == condition.objectType.as<CreatureID>()) //it's searched creature
  1076. totalCreatures += elem.second->getCount();
  1077. return totalCreatures >= condition.value;
  1078. }
  1079. case EventCondition::HAVE_RESOURCES:
  1080. {
  1081. return p->resources[condition.objectType.as<GameResID>()] >= condition.value;
  1082. }
  1083. case EventCondition::HAVE_BUILDING:
  1084. {
  1085. if (condition.objectID != ObjectInstanceID::NONE) // specific town
  1086. {
  1087. const auto * t = getTown(condition.objectID);
  1088. return (t->tempOwner == player && t->hasBuilt(condition.objectType.as<BuildingID>()));
  1089. }
  1090. else // any town
  1091. {
  1092. for (const CGTownInstance * t : p->getTowns())
  1093. {
  1094. if (t->hasBuilt(condition.objectType.as<BuildingID>()))
  1095. return true;
  1096. }
  1097. return false;
  1098. }
  1099. }
  1100. case EventCondition::DESTROY:
  1101. {
  1102. if (condition.objectID != ObjectInstanceID::NONE) // mode A - destroy specific object of this type
  1103. {
  1104. return p->destroyedObjects.count(condition.objectID);
  1105. }
  1106. else
  1107. {
  1108. for(const auto & elem : map->getObjects()) // mode B - destroy all objects of this type
  1109. {
  1110. if(elem && elem->ID == condition.objectType.as<MapObjectID>())
  1111. return false;
  1112. }
  1113. return true;
  1114. }
  1115. }
  1116. case EventCondition::CONTROL:
  1117. {
  1118. // list of players that need to control object to fulfull condition
  1119. // NOTE: CGameInfoCallback specified explicitly in order to get const version
  1120. const auto * team = CGameInfoCallback::getPlayerTeam(player);
  1121. if (condition.objectID != ObjectInstanceID::NONE) // mode A - flag one specific object, like town
  1122. {
  1123. const auto * object = getObjInstance(condition.objectID);
  1124. if (!object)
  1125. return false;
  1126. return team->players.count(object->getOwner()) != 0;
  1127. }
  1128. else
  1129. {
  1130. for(const auto & elem : map->getObjects()) // mode B - flag all objects of this type
  1131. {
  1132. //check not flagged objs
  1133. if ( elem && elem->ID == condition.objectType.as<MapObjectID>() && team->players.count(elem->getOwner()) == 0 )
  1134. return false;
  1135. }
  1136. return true;
  1137. }
  1138. }
  1139. case EventCondition::TRANSPORT:
  1140. {
  1141. const auto * t = getTown(condition.objectID);
  1142. bool garrisonedWon = t->getGarrisonHero() && t->getGarrisonHero()->getOwner() == player && t->getGarrisonHero()->hasArt(condition.objectType.as<ArtifactID>());
  1143. bool visitingWon = t->getVisitingHero() && t->getVisitingHero()->getOwner() == player && t->getVisitingHero()->hasArt(condition.objectType.as<ArtifactID>());
  1144. return garrisonedWon || visitingWon;
  1145. }
  1146. case EventCondition::DAYS_PASSED:
  1147. {
  1148. return day > condition.value;
  1149. }
  1150. case EventCondition::IS_HUMAN:
  1151. {
  1152. return p->human ? condition.value == 1 : condition.value == 0;
  1153. }
  1154. case EventCondition::DAYS_WITHOUT_TOWN:
  1155. {
  1156. if (p->daysWithoutCastle)
  1157. return p->daysWithoutCastle >= condition.value;
  1158. else
  1159. return false;
  1160. }
  1161. case EventCondition::CONST_VALUE:
  1162. {
  1163. return condition.value; // just convert to bool
  1164. }
  1165. default:
  1166. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1167. return false;
  1168. }
  1169. }
  1170. PlayerColor CGameState::checkForStandardWin() const
  1171. {
  1172. //std victory condition is:
  1173. //all enemies lost
  1174. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  1175. TeamID winnerTeam = TeamID::NO_TEAM;
  1176. for(const auto & elem : players)
  1177. {
  1178. if(elem.second.status == EPlayerStatus::WINNER)
  1179. return elem.second.color;
  1180. if(elem.second.status == EPlayerStatus::INGAME && elem.first.isValidPlayer())
  1181. {
  1182. if(supposedWinner == PlayerColor::NEUTRAL)
  1183. {
  1184. //first player remaining ingame - candidate for victory
  1185. supposedWinner = elem.second.color;
  1186. winnerTeam = elem.second.team;
  1187. }
  1188. else if(winnerTeam != elem.second.team)
  1189. {
  1190. //current candidate has enemy remaining in game -> no vicotry
  1191. return PlayerColor::NEUTRAL;
  1192. }
  1193. }
  1194. }
  1195. return supposedWinner;
  1196. }
  1197. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  1198. {
  1199. //std loss condition is: player lost all towns and heroes
  1200. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  1201. return pState.checkVanquished();
  1202. }
  1203. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level) const
  1204. {
  1205. auto playerInactive = [&](const PlayerColor & color)
  1206. {
  1207. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  1208. };
  1209. #define FILL_FIELD(FIELD, VAL_GETTER) \
  1210. { \
  1211. std::vector< std::pair< PlayerColor, si64 > > stats; \
  1212. for(auto g = players.begin(); g != players.end(); ++g) \
  1213. { \
  1214. if(playerInactive(g->second.color)) \
  1215. continue; \
  1216. std::pair< PlayerColor, si64 > stat; \
  1217. stat.first = g->second.color; \
  1218. stat.second = VAL_GETTER; \
  1219. stats.push_back(stat); \
  1220. } \
  1221. tgi.FIELD = Statistic::getRank(stats); \
  1222. }
  1223. for(auto & elem : players)
  1224. {
  1225. if(!playerInactive(elem.second.color))
  1226. tgi.playerColors.push_back(elem.second.color);
  1227. }
  1228. if(level >= 0) //num of towns & num of heroes
  1229. {
  1230. //num of towns
  1231. FILL_FIELD(numOfTowns, g->second.getTowns().size())
  1232. //num of heroes
  1233. FILL_FIELD(numOfHeroes, g->second.getHeroes().size())
  1234. }
  1235. if(level >= 1) //best hero's portrait
  1236. {
  1237. for(const auto & player : players)
  1238. {
  1239. if(playerInactive(player.second.color))
  1240. continue;
  1241. const CGHeroInstance * best = Statistic::findBestHero(this, player.second.color);
  1242. InfoAboutHero iah;
  1243. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  1244. iah.army.clear();
  1245. tgi.colorToBestHero[player.second.color] = iah;
  1246. }
  1247. }
  1248. if(level >= 2) //gold
  1249. {
  1250. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  1251. }
  1252. if(level >= 2) //wood & ore
  1253. {
  1254. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  1255. }
  1256. if(level >= 3) //mercury, sulfur, crystal, gems
  1257. {
  1258. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  1259. }
  1260. if(level >= 3) //obelisks found
  1261. {
  1262. FILL_FIELD(obelisks, Statistic::getObeliskVisited(this, getPlayerTeam(g->second.color)->id))
  1263. }
  1264. if(level >= 4) //artifacts
  1265. {
  1266. FILL_FIELD(artifacts, Statistic::getNumberOfArts(&g->second))
  1267. }
  1268. if(level >= 4) //army strength
  1269. {
  1270. FILL_FIELD(army, Statistic::getArmyStrength(&g->second))
  1271. }
  1272. if(level >= 5) //income
  1273. {
  1274. FILL_FIELD(income, Statistic::getIncome(this, &g->second))
  1275. }
  1276. if(level >= 2) //best hero's stats
  1277. {
  1278. //already set in lvl 1 handling
  1279. }
  1280. if(level >= 3) //personality
  1281. {
  1282. for(const auto & player : players)
  1283. {
  1284. if(playerInactive(player.second.color)) //do nothing for neutral player
  1285. continue;
  1286. if(player.second.human)
  1287. {
  1288. tgi.personality[player.second.color] = EAiTactic::NONE;
  1289. }
  1290. else //AI
  1291. {
  1292. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  1293. }
  1294. }
  1295. }
  1296. if(level >= 4) //best creature
  1297. {
  1298. //best creatures belonging to player (highest AI value)
  1299. for(const auto & player : players)
  1300. {
  1301. if(playerInactive(player.second.color)) //do nothing for neutral player
  1302. continue;
  1303. CreatureID bestCre; //best creature's ID
  1304. for(const auto & elem : player.second.getHeroes())
  1305. {
  1306. for(const auto & it : elem->Slots())
  1307. {
  1308. CreatureID toCmp = it.second->getId(); //ID of creature we should compare with the best one
  1309. if(bestCre == CreatureID::NONE || bestCre.toEntity(LIBRARY)->getAIValue() < toCmp.toEntity(LIBRARY)->getAIValue())
  1310. {
  1311. bestCre = toCmp;
  1312. }
  1313. }
  1314. }
  1315. tgi.bestCreature[player.second.color] = bestCre;
  1316. }
  1317. }
  1318. #undef FILL_FIELD
  1319. }
  1320. void CGameState::buildBonusSystemTree()
  1321. {
  1322. buildGlobalTeamPlayerTree();
  1323. for(auto & armed : map->getObjects<CGObjectInstance>())
  1324. armed->attachToBonusSystem(*this);
  1325. }
  1326. void CGameState::restoreBonusSystemTree()
  1327. {
  1328. heroesPool->setGameState(this);
  1329. buildGlobalTeamPlayerTree();
  1330. for(auto & armed : map->getObjects<CGObjectInstance>())
  1331. armed->restoreBonusSystem(*this);
  1332. for(auto & art : map->getArtifacts())
  1333. art->attachToBonusSystem(*this);
  1334. for(auto & heroID : map->getHeroesInPool())
  1335. map->tryGetFromHeroPool(heroID)->artDeserializationFix(*this, map->tryGetFromHeroPool(heroID));
  1336. if (campaign)
  1337. campaign->setGamestate(this);
  1338. }
  1339. void CGameState::buildGlobalTeamPlayerTree()
  1340. {
  1341. for(auto & team : teams)
  1342. {
  1343. TeamState * t = &team.second;
  1344. t->attachTo(globalEffects);
  1345. for(const PlayerColor & teamMember : team.second.players)
  1346. {
  1347. PlayerState *p = getPlayerState(teamMember);
  1348. assert(p);
  1349. p->attachTo(*t);
  1350. }
  1351. }
  1352. }
  1353. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  1354. {
  1355. CArtifactInstance * ai = createArtifact(aid);
  1356. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  1357. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1358. {
  1359. map->putArtifactInstance(*h, ai->getId(), slot);
  1360. return true;
  1361. }
  1362. else
  1363. {
  1364. return false;
  1365. }
  1366. }
  1367. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  1368. {
  1369. std::set<HeroTypeID> ret = map->allowedHeroes;
  1370. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  1371. {
  1372. if(playerSettingPair.second.hero != HeroTypeID::RANDOM)
  1373. ret -= HeroTypeID(playerSettingPair.second.hero);
  1374. }
  1375. for (auto heroID : map->getHeroesOnMap())
  1376. ret -= getHero(heroID)->getHeroTypeID();
  1377. return ret;
  1378. }
  1379. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  1380. {
  1381. return getUsedHero(hid);
  1382. }
  1383. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  1384. {
  1385. for(auto hero : map->getObjects<CGHeroInstance>()) //prisons
  1386. {
  1387. if (hero->getHeroTypeID() == hid)
  1388. return hero;
  1389. }
  1390. return nullptr;
  1391. }
  1392. TeamState::TeamState()
  1393. :CBonusSystemNode(BonusNodeType::TEAM)
  1394. {}
  1395. CArtifactInstance * CGameState::createScroll(const SpellID & spellId)
  1396. {
  1397. return map->createScroll(spellId);
  1398. }
  1399. CArtifactInstance * CGameState::createArtifact(const ArtifactID & artID, const SpellID & spellId)
  1400. {
  1401. return map->createArtifact(artID, spellId);
  1402. }
  1403. void CGameState::saveGame(CSaveFile & file) const
  1404. {
  1405. ActiveModsInSaveList activeModsDummy;
  1406. logGlobal->info("Saving game state");
  1407. file.save(*getMapHeader());
  1408. file.save(*getStartInfo());
  1409. file.save(activeModsDummy);
  1410. file.save(*this);
  1411. }
  1412. void CGameState::loadGame(CLoadFile & file)
  1413. {
  1414. logGlobal->info("Loading game state...");
  1415. CMapHeader dummyHeader;
  1416. ActiveModsInSaveList dummyActiveMods;
  1417. file.load(dummyHeader);
  1418. if (file.hasFeature(ESerializationVersion::NO_RAW_POINTERS_IN_SERIALIZER))
  1419. {
  1420. StartInfo dummyStartInfo;
  1421. file.load(dummyStartInfo);
  1422. file.load(dummyActiveMods);
  1423. file.load(*this);
  1424. }
  1425. else
  1426. {
  1427. auto dummyStartInfo = std::make_shared<StartInfo>();
  1428. bool dummyA = false;
  1429. uint32_t dummyB = 0;
  1430. uint16_t dummyC = 0;
  1431. file.load(dummyStartInfo);
  1432. file.load(dummyActiveMods);
  1433. file.load(dummyA);
  1434. file.load(dummyB);
  1435. file.load(dummyC);
  1436. file.load(*this);
  1437. }
  1438. }
  1439. #if SCRIPTING_ENABLED
  1440. scripting::Pool * CGameState::getGlobalContextPool() const
  1441. {
  1442. return nullptr; // TODO
  1443. }
  1444. #endif
  1445. void CGameState::saveCompatibilityRegisterMissingArtifacts()
  1446. {
  1447. for( const auto & newArtifact : saveCompatibilityUnregisteredArtifacts)
  1448. map->saveCompatibilityAddMissingArtifact(newArtifact);
  1449. saveCompatibilityUnregisteredArtifacts.clear();
  1450. }
  1451. VCMI_LIB_NAMESPACE_END