2
0

CGHeroInstance.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  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. std::string CGHeroInstance::getObjectName() const
  366. {
  367. if(ID != Obj::PRISON)
  368. {
  369. std::string 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. return CGObjectInstance::getObjectName();
  376. }
  377. const std::string & CGHeroInstance::getBiography() const
  378. {
  379. if (biography.length())
  380. return biography;
  381. return type->biography;
  382. }
  383. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  384. {
  385. return type->heroClass->isMagicHero() ? 3 : 4;
  386. }
  387. ui8 CGHeroInstance::maxlevelsToWisdom() const
  388. {
  389. return type->heroClass->isMagicHero() ? 3 : 6;
  390. }
  391. void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
  392. {
  393. magicSchoolCounter = 1;
  394. }
  395. void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
  396. {
  397. wisdomCounter = 1;
  398. }
  399. void CGHeroInstance::initObj()
  400. {
  401. blockVisit = true;
  402. auto hs = new HeroSpecial();
  403. hs->setNodeType(CBonusSystemNode::SPECIALTY);
  404. attachTo(hs); //do we ever need to detach it?
  405. if(!type)
  406. initHero(); //TODO: set up everything for prison before specialties are configured
  407. skillsInfo.rand.setSeed(cb->gameState()->getRandomGenerator().nextInt());
  408. skillsInfo.resetMagicSchoolCounter();
  409. skillsInfo.resetWisdomCounter();
  410. auto customApp = VLC->objtypeh->getHandlerFor(ID, type->heroClass->id)->getOverride(cb->gameState()->getTile(visitablePos())->terType, this);
  411. if (customApp)
  412. appearance = customApp.get();
  413. for(const auto &spec : type->spec) //TODO: unfity with bonus system
  414. {
  415. auto bonus = new Bonus();
  416. bonus->val = spec.val;
  417. bonus->sid = id.getNum(); //from the hero, specialty has no unique id
  418. bonus->duration = Bonus::PERMANENT;
  419. bonus->source = Bonus::HERO_SPECIAL;
  420. switch (spec.type)
  421. {
  422. case 1:// creature specialty
  423. {
  424. hs->growsWithLevel = true;
  425. const CCreature &specCreature = *VLC->creh->creatures[spec.additionalinfo]; //creature in which we have specialty
  426. //int creLevel = specCreature.level;
  427. //if(!creLevel)
  428. //{
  429. // if(spec.additionalinfo == 146)
  430. // creLevel = 5; //treat ballista as 5-level
  431. // else
  432. // {
  433. // logGlobal->warnStream() << "Warning: unknown level of " << specCreature.namePl;
  434. // continue;
  435. // }
  436. //}
  437. //bonus->additionalInfo = spec.additionalinfo; //creature id, should not be used again - this works only with limiter
  438. bonus->limiter.reset(new CCreatureTypeLimiter (specCreature, true)); //with upgrades
  439. bonus->type = Bonus::PRIMARY_SKILL;
  440. bonus->valType = Bonus::ADDITIVE_VALUE;
  441. bonus->subtype = PrimarySkill::ATTACK;
  442. hs->addNewBonus(bonus);
  443. bonus = new Bonus(*bonus);
  444. bonus->subtype = PrimarySkill::DEFENSE;
  445. hs->addNewBonus(bonus);
  446. //values will be calculated later
  447. bonus = new Bonus(*bonus);
  448. bonus->type = Bonus::STACKS_SPEED;
  449. bonus->val = 1; //+1 speed
  450. hs->addNewBonus(bonus);
  451. }
  452. break;
  453. case 2://secondary skill
  454. hs->growsWithLevel = true;
  455. bonus->type = Bonus::SPECIAL_SECONDARY_SKILL; //needs to be recalculated with level, based on this value
  456. bonus->valType = Bonus::BASE_NUMBER; // to receive nonzero value
  457. bonus->subtype = spec.subtype; //skill id
  458. bonus->val = spec.val; //value per level, in percent
  459. hs->addNewBonus(bonus);
  460. bonus = new Bonus(*bonus);
  461. switch (spec.additionalinfo)
  462. {
  463. case 0: //normal
  464. bonus->valType = Bonus::PERCENT_TO_BASE;
  465. break;
  466. case 1: //when it's navigation or there's no 'base' at all
  467. bonus->valType = Bonus::PERCENT_TO_ALL;
  468. break;
  469. }
  470. bonus->type = Bonus::SECONDARY_SKILL_PREMY; //value will be calculated later
  471. hs->addNewBonus(bonus);
  472. break;
  473. case 3://spell damage bonus, level dependent but calculated elsewhere
  474. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  475. bonus->subtype = spec.subtype;
  476. hs->addNewBonus(bonus);
  477. break;
  478. case 4://creature stat boost
  479. switch (spec.subtype)
  480. {
  481. case 1://attack
  482. bonus->type = Bonus::PRIMARY_SKILL;
  483. bonus->subtype = PrimarySkill::ATTACK;
  484. break;
  485. case 2://defense
  486. bonus->type = Bonus::PRIMARY_SKILL;
  487. bonus->subtype = PrimarySkill::DEFENSE;
  488. break;
  489. case 3:
  490. bonus->type = Bonus::CREATURE_DAMAGE;
  491. bonus->subtype = 0; //both min and max
  492. break;
  493. case 4://hp
  494. bonus->type = Bonus::STACK_HEALTH;
  495. break;
  496. case 5:
  497. bonus->type = Bonus::STACKS_SPEED;
  498. break;
  499. default:
  500. continue;
  501. }
  502. bonus->additionalInfo = spec.additionalinfo; //creature id
  503. bonus->valType = Bonus::ADDITIVE_VALUE;
  504. bonus->limiter.reset(new CCreatureTypeLimiter (*VLC->creh->creatures[spec.additionalinfo], true));
  505. hs->addNewBonus(bonus);
  506. break;
  507. case 5://spell damage bonus in percent
  508. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  509. bonus->valType = Bonus::BASE_NUMBER; // current spell system is screwed
  510. bonus->subtype = spec.subtype; //spell id
  511. hs->addNewBonus(bonus);
  512. break;
  513. case 6://damage bonus for bless (Adela)
  514. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  515. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  516. bonus->additionalInfo = spec.additionalinfo; //damage factor
  517. hs->addNewBonus(bonus);
  518. break;
  519. case 7://maxed mastery for spell
  520. bonus->type = Bonus::MAXED_SPELL;
  521. bonus->subtype = spec.subtype; //spell i
  522. hs->addNewBonus(bonus);
  523. break;
  524. case 8://peculiar spells - enchantments
  525. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  526. bonus->subtype = spec.subtype; //spell id
  527. bonus->additionalInfo = spec.additionalinfo;//0, 1 for Coronius
  528. hs->addNewBonus(bonus);
  529. break;
  530. case 9://upgrade creatures
  531. {
  532. const auto &creatures = VLC->creh->creatures;
  533. bonus->type = Bonus::SPECIAL_UPGRADE;
  534. bonus->subtype = spec.subtype; //base id
  535. bonus->additionalInfo = spec.additionalinfo; //target id
  536. hs->addNewBonus(bonus);
  537. bonus = new Bonus(*bonus);
  538. for(auto cre_id : creatures[spec.subtype]->upgrades)
  539. {
  540. bonus->subtype = cre_id; //propagate for regular upgrades of base creature
  541. hs->addNewBonus(bonus);
  542. bonus = new Bonus(*bonus);
  543. }
  544. vstd::clear_pointer(bonus);
  545. break;
  546. }
  547. case 10://resource generation
  548. bonus->type = Bonus::GENERATE_RESOURCE;
  549. bonus->subtype = spec.subtype;
  550. hs->addNewBonus(bonus);
  551. break;
  552. case 11://starting skill with mastery (Adrienne)
  553. setSecSkillLevel(SecondarySkill(spec.val), spec.additionalinfo, true);
  554. break;
  555. case 12://army speed
  556. bonus->type = Bonus::STACKS_SPEED;
  557. hs->addNewBonus(bonus);
  558. break;
  559. case 13://Dragon bonuses (Mutare)
  560. bonus->type = Bonus::PRIMARY_SKILL;
  561. bonus->valType = Bonus::ADDITIVE_VALUE;
  562. switch (spec.subtype)
  563. {
  564. case 1:
  565. bonus->subtype = PrimarySkill::ATTACK;
  566. break;
  567. case 2:
  568. bonus->subtype = PrimarySkill::DEFENSE;
  569. break;
  570. }
  571. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  572. hs->addNewBonus(bonus);
  573. break;
  574. default:
  575. logGlobal->warnStream() << "Unexpected hero specialty " << type;
  576. }
  577. }
  578. specialty.push_back(hs); //will it work?
  579. for (auto hs2 : type->specialty) //copy active (probably growing) bonuses from hero prootype to hero object
  580. {
  581. auto hs = new HeroSpecial();
  582. attachTo(hs); //do we ever need to detach it?
  583. hs->setNodeType(CBonusSystemNode::SPECIALTY);
  584. for (auto bonus : hs2.bonuses)
  585. {
  586. hs->addNewBonus (bonus);
  587. }
  588. hs->growsWithLevel = hs2.growsWithLevel;
  589. specialty.push_back(hs); //will it work?
  590. }
  591. //initialize bonuses
  592. recreateSecondarySkillsBonuses();
  593. Updatespecialty();
  594. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  595. type->name = name;
  596. }
  597. void CGHeroInstance::Updatespecialty() //TODO: calculate special value of bonuses on-the-fly?
  598. {
  599. for (auto hs : specialty)
  600. {
  601. if (hs->growsWithLevel)
  602. {
  603. //const auto &creatures = VLC->creh->creatures;
  604. for(Bonus * b : hs->getBonusList())
  605. {
  606. switch (b->type)
  607. {
  608. case Bonus::SECONDARY_SKILL_PREMY:
  609. b->val = (hs->valOfBonuses(Bonus::SPECIAL_SECONDARY_SKILL, b->subtype) * level);
  610. break; //use only hero skills as bonuses to avoid feedback loop
  611. case Bonus::PRIMARY_SKILL: //for creatures, that is
  612. {
  613. const CCreature * cre = nullptr;
  614. int creLevel = 0;
  615. if (auto creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(b->limiter)) //TODO: more general eveluation of bonuses?
  616. {
  617. cre = creatureLimiter->creature;
  618. creLevel = cre->level;
  619. if (!creLevel)
  620. {
  621. creLevel = 5; //treat ballista as tier 5
  622. }
  623. }
  624. else //no creature found, can't calculate value
  625. {
  626. logGlobal->warnStream() << "Primary skill specialty growth supported only with creature type limiters";
  627. break;
  628. }
  629. double primSkillModifier = (int)(level / creLevel) / 20.0;
  630. int param;
  631. switch (b->subtype)
  632. {
  633. case PrimarySkill::ATTACK:
  634. param = cre->Attack();
  635. break;
  636. case PrimarySkill::DEFENSE:
  637. param = cre->Defense();
  638. break;
  639. default:
  640. continue;
  641. }
  642. b->val = ceil(param * (1 + primSkillModifier)) - param; //yep, overcomplicated but matches original
  643. break;
  644. }
  645. }
  646. }
  647. }
  648. }
  649. }
  650. void CGHeroInstance::recreateSecondarySkillsBonuses()
  651. {
  652. auto secondarySkillsBonuses = getBonuses(Selector::sourceType(Bonus::SECONDARY_SKILL));
  653. for(auto bonus : *secondarySkillsBonuses)
  654. removeBonus(bonus);
  655. for(auto skill_info : secSkills)
  656. updateSkill(SecondarySkill(skill_info.first), skill_info.second);
  657. }
  658. void CGHeroInstance::updateSkill(SecondarySkill which, int val)
  659. {
  660. if(which == SecondarySkill::LEADERSHIP || which == SecondarySkill::LUCK)
  661. { //luck-> VLC->generaltexth->arraytxt[73+luckSkill]; VLC->generaltexth->arraytxt[104+moraleSkill]
  662. bool luck = which == SecondarySkill::LUCK;
  663. Bonus::BonusType type[] = {Bonus::MORALE, Bonus::LUCK};
  664. Bonus *b = getBonusLocalFirst(Selector::type(type[luck]).And(Selector::sourceType(Bonus::SECONDARY_SKILL)));
  665. if(!b)
  666. {
  667. b = new Bonus(Bonus::PERMANENT, type[luck], Bonus::SECONDARY_SKILL, +val, which, which, Bonus::BASE_NUMBER);
  668. addNewBonus(b);
  669. }
  670. else
  671. b->val = +val;
  672. }
  673. else if(which == SecondarySkill::DIPLOMACY) //surrender discount: 20% per level
  674. {
  675. if(Bonus *b = getBonusLocalFirst(Selector::type(Bonus::SURRENDER_DISCOUNT).And(Selector::sourceType(Bonus::SECONDARY_SKILL))))
  676. b->val = +val;
  677. else
  678. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::SURRENDER_DISCOUNT, Bonus::SECONDARY_SKILL, val * 20, which));
  679. }
  680. int skillVal = 0;
  681. switch (which)
  682. {
  683. case SecondarySkill::ARCHERY:
  684. switch (val)
  685. {
  686. case 1:
  687. skillVal = 10; break;
  688. case 2:
  689. skillVal = 25; break;
  690. case 3:
  691. skillVal = 50; break;
  692. }
  693. break;
  694. case SecondarySkill::LOGISTICS:
  695. skillVal = 10 * val; break;
  696. case SecondarySkill::NAVIGATION:
  697. skillVal = 50 * val; break;
  698. case SecondarySkill::MYSTICISM:
  699. skillVal = val; break;
  700. case SecondarySkill::EAGLE_EYE:
  701. skillVal = 30 + 10 * val; break;
  702. case SecondarySkill::NECROMANCY:
  703. skillVal = 10 * val; break;
  704. case SecondarySkill::LEARNING:
  705. skillVal = 5 * val; break;
  706. case SecondarySkill::OFFENCE:
  707. skillVal = 10 * val; break;
  708. case SecondarySkill::ARMORER:
  709. skillVal = 5 * val; break;
  710. case SecondarySkill::INTELLIGENCE:
  711. skillVal = 25 << (val-1); break;
  712. case SecondarySkill::SORCERY:
  713. skillVal = 5 * val; break;
  714. case SecondarySkill::RESISTANCE:
  715. skillVal = 5 << (val-1); break;
  716. case SecondarySkill::FIRST_AID:
  717. skillVal = 25 + 25*val; break;
  718. case SecondarySkill::ESTATES:
  719. skillVal = 125 << (val-1); break;
  720. }
  721. Bonus::ValueType skillValType = skillVal ? Bonus::BASE_NUMBER : Bonus::INDEPENDENT_MIN;
  722. if(Bonus * b = getBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which)
  723. .And(Selector::sourceType(Bonus::SECONDARY_SKILL)))) //only local hero bonus
  724. {
  725. b->val = skillVal;
  726. b->valType = skillValType;
  727. }
  728. else
  729. {
  730. auto bonus = new Bonus(Bonus::PERMANENT, Bonus::SECONDARY_SKILL_PREMY, Bonus::SECONDARY_SKILL, skillVal, id.getNum(), which, skillValType);
  731. bonus->source = Bonus::SECONDARY_SKILL;
  732. addNewBonus(bonus);
  733. }
  734. }
  735. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  736. {
  737. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  738. setStackCount(SlotID(0), val);
  739. }
  740. double CGHeroInstance::getFightingStrength() const
  741. {
  742. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  743. }
  744. double CGHeroInstance::getMagicStrength() const
  745. {
  746. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::KNOWLEDGE)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::SPELL_POWER)));
  747. }
  748. double CGHeroInstance::getHeroStrength() const
  749. {
  750. return sqrt(pow(getFightingStrength(), 2.0) * pow(getMagicStrength(), 2.0));
  751. }
  752. ui64 CGHeroInstance::getTotalStrength() const
  753. {
  754. double ret = getFightingStrength() * getArmyStrength();
  755. return (ui64) ret;
  756. }
  757. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  758. {
  759. return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
  760. }
  761. ui8 CGHeroInstance::getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool) const
  762. {
  763. si16 skill = -1; //skill level
  764. #define TRY_SCHOOL(schoolName, schoolMechanicsId, schoolOutId) \
  765. if(spell-> schoolName) \
  766. { \
  767. int thisSchool = std::max<int>(getSecSkillLevel( \
  768. SecondarySkill(14 + (schoolMechanicsId))), \
  769. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << (schoolMechanicsId))); \
  770. if(thisSchool > skill) \
  771. { \
  772. skill = thisSchool; \
  773. if(outSelectedSchool) \
  774. *outSelectedSchool = schoolOutId; \
  775. } \
  776. }
  777. TRY_SCHOOL(fire, 0, 1)
  778. TRY_SCHOOL(air, 1, 0)
  779. TRY_SCHOOL(water, 2, 2)
  780. TRY_SCHOOL(earth, 3, 3)
  781. #undef TRY_SCHOOL
  782. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  783. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect
  784. if (hasBonusOfType(Bonus::MAXED_SPELL, spell->id))//hero specialty (Daremyth, Melodia)
  785. skill = 3;
  786. assert(skill >= 0 && skill <= 3);
  787. return skill;
  788. }
  789. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  790. {
  791. if(!getArt(ArtifactPosition::SPELLBOOK)) //if hero has no spellbook
  792. return false;
  793. if (spell->isSpecialSpell())
  794. {
  795. if (vstd::contains(spells, spell->id))
  796. {//hero has this spell in spellbook
  797. logGlobal->errorStream() << "Special spell in spellbook "<<spell->name;
  798. }
  799. if (hasBonusOfType(Bonus::SPELL, spell->id))
  800. return true;
  801. return false;
  802. }
  803. else
  804. {
  805. if(vstd::contains(spells, spell->id) //hero has this spell in spellbook
  806. || (spell->air && hasBonusOfType(Bonus::AIR_SPELLS)) // this is air spell and hero can cast all air spells
  807. || (spell->fire && hasBonusOfType(Bonus::FIRE_SPELLS)) // this is fire spell and hero can cast all fire spells
  808. || (spell->water && hasBonusOfType(Bonus::WATER_SPELLS)) // this is water spell and hero can cast all water spells
  809. || (spell->earth && hasBonusOfType(Bonus::EARTH_SPELLS)) // this is earth spell and hero can cast all earth spells
  810. || hasBonusOfType(Bonus::SPELL, spell->id)
  811. || hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level)
  812. )
  813. return true;
  814. return false;
  815. }
  816. }
  817. /**
  818. * Calculates what creatures and how many to be raised from a battle.
  819. * @param battleResult The results of the battle.
  820. * @return Returns a pair with the first value indicating the ID of the creature
  821. * type and second value the amount. Both values are returned as -1 if necromancy
  822. * could not be applied.
  823. */
  824. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  825. {
  826. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  827. // Hero knows necromancy or has Necromancer Cloak
  828. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  829. {
  830. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  831. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  832. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  833. ui32 raisedUnits = 0;
  834. // Figure out what to raise and how many.
  835. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  836. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  837. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  838. const ui32 raisedUnitHP = raisedUnitType->valOfBonuses(Bonus::STACK_HEALTH);
  839. //calculate creatures raised from each defeated stack
  840. for (auto & casualtie : casualties)
  841. {
  842. // Get lost enemy hit points convertible to units.
  843. CCreature * c = VLC->creh->creatures[casualtie.first];
  844. const ui32 raisedHP = c->valOfBonuses(Bonus::STACK_HEALTH) * casualtie.second * necromancySkill;
  845. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, casualtie.second * necromancySkill); //limit to % of HP and % of original stack count
  846. }
  847. // Make room for new units.
  848. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  849. if (slot == SlotID())
  850. {
  851. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  852. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  853. raisedUnits = (raisedUnits*2)/3;
  854. slot = getSlotFor(raisedUnitType->idNumber);
  855. }
  856. if (raisedUnits <= 0)
  857. raisedUnits = 1;
  858. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  859. }
  860. return CStackBasicDescriptor();
  861. }
  862. /**
  863. * Show the necromancy dialog with information about units raised.
  864. * @param raisedStack Pair where the first element represents ID of the raised creature
  865. * and the second element the amount.
  866. */
  867. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack) const
  868. {
  869. InfoWindow iw;
  870. iw.soundID = soundBase::pickup01 + cb->gameState()->getRandomGenerator().nextInt(6);
  871. iw.player = tempOwner;
  872. iw.components.push_back(Component(raisedStack));
  873. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  874. {
  875. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  876. iw.text.addReplacement(raisedStack.count);
  877. }
  878. else // Practicing the dark arts of necromancy, ... (singular)
  879. {
  880. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  881. }
  882. iw.text.addReplacement(raisedStack);
  883. cb->showInfoDialog(&iw);
  884. }
  885. /*
  886. int3 CGHeroInstance::getSightCenter() const
  887. {
  888. return getPosition(false);
  889. }*/
  890. int CGHeroInstance::getSightRadious() const
  891. {
  892. return 5 + getSecSkillLevel(SecondarySkill::SCOUTING) + valOfBonuses(Bonus::SIGHT_RADIOUS); //default + scouting
  893. }
  894. si32 CGHeroInstance::manaRegain() const
  895. {
  896. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  897. return manaLimit();
  898. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 8) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  899. }
  900. // /**
  901. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  902. // * or discards it if it cannot be equipped.
  903. // */
  904. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  905. // {
  906. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  907. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  908. // ai->putAt(this, ai->firstAvailableSlot(this));
  909. // }
  910. int CGHeroInstance::getBoatType() const
  911. {
  912. switch(type->heroClass->getAlignment())
  913. {
  914. case EAlignment::GOOD:
  915. return 1;
  916. case EAlignment::EVIL:
  917. return 0;
  918. case EAlignment::NEUTRAL:
  919. return 2;
  920. default:
  921. throw std::runtime_error("Wrong alignment!");
  922. }
  923. }
  924. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  925. {
  926. 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) };
  927. for (auto & dir : dirs)
  928. offsets += dir;
  929. }
  930. int CGHeroInstance::getSpellCost(const CSpell *sp) const
  931. {
  932. return sp->getCost(getSpellSchoolLevel(sp));
  933. }
  934. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  935. {
  936. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  937. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL))));
  938. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  939. }
  940. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  941. {
  942. return type->heroClass->getAlignment();
  943. }
  944. void CGHeroInstance::initExp()
  945. {
  946. exp = cb->gameState()->getRandomGenerator().nextInt(40, 89);
  947. }
  948. std::string CGHeroInstance::nodeName() const
  949. {
  950. return "Hero " + name;
  951. }
  952. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  953. {
  954. assert(!getArt(pos));
  955. art->putAt(ArtifactLocation(this, pos));
  956. }
  957. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  958. {
  959. putArtifact(art->firstBackpackSlot(this), art);
  960. }
  961. bool CGHeroInstance::hasSpellbook() const
  962. {
  963. return getArt(ArtifactPosition::SPELLBOOK);
  964. }
  965. void CGHeroInstance::deserializationFix()
  966. {
  967. artDeserializationFix(this);
  968. for (auto hs : specialty)
  969. {
  970. attachTo (hs);
  971. }
  972. }
  973. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  974. {
  975. if(visitedTown)
  976. {
  977. if(inTownGarrison)
  978. return visitedTown;
  979. else
  980. return &visitedTown->townAndVis;
  981. }
  982. else
  983. return CArmedInstance::whereShouldBeAttached(gs);
  984. }
  985. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark /*= false*/) const
  986. {
  987. if(hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  988. return (MPsBefore - basicCost) * static_cast<double>(maxMovePoints(disembark)) / maxMovePoints(!disembark);
  989. return 0; //take all MPs otherwise
  990. }
  991. CGHeroInstance::ECanDig CGHeroInstance::diggingStatus() const
  992. {
  993. if(movement < maxMovePoints(true))
  994. return LACK_OF_MOVEMENT;
  995. else if(cb->getTile(getPosition(false))->terType == ETerrainType::WATER)
  996. return WRONG_TERRAIN;
  997. else
  998. {
  999. const TerrainTile *t = cb->getTile(getPosition());
  1000. //TODO look for hole
  1001. //CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  1002. if(/*hlp.length() || */t->blockingObjects.size() > 1)
  1003. return TILE_OCCUPIED;
  1004. else
  1005. return CAN_DIG;
  1006. }
  1007. }
  1008. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1009. {
  1010. return ArtBearer::HERO;
  1011. }
  1012. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
  1013. {
  1014. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  1015. if (!skillsInfo.wisdomCounter)
  1016. {
  1017. if (cb->isAllowed(2, SecondarySkill::WISDOM) && !getSecSkillLevel(SecondarySkill::WISDOM))
  1018. obligatorySkills.push_back(SecondarySkill::WISDOM);
  1019. }
  1020. if (!skillsInfo.magicSchoolCounter)
  1021. {
  1022. std::vector<SecondarySkill> ss;
  1023. ss += SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC;
  1024. std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());
  1025. for (auto skill : ss)
  1026. {
  1027. if (cb->isAllowed(2, skill) && !getSecSkillLevel(skill)) //only schools hero doesn't know yet
  1028. {
  1029. obligatorySkills.push_back(skill);
  1030. break; //only one
  1031. }
  1032. }
  1033. }
  1034. std::vector<SecondarySkill> skills;
  1035. //picking sec. skills for choice
  1036. std::set<SecondarySkill> basicAndAdv, expert, none;
  1037. for(int i=0;i<GameConstants::SKILL_QUANTITY;i++)
  1038. if (cb->isAllowed(2,i))
  1039. none.insert(SecondarySkill(i));
  1040. for(auto & elem : secSkills)
  1041. {
  1042. if(elem.second < SecSkillLevel::EXPERT)
  1043. basicAndAdv.insert(elem.first);
  1044. else
  1045. expert.insert(elem.first);
  1046. none.erase(elem.first);
  1047. }
  1048. for (auto s : obligatorySkills) //don't duplicate them
  1049. {
  1050. none.erase (s);
  1051. basicAndAdv.erase (s);
  1052. expert.erase (s);
  1053. }
  1054. //first offered skill:
  1055. // 1) give obligatory skill
  1056. // 2) give any other new skill
  1057. // 3) upgrade existing
  1058. if (canLearnSkill() && obligatorySkills.size() > 0)
  1059. {
  1060. skills.push_back (obligatorySkills[0]);
  1061. }
  1062. else if(none.size() && canLearnSkill()) //hero have free skill slot
  1063. {
  1064. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
  1065. none.erase(skills.back());
  1066. }
  1067. else if(!basicAndAdv.empty())
  1068. {
  1069. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
  1070. basicAndAdv.erase(skills.back());
  1071. }
  1072. //second offered skill:
  1073. //1) upgrade existing
  1074. //2) give obligatory skill
  1075. //3) give any other new skill
  1076. if(!basicAndAdv.empty())
  1077. {
  1078. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
  1079. skills.push_back(s);
  1080. basicAndAdv.erase(s);
  1081. }
  1082. else if (canLearnSkill() && obligatorySkills.size() > 1)
  1083. {
  1084. skills.push_back (obligatorySkills[1]);
  1085. }
  1086. else if(none.size() && canLearnSkill())
  1087. {
  1088. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
  1089. none.erase(skills.back());
  1090. }
  1091. return skills;
  1092. }
  1093. PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill() const
  1094. {
  1095. assert(gainsLevel());
  1096. int randomValue = cb->gameState()->getRandomGenerator().nextInt(99), pom = 0, primarySkill = 0;
  1097. const auto & skillChances = (level > 9) ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;
  1098. for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
  1099. {
  1100. pom += skillChances[primarySkill];
  1101. if(randomValue < pom)
  1102. {
  1103. break;
  1104. }
  1105. }
  1106. logGlobal->traceStream() << "The hero gets the primary skill " << primarySkill << " with a probability of " << randomValue << "%.";
  1107. return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
  1108. }
  1109. boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill() const
  1110. {
  1111. assert(gainsLevel());
  1112. boost::optional<SecondarySkill> chosenSecondarySkill;
  1113. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1114. if(!proposedSecondarySkills.empty())
  1115. {
  1116. std::vector<SecondarySkill> learnedSecondarySkills;
  1117. for(auto secondarySkill : proposedSecondarySkills)
  1118. {
  1119. if(getSecSkillLevel(secondarySkill) > 0)
  1120. {
  1121. learnedSecondarySkills.push_back(secondarySkill);
  1122. }
  1123. }
  1124. auto & rand = cb->gameState()->getRandomGenerator();
  1125. if(learnedSecondarySkills.empty())
  1126. {
  1127. // there are only new skills to learn, so choose anyone of them
  1128. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand);
  1129. }
  1130. else
  1131. {
  1132. // preferably upgrade a already learned secondary skill
  1133. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand);
  1134. }
  1135. }
  1136. return chosenSecondarySkill;
  1137. }
  1138. void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
  1139. {
  1140. if(primarySkill < PrimarySkill::EXPERIENCE)
  1141. {
  1142. Bonus * skill = getBonusLocalFirst(Selector::type(Bonus::PRIMARY_SKILL)
  1143. .And(Selector::subtype(primarySkill))
  1144. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));
  1145. assert(skill);
  1146. if(abs)
  1147. {
  1148. skill->val = value;
  1149. }
  1150. else
  1151. {
  1152. skill->val += value;
  1153. }
  1154. }
  1155. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1156. {
  1157. if(abs)
  1158. {
  1159. exp = value;
  1160. }
  1161. else
  1162. {
  1163. exp += value;
  1164. }
  1165. }
  1166. }
  1167. bool CGHeroInstance::gainsLevel() const
  1168. {
  1169. return exp >= VLC->heroh->reqExp(level+1);
  1170. }
  1171. void CGHeroInstance::levelUp(std::vector<SecondarySkill> skills)
  1172. {
  1173. ++level;
  1174. //deterministic secondary skills
  1175. skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
  1176. skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
  1177. if(vstd::contains(skills, SecondarySkill::WISDOM))
  1178. {
  1179. skillsInfo.resetWisdomCounter();
  1180. }
  1181. SecondarySkill spellSchools[] = {
  1182. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
  1183. for(auto skill : spellSchools)
  1184. {
  1185. if(vstd::contains(skills, skill))
  1186. {
  1187. skillsInfo.resetMagicSchoolCounter();
  1188. break;
  1189. }
  1190. }
  1191. //specialty
  1192. Updatespecialty();
  1193. }
  1194. void CGHeroInstance::levelUpAutomatically()
  1195. {
  1196. while(gainsLevel())
  1197. {
  1198. const auto primarySkill = nextPrimarySkill();
  1199. setPrimarySkill(primarySkill, 1, false);
  1200. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1201. const auto secondarySkill = nextSecondarySkill();
  1202. if(secondarySkill)
  1203. {
  1204. setSecSkillLevel(*secondarySkill, 1, false);
  1205. }
  1206. //TODO why has the secondary skills to be passed to the method?
  1207. levelUp(proposedSecondarySkills);
  1208. }
  1209. }