CGHeroInstance.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  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 "../entities/ResourceTypeHandler.h"
  39. #include "../battle/CBattleInfoEssentials.h"
  40. #include "../campaign/CampaignState.h"
  41. #include "../json/JsonBonus.h"
  42. #include "../pathfinder/TurnInfo.h"
  43. #include "../serializer/JsonSerializeFormat.h"
  44. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  45. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  46. #include "../mapObjects/MiscObjects.h"
  47. #include "../modding/ModScope.h"
  48. #include "../networkPacks/PacksForClient.h"
  49. #include "../networkPacks/PacksForClientBattle.h"
  50. #include "../constants/StringConstants.h"
  51. #include "../battle/Unit.h"
  52. #include "CConfigHandler.h"
  53. VCMI_LIB_NAMESPACE_BEGIN
  54. const ui32 CGHeroInstance::NO_PATROLLING = std::numeric_limits<ui32>::max();
  55. void CGHeroPlaceholder::serializeJsonOptions(JsonSerializeFormat & handler)
  56. {
  57. serializeJsonOwner(handler);
  58. bool isHeroType = heroType.has_value();
  59. handler.serializeBool("placeholderType", isHeroType, false);
  60. if(!handler.saving)
  61. {
  62. if(isHeroType)
  63. heroType = HeroTypeID::NONE;
  64. else
  65. powerRank = 0;
  66. }
  67. if(isHeroType)
  68. handler.serializeId("heroType", heroType.value(), HeroTypeID::NONE);
  69. else
  70. handler.serializeInt("powerRank", powerRank.value());
  71. }
  72. FactionID CGHeroInstance::getFactionID() const
  73. {
  74. return getHeroClass()->faction;
  75. }
  76. const IBonusBearer* CGHeroInstance::getBonusBearer() const
  77. {
  78. return this;
  79. }
  80. TerrainId CGHeroInstance::getNativeTerrain() const
  81. {
  82. TerrainId nativeTerrain = ETerrainId::ANY_TERRAIN;
  83. for(const auto & stack : stacks)
  84. {
  85. TerrainId stackNativeTerrain = stack.second->getNativeTerrain(); //consider terrain bonuses e.g. Lodestar.
  86. if(nativeTerrain == ETerrainId::ANY_TERRAIN)
  87. nativeTerrain = stackNativeTerrain;
  88. else if(nativeTerrain != stackNativeTerrain)
  89. return ETerrainId::NONE;
  90. }
  91. return nativeTerrain;
  92. }
  93. bool CGHeroInstance::isCoastVisitable() const
  94. {
  95. return true;
  96. }
  97. bool CGHeroInstance::isBlockedVisitable() const
  98. {
  99. return true;
  100. }
  101. BattleField CGHeroInstance::getBattlefield() const
  102. {
  103. return BattleField::NONE;
  104. }
  105. ui8 CGHeroInstance::getSecSkillLevel(const SecondarySkill & skill) const
  106. {
  107. for(const auto & elem : secSkills)
  108. if(elem.first == skill)
  109. return elem.second;
  110. return 0;
  111. }
  112. void CGHeroInstance::setSecSkillLevel(const SecondarySkill & which, int val, ChangeValueMode mode)
  113. {
  114. int currentLevel = getSecSkillLevel(which);
  115. int newLevel = mode == ChangeValueMode::ABSOLUTE ? val : currentLevel + val;
  116. int newLevelClamped = std::clamp<int>(newLevel, MasteryLevel::NONE, MasteryLevel::EXPERT);
  117. if (currentLevel == newLevelClamped)
  118. return; // no change
  119. if (newLevelClamped == 0) // skill removal
  120. {
  121. vstd::erase_if(secSkills, [which](const std::pair<SecondarySkill, ui8>& pair) { return pair.first == which; });
  122. }
  123. else if(currentLevel == 0) // gained new skill
  124. {
  125. secSkills.emplace_back(which, newLevelClamped);
  126. }
  127. else
  128. {
  129. for (auto & elem : secSkills)
  130. {
  131. if(elem.first == which)
  132. elem.second = newLevelClamped;
  133. }
  134. }
  135. updateSkillBonus(which, newLevelClamped);
  136. }
  137. int3 CGHeroInstance::convertToVisitablePos(const int3 & position) const
  138. {
  139. return position - getVisitableOffset();
  140. }
  141. int3 CGHeroInstance::convertFromVisitablePos(const int3 & position) const
  142. {
  143. return position + getVisitableOffset();
  144. }
  145. bool CGHeroInstance::canLearnSkill() const
  146. {
  147. return secSkills.size() < cb->getSettings().getInteger(EGameSettings::HEROES_SKILL_PER_HERO);
  148. }
  149. bool CGHeroInstance::canLearnSkill(const SecondarySkill & which) const
  150. {
  151. if ( !canLearnSkill())
  152. return false;
  153. if (!cb->isAllowed(which))
  154. return false;
  155. if (getSecSkillLevel(which) > 0)
  156. return false;
  157. if (getHeroClass()->secSkillProbability.count(which) == 0)
  158. return false;
  159. if (getHeroClass()->secSkillProbability.at(which) == 0)
  160. return false;
  161. return true;
  162. }
  163. int CGHeroInstance::movementPointsRemaining() const
  164. {
  165. return movement;
  166. }
  167. void CGHeroInstance::setMovementPoints(int points)
  168. {
  169. if(getBonusBearer()->hasBonusOfType(BonusType::UNLIMITED_MOVEMENT))
  170. movement = 1000000;
  171. else
  172. movement = std::max(0, points);
  173. }
  174. int CGHeroInstance::movementPointsLimit(bool onLand) const
  175. {
  176. auto ti = getTurnInfo(0);
  177. return onLand ? ti->getMovePointsLimitLand() : ti->getMovePointsLimitWater();
  178. }
  179. int CGHeroInstance::getLowestCreatureSpeed() const
  180. {
  181. if(stacksCount() != 0)
  182. {
  183. int minimalSpeed = std::numeric_limits<int>::max();
  184. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  185. for(const auto & slot : Slots())
  186. minimalSpeed = std::min(minimalSpeed, slot.second->getInitiative());
  187. return minimalSpeed;
  188. }
  189. else
  190. {
  191. if(commander && commander->alive)
  192. return commander->getInitiative();
  193. }
  194. return 10;
  195. }
  196. std::unique_ptr<TurnInfo> CGHeroInstance::getTurnInfo(int days) const
  197. {
  198. return std::make_unique<TurnInfo>(turnInfoCache.get(), this, days);
  199. }
  200. int CGHeroInstance::movementPointsLimitCached(bool onLand, const TurnInfo * ti) const
  201. {
  202. if (onLand)
  203. return ti->getMovePointsLimitLand();
  204. else
  205. return ti->getMovePointsLimitWater();
  206. }
  207. CGHeroInstance::CGHeroInstance(IGameInfoCallback * cb)
  208. : CArmedInstance(cb, BonusNodeType::HERO, false),
  209. CArtifactSet(cb),
  210. tacticFormationEnabled(false),
  211. inTownGarrison(false),
  212. moveDir(4),
  213. mana(UNINITIALIZED_MANA),
  214. movement(UNINITIALIZED_MOVEMENT),
  215. level(1),
  216. exp(UNINITIALIZED_EXPERIENCE),
  217. gender(EHeroGender::DEFAULT),
  218. primarySkills(this),
  219. magicSchoolMastery(this),
  220. turnInfoCache(std::make_unique<TurnInfoCache>(this)),
  221. manaPerKnowledgeCached(this, Selector::type()(BonusType::MANA_PER_KNOWLEDGE_PERCENTAGE))
  222. {
  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. int64_t CGHeroInstance::getEffectRange(const spells::Spell * spell) const
  719. {
  720. return 0;
  721. }
  722. PlayerColor CGHeroInstance::getCasterOwner() const
  723. {
  724. return tempOwner;
  725. }
  726. void CGHeroInstance::getCasterName(MetaString & text) const
  727. {
  728. //FIXME: use local name, MetaString need access to gamestate as hero name is part of map object
  729. text.replaceRawString(getNameTranslated());
  730. }
  731. void CGHeroInstance::getCastDescription(const spells::Spell * spell, const battle::Units & attacked, MetaString & text) const
  732. {
  733. const bool singleTarget = attacked.size() == 1;
  734. const int textIndex = singleTarget ? 195 : 196;
  735. text.appendLocalString(EMetaText::GENERAL_TXT, textIndex);
  736. getCasterName(text);
  737. text.replaceName(spell->getId());
  738. if(singleTarget)
  739. attacked.at(0)->addNameReplacement(text, true);
  740. }
  741. const CGHeroInstance * CGHeroInstance::getHeroCaster() const
  742. {
  743. return this;
  744. }
  745. void CGHeroInstance::spendMana(ServerCallback * server, const int spellCost) const
  746. {
  747. if(spellCost != 0)
  748. {
  749. SetMana sm;
  750. sm.mode = ChangeValueMode::RELATIVE;
  751. sm.hid = id;
  752. sm.val = -spellCost;
  753. server->apply(sm);
  754. }
  755. }
  756. bool CGHeroInstance::canCastThisSpell(const spells::Spell * spell) const
  757. {
  758. const bool inSpellBook = spellbookContainsSpell(spell->getId()) && hasSpellbook();
  759. if(spell->isSpecial())
  760. {
  761. if(inSpellBook)
  762. {//hero has this spell in spellbook
  763. logGlobal->error("Special spell %s in spellbook.", spell->getNameTranslated());
  764. }
  765. return hasBonusOfType(BonusType::SPELL, BonusSubtypeID(spell->getId()));
  766. }
  767. else if(!cb->isAllowed(spell->getId()))
  768. {
  769. if(inSpellBook)
  770. {
  771. //hero has this spell in spellbook
  772. //it is normal if set in map editor, but trace it to possible debug of magic guild
  773. logGlobal->trace("Banned spell %s in spellbook.", spell->getNameTranslated());
  774. }
  775. }
  776. return !getSourcesForSpell(spell->getId()).empty();
  777. }
  778. bool CGHeroInstance::canLearnSpell(const spells::Spell * spell, bool allowBanned) const
  779. {
  780. if(!hasSpellbook())
  781. return false;
  782. if(spell->getLevel() > maxSpellLevel()) //not enough wisdom
  783. return false;
  784. if(vstd::contains(spells, spell->getId()))//already known
  785. return false;
  786. if(spell->isSpecial())
  787. {
  788. logGlobal->warn("Hero %s try to learn special spell %s", nodeName(), spell->getNameTranslated());
  789. return false;//special spells can not be learned
  790. }
  791. if(spell->isCreatureAbility())
  792. {
  793. logGlobal->warn("Hero %s try to learn creature spell %s", nodeName(), spell->getNameTranslated());
  794. return false;//creature abilities can not be learned
  795. }
  796. if(!allowBanned && !cb->isAllowed(spell->getId()))
  797. {
  798. logGlobal->warn("Hero %s try to learn banned spell %s", nodeName(), spell->getNameTranslated());
  799. return false;//banned spells should not be learned
  800. }
  801. return true;
  802. }
  803. /**
  804. * Calculates what creatures and how many to be raised from a battle.
  805. * @param battleResult The results of the battle.
  806. * @return Returns a pair with the first value indicating the ID of the creature
  807. * type and second value the amount. Both values are returned as -1 if necromancy
  808. * could not be applied.
  809. */
  810. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  811. {
  812. TConstBonusListPtr improvedNecromancy = getBonusesOfType(BonusType::IMPROVED_NECROMANCY);
  813. // need skill or cloak of undead king - lesser artifacts don't work without skill
  814. if (improvedNecromancy->empty())
  815. return CStackBasicDescriptor();
  816. bool hasRaisedUnitsBonus = hasBonusOfType(BonusType::UNDEAD_RAISE_PERCENTAGE);
  817. int raisedUnitsPercentage = std::clamp(valOfBonuses(BonusType::UNDEAD_RAISE_PERCENTAGE), 0, 100);
  818. if(raisedUnitsPercentage == 0 && !hasRaisedUnitsBonus)
  819. return CStackBasicDescriptor();
  820. const std::map<CreatureID,si32> &casualties = battleResult.casualties[CBattleInfoEssentials::otherSide(battleResult.winner)];
  821. if(casualties.empty())
  822. return CStackBasicDescriptor();
  823. // figure out what to raise - pick strongest creature meeting requirements
  824. CreatureID bestCreature = CreatureID::NONE;
  825. int necromancerPower = improvedNecromancy->totalValue();
  826. // pick best bonus available
  827. for(const std::shared_ptr<Bonus> & newPick : *improvedNecromancy)
  828. {
  829. // addInfo[0] = required necromancy skill
  830. if(newPick->additionalInfo[0] > necromancerPower)
  831. continue;
  832. CreatureID newCreature = newPick->subtype.as<CreatureID>();;
  833. if(!bestCreature.hasValue())
  834. {
  835. bestCreature = newCreature;
  836. }
  837. else
  838. {
  839. auto quality = [](CreatureID pick) -> std::tuple<int, int>
  840. {
  841. const auto * c = pick.toCreature();
  842. return std::tuple<int, int> {c->getLevel(), static_cast<int>(c->getFullRecruitCost().marketValue())};
  843. };
  844. if(quality(bestCreature) < quality(newCreature))
  845. bestCreature = newCreature;
  846. }
  847. }
  848. assert(bestCreature != CreatureID::NONE);
  849. CreatureID selectedCreature = bestCreature;
  850. // raise upgraded creature (at 2/3 rate) if no space available otherwise
  851. if(getSlotFor(selectedCreature) == SlotID())
  852. {
  853. for (const auto & slot : Slots())
  854. {
  855. if (selectedCreature.toCreature()->isMyDirectOrIndirectUpgrade(slot.second->getCreature()))
  856. {
  857. selectedCreature = slot.second->getCreatureID();
  858. break;
  859. }
  860. }
  861. }
  862. // calculate number of creatures raised - low level units contribute at 50% rate
  863. const double raisedUnitHealth = selectedCreature.toCreature()->getMaxHealth();
  864. double raisedUnits = 0;
  865. for(const auto & casualty : casualties)
  866. {
  867. const CCreature * c = casualty.first.toCreature();
  868. double raisedFromCasualty = std::min(c->getMaxHealth() / raisedUnitHealth, 1.0) * casualty.second * raisedUnitsPercentage;
  869. if (bestCreature != selectedCreature)
  870. raisedUnits += raisedFromCasualty * 2 / 3 / 100;
  871. else
  872. raisedUnits += raisedFromCasualty / 100;
  873. }
  874. return CStackBasicDescriptor(selectedCreature, std::max(static_cast<int>(raisedUnits), 1));
  875. }
  876. int CGHeroInstance::getSightRadius() const
  877. {
  878. int baseValue = LIBRARY->engineSettings()->getInteger(EGameSettings::HEROES_BASE_SCOUNTING_RANGE);
  879. return applyBonuses(BonusType::SIGHT_RADIUS, baseValue);
  880. }
  881. si32 CGHeroInstance::manaRegain() const
  882. {
  883. int percentageRegeneration = valOfBonuses(BonusType::MANA_PERCENTAGE_REGENERATION);
  884. int regeneratedByPercentage = manaLimit() * percentageRegeneration / 100;
  885. int regeneratedByValue = valOfBonuses(BonusType::MANA_REGENERATION);
  886. return std::max(regeneratedByValue, regeneratedByPercentage);
  887. }
  888. si32 CGHeroInstance::getManaNewTurn() const
  889. {
  890. if(getVisitedTown() && getVisitedTown()->hasBuilt(BuildingID::MAGES_GUILD_1))
  891. {
  892. //if hero starts turn in town with mage guild - restore all mana
  893. return std::max(mana, manaLimit());
  894. }
  895. si32 res = mana + manaRegain();
  896. res = std::min(res, manaLimit());
  897. res = std::max(res, mana);
  898. res = std::max(res, 0);
  899. return res;
  900. }
  901. // /**
  902. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  903. // * or discards it if it cannot be equipped.
  904. // */
  905. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  906. // {
  907. // CArtifact * const artifact = LIBRARY->arth->objects[aid]; //pointer to constant object
  908. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  909. // ai->putAt(this, ai->firstAvailableSlot(this));
  910. // }
  911. BoatId CGHeroInstance::getBoatType() const
  912. {
  913. return BoatId(LIBRARY->townh->getById(getHeroClass()->faction)->getBoatType());
  914. }
  915. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  916. {
  917. offsets = {
  918. {0, -1, 0},
  919. {+1, -1, 0},
  920. {+1, 0, 0},
  921. {+1, +1, 0},
  922. {0, +1, 0},
  923. {-1, +1, 0},
  924. {-1, 0, 0},
  925. {-1, -1, 0},
  926. };
  927. }
  928. const IObjectInterface * CGHeroInstance::getObject() const
  929. {
  930. return this;
  931. }
  932. int32_t CGHeroInstance::getSpellCost(const spells::Spell * sp) const
  933. {
  934. return sp->getCost(getSpellSchoolLevel(sp));
  935. }
  936. void CGHeroInstance::pushPrimSkill( PrimarySkill which, int val )
  937. {
  938. auto sel = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(which))
  939. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  940. removeBonuses(sel);
  941. addNewBonus(std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::HERO_BASE_SKILL, val, BonusSourceID(id), BonusSubtypeID(which)));
  942. }
  943. EAlignment CGHeroInstance::getAlignment() const
  944. {
  945. return getHeroClass()->getAlignment();
  946. }
  947. void CGHeroInstance::initExp(vstd::RNG & rand)
  948. {
  949. exp = rand.nextInt(40, 89);
  950. }
  951. std::string CGHeroInstance::nodeName() const
  952. {
  953. return "Hero " + getNameTextID();
  954. }
  955. si32 CGHeroInstance::manaLimit() const
  956. {
  957. return getPrimSkillLevel(PrimarySkill::KNOWLEDGE) * manaPerKnowledgeCached.getValue() / 100;
  958. }
  959. HeroTypeID CGHeroInstance::getPortraitSource() const
  960. {
  961. if (customPortraitSource.isValid())
  962. return customPortraitSource;
  963. else
  964. return getHeroTypeID();
  965. }
  966. int32_t CGHeroInstance::getIconIndex() const
  967. {
  968. return getPortraitSource().toEntity(LIBRARY)->getIconIndex();
  969. }
  970. std::string CGHeroInstance::getNameTranslated() const
  971. {
  972. return LIBRARY->generaltexth->translate(getNameTextID());
  973. }
  974. std::string CGHeroInstance::getClassNameTranslated() const
  975. {
  976. return LIBRARY->generaltexth->translate(getClassNameTextID());
  977. }
  978. std::string CGHeroInstance::getClassNameTextID() const
  979. {
  980. if (isCampaignGem())
  981. return "core.genrltxt.735";
  982. return getHeroClass()->getNameTextID();
  983. }
  984. std::string CGHeroInstance::getNameTextID() const
  985. {
  986. if (!nameCustomTextId.empty())
  987. return nameCustomTextId;
  988. if (getHeroTypeID().hasValue())
  989. return getHeroType()->getNameTextID();
  990. // FIXME: called by logging from some specialties (mods?) before type is set on deserialization
  991. // assert(0);
  992. return "";
  993. }
  994. std::string CGHeroInstance::getBiographyTranslated() const
  995. {
  996. return LIBRARY->generaltexth->translate(getBiographyTextID());
  997. }
  998. std::string CGHeroInstance::getBiographyTextID() const
  999. {
  1000. if (!biographyCustomTextId.empty())
  1001. return biographyCustomTextId;
  1002. if (getHeroTypeID().hasValue())
  1003. return getHeroType()->getBiographyTextID();
  1004. return ""; //for random hero
  1005. }
  1006. CGHeroInstance::ArtPlacementMap CGHeroInstance::putArtifact(const ArtifactPosition & pos, const CArtifactInstance * art)
  1007. {
  1008. assert(art->canBePutAt(this, pos));
  1009. if(ArtifactUtils::isSlotEquipment(pos))
  1010. attachToSource(*art);
  1011. return CArtifactSet::putArtifact(pos, art);
  1012. }
  1013. void CGHeroInstance::removeArtifact(const ArtifactPosition & pos)
  1014. {
  1015. auto art = getArt(pos);
  1016. assert(art);
  1017. CArtifactSet::removeArtifact(pos);
  1018. if(ArtifactUtils::isSlotEquipment(pos))
  1019. detachFromSource(*art);
  1020. }
  1021. bool CGHeroInstance::hasSpellbook() const
  1022. {
  1023. return getArt(ArtifactPosition::SPELLBOOK);
  1024. }
  1025. void CGHeroInstance::addSpellToSpellbook(const SpellID & spell)
  1026. {
  1027. spells.insert(spell);
  1028. }
  1029. void CGHeroInstance::removeSpellFromSpellbook(const SpellID & spell)
  1030. {
  1031. spells.erase(spell);
  1032. }
  1033. bool CGHeroInstance::spellbookContainsSpell(const SpellID & spell) const
  1034. {
  1035. return vstd::contains(spells, spell);
  1036. }
  1037. std::vector<BonusSourceID> CGHeroInstance::getSourcesForSpell(const SpellID & spellId) const
  1038. {
  1039. std::vector<BonusSourceID> sources;
  1040. if(hasSpellbook() && spellbookContainsSpell(spellId))
  1041. sources.emplace_back(getArt(ArtifactPosition::SPELLBOOK)->getId());
  1042. for(const auto & bonus : *getBonusesOfType(BonusType::SPELL, spellId))
  1043. sources.emplace_back(bonus->sid);
  1044. bool tomesGrantBannedSpells = cb->getSettings().getBoolean(EGameSettings::SPELLS_TOMES_GRANT_BANNED_SPELLS);
  1045. if (tomesGrantBannedSpells || cb->isAllowed(spellId))
  1046. {
  1047. const auto spell = spellId.toSpell();
  1048. spell->forEachSchool([this, &sources](const SpellSchool & cnf, bool & stop)
  1049. {
  1050. for(const auto & bonus : *getBonusesOfType(BonusType::SPELLS_OF_SCHOOL, cnf))
  1051. sources.emplace_back(bonus->sid);
  1052. });
  1053. for(const auto & bonus : *getBonusesOfType(BonusType::SPELLS_OF_LEVEL, BonusCustomSubtype::spellLevel(spell->getLevel())))
  1054. sources.emplace_back(bonus->sid);
  1055. }
  1056. return sources;
  1057. }
  1058. void CGHeroInstance::removeSpellbook()
  1059. {
  1060. spells.clear();
  1061. if(hasSpellbook())
  1062. {
  1063. cb->gameState().getMap().removeArtifactInstance(*this, ArtifactPosition::SPELLBOOK);
  1064. }
  1065. }
  1066. void CGHeroInstance::removeAllSpells()
  1067. {
  1068. spells.clear();
  1069. }
  1070. const std::set<SpellID> & CGHeroInstance::getSpellsInSpellbook() const
  1071. {
  1072. return spells;
  1073. }
  1074. int CGHeroInstance::maxSpellLevel() const
  1075. {
  1076. return std::min(GameConstants::SPELL_LEVELS, valOfBonuses(BonusType::MAX_LEARNABLE_SPELL_LEVEL));
  1077. }
  1078. bool CGHeroInstance::inBoat() const
  1079. {
  1080. return boardedBoat.hasValue();
  1081. }
  1082. const CGBoat * CGHeroInstance::getBoat() const
  1083. {
  1084. if (boardedBoat.hasValue())
  1085. return dynamic_cast<const CGBoat*>(cb->getObjInstance(boardedBoat));
  1086. return nullptr;
  1087. }
  1088. CGBoat * CGHeroInstance::getBoat()
  1089. {
  1090. if (boardedBoat.hasValue())
  1091. return dynamic_cast<CGBoat*>(cb->gameState().getObjInstance(boardedBoat));
  1092. return nullptr;
  1093. }
  1094. void CGHeroInstance::setBoat(CGBoat* newBoat)
  1095. {
  1096. if (newBoat)
  1097. {
  1098. boardedBoat = newBoat->id;
  1099. attachTo(*newBoat);
  1100. newBoat->setBoardedHero(this);
  1101. }
  1102. else if (boardedBoat.hasValue())
  1103. {
  1104. auto oldBoat = getBoat();
  1105. boardedBoat = {};
  1106. detachFrom(*oldBoat);
  1107. oldBoat->setBoardedHero(nullptr);
  1108. }
  1109. }
  1110. void CGHeroInstance::restoreBonusSystem(CGameState & gs)
  1111. {
  1112. CArmedInstance::restoreBonusSystem(gs);
  1113. artDeserializationFix(gs, this);
  1114. if (commander)
  1115. commander->artDeserializationFix(gs, this->commander.get());
  1116. if (boardedBoat.hasValue())
  1117. {
  1118. auto boat = gs.getObjInstance(boardedBoat);
  1119. if (boat)
  1120. attachTo(dynamic_cast<CGBoat&>(*boat));
  1121. }
  1122. }
  1123. void CGHeroInstance::attachToBonusSystem(CGameState & gs)
  1124. {
  1125. CArmedInstance::attachToBonusSystem(gs);
  1126. if (boardedBoat.hasValue())
  1127. {
  1128. auto boat = gs.getObjInstance(boardedBoat);
  1129. if (boat)
  1130. attachTo(dynamic_cast<CGBoat&>(*boat));
  1131. }
  1132. }
  1133. void CGHeroInstance::detachFromBonusSystem(CGameState & gs)
  1134. {
  1135. CArmedInstance::detachFromBonusSystem(gs);
  1136. if (boardedBoat.hasValue())
  1137. {
  1138. auto boat = gs.getObjInstance(boardedBoat);
  1139. if (boat)
  1140. detachFrom(dynamic_cast<CGBoat&>(*boat));
  1141. }
  1142. }
  1143. CBonusSystemNode & CGHeroInstance::whereShouldBeAttached(CGameState & gs)
  1144. {
  1145. if(visitedTown.hasValue())
  1146. {
  1147. auto town = gs.getTown(visitedTown);
  1148. return town->townAndVis;
  1149. }
  1150. else
  1151. return CArmedInstance::whereShouldBeAttached(gs);
  1152. }
  1153. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const
  1154. {
  1155. if(!ti->hasFreeShipBoarding())
  1156. return 0; // take all MPs by default
  1157. auto boatLayer = inBoat() ? getBoat()->layer : EPathfindingLayer::SAIL;
  1158. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : boatLayer);
  1159. int mp2 = ti->getMaxMovePoints(disembark ? boatLayer : EPathfindingLayer::LAND);
  1160. int ret = static_cast<int>((MPsBefore - basicCost) * static_cast<double>(mp1) / mp2);
  1161. return ret;
  1162. }
  1163. EDiggingStatus CGHeroInstance::diggingStatus() const
  1164. {
  1165. if(static_cast<int>(movement) < movementPointsLimit(true))
  1166. return EDiggingStatus::LACK_OF_MOVEMENT;
  1167. if(!ArtifactID(ArtifactID::GRAIL).toArtifact()->canBePutAt(this))
  1168. return EDiggingStatus::BACKPACK_IS_FULL;
  1169. return cb->getTileDigStatus(visitablePos());
  1170. }
  1171. ArtBearer CGHeroInstance::bearerType() const
  1172. {
  1173. return ArtBearer::HERO;
  1174. }
  1175. std::vector<SecondarySkill> CGHeroInstance::getLevelupSkillCandidates(IGameRandomizer & gameRandomizer) const
  1176. {
  1177. std::set<SecondarySkill> basicAndAdv;
  1178. std::set<SecondarySkill> none;
  1179. std::vector<SecondarySkill> skills;
  1180. if (canLearnSkill())
  1181. {
  1182. for(int i = 0; i < LIBRARY->skillh->size(); i++)
  1183. if (canLearnSkill(SecondarySkill(i)))
  1184. none.insert(SecondarySkill(i));
  1185. }
  1186. for(const auto & elem : secSkills)
  1187. {
  1188. if(elem.second < MasteryLevel::EXPERT)
  1189. basicAndAdv.insert(elem.first);
  1190. none.erase(elem.first);
  1191. }
  1192. int maxUpgradedSkills = cb->getSettings().getInteger(EGameSettings::LEVEL_UP_UPGRADED_SKILLS_AMOUNT);
  1193. while (skills.size() < maxUpgradedSkills && !basicAndAdv.empty())
  1194. {
  1195. skills.push_back(gameRandomizer.rollSecondarySkillForLevelup(this, basicAndAdv));
  1196. basicAndAdv.erase(skills.back());
  1197. }
  1198. int maxTotalSkills = cb->getSettings().getInteger(EGameSettings::LEVEL_UP_TOTAL_SKILLS_AMOUNT);
  1199. while (skills.size() < maxTotalSkills && !none.empty())
  1200. {
  1201. skills.push_back(gameRandomizer.rollSecondarySkillForLevelup(this, none));
  1202. none.erase(skills.back());
  1203. }
  1204. return skills;
  1205. }
  1206. void CGHeroInstance::setPrimarySkill(PrimarySkill primarySkill, si64 value, ChangeValueMode mode)
  1207. {
  1208. auto skill = getLocalBonus(Selector::type()(BonusType::PRIMARY_SKILL)
  1209. .And(Selector::subtype()(BonusSubtypeID(primarySkill)))
  1210. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1211. assert(skill);
  1212. if(mode == ChangeValueMode::ABSOLUTE)
  1213. {
  1214. skill->val = static_cast<si32>(value);
  1215. }
  1216. else
  1217. {
  1218. skill->val += static_cast<si32>(value);
  1219. }
  1220. nodeHasChanged();
  1221. }
  1222. void CGHeroInstance::setExperience(si64 value, ChangeValueMode mode)
  1223. {
  1224. if(mode == ChangeValueMode::ABSOLUTE)
  1225. {
  1226. exp = value;
  1227. }
  1228. else
  1229. {
  1230. exp += value;
  1231. }
  1232. }
  1233. bool CGHeroInstance::gainsLevel() const
  1234. {
  1235. return level < LIBRARY->heroh->maxSupportedLevel() && exp >= static_cast<TExpType>(LIBRARY->heroh->reqExp(level+1));
  1236. }
  1237. void CGHeroInstance::levelUp()
  1238. {
  1239. ++level;
  1240. //update specialty and other bonuses that scale with level
  1241. nodeHasChanged();
  1242. }
  1243. void CGHeroInstance::attachCommanderToArmy()
  1244. {
  1245. if (commander)
  1246. commander->setArmy(this);
  1247. }
  1248. void CGHeroInstance::levelUpAutomatically(IGameRandomizer & gameRandomizer)
  1249. {
  1250. while(gainsLevel())
  1251. {
  1252. const auto primarySkill = gameRandomizer.rollPrimarySkillForLevelup(this);
  1253. const auto proposedSecondarySkills = getLevelupSkillCandidates(gameRandomizer);
  1254. setPrimarySkill(primarySkill, 1, ChangeValueMode::RELATIVE);
  1255. if(!proposedSecondarySkills.empty())
  1256. setSecSkillLevel(proposedSecondarySkills.front(), 1, ChangeValueMode::RELATIVE);
  1257. levelUp();
  1258. }
  1259. }
  1260. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, BonusSubtypeID subtype) const
  1261. {
  1262. //VISIONS spell support
  1263. const int visionsMultiplier = valOfBonuses(BonusType::VISIONS, subtype);
  1264. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1265. if (visionsMultiplier > 0)
  1266. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1267. const int distance = static_cast<int>(target->anchorPos().dist2d(visitablePos()));
  1268. //logGlobal->debug(boost::str(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1269. return (distance < visionsRange) && (target->anchorPos().z == anchorPos().z);
  1270. }
  1271. std::string CGHeroInstance::getHeroTypeName() const
  1272. {
  1273. if(ID == Obj::HERO || ID == Obj::PRISON)
  1274. return getHeroType()->getJsonKey();
  1275. return "";
  1276. }
  1277. void CGHeroInstance::afterAddToMap(CMap * map)
  1278. {
  1279. map->heroAddedToMap(this);
  1280. }
  1281. void CGHeroInstance::afterRemoveFromMap(CMap* map)
  1282. {
  1283. map->heroRemovedFromMap(this);
  1284. }
  1285. void CGHeroInstance::setHeroTypeName(const std::string & identifier)
  1286. {
  1287. if(ID == Obj::HERO || ID == Obj::PRISON)
  1288. {
  1289. auto rawId = LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), "hero", identifier);
  1290. if(rawId)
  1291. subID = rawId.value();
  1292. else
  1293. {
  1294. throw std::runtime_error("Couldn't resolve hero identifier " + identifier);
  1295. }
  1296. }
  1297. }
  1298. void CGHeroInstance::updateFrom(const JsonNode & data)
  1299. {
  1300. CGObjectInstance::updateFrom(data);
  1301. }
  1302. void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
  1303. {
  1304. handler.serializeString("biography", biographyCustomTextId);
  1305. handler.serializeInt("experience", exp, 0);
  1306. if(!handler.saving && exp != UNINITIALIZED_EXPERIENCE) //do not gain levels if experience is not initialized
  1307. {
  1308. while (gainsLevel())
  1309. {
  1310. ++level;
  1311. }
  1312. }
  1313. handler.serializeString("name", nameCustomTextId);
  1314. handler.serializeInt("gender", gender, 0);
  1315. handler.serializeId("portrait", customPortraitSource, HeroTypeID::NONE);
  1316. //primary skills
  1317. if(handler.saving)
  1318. {
  1319. const bool haveSkills = hasBonus(Selector::type()(BonusType::PRIMARY_SKILL).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1320. if(haveSkills)
  1321. {
  1322. auto primarySkills = handler.enterStruct("primarySkills");
  1323. for(auto skill : PrimarySkill::ALL_SKILLS())
  1324. {
  1325. int value = valOfBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(skill)).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1326. handler.serializeInt(NPrimarySkill::names[skill.getNum()], value, 0);
  1327. }
  1328. }
  1329. }
  1330. else
  1331. {
  1332. auto primarySkills = handler.enterStruct("primarySkills");
  1333. if(handler.getCurrent().getType() == JsonNode::JsonType::DATA_STRUCT)
  1334. {
  1335. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1336. {
  1337. int value = 0;
  1338. handler.serializeInt(NPrimarySkill::names[i], value, 0);
  1339. pushPrimSkill(static_cast<PrimarySkill>(i), value);
  1340. }
  1341. }
  1342. }
  1343. //secondary skills
  1344. if(handler.saving)
  1345. {
  1346. //does hero have default skills?
  1347. bool defaultSkills = false;
  1348. bool normalSkills = false;
  1349. for(const auto & p : secSkills)
  1350. {
  1351. if(p.first == SecondarySkill(SecondarySkill::NONE))
  1352. defaultSkills = true;
  1353. else
  1354. normalSkills = true;
  1355. }
  1356. if(defaultSkills && normalSkills)
  1357. logGlobal->error("Mixed default and normal secondary skills");
  1358. //in json default skills means no field/null
  1359. if(!defaultSkills)
  1360. {
  1361. //enter array here as handler initialize it
  1362. auto secondarySkills = handler.enterArray("secondarySkills");
  1363. secondarySkills.syncSize(secSkills, JsonNode::JsonType::DATA_VECTOR);
  1364. for(size_t skillIndex = 0; skillIndex < secondarySkills.size(); ++skillIndex)
  1365. {
  1366. JsonArraySerializer inner = secondarySkills.enterArray(skillIndex);
  1367. SecondarySkill skillId = secSkills.at(skillIndex).first;
  1368. handler.serializeId("skill", skillId);
  1369. std::string skillLevel = NSecondarySkill::levels.at(secSkills.at(skillIndex).second);
  1370. handler.serializeString("level", skillLevel);
  1371. }
  1372. }
  1373. }
  1374. else
  1375. {
  1376. auto secondarySkills = handler.getCurrent()["secondarySkills"];
  1377. secSkills.clear();
  1378. if(secondarySkills.getType() == JsonNode::JsonType::DATA_NULL)
  1379. {
  1380. secSkills.emplace_back(SecondarySkill::NONE, -1);
  1381. }
  1382. else
  1383. {
  1384. auto addSkill = [this](const std::string & skillId, const std::string & levelId)
  1385. {
  1386. const int rawId = SecondarySkill::decode(skillId);
  1387. if(rawId < 0)
  1388. {
  1389. logGlobal->error("Invalid secondary skill %s", skillId);
  1390. return;
  1391. }
  1392. const int level = vstd::find_pos(NSecondarySkill::levels, levelId);
  1393. if(level < 0)
  1394. {
  1395. logGlobal->error("Invalid secondary skill level%s", levelId);
  1396. return;
  1397. }
  1398. secSkills.emplace_back(SecondarySkill(rawId), level);
  1399. };
  1400. if(secondarySkills.getType() == JsonNode::JsonType::DATA_VECTOR)
  1401. {
  1402. for(const auto & p : secondarySkills.Vector())
  1403. {
  1404. auto skillMap = p.Struct();
  1405. addSkill(skillMap["skill"].String(), skillMap["level"].String());
  1406. }
  1407. }
  1408. else if(secondarySkills.getType() == JsonNode::JsonType::DATA_STRUCT)
  1409. {
  1410. for(const auto & p : secondarySkills.Struct())
  1411. {
  1412. addSkill(p.first, p.second.String());
  1413. };
  1414. }
  1415. }
  1416. }
  1417. handler.serializeIdArray("spellBook", spells);
  1418. if(handler.saving)
  1419. {
  1420. // FIXME: EditorCallback (used in map editor) has no access to GameState.
  1421. // serializeJsonArtifacts expects non-const CMap *
  1422. // Find some cleaner solution
  1423. if(auto * ecb = dynamic_cast<EditorCallback *>(cb))
  1424. CArtifactSet::serializeJsonArtifacts(handler, "artifacts", const_cast<CMap *>(ecb->getMapConstPtr()));
  1425. else
  1426. CArtifactSet::serializeJsonArtifacts(handler, "artifacts", &cb->gameState().getMap());
  1427. }
  1428. }
  1429. void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1430. {
  1431. serializeCommonOptions(handler);
  1432. serializeJsonOwner(handler);
  1433. if(ID == Obj::HERO || ID == Obj::PRISON)
  1434. {
  1435. std::string typeName;
  1436. if(handler.saving)
  1437. typeName = getHeroTypeName();
  1438. handler.serializeString("type", typeName);
  1439. if(!handler.saving)
  1440. setHeroTypeName(typeName);
  1441. }
  1442. if(!handler.saving)
  1443. {
  1444. if(!appearance)
  1445. {
  1446. // crossoverDeserialize
  1447. appearance = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClassID())->getTemplates().front();
  1448. }
  1449. }
  1450. CArmedInstance::serializeJsonOptions(handler);
  1451. {
  1452. ui32 rawPatrolRadius = NO_PATROLLING;
  1453. if(handler.saving)
  1454. {
  1455. rawPatrolRadius = patrol.patrolling ? patrol.patrolRadius : NO_PATROLLING;
  1456. }
  1457. handler.serializeInt("patrolRadius", rawPatrolRadius, NO_PATROLLING);
  1458. if(!handler.saving)
  1459. {
  1460. patrol.patrolling = (rawPatrolRadius != NO_PATROLLING);
  1461. patrol.initialPos = visitablePos();
  1462. patrol.patrolRadius = patrol.patrolling ? rawPatrolRadius : 0;
  1463. }
  1464. }
  1465. }
  1466. void CGHeroInstance::serializeJsonDefinition(JsonSerializeFormat & handler)
  1467. {
  1468. serializeCommonOptions(handler);
  1469. }
  1470. bool CGHeroInstance::isMissionCritical() const
  1471. {
  1472. for(const TriggeredEvent & event : cb->getMapHeader()->triggeredEvents)
  1473. {
  1474. if (event.effect.type != EventEffect::DEFEAT)
  1475. continue;
  1476. auto const & testFunctor = [&](const EventCondition & condition)
  1477. {
  1478. if ((condition.condition == EventCondition::CONTROL) && condition.objectID != ObjectInstanceID::NONE)
  1479. return (id != condition.objectID);
  1480. if (condition.condition == EventCondition::HAVE_ARTIFACT)
  1481. {
  1482. if(hasArt(condition.objectType.as<ArtifactID>()))
  1483. return true;
  1484. }
  1485. if(condition.condition == EventCondition::IS_HUMAN)
  1486. return true;
  1487. return false;
  1488. };
  1489. if(event.trigger.test(testFunctor))
  1490. return true;
  1491. }
  1492. return false;
  1493. }
  1494. void CGHeroInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance & stack) const
  1495. {
  1496. TConstBonusListPtr lista = stack.getBonusesOfType(BonusType::SPECIAL_UPGRADE, BonusSubtypeID(stack.getId()));
  1497. for(const auto & it : *lista)
  1498. {
  1499. auto nid = CreatureID(it->additionalInfo[0]);
  1500. if (nid != stack.getId()) //in very specific case the upgrade is available by default (?)
  1501. {
  1502. info.addUpgrade(nid, stack.getType());
  1503. }
  1504. }
  1505. }
  1506. bool CGHeroInstance::isCampaignYog() const
  1507. {
  1508. const StartInfo *si = cb->getStartInfo();
  1509. return si && si->campState &&si->campState->getYogWizardID() == getHeroTypeID();
  1510. }
  1511. bool CGHeroInstance::isCampaignGem() const
  1512. {
  1513. const StartInfo *si = cb->getStartInfo();
  1514. return si && si->campState &&si->campState->getGemSorceressID() == getHeroTypeID();
  1515. }
  1516. ResourceSet CGHeroInstance::dailyIncome() const
  1517. {
  1518. ResourceSet income;
  1519. for (GameResID k : LIBRARY->resourceTypeHandler->getAllObjects())
  1520. income[k] += valOfBonuses(BonusType::GENERATE_RESOURCE, BonusSubtypeID(k));
  1521. const auto & playerSettings = cb->getPlayerSettings(getOwner());
  1522. income.applyHandicap(playerSettings->handicap.percentIncome);
  1523. return income;
  1524. }
  1525. std::vector<CreatureID> CGHeroInstance::providedCreatures() const
  1526. {
  1527. return {};
  1528. }
  1529. const IOwnableObject * CGHeroInstance::asOwnable() const
  1530. {
  1531. return this;
  1532. }
  1533. int CGHeroInstance::getBasePrimarySkillValue(PrimarySkill which) const
  1534. {
  1535. std::string cachingStr = "CGHeroInstance::getBasePrimarySkillValue" + std::to_string(which.getNum());
  1536. auto selector = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(which)).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  1537. auto minSkillValue = LIBRARY->engineSettings()->getVectorValue(EGameSettings::HEROES_MINIMAL_PRIMARY_SKILLS, which.getNum());
  1538. return std::max(valOfBonuses(selector, cachingStr), minSkillValue);
  1539. }
  1540. VCMI_LIB_NAMESPACE_END