CGHeroInstance.cpp 54 KB

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