CGHeroInstance.cpp 39 KB

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