CGHeroInstance.cpp 51 KB

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