CGHeroInstance.cpp 52 KB

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