CGHeroInstance.cpp 48 KB

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