CGHeroInstance.cpp 50 KB

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