CGameState.cpp 50 KB

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