CGameState.cpp 50 KB

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