CGHeroInstance.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  1. /*
  2. * CGHeroInstance.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 "CGHeroInstance.h"
  12. #include <vcmi/ServerCallback.h>
  13. #include <vcmi/spells/Spell.h>
  14. #include <vstd/RNG.h>
  15. #include "../callback/IGameInfoCallback.h"
  16. #include "../callback/IGameEventCallback.h"
  17. #include "../callback/IGameRandomizer.h"
  18. #include "../callback/EditorCallback.h"
  19. #include "../texts/CGeneralTextHandler.h"
  20. #include "../TerrainHandler.h"
  21. #include "../RoadHandler.h"
  22. #include "../IGameSettings.h"
  23. #include "../CSoundBase.h"
  24. #include "../spells/CSpellHandler.h"
  25. #include "../CSkillHandler.h"
  26. #include "../gameState/CGameState.h"
  27. #include "../gameState/UpgradeInfo.h"
  28. #include "../CCreatureHandler.h"
  29. #include "../mapping/CMap.h"
  30. #include "../StartInfo.h"
  31. #include "../GameSettings.h"
  32. #include "CGTownInstance.h"
  33. #include "../entities/artifact/ArtifactUtils.h"
  34. #include "../entities/artifact/CArtifact.h"
  35. #include "../entities/faction/CTownHandler.h"
  36. #include "../entities/hero/CHeroHandler.h"
  37. #include "../entities/hero/CHeroClass.h"
  38. #include "../battle/CBattleInfoEssentials.h"
  39. #include "../campaign/CampaignState.h"
  40. #include "../json/JsonBonus.h"
  41. #include "../pathfinder/TurnInfo.h"
  42. #include "../serializer/JsonSerializeFormat.h"
  43. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  44. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  45. #include "../mapObjects/MiscObjects.h"
  46. #include "../modding/ModScope.h"
  47. #include "../networkPacks/PacksForClient.h"
  48. #include "../networkPacks/PacksForClientBattle.h"
  49. #include "../constants/StringConstants.h"
  50. #include "../battle/Unit.h"
  51. #include "CConfigHandler.h"
  52. VCMI_LIB_NAMESPACE_BEGIN
  53. const ui32 CGHeroInstance::NO_PATROLLING = std::numeric_limits<ui32>::max();
  54. void CGHeroPlaceholder::serializeJsonOptions(JsonSerializeFormat & handler)
  55. {
  56. serializeJsonOwner(handler);
  57. bool isHeroType = heroType.has_value();
  58. handler.serializeBool("placeholderType", isHeroType, false);
  59. if(!handler.saving)
  60. {
  61. if(isHeroType)
  62. heroType = HeroTypeID::NONE;
  63. else
  64. powerRank = 0;
  65. }
  66. if(isHeroType)
  67. handler.serializeId("heroType", heroType.value(), HeroTypeID::NONE);
  68. else
  69. handler.serializeInt("powerRank", powerRank.value());
  70. }
  71. FactionID CGHeroInstance::getFactionID() const
  72. {
  73. return getHeroClass()->faction;
  74. }
  75. const IBonusBearer* CGHeroInstance::getBonusBearer() const
  76. {
  77. return this;
  78. }
  79. TerrainId CGHeroInstance::getNativeTerrain() const
  80. {
  81. TerrainId nativeTerrain = ETerrainId::ANY_TERRAIN;
  82. for(const auto & stack : stacks)
  83. {
  84. TerrainId stackNativeTerrain = stack.second->getNativeTerrain(); //consider terrain bonuses e.g. Lodestar.
  85. if(nativeTerrain == ETerrainId::ANY_TERRAIN)
  86. nativeTerrain = stackNativeTerrain;
  87. else if(nativeTerrain != stackNativeTerrain)
  88. return ETerrainId::NONE;
  89. }
  90. return nativeTerrain;
  91. }
  92. bool CGHeroInstance::isCoastVisitable() const
  93. {
  94. return true;
  95. }
  96. bool CGHeroInstance::isBlockedVisitable() const
  97. {
  98. return true;
  99. }
  100. BattleField CGHeroInstance::getBattlefield() const
  101. {
  102. return BattleField::NONE;
  103. }
  104. ui8 CGHeroInstance::getSecSkillLevel(const SecondarySkill & skill) const
  105. {
  106. for(const auto & elem : secSkills)
  107. if(elem.first == skill)
  108. return elem.second;
  109. return 0;
  110. }
  111. void CGHeroInstance::setSecSkillLevel(const SecondarySkill & which, int val, ChangeValueMode mode)
  112. {
  113. int currentLevel = getSecSkillLevel(which);
  114. int newLevel = mode == ChangeValueMode::ABSOLUTE ? val : currentLevel + val;
  115. int newLevelClamped = std::clamp<int>(newLevel, MasteryLevel::NONE, MasteryLevel::EXPERT);
  116. if (currentLevel == newLevelClamped)
  117. return; // no change
  118. if (newLevelClamped == 0) // skill removal
  119. {
  120. vstd::erase_if(secSkills, [which](const std::pair<SecondarySkill, ui8>& pair) { return pair.first == which; });
  121. }
  122. else if(currentLevel == 0) // gained new skill
  123. {
  124. secSkills.emplace_back(which, newLevelClamped);
  125. }
  126. else
  127. {
  128. for (auto & elem : secSkills)
  129. {
  130. if(elem.first == which)
  131. elem.second = newLevelClamped;
  132. }
  133. }
  134. updateSkillBonus(which, newLevelClamped);
  135. }
  136. int3 CGHeroInstance::convertToVisitablePos(const int3 & position) const
  137. {
  138. return position - getVisitableOffset();
  139. }
  140. int3 CGHeroInstance::convertFromVisitablePos(const int3 & position) const
  141. {
  142. return position + getVisitableOffset();
  143. }
  144. bool CGHeroInstance::canLearnSkill() const
  145. {
  146. return secSkills.size() < cb->getSettings().getInteger(EGameSettings::HEROES_SKILL_PER_HERO);
  147. }
  148. bool CGHeroInstance::canLearnSkill(const SecondarySkill & which) const
  149. {
  150. if ( !canLearnSkill())
  151. return false;
  152. if (!cb->isAllowed(which))
  153. return false;
  154. if (getSecSkillLevel(which) > 0)
  155. return false;
  156. if (getHeroClass()->secSkillProbability.count(which) == 0)
  157. return false;
  158. if (getHeroClass()->secSkillProbability.at(which) == 0)
  159. return false;
  160. return true;
  161. }
  162. int CGHeroInstance::movementPointsRemaining() const
  163. {
  164. return movement;
  165. }
  166. void CGHeroInstance::setMovementPoints(int points)
  167. {
  168. if(getBonusBearer()->hasBonusOfType(BonusType::UNLIMITED_MOVEMENT))
  169. movement = 1000000;
  170. else
  171. movement = std::max(0, points);
  172. }
  173. int CGHeroInstance::movementPointsLimit(bool onLand) const
  174. {
  175. auto ti = getTurnInfo(0);
  176. return onLand ? ti->getMovePointsLimitLand() : ti->getMovePointsLimitWater();
  177. }
  178. int CGHeroInstance::getLowestCreatureSpeed() const
  179. {
  180. if(stacksCount() != 0)
  181. {
  182. int minimalSpeed = std::numeric_limits<int>::max();
  183. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  184. for(const auto & slot : Slots())
  185. minimalSpeed = std::min(minimalSpeed, slot.second->getInitiative());
  186. return minimalSpeed;
  187. }
  188. else
  189. {
  190. if(commander && commander->alive)
  191. return commander->getInitiative();
  192. }
  193. return 10;
  194. }
  195. std::unique_ptr<TurnInfo> CGHeroInstance::getTurnInfo(int days) const
  196. {
  197. return std::make_unique<TurnInfo>(turnInfoCache.get(), this, days);
  198. }
  199. int CGHeroInstance::movementPointsLimitCached(bool onLand, const TurnInfo * ti) const
  200. {
  201. if (onLand)
  202. return ti->getMovePointsLimitLand();
  203. else
  204. return ti->getMovePointsLimitWater();
  205. }
  206. CGHeroInstance::CGHeroInstance(IGameInfoCallback * cb)
  207. : CArmedInstance(cb),
  208. CArtifactSet(cb),
  209. tacticFormationEnabled(false),
  210. inTownGarrison(false),
  211. moveDir(4),
  212. mana(UNINITIALIZED_MANA),
  213. movement(UNINITIALIZED_MOVEMENT),
  214. level(1),
  215. exp(UNINITIALIZED_EXPERIENCE),
  216. gender(EHeroGender::DEFAULT),
  217. primarySkills(this),
  218. magicSchoolMastery(this),
  219. turnInfoCache(std::make_unique<TurnInfoCache>(this)),
  220. manaPerKnowledgeCached(this, Selector::type()(BonusType::MANA_PER_KNOWLEDGE_PERCENTAGE))
  221. {
  222. setNodeType(HERO);
  223. ID = Obj::HERO;
  224. secSkills.emplace_back(SecondarySkill::NONE, -1);
  225. }
  226. PlayerColor CGHeroInstance::getOwner() const
  227. {
  228. return tempOwner;
  229. }
  230. const CHeroClass * CGHeroInstance::getHeroClass() const
  231. {
  232. return getHeroType()->heroClass;
  233. }
  234. HeroClassID CGHeroInstance::getHeroClassID() const
  235. {
  236. auto heroType = getHeroTypeID();
  237. if (heroType.hasValue())
  238. return getHeroType()->heroClass->getId();
  239. else
  240. return HeroClassID();
  241. }
  242. const CHero * CGHeroInstance::getHeroType() const
  243. {
  244. return getHeroTypeID().toHeroType();
  245. }
  246. HeroTypeID CGHeroInstance::getHeroTypeID() const
  247. {
  248. if (ID == Obj::RANDOM_HERO)
  249. return HeroTypeID::NONE;
  250. return HeroTypeID(getObjTypeIndex().getNum());
  251. }
  252. void CGHeroInstance::setHeroType(HeroTypeID heroType)
  253. {
  254. subID = heroType;
  255. }
  256. bool CGHeroInstance::isGarrisoned() const
  257. {
  258. return inTownGarrison;
  259. }
  260. const CGTownInstance * CGHeroInstance::getVisitedTown() const
  261. {
  262. if (!visitedTown.hasValue())
  263. return nullptr;
  264. return cb->getTown(visitedTown);
  265. }
  266. CGTownInstance * CGHeroInstance::getVisitedTown()
  267. {
  268. if (!visitedTown.hasValue())
  269. return nullptr;
  270. return dynamic_cast<CGTownInstance*>(cb->gameState().getObjInstance(visitedTown));
  271. }
  272. void CGHeroInstance::setVisitedTown(const CGTownInstance * town, bool garrisoned)
  273. {
  274. if (town)
  275. visitedTown = town->id;
  276. else
  277. visitedTown = {};
  278. inTownGarrison = garrisoned;
  279. }
  280. const CCommanderInstance * CGHeroInstance::getCommander() const
  281. {
  282. return commander.get();
  283. }
  284. CCommanderInstance * CGHeroInstance::getCommander()
  285. {
  286. return commander.get();
  287. }
  288. void CGHeroInstance::initObj(IGameRandomizer & gameRandomizer)
  289. {
  290. if (ID == Obj::HERO)
  291. updateAppearance();
  292. }
  293. void CGHeroInstance::initHero(IGameRandomizer & gameRandomizer, const HeroTypeID & SUBID)
  294. {
  295. subID = SUBID.getNum();
  296. initHero(gameRandomizer);
  297. }
  298. TObjectTypeHandler CGHeroInstance::getObjectHandler() const
  299. {
  300. if (ID == Obj::HERO)
  301. return LIBRARY->objtypeh->getHandlerFor(ID, getHeroClass()->getIndex());
  302. else // prison or random hero
  303. return LIBRARY->objtypeh->getHandlerFor(ID, 0);
  304. }
  305. void CGHeroInstance::updateAppearance()
  306. {
  307. auto handler = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClass()->getIndex());
  308. auto terrain = cb->getTile(visitablePos())->getTerrainID();
  309. auto app = handler->getOverride(terrain, this);
  310. if (app)
  311. appearance = app;
  312. }
  313. void CGHeroInstance::initHero(IGameRandomizer & gameRandomizer)
  314. {
  315. assert(validTypes(true));
  316. if (gender == EHeroGender::DEFAULT)
  317. gender = getHeroType()->gender;
  318. if (ID == Obj::HERO)
  319. {
  320. auto handler = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClass()->getIndex());
  321. appearance = handler->getTemplates().front();
  322. }
  323. if(!vstd::contains(spells, SpellID::PRESET))
  324. {
  325. // hero starts with default spells
  326. for(const auto & spellID : getHeroType()->spells)
  327. spells.insert(spellID);
  328. }
  329. else //remove placeholder
  330. spells -= SpellID::PRESET;
  331. if(!vstd::contains(spells, SpellID::SPELLBOOK_PRESET))
  332. {
  333. // hero starts with default spellbook presence status
  334. if(!getArt(ArtifactPosition::SPELLBOOK) && getHeroType()->haveSpellBook)
  335. {
  336. auto artifact = cb->gameState().createArtifact(ArtifactID::SPELLBOOK);
  337. putArtifact(ArtifactPosition::SPELLBOOK, artifact);
  338. }
  339. }
  340. else
  341. spells -= SpellID::SPELLBOOK_PRESET;
  342. if(!getArt(ArtifactPosition::MACH4))
  343. {
  344. auto artifact = cb->gameState().createArtifact(ArtifactID::CATAPULT);
  345. putArtifact(ArtifactPosition::MACH4, artifact); //everyone has a catapult
  346. }
  347. if(!hasBonusFrom(BonusSource::HERO_BASE_SKILL))
  348. {
  349. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  350. {
  351. pushPrimSkill(static_cast<PrimarySkill>(g), getHeroClass()->primarySkillInitial[g]);
  352. }
  353. }
  354. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::NONE, -1)) //set secondary skills to default
  355. secSkills = getHeroType()->secSkillsInit;
  356. setFormation(EArmyFormation::LOOSE);
  357. if (!stacksCount()) //standard army//initial army
  358. {
  359. initArmy(gameRandomizer.getDefault());
  360. }
  361. assert(validTypes());
  362. if (patrol.patrolling)
  363. patrol.initialPos = visitablePos();
  364. if(exp == UNINITIALIZED_EXPERIENCE)
  365. {
  366. initExp(gameRandomizer.getDefault());
  367. }
  368. else
  369. {
  370. levelUpAutomatically(gameRandomizer);
  371. }
  372. // load base hero bonuses, TODO: per-map loading of base hero bonuses
  373. // must be done separately from global bonuses since recruitable heroes in taverns
  374. // are not attached to global bonus node but need access to some global bonuses
  375. // e.g. MANA_PER_KNOWLEDGE_PERCENTAGE for correct preview and initial state after recruit for(const auto & ob : LIBRARY->modh->heroBaseBonuses)
  376. // or MOVEMENT to compute initial movement before recruiting is finished
  377. const JsonNode & baseBonuses = cb->getSettings().getValue(EGameSettings::BONUSES_PER_HERO);
  378. for(const auto & b : baseBonuses.Struct())
  379. {
  380. auto bonus = JsonUtils::parseBonus(b.second);
  381. bonus->source = BonusSource::HERO_BASE_SKILL;
  382. bonus->sid = BonusSourceID(id);
  383. bonus->duration = BonusDuration::PERMANENT;
  384. addNewBonus(bonus);
  385. }
  386. if (cb->getSettings().getBoolean(EGameSettings::MODULE_COMMANDERS) && !commander && getHeroClass()->commander.hasValue())
  387. {
  388. commander = std::make_unique<CCommanderInstance>(cb, getHeroClass()->commander);
  389. commander->setArmy(getArmy()); //TODO: separate function for setting commanders
  390. commander->giveTotalStackExperience(exp); //after our exp is set
  391. }
  392. //copy active (probably growing) bonuses from hero prototype to hero object
  393. for(const std::shared_ptr<Bonus> & b : getHeroType()->specialty)
  394. addNewBonus(b);
  395. //initialize bonuses
  396. recreateSecondarySkillsBonuses();
  397. movement = movementPointsLimit(true);
  398. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  399. }
  400. void CGHeroInstance::initArmy(vstd::RNG & rand, IArmyDescriptor * dst)
  401. {
  402. if(!dst)
  403. dst = this;
  404. int warMachinesGiven = 0;
  405. auto stacksCountChances = cb->getSettings().getVector(EGameSettings::HEROES_STARTING_STACKS_CHANCES);
  406. int stacksCountInitRandomNumber = rand.nextInt(1, 100);
  407. size_t maxStacksCount = std::min(stacksCountChances.size(), getHeroType()->initialArmy.size());
  408. for(int stackNo=0; stackNo < maxStacksCount; stackNo++)
  409. {
  410. if (stacksCountInitRandomNumber > stacksCountChances[stackNo])
  411. continue;
  412. auto & stack = getHeroType()->initialArmy[stackNo];
  413. int count = rand.nextInt(stack.minAmount, stack.maxAmount);
  414. if(stack.creature == CreatureID::NONE)
  415. {
  416. logGlobal->error("Hero %s has invalid creature in initial army", getNameTranslated());
  417. continue;
  418. }
  419. const CCreature * creature = stack.creature.toCreature();
  420. if(creature->warMachine != ArtifactID::NONE) //war machine
  421. {
  422. warMachinesGiven++;
  423. if(dst != this)
  424. continue;
  425. ArtifactID aid = creature->warMachine;
  426. const CArtifact * art = aid.toArtifact();
  427. if(art != nullptr && !art->getPossibleSlots().at(ArtBearer::HERO).empty())
  428. {
  429. //TODO: should we try another possible slots?
  430. ArtifactPosition slot = art->getPossibleSlots().at(ArtBearer::HERO).front();
  431. if(!getArt(slot))
  432. {
  433. auto artifact = cb->gameState().createArtifact(aid);
  434. putArtifact(slot, artifact);
  435. }
  436. else
  437. logGlobal->warn("Hero %s already has artifact at %d, omitting giving artifact %d", getNameTranslated(), slot.toEnum(), aid.toEnum());
  438. }
  439. else
  440. {
  441. logGlobal->error("Hero %s has invalid war machine in initial army", getNameTranslated());
  442. }
  443. }
  444. else
  445. {
  446. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  447. }
  448. }
  449. }
  450. CGHeroInstance::~CGHeroInstance() = default;
  451. bool CGHeroInstance::needsLastStack() const
  452. {
  453. return true;
  454. }
  455. void CGHeroInstance::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  456. {
  457. if(h == this) return; //exclude potential self-visiting
  458. if (ID == Obj::HERO)
  459. {
  460. if( cb->getPlayerRelations(tempOwner, h->tempOwner) != PlayerRelations::ENEMIES)
  461. {
  462. //exchange
  463. gameEvents.heroExchange(h->id, id);
  464. }
  465. else //battle
  466. {
  467. if(getVisitedTown()) //we're in town
  468. getVisitedTown()->onHeroVisit(gameEvents, h); //town will handle attacking
  469. else
  470. gameEvents.startBattle(h, this);
  471. }
  472. }
  473. else if(ID == Obj::PRISON)
  474. {
  475. if (cb->getHeroCount(h->tempOwner, false) < cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))//free hero slot
  476. {
  477. //update hero parameters
  478. SetMovePoints smp;
  479. smp.hid = id;
  480. gameEvents.setManaPoints(id, manaLimit());
  481. ObjectInstanceID boatId;
  482. const auto boatPos = visitablePos();
  483. if (cb->getTile(boatPos)->isWater())
  484. {
  485. smp.val = movementPointsLimit(false);
  486. if (!inBoat())
  487. {
  488. //Create a new boat for hero
  489. gameEvents.createBoat(boatPos, getBoatType(), h->getOwner());
  490. boatId = cb->getTopObj(boatPos)->id;
  491. }
  492. }
  493. else
  494. {
  495. smp.val = movementPointsLimit(true);
  496. }
  497. gameEvents.giveHero(id, h->tempOwner, boatId); //recreates def and adds hero to player
  498. gameEvents.setObjPropertyID(id, ObjProperty::ID, Obj(Obj::HERO)); //set ID to 34 AFTER hero gets correct flag color
  499. gameEvents.setMovePoints (&smp);
  500. h->showInfoDialog(gameEvents, 102);
  501. }
  502. else //already 8 wandering heroes
  503. {
  504. h->showInfoDialog(gameEvents, 103);
  505. }
  506. }
  507. }
  508. std::string CGHeroInstance::getObjectName() const
  509. {
  510. if(ID != Obj::PRISON)
  511. {
  512. std::string hoverName = LIBRARY->generaltexth->allTexts[15];
  513. boost::algorithm::replace_first(hoverName,"%s",getNameTranslated());
  514. boost::algorithm::replace_first(hoverName,"%s", getClassNameTranslated());
  515. return hoverName;
  516. }
  517. else
  518. return LIBRARY->objtypeh->getObjectName(ID, 0);
  519. }
  520. std::string CGHeroInstance::getHoverText(PlayerColor player) const
  521. {
  522. std::string hoverText = CArmedInstance::getHoverText(player) + getMovementPointsTextIfOwner(player);
  523. return hoverText;
  524. }
  525. std::string CGHeroInstance::getMovementPointsTextIfOwner(PlayerColor player) const
  526. {
  527. std::string output = "";
  528. if(player == getOwner())
  529. {
  530. output += " " + LIBRARY->generaltexth->translate("vcmi.adventureMap.movementPointsHeroInfo");
  531. boost::replace_first(output, "%POINTS", std::to_string(movementPointsLimit(!inBoat())));
  532. boost::replace_first(output, "%REMAINING", std::to_string(movementPointsRemaining()));
  533. }
  534. return output;
  535. }
  536. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  537. {
  538. return getHeroClass()->isMagicHero() ? 3 : 4;
  539. }
  540. ui8 CGHeroInstance::maxlevelsToWisdom() const
  541. {
  542. return getHeroClass()->isMagicHero() ? 3 : 6;
  543. }
  544. void CGHeroInstance::pickRandomObject(IGameRandomizer & gameRandomizer)
  545. {
  546. assert(ID == Obj::HERO || ID == Obj::PRISON || ID == Obj::RANDOM_HERO);
  547. if (ID == Obj::RANDOM_HERO)
  548. {
  549. auto selectedHero = cb->gameState().pickNextHeroType(gameRandomizer.getDefault(), getOwner());
  550. ID = Obj::HERO;
  551. subID = selectedHero;
  552. randomizeArmy(getHeroClass()->faction);
  553. }
  554. auto oldSubID = subID;
  555. // to find object handler we must use heroClass->id
  556. // after setType subID used to store unique hero identify id. Check issue 2277 for details
  557. // exclude prisons which should use appearance as set in map, via map editor or RMG
  558. if (ID != Obj::PRISON)
  559. setType(ID, getHeroClass()->getIndex());
  560. this->subID = oldSubID;
  561. }
  562. void CGHeroInstance::recreateSecondarySkillsBonuses()
  563. {
  564. auto secondarySkillsBonuses = getBonusesFrom(BonusSource::SECONDARY_SKILL);
  565. for(const auto & bonus : *secondarySkillsBonuses)
  566. removeBonus(bonus);
  567. for(const auto & skill_info : secSkills)
  568. if(skill_info.second > 0)
  569. updateSkillBonus(SecondarySkill(skill_info.first), skill_info.second);
  570. }
  571. void CGHeroInstance::updateSkillBonus(const SecondarySkill & which, int val)
  572. {
  573. removeBonuses(Selector::source(BonusSource::SECONDARY_SKILL, BonusSourceID(which)));
  574. if(val > 0)
  575. {
  576. auto skillBonus = (*LIBRARY->skillh)[which]->at(val).effects;
  577. for(const auto& b : skillBonus)
  578. addNewBonus(std::make_shared<Bonus>(*b));
  579. }
  580. }
  581. void CGHeroInstance::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  582. {
  583. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  584. setStackCount(SlotID(0), identifier.getNum());
  585. }
  586. int CGHeroInstance::getPrimSkillLevel(PrimarySkill id) const
  587. {
  588. return primarySkills.getSkill(id);
  589. }
  590. double CGHeroInstance::getFightingStrength() const
  591. {
  592. const auto & skillValues = primarySkills.getSkills();
  593. return sqrt((1.0 + 0.05*skillValues[PrimarySkill::ATTACK.getNum()]) * (1.0 + 0.05*skillValues[PrimarySkill::DEFENSE.getNum()]));
  594. }
  595. double CGHeroInstance::getMagicStrength() const
  596. {
  597. const auto & skillValues = primarySkills.getSkills();
  598. if (!hasSpellbook())
  599. return 1;
  600. bool atLeastOneCombatSpell = false;
  601. for (auto spell : spells)
  602. {
  603. if (spell.toSpell()->isCombat())
  604. {
  605. atLeastOneCombatSpell = true;
  606. break;
  607. }
  608. }
  609. if (!atLeastOneCombatSpell)
  610. return 1;
  611. return sqrt((1.0 + 0.05*skillValues[PrimarySkill::KNOWLEDGE.getNum()] * mana / manaLimit()) * (1.0 + 0.05*skillValues[PrimarySkill::SPELL_POWER.getNum()] * mana / manaLimit()));
  612. }
  613. double CGHeroInstance::getHeroStrength() const
  614. {
  615. return getFightingStrength() * getMagicStrength();
  616. }
  617. uint64_t CGHeroInstance::getValueForDiplomacy() const
  618. {
  619. // H3 formula for hero strength when considering diplomacy skill
  620. uint64_t armyStrength = getArmyStrength();
  621. double heroStrength = sqrt(
  622. (1.0 + 0.05 * getPrimSkillLevel(PrimarySkill::ATTACK)) *
  623. (1.0 + 0.05 * getPrimSkillLevel(PrimarySkill::DEFENSE))
  624. );
  625. return heroStrength * armyStrength;
  626. }
  627. bool CGHeroInstance::compareCampaignValue(const CGHeroInstance * left, const CGHeroInstance * right)
  628. {
  629. // https://heroes.thelazy.net/index.php/Power_rating
  630. uint32_t leftLevel = left->level;
  631. uint64_t leftExperience = left->exp;
  632. uint32_t leftPrimary = left->getPrimSkillLevel(PrimarySkill::ATTACK) + left->getPrimSkillLevel(PrimarySkill::DEFENSE) + left->getPrimSkillLevel(PrimarySkill::SPELL_POWER) + left->getPrimSkillLevel(PrimarySkill::DEFENSE);
  633. uint32_t leftPrimaryAndLevel = leftPrimary + leftLevel;
  634. uint32_t rightLevel = right->level;
  635. uint64_t rightExperience = right->exp;
  636. uint32_t rightPrimary = right->getPrimSkillLevel(PrimarySkill::ATTACK) + right->getPrimSkillLevel(PrimarySkill::DEFENSE) + right->getPrimSkillLevel(PrimarySkill::SPELL_POWER) + right->getPrimSkillLevel(PrimarySkill::DEFENSE);
  637. uint32_t rightPrimaryAndLevel = rightPrimary + rightLevel;
  638. if (leftPrimaryAndLevel != rightPrimaryAndLevel)
  639. return leftPrimaryAndLevel > rightPrimaryAndLevel;
  640. if (leftLevel != rightLevel)
  641. return leftLevel > rightLevel;
  642. if (leftExperience != rightExperience)
  643. return leftExperience > rightExperience;
  644. return left->getHeroTypeID() > right->getHeroTypeID();
  645. }
  646. ui64 CGHeroInstance::getTotalStrength() const
  647. {
  648. double ret = getHeroStrength() * getArmyStrength();
  649. return static_cast<ui64>(ret);
  650. }
  651. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  652. {
  653. return static_cast<TExpType>(exp * (valOfBonuses(BonusType::HERO_EXPERIENCE_GAIN_PERCENT)) / 100.0);
  654. }
  655. int32_t CGHeroInstance::getCasterUnitId() const
  656. {
  657. return id.getNum();
  658. }
  659. int32_t CGHeroInstance::getSpellSchoolLevel(const spells::Spell * spell, SpellSchool * outSelectedSchool) const
  660. {
  661. int32_t skill = -1; //skill level
  662. spell->forEachSchool([&, this](const SpellSchool & cnf, bool & stop)
  663. {
  664. int32_t thisSchool = magicSchoolMastery.getMastery(cnf); //FIXME: Bonus shouldn't be additive (Witchking Artifacts : Crown of Skies)
  665. if(thisSchool > skill)
  666. {
  667. skill = thisSchool;
  668. if(outSelectedSchool)
  669. *outSelectedSchool = cnf;
  670. }
  671. });
  672. vstd::amax(skill, magicSchoolMastery.getMastery(SpellSchool::ANY)); //any school bonus
  673. vstd::amax(skill, valOfBonuses(BonusType::SPELL, BonusSubtypeID(spell->getId()))); //given by artifact or other effect
  674. vstd::amax(skill, 0); //in case we don't know any school
  675. vstd::amin(skill, 3);
  676. return skill;
  677. }
  678. int64_t CGHeroInstance::getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const
  679. {
  680. //applying sorcery secondary skill
  681. if(spell->isMagical())
  682. base = static_cast<int64_t>(base * (valOfBonuses(BonusType::SPELL_DAMAGE, BonusSubtypeID(SpellSchool::ANY))) / 100.0);
  683. base = static_cast<int64_t>(base * (100 + valOfBonuses(BonusType::SPECIFIC_SPELL_DAMAGE, BonusSubtypeID(spell->getId()))) / 100.0);
  684. int maxSchoolBonus = 0;
  685. spell->forEachSchool([&maxSchoolBonus, this](const SpellSchool & cnf, bool & stop)
  686. {
  687. vstd::amax(maxSchoolBonus, valOfBonuses(BonusType::SPELL_DAMAGE, BonusSubtypeID(cnf)));
  688. });
  689. base = static_cast<int64_t>(base * (100 + maxSchoolBonus) / 100.0);
  690. if(affectedStack && affectedStack->creatureLevel() > 0) //Hero specials like Solmyr, Deemer
  691. base = static_cast<int64_t>(base * static_cast<double>(100 + valOfBonuses(BonusType::SPECIAL_SPELL_LEV, BonusSubtypeID(spell->getId())) / affectedStack->creatureLevel()) / 100.0);
  692. return base;
  693. }
  694. int64_t CGHeroInstance::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
  695. {
  696. base = static_cast<int64_t>(base * (100 + valOfBonuses(BonusType::SPECIFIC_SPELL_DAMAGE, BonusSubtypeID(spell->getId()))) / 100.0);
  697. return base;
  698. }
  699. int32_t CGHeroInstance::getEffectLevel(const spells::Spell * spell) const
  700. {
  701. return getSpellSchoolLevel(spell);
  702. }
  703. int32_t CGHeroInstance::getEffectPower(const spells::Spell * spell) const
  704. {
  705. return getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  706. }
  707. int32_t CGHeroInstance::getEnchantPower(const spells::Spell * spell) const
  708. {
  709. int32_t spellpower = getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  710. int32_t durationCommon = valOfBonuses(BonusType::SPELL_DURATION, BonusSubtypeID());
  711. int32_t durationSpecific = valOfBonuses(BonusType::SPELL_DURATION, BonusSubtypeID(spell->getId()));
  712. return spellpower + durationCommon + durationSpecific;
  713. }
  714. int64_t CGHeroInstance::getEffectValue(const spells::Spell * spell) const
  715. {
  716. return 0;
  717. }
  718. PlayerColor CGHeroInstance::getCasterOwner() const
  719. {
  720. return tempOwner;
  721. }
  722. void CGHeroInstance::getCasterName(MetaString & text) const
  723. {
  724. //FIXME: use local name, MetaString need access to gamestate as hero name is part of map object
  725. text.replaceRawString(getNameTranslated());
  726. }
  727. void CGHeroInstance::getCastDescription(const spells::Spell * spell, const battle::Units & attacked, MetaString & text) const
  728. {
  729. const bool singleTarget = attacked.size() == 1;
  730. const int textIndex = singleTarget ? 195 : 196;
  731. text.appendLocalString(EMetaText::GENERAL_TXT, textIndex);
  732. getCasterName(text);
  733. text.replaceName(spell->getId());
  734. if(singleTarget)
  735. attacked.at(0)->addNameReplacement(text, true);
  736. }
  737. const CGHeroInstance * CGHeroInstance::getHeroCaster() const
  738. {
  739. return this;
  740. }
  741. void CGHeroInstance::spendMana(ServerCallback * server, const int spellCost) const
  742. {
  743. if(spellCost != 0)
  744. {
  745. SetMana sm;
  746. sm.mode = ChangeValueMode::RELATIVE;
  747. sm.hid = id;
  748. sm.val = -spellCost;
  749. server->apply(sm);
  750. }
  751. }
  752. bool CGHeroInstance::canCastThisSpell(const spells::Spell * spell) const
  753. {
  754. const bool isAllowed = cb->isAllowed(spell->getId());
  755. const bool inSpellBook = vstd::contains(spells, spell->getId()) && hasSpellbook();
  756. const bool specificBonus = hasBonusOfType(BonusType::SPELL, BonusSubtypeID(spell->getId()));
  757. bool schoolBonus = false;
  758. spell->forEachSchool([this, &schoolBonus](const SpellSchool & cnf, bool & stop)
  759. {
  760. if(hasBonusOfType(BonusType::SPELLS_OF_SCHOOL, BonusSubtypeID(cnf)))
  761. {
  762. schoolBonus = stop = true;
  763. }
  764. });
  765. const bool levelBonus = hasBonusOfType(BonusType::SPELLS_OF_LEVEL, BonusCustomSubtype::spellLevel(spell->getLevel()));
  766. if(spell->isSpecial())
  767. {
  768. if(inSpellBook)
  769. {//hero has this spell in spellbook
  770. logGlobal->error("Special spell %s in spellbook.", spell->getNameTranslated());
  771. }
  772. return specificBonus;
  773. }
  774. else if(!isAllowed)
  775. {
  776. if(inSpellBook)
  777. {
  778. //hero has this spell in spellbook
  779. //it is normal if set in map editor, but trace it to possible debug of magic guild
  780. logGlobal->trace("Banned spell %s in spellbook.", spell->getNameTranslated());
  781. }
  782. return inSpellBook || specificBonus || schoolBonus || levelBonus;
  783. }
  784. else
  785. {
  786. return inSpellBook || schoolBonus || specificBonus || levelBonus;
  787. }
  788. }
  789. bool CGHeroInstance::canLearnSpell(const spells::Spell * spell, bool allowBanned) const
  790. {
  791. if(!hasSpellbook())
  792. return false;
  793. if(spell->getLevel() > maxSpellLevel()) //not enough wisdom
  794. return false;
  795. if(vstd::contains(spells, spell->getId()))//already known
  796. return false;
  797. if(spell->isSpecial())
  798. {
  799. logGlobal->warn("Hero %s try to learn special spell %s", nodeName(), spell->getNameTranslated());
  800. return false;//special spells can not be learned
  801. }
  802. if(spell->isCreatureAbility())
  803. {
  804. logGlobal->warn("Hero %s try to learn creature spell %s", nodeName(), spell->getNameTranslated());
  805. return false;//creature abilities can not be learned
  806. }
  807. if(!allowBanned && !cb->isAllowed(spell->getId()))
  808. {
  809. logGlobal->warn("Hero %s try to learn banned spell %s", nodeName(), spell->getNameTranslated());
  810. return false;//banned spells should not be learned
  811. }
  812. return true;
  813. }
  814. /**
  815. * Calculates what creatures and how many to be raised from a battle.
  816. * @param battleResult The results of the battle.
  817. * @return Returns a pair with the first value indicating the ID of the creature
  818. * type and second value the amount. Both values are returned as -1 if necromancy
  819. * could not be applied.
  820. */
  821. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  822. {
  823. TConstBonusListPtr improvedNecromancy = getBonusesOfType(BonusType::IMPROVED_NECROMANCY);
  824. // need skill or cloak of undead king - lesser artifacts don't work without skill
  825. if (improvedNecromancy->empty())
  826. return CStackBasicDescriptor();
  827. int raisedUnitsPercentage = std::clamp(valOfBonuses(BonusType::UNDEAD_RAISE_PERCENTAGE), 0, 100);
  828. if (raisedUnitsPercentage == 0)
  829. return CStackBasicDescriptor();
  830. const std::map<CreatureID,si32> &casualties = battleResult.casualties[CBattleInfoEssentials::otherSide(battleResult.winner)];
  831. if(casualties.empty())
  832. return CStackBasicDescriptor();
  833. // figure out what to raise - pick strongest creature meeting requirements
  834. CreatureID bestCreature = CreatureID::NONE;
  835. int necromancerPower = improvedNecromancy->totalValue();
  836. // pick best bonus available
  837. for(const std::shared_ptr<Bonus> & newPick : *improvedNecromancy)
  838. {
  839. // addInfo[0] = required necromancy skill
  840. if(newPick->additionalInfo[0] > necromancerPower)
  841. continue;
  842. CreatureID newCreature = newPick->subtype.as<CreatureID>();;
  843. if(!bestCreature.hasValue())
  844. {
  845. bestCreature = newCreature;
  846. }
  847. else
  848. {
  849. auto quality = [](CreatureID pick) -> std::tuple<int, int>
  850. {
  851. const auto * c = pick.toCreature();
  852. return std::tuple<int, int> {c->getLevel(), static_cast<int>(c->getFullRecruitCost().marketValue())};
  853. };
  854. if(quality(bestCreature) < quality(newCreature))
  855. bestCreature = newCreature;
  856. }
  857. }
  858. assert(bestCreature != CreatureID::NONE);
  859. CreatureID selectedCreature = bestCreature;
  860. // raise upgraded creature (at 2/3 rate) if no space available otherwise
  861. if(getSlotFor(selectedCreature) == SlotID())
  862. {
  863. for (const auto & slot : Slots())
  864. {
  865. if (selectedCreature.toCreature()->isMyDirectOrIndirectUpgrade(slot.second->getCreature()))
  866. {
  867. selectedCreature = slot.second->getCreatureID();
  868. break;
  869. }
  870. }
  871. }
  872. // calculate number of creatures raised - low level units contribute at 50% rate
  873. const double raisedUnitHealth = selectedCreature.toCreature()->getMaxHealth();
  874. double raisedUnits = 0;
  875. for(const auto & casualty : casualties)
  876. {
  877. const CCreature * c = casualty.first.toCreature();
  878. double raisedFromCasualty = std::min(c->getMaxHealth() / raisedUnitHealth, 1.0) * casualty.second * raisedUnitsPercentage;
  879. if (bestCreature != selectedCreature)
  880. raisedUnits += raisedFromCasualty * 2 / 3 / 100;
  881. else
  882. raisedUnits += raisedFromCasualty / 100;
  883. }
  884. return CStackBasicDescriptor(selectedCreature, std::max(static_cast<int>(raisedUnits), 1));
  885. }
  886. int CGHeroInstance::getSightRadius() const
  887. {
  888. int baseValue = LIBRARY->engineSettings()->getInteger(EGameSettings::HEROES_BASE_SCOUNTING_RANGE);
  889. return applyBonuses(BonusType::SIGHT_RADIUS, baseValue);
  890. }
  891. si32 CGHeroInstance::manaRegain() const
  892. {
  893. int percentageRegeneration = valOfBonuses(BonusType::MANA_PERCENTAGE_REGENERATION);
  894. int regeneratedByPercentage = manaLimit() * percentageRegeneration / 100;
  895. int regeneratedByValue = valOfBonuses(BonusType::MANA_REGENERATION);
  896. return std::max(regeneratedByValue, regeneratedByPercentage);
  897. }
  898. si32 CGHeroInstance::getManaNewTurn() const
  899. {
  900. if(getVisitedTown() && getVisitedTown()->hasBuilt(BuildingID::MAGES_GUILD_1))
  901. {
  902. //if hero starts turn in town with mage guild - restore all mana
  903. return std::max(mana, manaLimit());
  904. }
  905. si32 res = mana + manaRegain();
  906. res = std::min(res, manaLimit());
  907. res = std::max(res, mana);
  908. res = std::max(res, 0);
  909. return res;
  910. }
  911. // /**
  912. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  913. // * or discards it if it cannot be equipped.
  914. // */
  915. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  916. // {
  917. // CArtifact * const artifact = LIBRARY->arth->objects[aid]; //pointer to constant object
  918. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  919. // ai->putAt(this, ai->firstAvailableSlot(this));
  920. // }
  921. BoatId CGHeroInstance::getBoatType() const
  922. {
  923. return BoatId(LIBRARY->townh->getById(getHeroClass()->faction)->getBoatType());
  924. }
  925. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  926. {
  927. offsets = {
  928. {0, -1, 0},
  929. {+1, -1, 0},
  930. {+1, 0, 0},
  931. {+1, +1, 0},
  932. {0, +1, 0},
  933. {-1, +1, 0},
  934. {-1, 0, 0},
  935. {-1, -1, 0},
  936. };
  937. }
  938. const IObjectInterface * CGHeroInstance::getObject() const
  939. {
  940. return this;
  941. }
  942. int32_t CGHeroInstance::getSpellCost(const spells::Spell * sp) const
  943. {
  944. return sp->getCost(getSpellSchoolLevel(sp));
  945. }
  946. void CGHeroInstance::pushPrimSkill( PrimarySkill which, int val )
  947. {
  948. auto sel = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(which))
  949. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  950. removeBonuses(sel);
  951. addNewBonus(std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::HERO_BASE_SKILL, val, BonusSourceID(id), BonusSubtypeID(which)));
  952. }
  953. EAlignment CGHeroInstance::getAlignment() const
  954. {
  955. return getHeroClass()->getAlignment();
  956. }
  957. void CGHeroInstance::initExp(vstd::RNG & rand)
  958. {
  959. exp = rand.nextInt(40, 89);
  960. }
  961. std::string CGHeroInstance::nodeName() const
  962. {
  963. return "Hero " + getNameTextID();
  964. }
  965. si32 CGHeroInstance::manaLimit() const
  966. {
  967. return getPrimSkillLevel(PrimarySkill::KNOWLEDGE) * manaPerKnowledgeCached.getValue() / 100;
  968. }
  969. HeroTypeID CGHeroInstance::getPortraitSource() const
  970. {
  971. if (customPortraitSource.isValid())
  972. return customPortraitSource;
  973. else
  974. return getHeroTypeID();
  975. }
  976. int32_t CGHeroInstance::getIconIndex() const
  977. {
  978. return getPortraitSource().toEntity(LIBRARY)->getIconIndex();
  979. }
  980. std::string CGHeroInstance::getNameTranslated() const
  981. {
  982. return LIBRARY->generaltexth->translate(getNameTextID());
  983. }
  984. std::string CGHeroInstance::getClassNameTranslated() const
  985. {
  986. return LIBRARY->generaltexth->translate(getClassNameTextID());
  987. }
  988. std::string CGHeroInstance::getClassNameTextID() const
  989. {
  990. if (isCampaignGem())
  991. return "core.genrltxt.735";
  992. return getHeroClass()->getNameTextID();
  993. }
  994. std::string CGHeroInstance::getNameTextID() const
  995. {
  996. if (!nameCustomTextId.empty())
  997. return nameCustomTextId;
  998. if (getHeroTypeID().hasValue())
  999. return getHeroType()->getNameTextID();
  1000. // FIXME: called by logging from some specialties (mods?) before type is set on deserialization
  1001. // assert(0);
  1002. return "";
  1003. }
  1004. std::string CGHeroInstance::getBiographyTranslated() const
  1005. {
  1006. return LIBRARY->generaltexth->translate(getBiographyTextID());
  1007. }
  1008. std::string CGHeroInstance::getBiographyTextID() const
  1009. {
  1010. if (!biographyCustomTextId.empty())
  1011. return biographyCustomTextId;
  1012. if (getHeroTypeID().hasValue())
  1013. return getHeroType()->getBiographyTextID();
  1014. return ""; //for random hero
  1015. }
  1016. CGHeroInstance::ArtPlacementMap CGHeroInstance::putArtifact(const ArtifactPosition & pos, const CArtifactInstance * art)
  1017. {
  1018. assert(art->canBePutAt(this, pos));
  1019. if(ArtifactUtils::isSlotEquipment(pos))
  1020. attachToSource(*art);
  1021. return CArtifactSet::putArtifact(pos, art);
  1022. }
  1023. void CGHeroInstance::removeArtifact(const ArtifactPosition & pos)
  1024. {
  1025. auto art = getArt(pos);
  1026. assert(art);
  1027. CArtifactSet::removeArtifact(pos);
  1028. if(ArtifactUtils::isSlotEquipment(pos))
  1029. detachFromSource(*art);
  1030. }
  1031. bool CGHeroInstance::hasSpellbook() const
  1032. {
  1033. return getArt(ArtifactPosition::SPELLBOOK);
  1034. }
  1035. void CGHeroInstance::addSpellToSpellbook(const SpellID & spell)
  1036. {
  1037. spells.insert(spell);
  1038. }
  1039. void CGHeroInstance::removeSpellFromSpellbook(const SpellID & spell)
  1040. {
  1041. spells.erase(spell);
  1042. }
  1043. bool CGHeroInstance::spellbookContainsSpell(const SpellID & spell) const
  1044. {
  1045. return vstd::contains(spells, spell);
  1046. }
  1047. void CGHeroInstance::removeSpellbook()
  1048. {
  1049. spells.clear();
  1050. if(hasSpellbook())
  1051. {
  1052. cb->gameState().getMap().removeArtifactInstance(*this, ArtifactPosition::SPELLBOOK);
  1053. }
  1054. }
  1055. const std::set<SpellID> & CGHeroInstance::getSpellsInSpellbook() const
  1056. {
  1057. return spells;
  1058. }
  1059. int CGHeroInstance::maxSpellLevel() const
  1060. {
  1061. return std::min(GameConstants::SPELL_LEVELS, valOfBonuses(BonusType::MAX_LEARNABLE_SPELL_LEVEL));
  1062. }
  1063. bool CGHeroInstance::inBoat() const
  1064. {
  1065. return boardedBoat.hasValue();
  1066. }
  1067. const CGBoat * CGHeroInstance::getBoat() const
  1068. {
  1069. if (boardedBoat.hasValue())
  1070. return dynamic_cast<const CGBoat*>(cb->getObjInstance(boardedBoat));
  1071. return nullptr;
  1072. }
  1073. CGBoat * CGHeroInstance::getBoat()
  1074. {
  1075. if (boardedBoat.hasValue())
  1076. return dynamic_cast<CGBoat*>(cb->gameState().getObjInstance(boardedBoat));
  1077. return nullptr;
  1078. }
  1079. void CGHeroInstance::setBoat(CGBoat* newBoat)
  1080. {
  1081. if (newBoat)
  1082. {
  1083. boardedBoat = newBoat->id;
  1084. attachTo(*newBoat);
  1085. newBoat->setBoardedHero(this);
  1086. }
  1087. else if (boardedBoat.hasValue())
  1088. {
  1089. auto oldBoat = getBoat();
  1090. boardedBoat = {};
  1091. detachFrom(*oldBoat);
  1092. oldBoat->setBoardedHero(nullptr);
  1093. }
  1094. }
  1095. void CGHeroInstance::restoreBonusSystem(CGameState & gs)
  1096. {
  1097. CArmedInstance::restoreBonusSystem(gs);
  1098. artDeserializationFix(gs, this);
  1099. if (commander)
  1100. commander->artDeserializationFix(gs, this->commander.get());
  1101. if (boardedBoat.hasValue())
  1102. {
  1103. auto boat = gs.getObjInstance(boardedBoat);
  1104. if (boat)
  1105. attachTo(dynamic_cast<CGBoat&>(*boat));
  1106. }
  1107. }
  1108. void CGHeroInstance::attachToBonusSystem(CGameState & gs)
  1109. {
  1110. CArmedInstance::attachToBonusSystem(gs);
  1111. if (boardedBoat.hasValue())
  1112. {
  1113. auto boat = gs.getObjInstance(boardedBoat);
  1114. if (boat)
  1115. attachTo(dynamic_cast<CGBoat&>(*boat));
  1116. }
  1117. }
  1118. void CGHeroInstance::detachFromBonusSystem(CGameState & gs)
  1119. {
  1120. CArmedInstance::detachFromBonusSystem(gs);
  1121. if (boardedBoat.hasValue())
  1122. {
  1123. auto boat = gs.getObjInstance(boardedBoat);
  1124. if (boat)
  1125. detachFrom(dynamic_cast<CGBoat&>(*boat));
  1126. }
  1127. }
  1128. CBonusSystemNode & CGHeroInstance::whereShouldBeAttached(CGameState & gs)
  1129. {
  1130. if(visitedTown.hasValue())
  1131. {
  1132. auto town = gs.getTown(visitedTown);
  1133. if(isGarrisoned())
  1134. return *town;
  1135. else
  1136. return town->townAndVis;
  1137. }
  1138. else
  1139. return CArmedInstance::whereShouldBeAttached(gs);
  1140. }
  1141. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const
  1142. {
  1143. if(!ti->hasFreeShipBoarding())
  1144. return 0; // take all MPs by default
  1145. auto boatLayer = inBoat() ? getBoat()->layer : EPathfindingLayer::SAIL;
  1146. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : boatLayer);
  1147. int mp2 = ti->getMaxMovePoints(disembark ? boatLayer : EPathfindingLayer::LAND);
  1148. int ret = static_cast<int>((MPsBefore - basicCost) * static_cast<double>(mp1) / mp2);
  1149. return ret;
  1150. }
  1151. EDiggingStatus CGHeroInstance::diggingStatus() const
  1152. {
  1153. if(static_cast<int>(movement) < movementPointsLimit(true))
  1154. return EDiggingStatus::LACK_OF_MOVEMENT;
  1155. if(!ArtifactID(ArtifactID::GRAIL).toArtifact()->canBePutAt(this))
  1156. return EDiggingStatus::BACKPACK_IS_FULL;
  1157. return cb->getTileDigStatus(visitablePos());
  1158. }
  1159. ArtBearer CGHeroInstance::bearerType() const
  1160. {
  1161. return ArtBearer::HERO;
  1162. }
  1163. std::vector<SecondarySkill> CGHeroInstance::getLevelupSkillCandidates(IGameRandomizer & gameRandomizer) const
  1164. {
  1165. std::set<SecondarySkill> basicAndAdv;
  1166. std::set<SecondarySkill> none;
  1167. std::vector<SecondarySkill> skills;
  1168. if (canLearnSkill())
  1169. {
  1170. for(int i = 0; i < LIBRARY->skillh->size(); i++)
  1171. if (canLearnSkill(SecondarySkill(i)))
  1172. none.insert(SecondarySkill(i));
  1173. }
  1174. for(const auto & elem : secSkills)
  1175. {
  1176. if(elem.second < MasteryLevel::EXPERT)
  1177. basicAndAdv.insert(elem.first);
  1178. none.erase(elem.first);
  1179. }
  1180. if (!basicAndAdv.empty())
  1181. {
  1182. skills.push_back(gameRandomizer.rollSecondarySkillForLevelup(this, basicAndAdv));
  1183. basicAndAdv.erase(skills.back());
  1184. }
  1185. if (!none.empty())
  1186. {
  1187. skills.push_back(gameRandomizer.rollSecondarySkillForLevelup(this, none));
  1188. none.erase(skills.back());
  1189. }
  1190. if (!basicAndAdv.empty() && skills.size() < 2)
  1191. {
  1192. skills.push_back(gameRandomizer.rollSecondarySkillForLevelup(this, basicAndAdv));
  1193. basicAndAdv.erase(skills.back());
  1194. }
  1195. if (!none.empty() && skills.size() < 2)
  1196. {
  1197. skills.push_back(gameRandomizer.rollSecondarySkillForLevelup(this, none));
  1198. none.erase(skills.back());
  1199. }
  1200. return skills;
  1201. }
  1202. void CGHeroInstance::setPrimarySkill(PrimarySkill primarySkill, si64 value, ChangeValueMode mode)
  1203. {
  1204. auto skill = getLocalBonus(Selector::type()(BonusType::PRIMARY_SKILL)
  1205. .And(Selector::subtype()(BonusSubtypeID(primarySkill)))
  1206. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1207. assert(skill);
  1208. if(mode == ChangeValueMode::ABSOLUTE)
  1209. {
  1210. skill->val = static_cast<si32>(value);
  1211. }
  1212. else
  1213. {
  1214. skill->val += static_cast<si32>(value);
  1215. }
  1216. nodeHasChanged();
  1217. }
  1218. void CGHeroInstance::setExperience(si64 value, ChangeValueMode mode)
  1219. {
  1220. if(mode == ChangeValueMode::ABSOLUTE)
  1221. {
  1222. exp = value;
  1223. }
  1224. else
  1225. {
  1226. exp += value;
  1227. }
  1228. }
  1229. bool CGHeroInstance::gainsLevel() const
  1230. {
  1231. return level < LIBRARY->heroh->maxSupportedLevel() && exp >= static_cast<TExpType>(LIBRARY->heroh->reqExp(level+1));
  1232. }
  1233. void CGHeroInstance::levelUp()
  1234. {
  1235. ++level;
  1236. //update specialty and other bonuses that scale with level
  1237. nodeHasChanged();
  1238. }
  1239. void CGHeroInstance::attachCommanderToArmy()
  1240. {
  1241. if (commander)
  1242. commander->setArmy(this);
  1243. }
  1244. void CGHeroInstance::levelUpAutomatically(IGameRandomizer & gameRandomizer)
  1245. {
  1246. while(gainsLevel())
  1247. {
  1248. const auto primarySkill = gameRandomizer.rollPrimarySkillForLevelup(this);
  1249. const auto proposedSecondarySkills = getLevelupSkillCandidates(gameRandomizer);
  1250. setPrimarySkill(primarySkill, 1, ChangeValueMode::RELATIVE);
  1251. if(!proposedSecondarySkills.empty())
  1252. setSecSkillLevel(proposedSecondarySkills.front(), 1, ChangeValueMode::RELATIVE);
  1253. levelUp();
  1254. }
  1255. }
  1256. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, BonusSubtypeID subtype) const
  1257. {
  1258. //VISIONS spell support
  1259. const int visionsMultiplier = valOfBonuses(BonusType::VISIONS, subtype);
  1260. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1261. if (visionsMultiplier > 0)
  1262. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1263. const int distance = static_cast<int>(target->anchorPos().dist2d(visitablePos()));
  1264. //logGlobal->debug(boost::str(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1265. return (distance < visionsRange) && (target->anchorPos().z == anchorPos().z);
  1266. }
  1267. std::string CGHeroInstance::getHeroTypeName() const
  1268. {
  1269. if(ID == Obj::HERO || ID == Obj::PRISON)
  1270. return getHeroType()->getJsonKey();
  1271. return "";
  1272. }
  1273. void CGHeroInstance::afterAddToMap(CMap * map)
  1274. {
  1275. map->heroAddedToMap(this);
  1276. }
  1277. void CGHeroInstance::afterRemoveFromMap(CMap* map)
  1278. {
  1279. map->heroRemovedFromMap(this);
  1280. }
  1281. void CGHeroInstance::setHeroTypeName(const std::string & identifier)
  1282. {
  1283. if(ID == Obj::HERO || ID == Obj::PRISON)
  1284. {
  1285. auto rawId = LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), "hero", identifier);
  1286. if(rawId)
  1287. subID = rawId.value();
  1288. else
  1289. {
  1290. throw std::runtime_error("Couldn't resolve hero identifier " + identifier);
  1291. }
  1292. }
  1293. }
  1294. void CGHeroInstance::updateFrom(const JsonNode & data)
  1295. {
  1296. CGObjectInstance::updateFrom(data);
  1297. }
  1298. void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
  1299. {
  1300. handler.serializeString("biography", biographyCustomTextId);
  1301. handler.serializeInt("experience", exp, 0);
  1302. if(!handler.saving && exp != UNINITIALIZED_EXPERIENCE) //do not gain levels if experience is not initialized
  1303. {
  1304. while (gainsLevel())
  1305. {
  1306. ++level;
  1307. }
  1308. }
  1309. handler.serializeString("name", nameCustomTextId);
  1310. handler.serializeInt("gender", gender, 0);
  1311. handler.serializeId("portrait", customPortraitSource, HeroTypeID::NONE);
  1312. //primary skills
  1313. if(handler.saving)
  1314. {
  1315. const bool haveSkills = hasBonus(Selector::type()(BonusType::PRIMARY_SKILL).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1316. if(haveSkills)
  1317. {
  1318. auto primarySkills = handler.enterStruct("primarySkills");
  1319. for(auto skill : PrimarySkill::ALL_SKILLS())
  1320. {
  1321. int value = valOfBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(skill)).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1322. handler.serializeInt(NPrimarySkill::names[skill.getNum()], value, 0);
  1323. }
  1324. }
  1325. }
  1326. else
  1327. {
  1328. auto primarySkills = handler.enterStruct("primarySkills");
  1329. if(handler.getCurrent().getType() == JsonNode::JsonType::DATA_STRUCT)
  1330. {
  1331. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1332. {
  1333. int value = 0;
  1334. handler.serializeInt(NPrimarySkill::names[i], value, 0);
  1335. pushPrimSkill(static_cast<PrimarySkill>(i), value);
  1336. }
  1337. }
  1338. }
  1339. //secondary skills
  1340. if(handler.saving)
  1341. {
  1342. //does hero have default skills?
  1343. bool defaultSkills = false;
  1344. bool normalSkills = false;
  1345. for(const auto & p : secSkills)
  1346. {
  1347. if(p.first == SecondarySkill(SecondarySkill::NONE))
  1348. defaultSkills = true;
  1349. else
  1350. normalSkills = true;
  1351. }
  1352. if(defaultSkills && normalSkills)
  1353. logGlobal->error("Mixed default and normal secondary skills");
  1354. //in json default skills means no field/null
  1355. if(!defaultSkills)
  1356. {
  1357. //enter array here as handler initialize it
  1358. auto secondarySkills = handler.enterArray("secondarySkills");
  1359. secondarySkills.syncSize(secSkills, JsonNode::JsonType::DATA_VECTOR);
  1360. for(size_t skillIndex = 0; skillIndex < secondarySkills.size(); ++skillIndex)
  1361. {
  1362. JsonArraySerializer inner = secondarySkills.enterArray(skillIndex);
  1363. SecondarySkill skillId = secSkills.at(skillIndex).first;
  1364. handler.serializeId("skill", skillId);
  1365. std::string skillLevel = NSecondarySkill::levels.at(secSkills.at(skillIndex).second);
  1366. handler.serializeString("level", skillLevel);
  1367. }
  1368. }
  1369. }
  1370. else
  1371. {
  1372. auto secondarySkills = handler.getCurrent()["secondarySkills"];
  1373. secSkills.clear();
  1374. if(secondarySkills.getType() == JsonNode::JsonType::DATA_NULL)
  1375. {
  1376. secSkills.emplace_back(SecondarySkill::NONE, -1);
  1377. }
  1378. else
  1379. {
  1380. auto addSkill = [this](const std::string & skillId, const std::string & levelId)
  1381. {
  1382. const int rawId = SecondarySkill::decode(skillId);
  1383. if(rawId < 0)
  1384. {
  1385. logGlobal->error("Invalid secondary skill %s", skillId);
  1386. return;
  1387. }
  1388. const int level = vstd::find_pos(NSecondarySkill::levels, levelId);
  1389. if(level < 0)
  1390. {
  1391. logGlobal->error("Invalid secondary skill level%s", levelId);
  1392. return;
  1393. }
  1394. secSkills.emplace_back(SecondarySkill(rawId), level);
  1395. };
  1396. if(secondarySkills.getType() == JsonNode::JsonType::DATA_VECTOR)
  1397. {
  1398. for(const auto & p : secondarySkills.Vector())
  1399. {
  1400. auto skillMap = p.Struct();
  1401. addSkill(skillMap["skill"].String(), skillMap["level"].String());
  1402. }
  1403. }
  1404. else if(secondarySkills.getType() == JsonNode::JsonType::DATA_STRUCT)
  1405. {
  1406. for(const auto & p : secondarySkills.Struct())
  1407. {
  1408. addSkill(p.first, p.second.String());
  1409. };
  1410. }
  1411. }
  1412. }
  1413. handler.serializeIdArray("spellBook", spells);
  1414. if(handler.saving)
  1415. {
  1416. // FIXME: EditorCallback (used in map editor) has no access to GameState.
  1417. // serializeJsonArtifacts expects non-const CMap *
  1418. // Find some cleaner solution
  1419. if(auto * ecb = dynamic_cast<EditorCallback *>(cb))
  1420. CArtifactSet::serializeJsonArtifacts(handler, "artifacts", const_cast<CMap *>(ecb->getMapConstPtr()));
  1421. else
  1422. CArtifactSet::serializeJsonArtifacts(handler, "artifacts", &cb->gameState().getMap());
  1423. }
  1424. }
  1425. void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1426. {
  1427. serializeCommonOptions(handler);
  1428. serializeJsonOwner(handler);
  1429. if(ID == Obj::HERO || ID == Obj::PRISON)
  1430. {
  1431. std::string typeName;
  1432. if(handler.saving)
  1433. typeName = getHeroTypeName();
  1434. handler.serializeString("type", typeName);
  1435. if(!handler.saving)
  1436. setHeroTypeName(typeName);
  1437. }
  1438. if(!handler.saving)
  1439. {
  1440. if(!appearance)
  1441. {
  1442. // crossoverDeserialize
  1443. appearance = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClassID())->getTemplates().front();
  1444. }
  1445. }
  1446. CArmedInstance::serializeJsonOptions(handler);
  1447. {
  1448. ui32 rawPatrolRadius = NO_PATROLLING;
  1449. if(handler.saving)
  1450. {
  1451. rawPatrolRadius = patrol.patrolling ? patrol.patrolRadius : NO_PATROLLING;
  1452. }
  1453. handler.serializeInt("patrolRadius", rawPatrolRadius, NO_PATROLLING);
  1454. if(!handler.saving)
  1455. {
  1456. patrol.patrolling = (rawPatrolRadius != NO_PATROLLING);
  1457. patrol.initialPos = visitablePos();
  1458. patrol.patrolRadius = patrol.patrolling ? rawPatrolRadius : 0;
  1459. }
  1460. }
  1461. }
  1462. void CGHeroInstance::serializeJsonDefinition(JsonSerializeFormat & handler)
  1463. {
  1464. serializeCommonOptions(handler);
  1465. }
  1466. bool CGHeroInstance::isMissionCritical() const
  1467. {
  1468. for(const TriggeredEvent & event : cb->getMapHeader()->triggeredEvents)
  1469. {
  1470. if (event.effect.type != EventEffect::DEFEAT)
  1471. continue;
  1472. auto const & testFunctor = [&](const EventCondition & condition)
  1473. {
  1474. if ((condition.condition == EventCondition::CONTROL) && condition.objectID != ObjectInstanceID::NONE)
  1475. return (id != condition.objectID);
  1476. if (condition.condition == EventCondition::HAVE_ARTIFACT)
  1477. {
  1478. if(hasArt(condition.objectType.as<ArtifactID>()))
  1479. return true;
  1480. }
  1481. if(condition.condition == EventCondition::IS_HUMAN)
  1482. return true;
  1483. return false;
  1484. };
  1485. if(event.trigger.test(testFunctor))
  1486. return true;
  1487. }
  1488. return false;
  1489. }
  1490. void CGHeroInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance & stack) const
  1491. {
  1492. TConstBonusListPtr lista = stack.getBonusesOfType(BonusType::SPECIAL_UPGRADE, BonusSubtypeID(stack.getId()));
  1493. for(const auto & it : *lista)
  1494. {
  1495. auto nid = CreatureID(it->additionalInfo[0]);
  1496. if (nid != stack.getId()) //in very specific case the upgrade is available by default (?)
  1497. {
  1498. info.addUpgrade(nid, stack.getType());
  1499. }
  1500. }
  1501. }
  1502. bool CGHeroInstance::isCampaignYog() const
  1503. {
  1504. const StartInfo *si = cb->getStartInfo();
  1505. return si && si->campState &&si->campState->getYogWizardID() == getHeroTypeID();
  1506. }
  1507. bool CGHeroInstance::isCampaignGem() const
  1508. {
  1509. const StartInfo *si = cb->getStartInfo();
  1510. return si && si->campState &&si->campState->getGemSorceressID() == getHeroTypeID();
  1511. }
  1512. ResourceSet CGHeroInstance::dailyIncome() const
  1513. {
  1514. ResourceSet income;
  1515. for (GameResID k : GameResID::ALL_RESOURCES())
  1516. income[k] += valOfBonuses(BonusType::GENERATE_RESOURCE, BonusSubtypeID(k));
  1517. const auto & playerSettings = cb->getPlayerSettings(getOwner());
  1518. income.applyHandicap(playerSettings->handicap.percentIncome);
  1519. return income;
  1520. }
  1521. std::vector<CreatureID> CGHeroInstance::providedCreatures() const
  1522. {
  1523. return {};
  1524. }
  1525. const IOwnableObject * CGHeroInstance::asOwnable() const
  1526. {
  1527. return this;
  1528. }
  1529. int CGHeroInstance::getBasePrimarySkillValue(PrimarySkill which) const
  1530. {
  1531. std::string cachingStr = "CGHeroInstance::getBasePrimarySkillValue" + std::to_string(which.getNum());
  1532. auto selector = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(which)).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  1533. auto minSkillValue = LIBRARY->engineSettings()->getVectorValue(EGameSettings::HEROES_MINIMAL_PRIMARY_SKILLS, which.getNum());
  1534. return std::max(valOfBonuses(selector, cachingStr), minSkillValue);
  1535. }
  1536. VCMI_LIB_NAMESPACE_END