CGTownInstance.cpp 34 KB

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