CGameState.cpp 50 KB

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