CGTownInstance.cpp 34 KB

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