CGHeroInstance.cpp 52 KB

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