CGameState.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800
  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 "../VCMI_Lib.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 <vstd/RNG.h>
  54. VCMI_LIB_NAMESPACE_BEGIN
  55. boost::shared_mutex CGameState::mutex;
  56. HeroTypeID CGameState::pickNextHeroType(const PlayerColor & owner)
  57. {
  58. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  59. if(ps.hero.isValid() && !isUsedHero(HeroTypeID(ps.hero))) //we haven't used selected hero
  60. {
  61. return HeroTypeID(ps.hero);
  62. }
  63. return pickUnusedHeroTypeRandomly(owner);
  64. }
  65. HeroTypeID CGameState::pickUnusedHeroTypeRandomly(const PlayerColor & owner)
  66. {
  67. //list of available heroes for this faction and others
  68. std::vector<HeroTypeID> factionHeroes;
  69. std::vector<HeroTypeID> otherHeroes;
  70. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  71. for(const HeroTypeID & hid : getUnusedAllowedHeroes())
  72. {
  73. if(hid.toHeroType()->heroClass->faction == ps.castle)
  74. factionHeroes.push_back(hid);
  75. else
  76. otherHeroes.push_back(hid);
  77. }
  78. // select random hero native to "our" faction
  79. if(!factionHeroes.empty())
  80. {
  81. return *RandomGeneratorUtil::nextItem(factionHeroes, getRandomGenerator());
  82. }
  83. logGlobal->warn("Cannot find free hero of appropriate faction for player %s - trying to get first available...", owner.toString());
  84. if(!otherHeroes.empty())
  85. {
  86. return *RandomGeneratorUtil::nextItem(otherHeroes, getRandomGenerator());
  87. }
  88. logGlobal->error("No free allowed heroes!");
  89. auto notAllowedHeroesButStillBetterThanCrash = getUnusedAllowedHeroes(true);
  90. if(!notAllowedHeroesButStillBetterThanCrash.empty())
  91. return *notAllowedHeroesButStillBetterThanCrash.begin();
  92. logGlobal->error("No free heroes at all!");
  93. throw std::runtime_error("Can not allocate hero. All heroes are already used.");
  94. }
  95. int CGameState::getDate(int d, Date mode)
  96. {
  97. int temp;
  98. switch (mode)
  99. {
  100. case Date::DAY:
  101. return d;
  102. case Date::DAY_OF_WEEK: //day of week
  103. temp = (d)%7; // 1 - Monday, 7 - Sunday
  104. return temp ? temp : 7;
  105. case Date::WEEK: //current week
  106. temp = ((d-1)/7)+1;
  107. if (!(temp%4))
  108. return 4;
  109. else
  110. return (temp%4);
  111. case Date::MONTH: //current month
  112. return ((d-1)/28)+1;
  113. case Date::DAY_OF_MONTH: //day of month
  114. temp = (d)%28;
  115. if (temp)
  116. return temp;
  117. else return 28;
  118. }
  119. return 0;
  120. }
  121. int CGameState::getDate(Date mode) const
  122. {
  123. return getDate(day, mode);
  124. }
  125. CGameState::CGameState()
  126. {
  127. gs = this;
  128. heroesPool = std::make_unique<TavernHeroesPool>();
  129. globalEffects.setNodeType(CBonusSystemNode::GLOBAL_EFFECTS);
  130. }
  131. CGameState::~CGameState()
  132. {
  133. // explicitly delete all ongoing battles first - BattleInfo destructor requires valid CGameState
  134. currentBattles.clear();
  135. map.dellNull();
  136. scenarioOps.dellNull();
  137. initialOpts.dellNull();
  138. }
  139. const IGameSettings & CGameState::getSettings() const
  140. {
  141. return map->getSettings();
  142. }
  143. void CGameState::preInit(Services * newServices, IGameCallback * newCallback)
  144. {
  145. services = newServices;
  146. callback = newCallback;
  147. }
  148. void CGameState::init(const IMapService * mapService, StartInfo * si, Load::ProgressAccumulator & progressTracking, bool allowSavingRandomMap)
  149. {
  150. assert(services);
  151. assert(callback);
  152. scenarioOps = CMemorySerializer::deepCopy(*si).release();
  153. initialOpts = CMemorySerializer::deepCopy(*si).release();
  154. si = nullptr;
  155. switch(scenarioOps->mode)
  156. {
  157. case EStartMode::NEW_GAME:
  158. initNewGame(mapService, allowSavingRandomMap, progressTracking);
  159. break;
  160. case EStartMode::CAMPAIGN:
  161. initCampaign();
  162. break;
  163. default:
  164. logGlobal->error("Wrong mode: %d", static_cast<int>(scenarioOps->mode));
  165. return;
  166. }
  167. logGlobal->info("Map loaded!");
  168. day = 0;
  169. logGlobal->debug("Initialization:");
  170. initGlobalBonuses();
  171. initPlayerStates();
  172. if (campaign)
  173. campaign->placeCampaignHeroes();
  174. removeHeroPlaceholders();
  175. initGrailPosition();
  176. initRandomFactionsForPlayers();
  177. randomizeMapObjects();
  178. placeStartingHeroes();
  179. initOwnedObjects();
  180. initDifficulty();
  181. initHeroes();
  182. initStartingBonus();
  183. initTowns();
  184. initTownNames();
  185. placeHeroesInTowns();
  186. initMapObjects();
  187. buildBonusSystemTree();
  188. initVisitingAndGarrisonedHeroes();
  189. initFogOfWar();
  190. for(auto & elem : teams)
  191. {
  192. map->obelisksVisited[elem.first] = 0;
  193. }
  194. logGlobal->debug("\tChecking objectives");
  195. map->checkForObjectives(); //needs to be run when all objects are properly placed
  196. }
  197. void CGameState::updateEntity(Metatype metatype, int32_t index, const JsonNode & data)
  198. {
  199. switch(metatype)
  200. {
  201. case Metatype::ARTIFACT_INSTANCE:
  202. logGlobal->error("Artifact instance update is not implemented");
  203. break;
  204. case Metatype::CREATURE_INSTANCE:
  205. logGlobal->error("Creature instance update is not implemented");
  206. break;
  207. case Metatype::HERO_INSTANCE:
  208. //index is hero type
  209. if(index >= 0 && index < map->allHeroes.size())
  210. {
  211. CGHeroInstance * hero = map->allHeroes.at(index);
  212. hero->updateFrom(data);
  213. }
  214. else
  215. {
  216. logGlobal->error("Update entity: hero index %s is out of range [%d,%d]", index, 0, map->allHeroes.size());
  217. }
  218. break;
  219. case Metatype::MAP_OBJECT_INSTANCE:
  220. if(index >= 0 && index < map->objects.size())
  221. {
  222. CGObjectInstance * obj = getObjInstance(ObjectInstanceID(index));
  223. obj->updateFrom(data);
  224. }
  225. else
  226. {
  227. logGlobal->error("Update entity: object index %s is out of range [%d,%d]", index, 0, map->objects.size());
  228. }
  229. break;
  230. default:
  231. logGlobal->error("This metatype update is not implemented");
  232. break;
  233. }
  234. }
  235. void CGameState::updateOnLoad(StartInfo * si)
  236. {
  237. assert(services);
  238. assert(callback);
  239. scenarioOps->playerInfos = si->playerInfos;
  240. for(auto & i : si->playerInfos)
  241. gs->players[i.first].human = i.second.isControlledByHuman();
  242. scenarioOps->extraOptionsInfo = si->extraOptionsInfo;
  243. scenarioOps->turnTimerInfo = si->turnTimerInfo;
  244. scenarioOps->simturnsInfo = si->simturnsInfo;
  245. }
  246. void CGameState::initNewGame(const IMapService * mapService, bool allowSavingRandomMap, Load::ProgressAccumulator & progressTracking)
  247. {
  248. if(scenarioOps->createRandomMap())
  249. {
  250. logGlobal->info("Create random map.");
  251. CStopWatch sw;
  252. // Gen map
  253. CMapGenerator mapGenerator(*scenarioOps->mapGenOptions, callback, getRandomGenerator().nextInt());
  254. progressTracking.include(mapGenerator);
  255. std::unique_ptr<CMap> randomMap = mapGenerator.generate();
  256. progressTracking.exclude(mapGenerator);
  257. // Update starting options
  258. for(int i = 0; i < randomMap->players.size(); ++i)
  259. {
  260. const auto & playerInfo = randomMap->players[i];
  261. if(playerInfo.canAnyonePlay())
  262. {
  263. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  264. playerSettings.compOnly = !playerInfo.canHumanPlay;
  265. playerSettings.castle = playerInfo.defaultCastle();
  266. if(playerSettings.isControlledByAI() && playerSettings.name.empty())
  267. {
  268. playerSettings.name = VLC->generaltexth->allTexts[468];
  269. }
  270. playerSettings.color = PlayerColor(i);
  271. }
  272. else
  273. {
  274. scenarioOps->playerInfos.erase(PlayerColor(i));
  275. }
  276. }
  277. if(allowSavingRandomMap)
  278. {
  279. try
  280. {
  281. auto path = VCMIDirs::get().userDataPath() / "Maps" / "RandomMaps";
  282. boost::filesystem::create_directories(path);
  283. std::shared_ptr<CMapGenOptions> options = scenarioOps->mapGenOptions;
  284. const std::string templateName = options->getMapTemplate()->getName();
  285. const std::string dt = vstd::getDateTimeISO8601Basic(std::time(nullptr));
  286. const std::string fileName = boost::str(boost::format("%s_%s.vmap") % dt % templateName );
  287. const auto fullPath = path / fileName;
  288. randomMap->name.appendRawString(boost::str(boost::format(" %s") % dt));
  289. mapService->saveMap(randomMap, fullPath);
  290. logGlobal->info("Random map has been saved to:");
  291. logGlobal->info(fullPath.string());
  292. }
  293. catch(...)
  294. {
  295. logGlobal->error("Saving random map failed with exception");
  296. }
  297. }
  298. map = randomMap.release();
  299. logGlobal->info("Generated random map in %i ms.", sw.getDiff());
  300. }
  301. else
  302. {
  303. logGlobal->info("Open map file: %s", scenarioOps->mapname);
  304. const ResourcePath mapURI(scenarioOps->mapname, EResType::MAP);
  305. map = mapService->loadMap(mapURI, callback).release();
  306. }
  307. }
  308. void CGameState::initCampaign()
  309. {
  310. campaign = std::make_unique<CGameStateCampaign>(this);
  311. map = campaign->getCurrentMap().release();
  312. }
  313. void CGameState::generateOwnedObjectsAfterDeserialize()
  314. {
  315. for (auto & object : map->objects)
  316. {
  317. if (object && object->asOwnable() && object->getOwner().isValidPlayer())
  318. players.at(object->getOwner()).addOwnedObject(object.get());
  319. }
  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. VLC->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->objects)
  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(CGObjectInstance *object : map->objects)
  424. {
  425. if(!object)
  426. continue;
  427. object->pickRandomObject(getRandomGenerator());
  428. //handle Favouring Winds - mark tiles under it
  429. if(object->ID == Obj::FAVORABLE_WINDS)
  430. {
  431. for (int i = 0; i < object->getWidth() ; i++)
  432. {
  433. for (int j = 0; j < object->getHeight() ; j++)
  434. {
  435. int3 pos = object->anchorPos() - int3(i,j,0);
  436. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  437. }
  438. }
  439. }
  440. }
  441. }
  442. void CGameState::initOwnedObjects()
  443. {
  444. for(CGObjectInstance *object : map->objects)
  445. {
  446. if (object && object->getOwner().isValidPlayer())
  447. getPlayerState(object->getOwner())->addOwnedObject(object);
  448. }
  449. }
  450. void CGameState::initPlayerStates()
  451. {
  452. logGlobal->debug("\tCreating player entries in gs");
  453. for(auto & elem : scenarioOps->playerInfos)
  454. {
  455. PlayerState & p = players[elem.first];
  456. p.color=elem.first;
  457. p.human = elem.second.isControlledByHuman();
  458. p.team = map->players[elem.first.getNum()].team;
  459. teams[p.team].id = p.team;//init team
  460. teams[p.team].players.insert(elem.first);//add player to team
  461. }
  462. }
  463. void CGameState::placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos)
  464. {
  465. for(auto town : map->towns)
  466. {
  467. if(town->anchorPos() == townPos)
  468. {
  469. townPos = town->visitablePos();
  470. break;
  471. }
  472. }
  473. auto handler = VLC->objtypeh->getHandlerFor(Obj::HERO, heroTypeId.toHeroType()->heroClass->getIndex());
  474. CGObjectInstance * obj = handler->create(callback, handler->getTemplates().front());
  475. CGHeroInstance * hero = dynamic_cast<CGHeroInstance *>(obj);
  476. hero->ID = Obj::HERO;
  477. hero->setHeroType(heroTypeId);
  478. hero->tempOwner = playerColor;
  479. hero->setAnchorPos(townPos + 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->getHeroTypeID().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.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->setAnchorPos(hero->anchorPos());
  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->getHeroTypeID().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->getHeroTypeID()))
  558. continue;
  559. ph->initHero(getRandomGenerator());
  560. heroesPool->addHeroToPool(ph);
  561. heroesToCreate.erase(ph->getHeroTypeID());
  562. map->allHeroes[ph->getHeroTypeID().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->getTown());
  662. if(!vti->getNameTextID().empty())
  663. continue;
  664. FactionID faction = vti->getFactionID();
  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->getTown());
  694. assert(vti->getTown()->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->getTown()->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->getFactionID());
  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->getFactionID());
  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. bool heroOnTownBlockableTile = t->blockingAt(h->visitablePos());
  839. // current hero position is at one of blocking tiles of current town
  840. // assume that this hero should be visiting the town (H3M format quirk) and move hero to correct position
  841. if (heroOnTownBlockableTile)
  842. {
  843. map->removeBlockVisTiles(h);
  844. int3 correctedPos = h->convertFromVisitablePos(t->visitablePos());
  845. h->setAnchorPos(correctedPos);
  846. map->addBlockVisTiles(h);
  847. assert(t->visitableAt(h->visitablePos()));
  848. }
  849. }
  850. }
  851. }
  852. }
  853. void CGameState::initVisitingAndGarrisonedHeroes()
  854. {
  855. for(auto & player : players)
  856. {
  857. if(player.first == PlayerColor::NEUTRAL)
  858. continue;
  859. //init visiting and garrisoned heroes
  860. for(CGHeroInstance * h : player.second.getHeroes())
  861. {
  862. for(CGTownInstance * t : player.second.getTowns())
  863. {
  864. if(h->visitablePos().z != t->visitablePos().z)
  865. continue;
  866. if (t->visitableAt(h->visitablePos()))
  867. {
  868. assert(t->visitingHero == nullptr);
  869. t->setVisitingHero(h);
  870. }
  871. }
  872. }
  873. }
  874. for (auto hero : map->heroesOnMap)
  875. {
  876. if (hero->visitedTown)
  877. {
  878. assert (hero->visitedTown->visitingHero == hero);
  879. }
  880. }
  881. }
  882. const BattleInfo * CGameState::getBattle(const PlayerColor & player) const
  883. {
  884. if (!player.isValidPlayer())
  885. return nullptr;
  886. for (const auto & battlePtr : currentBattles)
  887. if (battlePtr->getSide(BattleSide::ATTACKER).color == player || battlePtr->getSide(BattleSide::DEFENDER).color == player)
  888. return battlePtr.get();
  889. return nullptr;
  890. }
  891. const BattleInfo * CGameState::getBattle(const BattleID & battle) const
  892. {
  893. for (const auto & battlePtr : currentBattles)
  894. if (battlePtr->battleID == battle)
  895. return battlePtr.get();
  896. return nullptr;
  897. }
  898. BattleInfo * CGameState::getBattle(const BattleID & battle)
  899. {
  900. for (const auto & battlePtr : currentBattles)
  901. if (battlePtr->battleID == battle)
  902. return battlePtr.get();
  903. return nullptr;
  904. }
  905. BattleField CGameState::battleGetBattlefieldType(int3 tile, vstd::RNG & rand)
  906. {
  907. assert(tile.valid());
  908. if(!tile.valid())
  909. return BattleField::NONE;
  910. const TerrainTile &t = map->getTile(tile);
  911. auto * topObject = t.visitableObjects.front();
  912. if(topObject && topObject->getBattlefield() != BattleField::NONE)
  913. {
  914. return topObject->getBattlefield();
  915. }
  916. for(auto &obj : map->objects)
  917. {
  918. //look only for objects covering given tile
  919. if( !obj || !obj->coveringAt(tile))
  920. continue;
  921. auto customBattlefield = obj->getBattlefield();
  922. if(customBattlefield != BattleField::NONE)
  923. return customBattlefield;
  924. }
  925. if(map->isCoastalTile(tile)) //coastal tile is always ground
  926. return BattleField(*VLC->identifiers()->getIdentifier("core", "battlefield.sand_shore"));
  927. if (t.getTerrain()->battleFields.empty())
  928. throw std::runtime_error("Failed to find battlefield for terrain " + t.getTerrain()->getJsonKey());
  929. return BattleField(*RandomGeneratorUtil::nextItem(t.getTerrain()->battleFields, rand));
  930. }
  931. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  932. {
  933. assert(obj);
  934. assert(obj->hasStackAtSlot(stackPos));
  935. out = fillUpgradeInfo(obj->getStack(stackPos));
  936. }
  937. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance & stack) const
  938. {
  939. const CCreature *base = stack.getCreature();
  940. UpgradeInfo ret(base->getId());
  941. if (stack.armyObj->ID == Obj::HERO)
  942. {
  943. auto hero = dynamic_cast<const CGHeroInstance *>(stack.armyObj);
  944. hero->fillUpgradeInfo(ret, stack);
  945. if (hero->visitedTown)
  946. {
  947. hero->visitedTown->fillUpgradeInfo(ret, stack);
  948. }
  949. else
  950. {
  951. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  952. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  953. if (object != hero && upgradeSource != nullptr)
  954. upgradeSource->fillUpgradeInfo(ret, stack);
  955. }
  956. }
  957. if (stack.armyObj->ID == Obj::TOWN)
  958. {
  959. auto town = dynamic_cast<const CGTownInstance *>(stack.armyObj);
  960. town->fillUpgradeInfo(ret, stack);
  961. }
  962. return ret;
  963. }
  964. PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  965. {
  966. if ( color1 == color2 )
  967. return PlayerRelations::SAME_PLAYER;
  968. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  969. return PlayerRelations::ENEMIES;
  970. const TeamState * ts = getPlayerTeam(color1);
  971. if (ts && vstd::contains(ts->players, color2))
  972. return PlayerRelations::ALLIES;
  973. return PlayerRelations::ENEMIES;
  974. }
  975. void CGameState::apply(CPackForClient & pack)
  976. {
  977. pack.applyGs(this);
  978. }
  979. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  980. {
  981. calculatePaths(std::make_shared<SingleHeroPathfinderConfig>(out, this, hero));
  982. }
  983. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config)
  984. {
  985. //FIXME: creating pathfinder is costly, maybe reset / clear is enough?
  986. CPathfinder pathfinder(this, config);
  987. pathfinder.calculatePaths();
  988. }
  989. /**
  990. * Tells if the tile is guarded by a monster as well as the position
  991. * of the monster that will attack on it.
  992. *
  993. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  994. * the monster guarding the tile.
  995. */
  996. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  997. {
  998. std::vector<CGObjectInstance*> guards;
  999. const int3 originalPos = pos;
  1000. if (!map->isInTheMap(pos))
  1001. return guards;
  1002. const TerrainTile &posTile = map->getTile(pos);
  1003. if (posTile.visitable())
  1004. {
  1005. for (CGObjectInstance* obj : posTile.visitableObjects)
  1006. {
  1007. if(obj->isBlockedVisitable())
  1008. {
  1009. if (obj->ID == Obj::MONSTER) // Monster
  1010. guards.push_back(obj);
  1011. }
  1012. }
  1013. }
  1014. pos -= int3(1, 1, 0); // Start with top left.
  1015. for (int dx = 0; dx < 3; dx++)
  1016. {
  1017. for (int dy = 0; dy < 3; dy++)
  1018. {
  1019. if (map->isInTheMap(pos))
  1020. {
  1021. const auto & tile = map->getTile(pos);
  1022. if (tile.visitable() && (tile.isWater() == posTile.isWater()))
  1023. {
  1024. for (CGObjectInstance* obj : tile.visitableObjects)
  1025. {
  1026. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1027. {
  1028. guards.push_back(obj);
  1029. }
  1030. }
  1031. }
  1032. }
  1033. pos.y++;
  1034. }
  1035. pos.y -= 3;
  1036. pos.x++;
  1037. }
  1038. return guards;
  1039. }
  1040. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1041. {
  1042. return gs->map->guardingCreaturePositions[pos.z][pos.x][pos.y];
  1043. }
  1044. bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
  1045. {
  1046. if (!map->isInTheMap(pos))
  1047. return false;
  1048. if (!player)
  1049. return true;
  1050. if(player == PlayerColor::NEUTRAL)
  1051. return false;
  1052. if(player->isSpectator())
  1053. return true;
  1054. return getPlayerTeam(*player)->fogOfWarMap[pos.z][pos.x][pos.y];
  1055. }
  1056. bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
  1057. {
  1058. if(!player)
  1059. return true;
  1060. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1061. if (player == obj->tempOwner)
  1062. return true;
  1063. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1064. return false;
  1065. //object is visible when at least one blocked tile is visible
  1066. for(int fy=0; fy < obj->getHeight(); ++fy)
  1067. {
  1068. for(int fx=0; fx < obj->getWidth(); ++fx)
  1069. {
  1070. int3 pos = obj->anchorPos() + int3(-fx, -fy, 0);
  1071. if ( map->isInTheMap(pos) &&
  1072. obj->coveringAt(pos) &&
  1073. isVisible(pos, *player))
  1074. return true;
  1075. }
  1076. }
  1077. return false;
  1078. }
  1079. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1080. {
  1081. const TerrainTile * pom = &map->getTile(dst);
  1082. return map->checkForVisitableDir(src, pom, dst);
  1083. }
  1084. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  1085. {
  1086. const MetaString messageWonSelf = MetaString::createFromTextID("core.genrltxt.659");
  1087. const MetaString messageWonOther = MetaString::createFromTextID("core.genrltxt.5");
  1088. const MetaString messageLostSelf = MetaString::createFromTextID("core.genrltxt.7");
  1089. const MetaString messageLostOther = MetaString::createFromTextID("core.genrltxt.8");
  1090. auto evaluateEvent = [=](const EventCondition & condition)
  1091. {
  1092. return this->checkForVictory(player, condition);
  1093. };
  1094. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1095. //cheater or tester, but has entered the code...
  1096. if (p->enteredWinningCheatCode)
  1097. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1098. if (p->enteredLosingCheatCode)
  1099. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1100. for (const TriggeredEvent & event : map->triggeredEvents)
  1101. {
  1102. if (event.trigger.test(evaluateEvent))
  1103. {
  1104. if (event.effect.type == EventEffect::VICTORY)
  1105. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1106. if (event.effect.type == EventEffect::DEFEAT)
  1107. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1108. }
  1109. }
  1110. if (checkForStandardLoss(player))
  1111. {
  1112. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1113. }
  1114. return EVictoryLossCheckResult();
  1115. }
  1116. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  1117. {
  1118. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1119. switch (condition.condition)
  1120. {
  1121. case EventCondition::STANDARD_WIN:
  1122. {
  1123. return player == checkForStandardWin();
  1124. }
  1125. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1126. {
  1127. for(const auto & elem : p->getHeroes())
  1128. if(elem->hasArt(condition.objectType.as<ArtifactID>()))
  1129. return true;
  1130. return false;
  1131. }
  1132. case EventCondition::HAVE_CREATURES:
  1133. {
  1134. //check if in players armies there is enough creatures
  1135. int total = 0; //creature counter
  1136. for(auto object : map->objects)
  1137. {
  1138. const auto * ai = dynamic_cast<const CArmedInstance *>(object.get());
  1139. if(ai && ai->getOwner() == player)
  1140. {
  1141. for(const auto & elem : ai->Slots()) //iterate through army
  1142. if(elem.second->getId() == condition.objectType.as<CreatureID>()) //it's searched creature
  1143. total += elem.second->count;
  1144. }
  1145. }
  1146. return total >= condition.value;
  1147. }
  1148. case EventCondition::HAVE_RESOURCES:
  1149. {
  1150. return p->resources[condition.objectType.as<GameResID>()] >= condition.value;
  1151. }
  1152. case EventCondition::HAVE_BUILDING:
  1153. {
  1154. if (condition.objectID != ObjectInstanceID::NONE) // specific town
  1155. {
  1156. const auto * t = getTown(condition.objectID);
  1157. return (t->tempOwner == player && t->hasBuilt(condition.objectType.as<BuildingID>()));
  1158. }
  1159. else // any town
  1160. {
  1161. for (const CGTownInstance * t : p->getTowns())
  1162. {
  1163. if (t->hasBuilt(condition.objectType.as<BuildingID>()))
  1164. return true;
  1165. }
  1166. return false;
  1167. }
  1168. }
  1169. case EventCondition::DESTROY:
  1170. {
  1171. if (condition.objectID != ObjectInstanceID::NONE) // mode A - destroy specific object of this type
  1172. {
  1173. return p->destroyedObjects.count(condition.objectID);
  1174. }
  1175. else
  1176. {
  1177. for(const auto & elem : map->objects) // mode B - destroy all objects of this type
  1178. {
  1179. if(elem && elem->ID == condition.objectType.as<MapObjectID>())
  1180. return false;
  1181. }
  1182. return true;
  1183. }
  1184. }
  1185. case EventCondition::CONTROL:
  1186. {
  1187. // list of players that need to control object to fulfull condition
  1188. // NOTE: cgameinfocallback specified explicitly in order to get const version
  1189. const auto * team = CGameInfoCallback::getPlayerTeam(player);
  1190. if (condition.objectID != ObjectInstanceID::NONE) // mode A - flag one specific object, like town
  1191. {
  1192. const auto * object = getObjInstance(condition.objectID);
  1193. if (!object)
  1194. return false;
  1195. return team->players.count(object->getOwner()) != 0;
  1196. }
  1197. else
  1198. {
  1199. for(const auto & elem : map->objects) // mode B - flag all objects of this type
  1200. {
  1201. //check not flagged objs
  1202. if ( elem && elem->ID == condition.objectType.as<MapObjectID>() && team->players.count(elem->getOwner()) == 0 )
  1203. return false;
  1204. }
  1205. return true;
  1206. }
  1207. }
  1208. case EventCondition::TRANSPORT:
  1209. {
  1210. const auto * t = getTown(condition.objectID);
  1211. bool garrisonedWon = t->garrisonHero && t->garrisonHero->getOwner() == player && t->garrisonHero->hasArt(condition.objectType.as<ArtifactID>());
  1212. bool visitingWon = t->visitingHero && t->visitingHero->getOwner() == player && t->visitingHero->hasArt(condition.objectType.as<ArtifactID>());
  1213. return garrisonedWon || visitingWon;
  1214. }
  1215. case EventCondition::DAYS_PASSED:
  1216. {
  1217. return (si32)gs->day > condition.value;
  1218. }
  1219. case EventCondition::IS_HUMAN:
  1220. {
  1221. return p->human ? condition.value == 1 : condition.value == 0;
  1222. }
  1223. case EventCondition::DAYS_WITHOUT_TOWN:
  1224. {
  1225. if (p->daysWithoutCastle)
  1226. return p->daysWithoutCastle >= condition.value;
  1227. else
  1228. return false;
  1229. }
  1230. case EventCondition::CONST_VALUE:
  1231. {
  1232. return condition.value; // just convert to bool
  1233. }
  1234. default:
  1235. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1236. return false;
  1237. }
  1238. }
  1239. PlayerColor CGameState::checkForStandardWin() const
  1240. {
  1241. //std victory condition is:
  1242. //all enemies lost
  1243. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  1244. TeamID winnerTeam = TeamID::NO_TEAM;
  1245. for(const auto & elem : players)
  1246. {
  1247. if(elem.second.status == EPlayerStatus::WINNER)
  1248. return elem.second.color;
  1249. if(elem.second.status == EPlayerStatus::INGAME && elem.first.isValidPlayer())
  1250. {
  1251. if(supposedWinner == PlayerColor::NEUTRAL)
  1252. {
  1253. //first player remaining ingame - candidate for victory
  1254. supposedWinner = elem.second.color;
  1255. winnerTeam = elem.second.team;
  1256. }
  1257. else if(winnerTeam != elem.second.team)
  1258. {
  1259. //current candidate has enemy remaining in game -> no vicotry
  1260. return PlayerColor::NEUTRAL;
  1261. }
  1262. }
  1263. }
  1264. return supposedWinner;
  1265. }
  1266. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  1267. {
  1268. //std loss condition is: player lost all towns and heroes
  1269. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  1270. return pState.checkVanquished();
  1271. }
  1272. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  1273. {
  1274. auto playerInactive = [&](const PlayerColor & color)
  1275. {
  1276. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  1277. };
  1278. #define FILL_FIELD(FIELD, VAL_GETTER) \
  1279. { \
  1280. std::vector< std::pair< PlayerColor, si64 > > stats; \
  1281. for(auto g = players.begin(); g != players.end(); ++g) \
  1282. { \
  1283. if(playerInactive(g->second.color)) \
  1284. continue; \
  1285. std::pair< PlayerColor, si64 > stat; \
  1286. stat.first = g->second.color; \
  1287. stat.second = VAL_GETTER; \
  1288. stats.push_back(stat); \
  1289. } \
  1290. tgi.FIELD = Statistic::getRank(stats); \
  1291. }
  1292. for(auto & elem : players)
  1293. {
  1294. if(!playerInactive(elem.second.color))
  1295. tgi.playerColors.push_back(elem.second.color);
  1296. }
  1297. if(level >= 0) //num of towns & num of heroes
  1298. {
  1299. //num of towns
  1300. FILL_FIELD(numOfTowns, g->second.getTowns().size())
  1301. //num of heroes
  1302. FILL_FIELD(numOfHeroes, g->second.getHeroes().size())
  1303. }
  1304. if(level >= 1) //best hero's portrait
  1305. {
  1306. for(const auto & player : players)
  1307. {
  1308. if(playerInactive(player.second.color))
  1309. continue;
  1310. const CGHeroInstance * best = Statistic::findBestHero(this, player.second.color);
  1311. InfoAboutHero iah;
  1312. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  1313. iah.army.clear();
  1314. tgi.colorToBestHero[player.second.color] = iah;
  1315. }
  1316. }
  1317. if(level >= 2) //gold
  1318. {
  1319. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  1320. }
  1321. if(level >= 2) //wood & ore
  1322. {
  1323. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  1324. }
  1325. if(level >= 3) //mercury, sulfur, crystal, gems
  1326. {
  1327. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  1328. }
  1329. if(level >= 3) //obelisks found
  1330. {
  1331. FILL_FIELD(obelisks, Statistic::getObeliskVisited(gs, gs->getPlayerTeam(g->second.color)->id))
  1332. }
  1333. if(level >= 4) //artifacts
  1334. {
  1335. FILL_FIELD(artifacts, Statistic::getNumberOfArts(&g->second))
  1336. }
  1337. if(level >= 4) //army strength
  1338. {
  1339. FILL_FIELD(army, Statistic::getArmyStrength(&g->second))
  1340. }
  1341. if(level >= 5) //income
  1342. {
  1343. FILL_FIELD(income, Statistic::getIncome(gs, &g->second))
  1344. }
  1345. if(level >= 2) //best hero's stats
  1346. {
  1347. //already set in lvl 1 handling
  1348. }
  1349. if(level >= 3) //personality
  1350. {
  1351. for(const auto & player : players)
  1352. {
  1353. if(playerInactive(player.second.color)) //do nothing for neutral player
  1354. continue;
  1355. if(player.second.human)
  1356. {
  1357. tgi.personality[player.second.color] = EAiTactic::NONE;
  1358. }
  1359. else //AI
  1360. {
  1361. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  1362. }
  1363. }
  1364. }
  1365. if(level >= 4) //best creature
  1366. {
  1367. //best creatures belonging to player (highest AI value)
  1368. for(const auto & player : players)
  1369. {
  1370. if(playerInactive(player.second.color)) //do nothing for neutral player
  1371. continue;
  1372. CreatureID bestCre; //best creature's ID
  1373. for(const auto & elem : player.second.getHeroes())
  1374. {
  1375. for(const auto & it : elem->Slots())
  1376. {
  1377. CreatureID toCmp = it.second->getId(); //ID of creature we should compare with the best one
  1378. if(bestCre == CreatureID::NONE || bestCre.toEntity(VLC)->getAIValue() < toCmp.toEntity(VLC)->getAIValue())
  1379. {
  1380. bestCre = toCmp;
  1381. }
  1382. }
  1383. }
  1384. tgi.bestCreature[player.second.color] = bestCre;
  1385. }
  1386. }
  1387. #undef FILL_FIELD
  1388. }
  1389. void CGameState::buildBonusSystemTree()
  1390. {
  1391. buildGlobalTeamPlayerTree();
  1392. attachArmedObjects();
  1393. for(CGTownInstance *t : map->towns)
  1394. {
  1395. t->deserializationFix();
  1396. }
  1397. }
  1398. void CGameState::deserializationFix()
  1399. {
  1400. buildGlobalTeamPlayerTree();
  1401. attachArmedObjects();
  1402. }
  1403. void CGameState::buildGlobalTeamPlayerTree()
  1404. {
  1405. for(auto & team : teams)
  1406. {
  1407. TeamState * t = &team.second;
  1408. t->attachTo(globalEffects);
  1409. for(const PlayerColor & teamMember : team.second.players)
  1410. {
  1411. PlayerState *p = getPlayerState(teamMember);
  1412. assert(p);
  1413. p->attachTo(*t);
  1414. }
  1415. }
  1416. }
  1417. void CGameState::attachArmedObjects()
  1418. {
  1419. for(CGObjectInstance *obj : map->objects)
  1420. {
  1421. if(auto * armed = dynamic_cast<CArmedInstance *>(obj))
  1422. {
  1423. armed->whatShouldBeAttached().attachTo(armed->whereShouldBeAttached(this));
  1424. }
  1425. }
  1426. }
  1427. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  1428. {
  1429. CArtifactInstance * ai = ArtifactUtils::createArtifact(aid);
  1430. map->addNewArtifactInstance(ai);
  1431. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  1432. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1433. {
  1434. map->putArtifactInstance(*h, ai, slot);
  1435. return true;
  1436. }
  1437. else
  1438. {
  1439. return false;
  1440. }
  1441. }
  1442. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  1443. {
  1444. std::set<HeroTypeID> ret = map->allowedHeroes;
  1445. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  1446. {
  1447. if(playerSettingPair.second.hero != HeroTypeID::RANDOM)
  1448. ret -= HeroTypeID(playerSettingPair.second.hero);
  1449. }
  1450. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1451. ret -= hero->getHeroTypeID();
  1452. for(auto obj : map->objects) //prisons
  1453. {
  1454. auto * hero = dynamic_cast<const CGHeroInstance *>(obj.get());
  1455. if(hero && hero->ID == Obj::PRISON)
  1456. ret -= hero->getHeroTypeID();
  1457. }
  1458. return ret;
  1459. }
  1460. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  1461. {
  1462. return getUsedHero(hid);
  1463. }
  1464. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  1465. {
  1466. for(auto obj : map->objects) //prisons
  1467. {
  1468. if (!obj)
  1469. continue;
  1470. if ( obj->ID !=Obj::PRISON && obj->ID != Obj::HERO)
  1471. continue;
  1472. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  1473. assert(hero);
  1474. if (hero->getHeroTypeID() == hid)
  1475. return hero;
  1476. }
  1477. return nullptr;
  1478. }
  1479. TeamState::TeamState()
  1480. {
  1481. setNodeType(TEAM);
  1482. }
  1483. vstd::RNG & CGameState::getRandomGenerator()
  1484. {
  1485. return callback->getRandomGenerator();
  1486. }
  1487. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & rand, int flags, std::function<bool(ArtifactID)> accepts)
  1488. {
  1489. std::set<ArtifactID> potentialPicks;
  1490. // Select artifacts that satisfy provided criteria
  1491. for (auto const & artifactID : map->allowedArtifact)
  1492. {
  1493. if (!VLC->arth->legalArtifact(artifactID))
  1494. continue;
  1495. auto const * artifact = artifactID.toArtifact();
  1496. assert(artifact->aClass != CArtifact::ART_SPECIAL); // should be filtered out when allowedArtifacts is initialized
  1497. if ((flags & CArtifact::ART_TREASURE) == 0 && artifact->aClass == CArtifact::ART_TREASURE)
  1498. continue;
  1499. if ((flags & CArtifact::ART_MINOR) == 0 && artifact->aClass == CArtifact::ART_MINOR)
  1500. continue;
  1501. if ((flags & CArtifact::ART_MAJOR) == 0 && artifact->aClass == CArtifact::ART_MAJOR)
  1502. continue;
  1503. if ((flags & CArtifact::ART_RELIC) == 0 && artifact->aClass == CArtifact::ART_RELIC)
  1504. continue;
  1505. if (!accepts(artifact->getId()))
  1506. continue;
  1507. potentialPicks.insert(artifact->getId());
  1508. }
  1509. return pickRandomArtifact(rand, potentialPicks);
  1510. }
  1511. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & rand, std::set<ArtifactID> potentialPicks)
  1512. {
  1513. // No allowed artifacts at all - give Grail - this can't be banned (hopefully)
  1514. // FIXME: investigate how such cases are handled by H3 - some heavily customized user-made maps likely rely on H3 behavior
  1515. if (potentialPicks.empty())
  1516. {
  1517. logGlobal->warn("Failed to find artifact that matches requested parameters!");
  1518. return ArtifactID::GRAIL;
  1519. }
  1520. // Find how many times least used artifacts were picked by randomizer
  1521. int leastUsedTimes = std::numeric_limits<int>::max();
  1522. for (auto const & artifact : potentialPicks)
  1523. if (allocatedArtifacts[artifact] < leastUsedTimes)
  1524. leastUsedTimes = allocatedArtifacts[artifact];
  1525. // Pick all artifacts that were used least number of times
  1526. std::set<ArtifactID> preferredPicks;
  1527. for (auto const & artifact : potentialPicks)
  1528. if (allocatedArtifacts[artifact] == leastUsedTimes)
  1529. preferredPicks.insert(artifact);
  1530. assert(!preferredPicks.empty());
  1531. ArtifactID artID = *RandomGeneratorUtil::nextItem(preferredPicks, rand);
  1532. allocatedArtifacts[artID] += 1; // record +1 more usage
  1533. return artID;
  1534. }
  1535. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & rand, std::function<bool(ArtifactID)> accepts)
  1536. {
  1537. return pickRandomArtifact(rand, 0xff, std::move(accepts));
  1538. }
  1539. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & rand, int flags)
  1540. {
  1541. return pickRandomArtifact(rand, flags, [](const ArtifactID &) { return true; });
  1542. }
  1543. void UpgradeInfo::addUpgrade(const CreatureID & upgradeID, ResourceSet && upgradeCost, bool available)
  1544. {
  1545. isAvailable = available;
  1546. upgradesIDs.push_back(upgradeID);
  1547. upgradeCost.positive(); //upgrade cost can't be negative, ignore missing resources
  1548. upgradesCosts.push_back(std::move(upgradeCost));
  1549. // sort from highest ID to smallest
  1550. size_t pos = upgradesIDs.size() - 1;
  1551. while(pos > 0 && upgradesIDs[pos] > upgradesIDs[pos - 1])
  1552. {
  1553. std::swap(upgradesIDs[pos], upgradesIDs[pos - 1]);
  1554. std::swap(upgradesCosts[pos], upgradesCosts[pos - 1]);
  1555. --pos;
  1556. }
  1557. }
  1558. VCMI_LIB_NAMESPACE_END