CGTownInstance.cpp 33 KB

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