2
0

CGHeroInstance.cpp 41 KB

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