CGHeroInstance.cpp 45 KB

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