CGTownInstance.cpp 31 KB

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