CGameState.cpp 50 KB

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