CGameState.cpp 49 KB

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