2
0

CGameState.cpp 50 KB

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