CGHeroInstance.cpp 49 KB

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