CGHeroInstance.cpp 52 KB

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