CGTownInstance.cpp 35 KB

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