2
0

CGHeroInstance.cpp 54 KB

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