CGTownInstance.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. /*
  2. * CGTownInstance.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 "CGTownInstance.h"
  12. #include "TownBuildingInstance.h"
  13. #include "../IGameSettings.h"
  14. #include "../spells/CSpellHandler.h"
  15. #include "../bonuses/Bonus.h"
  16. #include "../battle/IBattleInfoCallback.h"
  17. #include "../battle/BattleLayout.h"
  18. #include "../CConfigHandler.h"
  19. #include "../texts/CGeneralTextHandler.h"
  20. #include "../gameState/CGameState.h"
  21. #include "../gameState/UpgradeInfo.h"
  22. #include "../mapping/CCastleEvent.h"
  23. #include "../mapping/CMap.h"
  24. #include "../CPlayerState.h"
  25. #include "../StartInfo.h"
  26. #include "../TerrainHandler.h"
  27. #include "../callback/IGameInfoCallback.h"
  28. #include "../callback/IGameEventCallback.h"
  29. #include "../callback/IGameRandomizer.h"
  30. #include "../entities/building/CBuilding.h"
  31. #include "../entities/faction/CTownHandler.h"
  32. #include "../entities/ResourceTypeHandler.h"
  33. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  34. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  35. #include "../mapObjects/CGHeroInstance.h"
  36. #include "../modding/ModScope.h"
  37. #include "../networkPacks/StackLocation.h"
  38. #include "../networkPacks/PacksForClient.h"
  39. #include "../networkPacks/PacksForClientBattle.h"
  40. #include "../serializer/JsonSerializeFormat.h"
  41. #include <vstd/RNG.h>
  42. VCMI_LIB_NAMESPACE_BEGIN
  43. int CGTownInstance::getSightRadius() const
  44. {
  45. int baseValue = LIBRARY->engineSettings()->getInteger(EGameSettings::TOWNS_BASE_SCOUNTING_RANGE);
  46. return applyBonuses(BonusType::SIGHT_RADIUS, baseValue);
  47. }
  48. void CGTownInstance::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  49. {
  50. ///this is freakin' overcomplicated solution
  51. switch (what)
  52. {
  53. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  54. rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::VISITORS, getVisitingHero()->id);
  55. break;
  56. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  57. rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::STRUCTURE_CLEAR_VISITORS, NumericID(0));
  58. break;
  59. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  60. rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::VISITORS, getGarrisonHero()->id);
  61. break;
  62. case ObjProperty::BONUS_VALUE_FIRST:
  63. bonusValue.first = identifier.getNum();
  64. break;
  65. case ObjProperty::BONUS_VALUE_SECOND:
  66. bonusValue.second = identifier.getNum();
  67. break;
  68. }
  69. }
  70. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  71. {
  72. if (hasBuilt(BuildingID::CASTLE))
  73. return CASTLE;
  74. if (hasBuilt(BuildingID::CITADEL))
  75. return CITADEL;
  76. if (hasBuilt(BuildingID::FORT))
  77. return FORT;
  78. return NONE;
  79. }
  80. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  81. {
  82. if (hasBuilt(BuildingID::CAPITOL))
  83. return 3;
  84. if (hasBuilt(BuildingID::CITY_HALL))
  85. return 2;
  86. if (hasBuilt(BuildingID::TOWN_HALL))
  87. return 1;
  88. if (hasBuilt(BuildingID::VILLAGE_HALL))
  89. return 0;
  90. return -1;
  91. }
  92. int CGTownInstance::mageGuildLevel() const
  93. {
  94. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  95. return 5;
  96. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  97. return 4;
  98. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  99. return 3;
  100. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  101. return 2;
  102. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  103. return 1;
  104. return 0;
  105. }
  106. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  107. {
  108. return getTown()->hordeLvl.at(HID);
  109. }
  110. int CGTownInstance::creatureGrowth(const int & level) const
  111. {
  112. return getGrowthInfo(level).totalGrowth();
  113. }
  114. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  115. {
  116. GrowthInfo ret;
  117. if (level<0 || level >=getTown()->creatures.size())
  118. return ret;
  119. if (creatures[level].second.empty())
  120. return ret; //no dwelling
  121. const Creature *creature = creatures[level].second.back().toEntity(LIBRARY);
  122. const int base = creature->getGrowth();
  123. int castleBonus = 0;
  124. if(tempOwner.isValidPlayer())
  125. {
  126. auto * playerSettings = cb->getPlayerSettings(tempOwner);
  127. ret.handicapPercentage = playerSettings->handicap.percentGrowth;
  128. }
  129. else
  130. ret.handicapPercentage = 100;
  131. ret.entries.emplace_back(LIBRARY->generaltexth->allTexts[590], base); // \n\nBasic growth %d"
  132. if (hasBuilt(BuildingID::CASTLE))
  133. ret.entries.emplace_back(subID, BuildingID::CASTLE, castleBonus = base);
  134. else if (hasBuilt(BuildingID::CITADEL))
  135. ret.entries.emplace_back(subID, BuildingID::CITADEL, castleBonus = base / 2);
  136. if(getTown()->hordeLvl.at(0) == level)//horde 1
  137. if(hasBuilt(BuildingID::HORDE_1))
  138. ret.entries.emplace_back(subID, BuildingID::HORDE_1, creature->getHorde());
  139. if(getTown()->hordeLvl.at(1) == level)//horde 2
  140. if(hasBuilt(BuildingID::HORDE_2))
  141. ret.entries.emplace_back(subID, BuildingID::HORDE_2, creature->getHorde());
  142. //statue-of-legion-like bonus: % to base+castle
  143. TConstBonusListPtr bonuses2 = getBonusesOfType(BonusType::CREATURE_GROWTH_PERCENT);
  144. for(const auto & b : *bonuses2)
  145. {
  146. const auto growth = b->val * (base + castleBonus) / 100;
  147. if (growth)
  148. {
  149. ret.entries.emplace_back(growth, b->Description(cb, growth));
  150. }
  151. }
  152. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  153. // Note: bonus uses 1-based levels (Pikeman is level 1), town list uses 0-based (Pikeman in 0-th creatures entry)
  154. TConstBonusListPtr bonuses = getBonusesOfType(BonusType::CREATURE_GROWTH, BonusCustomSubtype::creatureLevel(level+1));
  155. for(const auto & b : *bonuses)
  156. ret.entries.emplace_back(b->val, b->Description(cb));
  157. int dwellingBonus = 0;
  158. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  159. {
  160. dwellingBonus = getDwellingBonus(creatures[level].second, p->getOwnedObjects());
  161. }
  162. if(dwellingBonus)
  163. ret.entries.emplace_back(LIBRARY->generaltexth->allTexts[591], dwellingBonus); // \nExternal dwellings %+d
  164. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  165. ret.entries.emplace_back(subID, BuildingID::GRAIL, ret.totalGrowth() / 2);
  166. return ret;
  167. }
  168. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<const CGObjectInstance * >& dwellings) const
  169. {
  170. int totalBonus = 0;
  171. for (const auto& dwelling : dwellings)
  172. {
  173. const auto & dwellingCreatures = dwelling->asOwnable()->providedCreatures();
  174. bool hasMatch = false;
  175. for (const auto& creature : dwellingCreatures)
  176. hasMatch |= vstd::contains(creatureIds, creature);
  177. if (hasMatch)
  178. totalBonus += 1;
  179. }
  180. return totalBonus;
  181. }
  182. TResources CGTownInstance::dailyIncome() const
  183. {
  184. ResourceSet ret;
  185. for (GameResID k : LIBRARY->resourceTypeHandler->getAllObjects())
  186. ret[k] += valOfBonuses(BonusType::GENERATE_RESOURCE, BonusSubtypeID(k));
  187. for(const auto & p : getTown()->buildings)
  188. {
  189. BuildingID buildingUpgrade;
  190. for(const auto & p2 : getTown()->buildings)
  191. {
  192. if (p2.second->upgrade == p.first)
  193. {
  194. buildingUpgrade = p2.first;
  195. }
  196. }
  197. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  198. {
  199. ret += p.second->produce;
  200. }
  201. }
  202. if (!getOwner().isValidPlayer())
  203. return ret;
  204. const auto & playerSettings = cb->getPlayerSettings(getOwner());
  205. ret.applyHandicap(playerSettings->handicap.percentIncome);
  206. return ret;
  207. }
  208. std::vector<CreatureID> CGTownInstance::providedCreatures() const
  209. {
  210. return {};
  211. }
  212. bool CGTownInstance::hasFort() const
  213. {
  214. return hasBuilt(BuildingID::FORT);
  215. }
  216. bool CGTownInstance::hasCapitol() const
  217. {
  218. return hasBuilt(BuildingID::CAPITOL);
  219. }
  220. TownFortifications CGTownInstance::fortificationsLevel() const
  221. {
  222. auto result = getTown()->fortifications;
  223. for (auto const & buildingID : builtBuildings)
  224. result += getTown()->buildings.at(buildingID)->fortifications;
  225. if (result.wallsHealth == 0)
  226. return TownFortifications();
  227. return result;
  228. }
  229. CGTownInstance::CGTownInstance(IGameInfoCallback *cb):
  230. CGDwelling(cb, BonusNodeType::TOWN),
  231. IMarket(cb),
  232. townAndVis(BonusNodeType::TOWN_AND_VISITOR),
  233. built(0),
  234. destroyed(0),
  235. identifier(0),
  236. alignmentToPlayer(PlayerColor::NEUTRAL),
  237. spellResearchCounterDay(0),
  238. spellResearchAcceptedCounter(0),
  239. spellResearchPendingRerollsCounters(GameConstants::SPELL_LEVELS, 0),
  240. spellResearchAllowed(true)
  241. {
  242. attachTo(townAndVis);
  243. }
  244. CGTownInstance::~CGTownInstance() = default;
  245. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  246. {
  247. if(checkGuild && mageGuildLevel() < level)
  248. return 0;
  249. int ret = 6 - level; //how many spells are available at this level
  250. if (hasBuilt(BuildingSubID::LIBRARY))
  251. ret++;
  252. return ret;
  253. }
  254. bool CGTownInstance::needsLastStack() const
  255. {
  256. return getGarrisonHero() != nullptr;
  257. }
  258. void CGTownInstance::setOwner(IGameEventCallback & gameEvents, const PlayerColor & player) const
  259. {
  260. removeCapitols(gameEvents, player);
  261. gameEvents.setOwner(this, player);
  262. }
  263. void CGTownInstance::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  264. {
  265. if(cb->getPlayerRelations( getOwner(), h->getOwner() ) == PlayerRelations::ENEMIES)
  266. {
  267. if(armedGarrison() || getVisitingHero())
  268. {
  269. const CGHeroInstance * defendingHero = getVisitingHero() ? getVisitingHero() : getGarrisonHero();
  270. const CArmedInstance * defendingArmy = defendingHero ? static_cast<const CArmedInstance*>(defendingHero) : this;
  271. const bool isBattleOutside = isBattleOutsideTown(defendingHero);
  272. if(!isBattleOutside && defendingHero && defendingHero == getVisitingHero())
  273. mergeGarrisonOnSiege(gameEvents);
  274. gameEvents.startBattle(h, defendingArmy, getSightCenter(), h, defendingHero, BattleLayout::createDefaultLayout(*cb, h, defendingArmy), (isBattleOutside ? nullptr : this));
  275. }
  276. else
  277. {
  278. auto heroColor = h->getOwner();
  279. onTownCaptured(gameEvents, heroColor);
  280. if(cb->gameState().getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
  281. {
  282. return; //we just won game, we do not need to perform any extra actions
  283. //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
  284. }
  285. gameEvents.heroVisitCastle(this, h);
  286. }
  287. }
  288. else
  289. {
  290. assert(h->visitablePos() == this->visitablePos());
  291. bool commander_recover = h->getCommander() && !h->getCommander()->alive;
  292. if (commander_recover) // rise commander from dead
  293. {
  294. SetCommanderProperty scp;
  295. scp.heroid = h->id;
  296. scp.which = SetCommanderProperty::ALIVE;
  297. scp.amount = 1;
  298. gameEvents.sendAndApply(scp);
  299. }
  300. gameEvents.heroVisitCastle(this, h);
  301. // TODO(vmarkovtsev): implement payment for rising the commander
  302. if (commander_recover) // info window about commander
  303. {
  304. InfoWindow iw;
  305. iw.player = h->tempOwner;
  306. iw.text.appendRawString(h->getCommander()->getName());
  307. iw.components.emplace_back(ComponentType::CREATURE, h->getCommander()->getId(), h->getCommander()->getCount());
  308. gameEvents.showInfoDialog(&iw);
  309. }
  310. }
  311. }
  312. void CGTownInstance::onHeroLeave(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  313. {
  314. //FIXME: find out why this issue appears on random maps
  315. if(getVisitingHero() == h)
  316. {
  317. gameEvents.stopHeroVisitCastle(this, h);
  318. logGlobal->trace("%s correctly left town %s", h->getNameTranslated(), getNameTranslated());
  319. }
  320. else
  321. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->getNameTranslated(), getNameTranslated());
  322. }
  323. std::string CGTownInstance::getObjectName() const
  324. {
  325. if(ID == Obj::RANDOM_TOWN )
  326. return CGObjectInstance::getObjectName();
  327. return getNameTranslated() + ", " + getTown()->faction->getNameTranslated();
  328. }
  329. bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
  330. {
  331. return getTown()->getBuildingType(subId) != BuildingID::NONE;
  332. }
  333. void CGTownInstance::initializeConfigurableBuildings(IGameRandomizer & gameRandomizer)
  334. {
  335. for(const auto & kvp : getTown()->buildings)
  336. {
  337. if(kvp.second->rewardableObjectInfo.getParameters().isNull())
  338. continue;
  339. try {
  340. rewardableBuildings[kvp.first] = std::make_unique<TownRewardableBuildingInstance>(this, kvp.second->bid, gameRandomizer);
  341. }
  342. catch (std::runtime_error & e)
  343. {
  344. std::string buildingConfig = kvp.second->rewardableObjectInfo.getParameters().toCompactString();
  345. std::replace(buildingConfig.begin(), buildingConfig.end(), '\n', ' ');
  346. throw std::runtime_error("Failed to load rewardable building data for " + kvp.second->getJsonKey() + " Reason: " + e.what() + ", config was: " + buildingConfig);
  347. }
  348. }
  349. }
  350. DamageRange CGTownInstance::getTowerDamageRange() const
  351. {
  352. // http://heroes.thelazy.net/wiki/Arrow_tower
  353. // base damage, irregardless of town level
  354. static constexpr int baseDamage = 6;
  355. // extra damage, for each building in town
  356. static constexpr int extraDamage = 1;
  357. const int minDamage = baseDamage + extraDamage * getTownLevel();
  358. return {
  359. minDamage,
  360. minDamage * 2
  361. };
  362. }
  363. DamageRange CGTownInstance::getKeepDamageRange() const
  364. {
  365. // http://heroes.thelazy.net/wiki/Arrow_tower
  366. // base damage, irregardless of town level
  367. static constexpr int baseDamage = 10;
  368. // extra damage, for each building in town
  369. static constexpr int extraDamage = 2;
  370. const int minDamage = baseDamage + extraDamage * getTownLevel();
  371. return {
  372. minDamage,
  373. minDamage * 2
  374. };
  375. }
  376. FactionID CGTownInstance::randomizeFaction(vstd::RNG & rand)
  377. {
  378. if(getOwner().isValidPlayer())
  379. return cb->getStartInfo()->getIthPlayersSettings(getOwner()).castle;
  380. if(alignmentToPlayer.isValidPlayer())
  381. return cb->getStartInfo()->getIthPlayersSettings(alignmentToPlayer).castle;
  382. std::vector<FactionID> potentialPicks;
  383. for (FactionID faction(0); faction < FactionID(LIBRARY->townh->size()); ++faction)
  384. if (LIBRARY->factions()->getById(faction)->hasTown())
  385. potentialPicks.push_back(faction);
  386. assert(!potentialPicks.empty());
  387. return *RandomGeneratorUtil::nextItem(potentialPicks, rand);
  388. }
  389. void CGTownInstance::pickRandomObject(IGameRandomizer & gameRandomizer)
  390. {
  391. assert(ID == MapObjectID::TOWN || ID == MapObjectID::RANDOM_TOWN);
  392. if (ID == MapObjectID::RANDOM_TOWN)
  393. {
  394. ID = MapObjectID::TOWN;
  395. subID = randomizeFaction(gameRandomizer.getDefault());
  396. }
  397. assert(ID == Obj::TOWN); // just in case
  398. setType(ID, subID);
  399. randomizeArmy(getFactionID());
  400. updateAppearance();
  401. }
  402. void CGTownInstance::initObj(IGameRandomizer & gameRandomizer) ///initialize town structures
  403. {
  404. blockVisit = true;
  405. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  406. creatures.resize(getTown()->creatures.size() + 1);
  407. else
  408. creatures.resize(getTown()->creatures.size());
  409. for (int level = 0; level < getTown()->creatures.size(); level++)
  410. {
  411. BuildingID buildID = BuildingID(BuildingID::getDwellingFromLevel(level, 0));
  412. int upgradeNum = 0;
  413. for (; getTown()->buildings.count(buildID); upgradeNum++, BuildingID::advanceDwelling(buildID))
  414. {
  415. if (hasBuilt(buildID) && getTown()->creatures.at(level).size() > upgradeNum)
  416. creatures[level].second.push_back(getTown()->creatures[level][upgradeNum]);
  417. }
  418. }
  419. initializeConfigurableBuildings(gameRandomizer);
  420. initializeNeutralTownGarrison(gameRandomizer.getDefault());
  421. recreateBuildingsBonuses();
  422. updateAppearance();
  423. }
  424. void CGTownInstance::initializeNeutralTownGarrison(vstd::RNG & rand)
  425. {
  426. struct RandomGuardsInfo{
  427. int tier;
  428. int chance;
  429. int min;
  430. int max;
  431. };
  432. constexpr std::array<RandomGuardsInfo, 4> randomGuards = {
  433. RandomGuardsInfo{ 0, 33, 8, 15 },
  434. RandomGuardsInfo{ 1, 33, 5, 7 },
  435. RandomGuardsInfo{ 2, 20, 3, 5 },
  436. RandomGuardsInfo{ 3, 14, 1, 3 },
  437. };
  438. // Only neutral towns may get initial garrison
  439. if (getOwner().isValidPlayer())
  440. return;
  441. // Only towns with garrison not set in map editor may get initial garrison
  442. // FIXME: H3 editor allow explicitly empty garrison, but vcmi loses this flag on load
  443. if (stacksCount() > 0)
  444. return;
  445. for (auto const & guard : randomGuards)
  446. {
  447. if (rand.nextInt(99) >= guard.chance)
  448. continue;
  449. CreatureID guardID = getTown()->creatures[guard.tier].at(0);
  450. int guardSize = rand.nextInt(guard.min, guard.max);
  451. putStack(getFreeSlot(), std::make_unique<CStackInstance>(cb, guardID, guardSize));
  452. }
  453. }
  454. void CGTownInstance::newTurn(IGameEventCallback & gameEvents, IGameRandomizer & gameRandomizer) const
  455. {
  456. for(const auto & building : rewardableBuildings)
  457. building.second->newTurn(gameEvents, gameRandomizer);
  458. if(hasBuilt(BuildingSubID::BANK) && bonusValue.second > 0)
  459. {
  460. TResources res;
  461. res[EGameResID::GOLD] = -500;
  462. gameEvents.giveResources(getOwner(), res);
  463. gameEvents.setObjPropertyValue(id, ObjProperty::BONUS_VALUE_SECOND, bonusValue.second - 500);
  464. }
  465. }
  466. bool CGTownInstance::passableFor(PlayerColor color) const
  467. {
  468. if (!armedGarrison())//empty castle - anyone can visit
  469. return true;
  470. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  471. return false;
  472. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  473. }
  474. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  475. {
  476. offsets = {int3(-1,2,0), int3(+1,2,0)};
  477. }
  478. CGTownInstance::EGeneratorState CGTownInstance::shipyardStatus() const
  479. {
  480. if (!hasBuilt(BuildingID::SHIPYARD))
  481. return EGeneratorState::UNKNOWN;
  482. return IShipyard::shipyardStatus();
  483. }
  484. const IObjectInterface * CGTownInstance::getObject() const
  485. {
  486. return this;
  487. }
  488. void CGTownInstance::mergeGarrisonOnSiege(IGameEventCallback & gameEvents) const
  489. {
  490. auto getWeakestStackSlot = [&](ui64 powerLimit)
  491. {
  492. SlotID weakestSlot;
  493. for ( const auto & pair : getVisitingHero()->stacks)
  494. {
  495. if(powerLimit > pair.second->getPower() &&
  496. (weakestSlot == SlotID() || pair.second->getPower() < getVisitingHero()->getStack(weakestSlot).getPower()))
  497. {
  498. weakestSlot = pair.first;
  499. }
  500. }
  501. return weakestSlot;
  502. };
  503. auto count = static_cast<int>(stacks.size());
  504. for(int i = 0; i < count; i++)
  505. {
  506. const auto & pair = *vstd::maxElementByFun(stacks, [&](const auto & elem)
  507. {
  508. ui64 power = elem.second->getPower();
  509. auto dst = getVisitingHero()->getSlotFor(elem.second->getCreatureID());
  510. if(dst.validSlot() && getVisitingHero()->hasStackAtSlot(dst))
  511. power += getVisitingHero()->getStack(dst).getPower();
  512. return power;
  513. });
  514. auto dst = getVisitingHero()->getSlotFor(pair.second->getCreatureID());
  515. if(dst.validSlot())
  516. gameEvents.moveStack(StackLocation(id, pair.first), StackLocation(getVisitingHero()->id, dst), -1);
  517. else
  518. {
  519. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  520. if(dst.validSlot())
  521. gameEvents.swapStacks(StackLocation(id, pair.first), StackLocation(getVisitingHero()->id, dst));
  522. }
  523. }
  524. }
  525. void CGTownInstance::removeCapitols(IGameEventCallback & gameEvents, const PlayerColor & owner) const
  526. {
  527. if (hasCapitol()) // search if there's an older capitol
  528. {
  529. const PlayerState* state = cb->getPlayerState(owner); //get all towns owned by player
  530. for (const auto & otherTown : state->getTowns())
  531. {
  532. if (otherTown != this && otherTown->hasCapitol())
  533. {
  534. RazeStructures rs;
  535. rs.tid = id;
  536. rs.bid.insert(BuildingID::CAPITOL);
  537. rs.destroyed = destroyed;
  538. gameEvents.sendAndApply(rs);
  539. return;
  540. }
  541. }
  542. }
  543. }
  544. void CGTownInstance::clearArmy(IGameEventCallback & gameEvents) const
  545. {
  546. while(!stacks.empty())
  547. {
  548. gameEvents.eraseStack(StackLocation(id, stacks.begin()->first), true);
  549. }
  550. }
  551. BoatId CGTownInstance::getBoatType() const
  552. {
  553. return getTown()->faction->boatType;
  554. }
  555. int CGTownInstance::getMarketEfficiency() const
  556. {
  557. if(!hasBuiltResourceMarketplace())
  558. return 0;
  559. const PlayerState *p = cb->getPlayerState(tempOwner);
  560. assert(p);
  561. int marketCount = p->valOfBonuses(BonusType::MARKETPLACE_ACCESS);
  562. return marketCount;
  563. }
  564. std::vector<TradeItemBuy> CGTownInstance::availableItemsIds(EMarketMode mode) const
  565. {
  566. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  567. {
  568. std::vector<TradeItemBuy> ret;
  569. for(const ArtifactID a : cb->gameState().getMap().townMerchantArtifacts)
  570. ret.push_back(a);
  571. return ret;
  572. }
  573. else if ( mode == EMarketMode::RESOURCE_SKILL )
  574. {
  575. for (const auto & buildingID : builtBuildings)
  576. {
  577. const auto * buildingPtr = getTown()->buildings.at(buildingID).get();
  578. if (vstd::contains(buildingPtr->marketModes, mode))
  579. return buildingPtr->marketOffer;
  580. }
  581. logMod->warn("Town has resource-skill trade but has no skills to offer!");
  582. return {};
  583. }
  584. else
  585. return IMarket::availableItemsIds(mode);
  586. }
  587. ObjectInstanceID CGTownInstance::getObjInstanceID() const
  588. {
  589. return id;
  590. }
  591. void CGTownInstance::updateAppearance()
  592. {
  593. const auto tile = cb->getTile(visitablePos());
  594. if(!tile)
  595. {
  596. logGlobal->warn("Town is misplaced at (%d, %d, %d)", visitablePos().x,
  597. visitablePos().y, visitablePos().z);
  598. return;
  599. }
  600. auto terrain = tile->getTerrainID();
  601. //FIXME: not the best way to do this
  602. auto app = getObjectHandler()->getOverride(terrain, this);
  603. if (app)
  604. appearance = app;
  605. }
  606. std::string CGTownInstance::nodeName() const
  607. {
  608. return "Town at " + pos.toString();
  609. }
  610. void CGTownInstance::updateMoraleBonusFromArmy()
  611. {
  612. auto b = getExportedBonusList().getFirst(Selector::sourceType()(BonusSource::ARMY).And(Selector::type()(BonusType::MORALE)));
  613. if(!b)
  614. {
  615. b = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::MORALE, BonusSource::ARMY, 0, BonusSourceID());
  616. addNewBonus(b);
  617. }
  618. if (getGarrisonHero())
  619. {
  620. b->val = 0;
  621. nodeHasChanged();
  622. }
  623. else
  624. CArmedInstance::updateMoraleBonusFromArmy();
  625. }
  626. void CGTownInstance::recreateBuildingsBonuses()
  627. {
  628. BonusList bl;
  629. getExportedBonusList().getBonuses(bl, Selector::sourceType()(BonusSource::TOWN_STRUCTURE));
  630. for(const auto & b : bl)
  631. removeBonus(b);
  632. for(const auto & bid : builtBuildings)
  633. {
  634. bool bonusesReplacedByUpgrade = false;
  635. for(const auto & upgradeID : builtBuildings)
  636. {
  637. const auto & upgrade = getTown()->buildings.at(upgradeID);
  638. if (upgrade->getBase() == bid && upgrade->upgradeReplacesBonuses)
  639. bonusesReplacedByUpgrade = true;
  640. }
  641. // bonuses from this building are disabled and replaced by bonuses from an upgrade
  642. if (bonusesReplacedByUpgrade)
  643. continue;
  644. const auto & building = getTown()->buildings.at(bid);
  645. if(building->buildingBonuses.empty())
  646. continue;
  647. for(auto & bonus : building->buildingBonuses)
  648. {
  649. // Add copy of bonus to bonus system
  650. // Othervice, bonuses with player or global propagator will not stack if player has multiple towns of same faction
  651. auto bonusCopy = std::make_shared<Bonus>(*bonus);
  652. addNewBonus(bonusCopy);
  653. }
  654. }
  655. }
  656. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  657. {
  658. if(getVisitingHero() == h)
  659. return;
  660. if(h)
  661. {
  662. h->detachFromBonusSystem(cb->gameState());
  663. h->setVisitedTown(this, false);
  664. h->attachToBonusSystem(cb->gameState());
  665. visitingHero = h->id;
  666. }
  667. else if (visitingHero.hasValue())
  668. {
  669. auto oldVisitor = dynamic_cast<CGHeroInstance*>(cb->gameState().getObjInstance(visitingHero));
  670. oldVisitor->detachFromBonusSystem(cb->gameState());
  671. oldVisitor->setVisitedTown(nullptr, false);
  672. oldVisitor->attachToBonusSystem(cb->gameState());
  673. visitingHero = {};
  674. }
  675. }
  676. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  677. {
  678. if(getGarrisonHero() == h)
  679. return;
  680. if(h)
  681. {
  682. h->detachFromBonusSystem(cb->gameState());
  683. h->setVisitedTown(this, true);
  684. h->attachToBonusSystem(cb->gameState());
  685. garrisonHero = h->id;
  686. }
  687. else if (garrisonHero.hasValue())
  688. {
  689. auto oldVisitor = dynamic_cast<CGHeroInstance*>(cb->gameState().getObjInstance(garrisonHero));
  690. oldVisitor->detachFromBonusSystem(cb->gameState());
  691. oldVisitor->setVisitedTown(nullptr, false);
  692. oldVisitor->attachToBonusSystem(cb->gameState());
  693. garrisonHero = {};
  694. }
  695. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  696. }
  697. const CGHeroInstance * CGTownInstance::getVisitingHero() const
  698. {
  699. if (!visitingHero.hasValue())
  700. return nullptr;
  701. return cb->getHero(visitingHero);
  702. }
  703. const CGHeroInstance * CGTownInstance::getGarrisonHero() const
  704. {
  705. if (!garrisonHero.hasValue())
  706. return nullptr;
  707. return cb->getHero(garrisonHero);
  708. }
  709. bool CGTownInstance::armedGarrison() const
  710. {
  711. return !stacks.empty() || getGarrisonHero();
  712. }
  713. int CGTownInstance::getTownLevel() const
  714. {
  715. // count all buildings that are not upgrades
  716. int level = 0;
  717. for(const auto & bid : builtBuildings)
  718. {
  719. if(getTown()->buildings.at(bid)->upgrade == BuildingID::NONE)
  720. level++;
  721. }
  722. return level;
  723. }
  724. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  725. {
  726. return townAndVis;
  727. }
  728. std::string CGTownInstance::getNameTranslated() const
  729. {
  730. return customName.empty() ? LIBRARY->generaltexth->translate(nameTextId) : customName;
  731. }
  732. std::string CGTownInstance::getNameTextID() const
  733. {
  734. return nameTextId;
  735. }
  736. void CGTownInstance::setNameTextId( const std::string & newName )
  737. {
  738. nameTextId = newName;
  739. }
  740. void CGTownInstance::setCustomName( const std::string & newName )
  741. {
  742. customName = newName;
  743. }
  744. const CArmedInstance * CGTownInstance::getUpperArmy() const
  745. {
  746. if(getGarrisonHero())
  747. return getGarrisonHero();
  748. return this;
  749. }
  750. bool CGTownInstance::hasBuiltResourceMarketplace() const
  751. {
  752. const auto modes = availableModes();
  753. return std::find(modes.begin(), modes.end(), EMarketMode::RESOURCE_RESOURCE) != modes.end();
  754. }
  755. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  756. {
  757. for(const auto & bid : builtBuildings)
  758. {
  759. if(getTown()->buildings.at(bid)->subId == buildingID)
  760. return true;
  761. }
  762. return false;
  763. }
  764. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  765. {
  766. return vstd::contains(builtBuildings, buildingID);
  767. }
  768. void CGTownInstance::addBuilding(const BuildingID & buildingID)
  769. {
  770. if(buildingID == BuildingID::NONE)
  771. return;
  772. builtBuildings.insert(buildingID);
  773. }
  774. std::set<EMarketMode> CGTownInstance::availableModes() const
  775. {
  776. std::set<EMarketMode> result;
  777. for (const auto & buildingID : builtBuildings)
  778. {
  779. const auto * buildingPtr = getTown()->buildings.at(buildingID).get();
  780. result.insert(buildingPtr->marketModes.begin(), buildingPtr->marketModes.end());
  781. }
  782. return result;
  783. }
  784. void CGTownInstance::removeBuilding(const BuildingID & buildingID)
  785. {
  786. if(!vstd::contains(builtBuildings, buildingID))
  787. return;
  788. builtBuildings.erase(buildingID);
  789. }
  790. void CGTownInstance::removeAllBuildings()
  791. {
  792. builtBuildings.clear();
  793. }
  794. std::set<BuildingID> CGTownInstance::getBuildings() const
  795. {
  796. return builtBuildings;
  797. }
  798. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  799. {
  800. if (vstd::contains(getTown()->buildings, buildingID))
  801. return getTown()->buildings.at(buildingID)->resources;
  802. else
  803. {
  804. logGlobal->error("Town %s at %s has no possible building %d!", getNameTranslated(), anchorPos().toString(), buildingID.toEnum());
  805. return TResources();
  806. }
  807. }
  808. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  809. {
  810. const auto & building = getTown()->buildings.at(buildID);
  811. //TODO: find better solution to prevent infinite loops
  812. std::set<BuildingID> processed;
  813. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  814. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  815. {
  816. if (getTown()->buildings.count(id) == 0)
  817. {
  818. logMod->error("Invalid building ID %d in building dependencies!", id.getNum());
  819. return CBuilding::TRequired::OperatorAll();
  820. }
  821. const auto & build = getTown()->buildings.at(id);
  822. CBuilding::TRequired::OperatorAll requirements;
  823. if (!hasBuilt(id))
  824. {
  825. if (deep)
  826. requirements.expressions.emplace_back(id);
  827. else
  828. return id;
  829. }
  830. if(!vstd::contains(processed, id))
  831. {
  832. processed.insert(id);
  833. if (build->upgrade != BuildingID::NONE)
  834. requirements.expressions.push_back(dependTest(build->upgrade));
  835. requirements.expressions.push_back(build->requirements.morph(dependTest));
  836. }
  837. return requirements;
  838. };
  839. CBuilding::TRequired::OperatorAll requirements;
  840. if (building->upgrade != BuildingID::NONE)
  841. {
  842. const auto & upgr = getTown()->buildings.at(building->upgrade);
  843. requirements.expressions.push_back(dependTest(upgr->bid));
  844. processed.clear();
  845. }
  846. requirements.expressions.push_back(building->requirements.morph(dependTest));
  847. CBuilding::TRequired::Variant variant(requirements);
  848. CBuilding::TRequired ret(variant);
  849. ret.minimize();
  850. return ret;
  851. }
  852. void CGTownInstance::addHeroToStructureVisitors(IGameEventCallback & gameEvents, const CGHeroInstance *h, si64 structureInstanceID ) const
  853. {
  854. if(getVisitingHero() == h)
  855. gameEvents.setObjPropertyValue(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  856. else if(getGarrisonHero() == h)
  857. gameEvents.setObjPropertyValue(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  858. else
  859. {
  860. //should never ever happen
  861. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  862. throw std::runtime_error("unexpected hero in CGTownInstance::addHeroToStructureVisitors");
  863. }
  864. }
  865. void CGTownInstance::battleFinished(IGameEventCallback & gameEvents, const CGHeroInstance * hero, const BattleResult & result) const
  866. {
  867. if(result.winner == BattleSide::ATTACKER)
  868. {
  869. clearArmy(gameEvents);
  870. onTownCaptured(gameEvents, hero->getOwner());
  871. }
  872. }
  873. void CGTownInstance::onTownCaptured(IGameEventCallback & gameEvents, const PlayerColor & winner) const
  874. {
  875. setOwner(gameEvents, winner);
  876. gameEvents.changeFogOfWar(getSightCenter(), getSightRadius(), winner, ETileVisibility::REVEALED);
  877. }
  878. void CGTownInstance::afterAddToMap(CMap * map)
  879. {
  880. map->townAddedToMap(this);
  881. }
  882. void CGTownInstance::afterRemoveFromMap(CMap * map)
  883. {
  884. map->townRemovedFromMap(this);
  885. }
  886. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  887. {
  888. CGObjectInstance::serializeJsonOwner(handler);
  889. if(!handler.saving)
  890. handler.serializeEnum("tightFormation", formation, NArmyFormation::names); //for old format
  891. CArmedInstance::serializeJsonOptions(handler);
  892. handler.serializeString("name", nameTextId);
  893. {
  894. auto decodeBuilding = [this](const std::string & identifier) -> si32
  895. {
  896. auto rawId = LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), getTown()->getBuildingScope(), identifier);
  897. if(rawId)
  898. return rawId.value();
  899. else
  900. return -1;
  901. };
  902. auto encodeBuilding = [this](si32 index) -> std::string
  903. {
  904. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  905. };
  906. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  907. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  908. if(handler.saving)
  909. {
  910. bool customBuildings = false;
  911. boost::logic::tribool hasFort(false);
  912. for(const BuildingID & id : forbiddenBuildings)
  913. {
  914. buildingsLIC.none.insert(id.getNum());
  915. customBuildings = true;
  916. }
  917. for(const BuildingID & id : builtBuildings)
  918. {
  919. if(id == BuildingID::DEFAULT)
  920. continue;
  921. const auto & building = getTown()->buildings.at(id);
  922. if(building->mode == CBuilding::BUILD_AUTO)
  923. continue;
  924. if(id == BuildingID::FORT)
  925. hasFort = true;
  926. buildingsLIC.all.insert(id.getNum());
  927. customBuildings = true;
  928. }
  929. if(customBuildings)
  930. handler.serializeLIC("buildings", buildingsLIC);
  931. else
  932. handler.serializeBool("hasFort",hasFort);
  933. }
  934. else
  935. {
  936. handler.serializeLIC("buildings", buildingsLIC);
  937. addBuilding(BuildingID::VILLAGE_HALL);
  938. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  939. {
  940. addBuilding(BuildingID::DEFAULT);
  941. bool hasFort = false;
  942. handler.serializeBool("hasFort",hasFort);
  943. if(hasFort)
  944. addBuilding(BuildingID::FORT);
  945. }
  946. else
  947. {
  948. for(const si32 item : buildingsLIC.none)
  949. forbiddenBuildings.insert(BuildingID(item));
  950. for(const si32 item : buildingsLIC.all)
  951. addBuilding(BuildingID(item));
  952. }
  953. }
  954. }
  955. {
  956. handler.serializeIdArray( "possibleSpells", possibleSpells);
  957. handler.serializeIdArray( "obligatorySpells", obligatorySpells);
  958. }
  959. {
  960. auto eventsHandler = handler.enterArray("events");
  961. eventsHandler.syncSize(events, JsonNode::JsonType::DATA_VECTOR);
  962. eventsHandler.serializeStruct(events);
  963. }
  964. handler.serializeId("alignmentToPlayer", alignmentToPlayer, PlayerColor::NEUTRAL);
  965. }
  966. const CFaction * CGTownInstance::getFaction() const
  967. {
  968. return getFactionID().toFaction();
  969. }
  970. const CTown * CGTownInstance::getTown() const
  971. {
  972. if(ID == Obj::RANDOM_TOWN)
  973. return LIBRARY->townh->randomFaction->town.get();
  974. return getFaction()->town.get();
  975. }
  976. FactionID CGTownInstance::getFactionID() const
  977. {
  978. return FactionID(subID.getNum());
  979. }
  980. TerrainId CGTownInstance::getNativeTerrain() const
  981. {
  982. auto const & terrain = getTown()->faction->getNativeTerrain();
  983. if (!terrain.toEntity(LIBRARY)->isSurface() && !terrain.toEntity(LIBRARY)->isUnderground())
  984. logMod->warn("Faction %s has terrain %s as native, but terrain is not suitable for either surface or subterranean layers!", getTown()->faction->getJsonKey(), terrain.toEntity(LIBRARY)->getJsonKey());
  985. return terrain;
  986. }
  987. ArtifactID CGTownInstance::getWarMachineInBuilding(BuildingID building) const
  988. {
  989. if (builtBuildings.count(building) == 0)
  990. return ArtifactID::NONE;
  991. if (building == BuildingID::BLACKSMITH && getTown()->warMachineDeprecated.hasValue())
  992. return getTown()->warMachineDeprecated.toCreature()->warMachine;
  993. return getTown()->buildings.at(building)->warMachine;
  994. }
  995. bool CGTownInstance::isWarMachineAvailable(ArtifactID warMachine) const
  996. {
  997. for (auto const & buildingID : builtBuildings)
  998. if (getTown()->buildings.at(buildingID)->warMachine == warMachine)
  999. return true;
  1000. if (builtBuildings.count(BuildingID::BLACKSMITH) &&
  1001. getTown()->warMachineDeprecated.hasValue() &&
  1002. getTown()->warMachineDeprecated.toCreature()->warMachine == warMachine)
  1003. return true;
  1004. return false;
  1005. }
  1006. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1007. : count(_count)
  1008. {
  1009. MetaString formatter;
  1010. formatter.appendRawString(format);
  1011. formatter.replacePositiveNumber(count);
  1012. description = formatter.toString();
  1013. }
  1014. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1015. {
  1016. MetaString formatter;
  1017. formatter.appendRawString("%s %+d");
  1018. formatter.replaceRawString(FactionID(subID).toFaction()->town->buildings.at(building)->getNameTranslated());
  1019. formatter.replacePositiveNumber(count);
  1020. description = formatter.toString();
  1021. }
  1022. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1023. count(_count),
  1024. description(std::move(fullDescription))
  1025. {
  1026. }
  1027. int GrowthInfo::totalGrowth() const
  1028. {
  1029. int ret = 0;
  1030. for(const Entry &entry : entries)
  1031. ret += entry.count;
  1032. // always round up income - we don't want buildings to always produce zero if handicap in use
  1033. return vstd::divideAndCeil(ret * handicapPercentage, 100);
  1034. }
  1035. void CGTownInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1036. {
  1037. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : creatures)
  1038. {
  1039. if (vstd::contains(dwelling.second, stack.getId())) //Dwelling with our creature
  1040. {
  1041. for(const auto & upgrID : dwelling.second)
  1042. {
  1043. if(vstd::contains(stack.getCreature()->upgrades, upgrID)) //possible upgrade
  1044. {
  1045. info.addUpgrade(upgrID, stack.getType());
  1046. }
  1047. }
  1048. }
  1049. }
  1050. }
  1051. void CGTownInstance::postDeserialize()
  1052. {
  1053. for(auto & building : rewardableBuildings)
  1054. building.second->town = this;
  1055. if (getFactionID().hasValue())
  1056. {
  1057. vstd::erase_if(builtBuildings, [this](const BuildingID & buildID)
  1058. {
  1059. return getTown()->buildings.count(buildID) == 0;
  1060. });
  1061. }
  1062. }
  1063. std::map<BuildingID, TownRewardableBuildingInstance*> CGTownInstance::convertOldBuildings(std::vector<TownRewardableBuildingInstance*> oldVector)
  1064. {
  1065. std::map<BuildingID, TownRewardableBuildingInstance*> result;
  1066. for(auto & building : oldVector)
  1067. {
  1068. result[building->getBuildingType()] = new TownRewardableBuildingInstance(*building);
  1069. delete building;
  1070. }
  1071. return result;
  1072. }
  1073. VCMI_LIB_NAMESPACE_END