CGTownInstance.cpp 35 KB

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