CGTownInstance.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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 "../CModHandler.h"
  20. #include "../IGameCallback.h"
  21. #include "../CGameState.h"
  22. #include "../mapping/CMap.h"
  23. #include "../CPlayerState.h"
  24. #include "../TerrainHandler.h"
  25. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  26. #include "../mapObjectConstructors/CObjectClassesHandler.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 << 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(-3,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. switch (town->faction->alignment)
  592. {
  593. case EAlignment::EVIL : return EBoatId::BOAT_EVIL;
  594. case EAlignment::GOOD : return EBoatId::BOAT_GOOD;
  595. case EAlignment::NEUTRAL : return EBoatId::BOAT_NEUTRAL;
  596. default: return EBoatId::NONE;
  597. }
  598. }
  599. int CGTownInstance::getMarketEfficiency() const
  600. {
  601. if(!hasBuiltSomeTradeBuilding())
  602. return 0;
  603. const PlayerState *p = cb->getPlayerState(tempOwner);
  604. assert(p);
  605. int marketCount = 0;
  606. for(const CGTownInstance *t : p->towns)
  607. if(t->hasBuiltSomeTradeBuilding())
  608. marketCount++;
  609. return marketCount;
  610. }
  611. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  612. {
  613. switch(mode)
  614. {
  615. case EMarketMode::RESOURCE_RESOURCE:
  616. case EMarketMode::RESOURCE_PLAYER:
  617. return hasBuilt(BuildingID::MARKETPLACE);
  618. case EMarketMode::ARTIFACT_RESOURCE:
  619. case EMarketMode::RESOURCE_ARTIFACT:
  620. return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
  621. case EMarketMode::CREATURE_RESOURCE:
  622. return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
  623. case EMarketMode::CREATURE_UNDEAD:
  624. return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
  625. case EMarketMode::RESOURCE_SKILL:
  626. return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
  627. default:
  628. assert(0);
  629. return false;
  630. }
  631. }
  632. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  633. {
  634. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  635. {
  636. std::vector<int> ret;
  637. for(const CArtifact *a : merchantArtifacts)
  638. if(a)
  639. ret.push_back(a->getId());
  640. else
  641. ret.push_back(-1);
  642. return ret;
  643. }
  644. else if ( mode == EMarketMode::RESOURCE_SKILL )
  645. {
  646. return universitySkills;
  647. }
  648. else
  649. return IMarket::availableItemsIds(mode);
  650. }
  651. void CGTownInstance::setType(si32 ID, si32 subID)
  652. {
  653. assert(ID == Obj::TOWN); // just in case
  654. CGObjectInstance::setType(ID, subID);
  655. town = (*VLC->townh)[subID]->town;
  656. randomizeArmy(subID);
  657. updateAppearance();
  658. }
  659. void CGTownInstance::updateAppearance()
  660. {
  661. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  662. //FIXME: not the best way to do this
  663. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(terrain, this);
  664. if (app)
  665. appearance = app;
  666. }
  667. std::string CGTownInstance::nodeName() const
  668. {
  669. return "Town (" + (town ? town->faction->getNameTranslated() : "unknown") + ") of " + name;
  670. }
  671. void CGTownInstance::deserializationFix()
  672. {
  673. attachTo(townAndVis);
  674. //Hero is already handled by CGameState::attachArmedObjects
  675. // if(visitingHero)
  676. // visitingHero->attachTo(&townAndVis);
  677. // if(garrisonHero)
  678. // garrisonHero->attachTo(this);
  679. }
  680. void CGTownInstance::updateMoraleBonusFromArmy()
  681. {
  682. auto b = getExportedBonusList().getFirst(Selector::sourceType()(BonusSource::ARMY).And(Selector::type()(BonusType::MORALE)));
  683. if(!b)
  684. {
  685. b = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::MORALE, BonusSource::ARMY, 0, -1);
  686. addNewBonus(b);
  687. }
  688. if (garrisonHero)
  689. {
  690. b->val = 0;
  691. CBonusSystemNode::treeHasChanged();
  692. }
  693. else
  694. CArmedInstance::updateMoraleBonusFromArmy();
  695. }
  696. void CGTownInstance::recreateBuildingsBonuses()
  697. {
  698. BonusList bl;
  699. getExportedBonusList().getBonuses(bl, Selector::sourceType()(BonusSource::TOWN_STRUCTURE));
  700. for(const auto & b : bl)
  701. removeBonus(b);
  702. for(const auto & bid : builtBuildings)
  703. {
  704. if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
  705. continue;
  706. auto building = town->buildings.at(bid);
  707. if(building->buildingBonuses.empty())
  708. continue;
  709. for(auto & bonus : building->buildingBonuses)
  710. addNewBonus(bonus);
  711. }
  712. }
  713. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  714. {
  715. if(visitingHero.get() == h)
  716. return;
  717. if(h)
  718. {
  719. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  720. assert(p);
  721. h->detachFrom(*p);
  722. h->attachTo(townAndVis);
  723. visitingHero = h;
  724. h->visitedTown = this;
  725. h->inTownGarrison = false;
  726. }
  727. else
  728. {
  729. PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
  730. visitingHero->visitedTown = nullptr;
  731. visitingHero->detachFrom(townAndVis);
  732. visitingHero->attachTo(*p);
  733. visitingHero = nullptr;
  734. }
  735. }
  736. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  737. {
  738. if(garrisonHero.get() == h)
  739. return;
  740. if(h)
  741. {
  742. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  743. assert(p);
  744. h->detachFrom(*p);
  745. h->attachTo(*this);
  746. garrisonHero = h;
  747. h->visitedTown = this;
  748. h->inTownGarrison = true;
  749. }
  750. else
  751. {
  752. PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
  753. garrisonHero->visitedTown = nullptr;
  754. garrisonHero->inTownGarrison = false;
  755. garrisonHero->detachFrom(*this);
  756. garrisonHero->attachTo(*p);
  757. garrisonHero = nullptr;
  758. }
  759. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  760. }
  761. bool CGTownInstance::armedGarrison() const
  762. {
  763. return !stacks.empty() || garrisonHero;
  764. }
  765. const CTown * CGTownInstance::getTown() const
  766. {
  767. if(ID == Obj::RANDOM_TOWN)
  768. return VLC->townh->randomTown;
  769. else
  770. {
  771. if(nullptr == town)
  772. {
  773. return (*VLC->townh)[subID]->town;
  774. }
  775. else
  776. return town;
  777. }
  778. }
  779. int CGTownInstance::getTownLevel() const
  780. {
  781. // count all buildings that are not upgrades
  782. int level = 0;
  783. for(const auto & bid : builtBuildings)
  784. {
  785. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  786. level++;
  787. }
  788. return level;
  789. }
  790. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  791. {
  792. return townAndVis;
  793. }
  794. std::string CGTownInstance::getNameTranslated() const
  795. {
  796. return name;
  797. }
  798. void CGTownInstance::setNameTranslated( const std::string & newName )
  799. {
  800. name = newName;
  801. }
  802. const CArmedInstance * CGTownInstance::getUpperArmy() const
  803. {
  804. if(garrisonHero)
  805. return garrisonHero;
  806. return this;
  807. }
  808. std::vector<const CGTownBuilding *> CGTownInstance::getBonusingBuildings(BuildingSubID::EBuildingSubID subId) const
  809. {
  810. std::vector<const CGTownBuilding *> ret;
  811. for(auto * const building : bonusingBuildings)
  812. {
  813. if(building->getBuildingSubtype() == subId)
  814. ret.push_back(building);
  815. }
  816. return ret;
  817. }
  818. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  819. {
  820. for(const auto & bid : builtBuildings)
  821. {
  822. if(town->buildings.at(bid)->IsTradeBuilding())
  823. return true;
  824. }
  825. return false;
  826. }
  827. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  828. {
  829. for(const auto & bid : builtBuildings)
  830. {
  831. if(town->buildings.at(bid)->subId == buildingID)
  832. return true;
  833. }
  834. return false;
  835. }
  836. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  837. {
  838. return vstd::contains(builtBuildings, buildingID);
  839. }
  840. bool CGTownInstance::hasBuilt(const BuildingID & buildingID, int townID) const
  841. {
  842. if (townID == town->faction->getIndex() || townID == ETownType::ANY)
  843. return hasBuilt(buildingID);
  844. return false;
  845. }
  846. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  847. {
  848. if (vstd::contains(town->buildings, buildingID))
  849. return town->buildings.at(buildingID)->resources;
  850. else
  851. {
  852. logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
  853. return TResources();
  854. }
  855. }
  856. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  857. {
  858. const CBuilding * building = town->buildings.at(buildID);
  859. //TODO: find better solution to prevent infinite loops
  860. std::set<BuildingID> processed;
  861. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  862. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  863. {
  864. const CBuilding * build = town->buildings.at(id);
  865. CBuilding::TRequired::OperatorAll requirements;
  866. if (!hasBuilt(id))
  867. {
  868. if (deep)
  869. requirements.expressions.emplace_back(id);
  870. else
  871. return id;
  872. }
  873. if(!vstd::contains(processed, id))
  874. {
  875. processed.insert(id);
  876. if (build->upgrade != BuildingID::NONE)
  877. requirements.expressions.push_back(dependTest(build->upgrade));
  878. requirements.expressions.push_back(build->requirements.morph(dependTest));
  879. }
  880. return requirements;
  881. };
  882. CBuilding::TRequired::OperatorAll requirements;
  883. if (building->upgrade != BuildingID::NONE)
  884. {
  885. const CBuilding * upgr = town->buildings.at(building->upgrade);
  886. requirements.expressions.push_back(dependTest(upgr->bid));
  887. processed.clear();
  888. }
  889. requirements.expressions.push_back(building->requirements.morph(dependTest));
  890. CBuilding::TRequired::Variant variant(requirements);
  891. CBuilding::TRequired ret(variant);
  892. ret.minimize();
  893. return ret;
  894. }
  895. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  896. {
  897. if(visitingHero == h)
  898. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  899. else if(garrisonHero == h)
  900. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  901. else
  902. {
  903. //should never ever happen
  904. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  905. throw std::runtime_error("internal error");
  906. }
  907. }
  908. void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
  909. {
  910. if(result.winner == BattleSide::ATTACKER)
  911. {
  912. clearArmy();
  913. onTownCaptured(hero->getOwner());
  914. }
  915. }
  916. void CGTownInstance::onTownCaptured(const PlayerColor & winner) const
  917. {
  918. setOwner(winner);
  919. FoWChange fw;
  920. fw.player = winner;
  921. fw.mode = 1;
  922. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), winner, 1);
  923. cb->sendAndApply(& fw);
  924. }
  925. void CGTownInstance::afterAddToMap(CMap * map)
  926. {
  927. if(ID == Obj::TOWN)
  928. map->towns.emplace_back(this);
  929. }
  930. void CGTownInstance::afterRemoveFromMap(CMap * map)
  931. {
  932. if (ID == Obj::TOWN)
  933. vstd::erase_if_present(map->towns, this);
  934. }
  935. void CGTownInstance::reset()
  936. {
  937. CGTownInstance::merchantArtifacts.clear();
  938. CGTownInstance::universitySkills.clear();
  939. }
  940. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  941. {
  942. static const std::vector<std::string> FORMATIONS = { "wide", "tight" };
  943. CGObjectInstance::serializeJsonOwner(handler);
  944. CCreatureSet::serializeJson(handler, "army", 7);
  945. handler.serializeEnum("tightFormation", formation, FORMATIONS);
  946. handler.serializeString("name", name);
  947. {
  948. auto decodeBuilding = [this](const std::string & identifier) -> si32
  949. {
  950. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier);
  951. if(rawId)
  952. return rawId.value();
  953. else
  954. return -1;
  955. };
  956. auto encodeBuilding = [this](si32 index) -> std::string
  957. {
  958. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  959. };
  960. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  961. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  962. if(handler.saving)
  963. {
  964. bool customBuildings = false;
  965. boost::logic::tribool hasFort(false);
  966. for(const BuildingID & id : forbiddenBuildings)
  967. {
  968. buildingsLIC.none.insert(id);
  969. customBuildings = true;
  970. }
  971. for(const BuildingID & id : builtBuildings)
  972. {
  973. if(id == BuildingID::DEFAULT)
  974. continue;
  975. const CBuilding * building = getTown()->buildings.at(id);
  976. if(building->mode == CBuilding::BUILD_AUTO)
  977. continue;
  978. if(id == BuildingID::FORT)
  979. hasFort = true;
  980. buildingsLIC.all.insert(id);
  981. customBuildings = true;
  982. }
  983. if(customBuildings)
  984. handler.serializeLIC("buildings", buildingsLIC);
  985. else
  986. handler.serializeBool("hasFort",hasFort);
  987. }
  988. else
  989. {
  990. handler.serializeLIC("buildings", buildingsLIC);
  991. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  992. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  993. {
  994. builtBuildings.insert(BuildingID::DEFAULT);
  995. bool hasFort = false;
  996. handler.serializeBool("hasFort",hasFort);
  997. if(hasFort)
  998. builtBuildings.insert(BuildingID::FORT);
  999. }
  1000. else
  1001. {
  1002. for(const si32 item : buildingsLIC.none)
  1003. forbiddenBuildings.insert(BuildingID(item));
  1004. for(const si32 item : buildingsLIC.all)
  1005. builtBuildings.insert(BuildingID(item));
  1006. }
  1007. }
  1008. }
  1009. {
  1010. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  1011. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  1012. if(handler.saving)
  1013. {
  1014. for(const SpellID & id : possibleSpells)
  1015. spellsLIC.any[id.num] = true;
  1016. for(const SpellID & id : obligatorySpells)
  1017. spellsLIC.all[id.num] = true;
  1018. }
  1019. handler.serializeLIC("spells", spellsLIC);
  1020. if(!handler.saving)
  1021. {
  1022. possibleSpells.clear();
  1023. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1024. {
  1025. if(spellsLIC.any[idx])
  1026. possibleSpells.emplace_back(idx);
  1027. }
  1028. obligatorySpells.clear();
  1029. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1030. {
  1031. if(spellsLIC.all[idx])
  1032. obligatorySpells.emplace_back(idx);
  1033. }
  1034. }
  1035. }
  1036. }
  1037. FactionID CGTownInstance::getFaction() const
  1038. {
  1039. return town->faction->getId();
  1040. }
  1041. TerrainId CGTownInstance::getNativeTerrain() const
  1042. {
  1043. return town->faction->getNativeTerrain();
  1044. }
  1045. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1046. : count(_count)
  1047. {
  1048. description = boost::str(boost::format(format) % count);
  1049. }
  1050. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1051. {
  1052. description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated() % count);
  1053. }
  1054. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1055. count(_count),
  1056. description(std::move(fullDescription))
  1057. {
  1058. }
  1059. CTownAndVisitingHero::CTownAndVisitingHero()
  1060. {
  1061. setNodeType(TOWN_AND_VISITOR);
  1062. }
  1063. int GrowthInfo::totalGrowth() const
  1064. {
  1065. int ret = 0;
  1066. for(const Entry &entry : entries)
  1067. ret += entry.count;
  1068. return ret;
  1069. }
  1070. void CGTownInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1071. {
  1072. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : creatures)
  1073. {
  1074. if (vstd::contains(dwelling.second, stack.type->getId())) //Dwelling with our creature
  1075. {
  1076. for(const auto & upgrID : dwelling.second)
  1077. {
  1078. if(vstd::contains(stack.type->upgrades, upgrID)) //possible upgrade
  1079. {
  1080. info.newID.push_back(upgrID);
  1081. info.cost.push_back(upgrID.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost());
  1082. }
  1083. }
  1084. }
  1085. }
  1086. }
  1087. VCMI_LIB_NAMESPACE_END