CGameState.cpp 55 KB

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