CGHeroInstance.cpp 38 KB

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