CGTownInstance.cpp 33 KB

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