CGHeroInstance.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  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. if(casualties.empty())
  817. return CStackBasicDescriptor();
  818. // figure out what to raise - pick strongest creature meeting requirements
  819. CreatureID creatureTypeRaised = CreatureID::NONE; //now we always have IMPROVED_NECROMANCY, no need for hardcode
  820. int requiredCasualtyLevel = 1;
  821. TConstBonusListPtr improvedNecromancy = getBonusesOfType(BonusType::IMPROVED_NECROMANCY);
  822. if(!improvedNecromancy->empty())
  823. {
  824. int maxCasualtyLevel = 1;
  825. for(const auto & casualty : casualties)
  826. vstd::amax(maxCasualtyLevel, LIBRARY->creatures()->getById(casualty.first)->getLevel());
  827. // pick best bonus available
  828. std::shared_ptr<Bonus> topPick;
  829. for(const std::shared_ptr<Bonus> & newPick : *improvedNecromancy)
  830. {
  831. // addInfo[0] = required necromancy skill, addInfo[1] = required casualty level
  832. if(newPick->additionalInfo[0] > necromancyLevel || newPick->additionalInfo[1] > maxCasualtyLevel)
  833. continue;
  834. if(!topPick)
  835. {
  836. topPick = newPick;
  837. }
  838. else
  839. {
  840. auto quality = [](const std::shared_ptr<Bonus> & pick) -> std::tuple<int, int, int>
  841. {
  842. const auto * c = pick->subtype.as<CreatureID>().toCreature();
  843. return std::tuple<int, int, int> {c->getLevel(), static_cast<int>(c->getFullRecruitCost().marketValue()), -pick->additionalInfo[1]};
  844. };
  845. if(quality(topPick) < quality(newPick))
  846. topPick = newPick;
  847. }
  848. }
  849. if(topPick)
  850. {
  851. creatureTypeRaised = topPick->subtype.as<CreatureID>();
  852. requiredCasualtyLevel = std::max(topPick->additionalInfo[1], 1);
  853. }
  854. }
  855. assert(creatureTypeRaised != CreatureID::NONE);
  856. // raise upgraded creature (at 2/3 rate) if no space available otherwise
  857. if(getSlotFor(creatureTypeRaised) == SlotID())
  858. {
  859. for(const CreatureID & upgraded : creatureTypeRaised.toCreature()->upgrades)
  860. {
  861. if(getSlotFor(upgraded) != SlotID())
  862. {
  863. creatureTypeRaised = upgraded;
  864. necromancySkill *= 2/3.0;
  865. break;
  866. }
  867. }
  868. }
  869. // calculate number of creatures raised - low level units contribute at 50% rate
  870. const double raisedUnitHealth = creatureTypeRaised.toCreature()->getMaxHealth();
  871. double raisedUnits = 0;
  872. for(const auto & casualty : casualties)
  873. {
  874. const CCreature * c = casualty.first.toCreature();
  875. double raisedFromCasualty = std::min(c->getMaxHealth() / raisedUnitHealth, 1.0) * casualty.second * necromancySkill;
  876. if(c->getLevel() < requiredCasualtyLevel)
  877. raisedFromCasualty *= 0.5;
  878. raisedUnits += raisedFromCasualty;
  879. }
  880. return CStackBasicDescriptor(creatureTypeRaised, std::max(static_cast<int>(raisedUnits), 1));
  881. }
  882. return CStackBasicDescriptor();
  883. }
  884. /*
  885. int3 CGHeroInstance::getSightCenter() const
  886. {
  887. return getPosition(false);
  888. }*/
  889. int CGHeroInstance::getSightRadius() const
  890. {
  891. return valOfBonuses(BonusType::SIGHT_RADIUS); // scouting gives SIGHT_RADIUS bonus
  892. }
  893. si32 CGHeroInstance::manaRegain() const
  894. {
  895. if (hasBonusOfType(BonusType::FULL_MANA_REGENERATION))
  896. return manaLimit();
  897. return valOfBonuses(BonusType::MANA_REGENERATION);
  898. }
  899. si32 CGHeroInstance::getManaNewTurn() const
  900. {
  901. if(visitedTown && visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  902. {
  903. //if hero starts turn in town with mage guild - restore all mana
  904. return std::max(mana, manaLimit());
  905. }
  906. si32 res = mana + manaRegain();
  907. res = std::min(res, manaLimit());
  908. res = std::max(res, mana);
  909. res = std::max(res, 0);
  910. return res;
  911. }
  912. // /**
  913. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  914. // * or discards it if it cannot be equipped.
  915. // */
  916. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  917. // {
  918. // CArtifact * const artifact = LIBRARY->arth->objects[aid]; //pointer to constant object
  919. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  920. // ai->putAt(this, ai->firstAvailableSlot(this));
  921. // }
  922. BoatId CGHeroInstance::getBoatType() const
  923. {
  924. return BoatId(LIBRARY->townh->getById(getHeroClass()->faction)->getBoatType());
  925. }
  926. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  927. {
  928. offsets = {
  929. {0, -1, 0},
  930. {+1, -1, 0},
  931. {+1, 0, 0},
  932. {+1, +1, 0},
  933. {0, +1, 0},
  934. {-1, +1, 0},
  935. {-1, 0, 0},
  936. {-1, -1, 0},
  937. };
  938. }
  939. const IObjectInterface * CGHeroInstance::getObject() const
  940. {
  941. return this;
  942. }
  943. int32_t CGHeroInstance::getSpellCost(const spells::Spell * sp) const
  944. {
  945. return sp->getCost(getSpellSchoolLevel(sp));
  946. }
  947. void CGHeroInstance::pushPrimSkill( PrimarySkill which, int val )
  948. {
  949. auto sel = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(which))
  950. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  951. removeBonuses(sel);
  952. addNewBonus(std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::HERO_BASE_SKILL, val, BonusSourceID(id), BonusSubtypeID(which)));
  953. }
  954. EAlignment CGHeroInstance::getAlignment() const
  955. {
  956. return getHeroClass()->getAlignment();
  957. }
  958. void CGHeroInstance::initExp(vstd::RNG & rand)
  959. {
  960. exp = rand.nextInt(40, 89);
  961. }
  962. std::string CGHeroInstance::nodeName() const
  963. {
  964. return "Hero " + getNameTextID();
  965. }
  966. si32 CGHeroInstance::manaLimit() const
  967. {
  968. return getPrimSkillLevel(PrimarySkill::KNOWLEDGE) * manaPerKnowledgeCached.getValue() / 100;
  969. }
  970. HeroTypeID CGHeroInstance::getPortraitSource() const
  971. {
  972. if (customPortraitSource.isValid())
  973. return customPortraitSource;
  974. else
  975. return getHeroTypeID();
  976. }
  977. int32_t CGHeroInstance::getIconIndex() const
  978. {
  979. return getPortraitSource().toEntity(LIBRARY)->getIconIndex();
  980. }
  981. std::string CGHeroInstance::getNameTranslated() const
  982. {
  983. return LIBRARY->generaltexth->translate(getNameTextID());
  984. }
  985. std::string CGHeroInstance::getClassNameTranslated() const
  986. {
  987. return LIBRARY->generaltexth->translate(getClassNameTextID());
  988. }
  989. std::string CGHeroInstance::getClassNameTextID() const
  990. {
  991. if (isCampaignGem())
  992. return "core.genrltxt.735";
  993. return getHeroClass()->getNameTextID();
  994. }
  995. std::string CGHeroInstance::getNameTextID() const
  996. {
  997. if (!nameCustomTextId.empty())
  998. return nameCustomTextId;
  999. if (getHeroTypeID().hasValue())
  1000. return getHeroType()->getNameTextID();
  1001. // FIXME: called by logging from some specialties (mods?) before type is set on deserialization
  1002. // assert(0);
  1003. return "";
  1004. }
  1005. std::string CGHeroInstance::getBiographyTranslated() const
  1006. {
  1007. return LIBRARY->generaltexth->translate(getBiographyTextID());
  1008. }
  1009. std::string CGHeroInstance::getBiographyTextID() const
  1010. {
  1011. if (!biographyCustomTextId.empty())
  1012. return biographyCustomTextId;
  1013. if (getHeroTypeID().hasValue())
  1014. return getHeroType()->getBiographyTextID();
  1015. return ""; //for random hero
  1016. }
  1017. CGHeroInstance::ArtPlacementMap CGHeroInstance::putArtifact(const ArtifactPosition & pos, CArtifactInstance * art)
  1018. {
  1019. assert(art->canBePutAt(this, pos));
  1020. if(ArtifactUtils::isSlotEquipment(pos))
  1021. attachTo(*art);
  1022. return CArtifactSet::putArtifact(pos, art);
  1023. }
  1024. void CGHeroInstance::removeArtifact(const ArtifactPosition & pos)
  1025. {
  1026. auto art = getArt(pos);
  1027. assert(art);
  1028. CArtifactSet::removeArtifact(pos);
  1029. if(ArtifactUtils::isSlotEquipment(pos))
  1030. detachFrom(*art);
  1031. }
  1032. bool CGHeroInstance::hasSpellbook() const
  1033. {
  1034. return getArt(ArtifactPosition::SPELLBOOK);
  1035. }
  1036. void CGHeroInstance::addSpellToSpellbook(const SpellID & spell)
  1037. {
  1038. spells.insert(spell);
  1039. }
  1040. void CGHeroInstance::removeSpellFromSpellbook(const SpellID & spell)
  1041. {
  1042. spells.erase(spell);
  1043. }
  1044. bool CGHeroInstance::spellbookContainsSpell(const SpellID & spell) const
  1045. {
  1046. return vstd::contains(spells, spell);
  1047. }
  1048. void CGHeroInstance::removeSpellbook()
  1049. {
  1050. spells.clear();
  1051. if(hasSpellbook())
  1052. {
  1053. cb->gameState()->getMap().removeArtifactInstance(*this, ArtifactPosition::SPELLBOOK);
  1054. }
  1055. }
  1056. const std::set<SpellID> & CGHeroInstance::getSpellsInSpellbook() const
  1057. {
  1058. return spells;
  1059. }
  1060. int CGHeroInstance::maxSpellLevel() const
  1061. {
  1062. return std::min(GameConstants::SPELL_LEVELS, valOfBonuses(BonusType::MAX_LEARNABLE_SPELL_LEVEL));
  1063. }
  1064. void CGHeroInstance::attachToBoat(CGBoat* newBoat)
  1065. {
  1066. assert(newBoat);
  1067. boat = newBoat;
  1068. attachTo(const_cast<CGBoat&>(*boat));
  1069. const_cast<CGBoat*>(boat)->hero = this;
  1070. }
  1071. void CGHeroInstance::deserializationFix()
  1072. {
  1073. artDeserializationFix(this);
  1074. boatDeserializationFix();
  1075. }
  1076. void CGHeroInstance::boatDeserializationFix()
  1077. {
  1078. if (boat)
  1079. attachTo(const_cast<CGBoat&>(*boat));
  1080. }
  1081. CBonusSystemNode * CGHeroInstance::whereShouldBeAttachedOnSiege(const bool isBattleOutsideTown) const
  1082. {
  1083. if(!visitedTown)
  1084. return nullptr;
  1085. return isBattleOutsideTown ? (CBonusSystemNode *)(& visitedTown->townAndVis)
  1086. : (CBonusSystemNode *)(visitedTown.get());
  1087. }
  1088. CBonusSystemNode * CGHeroInstance::whereShouldBeAttachedOnSiege(CGameState * gs)
  1089. {
  1090. if(visitedTown)
  1091. return whereShouldBeAttachedOnSiege(visitedTown->isBattleOutsideTown(this));
  1092. return &CArmedInstance::whereShouldBeAttached(gs);
  1093. }
  1094. CBonusSystemNode & CGHeroInstance::whereShouldBeAttached(CGameState * gs)
  1095. {
  1096. if(visitedTown)
  1097. {
  1098. if(inTownGarrison)
  1099. return *visitedTown;
  1100. else
  1101. return visitedTown->townAndVis;
  1102. }
  1103. else
  1104. return CArmedInstance::whereShouldBeAttached(gs);
  1105. }
  1106. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const
  1107. {
  1108. if(!ti->hasFreeShipBoarding())
  1109. return 0; // take all MPs by default
  1110. auto boatLayer = boat ? boat->layer : EPathfindingLayer::SAIL;
  1111. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : boatLayer);
  1112. int mp2 = ti->getMaxMovePoints(disembark ? boatLayer : EPathfindingLayer::LAND);
  1113. int ret = static_cast<int>((MPsBefore - basicCost) * static_cast<double>(mp1) / mp2);
  1114. return ret;
  1115. }
  1116. EDiggingStatus CGHeroInstance::diggingStatus() const
  1117. {
  1118. if(static_cast<int>(movement) < movementPointsLimit(true))
  1119. return EDiggingStatus::LACK_OF_MOVEMENT;
  1120. if(!ArtifactID(ArtifactID::GRAIL).toArtifact()->canBePutAt(this))
  1121. return EDiggingStatus::BACKPACK_IS_FULL;
  1122. return cb->getTileDigStatus(visitablePos());
  1123. }
  1124. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1125. {
  1126. return ArtBearer::HERO;
  1127. }
  1128. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills(vstd::RNG & rand) const
  1129. {
  1130. auto getObligatorySkills = [](CSkill::Obligatory obl){
  1131. std::set<SecondarySkill> obligatory;
  1132. for(auto i = 0; i < LIBRARY->skillh->size(); i++)
  1133. if((*LIBRARY->skillh)[SecondarySkill(i)]->obligatory(obl))
  1134. obligatory.insert(i); //Always return all obligatory skills
  1135. return obligatory;
  1136. };
  1137. auto intersect = [](const std::set<SecondarySkill> & left, const std::set<SecondarySkill> & right)
  1138. {
  1139. std::set<SecondarySkill> intersect;
  1140. std::set_intersection(left.begin(), left.end(), right.begin(), right.end(),
  1141. std::inserter(intersect, intersect.begin()));
  1142. return intersect;
  1143. };
  1144. std::set<SecondarySkill> wisdomList = getObligatorySkills(CSkill::Obligatory::MAJOR);
  1145. std::set<SecondarySkill> schoolList = getObligatorySkills(CSkill::Obligatory::MINOR);
  1146. std::set<SecondarySkill> basicAndAdv;
  1147. std::set<SecondarySkill> none;
  1148. for(int i = 0; i < LIBRARY->skillh->size(); i++)
  1149. if (canLearnSkill(SecondarySkill(i)))
  1150. none.insert(SecondarySkill(i));
  1151. for(const auto & elem : secSkills)
  1152. {
  1153. if(elem.second < MasteryLevel::EXPERT)
  1154. basicAndAdv.insert(elem.first);
  1155. none.erase(elem.first);
  1156. }
  1157. bool wantsWisdom = skillsInfo.wisdomCounter + 1 >= maxlevelsToWisdom();
  1158. bool wantsSchool = skillsInfo.magicSchoolCounter + 1 >= maxlevelsToMagicSchool();
  1159. std::vector<SecondarySkill> skills;
  1160. auto chooseSkill = [&](std::set<SecondarySkill> & options)
  1161. {
  1162. bool selectWisdom = wantsWisdom && !intersect(options, wisdomList).empty();
  1163. bool selectSchool = wantsSchool && !intersect(options, schoolList).empty();
  1164. SecondarySkill selection;
  1165. if (selectWisdom)
  1166. selection = getHeroClass()->chooseSecSkill(intersect(options, wisdomList), rand);
  1167. else if (selectSchool)
  1168. selection = getHeroClass()->chooseSecSkill(intersect(options, schoolList), rand);
  1169. else
  1170. selection = getHeroClass()->chooseSecSkill(options, rand);
  1171. skills.push_back(selection);
  1172. options.erase(selection);
  1173. if (wisdomList.count(selection))
  1174. wisdomList.clear();
  1175. if (schoolList.count(selection))
  1176. schoolList.clear();
  1177. };
  1178. if (!basicAndAdv.empty())
  1179. chooseSkill(basicAndAdv);
  1180. if (canLearnSkill() && !none.empty())
  1181. chooseSkill(none);
  1182. if (!basicAndAdv.empty() && skills.size() < 2)
  1183. chooseSkill(basicAndAdv);
  1184. if (canLearnSkill() && !none.empty() && skills.size() < 2)
  1185. chooseSkill(none);
  1186. return skills;
  1187. }
  1188. PrimarySkill CGHeroInstance::nextPrimarySkill(vstd::RNG & rand) const
  1189. {
  1190. assert(gainsLevel());
  1191. const auto isLowLevelHero = level < GameConstants::HERO_HIGH_LEVEL;
  1192. const auto & skillChances = isLowLevelHero ? getHeroClass()->primarySkillLowLevel : getHeroClass()->primarySkillHighLevel;
  1193. if (isCampaignYog())
  1194. {
  1195. // Yog can only receive Attack or Defence on level-up
  1196. std::vector<int> yogChances = { skillChances[0], skillChances[1]};
  1197. return static_cast<PrimarySkill>(RandomGeneratorUtil::nextItemWeighted(yogChances, rand));
  1198. }
  1199. return static_cast<PrimarySkill>(RandomGeneratorUtil::nextItemWeighted(skillChances, rand));
  1200. }
  1201. std::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(vstd::RNG & rand) const
  1202. {
  1203. assert(gainsLevel());
  1204. std::optional<SecondarySkill> chosenSecondarySkill;
  1205. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills(rand);
  1206. if(!proposedSecondarySkills.empty())
  1207. {
  1208. std::vector<SecondarySkill> learnedSecondarySkills;
  1209. for(const auto & secondarySkill : proposedSecondarySkills)
  1210. {
  1211. if(getSecSkillLevel(secondarySkill) > 0)
  1212. {
  1213. learnedSecondarySkills.push_back(secondarySkill);
  1214. }
  1215. }
  1216. if(learnedSecondarySkills.empty())
  1217. {
  1218. // there are only new skills to learn, so choose anyone of them
  1219. chosenSecondarySkill = std::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand));
  1220. }
  1221. else
  1222. {
  1223. // preferably upgrade a already learned secondary skill
  1224. chosenSecondarySkill = std::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand));
  1225. }
  1226. }
  1227. return chosenSecondarySkill;
  1228. }
  1229. void CGHeroInstance::setPrimarySkill(PrimarySkill primarySkill, si64 value, ui8 abs)
  1230. {
  1231. if(primarySkill < PrimarySkill::EXPERIENCE)
  1232. {
  1233. auto skill = getLocalBonus(Selector::type()(BonusType::PRIMARY_SKILL)
  1234. .And(Selector::subtype()(BonusSubtypeID(primarySkill)))
  1235. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1236. assert(skill);
  1237. if(abs)
  1238. {
  1239. skill->val = static_cast<si32>(value);
  1240. }
  1241. else
  1242. {
  1243. skill->val += static_cast<si32>(value);
  1244. }
  1245. nodeHasChanged();
  1246. }
  1247. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1248. {
  1249. if(abs)
  1250. {
  1251. exp = value;
  1252. }
  1253. else
  1254. {
  1255. exp += value;
  1256. }
  1257. }
  1258. }
  1259. bool CGHeroInstance::gainsLevel() const
  1260. {
  1261. return level < LIBRARY->heroh->maxSupportedLevel() && exp >= static_cast<TExpType>(LIBRARY->heroh->reqExp(level+1));
  1262. }
  1263. void CGHeroInstance::levelUp(const std::vector<SecondarySkill> & skills)
  1264. {
  1265. ++level;
  1266. //deterministic secondary skills
  1267. ++skillsInfo.magicSchoolCounter;
  1268. ++skillsInfo.wisdomCounter;
  1269. for(const auto & skill : skills)
  1270. {
  1271. if((*LIBRARY->skillh)[skill]->obligatory(CSkill::Obligatory::MAJOR))
  1272. skillsInfo.resetWisdomCounter();
  1273. if((*LIBRARY->skillh)[skill]->obligatory(CSkill::Obligatory::MINOR))
  1274. skillsInfo.resetMagicSchoolCounter();
  1275. }
  1276. //update specialty and other bonuses that scale with level
  1277. nodeHasChanged();
  1278. }
  1279. void CGHeroInstance::levelUpAutomatically(vstd::RNG & rand)
  1280. {
  1281. while(gainsLevel())
  1282. {
  1283. const auto primarySkill = nextPrimarySkill(rand);
  1284. setPrimarySkill(primarySkill, 1, false);
  1285. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills(rand);
  1286. const auto secondarySkill = nextSecondarySkill(rand);
  1287. if(secondarySkill)
  1288. {
  1289. setSecSkillLevel(*secondarySkill, 1, false);
  1290. }
  1291. //TODO why has the secondary skills to be passed to the method?
  1292. levelUp(proposedSecondarySkills);
  1293. }
  1294. }
  1295. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, BonusSubtypeID subtype) const
  1296. {
  1297. //VISIONS spell support
  1298. const int visionsMultiplier = valOfBonuses(BonusType::VISIONS, subtype);
  1299. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1300. if (visionsMultiplier > 0)
  1301. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1302. const int distance = static_cast<int>(target->anchorPos().dist2d(visitablePos()));
  1303. //logGlobal->debug(boost::str(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1304. return (distance < visionsRange) && (target->anchorPos().z == anchorPos().z);
  1305. }
  1306. std::string CGHeroInstance::getHeroTypeName() const
  1307. {
  1308. if(ID == Obj::HERO || ID == Obj::PRISON)
  1309. return getHeroType()->getJsonKey();
  1310. return "";
  1311. }
  1312. void CGHeroInstance::afterAddToMap(CMap * map)
  1313. {
  1314. if(ID != Obj::PRISON)
  1315. map->heroesOnMap.emplace_back(this);
  1316. }
  1317. void CGHeroInstance::afterRemoveFromMap(CMap* map)
  1318. {
  1319. if (ID == Obj::PRISON)
  1320. vstd::erase_if_present(map->heroesOnMap, this);
  1321. }
  1322. void CGHeroInstance::setHeroTypeName(const std::string & identifier)
  1323. {
  1324. if(ID == Obj::HERO || ID == Obj::PRISON)
  1325. {
  1326. auto rawId = LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), "hero", identifier);
  1327. if(rawId)
  1328. subID = rawId.value();
  1329. else
  1330. {
  1331. throw std::runtime_error("Couldn't resolve hero identifier " + identifier);
  1332. }
  1333. }
  1334. }
  1335. void CGHeroInstance::updateFrom(const JsonNode & data)
  1336. {
  1337. CGObjectInstance::updateFrom(data);
  1338. }
  1339. void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
  1340. {
  1341. handler.serializeString("biography", biographyCustomTextId);
  1342. handler.serializeInt("experience", exp, 0);
  1343. if(!handler.saving && exp != UNINITIALIZED_EXPERIENCE) //do not gain levels if experience is not initialized
  1344. {
  1345. while (gainsLevel())
  1346. {
  1347. ++level;
  1348. }
  1349. }
  1350. handler.serializeString("name", nameCustomTextId);
  1351. handler.serializeInt("gender", gender, 0);
  1352. handler.serializeId("portrait", customPortraitSource, HeroTypeID::NONE);
  1353. //primary skills
  1354. if(handler.saving)
  1355. {
  1356. const bool haveSkills = hasBonus(Selector::type()(BonusType::PRIMARY_SKILL).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1357. if(haveSkills)
  1358. {
  1359. auto primarySkills = handler.enterStruct("primarySkills");
  1360. for(auto skill : PrimarySkill::ALL_SKILLS())
  1361. {
  1362. int value = valOfBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(skill)).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1363. handler.serializeInt(NPrimarySkill::names[skill.getNum()], value, 0);
  1364. }
  1365. }
  1366. }
  1367. else
  1368. {
  1369. auto primarySkills = handler.enterStruct("primarySkills");
  1370. if(handler.getCurrent().getType() == JsonNode::JsonType::DATA_STRUCT)
  1371. {
  1372. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1373. {
  1374. int value = 0;
  1375. handler.serializeInt(NPrimarySkill::names[i], value, 0);
  1376. pushPrimSkill(static_cast<PrimarySkill>(i), value);
  1377. }
  1378. }
  1379. }
  1380. //secondary skills
  1381. if(handler.saving)
  1382. {
  1383. //does hero have default skills?
  1384. bool defaultSkills = false;
  1385. bool normalSkills = false;
  1386. for(const auto & p : secSkills)
  1387. {
  1388. if(p.first == SecondarySkill(SecondarySkill::NONE))
  1389. defaultSkills = true;
  1390. else
  1391. normalSkills = true;
  1392. }
  1393. if(defaultSkills && normalSkills)
  1394. logGlobal->error("Mixed default and normal secondary skills");
  1395. //in json default skills means no field/null
  1396. if(!defaultSkills)
  1397. {
  1398. //enter array here as handler initialize it
  1399. auto secondarySkills = handler.enterArray("secondarySkills");
  1400. secondarySkills.syncSize(secSkills, JsonNode::JsonType::DATA_VECTOR);
  1401. for(size_t skillIndex = 0; skillIndex < secondarySkills.size(); ++skillIndex)
  1402. {
  1403. JsonArraySerializer inner = secondarySkills.enterArray(skillIndex);
  1404. SecondarySkill skillId = secSkills.at(skillIndex).first;
  1405. handler.serializeId("skill", skillId);
  1406. std::string skillLevel = NSecondarySkill::levels.at(secSkills.at(skillIndex).second);
  1407. handler.serializeString("level", skillLevel);
  1408. }
  1409. }
  1410. }
  1411. else
  1412. {
  1413. auto secondarySkills = handler.getCurrent()["secondarySkills"];
  1414. secSkills.clear();
  1415. if(secondarySkills.getType() == JsonNode::JsonType::DATA_NULL)
  1416. {
  1417. secSkills.emplace_back(SecondarySkill::NONE, -1);
  1418. }
  1419. else
  1420. {
  1421. auto addSkill = [this](const std::string & skillId, const std::string & levelId)
  1422. {
  1423. const int rawId = SecondarySkill::decode(skillId);
  1424. if(rawId < 0)
  1425. {
  1426. logGlobal->error("Invalid secondary skill %s", skillId);
  1427. return;
  1428. }
  1429. const int level = vstd::find_pos(NSecondarySkill::levels, levelId);
  1430. if(level < 0)
  1431. {
  1432. logGlobal->error("Invalid secondary skill level%s", levelId);
  1433. return;
  1434. }
  1435. secSkills.emplace_back(SecondarySkill(rawId), level);
  1436. };
  1437. if(secondarySkills.getType() == JsonNode::JsonType::DATA_VECTOR)
  1438. {
  1439. for(const auto & p : secondarySkills.Vector())
  1440. {
  1441. auto skillMap = p.Struct();
  1442. addSkill(skillMap["skill"].String(), skillMap["level"].String());
  1443. }
  1444. }
  1445. else if(secondarySkills.getType() == JsonNode::JsonType::DATA_STRUCT)
  1446. {
  1447. for(const auto & p : secondarySkills.Struct())
  1448. {
  1449. addSkill(p.first, p.second.String());
  1450. };
  1451. }
  1452. }
  1453. }
  1454. handler.serializeIdArray("spellBook", spells);
  1455. if(handler.saving)
  1456. CArtifactSet::serializeJsonArtifacts(handler, "artifacts");
  1457. }
  1458. void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1459. {
  1460. serializeCommonOptions(handler);
  1461. serializeJsonOwner(handler);
  1462. if(ID == Obj::HERO || ID == Obj::PRISON)
  1463. {
  1464. std::string typeName;
  1465. if(handler.saving)
  1466. typeName = getHeroTypeName();
  1467. handler.serializeString("type", typeName);
  1468. if(!handler.saving)
  1469. setHeroTypeName(typeName);
  1470. }
  1471. if(!handler.saving)
  1472. {
  1473. if(!appearance)
  1474. {
  1475. // crossoverDeserialize
  1476. appearance = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClassID())->getTemplates().front();
  1477. }
  1478. }
  1479. CArmedInstance::serializeJsonOptions(handler);
  1480. {
  1481. ui32 rawPatrolRadius = NO_PATROLLING;
  1482. if(handler.saving)
  1483. {
  1484. rawPatrolRadius = patrol.patrolling ? patrol.patrolRadius : NO_PATROLLING;
  1485. }
  1486. handler.serializeInt("patrolRadius", rawPatrolRadius, NO_PATROLLING);
  1487. if(!handler.saving)
  1488. {
  1489. patrol.patrolling = (rawPatrolRadius != NO_PATROLLING);
  1490. patrol.initialPos = visitablePos();
  1491. patrol.patrolRadius = patrol.patrolling ? rawPatrolRadius : 0;
  1492. }
  1493. }
  1494. }
  1495. void CGHeroInstance::serializeJsonDefinition(JsonSerializeFormat & handler)
  1496. {
  1497. serializeCommonOptions(handler);
  1498. }
  1499. bool CGHeroInstance::isMissionCritical() const
  1500. {
  1501. for(const TriggeredEvent & event : cb->getMapHeader()->triggeredEvents)
  1502. {
  1503. if (event.effect.type != EventEffect::DEFEAT)
  1504. continue;
  1505. auto const & testFunctor = [&](const EventCondition & condition)
  1506. {
  1507. if ((condition.condition == EventCondition::CONTROL) && condition.objectID != ObjectInstanceID::NONE)
  1508. return (id != condition.objectID);
  1509. if (condition.condition == EventCondition::HAVE_ARTIFACT)
  1510. {
  1511. if(hasArt(condition.objectType.as<ArtifactID>()))
  1512. return true;
  1513. }
  1514. if(condition.condition == EventCondition::IS_HUMAN)
  1515. return true;
  1516. return false;
  1517. };
  1518. if(event.trigger.test(testFunctor))
  1519. return true;
  1520. }
  1521. return false;
  1522. }
  1523. void CGHeroInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance & stack) const
  1524. {
  1525. TConstBonusListPtr lista = getBonusesOfType(BonusType::SPECIAL_UPGRADE, BonusSubtypeID(stack.getId()));
  1526. for(const auto & it : *lista)
  1527. {
  1528. auto nid = CreatureID(it->additionalInfo[0]);
  1529. if (nid != stack.getId()) //in very specific case the upgrade is available by default (?)
  1530. {
  1531. info.addUpgrade(nid, stack.getType());
  1532. }
  1533. }
  1534. }
  1535. bool CGHeroInstance::isCampaignYog() const
  1536. {
  1537. const StartInfo *si = cb->getStartInfo();
  1538. // it would be nice to find a way to move this hack to config/mapOverrides.json
  1539. if(!si || !si->campState)
  1540. return false;
  1541. std::string campaign = si->campState->getFilename();
  1542. if (!boost::starts_with(campaign, "DATA/YOG")) // "Birth of a Barbarian"
  1543. return false;
  1544. if (getHeroTypeID() != HeroTypeID::SOLMYR) // Yog (based on Solmyr)
  1545. return false;
  1546. return true;
  1547. }
  1548. bool CGHeroInstance::isCampaignGem() 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/GEM") && !boost::starts_with(campaign, "DATA/FINAL")) // "New Beginning" and "Unholy Alliance"
  1556. return false;
  1557. if (getHeroTypeID() != HeroTypeID::GEM) // Yog (based on Solmyr)
  1558. return false;
  1559. return true;
  1560. }
  1561. ResourceSet CGHeroInstance::dailyIncome() const
  1562. {
  1563. ResourceSet income;
  1564. for (GameResID k : GameResID::ALL_RESOURCES())
  1565. income[k] += valOfBonuses(BonusType::GENERATE_RESOURCE, BonusSubtypeID(k));
  1566. const auto & playerSettings = cb->getPlayerSettings(getOwner());
  1567. income.applyHandicap(playerSettings->handicap.percentIncome);
  1568. return income;
  1569. }
  1570. std::vector<CreatureID> CGHeroInstance::providedCreatures() const
  1571. {
  1572. return {};
  1573. }
  1574. const IOwnableObject * CGHeroInstance::asOwnable() const
  1575. {
  1576. return this;
  1577. }
  1578. int CGHeroInstance::getBasePrimarySkillValue(PrimarySkill which) const
  1579. {
  1580. std::string cachingStr = "CGHeroInstance::getBasePrimarySkillValue" + std::to_string(static_cast<int>(which));
  1581. auto selector = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(which)).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  1582. auto minSkillValue = LIBRARY->engineSettings()->getVectorValue(EGameSettings::HEROES_MINIMAL_PRIMARY_SKILLS, which.getNum());
  1583. return std::max(valOfBonuses(selector, cachingStr), minSkillValue);
  1584. }
  1585. VCMI_LIB_NAMESPACE_END