CGTownInstance.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  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 "CObjectClassesHandler.h"
  13. #include "../spells/CSpellHandler.h"
  14. #include "../battle/IBattleInfoCallback.h"
  15. #include "../NetPacks.h"
  16. #include "../CConfigHandler.h"
  17. #include "../CGeneralTextHandler.h"
  18. #include "../CModHandler.h"
  19. #include "../IGameCallback.h"
  20. #include "../CGameState.h"
  21. #include "../mapping/CMap.h"
  22. #include "../CPlayerState.h"
  23. #include "../TerrainHandler.h"
  24. #include "../serializer/JsonSerializeFormat.h"
  25. #include "../HeroBonus.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  28. std::vector<int> CGTownInstance::universitySkills;
  29. int CGTownInstance::getSightRadius() const //returns sight distance
  30. {
  31. auto ret = CBuilding::HEIGHT_NO_TOWER;
  32. for(const auto & bid : builtBuildings)
  33. {
  34. if(bid.IsSpecialOrGrail())
  35. {
  36. auto height = town->buildings.at(bid)->height;
  37. if(ret < height)
  38. ret = height;
  39. }
  40. }
  41. return ret;
  42. }
  43. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  44. {
  45. ///this is freakin' overcomplicated solution
  46. switch (what)
  47. {
  48. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  49. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, visitingHero->id.getNum());
  50. break;
  51. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  52. bonusingBuildings[val]->setProperty (ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  53. break;
  54. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  55. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, garrisonHero->id.getNum());
  56. break;
  57. case ObjProperty::BONUS_VALUE_FIRST:
  58. bonusValue.first = val;
  59. break;
  60. case ObjProperty::BONUS_VALUE_SECOND:
  61. bonusValue.second = val;
  62. break;
  63. }
  64. }
  65. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  66. {
  67. if (hasBuilt(BuildingID::CASTLE))
  68. return CASTLE;
  69. if (hasBuilt(BuildingID::CITADEL))
  70. return CITADEL;
  71. if (hasBuilt(BuildingID::FORT))
  72. return FORT;
  73. return NONE;
  74. }
  75. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  76. {
  77. if (hasBuilt(BuildingID::CAPITOL))
  78. return 3;
  79. if (hasBuilt(BuildingID::CITY_HALL))
  80. return 2;
  81. if (hasBuilt(BuildingID::TOWN_HALL))
  82. return 1;
  83. if (hasBuilt(BuildingID::VILLAGE_HALL))
  84. return 0;
  85. return -1;
  86. }
  87. int CGTownInstance::mageGuildLevel() const
  88. {
  89. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  90. return 5;
  91. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  92. return 4;
  93. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  94. return 3;
  95. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  96. return 2;
  97. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  98. return 1;
  99. return 0;
  100. }
  101. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  102. {
  103. return town->hordeLvl.at(HID);
  104. }
  105. int CGTownInstance::creatureGrowth(const int & level) const
  106. {
  107. return getGrowthInfo(level).totalGrowth();
  108. }
  109. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  110. {
  111. GrowthInfo ret;
  112. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  113. return ret;
  114. if (creatures[level].second.empty())
  115. return ret; //no dwelling
  116. const CCreature *creature = VLC->creh->objects[creatures[level].second.back()];
  117. const int base = creature->getGrowth();
  118. int castleBonus = 0;
  119. ret.entries.emplace_back(VLC->generaltexth->allTexts[590], base); // \n\nBasic growth %d"
  120. if (hasBuilt(BuildingID::CASTLE))
  121. ret.entries.emplace_back(subID, BuildingID::CASTLE, castleBonus = base);
  122. else if (hasBuilt(BuildingID::CITADEL))
  123. ret.entries.emplace_back(subID, BuildingID::CITADEL, castleBonus = base / 2);
  124. if(town->hordeLvl.at(0) == level)//horde 1
  125. if(hasBuilt(BuildingID::HORDE_1))
  126. ret.entries.emplace_back(subID, BuildingID::HORDE_1, creature->getHorde());
  127. if(town->hordeLvl.at(1) == level)//horde 2
  128. if(hasBuilt(BuildingID::HORDE_2))
  129. ret.entries.emplace_back(subID, BuildingID::HORDE_2, creature->getHorde());
  130. //statue-of-legion-like bonus: % to base+castle
  131. TConstBonusListPtr bonuses2 = getBonuses(Selector::type()(Bonus::CREATURE_GROWTH_PERCENT));
  132. for(const auto & b : *bonuses2)
  133. {
  134. const auto growth = b->val * (base + castleBonus) / 100;
  135. ret.entries.emplace_back(growth, b->Description(growth));
  136. }
  137. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  138. TConstBonusListPtr bonuses = getBonuses(Selector::type()(Bonus::CREATURE_GROWTH).And(Selector::subtype()(level)));
  139. for(const auto & b : *bonuses)
  140. ret.entries.emplace_back(b->val, b->Description());
  141. int dwellingBonus = 0;
  142. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  143. {
  144. dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
  145. }
  146. if(dwellingBonus)
  147. ret.entries.emplace_back(VLC->generaltexth->allTexts[591], dwellingBonus); // \nExternal dwellings %+d
  148. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  149. ret.entries.emplace_back(subID, BuildingID::GRAIL, ret.totalGrowth() / 2);
  150. return ret;
  151. }
  152. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<ConstTransitivePtr<CGDwelling> >& dwellings) const
  153. {
  154. int totalBonus = 0;
  155. for (const auto& dwelling : dwellings)
  156. {
  157. for (const auto& creature : dwelling->creatures)
  158. {
  159. totalBonus += vstd::contains(creatureIds, creature.second[0]) ? 1 : 0;
  160. }
  161. }
  162. return totalBonus;
  163. }
  164. TResources CGTownInstance::dailyIncome() const
  165. {
  166. TResources ret;
  167. for(const auto & p : town->buildings)
  168. {
  169. BuildingID buildingUpgrade;
  170. for(const auto & p2 : town->buildings)
  171. {
  172. if (p2.second->upgrade == p.first)
  173. {
  174. buildingUpgrade = p2.first;
  175. }
  176. }
  177. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  178. {
  179. ret += p.second->produce;
  180. }
  181. }
  182. return ret;
  183. }
  184. bool CGTownInstance::hasFort() const
  185. {
  186. return hasBuilt(BuildingID::FORT);
  187. }
  188. bool CGTownInstance::hasCapitol() const
  189. {
  190. return hasBuilt(BuildingID::CAPITOL);
  191. }
  192. CGTownInstance::CGTownInstance():
  193. IShipyard(this),
  194. IMarket(),
  195. town(nullptr),
  196. builded(0),
  197. destroyed(0),
  198. identifier(0),
  199. alignmentToPlayer(PlayerColor::NEUTRAL)
  200. {
  201. this->setNodeType(CBonusSystemNode::TOWN);
  202. }
  203. CGTownInstance::~CGTownInstance()
  204. {
  205. for (auto & elem : bonusingBuildings)
  206. delete elem;
  207. }
  208. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  209. {
  210. if(checkGuild && mageGuildLevel() < level)
  211. return 0;
  212. int ret = 6 - level; //how many spells are available at this level
  213. if (hasBuilt(BuildingSubID::LIBRARY))
  214. ret++;
  215. return ret;
  216. }
  217. bool CGTownInstance::needsLastStack() const
  218. {
  219. return garrisonHero != nullptr;
  220. }
  221. void CGTownInstance::setOwner(const PlayerColor & player) const
  222. {
  223. removeCapitols(player);
  224. cb->setOwner(this, player);
  225. }
  226. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  227. {
  228. if(!cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  229. {
  230. if(armedGarrison() || visitingHero)
  231. {
  232. const CGHeroInstance * defendingHero = visitingHero ? visitingHero : garrisonHero;
  233. const CArmedInstance * defendingArmy = defendingHero ? (CArmedInstance *)defendingHero : this;
  234. const bool isBattleOutside = isBattleOutsideTown(defendingHero);
  235. if(!isBattleOutside && visitingHero && defendingHero == visitingHero)
  236. {
  237. //we have two approaches to merge armies: mergeGarrisonOnSiege() and used in the CGameHandler::garrisonSwap(ObjectInstanceID tid)
  238. auto * nodeSiege = defendingHero->whereShouldBeAttachedOnSiege(isBattleOutside);
  239. if(nodeSiege == (CBonusSystemNode *)this)
  240. cb->swapGarrisonOnSiege(this->id);
  241. const_cast<CGHeroInstance *>(defendingHero)->inTownGarrison = false; //hack to return visitor from garrison after battle
  242. }
  243. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (isBattleOutside ? nullptr : this));
  244. }
  245. else
  246. {
  247. auto heroColor = h->getOwner();
  248. onTownCaptured(heroColor);
  249. if(cb->gameState()->getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
  250. {
  251. return; //we just won game, we do not need to perform any extra actions
  252. //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
  253. }
  254. cb->heroVisitCastle(this, h);
  255. }
  256. }
  257. else if(h->visitablePos() == visitablePos())
  258. {
  259. bool commander_recover = h->commander && !h->commander->alive;
  260. if (commander_recover) // rise commander from dead
  261. {
  262. SetCommanderProperty scp;
  263. scp.heroid = h->id;
  264. scp.which = SetCommanderProperty::ALIVE;
  265. scp.amount = 1;
  266. cb->sendAndApply(&scp);
  267. }
  268. cb->heroVisitCastle(this, h);
  269. // TODO(vmarkovtsev): implement payment for rising the commander
  270. if (commander_recover) // info window about commander
  271. {
  272. InfoWindow iw;
  273. iw.player = h->tempOwner;
  274. iw.text << h->commander->getName();
  275. iw.components.emplace_back(*h->commander);
  276. cb->showInfoDialog(&iw);
  277. }
  278. }
  279. else
  280. {
  281. logGlobal->error("%s visits allied town of %s from different pos?", h->getNameTranslated(), name);
  282. }
  283. }
  284. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  285. {
  286. //FIXME: find out why this issue appears on random maps
  287. if(visitingHero == h)
  288. {
  289. cb->stopHeroVisitCastle(this, h);
  290. logGlobal->trace("%s correctly left town %s", h->getNameTranslated(), name);
  291. }
  292. else
  293. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->getNameTranslated(), name);
  294. }
  295. std::string CGTownInstance::getObjectName() const
  296. {
  297. return name + ", " + town->faction->getNameTranslated();
  298. }
  299. bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
  300. {
  301. return town->getBuildingType(subId) != BuildingID::NONE;
  302. }
  303. void CGTownInstance::initOverriddenBids()
  304. {
  305. for(const auto & bid : builtBuildings)
  306. {
  307. const auto & overrideThem = town->buildings.at(bid)->overrideBids;
  308. for(const auto & overrideIt : overrideThem)
  309. overriddenBuildings.insert(overrideIt);
  310. }
  311. }
  312. bool CGTownInstance::isBonusingBuildingAdded(BuildingID::EBuildingID bid) const
  313. {
  314. auto present = std::find_if(bonusingBuildings.begin(), bonusingBuildings.end(), [&](CGTownBuilding* building)
  315. {
  316. return building->getBuildingType().num == bid;
  317. });
  318. return present != bonusingBuildings.end();
  319. }
  320. void CGTownInstance::addTownBonuses(CRandomGenerator & rand)
  321. {
  322. for(const auto & kvp : town->buildings)
  323. {
  324. if(vstd::contains(overriddenBuildings, kvp.first))
  325. continue;
  326. if(kvp.second->IsVisitingBonus())
  327. bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
  328. if(kvp.second->IsWeekBonus())
  329. bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
  330. if(kvp.second->subId == BuildingSubID::CONFIGURABLE_REWARD)
  331. {
  332. auto * newBuilding = new CTownRewardableBuilding(this);
  333. kvp.second->rewardableObjectInfo.configureObject(newBuilding->configuration(), rand);
  334. bonusingBuildings.push_back(newBuilding);
  335. }
  336. }
  337. }
  338. DamageRange CGTownInstance::getTowerDamageRange() const
  339. {
  340. assert(hasBuilt(BuildingID::CASTLE));
  341. // http://heroes.thelazy.net/wiki/Arrow_tower
  342. // base damage, irregardless of town level
  343. static constexpr int baseDamage = 6;
  344. // extra damage, for each building in town
  345. static constexpr int extraDamage = 1;
  346. const int minDamage = baseDamage + extraDamage * getTownLevel();
  347. return {
  348. minDamage,
  349. minDamage * 2
  350. };
  351. }
  352. DamageRange CGTownInstance::getKeepDamageRange() const
  353. {
  354. assert(hasBuilt(BuildingID::CITADEL));
  355. // http://heroes.thelazy.net/wiki/Arrow_tower
  356. // base damage, irregardless of town level
  357. static constexpr int baseDamage = 10;
  358. // extra damage, for each building in town
  359. static constexpr int extraDamage = 2;
  360. const int minDamage = baseDamage + extraDamage * getTownLevel();
  361. return {
  362. minDamage,
  363. minDamage * 2
  364. };
  365. }
  366. void CGTownInstance::deleteTownBonus(BuildingID::EBuildingID bid)
  367. {
  368. size_t i = 0;
  369. CGTownBuilding * freeIt = nullptr;
  370. for(i = 0; i != bonusingBuildings.size(); i++)
  371. {
  372. if(bonusingBuildings[i]->getBuildingType() == bid)
  373. {
  374. freeIt = bonusingBuildings[i];
  375. break;
  376. }
  377. }
  378. if(freeIt == nullptr)
  379. return;
  380. auto building = town->buildings.at(bid);
  381. auto isVisitingBonus = building->IsVisitingBonus();
  382. auto isWeekBonus = building->IsWeekBonus();
  383. if(!isVisitingBonus && !isWeekBonus)
  384. return;
  385. bonusingBuildings.erase(bonusingBuildings.begin() + i);
  386. delete freeIt;
  387. }
  388. void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
  389. {
  390. blockVisit = true;
  391. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  392. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  393. else
  394. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  395. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  396. {
  397. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  398. int upgradeNum = 0;
  399. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  400. {
  401. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  402. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  403. }
  404. }
  405. initOverriddenBids();
  406. addTownBonuses(rand); //add special bonuses from buildings to the bonusingBuildings vector.
  407. recreateBuildingsBonuses();
  408. updateAppearance();
  409. }
  410. void CGTownInstance::newTurn(CRandomGenerator & 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 < PlayerColor::PLAYER_LIMIT)
  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->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  425. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  426. }
  427. const auto * manaVortex = getBonusingBuilding(BuildingSubID::MANA_VORTEX);
  428. if (manaVortex != nullptr)
  429. cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  430. //get Mana Vortex or Stables bonuses
  431. //same code is in the CGameHandler::buildStructure method
  432. if (visitingHero != nullptr)
  433. cb->visitCastleObjects(this, visitingHero);
  434. if (garrisonHero != nullptr)
  435. cb->visitCastleObjects(this, garrisonHero);
  436. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  437. {
  438. std::vector<SlotID> nativeCrits; //slots
  439. for(const auto & elem : Slots())
  440. {
  441. if (elem.second->type->getFaction() == subID) //native
  442. {
  443. nativeCrits.push_back(elem.first); //collect matching slots
  444. }
  445. }
  446. if(!nativeCrits.empty())
  447. {
  448. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  449. StackLocation sl(this, pos);
  450. const CCreature *c = getCreature(pos);
  451. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  452. {
  453. cb->changeStackCount(sl, c->getGrowth());
  454. }
  455. else //upgrade
  456. {
  457. cb->changeStackType(sl, VLC->creh->objects[*c->upgrades.begin()]);
  458. }
  459. }
  460. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  461. {
  462. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  463. if (!town->creatures[i].empty())
  464. {
  465. CreatureID c = town->creatures[i][0];
  466. SlotID n;
  467. TQuantity count = creatureGrowth(i);
  468. if (!count) // no dwelling
  469. count = VLC->creh->objects[c]->getGrowth();
  470. {//no lower tiers or above current month
  471. if ((n = getSlotFor(c)).validSlot())
  472. {
  473. StackLocation sl(this, n);
  474. if (slotEmpty(n))
  475. cb->insertNewStack(sl, VLC->creh->objects[c], count);
  476. else //add to existing
  477. cb->changeStackCount(sl, count);
  478. }
  479. }
  480. }
  481. }
  482. }
  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(-3,2,0)};
  502. }
  503. void CGTownInstance::mergeGarrisonOnSiege() const
  504. {
  505. auto getWeakestStackSlot = [&](ui64 powerLimit)
  506. {
  507. std::vector<SlotID> weakSlots;
  508. auto stacksList = visitingHero->stacks;
  509. std::pair<SlotID, CStackInstance *> pair;
  510. while(!stacksList.empty())
  511. {
  512. pair = *vstd::minElementByFun(stacksList, [&](const std::pair<SlotID, CStackInstance *> & elem) { return elem.second->getPower(); });
  513. if(powerLimit > pair.second->getPower() &&
  514. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  515. {
  516. weakSlots.push_back(pair.first);
  517. stacksList.erase(pair.first);
  518. }
  519. else
  520. break;
  521. }
  522. if(!weakSlots.empty())
  523. return *std::max_element(weakSlots.begin(), weakSlots.end());
  524. return SlotID();
  525. };
  526. auto count = static_cast<int>(stacks.size());
  527. for(int i = 0; i < count; i++)
  528. {
  529. auto pair = *vstd::maxElementByFun(stacks, [&](const std::pair<SlotID, CStackInstance *> & elem)
  530. {
  531. ui64 power = elem.second->getPower();
  532. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  533. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  534. power += visitingHero->getStack(dst).getPower();
  535. return power;
  536. });
  537. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  538. if(dst.validSlot())
  539. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  540. else
  541. {
  542. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  543. if(dst.validSlot())
  544. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  545. }
  546. }
  547. }
  548. void CGTownInstance::removeCapitols(const PlayerColor & owner) const
  549. {
  550. if (hasCapitol()) // search if there's an older capitol
  551. {
  552. PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
  553. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  554. {
  555. if (*i != this && (*i)->hasCapitol())
  556. {
  557. RazeStructures rs;
  558. rs.tid = id;
  559. rs.bid.insert(BuildingID::CAPITOL);
  560. rs.destroyed = destroyed;
  561. cb->sendAndApply(&rs);
  562. return;
  563. }
  564. }
  565. }
  566. }
  567. void CGTownInstance::clearArmy() const
  568. {
  569. while(!stacks.empty())
  570. {
  571. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  572. }
  573. }
  574. BoatId CGTownInstance::getBoatType() const
  575. {
  576. switch (town->faction->alignment)
  577. {
  578. case EAlignment::EVIL : return EBoatId::BOAT_EVIL;
  579. case EAlignment::GOOD : return EBoatId::BOAT_GOOD;
  580. case EAlignment::NEUTRAL : return EBoatId::BOAT_NEUTRAL;
  581. default: return EBoatId::NONE;
  582. }
  583. }
  584. int CGTownInstance::getMarketEfficiency() const
  585. {
  586. if(!hasBuiltSomeTradeBuilding())
  587. return 0;
  588. const PlayerState *p = cb->getPlayerState(tempOwner);
  589. assert(p);
  590. int marketCount = 0;
  591. for(const CGTownInstance *t : p->towns)
  592. if(t->hasBuiltSomeTradeBuilding())
  593. marketCount++;
  594. return marketCount;
  595. }
  596. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  597. {
  598. switch(mode)
  599. {
  600. case EMarketMode::RESOURCE_RESOURCE:
  601. case EMarketMode::RESOURCE_PLAYER:
  602. return hasBuilt(BuildingID::MARKETPLACE);
  603. case EMarketMode::ARTIFACT_RESOURCE:
  604. case EMarketMode::RESOURCE_ARTIFACT:
  605. return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
  606. case EMarketMode::CREATURE_RESOURCE:
  607. return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
  608. case EMarketMode::CREATURE_UNDEAD:
  609. return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
  610. case EMarketMode::RESOURCE_SKILL:
  611. return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
  612. default:
  613. assert(0);
  614. return false;
  615. }
  616. }
  617. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  618. {
  619. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  620. {
  621. std::vector<int> ret;
  622. for(const CArtifact *a : merchantArtifacts)
  623. if(a)
  624. ret.push_back(a->getId());
  625. else
  626. ret.push_back(-1);
  627. return ret;
  628. }
  629. else if ( mode == EMarketMode::RESOURCE_SKILL )
  630. {
  631. return universitySkills;
  632. }
  633. else
  634. return IMarket::availableItemsIds(mode);
  635. }
  636. void CGTownInstance::setType(si32 ID, si32 subID)
  637. {
  638. assert(ID == Obj::TOWN); // just in case
  639. CGObjectInstance::setType(ID, subID);
  640. town = (*VLC->townh)[subID]->town;
  641. randomizeArmy(subID);
  642. updateAppearance();
  643. }
  644. void CGTownInstance::updateAppearance()
  645. {
  646. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  647. //FIXME: not the best way to do this
  648. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(terrain, this);
  649. if (app)
  650. appearance = app;
  651. }
  652. std::string CGTownInstance::nodeName() const
  653. {
  654. return "Town (" + (town ? town->faction->getNameTranslated() : "unknown") + ") of " + name;
  655. }
  656. void CGTownInstance::deserializationFix()
  657. {
  658. attachTo(townAndVis);
  659. //Hero is already handled by CGameState::attachArmedObjects
  660. // if(visitingHero)
  661. // visitingHero->attachTo(&townAndVis);
  662. // if(garrisonHero)
  663. // garrisonHero->attachTo(this);
  664. }
  665. void CGTownInstance::updateMoraleBonusFromArmy()
  666. {
  667. auto b = getExportedBonusList().getFirst(Selector::sourceType()(Bonus::ARMY).And(Selector::type()(Bonus::MORALE)));
  668. if(!b)
  669. {
  670. b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  671. addNewBonus(b);
  672. }
  673. if (garrisonHero)
  674. {
  675. b->val = 0;
  676. CBonusSystemNode::treeHasChanged();
  677. }
  678. else
  679. CArmedInstance::updateMoraleBonusFromArmy();
  680. }
  681. void CGTownInstance::recreateBuildingsBonuses()
  682. {
  683. BonusList bl;
  684. getExportedBonusList().getBonuses(bl, Selector::sourceType()(Bonus::TOWN_STRUCTURE));
  685. for(const auto & b : bl)
  686. removeBonus(b);
  687. for(const auto & bid : builtBuildings)
  688. {
  689. if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
  690. continue;
  691. auto building = town->buildings.at(bid);
  692. if(building->buildingBonuses.empty())
  693. continue;
  694. for(auto & bonus : building->buildingBonuses)
  695. addNewBonus(bonus);
  696. }
  697. }
  698. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  699. {
  700. assert(!!visitingHero == !h);
  701. if(h)
  702. {
  703. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  704. assert(p);
  705. h->detachFrom(*p);
  706. h->attachTo(townAndVis);
  707. visitingHero = h;
  708. h->visitedTown = this;
  709. h->inTownGarrison = false;
  710. }
  711. else
  712. {
  713. PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
  714. visitingHero->visitedTown = nullptr;
  715. visitingHero->detachFrom(townAndVis);
  716. visitingHero->attachTo(*p);
  717. visitingHero = nullptr;
  718. }
  719. }
  720. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  721. {
  722. assert(!!garrisonHero == !h);
  723. if(h)
  724. {
  725. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  726. assert(p);
  727. h->detachFrom(*p);
  728. h->attachTo(*this);
  729. garrisonHero = h;
  730. h->visitedTown = this;
  731. h->inTownGarrison = true;
  732. }
  733. else
  734. {
  735. PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
  736. garrisonHero->visitedTown = nullptr;
  737. garrisonHero->inTownGarrison = false;
  738. garrisonHero->detachFrom(*this);
  739. garrisonHero->attachTo(*p);
  740. garrisonHero = nullptr;
  741. }
  742. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  743. }
  744. bool CGTownInstance::armedGarrison() const
  745. {
  746. return !stacks.empty() || garrisonHero;
  747. }
  748. const CTown * CGTownInstance::getTown() const
  749. {
  750. if(ID == Obj::RANDOM_TOWN)
  751. return VLC->townh->randomTown;
  752. else
  753. {
  754. if(nullptr == town)
  755. {
  756. return (*VLC->townh)[subID]->town;
  757. }
  758. else
  759. return town;
  760. }
  761. }
  762. int CGTownInstance::getTownLevel() const
  763. {
  764. // count all buildings that are not upgrades
  765. int level = 0;
  766. for(const auto & bid : builtBuildings)
  767. {
  768. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  769. level++;
  770. }
  771. return level;
  772. }
  773. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  774. {
  775. return townAndVis;
  776. }
  777. std::string CGTownInstance::getNameTranslated() const
  778. {
  779. return name;
  780. }
  781. void CGTownInstance::setNameTranslated( const std::string & newName )
  782. {
  783. name = newName;
  784. }
  785. const CArmedInstance * CGTownInstance::getUpperArmy() const
  786. {
  787. if(garrisonHero)
  788. return garrisonHero;
  789. return this;
  790. }
  791. const CGTownBuilding * CGTownInstance::getBonusingBuilding(BuildingSubID::EBuildingSubID subId) const
  792. {
  793. for(auto * const building : bonusingBuildings)
  794. {
  795. if(building->getBuildingSubtype() == subId)
  796. return building;
  797. }
  798. return nullptr;
  799. }
  800. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  801. {
  802. for(const auto & bid : builtBuildings)
  803. {
  804. if(town->buildings.at(bid)->IsTradeBuilding())
  805. return true;
  806. }
  807. return false;
  808. }
  809. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  810. {
  811. for(const auto & bid : builtBuildings)
  812. {
  813. if(town->buildings.at(bid)->subId == buildingID)
  814. return true;
  815. }
  816. return false;
  817. }
  818. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  819. {
  820. return vstd::contains(builtBuildings, buildingID);
  821. }
  822. bool CGTownInstance::hasBuilt(const BuildingID & buildingID, int townID) const
  823. {
  824. if (townID == town->faction->getIndex() || townID == ETownType::ANY)
  825. return hasBuilt(buildingID);
  826. return false;
  827. }
  828. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  829. {
  830. if (vstd::contains(town->buildings, buildingID))
  831. return town->buildings.at(buildingID)->resources;
  832. else
  833. {
  834. logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
  835. return TResources();
  836. }
  837. }
  838. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  839. {
  840. const CBuilding * building = town->buildings.at(buildID);
  841. //TODO: find better solution to prevent infinite loops
  842. std::set<BuildingID> processed;
  843. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  844. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  845. {
  846. const CBuilding * build = town->buildings.at(id);
  847. CBuilding::TRequired::OperatorAll requirements;
  848. if (!hasBuilt(id))
  849. {
  850. if (deep)
  851. requirements.expressions.emplace_back(id);
  852. else
  853. return id;
  854. }
  855. if(!vstd::contains(processed, id))
  856. {
  857. processed.insert(id);
  858. if (build->upgrade != BuildingID::NONE)
  859. requirements.expressions.push_back(dependTest(build->upgrade));
  860. requirements.expressions.push_back(build->requirements.morph(dependTest));
  861. }
  862. return requirements;
  863. };
  864. CBuilding::TRequired::OperatorAll requirements;
  865. if (building->upgrade != BuildingID::NONE)
  866. {
  867. const CBuilding * upgr = town->buildings.at(building->upgrade);
  868. requirements.expressions.push_back(dependTest(upgr->bid));
  869. processed.clear();
  870. }
  871. requirements.expressions.push_back(building->requirements.morph(dependTest));
  872. CBuilding::TRequired::Variant variant(requirements);
  873. CBuilding::TRequired ret(variant);
  874. ret.minimize();
  875. return ret;
  876. }
  877. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  878. {
  879. if(visitingHero == h)
  880. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  881. else if(garrisonHero == h)
  882. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  883. else
  884. {
  885. //should never ever happen
  886. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  887. throw std::runtime_error("internal error");
  888. }
  889. }
  890. void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
  891. {
  892. if(result.winner == BattleSide::ATTACKER)
  893. {
  894. clearArmy();
  895. onTownCaptured(hero->getOwner());
  896. }
  897. }
  898. void CGTownInstance::onTownCaptured(const PlayerColor & winner) const
  899. {
  900. setOwner(winner);
  901. FoWChange fw;
  902. fw.player = winner;
  903. fw.mode = 1;
  904. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), winner, 1);
  905. cb->sendAndApply(& fw);
  906. }
  907. void CGTownInstance::afterAddToMap(CMap * map)
  908. {
  909. if(ID == Obj::TOWN)
  910. map->towns.emplace_back(this);
  911. }
  912. void CGTownInstance::afterRemoveFromMap(CMap * map)
  913. {
  914. if (ID == Obj::TOWN)
  915. vstd::erase_if_present(map->towns, this);
  916. }
  917. void CGTownInstance::reset()
  918. {
  919. CGTownInstance::merchantArtifacts.clear();
  920. CGTownInstance::universitySkills.clear();
  921. }
  922. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  923. {
  924. static const std::vector<std::string> FORMATIONS = { "wide", "tight" };
  925. CGObjectInstance::serializeJsonOwner(handler);
  926. CCreatureSet::serializeJson(handler, "army", 7);
  927. handler.serializeEnum("tightFormation", formation, FORMATIONS);
  928. handler.serializeString("name", name);
  929. {
  930. auto decodeBuilding = [this](const std::string & identifier) -> si32
  931. {
  932. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier);
  933. if(rawId)
  934. return rawId.value();
  935. else
  936. return -1;
  937. };
  938. auto encodeBuilding = [this](si32 index) -> std::string
  939. {
  940. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  941. };
  942. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  943. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  944. if(handler.saving)
  945. {
  946. bool customBuildings = false;
  947. boost::logic::tribool hasFort(false);
  948. for(const BuildingID & id : forbiddenBuildings)
  949. {
  950. buildingsLIC.none.insert(id);
  951. customBuildings = true;
  952. }
  953. for(const BuildingID & id : builtBuildings)
  954. {
  955. if(id == BuildingID::DEFAULT)
  956. continue;
  957. const CBuilding * building = getTown()->buildings.at(id);
  958. if(building->mode == CBuilding::BUILD_AUTO)
  959. continue;
  960. if(id == BuildingID::FORT)
  961. hasFort = true;
  962. buildingsLIC.all.insert(id);
  963. customBuildings = true;
  964. }
  965. if(customBuildings)
  966. handler.serializeLIC("buildings", buildingsLIC);
  967. else
  968. handler.serializeBool("hasFort",hasFort);
  969. }
  970. else
  971. {
  972. handler.serializeLIC("buildings", buildingsLIC);
  973. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  974. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  975. {
  976. builtBuildings.insert(BuildingID::DEFAULT);
  977. bool hasFort = false;
  978. handler.serializeBool("hasFort",hasFort);
  979. if(hasFort)
  980. builtBuildings.insert(BuildingID::FORT);
  981. }
  982. else
  983. {
  984. for(const si32 item : buildingsLIC.none)
  985. forbiddenBuildings.insert(BuildingID(item));
  986. for(const si32 item : buildingsLIC.all)
  987. builtBuildings.insert(BuildingID(item));
  988. }
  989. }
  990. }
  991. {
  992. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  993. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  994. if(handler.saving)
  995. {
  996. for(const SpellID & id : possibleSpells)
  997. spellsLIC.any[id.num] = true;
  998. for(const SpellID & id : obligatorySpells)
  999. spellsLIC.all[id.num] = true;
  1000. }
  1001. handler.serializeLIC("spells", spellsLIC);
  1002. if(!handler.saving)
  1003. {
  1004. possibleSpells.clear();
  1005. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1006. {
  1007. if(spellsLIC.any[idx])
  1008. possibleSpells.emplace_back(idx);
  1009. }
  1010. obligatorySpells.clear();
  1011. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1012. {
  1013. if(spellsLIC.all[idx])
  1014. obligatorySpells.emplace_back(idx);
  1015. }
  1016. }
  1017. }
  1018. }
  1019. FactionID CGTownInstance::getFaction() const
  1020. {
  1021. return town->faction->getId();
  1022. }
  1023. TerrainId CGTownInstance::getNativeTerrain() const
  1024. {
  1025. return town->faction->getNativeTerrain();
  1026. }
  1027. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1028. : count(_count)
  1029. {
  1030. description = boost::str(boost::format(format) % count);
  1031. }
  1032. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1033. {
  1034. description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated() % count);
  1035. }
  1036. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1037. count(_count),
  1038. description(std::move(fullDescription))
  1039. {
  1040. }
  1041. CTownAndVisitingHero::CTownAndVisitingHero()
  1042. {
  1043. setNodeType(TOWN_AND_VISITOR);
  1044. }
  1045. int GrowthInfo::totalGrowth() const
  1046. {
  1047. int ret = 0;
  1048. for(const Entry &entry : entries)
  1049. ret += entry.count;
  1050. return ret;
  1051. }
  1052. VCMI_LIB_NAMESPACE_END