CGTownInstance.cpp 35 KB

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