CGHeroInstance.cpp 45 KB

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