CGHeroInstance.cpp 53 KB

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