2
0

CGHeroInstance.cpp 50 KB

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