CGTownInstance.cpp 34 KB

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