CGTownInstance.cpp 34 KB

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