CGHeroInstance.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  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 "../CSoundBase.h"
  16. #include "../CSpellHandler.h"
  17. #include "CObjectClassesHandler.h"
  18. using namespace boost::assign;
  19. ///helpers
  20. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID)
  21. {
  22. InfoWindow iw;
  23. iw.soundID = soundID;
  24. iw.player = playerID;
  25. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  26. IObjectInterface::cb->sendAndApply(&iw);
  27. }
  28. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID)
  29. {
  30. const PlayerColor playerID = h->getOwner();
  31. showInfoDialog(playerID,txtID,soundID);
  32. }
  33. static int lowestSpeed(const CGHeroInstance * chi)
  34. {
  35. if(!chi->Slots().size())
  36. {
  37. logGlobal->errorStream() << "Error! Hero " << chi->id.getNum() << " ("<<chi->name<<") has no army!";
  38. return 20;
  39. }
  40. auto i = chi->Slots().begin();
  41. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  42. int ret = (i++)->second->valOfBonuses(Bonus::STACKS_SPEED);
  43. for (;i!=chi->Slots().end();i++)
  44. {
  45. ret = std::min(ret, i->second->valOfBonuses(Bonus::STACKS_SPEED));
  46. }
  47. return ret;
  48. }
  49. ui32 CGHeroInstance::getTileCost(const TerrainTile &dest, const TerrainTile &from) const
  50. {
  51. //base move cost
  52. unsigned ret = 100;
  53. //if there is road both on dest and src tiles - use road movement cost
  54. if(dest.roadType != ERoadType::NO_ROAD && from.roadType != ERoadType::NO_ROAD)
  55. {
  56. int road = std::min(dest.roadType,from.roadType); //used road ID
  57. switch(road)
  58. {
  59. case ERoadType::DIRT_ROAD:
  60. ret = 75;
  61. break;
  62. case ERoadType::GRAVEL_ROAD:
  63. ret = 65;
  64. break;
  65. case ERoadType::COBBLESTONE_ROAD:
  66. ret = 50;
  67. break;
  68. default:
  69. logGlobal->errorStream() << "Unknown road type: " << road << "... Something wrong!";
  70. break;
  71. }
  72. }
  73. else
  74. {
  75. //FIXME: in H3 presence of Nomad in army will remove terrain penalty for sand. Bonus not implemented in VCMI
  76. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  77. // This is clearly bug in H3 however intended behaviour is not clear.
  78. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  79. // will always have best penalty without any influence from player-defined stacks order
  80. bool nativeArmy = true;
  81. for(auto stack : stacks)
  82. {
  83. int nativeTerrain = VLC->townh->factions[stack.second->type->faction]->nativeTerrain;
  84. if (nativeTerrain != -1 && nativeTerrain != from.terType)
  85. {
  86. nativeArmy = false;
  87. break;
  88. }
  89. }
  90. if (!nativeArmy)
  91. ret = VLC->heroh->terrCosts[from.terType];
  92. }
  93. return ret;
  94. }
  95. int3 CGHeroInstance::convertPosition(int3 src, bool toh3m) //toh3m=true: manifest->h3m; toh3m=false: h3m->manifest
  96. {
  97. if (toh3m)
  98. {
  99. src.x+=1;
  100. return src;
  101. }
  102. else
  103. {
  104. src.x-=1;
  105. return src;
  106. }
  107. }
  108. int3 CGHeroInstance::getPosition(bool h3m) const //h3m=true - returns position of hero object; h3m=false - returns position of hero 'manifestation'
  109. {
  110. if (h3m)
  111. {
  112. return pos;
  113. }
  114. else
  115. {
  116. return convertPosition(pos,false);
  117. }
  118. }
  119. bool CGHeroInstance::canWalkOnSea() const
  120. {
  121. return hasBonusOfType(Bonus::FLYING_MOVEMENT) || hasBonusOfType(Bonus::WATER_WALKING);
  122. }
  123. ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
  124. {
  125. for(auto & elem : secSkills)
  126. if(elem.first == skill)
  127. return elem.second;
  128. return 0;
  129. }
  130. void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
  131. {
  132. if(getSecSkillLevel(which) == 0)
  133. {
  134. secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
  135. updateSkill(which, val);
  136. }
  137. else
  138. {
  139. for (auto & elem : secSkills)
  140. {
  141. if(elem.first == which)
  142. {
  143. if(abs)
  144. elem.second = val;
  145. else
  146. elem.second += val;
  147. if(elem.second > 3) //workaround to avoid crashes when same sec skill is given more than once
  148. {
  149. logGlobal->warnStream() << "Warning: Skill " << which << " increased over limit! Decreasing to Expert.";
  150. elem.second = 3;
  151. }
  152. updateSkill(which, elem.second); //when we know final value
  153. }
  154. }
  155. }
  156. }
  157. bool CGHeroInstance::canLearnSkill() const
  158. {
  159. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  160. }
  161. int CGHeroInstance::maxMovePoints(bool onLand) const
  162. {
  163. int base;
  164. if(onLand)
  165. {
  166. // used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
  167. static const int baseSpeed = 1300; // base speed from creature with 0 speed
  168. int armySpeed = lowestSpeed(this) * 20 / 3;
  169. base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
  170. vstd::abetween(base, 1500, 2000); // base speed is limited by these values
  171. }
  172. else
  173. {
  174. base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
  175. }
  176. const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
  177. const int bonus = valOfBonuses(Bonus::MOVEMENT) + valOfBonuses(bt);
  178. const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
  179. const double modifier = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;
  180. return int(base* (1+modifier)) + bonus;
  181. }
  182. CGHeroInstance::CGHeroInstance()
  183. : IBoatGenerator(this)
  184. {
  185. setNodeType(HERO);
  186. ID = Obj::HERO;
  187. tacticFormationEnabled = inTownGarrison = false;
  188. mana = movement = portrait = level = -1;
  189. isStanding = true;
  190. moveDir = 4;
  191. exp = 0xffffffff;
  192. visitedTown = nullptr;
  193. type = nullptr;
  194. boat = nullptr;
  195. commander = nullptr;
  196. sex = 0xff;
  197. secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
  198. }
  199. void CGHeroInstance::initHero(HeroTypeID SUBID)
  200. {
  201. subID = SUBID.getNum();
  202. initHero();
  203. }
  204. void CGHeroInstance::setType(si32 ID, si32 subID)
  205. {
  206. assert(ID == Obj::HERO); // just in case
  207. type = VLC->heroh->heroes[subID];
  208. portrait = type->imageIndex;
  209. CGObjectInstance::setType(ID, type->heroClass->id);
  210. randomizeArmy(type->heroClass->faction);
  211. }
  212. void CGHeroInstance::initHero()
  213. {
  214. assert(validTypes(true));
  215. if(!type)
  216. type = VLC->heroh->heroes[subID];
  217. if (ID == Obj::HERO)
  218. appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, type->heroClass->id)->getTemplates().front();
  219. if(!vstd::contains(spells, SpellID::PRESET)) //hero starts with a spell
  220. {
  221. for(auto spellID : type->spells)
  222. spells.insert(spellID);
  223. }
  224. else //remove placeholder
  225. spells -= SpellID::PRESET;
  226. if(!getArt(ArtifactPosition::MACH4) && !getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook) //no catapult means we haven't read pre-existent set -> use default rules for spellbook
  227. putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  228. if(!getArt(ArtifactPosition::MACH4))
  229. putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createNewArtifactInstance(3)); //everyone has a catapult
  230. if(portrait < 0 || portrait == 255)
  231. portrait = type->imageIndex;
  232. if(!hasBonus(Selector::sourceType(Bonus::HERO_BASE_SKILL)))
  233. {
  234. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  235. {
  236. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(g), type->heroClass->primarySkillInitial[g]);
  237. }
  238. }
  239. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1)) //set secondary skills to default
  240. secSkills = type->secSkillsInit;
  241. if (!name.length())
  242. name = type->name;
  243. if (sex == 0xFF)//sex is default
  244. sex = type->sex;
  245. setFormation(false);
  246. if (!stacksCount()) //standard army//initial army
  247. {
  248. initArmy();
  249. }
  250. assert(validTypes());
  251. level = 1;
  252. if(exp == 0xffffffff)
  253. {
  254. initExp();
  255. }
  256. else
  257. {
  258. levelUpAutomatically();
  259. }
  260. if (VLC->modh->modules.COMMANDERS && !commander)
  261. {
  262. commander = new CCommanderInstance(type->heroClass->commander->idNumber);
  263. commander->setArmyObj (castToArmyObj()); //TODO: separate function for setting commanders
  264. commander->giveStackExp (exp); //after our exp is set
  265. }
  266. if (mana < 0)
  267. mana = manaLimit();
  268. }
  269. void CGHeroInstance::initArmy(IArmyDescriptor *dst /*= nullptr*/)
  270. {
  271. if(!dst)
  272. dst = this;
  273. int howManyStacks = 0; //how many stacks will hero receives <1 - 3>
  274. int pom = cb->gameState()->getRandomGenerator().nextInt(99);
  275. int warMachinesGiven = 0;
  276. if(pom < 9)
  277. howManyStacks = 1;
  278. else if(pom < 79)
  279. howManyStacks = 2;
  280. else
  281. howManyStacks = 3;
  282. vstd::amin(howManyStacks, type->initialArmy.size());
  283. for(int stackNo=0; stackNo < howManyStacks; stackNo++)
  284. {
  285. auto & stack = type->initialArmy[stackNo];
  286. int count = cb->gameState()->getRandomGenerator().nextInt(stack.minAmount, stack.maxAmount);
  287. if(stack.creature >= CreatureID::CATAPULT &&
  288. stack.creature <= CreatureID::ARROW_TOWERS) //war machine
  289. {
  290. warMachinesGiven++;
  291. if(dst != this)
  292. continue;
  293. int slot = -1;
  294. ArtifactID aid = ArtifactID::NONE;
  295. switch (stack.creature)
  296. {
  297. case CreatureID::CATAPULT:
  298. slot = ArtifactPosition::MACH4;
  299. aid = ArtifactID::CATAPULT;
  300. break;
  301. default:
  302. aid = CArtHandler::creatureToMachineID(stack.creature);
  303. slot = 9 + aid;
  304. break;
  305. }
  306. auto convSlot = ArtifactPosition(slot);
  307. if(!getArt(convSlot))
  308. putArtifact(convSlot, CArtifactInstance::createNewArtifactInstance(aid));
  309. else
  310. logGlobal->warnStream() << "Hero " << name << " already has artifact at " << slot << ", omitting giving " << aid;
  311. }
  312. else
  313. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  314. }
  315. }
  316. CGHeroInstance::~CGHeroInstance()
  317. {
  318. commander.dellNull();
  319. }
  320. bool CGHeroInstance::needsLastStack() const
  321. {
  322. return true;
  323. }
  324. void CGHeroInstance::onHeroVisit(const CGHeroInstance * h) const
  325. {
  326. if(h == this) return; //exclude potential self-visiting
  327. if (ID == Obj::HERO)
  328. {
  329. if( cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner)) //our or ally hero
  330. {
  331. //exchange
  332. cb->heroExchange(h->id, id);
  333. }
  334. else //battle
  335. {
  336. if(visitedTown) //we're in town
  337. visitedTown->onHeroVisit(h); //town will handle attacking
  338. else
  339. cb->startBattleI(h, this);
  340. }
  341. }
  342. else if(ID == Obj::PRISON)
  343. {
  344. int txt_id;
  345. if (cb->getHeroCount(h->tempOwner, false) < VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)//GameConstants::MAX_HEROES_PER_PLAYER) //free hero slot
  346. {
  347. cb->changeObjPos(id,pos+int3(1,0,0),0);
  348. //update hero parameters
  349. SetMovePoints smp;
  350. smp.hid = id;
  351. smp.val = maxMovePoints (true); //TODO: hota prison on water?
  352. cb->setMovePoints (&smp);
  353. cb->setManaPoints (id, manaLimit());
  354. cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
  355. cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player
  356. txt_id = 102;
  357. }
  358. else //already 8 wandering heroes
  359. {
  360. txt_id = 103;
  361. }
  362. showInfoDialog(h,txt_id,soundBase::ROGUE);
  363. }
  364. }
  365. const std::string & CGHeroInstance::getHoverText() const
  366. {
  367. if(ID != Obj::PRISON)
  368. {
  369. hoverName = VLC->generaltexth->allTexts[15];
  370. boost::algorithm::replace_first(hoverName,"%s",name);
  371. boost::algorithm::replace_first(hoverName,"%s", type->heroClass->name);
  372. return hoverName;
  373. }
  374. else
  375. hoverName = VLC->objtypeh->getObjectName(ID);
  376. return hoverName;
  377. }
  378. const std::string & CGHeroInstance::getBiography() const
  379. {
  380. if (biography.length())
  381. return biography;
  382. return type->biography;
  383. }
  384. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  385. {
  386. return type->heroClass->isMagicHero() ? 3 : 4;
  387. }
  388. ui8 CGHeroInstance::maxlevelsToWisdom() const
  389. {
  390. return type->heroClass->isMagicHero() ? 3 : 6;
  391. }
  392. void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
  393. {
  394. magicSchoolCounter = 1;
  395. }
  396. void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
  397. {
  398. wisdomCounter = 1;
  399. }
  400. void CGHeroInstance::initObj()
  401. {
  402. blockVisit = true;
  403. auto hs = new HeroSpecial();
  404. hs->setNodeType(CBonusSystemNode::SPECIALTY);
  405. attachTo(hs); //do we ever need to detach it?
  406. if(!type)
  407. initHero(); //TODO: set up everything for prison before specialties are configured
  408. skillsInfo.rand.setSeed(cb->gameState()->getRandomGenerator().nextInt());
  409. skillsInfo.resetMagicSchoolCounter();
  410. skillsInfo.resetWisdomCounter();
  411. auto customApp = VLC->objtypeh->getHandlerFor(ID, type->heroClass->id)->getOverride(cb->gameState()->getTile(visitablePos())->terType, this);
  412. if (customApp)
  413. appearance = customApp.get();
  414. for(const auto &spec : type->spec) //TODO: unfity with bonus system
  415. {
  416. auto bonus = new Bonus();
  417. bonus->val = spec.val;
  418. bonus->sid = id.getNum(); //from the hero, specialty has no unique id
  419. bonus->duration = Bonus::PERMANENT;
  420. bonus->source = Bonus::HERO_SPECIAL;
  421. switch (spec.type)
  422. {
  423. case 1:// creature specialty
  424. {
  425. hs->growsWithLevel = true;
  426. const CCreature &specCreature = *VLC->creh->creatures[spec.additionalinfo]; //creature in which we have specialty
  427. //int creLevel = specCreature.level;
  428. //if(!creLevel)
  429. //{
  430. // if(spec.additionalinfo == 146)
  431. // creLevel = 5; //treat ballista as 5-level
  432. // else
  433. // {
  434. // logGlobal->warnStream() << "Warning: unknown level of " << specCreature.namePl;
  435. // continue;
  436. // }
  437. //}
  438. //bonus->additionalInfo = spec.additionalinfo; //creature id, should not be used again - this works only with limiter
  439. bonus->limiter.reset(new CCreatureTypeLimiter (specCreature, true)); //with upgrades
  440. bonus->type = Bonus::PRIMARY_SKILL;
  441. bonus->valType = Bonus::ADDITIVE_VALUE;
  442. bonus->subtype = PrimarySkill::ATTACK;
  443. hs->addNewBonus(bonus);
  444. bonus = new Bonus(*bonus);
  445. bonus->subtype = PrimarySkill::DEFENSE;
  446. hs->addNewBonus(bonus);
  447. //values will be calculated later
  448. bonus = new Bonus(*bonus);
  449. bonus->type = Bonus::STACKS_SPEED;
  450. bonus->val = 1; //+1 speed
  451. hs->addNewBonus(bonus);
  452. }
  453. break;
  454. case 2://secondary skill
  455. hs->growsWithLevel = true;
  456. bonus->type = Bonus::SPECIAL_SECONDARY_SKILL; //needs to be recalculated with level, based on this value
  457. bonus->valType = Bonus::BASE_NUMBER; // to receive nonzero value
  458. bonus->subtype = spec.subtype; //skill id
  459. bonus->val = spec.val; //value per level, in percent
  460. hs->addNewBonus(bonus);
  461. bonus = new Bonus(*bonus);
  462. switch (spec.additionalinfo)
  463. {
  464. case 0: //normal
  465. bonus->valType = Bonus::PERCENT_TO_BASE;
  466. break;
  467. case 1: //when it's navigation or there's no 'base' at all
  468. bonus->valType = Bonus::PERCENT_TO_ALL;
  469. break;
  470. }
  471. bonus->type = Bonus::SECONDARY_SKILL_PREMY; //value will be calculated later
  472. hs->addNewBonus(bonus);
  473. break;
  474. case 3://spell damage bonus, level dependent but calculated elsewhere
  475. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  476. bonus->subtype = spec.subtype;
  477. hs->addNewBonus(bonus);
  478. break;
  479. case 4://creature stat boost
  480. switch (spec.subtype)
  481. {
  482. case 1://attack
  483. bonus->type = Bonus::PRIMARY_SKILL;
  484. bonus->subtype = PrimarySkill::ATTACK;
  485. break;
  486. case 2://defense
  487. bonus->type = Bonus::PRIMARY_SKILL;
  488. bonus->subtype = PrimarySkill::DEFENSE;
  489. break;
  490. case 3:
  491. bonus->type = Bonus::CREATURE_DAMAGE;
  492. bonus->subtype = 0; //both min and max
  493. break;
  494. case 4://hp
  495. bonus->type = Bonus::STACK_HEALTH;
  496. break;
  497. case 5:
  498. bonus->type = Bonus::STACKS_SPEED;
  499. break;
  500. default:
  501. continue;
  502. }
  503. bonus->additionalInfo = spec.additionalinfo; //creature id
  504. bonus->valType = Bonus::ADDITIVE_VALUE;
  505. bonus->limiter.reset(new CCreatureTypeLimiter (*VLC->creh->creatures[spec.additionalinfo], true));
  506. hs->addNewBonus(bonus);
  507. break;
  508. case 5://spell damage bonus in percent
  509. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  510. bonus->valType = Bonus::BASE_NUMBER; // current spell system is screwed
  511. bonus->subtype = spec.subtype; //spell id
  512. hs->addNewBonus(bonus);
  513. break;
  514. case 6://damage bonus for bless (Adela)
  515. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  516. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  517. bonus->additionalInfo = spec.additionalinfo; //damage factor
  518. hs->addNewBonus(bonus);
  519. break;
  520. case 7://maxed mastery for spell
  521. bonus->type = Bonus::MAXED_SPELL;
  522. bonus->subtype = spec.subtype; //spell i
  523. hs->addNewBonus(bonus);
  524. break;
  525. case 8://peculiar spells - enchantments
  526. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  527. bonus->subtype = spec.subtype; //spell id
  528. bonus->additionalInfo = spec.additionalinfo;//0, 1 for Coronius
  529. hs->addNewBonus(bonus);
  530. break;
  531. case 9://upgrade creatures
  532. {
  533. const auto &creatures = VLC->creh->creatures;
  534. bonus->type = Bonus::SPECIAL_UPGRADE;
  535. bonus->subtype = spec.subtype; //base id
  536. bonus->additionalInfo = spec.additionalinfo; //target id
  537. hs->addNewBonus(bonus);
  538. bonus = new Bonus(*bonus);
  539. for(auto cre_id : creatures[spec.subtype]->upgrades)
  540. {
  541. bonus->subtype = cre_id; //propagate for regular upgrades of base creature
  542. hs->addNewBonus(bonus);
  543. bonus = new Bonus(*bonus);
  544. }
  545. vstd::clear_pointer(bonus);
  546. break;
  547. }
  548. case 10://resource generation
  549. bonus->type = Bonus::GENERATE_RESOURCE;
  550. bonus->subtype = spec.subtype;
  551. hs->addNewBonus(bonus);
  552. break;
  553. case 11://starting skill with mastery (Adrienne)
  554. setSecSkillLevel(SecondarySkill(spec.val), spec.additionalinfo, true);
  555. break;
  556. case 12://army speed
  557. bonus->type = Bonus::STACKS_SPEED;
  558. hs->addNewBonus(bonus);
  559. break;
  560. case 13://Dragon bonuses (Mutare)
  561. bonus->type = Bonus::PRIMARY_SKILL;
  562. bonus->valType = Bonus::ADDITIVE_VALUE;
  563. switch (spec.subtype)
  564. {
  565. case 1:
  566. bonus->subtype = PrimarySkill::ATTACK;
  567. break;
  568. case 2:
  569. bonus->subtype = PrimarySkill::DEFENSE;
  570. break;
  571. }
  572. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  573. hs->addNewBonus(bonus);
  574. break;
  575. default:
  576. logGlobal->warnStream() << "Unexpected hero specialty " << type;
  577. }
  578. }
  579. specialty.push_back(hs); //will it work?
  580. for (auto hs2 : type->specialty) //copy active (probably growing) bonuses from hero prootype to hero object
  581. {
  582. auto hs = new HeroSpecial();
  583. attachTo(hs); //do we ever need to detach it?
  584. hs->setNodeType(CBonusSystemNode::SPECIALTY);
  585. for (auto bonus : hs2.bonuses)
  586. {
  587. hs->addNewBonus (bonus);
  588. }
  589. hs->growsWithLevel = hs2.growsWithLevel;
  590. specialty.push_back(hs); //will it work?
  591. }
  592. //initialize bonuses
  593. recreateSecondarySkillsBonuses();
  594. Updatespecialty();
  595. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  596. type->name = name;
  597. }
  598. void CGHeroInstance::Updatespecialty() //TODO: calculate special value of bonuses on-the-fly?
  599. {
  600. for (auto hs : specialty)
  601. {
  602. if (hs->growsWithLevel)
  603. {
  604. //const auto &creatures = VLC->creh->creatures;
  605. for(Bonus * b : hs->getBonusList())
  606. {
  607. switch (b->type)
  608. {
  609. case Bonus::SECONDARY_SKILL_PREMY:
  610. b->val = (hs->valOfBonuses(Bonus::SPECIAL_SECONDARY_SKILL, b->subtype) * level);
  611. break; //use only hero skills as bonuses to avoid feedback loop
  612. case Bonus::PRIMARY_SKILL: //for creatures, that is
  613. {
  614. const CCreature * cre = nullptr;
  615. int creLevel = 0;
  616. if (auto creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(b->limiter)) //TODO: more general eveluation of bonuses?
  617. {
  618. cre = creatureLimiter->creature;
  619. creLevel = cre->level;
  620. if (!creLevel)
  621. {
  622. creLevel = 5; //treat ballista as tier 5
  623. }
  624. }
  625. else //no creature found, can't calculate value
  626. {
  627. logGlobal->warnStream() << "Primary skill specialty growth supported only with creature type limiters";
  628. break;
  629. }
  630. double primSkillModifier = (int)(level / creLevel) / 20.0;
  631. int param;
  632. switch (b->subtype)
  633. {
  634. case PrimarySkill::ATTACK:
  635. param = cre->Attack();
  636. break;
  637. case PrimarySkill::DEFENSE:
  638. param = cre->Defense();
  639. break;
  640. default:
  641. continue;
  642. }
  643. b->val = ceil(param * (1 + primSkillModifier)) - param; //yep, overcomplicated but matches original
  644. break;
  645. }
  646. }
  647. }
  648. }
  649. }
  650. }
  651. void CGHeroInstance::recreateSecondarySkillsBonuses()
  652. {
  653. auto secondarySkillsBonuses = getBonuses(Selector::sourceType(Bonus::SECONDARY_SKILL));
  654. for(auto bonus : *secondarySkillsBonuses)
  655. removeBonus(bonus);
  656. for(auto skill_info : secSkills)
  657. updateSkill(SecondarySkill(skill_info.first), skill_info.second);
  658. }
  659. void CGHeroInstance::updateSkill(SecondarySkill which, int val)
  660. {
  661. if(which == SecondarySkill::LEADERSHIP || which == SecondarySkill::LUCK)
  662. { //luck-> VLC->generaltexth->arraytxt[73+luckSkill]; VLC->generaltexth->arraytxt[104+moraleSkill]
  663. bool luck = which == SecondarySkill::LUCK;
  664. Bonus::BonusType type[] = {Bonus::MORALE, Bonus::LUCK};
  665. Bonus *b = getBonusLocalFirst(Selector::type(type[luck]).And(Selector::sourceType(Bonus::SECONDARY_SKILL)));
  666. if(!b)
  667. {
  668. b = new Bonus(Bonus::PERMANENT, type[luck], Bonus::SECONDARY_SKILL, +val, which, which, Bonus::BASE_NUMBER);
  669. addNewBonus(b);
  670. }
  671. else
  672. b->val = +val;
  673. }
  674. else if(which == SecondarySkill::DIPLOMACY) //surrender discount: 20% per level
  675. {
  676. if(Bonus *b = getBonusLocalFirst(Selector::type(Bonus::SURRENDER_DISCOUNT).And(Selector::sourceType(Bonus::SECONDARY_SKILL))))
  677. b->val = +val;
  678. else
  679. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::SURRENDER_DISCOUNT, Bonus::SECONDARY_SKILL, val * 20, which));
  680. }
  681. int skillVal = 0;
  682. switch (which)
  683. {
  684. case SecondarySkill::ARCHERY:
  685. switch (val)
  686. {
  687. case 1:
  688. skillVal = 10; break;
  689. case 2:
  690. skillVal = 25; break;
  691. case 3:
  692. skillVal = 50; break;
  693. }
  694. break;
  695. case SecondarySkill::LOGISTICS:
  696. skillVal = 10 * val; break;
  697. case SecondarySkill::NAVIGATION:
  698. skillVal = 50 * val; break;
  699. case SecondarySkill::MYSTICISM:
  700. skillVal = val; break;
  701. case SecondarySkill::EAGLE_EYE:
  702. skillVal = 30 + 10 * val; break;
  703. case SecondarySkill::NECROMANCY:
  704. skillVal = 10 * val; break;
  705. case SecondarySkill::LEARNING:
  706. skillVal = 5 * val; break;
  707. case SecondarySkill::OFFENCE:
  708. skillVal = 10 * val; break;
  709. case SecondarySkill::ARMORER:
  710. skillVal = 5 * val; break;
  711. case SecondarySkill::INTELLIGENCE:
  712. skillVal = 25 << (val-1); break;
  713. case SecondarySkill::SORCERY:
  714. skillVal = 5 * val; break;
  715. case SecondarySkill::RESISTANCE:
  716. skillVal = 5 << (val-1); break;
  717. case SecondarySkill::FIRST_AID:
  718. skillVal = 25 + 25*val; break;
  719. case SecondarySkill::ESTATES:
  720. skillVal = 125 << (val-1); break;
  721. }
  722. Bonus::ValueType skillValType = skillVal ? Bonus::BASE_NUMBER : Bonus::INDEPENDENT_MIN;
  723. if(Bonus * b = getBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which)
  724. .And(Selector::sourceType(Bonus::SECONDARY_SKILL)))) //only local hero bonus
  725. {
  726. b->val = skillVal;
  727. b->valType = skillValType;
  728. }
  729. else
  730. {
  731. auto bonus = new Bonus(Bonus::PERMANENT, Bonus::SECONDARY_SKILL_PREMY, Bonus::SECONDARY_SKILL, skillVal, id.getNum(), which, skillValType);
  732. bonus->source = Bonus::SECONDARY_SKILL;
  733. addNewBonus(bonus);
  734. }
  735. }
  736. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  737. {
  738. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  739. setStackCount(SlotID(0), val);
  740. }
  741. double CGHeroInstance::getFightingStrength() const
  742. {
  743. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  744. }
  745. double CGHeroInstance::getMagicStrength() const
  746. {
  747. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::KNOWLEDGE)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::SPELL_POWER)));
  748. }
  749. double CGHeroInstance::getHeroStrength() const
  750. {
  751. return sqrt(pow(getFightingStrength(), 2.0) * pow(getMagicStrength(), 2.0));
  752. }
  753. ui64 CGHeroInstance::getTotalStrength() const
  754. {
  755. double ret = getFightingStrength() * getArmyStrength();
  756. return (ui64) ret;
  757. }
  758. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  759. {
  760. return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
  761. }
  762. ui8 CGHeroInstance::getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool) const
  763. {
  764. si16 skill = -1; //skill level
  765. #define TRY_SCHOOL(schoolName, schoolMechanicsId, schoolOutId) \
  766. if(spell-> schoolName) \
  767. { \
  768. int thisSchool = std::max<int>(getSecSkillLevel( \
  769. SecondarySkill(14 + (schoolMechanicsId))), \
  770. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << (schoolMechanicsId))); \
  771. if(thisSchool > skill) \
  772. { \
  773. skill = thisSchool; \
  774. if(outSelectedSchool) \
  775. *outSelectedSchool = schoolOutId; \
  776. } \
  777. }
  778. TRY_SCHOOL(fire, 0, 1)
  779. TRY_SCHOOL(air, 1, 0)
  780. TRY_SCHOOL(water, 2, 2)
  781. TRY_SCHOOL(earth, 3, 3)
  782. #undef TRY_SCHOOL
  783. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  784. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect
  785. if (hasBonusOfType(Bonus::MAXED_SPELL, spell->id))//hero specialty (Daremyth, Melodia)
  786. skill = 3;
  787. assert(skill >= 0 && skill <= 3);
  788. return skill;
  789. }
  790. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  791. {
  792. if(!getArt(ArtifactPosition::SPELLBOOK)) //if hero has no spellbook
  793. return false;
  794. if (spell->isSpecialSpell())
  795. {
  796. if (vstd::contains(spells, spell->id))
  797. {//hero has this spell in spellbook
  798. logGlobal->errorStream() << "Special spell in spellbook "<<spell->name;
  799. }
  800. if (hasBonusOfType(Bonus::SPELL, spell->id))
  801. return true;
  802. return false;
  803. }
  804. else
  805. {
  806. if(vstd::contains(spells, spell->id) //hero has this spell in spellbook
  807. || (spell->air && hasBonusOfType(Bonus::AIR_SPELLS)) // this is air spell and hero can cast all air spells
  808. || (spell->fire && hasBonusOfType(Bonus::FIRE_SPELLS)) // this is fire spell and hero can cast all fire spells
  809. || (spell->water && hasBonusOfType(Bonus::WATER_SPELLS)) // this is water spell and hero can cast all water spells
  810. || (spell->earth && hasBonusOfType(Bonus::EARTH_SPELLS)) // this is earth spell and hero can cast all earth spells
  811. || hasBonusOfType(Bonus::SPELL, spell->id)
  812. || hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level)
  813. )
  814. return true;
  815. return false;
  816. }
  817. }
  818. /**
  819. * Calculates what creatures and how many to be raised from a battle.
  820. * @param battleResult The results of the battle.
  821. * @return Returns a pair with the first value indicating the ID of the creature
  822. * type and second value the amount. Both values are returned as -1 if necromancy
  823. * could not be applied.
  824. */
  825. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  826. {
  827. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  828. // Hero knows necromancy or has Necromancer Cloak
  829. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  830. {
  831. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  832. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  833. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  834. ui32 raisedUnits = 0;
  835. // Figure out what to raise and how many.
  836. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  837. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  838. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  839. const ui32 raisedUnitHP = raisedUnitType->valOfBonuses(Bonus::STACK_HEALTH);
  840. //calculate creatures raised from each defeated stack
  841. for (auto & casualtie : casualties)
  842. {
  843. // Get lost enemy hit points convertible to units.
  844. CCreature * c = VLC->creh->creatures[casualtie.first];
  845. const ui32 raisedHP = c->valOfBonuses(Bonus::STACK_HEALTH) * casualtie.second * necromancySkill;
  846. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, casualtie.second * necromancySkill); //limit to % of HP and % of original stack count
  847. }
  848. // Make room for new units.
  849. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  850. if (slot == SlotID())
  851. {
  852. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  853. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  854. raisedUnits = (raisedUnits*2)/3;
  855. slot = getSlotFor(raisedUnitType->idNumber);
  856. }
  857. if (raisedUnits <= 0)
  858. raisedUnits = 1;
  859. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  860. }
  861. return CStackBasicDescriptor();
  862. }
  863. /**
  864. * Show the necromancy dialog with information about units raised.
  865. * @param raisedStack Pair where the first element represents ID of the raised creature
  866. * and the second element the amount.
  867. */
  868. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack) const
  869. {
  870. InfoWindow iw;
  871. iw.soundID = soundBase::pickup01 + cb->gameState()->getRandomGenerator().nextInt(6);
  872. iw.player = tempOwner;
  873. iw.components.push_back(Component(raisedStack));
  874. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  875. {
  876. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  877. iw.text.addReplacement(raisedStack.count);
  878. }
  879. else // Practicing the dark arts of necromancy, ... (singular)
  880. {
  881. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  882. }
  883. iw.text.addReplacement(raisedStack);
  884. cb->showInfoDialog(&iw);
  885. }
  886. /*
  887. int3 CGHeroInstance::getSightCenter() const
  888. {
  889. return getPosition(false);
  890. }*/
  891. int CGHeroInstance::getSightRadious() const
  892. {
  893. return 5 + getSecSkillLevel(SecondarySkill::SCOUTING) + valOfBonuses(Bonus::SIGHT_RADIOUS); //default + scouting
  894. }
  895. si32 CGHeroInstance::manaRegain() const
  896. {
  897. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  898. return manaLimit();
  899. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 8) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  900. }
  901. // /**
  902. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  903. // * or discards it if it cannot be equipped.
  904. // */
  905. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  906. // {
  907. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  908. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  909. // ai->putAt(this, ai->firstAvailableSlot(this));
  910. // }
  911. int CGHeroInstance::getBoatType() const
  912. {
  913. switch(type->heroClass->getAlignment())
  914. {
  915. case EAlignment::GOOD:
  916. return 1;
  917. case EAlignment::EVIL:
  918. return 0;
  919. case EAlignment::NEUTRAL:
  920. return 2;
  921. default:
  922. throw std::runtime_error("Wrong alignment!");
  923. }
  924. }
  925. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  926. {
  927. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0), int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  928. for (auto & dir : dirs)
  929. offsets += dir;
  930. }
  931. int CGHeroInstance::getSpellCost(const CSpell *sp) const
  932. {
  933. return sp->getCost(getSpellSchoolLevel(sp));
  934. }
  935. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  936. {
  937. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  938. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL))));
  939. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  940. }
  941. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  942. {
  943. return type->heroClass->getAlignment();
  944. }
  945. void CGHeroInstance::initExp()
  946. {
  947. exp = cb->gameState()->getRandomGenerator().nextInt(40, 89);
  948. }
  949. std::string CGHeroInstance::nodeName() const
  950. {
  951. return "Hero " + name;
  952. }
  953. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  954. {
  955. assert(!getArt(pos));
  956. art->putAt(ArtifactLocation(this, pos));
  957. }
  958. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  959. {
  960. putArtifact(art->firstBackpackSlot(this), art);
  961. }
  962. bool CGHeroInstance::hasSpellbook() const
  963. {
  964. return getArt(ArtifactPosition::SPELLBOOK);
  965. }
  966. void CGHeroInstance::deserializationFix()
  967. {
  968. artDeserializationFix(this);
  969. for (auto hs : specialty)
  970. {
  971. attachTo (hs);
  972. }
  973. }
  974. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  975. {
  976. if(visitedTown)
  977. {
  978. if(inTownGarrison)
  979. return visitedTown;
  980. else
  981. return &visitedTown->townAndVis;
  982. }
  983. else
  984. return CArmedInstance::whereShouldBeAttached(gs);
  985. }
  986. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark /*= false*/) const
  987. {
  988. if(hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  989. return (MPsBefore - basicCost) * static_cast<double>(maxMovePoints(disembark)) / maxMovePoints(!disembark);
  990. return 0; //take all MPs otherwise
  991. }
  992. CGHeroInstance::ECanDig CGHeroInstance::diggingStatus() const
  993. {
  994. if(movement < maxMovePoints(true))
  995. return LACK_OF_MOVEMENT;
  996. else if(cb->getTile(getPosition(false))->terType == ETerrainType::WATER)
  997. return WRONG_TERRAIN;
  998. else
  999. {
  1000. const TerrainTile *t = cb->getTile(getPosition());
  1001. //TODO look for hole
  1002. //CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  1003. if(/*hlp.length() || */t->blockingObjects.size() > 1)
  1004. return TILE_OCCUPIED;
  1005. else
  1006. return CAN_DIG;
  1007. }
  1008. }
  1009. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1010. {
  1011. return ArtBearer::HERO;
  1012. }
  1013. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
  1014. {
  1015. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  1016. if (!skillsInfo.wisdomCounter)
  1017. {
  1018. if (cb->isAllowed(2, SecondarySkill::WISDOM) && !getSecSkillLevel(SecondarySkill::WISDOM))
  1019. obligatorySkills.push_back(SecondarySkill::WISDOM);
  1020. }
  1021. if (!skillsInfo.magicSchoolCounter)
  1022. {
  1023. std::vector<SecondarySkill> ss;
  1024. ss += SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC;
  1025. std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());
  1026. for (auto skill : ss)
  1027. {
  1028. if (cb->isAllowed(2, skill) && !getSecSkillLevel(skill)) //only schools hero doesn't know yet
  1029. {
  1030. obligatorySkills.push_back(skill);
  1031. break; //only one
  1032. }
  1033. }
  1034. }
  1035. std::vector<SecondarySkill> skills;
  1036. //picking sec. skills for choice
  1037. std::set<SecondarySkill> basicAndAdv, expert, none;
  1038. for(int i=0;i<GameConstants::SKILL_QUANTITY;i++)
  1039. if (cb->isAllowed(2,i))
  1040. none.insert(SecondarySkill(i));
  1041. for(auto & elem : secSkills)
  1042. {
  1043. if(elem.second < SecSkillLevel::EXPERT)
  1044. basicAndAdv.insert(elem.first);
  1045. else
  1046. expert.insert(elem.first);
  1047. none.erase(elem.first);
  1048. }
  1049. for (auto s : obligatorySkills) //don't duplicate them
  1050. {
  1051. none.erase (s);
  1052. basicAndAdv.erase (s);
  1053. expert.erase (s);
  1054. }
  1055. //first offered skill:
  1056. // 1) give obligatory skill
  1057. // 2) give any other new skill
  1058. // 3) upgrade existing
  1059. if (canLearnSkill() && obligatorySkills.size() > 0)
  1060. {
  1061. skills.push_back (obligatorySkills[0]);
  1062. }
  1063. else if(none.size() && canLearnSkill()) //hero have free skill slot
  1064. {
  1065. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
  1066. none.erase(skills.back());
  1067. }
  1068. else if(!basicAndAdv.empty())
  1069. {
  1070. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
  1071. basicAndAdv.erase(skills.back());
  1072. }
  1073. //second offered skill:
  1074. //1) upgrade existing
  1075. //2) give obligatory skill
  1076. //3) give any other new skill
  1077. if(!basicAndAdv.empty())
  1078. {
  1079. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
  1080. skills.push_back(s);
  1081. basicAndAdv.erase(s);
  1082. }
  1083. else if (canLearnSkill() && obligatorySkills.size() > 1)
  1084. {
  1085. skills.push_back (obligatorySkills[1]);
  1086. }
  1087. else if(none.size() && canLearnSkill())
  1088. {
  1089. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
  1090. none.erase(skills.back());
  1091. }
  1092. return skills;
  1093. }
  1094. PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill() const
  1095. {
  1096. assert(gainsLevel());
  1097. int randomValue = cb->gameState()->getRandomGenerator().nextInt(99), pom = 0, primarySkill = 0;
  1098. const auto & skillChances = (level > 9) ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;
  1099. for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
  1100. {
  1101. pom += skillChances[primarySkill];
  1102. if(randomValue < pom)
  1103. {
  1104. break;
  1105. }
  1106. }
  1107. logGlobal->traceStream() << "The hero gets the primary skill " << primarySkill << " with a probability of " << randomValue << "%.";
  1108. return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
  1109. }
  1110. boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill() const
  1111. {
  1112. assert(gainsLevel());
  1113. boost::optional<SecondarySkill> chosenSecondarySkill;
  1114. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1115. if(!proposedSecondarySkills.empty())
  1116. {
  1117. std::vector<SecondarySkill> learnedSecondarySkills;
  1118. for(auto secondarySkill : proposedSecondarySkills)
  1119. {
  1120. if(getSecSkillLevel(secondarySkill) > 0)
  1121. {
  1122. learnedSecondarySkills.push_back(secondarySkill);
  1123. }
  1124. }
  1125. auto & rand = cb->gameState()->getRandomGenerator();
  1126. if(learnedSecondarySkills.empty())
  1127. {
  1128. // there are only new skills to learn, so choose anyone of them
  1129. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand);
  1130. }
  1131. else
  1132. {
  1133. // preferably upgrade a already learned secondary skill
  1134. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand);
  1135. }
  1136. }
  1137. return chosenSecondarySkill;
  1138. }
  1139. void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
  1140. {
  1141. if(primarySkill < PrimarySkill::EXPERIENCE)
  1142. {
  1143. Bonus * skill = getBonusLocalFirst(Selector::type(Bonus::PRIMARY_SKILL)
  1144. .And(Selector::subtype(primarySkill))
  1145. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));
  1146. assert(skill);
  1147. if(abs)
  1148. {
  1149. skill->val = value;
  1150. }
  1151. else
  1152. {
  1153. skill->val += value;
  1154. }
  1155. }
  1156. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1157. {
  1158. if(abs)
  1159. {
  1160. exp = value;
  1161. }
  1162. else
  1163. {
  1164. exp += value;
  1165. }
  1166. }
  1167. }
  1168. bool CGHeroInstance::gainsLevel() const
  1169. {
  1170. return exp >= VLC->heroh->reqExp(level+1);
  1171. }
  1172. void CGHeroInstance::levelUp(std::vector<SecondarySkill> skills)
  1173. {
  1174. ++level;
  1175. //deterministic secondary skills
  1176. skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
  1177. skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
  1178. if(vstd::contains(skills, SecondarySkill::WISDOM))
  1179. {
  1180. skillsInfo.resetWisdomCounter();
  1181. }
  1182. SecondarySkill spellSchools[] = {
  1183. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
  1184. for(auto skill : spellSchools)
  1185. {
  1186. if(vstd::contains(skills, skill))
  1187. {
  1188. skillsInfo.resetMagicSchoolCounter();
  1189. break;
  1190. }
  1191. }
  1192. //specialty
  1193. Updatespecialty();
  1194. }
  1195. void CGHeroInstance::levelUpAutomatically()
  1196. {
  1197. while(gainsLevel())
  1198. {
  1199. const auto primarySkill = nextPrimarySkill();
  1200. setPrimarySkill(primarySkill, 1, false);
  1201. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1202. const auto secondarySkill = nextSecondarySkill();
  1203. if(secondarySkill)
  1204. {
  1205. setSecSkillLevel(*secondarySkill, 1, false);
  1206. }
  1207. //TODO why has the secondary skills to be passed to the method?
  1208. levelUp(proposedSecondarySkills);
  1209. }
  1210. }