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