CGTownInstance.cpp 34 KB

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