CGTownInstance.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  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 "../gameState/CGameState.h"
  20. #include "../gameState/UpgradeInfo.h"
  21. #include "../mapping/CMap.h"
  22. #include "../CPlayerState.h"
  23. #include "../StartInfo.h"
  24. #include "../TerrainHandler.h"
  25. #include "../callback/IGameInfoCallback.h"
  26. #include "../callback/IGameEventCallback.h"
  27. #include "../callback/IGameRandomizer.h"
  28. #include "../entities/building/CBuilding.h"
  29. #include "../entities/faction/CTownHandler.h"
  30. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  31. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  32. #include "../mapObjects/CGHeroInstance.h"
  33. #include "../modding/ModScope.h"
  34. #include "../networkPacks/StackLocation.h"
  35. #include "../networkPacks/PacksForClient.h"
  36. #include "../networkPacks/PacksForClientBattle.h"
  37. #include "../serializer/JsonSerializeFormat.h"
  38. #include <vstd/RNG.h>
  39. VCMI_LIB_NAMESPACE_BEGIN
  40. int CGTownInstance::getSightRadius() const //returns sight distance
  41. {
  42. auto ret = CBuilding::HEIGHT_NO_TOWER;
  43. for(const auto & bid : builtBuildings)
  44. {
  45. auto height = getTown()->buildings.at(bid)->height;
  46. if(ret < height)
  47. ret = height;
  48. }
  49. return ret;
  50. }
  51. void CGTownInstance::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  52. {
  53. ///this is freakin' overcomplicated solution
  54. switch (what)
  55. {
  56. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  57. rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::VISITORS, getVisitingHero()->id);
  58. break;
  59. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  60. rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::STRUCTURE_CLEAR_VISITORS, NumericID(0));
  61. break;
  62. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  63. rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::VISITORS, getGarrisonHero()->id);
  64. break;
  65. case ObjProperty::BONUS_VALUE_FIRST:
  66. bonusValue.first = identifier.getNum();
  67. break;
  68. case ObjProperty::BONUS_VALUE_SECOND:
  69. bonusValue.second = identifier.getNum();
  70. break;
  71. }
  72. }
  73. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  74. {
  75. if (hasBuilt(BuildingID::CASTLE))
  76. return CASTLE;
  77. if (hasBuilt(BuildingID::CITADEL))
  78. return CITADEL;
  79. if (hasBuilt(BuildingID::FORT))
  80. return FORT;
  81. return NONE;
  82. }
  83. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  84. {
  85. if (hasBuilt(BuildingID::CAPITOL))
  86. return 3;
  87. if (hasBuilt(BuildingID::CITY_HALL))
  88. return 2;
  89. if (hasBuilt(BuildingID::TOWN_HALL))
  90. return 1;
  91. if (hasBuilt(BuildingID::VILLAGE_HALL))
  92. return 0;
  93. return -1;
  94. }
  95. int CGTownInstance::mageGuildLevel() const
  96. {
  97. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  98. return 5;
  99. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  100. return 4;
  101. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  102. return 3;
  103. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  104. return 2;
  105. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  106. return 1;
  107. return 0;
  108. }
  109. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  110. {
  111. return getTown()->hordeLvl.at(HID);
  112. }
  113. int CGTownInstance::creatureGrowth(const int & level) const
  114. {
  115. return getGrowthInfo(level).totalGrowth();
  116. }
  117. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  118. {
  119. GrowthInfo ret;
  120. if (level<0 || level >=getTown()->creatures.size())
  121. return ret;
  122. if (creatures[level].second.empty())
  123. return ret; //no dwelling
  124. const Creature *creature = creatures[level].second.back().toEntity(LIBRARY);
  125. const int base = creature->getGrowth();
  126. int castleBonus = 0;
  127. if(tempOwner.isValidPlayer())
  128. {
  129. auto * playerSettings = cb->getPlayerSettings(tempOwner);
  130. ret.handicapPercentage = playerSettings->handicap.percentGrowth;
  131. }
  132. else
  133. ret.handicapPercentage = 100;
  134. ret.entries.emplace_back(LIBRARY->generaltexth->allTexts[590], base); // \n\nBasic growth %d"
  135. if (hasBuilt(BuildingID::CASTLE))
  136. ret.entries.emplace_back(subID, BuildingID::CASTLE, castleBonus = base);
  137. else if (hasBuilt(BuildingID::CITADEL))
  138. ret.entries.emplace_back(subID, BuildingID::CITADEL, castleBonus = base / 2);
  139. if(getTown()->hordeLvl.at(0) == level)//horde 1
  140. if(hasBuilt(BuildingID::HORDE_1))
  141. ret.entries.emplace_back(subID, BuildingID::HORDE_1, creature->getHorde());
  142. if(getTown()->hordeLvl.at(1) == level)//horde 2
  143. if(hasBuilt(BuildingID::HORDE_2))
  144. ret.entries.emplace_back(subID, BuildingID::HORDE_2, creature->getHorde());
  145. //statue-of-legion-like bonus: % to base+castle
  146. TConstBonusListPtr bonuses2 = getBonusesOfType(BonusType::CREATURE_GROWTH_PERCENT);
  147. for(const auto & b : *bonuses2)
  148. {
  149. const auto growth = b->val * (base + castleBonus) / 100;
  150. if (growth)
  151. {
  152. ret.entries.emplace_back(growth, b->Description(cb, growth));
  153. }
  154. }
  155. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  156. // Note: bonus uses 1-based levels (Pikeman is level 1), town list uses 0-based (Pikeman in 0-th creatures entry)
  157. TConstBonusListPtr bonuses = getBonusesOfType(BonusType::CREATURE_GROWTH, BonusCustomSubtype::creatureLevel(level+1));
  158. for(const auto & b : *bonuses)
  159. ret.entries.emplace_back(b->val, b->Description(cb));
  160. int dwellingBonus = 0;
  161. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  162. {
  163. dwellingBonus = getDwellingBonus(creatures[level].second, p->getOwnedObjects());
  164. }
  165. if(dwellingBonus)
  166. ret.entries.emplace_back(LIBRARY->generaltexth->allTexts[591], dwellingBonus); // \nExternal dwellings %+d
  167. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  168. ret.entries.emplace_back(subID, BuildingID::GRAIL, ret.totalGrowth() / 2);
  169. return ret;
  170. }
  171. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<const CGObjectInstance * >& dwellings) const
  172. {
  173. int totalBonus = 0;
  174. for (const auto& dwelling : dwellings)
  175. {
  176. const auto & dwellingCreatures = dwelling->asOwnable()->providedCreatures();
  177. bool hasMatch = false;
  178. for (const auto& creature : dwellingCreatures)
  179. hasMatch = vstd::contains(creatureIds, creature);
  180. if (hasMatch)
  181. totalBonus += 1;
  182. }
  183. return totalBonus;
  184. }
  185. TResources CGTownInstance::dailyIncome() const
  186. {
  187. TResources ret;
  188. for(const auto & p : getTown()->buildings)
  189. {
  190. BuildingID buildingUpgrade;
  191. for(const auto & p2 : getTown()->buildings)
  192. {
  193. if (p2.second->upgrade == p.first)
  194. {
  195. buildingUpgrade = p2.first;
  196. }
  197. }
  198. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  199. {
  200. ret += p.second->produce;
  201. }
  202. }
  203. if (!getOwner().isValidPlayer())
  204. return ret;
  205. const auto & playerSettings = cb->getPlayerSettings(getOwner());
  206. ret.applyHandicap(playerSettings->handicap.percentIncome);
  207. return ret;
  208. }
  209. std::vector<CreatureID> CGTownInstance::providedCreatures() const
  210. {
  211. return {};
  212. }
  213. bool CGTownInstance::hasFort() const
  214. {
  215. return hasBuilt(BuildingID::FORT);
  216. }
  217. bool CGTownInstance::hasCapitol() const
  218. {
  219. return hasBuilt(BuildingID::CAPITOL);
  220. }
  221. TownFortifications CGTownInstance::fortificationsLevel() const
  222. {
  223. auto result = getTown()->fortifications;
  224. for (auto const & buildingID : builtBuildings)
  225. result += getTown()->buildings.at(buildingID)->fortifications;
  226. if (result.wallsHealth == 0)
  227. return TownFortifications();
  228. return result;
  229. }
  230. CGTownInstance::CGTownInstance(IGameInfoCallback *cb):
  231. CGDwelling(cb),
  232. IMarket(cb),
  233. built(0),
  234. destroyed(0),
  235. identifier(0),
  236. alignmentToPlayer(PlayerColor::NEUTRAL),
  237. spellResearchCounterDay(0),
  238. spellResearchAcceptedCounter(0),
  239. spellResearchAllowed(true)
  240. {
  241. setNodeType(CBonusSystemNode::TOWN);
  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 ? (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. gameEvents.swapGarrisonOnSiege(this->id);
  278. const_cast<CGHeroInstance *>(defendingHero)->setVisitedTown(this, false); //hack to return visitor from garrison after battle
  279. }
  280. gameEvents.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(gameEvents, 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. gameEvents.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. gameEvents.sendAndApply(scp);
  305. }
  306. gameEvents.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. gameEvents.showInfoDialog(&iw);
  315. }
  316. }
  317. }
  318. void CGTownInstance::onHeroLeave(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  319. {
  320. //FIXME: find out why this issue appears on random maps
  321. if(getVisitingHero() == h)
  322. {
  323. gameEvents.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(IGameRandomizer & gameRandomizer)
  340. {
  341. for(const auto & kvp : getTown()->buildings)
  342. {
  343. if(kvp.second->rewardableObjectInfo.getParameters().isNull())
  344. continue;
  345. try {
  346. rewardableBuildings[kvp.first] = std::make_unique<TownRewardableBuildingInstance>(this, kvp.second->bid, gameRandomizer);
  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(IGameRandomizer & gameRandomizer)
  396. {
  397. assert(ID == MapObjectID::TOWN || ID == MapObjectID::RANDOM_TOWN);
  398. if (ID == MapObjectID::RANDOM_TOWN)
  399. {
  400. ID = MapObjectID::TOWN;
  401. subID = randomizeFaction(gameRandomizer.getDefault());
  402. }
  403. assert(ID == Obj::TOWN); // just in case
  404. setType(ID, subID);
  405. randomizeArmy(getFactionID());
  406. updateAppearance();
  407. }
  408. void CGTownInstance::initObj(IGameRandomizer & gameRandomizer) ///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(gameRandomizer);
  426. initializeNeutralTownGarrison(gameRandomizer.getDefault());
  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>(cb, guardID, guardSize));
  458. }
  459. }
  460. void CGTownInstance::newTurn(IGameEventCallback & gameEvents, IGameRandomizer & gameRandomizer) const
  461. {
  462. for(const auto & building : rewardableBuildings)
  463. building.second->newTurn(gameEvents, gameRandomizer);
  464. if(hasBuilt(BuildingSubID::BANK) && bonusValue.second > 0)
  465. {
  466. TResources res;
  467. res[EGameResID::GOLD] = -500;
  468. gameEvents.giveResources(getOwner(), res);
  469. gameEvents.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(IGameEventCallback & gameEvents) 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. gameEvents.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. gameEvents.swapStacks(StackLocation(id, pair.first), StackLocation(getVisitingHero()->id, dst));
  528. }
  529. }
  530. }
  531. void CGTownInstance::removeCapitols(IGameEventCallback & gameEvents, const PlayerColor & owner) const
  532. {
  533. if (hasCapitol()) // search if there's an older capitol
  534. {
  535. const PlayerState* state = cb->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. gameEvents.sendAndApply(rs);
  545. return;
  546. }
  547. }
  548. }
  549. }
  550. void CGTownInstance::clearArmy(IGameEventCallback & gameEvents) const
  551. {
  552. while(!stacks.empty())
  553. {
  554. gameEvents.eraseStack(StackLocation(id, stacks.begin()->first), true);
  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->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::updateMoraleBonusFromArmy()
  606. {
  607. auto b = getExportedBonusList().getFirst(Selector::sourceType()(BonusSource::ARMY).And(Selector::type()(BonusType::MORALE)));
  608. if(!b)
  609. {
  610. b = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::MORALE, BonusSource::ARMY, 0, BonusSourceID());
  611. addNewBonus(b);
  612. }
  613. if (getGarrisonHero())
  614. {
  615. b->val = 0;
  616. nodeHasChanged();
  617. }
  618. else
  619. CArmedInstance::updateMoraleBonusFromArmy();
  620. }
  621. void CGTownInstance::recreateBuildingsBonuses()
  622. {
  623. BonusList bl;
  624. getExportedBonusList().getBonuses(bl, Selector::sourceType()(BonusSource::TOWN_STRUCTURE));
  625. for(const auto & b : bl)
  626. removeBonus(b);
  627. for(const auto & bid : builtBuildings)
  628. {
  629. bool bonusesReplacedByUpgrade = false;
  630. for(const auto & upgradeID : builtBuildings)
  631. {
  632. const auto & upgrade = getTown()->buildings.at(upgradeID);
  633. if (upgrade->getBase() == bid && upgrade->upgradeReplacesBonuses)
  634. bonusesReplacedByUpgrade = true;
  635. }
  636. // bonuses from this building are disabled and replaced by bonuses from an upgrade
  637. if (bonusesReplacedByUpgrade)
  638. continue;
  639. const auto & building = getTown()->buildings.at(bid);
  640. if(building->buildingBonuses.empty())
  641. continue;
  642. for(auto & bonus : building->buildingBonuses)
  643. {
  644. // Add copy of bonus to bonus system
  645. // Othervice, bonuses with player or global propagator will not stack if player has multiple towns of same faction
  646. auto bonusCopy = std::make_shared<Bonus>(*bonus);
  647. addNewBonus(bonusCopy);
  648. }
  649. }
  650. }
  651. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  652. {
  653. if(getVisitingHero() == h)
  654. return;
  655. if(h)
  656. {
  657. h->detachFromBonusSystem(cb->gameState());
  658. h->setVisitedTown(this, false);
  659. h->attachToBonusSystem(cb->gameState());
  660. visitingHero = h->id;
  661. }
  662. else if (visitingHero.hasValue())
  663. {
  664. auto oldVisitor = dynamic_cast<CGHeroInstance*>(cb->gameState().getObjInstance(visitingHero));
  665. oldVisitor->detachFromBonusSystem(cb->gameState());
  666. oldVisitor->setVisitedTown(nullptr, false);
  667. oldVisitor->attachToBonusSystem(cb->gameState());
  668. visitingHero = {};
  669. }
  670. }
  671. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  672. {
  673. if(getGarrisonHero() == h)
  674. return;
  675. if(h)
  676. {
  677. h->detachFromBonusSystem(cb->gameState());
  678. h->setVisitedTown(this, true);
  679. h->attachToBonusSystem(cb->gameState());
  680. garrisonHero = h->id;
  681. }
  682. else if (garrisonHero.hasValue())
  683. {
  684. auto oldVisitor = dynamic_cast<CGHeroInstance*>(cb->gameState().getObjInstance(garrisonHero));
  685. oldVisitor->detachFromBonusSystem(cb->gameState());
  686. oldVisitor->setVisitedTown(nullptr, false);
  687. oldVisitor->attachToBonusSystem(cb->gameState());
  688. garrisonHero = {};
  689. }
  690. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  691. }
  692. const CGHeroInstance * CGTownInstance::getVisitingHero() const
  693. {
  694. if (!visitingHero.hasValue())
  695. return nullptr;
  696. return cb->getHero(visitingHero);
  697. }
  698. const CGHeroInstance * CGTownInstance::getGarrisonHero() const
  699. {
  700. if (!garrisonHero.hasValue())
  701. return nullptr;
  702. return cb->getHero(garrisonHero);
  703. }
  704. bool CGTownInstance::armedGarrison() const
  705. {
  706. return !stacks.empty() || getGarrisonHero();
  707. }
  708. int CGTownInstance::getTownLevel() const
  709. {
  710. // count all buildings that are not upgrades
  711. int level = 0;
  712. for(const auto & bid : builtBuildings)
  713. {
  714. if(getTown()->buildings.at(bid)->upgrade == BuildingID::NONE)
  715. level++;
  716. }
  717. return level;
  718. }
  719. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  720. {
  721. return townAndVis;
  722. }
  723. std::string CGTownInstance::getNameTranslated() const
  724. {
  725. return LIBRARY->generaltexth->translate(nameTextId);
  726. }
  727. std::string CGTownInstance::getNameTextID() const
  728. {
  729. return nameTextId;
  730. }
  731. void CGTownInstance::setNameTextId( const std::string & newName )
  732. {
  733. nameTextId = newName;
  734. }
  735. const CArmedInstance * CGTownInstance::getUpperArmy() const
  736. {
  737. if(getGarrisonHero())
  738. return getGarrisonHero();
  739. return this;
  740. }
  741. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  742. {
  743. return availableModes().empty() ? false : true;
  744. }
  745. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  746. {
  747. for(const auto & bid : builtBuildings)
  748. {
  749. if(getTown()->buildings.at(bid)->subId == buildingID)
  750. return true;
  751. }
  752. return false;
  753. }
  754. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  755. {
  756. return vstd::contains(builtBuildings, buildingID);
  757. }
  758. bool CGTownInstance::hasBuilt(const BuildingID & buildingID, FactionID townID) const
  759. {
  760. if (townID == getTown()->faction->getId() || townID == FactionID::ANY)
  761. return hasBuilt(buildingID);
  762. return false;
  763. }
  764. void CGTownInstance::addBuilding(const BuildingID & buildingID)
  765. {
  766. if(buildingID == BuildingID::NONE)
  767. return;
  768. builtBuildings.insert(buildingID);
  769. }
  770. std::set<EMarketMode> CGTownInstance::availableModes() const
  771. {
  772. std::set<EMarketMode> result;
  773. for (const auto & buildingID : builtBuildings)
  774. {
  775. const auto * buildingPtr = getTown()->buildings.at(buildingID).get();
  776. result.insert(buildingPtr->marketModes.begin(), buildingPtr->marketModes.end());
  777. }
  778. return result;
  779. }
  780. void CGTownInstance::removeBuilding(const BuildingID & buildingID)
  781. {
  782. if(!vstd::contains(builtBuildings, buildingID))
  783. return;
  784. builtBuildings.erase(buildingID);
  785. }
  786. void CGTownInstance::removeAllBuildings()
  787. {
  788. builtBuildings.clear();
  789. }
  790. std::set<BuildingID> CGTownInstance::getBuildings() const
  791. {
  792. return builtBuildings;
  793. }
  794. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  795. {
  796. if (vstd::contains(getTown()->buildings, buildingID))
  797. return getTown()->buildings.at(buildingID)->resources;
  798. else
  799. {
  800. logGlobal->error("Town %s at %s has no possible building %d!", getNameTranslated(), anchorPos().toString(), buildingID.toEnum());
  801. return TResources();
  802. }
  803. }
  804. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  805. {
  806. const auto & building = getTown()->buildings.at(buildID);
  807. //TODO: find better solution to prevent infinite loops
  808. std::set<BuildingID> processed;
  809. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  810. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  811. {
  812. if (getTown()->buildings.count(id) == 0)
  813. {
  814. logMod->error("Invalid building ID %d in building dependencies!", id.getNum());
  815. return CBuilding::TRequired::OperatorAll();
  816. }
  817. const auto & build = getTown()->buildings.at(id);
  818. CBuilding::TRequired::OperatorAll requirements;
  819. if (!hasBuilt(id))
  820. {
  821. if (deep)
  822. requirements.expressions.emplace_back(id);
  823. else
  824. return id;
  825. }
  826. if(!vstd::contains(processed, id))
  827. {
  828. processed.insert(id);
  829. if (build->upgrade != BuildingID::NONE)
  830. requirements.expressions.push_back(dependTest(build->upgrade));
  831. requirements.expressions.push_back(build->requirements.morph(dependTest));
  832. }
  833. return requirements;
  834. };
  835. CBuilding::TRequired::OperatorAll requirements;
  836. if (building->upgrade != BuildingID::NONE)
  837. {
  838. const auto & upgr = getTown()->buildings.at(building->upgrade);
  839. requirements.expressions.push_back(dependTest(upgr->bid));
  840. processed.clear();
  841. }
  842. requirements.expressions.push_back(building->requirements.morph(dependTest));
  843. CBuilding::TRequired::Variant variant(requirements);
  844. CBuilding::TRequired ret(variant);
  845. ret.minimize();
  846. return ret;
  847. }
  848. void CGTownInstance::addHeroToStructureVisitors(IGameEventCallback & gameEvents, const CGHeroInstance *h, si64 structureInstanceID ) const
  849. {
  850. if(getVisitingHero() == h)
  851. gameEvents.setObjPropertyValue(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  852. else if(getGarrisonHero() == h)
  853. gameEvents.setObjPropertyValue(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  854. else
  855. {
  856. //should never ever happen
  857. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  858. throw std::runtime_error("unexpected hero in CGTownInstance::addHeroToStructureVisitors");
  859. }
  860. }
  861. void CGTownInstance::battleFinished(IGameEventCallback & gameEvents, const CGHeroInstance * hero, const BattleResult & result) const
  862. {
  863. if(result.winner == BattleSide::ATTACKER)
  864. {
  865. clearArmy(gameEvents);
  866. onTownCaptured(gameEvents, hero->getOwner());
  867. }
  868. }
  869. void CGTownInstance::onTownCaptured(IGameEventCallback & gameEvents, const PlayerColor & winner) const
  870. {
  871. setOwner(gameEvents, winner);
  872. gameEvents.changeFogOfWar(getSightCenter(), getSightRadius(), winner, ETileVisibility::REVEALED);
  873. }
  874. void CGTownInstance::afterAddToMap(CMap * map)
  875. {
  876. map->townAddedToMap(this);
  877. }
  878. void CGTownInstance::afterRemoveFromMap(CMap * map)
  879. {
  880. map->townRemovedFromMap(this);
  881. }
  882. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  883. {
  884. CGObjectInstance::serializeJsonOwner(handler);
  885. if(!handler.saving)
  886. handler.serializeEnum("tightFormation", formation, NArmyFormation::names); //for old format
  887. CArmedInstance::serializeJsonOptions(handler);
  888. handler.serializeString("name", nameTextId);
  889. {
  890. auto decodeBuilding = [this](const std::string & identifier) -> si32
  891. {
  892. auto rawId = LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), getTown()->getBuildingScope(), identifier);
  893. if(rawId)
  894. return rawId.value();
  895. else
  896. return -1;
  897. };
  898. auto encodeBuilding = [this](si32 index) -> std::string
  899. {
  900. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  901. };
  902. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  903. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  904. if(handler.saving)
  905. {
  906. bool customBuildings = false;
  907. boost::logic::tribool hasFort(false);
  908. for(const BuildingID & id : forbiddenBuildings)
  909. {
  910. buildingsLIC.none.insert(id.getNum());
  911. customBuildings = true;
  912. }
  913. for(const BuildingID & id : builtBuildings)
  914. {
  915. if(id == BuildingID::DEFAULT)
  916. continue;
  917. const auto & building = getTown()->buildings.at(id);
  918. if(building->mode == CBuilding::BUILD_AUTO)
  919. continue;
  920. if(id == BuildingID::FORT)
  921. hasFort = true;
  922. buildingsLIC.all.insert(id.getNum());
  923. customBuildings = true;
  924. }
  925. if(customBuildings)
  926. handler.serializeLIC("buildings", buildingsLIC);
  927. else
  928. handler.serializeBool("hasFort",hasFort);
  929. }
  930. else
  931. {
  932. handler.serializeLIC("buildings", buildingsLIC);
  933. addBuilding(BuildingID::VILLAGE_HALL);
  934. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  935. {
  936. addBuilding(BuildingID::DEFAULT);
  937. bool hasFort = false;
  938. handler.serializeBool("hasFort",hasFort);
  939. if(hasFort)
  940. addBuilding(BuildingID::FORT);
  941. }
  942. else
  943. {
  944. for(const si32 item : buildingsLIC.none)
  945. forbiddenBuildings.insert(BuildingID(item));
  946. for(const si32 item : buildingsLIC.all)
  947. addBuilding(BuildingID(item));
  948. }
  949. }
  950. }
  951. {
  952. handler.serializeIdArray( "possibleSpells", possibleSpells);
  953. handler.serializeIdArray( "obligatorySpells", obligatorySpells);
  954. }
  955. {
  956. auto eventsHandler = handler.enterArray("events");
  957. eventsHandler.syncSize(events, JsonNode::JsonType::DATA_VECTOR);
  958. eventsHandler.serializeStruct(events);
  959. }
  960. handler.serializeId("alignmentToPlayer", alignmentToPlayer, PlayerColor::NEUTRAL);
  961. }
  962. const CFaction * CGTownInstance::getFaction() const
  963. {
  964. return getFactionID().toFaction();
  965. }
  966. const CTown * CGTownInstance::getTown() const
  967. {
  968. if(ID == Obj::RANDOM_TOWN)
  969. return LIBRARY->townh->randomFaction->town.get();
  970. return getFaction()->town.get();
  971. }
  972. FactionID CGTownInstance::getFactionID() const
  973. {
  974. return FactionID(subID.getNum());
  975. }
  976. TerrainId CGTownInstance::getNativeTerrain() const
  977. {
  978. return getTown()->faction->getNativeTerrain();
  979. }
  980. ArtifactID CGTownInstance::getWarMachineInBuilding(BuildingID building) const
  981. {
  982. if (builtBuildings.count(building) == 0)
  983. return ArtifactID::NONE;
  984. if (building == BuildingID::BLACKSMITH && getTown()->warMachineDeprecated.hasValue())
  985. return getTown()->warMachineDeprecated.toCreature()->warMachine;
  986. return getTown()->buildings.at(building)->warMachine;
  987. }
  988. bool CGTownInstance::isWarMachineAvailable(ArtifactID warMachine) const
  989. {
  990. for (auto const & buildingID : builtBuildings)
  991. if (getTown()->buildings.at(buildingID)->warMachine == warMachine)
  992. return true;
  993. if (builtBuildings.count(BuildingID::BLACKSMITH) &&
  994. getTown()->warMachineDeprecated.hasValue() &&
  995. getTown()->warMachineDeprecated.toCreature()->warMachine == warMachine)
  996. return true;
  997. return false;
  998. }
  999. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1000. : count(_count)
  1001. {
  1002. MetaString formatter;
  1003. formatter.appendRawString(format);
  1004. formatter.replacePositiveNumber(count);
  1005. description = formatter.toString();
  1006. }
  1007. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1008. {
  1009. MetaString formatter;
  1010. formatter.appendRawString("%s %+d");
  1011. formatter.replaceRawString(FactionID(subID).toFaction()->town->buildings.at(building)->getNameTranslated());
  1012. formatter.replacePositiveNumber(count);
  1013. description = formatter.toString();
  1014. }
  1015. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1016. count(_count),
  1017. description(std::move(fullDescription))
  1018. {
  1019. }
  1020. CTownAndVisitingHero::CTownAndVisitingHero()
  1021. {
  1022. setNodeType(TOWN_AND_VISITOR);
  1023. }
  1024. int GrowthInfo::totalGrowth() const
  1025. {
  1026. int ret = 0;
  1027. for(const Entry &entry : entries)
  1028. ret += entry.count;
  1029. // always round up income - we don't want buildings to always produce zero if handicap in use
  1030. return vstd::divideAndCeil(ret * handicapPercentage, 100);
  1031. }
  1032. void CGTownInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1033. {
  1034. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : creatures)
  1035. {
  1036. if (vstd::contains(dwelling.second, stack.getId())) //Dwelling with our creature
  1037. {
  1038. for(const auto & upgrID : dwelling.second)
  1039. {
  1040. if(vstd::contains(stack.getCreature()->upgrades, upgrID)) //possible upgrade
  1041. {
  1042. info.addUpgrade(upgrID, stack.getType());
  1043. }
  1044. }
  1045. }
  1046. }
  1047. }
  1048. void CGTownInstance::postDeserialize()
  1049. {
  1050. for(auto & building : rewardableBuildings)
  1051. building.second->town = this;
  1052. if (getFactionID().hasValue())
  1053. {
  1054. vstd::erase_if(builtBuildings, [this](const BuildingID & buildID)
  1055. {
  1056. return getTown()->buildings.count(buildID) == 0;
  1057. });
  1058. }
  1059. }
  1060. std::map<BuildingID, TownRewardableBuildingInstance*> CGTownInstance::convertOldBuildings(std::vector<TownRewardableBuildingInstance*> oldVector)
  1061. {
  1062. std::map<BuildingID, TownRewardableBuildingInstance*> result;
  1063. for(auto & building : oldVector)
  1064. {
  1065. result[building->getBuildingType()] = new TownRewardableBuildingInstance(*building);
  1066. delete building;
  1067. }
  1068. return result;
  1069. }
  1070. VCMI_LIB_NAMESPACE_END