CGTownInstance.cpp 34 KB

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