CGHeroInstance.cpp 53 KB

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