CGTownInstance.cpp 34 KB

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