CGTownInstance.cpp 33 KB

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