CGHeroInstance.cpp 42 KB

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