CGameState.cpp 50 KB

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