CGHeroInstance.cpp 50 KB

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