CGHeroInstance.cpp 50 KB

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