CGHeroInstance.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  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->terrainTypeHandler->getById(dest.terType->getId())->moveCost;
  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. gender(EHeroGender::DEFAULT),
  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 (gender == EHeroGender::DEFAULT)
  254. gender = type->gender;
  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 id.getNum();
  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. const CGHeroInstance * CGHeroInstance::getHeroCaster() const
  567. {
  568. return this;
  569. }
  570. void CGHeroInstance::spendMana(ServerCallback * server, const int spellCost) const
  571. {
  572. if(spellCost != 0)
  573. {
  574. SetMana sm;
  575. sm.absolute = false;
  576. sm.hid = id;
  577. sm.val = -spellCost;
  578. server->apply(&sm);
  579. }
  580. }
  581. bool CGHeroInstance::canCastThisSpell(const spells::Spell * spell) const
  582. {
  583. const bool isAllowed = IObjectInterface::cb->isAllowed(0, spell->getIndex());
  584. const bool inSpellBook = vstd::contains(spells, spell->getId()) && hasSpellbook();
  585. const bool specificBonus = hasBonusOfType(Bonus::SPELL, spell->getIndex());
  586. bool schoolBonus = false;
  587. spell->forEachSchool([this, &schoolBonus](const spells::SchoolInfo & cnf, bool & stop)
  588. {
  589. if(hasBonusOfType(cnf.knoledgeBonus))
  590. {
  591. schoolBonus = stop = true;
  592. }
  593. });
  594. const bool levelBonus = hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->getLevel());
  595. if(spell->isSpecial())
  596. {
  597. if(inSpellBook)
  598. {//hero has this spell in spellbook
  599. logGlobal->error("Special spell %s in spellbook.", spell->getNameTranslated());
  600. }
  601. return specificBonus;
  602. }
  603. else if(!isAllowed)
  604. {
  605. if(inSpellBook)
  606. {
  607. //hero has this spell in spellbook
  608. //it is normal if set in map editor, but trace it to possible debug of magic guild
  609. logGlobal->trace("Banned spell %s in spellbook.", spell->getNameTranslated());
  610. }
  611. return inSpellBook || specificBonus || schoolBonus || levelBonus;
  612. }
  613. else
  614. {
  615. return inSpellBook || schoolBonus || specificBonus || levelBonus;
  616. }
  617. }
  618. bool CGHeroInstance::canLearnSpell(const spells::Spell * spell) const
  619. {
  620. if(!hasSpellbook())
  621. return false;
  622. if(spell->getLevel() > maxSpellLevel()) //not enough wisdom
  623. return false;
  624. if(vstd::contains(spells, spell->getId()))//already known
  625. return false;
  626. if(spell->isSpecial())
  627. {
  628. logGlobal->warn("Hero %s try to learn special spell %s", nodeName(), spell->getNameTranslated());
  629. return false;//special spells can not be learned
  630. }
  631. if(spell->isCreatureAbility())
  632. {
  633. logGlobal->warn("Hero %s try to learn creature spell %s", nodeName(), spell->getNameTranslated());
  634. return false;//creature abilities can not be learned
  635. }
  636. if(!IObjectInterface::cb->isAllowed(0, spell->getIndex()))
  637. {
  638. logGlobal->warn("Hero %s try to learn banned spell %s", nodeName(), spell->getNameTranslated());
  639. return false;//banned spells should not be learned
  640. }
  641. return true;
  642. }
  643. /**
  644. * Calculates what creatures and how many to be raised from a battle.
  645. * @param battleResult The results of the battle.
  646. * @return Returns a pair with the first value indicating the ID of the creature
  647. * type and second value the amount. Both values are returned as -1 if necromancy
  648. * could not be applied.
  649. */
  650. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  651. {
  652. bool hasImprovedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  653. // need skill or cloak of undead king - lesser artifacts don't work without skill
  654. if (hasImprovedNecromancy)
  655. {
  656. double necromancySkill = valOfBonuses(Bonus::UNDEAD_RAISE_PERCENTAGE) / 100.0;
  657. const ui8 necromancyLevel = valOfBonuses(Bonus::IMPROVED_NECROMANCY);
  658. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  659. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  660. // figure out what to raise - pick strongest creature meeting requirements
  661. auto creatureTypeRaised = CreatureID::NONE; //now we always have IMPROVED_NECROMANCY, no need for hardcode
  662. int requiredCasualtyLevel = 1;
  663. TConstBonusListPtr improvedNecromancy = getBonuses(Selector::type()(Bonus::IMPROVED_NECROMANCY));
  664. if(!improvedNecromancy->empty())
  665. {
  666. auto getCreatureID = [](const std::shared_ptr<Bonus> & bonus) -> CreatureID
  667. {
  668. assert(bonus->subtype >=0);
  669. if(bonus->subtype >= 0)
  670. return CreatureID(bonus->subtype);
  671. return CreatureID::NONE;
  672. };
  673. int maxCasualtyLevel = 1;
  674. for(const auto & casualty : casualties)
  675. vstd::amax(maxCasualtyLevel, VLC->creatures()->getByIndex(casualty.first)->getLevel());
  676. // pick best bonus available
  677. std::shared_ptr<Bonus> topPick;
  678. for(const std::shared_ptr<Bonus> & newPick : *improvedNecromancy)
  679. {
  680. // addInfo[0] = required necromancy skill, addInfo[1] = required casualty level
  681. if(newPick->additionalInfo[0] > necromancyLevel || newPick->additionalInfo[1] > maxCasualtyLevel)
  682. continue;
  683. if(!topPick)
  684. {
  685. topPick = newPick;
  686. }
  687. else
  688. {
  689. auto quality = [getCreatureID](const std::shared_ptr<Bonus> & pick) -> std::tuple<int, int, int>
  690. {
  691. const auto * c = getCreatureID(pick).toCreature();
  692. return std::tuple<int, int, int> {c->getLevel(), static_cast<int>(c->getFullRecruitCost().marketValue()), -pick->additionalInfo[1]};
  693. };
  694. if(quality(topPick) < quality(newPick))
  695. topPick = newPick;
  696. }
  697. }
  698. if(topPick)
  699. {
  700. creatureTypeRaised = getCreatureID(topPick);
  701. requiredCasualtyLevel = std::max(topPick->additionalInfo[1], 1);
  702. }
  703. }
  704. assert(creatureTypeRaised != CreatureID::NONE);
  705. // raise upgraded creature (at 2/3 rate) if no space available otherwise
  706. if(getSlotFor(creatureTypeRaised) == SlotID())
  707. {
  708. for(const CreatureID & upgraded : VLC->creh->objects[creatureTypeRaised]->upgrades)
  709. {
  710. if(getSlotFor(upgraded) != SlotID())
  711. {
  712. creatureTypeRaised = upgraded;
  713. necromancySkill *= 2/3.0;
  714. break;
  715. }
  716. }
  717. }
  718. // calculate number of creatures raised - low level units contribute at 50% rate
  719. const double raisedUnitHealth = VLC->creh->objects[creatureTypeRaised]->MaxHealth();
  720. double raisedUnits = 0;
  721. for(const auto & casualty : casualties)
  722. {
  723. const CCreature * c = VLC->creh->objects[casualty.first];
  724. double raisedFromCasualty = std::min(c->MaxHealth() / raisedUnitHealth, 1.0) * casualty.second * necromancySkill;
  725. if(c->getLevel() < requiredCasualtyLevel)
  726. raisedFromCasualty *= 0.5;
  727. raisedUnits += raisedFromCasualty;
  728. }
  729. return CStackBasicDescriptor(creatureTypeRaised, std::max(static_cast<int>(raisedUnits), 1));
  730. }
  731. return CStackBasicDescriptor();
  732. }
  733. /**
  734. * Show the necromancy dialog with information about units raised.
  735. * @param raisedStack Pair where the first element represents ID of the raised creature
  736. * and the second element the amount.
  737. */
  738. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack, CRandomGenerator & rand) const
  739. {
  740. InfoWindow iw;
  741. iw.type = EInfoWindowMode::AUTO;
  742. iw.soundID = soundBase::pickup01 + rand.nextInt(6);
  743. iw.player = tempOwner;
  744. iw.components.emplace_back(raisedStack);
  745. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  746. {
  747. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  748. iw.text.addReplacement(raisedStack.count);
  749. }
  750. else // Practicing the dark arts of necromancy, ... (singular)
  751. {
  752. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  753. }
  754. iw.text.addReplacement(raisedStack);
  755. cb->showInfoDialog(&iw);
  756. }
  757. /*
  758. int3 CGHeroInstance::getSightCenter() const
  759. {
  760. return getPosition(false);
  761. }*/
  762. int CGHeroInstance::getSightRadius() const
  763. {
  764. return valOfBonuses(Bonus::SIGHT_RADIUS); // scouting gives SIGHT_RADIUS bonus
  765. }
  766. si32 CGHeroInstance::manaRegain() const
  767. {
  768. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  769. return manaLimit();
  770. return valOfBonuses(Bonus::MANA_REGENERATION);
  771. }
  772. si32 CGHeroInstance::getManaNewTurn() const
  773. {
  774. if(visitedTown && visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  775. {
  776. //if hero starts turn in town with mage guild - restore all mana
  777. return std::max(mana, manaLimit());
  778. }
  779. si32 res = mana + manaRegain();
  780. res = std::min(res, manaLimit());
  781. res = std::max(res, mana);
  782. res = std::max(res, 0);
  783. return res;
  784. }
  785. // /**
  786. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  787. // * or discards it if it cannot be equipped.
  788. // */
  789. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  790. // {
  791. // CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  792. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  793. // ai->putAt(this, ai->firstAvailableSlot(this));
  794. // }
  795. BoatId CGHeroInstance::getBoatType() const
  796. {
  797. switch(type->heroClass->getAlignment())
  798. {
  799. case EAlignment::EVIL : return EBoatId::BOAT_EVIL;
  800. case EAlignment::GOOD : return EBoatId::BOAT_GOOD;
  801. case EAlignment::NEUTRAL : return EBoatId::BOAT_NEUTRAL;
  802. default: return EBoatId::NONE;
  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. auto boatLayer = boat ? boat->layer : EPathfindingLayer::SAIL;
  949. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : boatLayer);
  950. int mp2 = ti->getMaxMovePoints(disembark ? boatLayer : EPathfindingLayer::LAND);
  951. int ret = static_cast<int>((MPsBefore - basicCost) * static_cast<double>(mp1) / mp2);
  952. return ret;
  953. }
  954. EDiggingStatus CGHeroInstance::diggingStatus() const
  955. {
  956. if(static_cast<int>(movement) < maxMovePoints(true))
  957. return EDiggingStatus::LACK_OF_MOVEMENT;
  958. if(!VLC->arth->objects[ArtifactID::GRAIL]->canBePutAt(this))
  959. return EDiggingStatus::BACKPACK_IS_FULL;
  960. return cb->getTileDigStatus(visitablePos());
  961. }
  962. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  963. {
  964. return ArtBearer::HERO;
  965. }
  966. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
  967. {
  968. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  969. auto getObligatorySkills = [](CSkill::Obligatory obl){
  970. std::vector<SecondarySkill> obligatory = {};
  971. for(int i = 0; i < VLC->skillh->size(); i++)
  972. if((*VLC->skillh)[SecondarySkill(i)]->obligatory(obl))
  973. {
  974. obligatory.emplace_back(i);
  975. break;
  976. }
  977. return obligatory;
  978. };
  979. auto selectObligatorySkill = [&](std::vector<SecondarySkill>& ss) -> void
  980. {
  981. std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());
  982. for(const auto & skill : ss)
  983. {
  984. if (canLearnSkill(skill)) //only skills hero doesn't know yet
  985. {
  986. obligatorySkills.push_back(skill);
  987. break; //only one
  988. }
  989. }
  990. };
  991. if (!skillsInfo.wisdomCounter)
  992. {
  993. auto obligatory = getObligatorySkills(CSkill::Obligatory::MAJOR);
  994. selectObligatorySkill(obligatory);
  995. }
  996. if (!skillsInfo.magicSchoolCounter)
  997. {
  998. auto obligatory = getObligatorySkills(CSkill::Obligatory::MINOR);
  999. selectObligatorySkill(obligatory);
  1000. }
  1001. std::vector<SecondarySkill> skills;
  1002. //picking sec. skills for choice
  1003. std::set<SecondarySkill> basicAndAdv;
  1004. std::set<SecondarySkill> expert;
  1005. std::set<SecondarySkill> none;
  1006. for(int i = 0; i < VLC->skillh->size(); i++)
  1007. if (canLearnSkill(SecondarySkill(i)))
  1008. none.insert(SecondarySkill(i));
  1009. for(const auto & elem : secSkills)
  1010. {
  1011. if(elem.second < SecSkillLevel::EXPERT)
  1012. basicAndAdv.insert(elem.first);
  1013. else
  1014. expert.insert(elem.first);
  1015. none.erase(elem.first);
  1016. }
  1017. for(const auto & s : obligatorySkills) //don't duplicate them
  1018. {
  1019. none.erase (s);
  1020. basicAndAdv.erase (s);
  1021. expert.erase (s);
  1022. }
  1023. //first offered skill:
  1024. // 1) give obligatory skill
  1025. // 2) give any other new skill
  1026. // 3) upgrade existing
  1027. if(canLearnSkill() && !obligatorySkills.empty())
  1028. {
  1029. skills.push_back (obligatorySkills[0]);
  1030. }
  1031. else if(!none.empty() && canLearnSkill()) //hero have free skill slot
  1032. {
  1033. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
  1034. none.erase(skills.back());
  1035. }
  1036. else if(!basicAndAdv.empty())
  1037. {
  1038. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
  1039. basicAndAdv.erase(skills.back());
  1040. }
  1041. //second offered skill:
  1042. //1) upgrade existing
  1043. //2) give obligatory skill
  1044. //3) give any other new skill
  1045. if(!basicAndAdv.empty())
  1046. {
  1047. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
  1048. skills.push_back(s);
  1049. basicAndAdv.erase(s);
  1050. }
  1051. else if (canLearnSkill() && obligatorySkills.size() > 1)
  1052. {
  1053. skills.push_back (obligatorySkills[1]);
  1054. }
  1055. else if(!none.empty() && canLearnSkill())
  1056. {
  1057. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
  1058. none.erase(skills.back());
  1059. }
  1060. if (skills.size() == 2) // Fix for #1868 to avoid changing logic (possibly causing bugs in process)
  1061. std::swap(skills[0], skills[1]);
  1062. return skills;
  1063. }
  1064. PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill(CRandomGenerator & rand) const
  1065. {
  1066. assert(gainsLevel());
  1067. int randomValue = rand.nextInt(99);
  1068. int pom = 0;
  1069. int primarySkill = 0;
  1070. const auto isLowLevelHero = level < GameConstants::HERO_HIGH_LEVEL;
  1071. const auto & skillChances = isLowLevelHero ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;
  1072. for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
  1073. {
  1074. pom += skillChances[primarySkill];
  1075. if(randomValue < pom)
  1076. {
  1077. break;
  1078. }
  1079. }
  1080. if(primarySkill >= GameConstants::PRIMARY_SKILLS)
  1081. {
  1082. primarySkill = rand.nextInt(GameConstants::PRIMARY_SKILLS - 1);
  1083. logGlobal->error("Wrong values in primarySkill%sLevel for hero class %s", isLowLevelHero ? "Low" : "High", type->heroClass->getNameTranslated());
  1084. randomValue = 100 / GameConstants::PRIMARY_SKILLS;
  1085. }
  1086. logGlobal->trace("The hero gets the primary skill %d with a probability of %d %%.", primarySkill, randomValue);
  1087. return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
  1088. }
  1089. std::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(CRandomGenerator & rand) const
  1090. {
  1091. assert(gainsLevel());
  1092. std::optional<SecondarySkill> chosenSecondarySkill;
  1093. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1094. if(!proposedSecondarySkills.empty())
  1095. {
  1096. std::vector<SecondarySkill> learnedSecondarySkills;
  1097. for(const auto & secondarySkill : proposedSecondarySkills)
  1098. {
  1099. if(getSecSkillLevel(secondarySkill) > 0)
  1100. {
  1101. learnedSecondarySkills.push_back(secondarySkill);
  1102. }
  1103. }
  1104. if(learnedSecondarySkills.empty())
  1105. {
  1106. // there are only new skills to learn, so choose anyone of them
  1107. chosenSecondarySkill = std::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand));
  1108. }
  1109. else
  1110. {
  1111. // preferably upgrade a already learned secondary skill
  1112. chosenSecondarySkill = std::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand));
  1113. }
  1114. }
  1115. return chosenSecondarySkill;
  1116. }
  1117. void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
  1118. {
  1119. if(primarySkill < PrimarySkill::EXPERIENCE)
  1120. {
  1121. auto skill = getBonusLocalFirst(Selector::type()(Bonus::PRIMARY_SKILL)
  1122. .And(Selector::subtype()(primarySkill))
  1123. .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)));
  1124. assert(skill);
  1125. if(abs)
  1126. {
  1127. skill->val = static_cast<si32>(value);
  1128. }
  1129. else
  1130. {
  1131. skill->val += static_cast<si32>(value);
  1132. }
  1133. CBonusSystemNode::treeHasChanged();
  1134. }
  1135. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1136. {
  1137. if(abs)
  1138. {
  1139. exp = value;
  1140. }
  1141. else
  1142. {
  1143. exp += value;
  1144. }
  1145. }
  1146. }
  1147. bool CGHeroInstance::gainsLevel() const
  1148. {
  1149. return exp >= static_cast<TExpType>(VLC->heroh->reqExp(level+1));
  1150. }
  1151. void CGHeroInstance::levelUp(const std::vector<SecondarySkill> & skills)
  1152. {
  1153. ++level;
  1154. //deterministic secondary skills
  1155. skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
  1156. skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
  1157. for(const auto & skill : skills)
  1158. {
  1159. if((*VLC->skillh)[skill]->obligatory(CSkill::Obligatory::MAJOR))
  1160. skillsInfo.resetWisdomCounter();
  1161. if((*VLC->skillh)[skill]->obligatory(CSkill::Obligatory::MINOR))
  1162. skillsInfo.resetMagicSchoolCounter();
  1163. }
  1164. //update specialty and other bonuses that scale with level
  1165. treeHasChanged();
  1166. }
  1167. void CGHeroInstance::levelUpAutomatically(CRandomGenerator & rand)
  1168. {
  1169. while(gainsLevel())
  1170. {
  1171. const auto primarySkill = nextPrimarySkill(rand);
  1172. setPrimarySkill(primarySkill, 1, false);
  1173. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1174. const auto secondarySkill = nextSecondarySkill(rand);
  1175. if(secondarySkill)
  1176. {
  1177. setSecSkillLevel(*secondarySkill, 1, false);
  1178. }
  1179. //TODO why has the secondary skills to be passed to the method?
  1180. levelUp(proposedSecondarySkills);
  1181. }
  1182. }
  1183. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, const int subtype) const
  1184. {
  1185. //VISIONS spell support
  1186. const std::string cached = boost::to_string((boost::format("type_%d__subtype_%d") % Bonus::VISIONS % subtype));
  1187. const int visionsMultiplier = valOfBonuses(Selector::typeSubtype(Bonus::VISIONS,subtype), cached);
  1188. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1189. if (visionsMultiplier > 0)
  1190. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1191. const int distance = static_cast<int>(target->pos.dist2d(visitablePos()));
  1192. //logGlobal->debug(boost::to_string(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1193. return (distance < visionsRange) && (target->pos.z == pos.z);
  1194. }
  1195. std::string CGHeroInstance::getHeroTypeName() const
  1196. {
  1197. if(ID == Obj::HERO || ID == Obj::PRISON)
  1198. {
  1199. if(type)
  1200. {
  1201. return type->getJsonKey();
  1202. }
  1203. else
  1204. {
  1205. return VLC->heroh->objects[subID]->getJsonKey();
  1206. }
  1207. }
  1208. return "";
  1209. }
  1210. void CGHeroInstance::afterAddToMap(CMap * map)
  1211. {
  1212. if(ID == Obj::HERO)
  1213. map->heroesOnMap.emplace_back(this);
  1214. }
  1215. void CGHeroInstance::afterRemoveFromMap(CMap* map)
  1216. {
  1217. if (ID == Obj::HERO)
  1218. vstd::erase_if_present(map->heroesOnMap, this);
  1219. }
  1220. void CGHeroInstance::setHeroTypeName(const std::string & identifier)
  1221. {
  1222. if(ID == Obj::HERO || ID == Obj::PRISON)
  1223. {
  1224. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "hero", identifier);
  1225. if(rawId)
  1226. subID = rawId.value();
  1227. else
  1228. {
  1229. throw std::runtime_error("Couldn't resolve hero identifier " + identifier);
  1230. }
  1231. }
  1232. }
  1233. void CGHeroInstance::updateFrom(const JsonNode & data)
  1234. {
  1235. CGObjectInstance::updateFrom(data);
  1236. }
  1237. void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
  1238. {
  1239. handler.serializeString("biography", biographyCustom);
  1240. handler.serializeInt("experience", exp, 0);
  1241. if(!handler.saving && exp != UNINITIALIZED_EXPERIENCE) //do not gain levels if experience is not initialized
  1242. {
  1243. while (gainsLevel())
  1244. {
  1245. ++level;
  1246. }
  1247. }
  1248. handler.serializeString("name", nameCustom);
  1249. handler.serializeInt("gender", gender, 0);
  1250. {
  1251. const int legacyHeroes = VLC->settings()->getInteger(EGameSettings::TEXTS_HERO);
  1252. const int moddedStart = legacyHeroes + GameConstants::HERO_PORTRAIT_SHIFT;
  1253. if(handler.saving)
  1254. {
  1255. if(portrait >= 0)
  1256. {
  1257. if(portrait < legacyHeroes || portrait >= moddedStart)
  1258. {
  1259. int tempPortrait = portrait - GameConstants::HERO_PORTRAIT_SHIFT;
  1260. handler.serializeId<si32, si32, HeroTypeID>("portrait", tempPortrait, -1);
  1261. }
  1262. else
  1263. handler.serializeInt("portrait", portrait, -1);
  1264. }
  1265. }
  1266. else
  1267. {
  1268. const JsonNode & portraitNode = handler.getCurrent()["portrait"];
  1269. if(portraitNode.getType() == JsonNode::JsonType::DATA_STRING)
  1270. {
  1271. handler.serializeId<si32, si32, HeroTypeID>("portrait", portrait, -1);
  1272. portrait += GameConstants::HERO_PORTRAIT_SHIFT;
  1273. }
  1274. else
  1275. handler.serializeInt("portrait", portrait, -1);
  1276. }
  1277. }
  1278. //primary skills
  1279. if(handler.saving)
  1280. {
  1281. const bool haveSkills = hasBonus(Selector::type()(Bonus::PRIMARY_SKILL).And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)));
  1282. if(haveSkills)
  1283. {
  1284. auto primarySkills = handler.enterStruct("primarySkills");
  1285. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1286. {
  1287. int value = valOfBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, i).And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)));
  1288. handler.serializeInt(PrimarySkill::names[i], value, 0);
  1289. }
  1290. }
  1291. }
  1292. else
  1293. {
  1294. auto primarySkills = handler.enterStruct("primarySkills");
  1295. if(handler.getCurrent().getType() == JsonNode::JsonType::DATA_STRUCT)
  1296. {
  1297. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1298. {
  1299. int value = 0;
  1300. handler.serializeInt(PrimarySkill::names[i], value, 0);
  1301. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(i), value);
  1302. }
  1303. }
  1304. }
  1305. //secondary skills
  1306. if(handler.saving)
  1307. {
  1308. //does hero have default skills?
  1309. bool defaultSkills = false;
  1310. bool normalSkills = false;
  1311. for(const auto & p : secSkills)
  1312. {
  1313. if(p.first == SecondarySkill(SecondarySkill::DEFAULT))
  1314. defaultSkills = true;
  1315. else
  1316. normalSkills = true;
  1317. }
  1318. if(defaultSkills && normalSkills)
  1319. logGlobal->error("Mixed default and normal secondary skills");
  1320. //in json default skills means no field/null
  1321. if(!defaultSkills)
  1322. {
  1323. //enter structure here as handler initialize it
  1324. auto secondarySkills = handler.enterStruct("secondarySkills");
  1325. for(auto & p : secSkills)
  1326. {
  1327. const si32 rawId = p.first.num;
  1328. if(rawId < 0 || rawId >= VLC->skillh->size())
  1329. logGlobal->error("Invalid secondary skill %d", rawId);
  1330. handler.serializeEnum((*VLC->skillh)[SecondarySkill(rawId)]->getJsonKey(), p.second, 0, NSecondarySkill::levels);
  1331. }
  1332. }
  1333. }
  1334. else
  1335. {
  1336. auto secondarySkills = handler.enterStruct("secondarySkills");
  1337. const JsonNode & skillMap = handler.getCurrent();
  1338. secSkills.clear();
  1339. if(skillMap.getType() == JsonNode::JsonType::DATA_NULL)
  1340. {
  1341. secSkills.emplace_back(SecondarySkill::DEFAULT, -1);
  1342. }
  1343. else
  1344. {
  1345. for(const auto & p : skillMap.Struct())
  1346. {
  1347. const std::string skillId = p.first;
  1348. const std::string levelId = p.second.String();
  1349. const int rawId = CSkillHandler::decodeSkill(skillId);
  1350. if(rawId < 0)
  1351. {
  1352. logGlobal->error("Invalid secondary skill %s", skillId);
  1353. continue;
  1354. }
  1355. const int level = vstd::find_pos(NSecondarySkill::levels, levelId);
  1356. if(level < 0)
  1357. {
  1358. logGlobal->error("Invalid secondary skill level%s", levelId);
  1359. continue;
  1360. }
  1361. secSkills.emplace_back(SecondarySkill(rawId), level);
  1362. }
  1363. }
  1364. }
  1365. handler.serializeIdArray("spellBook", spells);
  1366. if(handler.saving)
  1367. CArtifactSet::serializeJsonArtifacts(handler, "artifacts", nullptr);
  1368. }
  1369. void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1370. {
  1371. serializeCommonOptions(handler);
  1372. serializeJsonOwner(handler);
  1373. if(ID == Obj::HERO || ID == Obj::PRISON)
  1374. {
  1375. std::string typeName;
  1376. if(handler.saving)
  1377. typeName = getHeroTypeName();
  1378. handler.serializeString("type", typeName);
  1379. if(!handler.saving)
  1380. setHeroTypeName(typeName);
  1381. }
  1382. static const std::vector<std::string> FORMATIONS = { "wide", "tight" };
  1383. CCreatureSet::serializeJson(handler, "army", 7);
  1384. handler.serializeEnum("formation", formation, FORMATIONS);
  1385. {
  1386. static constexpr int NO_PATROLING = -1;
  1387. int rawPatrolRadius = NO_PATROLING;
  1388. if(handler.saving)
  1389. {
  1390. rawPatrolRadius = patrol.patrolling ? patrol.patrolRadius : NO_PATROLING;
  1391. }
  1392. handler.serializeInt("patrolRadius", rawPatrolRadius, NO_PATROLING);
  1393. if(!handler.saving)
  1394. {
  1395. if(!appearance)
  1396. {
  1397. // crossoverDeserialize
  1398. type = VLC->heroh->objects[subID];
  1399. appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, type->heroClass->getIndex())->getTemplates().front();
  1400. }
  1401. patrol.patrolling = (rawPatrolRadius > NO_PATROLING);
  1402. patrol.initialPos = visitablePos();
  1403. patrol.patrolRadius = (rawPatrolRadius > NO_PATROLING) ? rawPatrolRadius : 0;
  1404. }
  1405. }
  1406. }
  1407. void CGHeroInstance::serializeJsonDefinition(JsonSerializeFormat & handler)
  1408. {
  1409. serializeCommonOptions(handler);
  1410. }
  1411. bool CGHeroInstance::isMissionCritical() const
  1412. {
  1413. for(const TriggeredEvent & event : IObjectInterface::cb->getMapHeader()->triggeredEvents)
  1414. {
  1415. if(event.trigger.test([&](const EventCondition & condition)
  1416. {
  1417. if ((condition.condition == EventCondition::CONTROL || condition.condition == EventCondition::HAVE_0) && condition.object)
  1418. {
  1419. const auto * hero = dynamic_cast<const CGHeroInstance *>(condition.object);
  1420. return (hero != this);
  1421. }
  1422. else if(condition.condition == EventCondition::IS_HUMAN)
  1423. {
  1424. return true;
  1425. }
  1426. return false;
  1427. }))
  1428. {
  1429. return true;
  1430. }
  1431. }
  1432. return false;
  1433. }
  1434. VCMI_LIB_NAMESPACE_END