CGHeroInstance.cpp 52 KB

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