2
0

CGHeroInstance.cpp 46 KB

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