CGHeroInstance.cpp 41 KB

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