CGTownInstance.cpp 33 KB

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