CGHeroInstance.cpp 49 KB

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