CGTownInstance.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  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(this),
  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. //it does not check hasBuilt because this check is in the OnHeroVisit handler
  321. void CGTownInstance::tryAddOnePerWeekBonus(BuildingSubID::EBuildingSubID subID)
  322. {
  323. auto bid = town->getBuildingType(subID);
  324. if(bid != BuildingID::NONE && !isBonusingBuildingAdded(bid))
  325. bonusingBuildings.push_back(new COPWBonus(bid, subID, this));
  326. }
  327. void CGTownInstance::tryAddVisitingBonus(BuildingSubID::EBuildingSubID subID)
  328. {
  329. auto bid = town->getBuildingType(subID);
  330. if(bid != BuildingID::NONE && !isBonusingBuildingAdded(bid))
  331. bonusingBuildings.push_back(new CTownBonus(bid, subID, this));
  332. }
  333. void CGTownInstance::addTownBonuses()
  334. {
  335. for(const auto & kvp : town->buildings)
  336. {
  337. if(vstd::contains(overriddenBuildings, kvp.first))
  338. continue;
  339. if(kvp.second->IsVisitingBonus())
  340. bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
  341. if(kvp.second->IsWeekBonus())
  342. bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
  343. }
  344. }
  345. DamageRange CGTownInstance::getTowerDamageRange() const
  346. {
  347. assert(hasBuilt(BuildingID::CASTLE));
  348. // http://heroes.thelazy.net/wiki/Arrow_tower
  349. // base damage, irregardless of town level
  350. static constexpr int baseDamage = 6;
  351. // extra damage, for each building in town
  352. static constexpr int extraDamage = 1;
  353. const int minDamage = baseDamage + extraDamage * getTownLevel();
  354. return {
  355. minDamage,
  356. minDamage * 2
  357. };
  358. }
  359. DamageRange CGTownInstance::getKeepDamageRange() const
  360. {
  361. assert(hasBuilt(BuildingID::CITADEL));
  362. // http://heroes.thelazy.net/wiki/Arrow_tower
  363. // base damage, irregardless of town level
  364. static constexpr int baseDamage = 10;
  365. // extra damage, for each building in town
  366. static constexpr int extraDamage = 2;
  367. const int minDamage = baseDamage + extraDamage * getTownLevel();
  368. return {
  369. minDamage,
  370. minDamage * 2
  371. };
  372. }
  373. void CGTownInstance::deleteTownBonus(BuildingID::EBuildingID bid)
  374. {
  375. size_t i = 0;
  376. CGTownBuilding * freeIt = nullptr;
  377. for(i = 0; i != bonusingBuildings.size(); i++)
  378. {
  379. if(bonusingBuildings[i]->getBuildingType() == bid)
  380. {
  381. freeIt = bonusingBuildings[i];
  382. break;
  383. }
  384. }
  385. if(freeIt == nullptr)
  386. return;
  387. auto building = town->buildings.at(bid);
  388. auto isVisitingBonus = building->IsVisitingBonus();
  389. auto isWeekBonus = building->IsWeekBonus();
  390. if(!isVisitingBonus && !isWeekBonus)
  391. return;
  392. bonusingBuildings.erase(bonusingBuildings.begin() + i);
  393. delete freeIt;
  394. }
  395. void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
  396. {
  397. blockVisit = true;
  398. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  399. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  400. else
  401. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  402. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  403. {
  404. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  405. int upgradeNum = 0;
  406. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  407. {
  408. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  409. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  410. }
  411. }
  412. initOverriddenBids();
  413. addTownBonuses(); //add special bonuses from buildings to the bonusingBuildings vector.
  414. recreateBuildingsBonuses();
  415. updateAppearance();
  416. }
  417. bool CGTownInstance::hasBuiltInOldWay(ETownType::ETownType type, const BuildingID & bid) const
  418. {
  419. return (this->town->faction != nullptr && this->town->faction->getIndex() == type && hasBuilt(bid));
  420. }
  421. void CGTownInstance::newTurn(CRandomGenerator & rand) const
  422. {
  423. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  424. {
  425. //give resources if there's a Mystic Pond
  426. if (hasBuilt(BuildingSubID::MYSTIC_POND)
  427. && cb->getDate(Date::DAY) != 1
  428. && (tempOwner < PlayerColor::PLAYER_LIMIT)
  429. )
  430. {
  431. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  432. resID = (resID==2)?1:resID;
  433. int resVal = rand.nextInt(1, 4);//with size 1..4
  434. cb->giveResource(tempOwner, static_cast<EGameResID>(resID), resVal);
  435. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  436. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  437. }
  438. const auto * manaVortex = getBonusingBuilding(BuildingSubID::MANA_VORTEX);
  439. if (manaVortex != nullptr)
  440. cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  441. //get Mana Vortex or Stables bonuses
  442. //same code is in the CGameHandler::buildStructure method
  443. if (visitingHero != nullptr)
  444. cb->visitCastleObjects(this, visitingHero);
  445. if (garrisonHero != nullptr)
  446. cb->visitCastleObjects(this, garrisonHero);
  447. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  448. {
  449. std::vector<SlotID> nativeCrits; //slots
  450. for(const auto & elem : Slots())
  451. {
  452. if (elem.second->type->getFaction() == subID) //native
  453. {
  454. nativeCrits.push_back(elem.first); //collect matching slots
  455. }
  456. }
  457. if(!nativeCrits.empty())
  458. {
  459. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  460. StackLocation sl(this, pos);
  461. const CCreature *c = getCreature(pos);
  462. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  463. {
  464. cb->changeStackCount(sl, c->getGrowth());
  465. }
  466. else //upgrade
  467. {
  468. cb->changeStackType(sl, VLC->creh->objects[*c->upgrades.begin()]);
  469. }
  470. }
  471. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  472. {
  473. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  474. if (!town->creatures[i].empty())
  475. {
  476. CreatureID c = town->creatures[i][0];
  477. SlotID n;
  478. TQuantity count = creatureGrowth(i);
  479. if (!count) // no dwelling
  480. count = VLC->creh->objects[c]->getGrowth();
  481. {//no lower tiers or above current month
  482. if ((n = getSlotFor(c)).validSlot())
  483. {
  484. StackLocation sl(this, n);
  485. if (slotEmpty(n))
  486. cb->insertNewStack(sl, VLC->creh->objects[c], count);
  487. else //add to existing
  488. cb->changeStackCount(sl, count);
  489. }
  490. }
  491. }
  492. }
  493. }
  494. }
  495. }
  496. /*
  497. int3 CGTownInstance::getSightCenter() const
  498. {
  499. return pos - int3(2,0,0);
  500. }
  501. */
  502. bool CGTownInstance::passableFor(PlayerColor color) const
  503. {
  504. if (!armedGarrison())//empty castle - anyone can visit
  505. return true;
  506. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  507. return false;
  508. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  509. }
  510. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  511. {
  512. offsets = {int3(-1,2,0), int3(-3,2,0)};
  513. }
  514. void CGTownInstance::mergeGarrisonOnSiege() const
  515. {
  516. auto getWeakestStackSlot = [&](ui64 powerLimit)
  517. {
  518. std::vector<SlotID> weakSlots;
  519. auto stacksList = visitingHero->stacks;
  520. std::pair<SlotID, CStackInstance *> pair;
  521. while(!stacksList.empty())
  522. {
  523. pair = *vstd::minElementByFun(stacksList, [&](const std::pair<SlotID, CStackInstance *> & elem) { return elem.second->getPower(); });
  524. if(powerLimit > pair.second->getPower() &&
  525. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  526. {
  527. weakSlots.push_back(pair.first);
  528. stacksList.erase(pair.first);
  529. }
  530. else
  531. break;
  532. }
  533. if(!weakSlots.empty())
  534. return *std::max_element(weakSlots.begin(), weakSlots.end());
  535. return SlotID();
  536. };
  537. auto count = static_cast<int>(stacks.size());
  538. for(int i = 0; i < count; i++)
  539. {
  540. auto pair = *vstd::maxElementByFun(stacks, [&](const std::pair<SlotID, CStackInstance *> & elem)
  541. {
  542. ui64 power = elem.second->getPower();
  543. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  544. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  545. power += visitingHero->getStack(dst).getPower();
  546. return power;
  547. });
  548. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  549. if(dst.validSlot())
  550. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  551. else
  552. {
  553. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  554. if(dst.validSlot())
  555. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  556. }
  557. }
  558. }
  559. void CGTownInstance::removeCapitols(const PlayerColor & owner) const
  560. {
  561. if (hasCapitol()) // search if there's an older capitol
  562. {
  563. PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
  564. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  565. {
  566. if (*i != this && (*i)->hasCapitol())
  567. {
  568. RazeStructures rs;
  569. rs.tid = id;
  570. rs.bid.insert(BuildingID::CAPITOL);
  571. rs.destroyed = destroyed;
  572. cb->sendAndApply(&rs);
  573. return;
  574. }
  575. }
  576. }
  577. }
  578. void CGTownInstance::clearArmy() const
  579. {
  580. while(!stacks.empty())
  581. {
  582. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  583. }
  584. }
  585. BoatId CGTownInstance::getBoatType() const
  586. {
  587. switch (town->faction->alignment)
  588. {
  589. case EAlignment::EVIL : return EBoatId::BOAT_EVIL;
  590. case EAlignment::GOOD : return EBoatId::BOAT_GOOD;
  591. case EAlignment::NEUTRAL : return EBoatId::BOAT_NEUTRAL;
  592. default: return EBoatId::NONE;
  593. }
  594. }
  595. int CGTownInstance::getMarketEfficiency() const
  596. {
  597. if(!hasBuiltSomeTradeBuilding())
  598. return 0;
  599. const PlayerState *p = cb->getPlayerState(tempOwner);
  600. assert(p);
  601. int marketCount = 0;
  602. for(const CGTownInstance *t : p->towns)
  603. if(t->hasBuiltSomeTradeBuilding())
  604. marketCount++;
  605. return marketCount;
  606. }
  607. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  608. {
  609. switch(mode)
  610. {
  611. case EMarketMode::RESOURCE_RESOURCE:
  612. case EMarketMode::RESOURCE_PLAYER:
  613. return hasBuilt(BuildingID::MARKETPLACE);
  614. case EMarketMode::ARTIFACT_RESOURCE:
  615. case EMarketMode::RESOURCE_ARTIFACT:
  616. return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
  617. case EMarketMode::CREATURE_RESOURCE:
  618. return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
  619. case EMarketMode::CREATURE_UNDEAD:
  620. return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
  621. case EMarketMode::RESOURCE_SKILL:
  622. return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
  623. default:
  624. assert(0);
  625. return false;
  626. }
  627. }
  628. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  629. {
  630. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  631. {
  632. std::vector<int> ret;
  633. for(const CArtifact *a : merchantArtifacts)
  634. if(a)
  635. ret.push_back(a->getId());
  636. else
  637. ret.push_back(-1);
  638. return ret;
  639. }
  640. else if ( mode == EMarketMode::RESOURCE_SKILL )
  641. {
  642. return universitySkills;
  643. }
  644. else
  645. return IMarket::availableItemsIds(mode);
  646. }
  647. void CGTownInstance::setType(si32 ID, si32 subID)
  648. {
  649. assert(ID == Obj::TOWN); // just in case
  650. CGObjectInstance::setType(ID, subID);
  651. town = (*VLC->townh)[subID]->town;
  652. randomizeArmy(subID);
  653. updateAppearance();
  654. }
  655. void CGTownInstance::updateAppearance()
  656. {
  657. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  658. //FIXME: not the best way to do this
  659. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(terrain, this);
  660. if (app)
  661. appearance = app;
  662. }
  663. std::string CGTownInstance::nodeName() const
  664. {
  665. return "Town (" + (town ? town->faction->getNameTranslated() : "unknown") + ") of " + name;
  666. }
  667. void CGTownInstance::deserializationFix()
  668. {
  669. attachTo(townAndVis);
  670. //Hero is already handled by CGameState::attachArmedObjects
  671. // if(visitingHero)
  672. // visitingHero->attachTo(&townAndVis);
  673. // if(garrisonHero)
  674. // garrisonHero->attachTo(this);
  675. }
  676. void CGTownInstance::updateMoraleBonusFromArmy()
  677. {
  678. auto b = getExportedBonusList().getFirst(Selector::sourceType()(Bonus::ARMY).And(Selector::type()(Bonus::MORALE)));
  679. if(!b)
  680. {
  681. b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  682. addNewBonus(b);
  683. }
  684. if (garrisonHero)
  685. {
  686. b->val = 0;
  687. CBonusSystemNode::treeHasChanged();
  688. }
  689. else
  690. CArmedInstance::updateMoraleBonusFromArmy();
  691. }
  692. void CGTownInstance::recreateBuildingsBonuses()
  693. {
  694. BonusList bl;
  695. getExportedBonusList().getBonuses(bl, Selector::sourceType()(Bonus::TOWN_STRUCTURE));
  696. for(const auto & b : bl)
  697. removeBonus(b);
  698. for(const auto & bid : builtBuildings)
  699. {
  700. if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
  701. continue;
  702. auto building = town->buildings.at(bid);
  703. if(building->buildingBonuses.empty())
  704. continue;
  705. for(auto & bonus : building->buildingBonuses)
  706. addNewBonus(bonus);
  707. }
  708. }
  709. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  710. {
  711. assert(!!visitingHero == !h);
  712. if(h)
  713. {
  714. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  715. assert(p);
  716. h->detachFrom(*p);
  717. h->attachTo(townAndVis);
  718. visitingHero = h;
  719. h->visitedTown = this;
  720. h->inTownGarrison = false;
  721. }
  722. else
  723. {
  724. PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
  725. visitingHero->visitedTown = nullptr;
  726. visitingHero->detachFrom(townAndVis);
  727. visitingHero->attachTo(*p);
  728. visitingHero = nullptr;
  729. }
  730. }
  731. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  732. {
  733. assert(!!garrisonHero == !h);
  734. if(h)
  735. {
  736. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  737. assert(p);
  738. h->detachFrom(*p);
  739. h->attachTo(*this);
  740. garrisonHero = h;
  741. h->visitedTown = this;
  742. h->inTownGarrison = true;
  743. }
  744. else
  745. {
  746. PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
  747. garrisonHero->visitedTown = nullptr;
  748. garrisonHero->inTownGarrison = false;
  749. garrisonHero->detachFrom(*this);
  750. garrisonHero->attachTo(*p);
  751. garrisonHero = nullptr;
  752. }
  753. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  754. }
  755. bool CGTownInstance::armedGarrison() const
  756. {
  757. return !stacks.empty() || garrisonHero;
  758. }
  759. const CTown * CGTownInstance::getTown() const
  760. {
  761. if(ID == Obj::RANDOM_TOWN)
  762. return VLC->townh->randomTown;
  763. else
  764. {
  765. if(nullptr == town)
  766. {
  767. return (*VLC->townh)[subID]->town;
  768. }
  769. else
  770. return town;
  771. }
  772. }
  773. int CGTownInstance::getTownLevel() const
  774. {
  775. // count all buildings that are not upgrades
  776. int level = 0;
  777. for(const auto & bid : builtBuildings)
  778. {
  779. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  780. level++;
  781. }
  782. return level;
  783. }
  784. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  785. {
  786. return townAndVis;
  787. }
  788. std::string CGTownInstance::getNameTranslated() const
  789. {
  790. return name;
  791. }
  792. void CGTownInstance::setNameTranslated( const std::string & newName )
  793. {
  794. name = newName;
  795. }
  796. const CArmedInstance * CGTownInstance::getUpperArmy() const
  797. {
  798. if(garrisonHero)
  799. return garrisonHero;
  800. return this;
  801. }
  802. const CGTownBuilding * CGTownInstance::getBonusingBuilding(BuildingSubID::EBuildingSubID subId) const
  803. {
  804. for(auto * const building : bonusingBuildings)
  805. {
  806. if(building->getBuildingSubtype() == subId)
  807. return building;
  808. }
  809. return nullptr;
  810. }
  811. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  812. {
  813. for(const auto & bid : builtBuildings)
  814. {
  815. if(town->buildings.at(bid)->IsTradeBuilding())
  816. return true;
  817. }
  818. return false;
  819. }
  820. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  821. {
  822. for(const auto & bid : builtBuildings)
  823. {
  824. if(town->buildings.at(bid)->subId == buildingID)
  825. return true;
  826. }
  827. return false;
  828. }
  829. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  830. {
  831. return vstd::contains(builtBuildings, buildingID);
  832. }
  833. bool CGTownInstance::hasBuilt(const BuildingID & buildingID, int townID) const
  834. {
  835. if (townID == town->faction->getIndex() || townID == ETownType::ANY)
  836. return hasBuilt(buildingID);
  837. return false;
  838. }
  839. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  840. {
  841. if (vstd::contains(town->buildings, buildingID))
  842. return town->buildings.at(buildingID)->resources;
  843. else
  844. {
  845. logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
  846. return TResources();
  847. }
  848. }
  849. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  850. {
  851. const CBuilding * building = town->buildings.at(buildID);
  852. //TODO: find better solution to prevent infinite loops
  853. std::set<BuildingID> processed;
  854. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  855. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  856. {
  857. const CBuilding * build = town->buildings.at(id);
  858. CBuilding::TRequired::OperatorAll requirements;
  859. if (!hasBuilt(id))
  860. {
  861. if (deep)
  862. requirements.expressions.emplace_back(id);
  863. else
  864. return id;
  865. }
  866. if(!vstd::contains(processed, id))
  867. {
  868. processed.insert(id);
  869. if (build->upgrade != BuildingID::NONE)
  870. requirements.expressions.push_back(dependTest(build->upgrade));
  871. requirements.expressions.push_back(build->requirements.morph(dependTest));
  872. }
  873. return requirements;
  874. };
  875. CBuilding::TRequired::OperatorAll requirements;
  876. if (building->upgrade != BuildingID::NONE)
  877. {
  878. const CBuilding * upgr = town->buildings.at(building->upgrade);
  879. requirements.expressions.push_back(dependTest(upgr->bid));
  880. processed.clear();
  881. }
  882. requirements.expressions.push_back(building->requirements.morph(dependTest));
  883. CBuilding::TRequired::Variant variant(requirements);
  884. CBuilding::TRequired ret(variant);
  885. ret.minimize();
  886. return ret;
  887. }
  888. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  889. {
  890. if(visitingHero == h)
  891. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  892. else if(garrisonHero == h)
  893. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  894. else
  895. {
  896. //should never ever happen
  897. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  898. throw std::runtime_error("internal error");
  899. }
  900. }
  901. void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
  902. {
  903. if(result.winner == BattleSide::ATTACKER)
  904. {
  905. clearArmy();
  906. onTownCaptured(hero->getOwner());
  907. }
  908. }
  909. void CGTownInstance::onTownCaptured(const PlayerColor & winner) const
  910. {
  911. setOwner(winner);
  912. FoWChange fw;
  913. fw.player = winner;
  914. fw.mode = 1;
  915. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), winner, 1);
  916. cb->sendAndApply(& fw);
  917. }
  918. void CGTownInstance::afterAddToMap(CMap * map)
  919. {
  920. if(ID == Obj::TOWN)
  921. map->towns.emplace_back(this);
  922. }
  923. void CGTownInstance::afterRemoveFromMap(CMap * map)
  924. {
  925. if (ID == Obj::TOWN)
  926. vstd::erase_if_present(map->towns, this);
  927. }
  928. void CGTownInstance::reset()
  929. {
  930. CGTownInstance::merchantArtifacts.clear();
  931. CGTownInstance::universitySkills.clear();
  932. }
  933. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  934. {
  935. static const std::vector<std::string> FORMATIONS = { "wide", "tight" };
  936. CGObjectInstance::serializeJsonOwner(handler);
  937. CCreatureSet::serializeJson(handler, "army", 7);
  938. handler.serializeEnum("tightFormation", formation, FORMATIONS);
  939. handler.serializeString("name", name);
  940. {
  941. auto decodeBuilding = [this](const std::string & identifier) -> si32
  942. {
  943. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier);
  944. if(rawId)
  945. return rawId.value();
  946. else
  947. return -1;
  948. };
  949. auto encodeBuilding = [this](si32 index) -> std::string
  950. {
  951. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  952. };
  953. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  954. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  955. if(handler.saving)
  956. {
  957. bool customBuildings = false;
  958. boost::logic::tribool hasFort(false);
  959. for(const BuildingID & id : forbiddenBuildings)
  960. {
  961. buildingsLIC.none.insert(id);
  962. customBuildings = true;
  963. }
  964. for(const BuildingID & id : builtBuildings)
  965. {
  966. if(id == BuildingID::DEFAULT)
  967. continue;
  968. const CBuilding * building = getTown()->buildings.at(id);
  969. if(building->mode == CBuilding::BUILD_AUTO)
  970. continue;
  971. if(id == BuildingID::FORT)
  972. hasFort = true;
  973. buildingsLIC.all.insert(id);
  974. customBuildings = true;
  975. }
  976. if(customBuildings)
  977. handler.serializeLIC("buildings", buildingsLIC);
  978. else
  979. handler.serializeBool("hasFort",hasFort);
  980. }
  981. else
  982. {
  983. handler.serializeLIC("buildings", buildingsLIC);
  984. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  985. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  986. {
  987. builtBuildings.insert(BuildingID::DEFAULT);
  988. bool hasFort = false;
  989. handler.serializeBool("hasFort",hasFort);
  990. if(hasFort)
  991. builtBuildings.insert(BuildingID::FORT);
  992. }
  993. else
  994. {
  995. for(const si32 item : buildingsLIC.none)
  996. forbiddenBuildings.insert(BuildingID(item));
  997. for(const si32 item : buildingsLIC.all)
  998. builtBuildings.insert(BuildingID(item));
  999. }
  1000. }
  1001. }
  1002. {
  1003. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  1004. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  1005. if(handler.saving)
  1006. {
  1007. for(const SpellID & id : possibleSpells)
  1008. spellsLIC.any[id.num] = true;
  1009. for(const SpellID & id : obligatorySpells)
  1010. spellsLIC.all[id.num] = true;
  1011. }
  1012. handler.serializeLIC("spells", spellsLIC);
  1013. if(!handler.saving)
  1014. {
  1015. possibleSpells.clear();
  1016. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1017. {
  1018. if(spellsLIC.any[idx])
  1019. possibleSpells.emplace_back(idx);
  1020. }
  1021. obligatorySpells.clear();
  1022. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1023. {
  1024. if(spellsLIC.all[idx])
  1025. obligatorySpells.emplace_back(idx);
  1026. }
  1027. }
  1028. }
  1029. }
  1030. FactionID CGTownInstance::getFaction() const
  1031. {
  1032. return town->faction->getId();
  1033. }
  1034. TerrainId CGTownInstance::getNativeTerrain() const
  1035. {
  1036. return town->faction->getNativeTerrain();
  1037. }
  1038. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1039. : count(_count)
  1040. {
  1041. description = boost::str(boost::format(format) % count);
  1042. }
  1043. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1044. {
  1045. description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated() % count);
  1046. }
  1047. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1048. count(_count),
  1049. description(std::move(fullDescription))
  1050. {
  1051. }
  1052. CTownAndVisitingHero::CTownAndVisitingHero()
  1053. {
  1054. setNodeType(TOWN_AND_VISITOR);
  1055. }
  1056. int GrowthInfo::totalGrowth() const
  1057. {
  1058. int ret = 0;
  1059. for(const Entry &entry : entries)
  1060. ret += entry.count;
  1061. return ret;
  1062. }
  1063. VCMI_LIB_NAMESPACE_END