CGameState.cpp 50 KB

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