CGHeroInstance.cpp 42 KB

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