CGHeroInstance.cpp 42 KB

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