CGTownInstance.cpp 34 KB

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