CGHeroInstance.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  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 <vcmi/ServerCallback.h>
  13. #include <vcmi/spells/Spell.h>
  14. #include "../NetPacks.h"
  15. #include "../CGeneralTextHandler.h"
  16. #include "../CHeroHandler.h"
  17. #include "../TerrainHandler.h"
  18. #include "../RoadHandler.h"
  19. #include "../CModHandler.h"
  20. #include "../CSoundBase.h"
  21. #include "../spells/CSpellHandler.h"
  22. #include "../CSkillHandler.h"
  23. #include "CObjectClassesHandler.h"
  24. #include "../IGameCallback.h"
  25. #include "../CGameState.h"
  26. #include "../CCreatureHandler.h"
  27. #include "../CTownHandler.h"
  28. #include "../mapping/CMap.h"
  29. #include "CGTownInstance.h"
  30. #include "../serializer/JsonSerializeFormat.h"
  31. #include "../StringConstants.h"
  32. #include "../battle/Unit.h"
  33. VCMI_LIB_NAMESPACE_BEGIN
  34. ///helpers
  35. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID = 0)
  36. {
  37. InfoWindow iw;
  38. iw.soundID = soundID;
  39. iw.player = playerID;
  40. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  41. IObjectInterface::cb->sendAndApply(&iw);
  42. }
  43. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID = 0)
  44. {
  45. const PlayerColor playerID = h->getOwner();
  46. showInfoDialog(playerID,txtID,soundID);
  47. }
  48. static int lowestSpeed(const CGHeroInstance * chi)
  49. {
  50. static const CSelector selectorSTACKS_SPEED = Selector::type()(Bonus::STACKS_SPEED);
  51. static const std::string keySTACKS_SPEED = "type_" + std::to_string((si32)Bonus::STACKS_SPEED);
  52. if(!chi->stacksCount())
  53. {
  54. if(chi->commander && chi->commander->alive)
  55. {
  56. return chi->commander->valOfBonuses(selectorSTACKS_SPEED, keySTACKS_SPEED);
  57. }
  58. logGlobal->error("Hero %d (%s) has no army!", chi->id.getNum(), chi->getNameTranslated());
  59. return 20;
  60. }
  61. auto i = chi->Slots().begin();
  62. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  63. int ret = (i++)->second->valOfBonuses(selectorSTACKS_SPEED, keySTACKS_SPEED);
  64. for(; i != chi->Slots().end(); i++)
  65. ret = std::min(ret, i->second->valOfBonuses(selectorSTACKS_SPEED, keySTACKS_SPEED));
  66. return ret;
  67. }
  68. ui32 CGHeroInstance::getTileCost(const TerrainTile & dest, const TerrainTile & from, const TurnInfo * ti) const
  69. {
  70. int64_t ret = GameConstants::BASE_MOVEMENT_COST;
  71. //if there is road both on dest and src tiles - use road movement cost
  72. if(dest.roadType->getId() != Road::NO_ROAD && from.roadType->getId() != Road::NO_ROAD)
  73. {
  74. ret = std::max(dest.roadType->movementCost, from.roadType->movementCost);
  75. }
  76. else if(ti->nativeTerrain != from.terType->getId() &&//the terrain is not native
  77. ti->nativeTerrain != ETerrainId::ANY_TERRAIN && //no special creature bonus
  78. !ti->hasBonusOfType(Bonus::NO_TERRAIN_PENALTY, from.terType->getIndex())) //no special movement bonus
  79. {
  80. ret = VLC->heroh->terrCosts[from.terType->getId()];
  81. ret -= ti->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::PATHFINDING);
  82. if(ret < GameConstants::BASE_MOVEMENT_COST)
  83. ret = GameConstants::BASE_MOVEMENT_COST;
  84. }
  85. return (ui32)ret;
  86. }
  87. TerrainId 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. // and army that consist solely from neutral will always be considered to be on native terrain
  94. TerrainId nativeTerrain = ETerrainId::ANY_TERRAIN;
  95. for(auto stack : stacks)
  96. {
  97. TerrainId stackNativeTerrain = stack.second->type->getNativeTerrain(); //consider terrain bonuses e.g. Lodestar.
  98. if(stackNativeTerrain == ETerrainId::NONE)
  99. continue;
  100. if(nativeTerrain == ETerrainId::ANY_TERRAIN)
  101. nativeTerrain = stackNativeTerrain;
  102. else if(nativeTerrain != stackNativeTerrain)
  103. return ETerrainId::NONE;
  104. }
  105. return nativeTerrain;
  106. }
  107. BattleField CGHeroInstance::getBattlefield() const
  108. {
  109. return BattleField::NONE;
  110. }
  111. ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
  112. {
  113. for(auto & elem : secSkills)
  114. if(elem.first == skill)
  115. return elem.second;
  116. return 0;
  117. }
  118. void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
  119. {
  120. if(getSecSkillLevel(which) == 0)
  121. {
  122. secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
  123. updateSkillBonus(which, val);
  124. }
  125. else
  126. {
  127. for (auto & elem : secSkills)
  128. {
  129. if(elem.first == which)
  130. {
  131. if(abs)
  132. elem.second = val;
  133. else
  134. elem.second += val;
  135. if(elem.second > 3) //workaround to avoid crashes when same sec skill is given more than once
  136. {
  137. logGlobal->warn("Skill %d increased over limit! Decreasing to Expert.", static_cast<int>(which.toEnum()));
  138. elem.second = 3;
  139. }
  140. updateSkillBonus(which, elem.second); //when we know final value
  141. }
  142. }
  143. }
  144. }
  145. int3 CGHeroInstance::convertToVisitablePos(const int3 & position) const
  146. {
  147. return position - getVisitableOffset();
  148. }
  149. int3 CGHeroInstance::convertFromVisitablePos(const int3 & position) const
  150. {
  151. return position + getVisitableOffset();
  152. }
  153. bool CGHeroInstance::canLearnSkill() const
  154. {
  155. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  156. }
  157. bool CGHeroInstance::canLearnSkill(SecondarySkill which) const
  158. {
  159. if ( !canLearnSkill())
  160. return false;
  161. if (!cb->isAllowed(2, which))
  162. return false;
  163. if (getSecSkillLevel(which) > 0)
  164. return false;
  165. if (type->heroClass->secSkillProbability[which] == 0)
  166. return false;
  167. return true;
  168. }
  169. int CGHeroInstance::maxMovePoints(bool onLand) const
  170. {
  171. TurnInfo ti(this);
  172. return maxMovePointsCached(onLand, &ti);
  173. }
  174. int CGHeroInstance::maxMovePointsCached(bool onLand, const TurnInfo * ti) const
  175. {
  176. int base;
  177. if(onLand)
  178. {
  179. // used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
  180. static const int baseSpeed = 1300; // base speed from creature with 0 speed
  181. int armySpeed = lowestSpeed(this) * 20 / 3;
  182. base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
  183. vstd::abetween(base, 1500, 2000); // base speed is limited by these values
  184. }
  185. else
  186. {
  187. base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
  188. }
  189. const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
  190. const int bonus = ti->valOfBonuses(Bonus::MOVEMENT) + ti->valOfBonuses(bt);
  191. const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
  192. const double modifier = ti->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;
  193. return int(base * (1 + modifier)) + bonus;
  194. }
  195. CGHeroInstance::CGHeroInstance()
  196. : IBoatGenerator(this)
  197. {
  198. setNodeType(HERO);
  199. ID = Obj::HERO;
  200. tacticFormationEnabled = inTownGarrison = false;
  201. mana = UNINITIALIZED_MANA;
  202. movement = UNINITIALIZED_MOVEMENT;
  203. portrait = UNINITIALIZED_PORTRAIT;
  204. isStanding = true;
  205. moveDir = 4;
  206. level = 1;
  207. exp = 0xffffffff;
  208. visitedTown = nullptr;
  209. type = nullptr;
  210. boat = nullptr;
  211. commander = nullptr;
  212. sex = 0xff;
  213. secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
  214. }
  215. PlayerColor CGHeroInstance::getOwner() const
  216. {
  217. return tempOwner;
  218. }
  219. void CGHeroInstance::initHero(CRandomGenerator & rand, HeroTypeID SUBID)
  220. {
  221. subID = SUBID.getNum();
  222. initHero(rand);
  223. }
  224. void CGHeroInstance::setType(si32 ID, si32 subID)
  225. {
  226. assert(ID == Obj::HERO); // just in case
  227. type = VLC->heroh->objects[subID];
  228. portrait = type->imageIndex;
  229. CGObjectInstance::setType(ID, type->heroClass->getIndex()); // to find object handler we must use heroClass->id
  230. this->subID = subID; // after setType subID used to store unique hero identify id. Check issue 2277 for details
  231. randomizeArmy(type->heroClass->faction);
  232. }
  233. void CGHeroInstance::initHero(CRandomGenerator & rand)
  234. {
  235. assert(validTypes(true));
  236. if(!type)
  237. type = VLC->heroh->objects[subID];
  238. if (ID == Obj::HERO)
  239. appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, type->heroClass->getIndex())->getTemplates().front();
  240. if(!vstd::contains(spells, SpellID::PRESET)) //hero starts with a spell
  241. {
  242. for(auto spellID : type->spells)
  243. spells.insert(spellID);
  244. }
  245. else //remove placeholder
  246. spells -= SpellID::PRESET;
  247. if(!getArt(ArtifactPosition::MACH4) && !getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook) //no catapult means we haven't read pre-existent set -> use default rules for spellbook
  248. putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(ArtifactID::SPELLBOOK));
  249. if(!getArt(ArtifactPosition::MACH4))
  250. putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createNewArtifactInstance(ArtifactID::CATAPULT)); //everyone has a catapult
  251. if(portrait < 0 || portrait == 255)
  252. portrait = type->imageIndex;
  253. if(!hasBonus(Selector::sourceType()(Bonus::HERO_BASE_SKILL)))
  254. {
  255. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  256. {
  257. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(g), type->heroClass->primarySkillInitial[g]);
  258. }
  259. }
  260. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1)) //set secondary skills to default
  261. secSkills = type->secSkillsInit;
  262. if (sex == 0xFF)//sex is default
  263. sex = type->sex;
  264. setFormation(false);
  265. if (!stacksCount()) //standard army//initial army
  266. {
  267. initArmy(rand);
  268. }
  269. assert(validTypes());
  270. if (patrol.patrolling)
  271. patrol.initialPos = visitablePos();
  272. if(exp == 0xffffffff)
  273. {
  274. initExp(rand);
  275. }
  276. else
  277. {
  278. levelUpAutomatically(rand);
  279. }
  280. if (VLC->modh->modules.COMMANDERS && !commander)
  281. {
  282. commander = new CCommanderInstance(type->heroClass->commander->idNumber);
  283. commander->setArmyObj (castToArmyObj()); //TODO: separate function for setting commanders
  284. commander->giveStackExp (exp); //after our exp is set
  285. }
  286. if (mana < 0)
  287. mana = manaLimit();
  288. }
  289. void CGHeroInstance::initArmy(CRandomGenerator & rand, IArmyDescriptor * dst)
  290. {
  291. if(!dst)
  292. dst = this;
  293. int howManyStacks = 0; //how many stacks will hero receives <1 - 3>
  294. int pom = rand.nextInt(99);
  295. int warMachinesGiven = 0;
  296. if(pom < 9)
  297. howManyStacks = 1;
  298. else if(pom < 79)
  299. howManyStacks = 2;
  300. else
  301. howManyStacks = 3;
  302. vstd::amin(howManyStacks, type->initialArmy.size());
  303. for(int stackNo=0; stackNo < howManyStacks; stackNo++)
  304. {
  305. auto & stack = type->initialArmy[stackNo];
  306. int count = rand.nextInt(stack.minAmount, stack.maxAmount);
  307. const CCreature * creature = stack.creature.toCreature();
  308. if(creature == nullptr)
  309. {
  310. logGlobal->error("Hero %s has invalid creature with id %d in initial army", getNameTranslated(), stack.creature.toEnum());
  311. continue;
  312. }
  313. if(creature->warMachine != ArtifactID::NONE) //war machine
  314. {
  315. warMachinesGiven++;
  316. if(dst != this)
  317. continue;
  318. ArtifactID aid = creature->warMachine;
  319. const CArtifact * art = aid.toArtifact();
  320. if(art != nullptr && !art->possibleSlots.at(ArtBearer::HERO).empty())
  321. {
  322. //TODO: should we try another possible slots?
  323. ArtifactPosition slot = art->possibleSlots.at(ArtBearer::HERO).front();
  324. if(!getArt(slot))
  325. putArtifact(slot, CArtifactInstance::createNewArtifactInstance(aid));
  326. else
  327. logGlobal->warn("Hero %s already has artifact at %d, omitting giving artifact %d", getNameTranslated(), slot.toEnum(), aid.toEnum());
  328. }
  329. else
  330. {
  331. logGlobal->error("Hero %s has invalid war machine in initial army", getNameTranslated());
  332. }
  333. }
  334. else
  335. {
  336. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  337. }
  338. }
  339. }
  340. CGHeroInstance::~CGHeroInstance()
  341. {
  342. commander.dellNull();
  343. }
  344. bool CGHeroInstance::needsLastStack() const
  345. {
  346. return true;
  347. }
  348. void CGHeroInstance::onHeroVisit(const CGHeroInstance * h) const
  349. {
  350. if(h == this) return; //exclude potential self-visiting
  351. if (ID == Obj::HERO)
  352. {
  353. if( cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner)) //our or ally hero
  354. {
  355. //exchange
  356. cb->heroExchange(h->id, id);
  357. }
  358. else //battle
  359. {
  360. if(visitedTown) //we're in town
  361. visitedTown->onHeroVisit(h); //town will handle attacking
  362. else
  363. cb->startBattleI(h, this);
  364. }
  365. }
  366. else if(ID == Obj::PRISON)
  367. {
  368. int txt_id;
  369. if (cb->getHeroCount(h->tempOwner, false) < VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)//free hero slot
  370. {
  371. //update hero parameters
  372. SetMovePoints smp;
  373. smp.hid = id;
  374. smp.val = maxMovePoints (true); //TODO: hota prison on water?
  375. cb->setMovePoints (&smp);
  376. cb->setManaPoints (id, manaLimit());
  377. cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
  378. cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player
  379. txt_id = 102;
  380. }
  381. else //already 8 wandering heroes
  382. {
  383. txt_id = 103;
  384. }
  385. showInfoDialog(h,txt_id);
  386. }
  387. }
  388. std::string CGHeroInstance::getObjectName() const
  389. {
  390. if(ID != Obj::PRISON)
  391. {
  392. std::string hoverName = VLC->generaltexth->allTexts[15];
  393. boost::algorithm::replace_first(hoverName,"%s",getNameTranslated());
  394. boost::algorithm::replace_first(hoverName,"%s", type->heroClass->getNameTranslated());
  395. return hoverName;
  396. }
  397. else
  398. return CGObjectInstance::getObjectName();
  399. }
  400. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  401. {
  402. return type->heroClass->isMagicHero() ? 3 : 4;
  403. }
  404. ui8 CGHeroInstance::maxlevelsToWisdom() const
  405. {
  406. return type->heroClass->isMagicHero() ? 3 : 6;
  407. }
  408. CGHeroInstance::SecondarySkillsInfo::SecondarySkillsInfo()
  409. {
  410. rand.setSeed(0);
  411. magicSchoolCounter = 1;
  412. wisdomCounter = 1;
  413. }
  414. void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
  415. {
  416. magicSchoolCounter = 1;
  417. }
  418. void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
  419. {
  420. wisdomCounter = 1;
  421. }
  422. void CGHeroInstance::initObj(CRandomGenerator & rand)
  423. {
  424. blockVisit = true;
  425. if(!type)
  426. initHero(rand); //TODO: set up everything for prison before specialties are configured
  427. skillsInfo.rand.setSeed(rand.nextInt());
  428. skillsInfo.resetMagicSchoolCounter();
  429. skillsInfo.resetWisdomCounter();
  430. if (ID != Obj::PRISON)
  431. {
  432. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  433. auto customApp = VLC->objtypeh->getHandlerFor(ID, type->heroClass->getIndex())->getOverride(terrain, this);
  434. if (customApp)
  435. appearance = customApp;
  436. }
  437. //copy active (probably growing) bonuses from hero prototype to hero object
  438. for(std::shared_ptr<Bonus> b : type->specialty)
  439. addNewBonus(b);
  440. //dito for old-style bonuses -> compatibility for old savegames
  441. for(SSpecialtyBonus & sb : type->specialtyDeprecated)
  442. for(std::shared_ptr<Bonus> b : sb.bonuses)
  443. addNewBonus(b);
  444. for(SSpecialtyInfo & spec : type->specDeprecated)
  445. for(std::shared_ptr<Bonus> b : SpecialtyInfoToBonuses(spec, type->getIndex()))
  446. addNewBonus(b);
  447. //initialize bonuses
  448. recreateSecondarySkillsBonuses();
  449. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  450. }
  451. void CGHeroInstance::recreateSecondarySkillsBonuses()
  452. {
  453. auto secondarySkillsBonuses = getBonuses(Selector::sourceType()(Bonus::SECONDARY_SKILL));
  454. for(auto bonus : *secondarySkillsBonuses)
  455. removeBonus(bonus);
  456. for(auto skill_info : secSkills)
  457. if(skill_info.second > 0)
  458. updateSkillBonus(SecondarySkill(skill_info.first), skill_info.second);
  459. }
  460. void CGHeroInstance::updateSkillBonus(SecondarySkill which, int val)
  461. {
  462. removeBonuses(Selector::source(Bonus::SECONDARY_SKILL, which));
  463. auto skillBonus = (*VLC->skillh)[which]->at(val).effects;
  464. for (auto b : skillBonus)
  465. addNewBonus(std::make_shared<Bonus>(*b));
  466. }
  467. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  468. {
  469. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  470. setStackCount(SlotID(0), val);
  471. }
  472. double CGHeroInstance::getFightingStrength() const
  473. {
  474. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  475. }
  476. double CGHeroInstance::getMagicStrength() const
  477. {
  478. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::KNOWLEDGE)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::SPELL_POWER)));
  479. }
  480. double CGHeroInstance::getHeroStrength() const
  481. {
  482. return sqrt(pow(getFightingStrength(), 2.0) * pow(getMagicStrength(), 2.0));
  483. }
  484. ui64 CGHeroInstance::getTotalStrength() const
  485. {
  486. double ret = getFightingStrength() * getArmyStrength();
  487. return (ui64) ret;
  488. }
  489. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  490. {
  491. return (TExpType)(exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0);
  492. }
  493. int32_t CGHeroInstance::getCasterUnitId() const
  494. {
  495. return -1; //TODO: special value for attacker/defender hero
  496. }
  497. int32_t CGHeroInstance::getSpellSchoolLevel(const spells::Spell * spell, int32_t * outSelectedSchool) const
  498. {
  499. int32_t skill = -1; //skill level
  500. spell->forEachSchool([&, this](const spells::SchoolInfo & cnf, bool & stop)
  501. {
  502. int32_t thisSchool = std::max<int32_t>(
  503. valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, cnf.skill),
  504. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << ((ui8)cnf.id))); //FIXME: Bonus shouldn't be additive (Witchking Artifacts : Crown of Skies)
  505. if(thisSchool > skill)
  506. {
  507. skill = thisSchool;
  508. if(outSelectedSchool)
  509. *outSelectedSchool = (ui8)cnf.id;
  510. }
  511. });
  512. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  513. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->getIndex())); //given by artifact or other effect
  514. vstd::amax(skill, 0); //in case we don't know any school
  515. vstd::amin(skill, 3);
  516. return skill;
  517. }
  518. int64_t CGHeroInstance::getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const
  519. {
  520. //applying sorcery secondary skill
  521. base = (int64_t)(base * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0);
  522. base = (int64_t)(base * (100 + valOfBonuses(Bonus::SPELL_DAMAGE) + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0);
  523. int maxSchoolBonus = 0;
  524. spell->forEachSchool([&maxSchoolBonus, this](const spells::SchoolInfo & cnf, bool & stop)
  525. {
  526. vstd::amax(maxSchoolBonus, valOfBonuses(cnf.damagePremyBonus));
  527. });
  528. base = (int64_t)(base * (100 + maxSchoolBonus) / 100.0);
  529. if(affectedStack && affectedStack->creatureLevel() > 0) //Hero specials like Solmyr, Deemer
  530. base = (int64_t)(base * double(100 + valOfBonuses(Bonus::SPECIAL_SPELL_LEV, spell->getIndex()) / affectedStack->creatureLevel()) / 100.0);
  531. return base;
  532. }
  533. int64_t CGHeroInstance::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
  534. {
  535. base = (int64_t)(base * (100 + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0);
  536. return base;
  537. }
  538. int32_t CGHeroInstance::getEffectLevel(const spells::Spell * spell) const
  539. {
  540. if(hasBonusOfType(Bonus::MAXED_SPELL, spell->getIndex()))
  541. return 3;//todo: recheck specialty from where this bonus is. possible bug
  542. else
  543. return getSpellSchoolLevel(spell);
  544. }
  545. int32_t CGHeroInstance::getEffectPower(const spells::Spell * spell) const
  546. {
  547. return getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  548. }
  549. int32_t CGHeroInstance::getEnchantPower(const spells::Spell * spell) const
  550. {
  551. return getPrimSkillLevel(PrimarySkill::SPELL_POWER) + valOfBonuses(Bonus::SPELL_DURATION);
  552. }
  553. int64_t CGHeroInstance::getEffectValue(const spells::Spell * spell) const
  554. {
  555. return 0;
  556. }
  557. PlayerColor CGHeroInstance::getCasterOwner() const
  558. {
  559. return tempOwner;
  560. }
  561. void CGHeroInstance::getCasterName(MetaString & text) const
  562. {
  563. //FIXME: use local name, MetaString need access to gamestate as hero name is part of map object
  564. text.addReplacement(getNameTranslated());
  565. }
  566. void CGHeroInstance::getCastDescription(const spells::Spell * spell, const std::vector<const battle::Unit *> & attacked, MetaString & text) const
  567. {
  568. const bool singleTarget = attacked.size() == 1;
  569. const int textIndex = singleTarget ? 195 : 196;
  570. text.addTxt(MetaString::GENERAL_TXT, textIndex);
  571. getCasterName(text);
  572. text.addReplacement(MetaString::SPELL_NAME, spell->getIndex());
  573. if(singleTarget)
  574. attacked.at(0)->addNameReplacement(text, true);
  575. }
  576. void CGHeroInstance::spendMana(ServerCallback * server, const int spellCost) const
  577. {
  578. if(spellCost != 0)
  579. {
  580. SetMana sm;
  581. sm.absolute = false;
  582. sm.hid = id;
  583. sm.val = -spellCost;
  584. server->apply(&sm);
  585. }
  586. }
  587. bool CGHeroInstance::canCastThisSpell(const spells::Spell * spell) const
  588. {
  589. const bool isAllowed = IObjectInterface::cb->isAllowed(0, spell->getIndex());
  590. const bool inSpellBook = vstd::contains(spells, spell->getId()) && hasSpellbook();
  591. const bool specificBonus = hasBonusOfType(Bonus::SPELL, spell->getIndex());
  592. bool schoolBonus = false;
  593. spell->forEachSchool([this, &schoolBonus](const spells::SchoolInfo & cnf, bool & stop)
  594. {
  595. if(hasBonusOfType(cnf.knoledgeBonus))
  596. {
  597. schoolBonus = stop = true;
  598. }
  599. });
  600. const bool levelBonus = hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->getLevel());
  601. if(spell->isSpecial())
  602. {
  603. if(inSpellBook)
  604. {//hero has this spell in spellbook
  605. logGlobal->error("Special spell %s in spellbook.", spell->getNameTranslated());
  606. }
  607. return specificBonus;
  608. }
  609. else if(!isAllowed)
  610. {
  611. if(inSpellBook)
  612. {
  613. //hero has this spell in spellbook
  614. //it is normal if set in map editor, but trace it to possible debug of magic guild
  615. logGlobal->trace("Banned spell %s in spellbook.", spell->getNameTranslated());
  616. }
  617. return inSpellBook || specificBonus || schoolBonus || levelBonus;
  618. }
  619. else
  620. {
  621. return inSpellBook || schoolBonus || specificBonus || levelBonus;
  622. }
  623. }
  624. bool CGHeroInstance::canLearnSpell(const spells::Spell * spell) const
  625. {
  626. if(!hasSpellbook())
  627. return false;
  628. if(spell->getLevel() > maxSpellLevel()) //not enough wisdom
  629. return false;
  630. if(vstd::contains(spells, spell->getId()))//already known
  631. return false;
  632. if(spell->isSpecial())
  633. {
  634. logGlobal->warn("Hero %s try to learn special spell %s", nodeName(), spell->getNameTranslated());
  635. return false;//special spells can not be learned
  636. }
  637. if(spell->isCreatureAbility())
  638. {
  639. logGlobal->warn("Hero %s try to learn creature spell %s", nodeName(), spell->getNameTranslated());
  640. return false;//creature abilities can not be learned
  641. }
  642. if(!IObjectInterface::cb->isAllowed(0, spell->getIndex()))
  643. {
  644. logGlobal->warn("Hero %s try to learn banned spell %s", nodeName(), spell->getNameTranslated());
  645. return false;//banned spells should not be learned
  646. }
  647. return true;
  648. }
  649. /**
  650. * Calculates what creatures and how many to be raised from a battle.
  651. * @param battleResult The results of the battle.
  652. * @return Returns a pair with the first value indicating the ID of the creature
  653. * type and second value the amount. Both values are returned as -1 if necromancy
  654. * could not be applied.
  655. */
  656. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  657. {
  658. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  659. // need skill or cloak of undead king - lesser artifacts don't work without skill
  660. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  661. {
  662. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY) / 100.0;
  663. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  664. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  665. // figure out what to raise - pick strongest creature meeting requirements
  666. CreatureID creatureTypeRaised = CreatureID::SKELETON;
  667. int requiredCasualtyLevel = 1;
  668. TConstBonusListPtr improvedNecromancy = getBonuses(Selector::type()(Bonus::IMPROVED_NECROMANCY));
  669. if(!improvedNecromancy->empty())
  670. {
  671. auto getCreatureID = [necromancyLevel](std::shared_ptr<Bonus> bonus) -> CreatureID
  672. {
  673. const CreatureID legacyTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  674. return CreatureID(bonus->subtype >= 0 ? bonus->subtype : legacyTypes[necromancyLevel]);
  675. };
  676. int maxCasualtyLevel = 1;
  677. for(auto & casualty : casualties)
  678. vstd::amax(maxCasualtyLevel, VLC->creh->objects[casualty.first]->level);
  679. // pick best bonus available
  680. std::shared_ptr<Bonus> topPick;
  681. for(std::shared_ptr<Bonus> newPick : *improvedNecromancy)
  682. {
  683. // addInfo[0] = required necromancy skill, addInfo[1] = required casualty level
  684. if(newPick->additionalInfo[0] > necromancyLevel || newPick->additionalInfo[1] > maxCasualtyLevel)
  685. continue;
  686. if(!topPick)
  687. {
  688. topPick = newPick;
  689. }
  690. else
  691. {
  692. auto quality = [getCreatureID](std::shared_ptr<Bonus> pick) -> std::tuple<int, int, int>
  693. {
  694. const CCreature * c = VLC->creh->objects[getCreatureID(pick)];
  695. return std::tuple<int, int, int> {c->level, static_cast<int>(c->cost.marketValue()), -pick->additionalInfo[1]};
  696. };
  697. if(quality(topPick) < quality(newPick))
  698. topPick = newPick;
  699. }
  700. }
  701. if(topPick)
  702. {
  703. creatureTypeRaised = getCreatureID(topPick);
  704. requiredCasualtyLevel = std::max(topPick->additionalInfo[1], 1);
  705. }
  706. }
  707. // raise upgraded creature (at 2/3 rate) if no space available otherwise
  708. if(getSlotFor(creatureTypeRaised) == SlotID())
  709. {
  710. for(CreatureID upgraded : VLC->creh->objects[creatureTypeRaised]->upgrades)
  711. {
  712. if(getSlotFor(upgraded) != SlotID())
  713. {
  714. creatureTypeRaised = upgraded;
  715. necromancySkill *= 2/3.0;
  716. break;
  717. }
  718. }
  719. }
  720. // calculate number of creatures raised - low level units contribute at 50% rate
  721. const double raisedUnitHealth = VLC->creh->objects[creatureTypeRaised]->MaxHealth();
  722. double raisedUnits = 0;
  723. for(auto & casualty : casualties)
  724. {
  725. const CCreature * c = VLC->creh->objects[casualty.first];
  726. double raisedFromCasualty = std::min(c->MaxHealth() / raisedUnitHealth, 1.0) * casualty.second * necromancySkill;
  727. if(c->level < requiredCasualtyLevel)
  728. raisedFromCasualty *= 0.5;
  729. raisedUnits += raisedFromCasualty;
  730. }
  731. return CStackBasicDescriptor(creatureTypeRaised, std::max(static_cast<int>(raisedUnits), 1));
  732. }
  733. return CStackBasicDescriptor();
  734. }
  735. /**
  736. * Show the necromancy dialog with information about units raised.
  737. * @param raisedStack Pair where the first element represents ID of the raised creature
  738. * and the second element the amount.
  739. */
  740. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack, CRandomGenerator & rand) const
  741. {
  742. InfoWindow iw;
  743. iw.soundID = soundBase::pickup01 + rand.nextInt(6);
  744. iw.player = tempOwner;
  745. iw.components.push_back(Component(raisedStack));
  746. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  747. {
  748. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  749. iw.text.addReplacement(raisedStack.count);
  750. }
  751. else // Practicing the dark arts of necromancy, ... (singular)
  752. {
  753. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  754. }
  755. iw.text.addReplacement(raisedStack);
  756. cb->showInfoDialog(&iw);
  757. }
  758. /*
  759. int3 CGHeroInstance::getSightCenter() const
  760. {
  761. return getPosition(false);
  762. }*/
  763. int CGHeroInstance::getSightRadius() const
  764. {
  765. return 5 + valOfBonuses(Bonus::SIGHT_RADIOUS); // scouting gives SIGHT_RADIUS bonus
  766. }
  767. si32 CGHeroInstance::manaRegain() const
  768. {
  769. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  770. return manaLimit();
  771. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::MYSTICISM) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  772. }
  773. si32 CGHeroInstance::getManaNewTurn() const
  774. {
  775. if(visitedTown && visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  776. {
  777. //if hero starts turn in town with mage guild - restore all mana
  778. return std::max(mana, manaLimit());
  779. }
  780. si32 res = mana + manaRegain();
  781. res = std::min(res, manaLimit());
  782. res = std::max(res, mana);
  783. res = std::max(res, 0);
  784. return res;
  785. }
  786. // /**
  787. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  788. // * or discards it if it cannot be equipped.
  789. // */
  790. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  791. // {
  792. // CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  793. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  794. // ai->putAt(this, ai->firstAvailableSlot(this));
  795. // }
  796. int CGHeroInstance::getBoatType() const
  797. {
  798. switch(type->heroClass->getAlignment())
  799. {
  800. case EAlignment::GOOD:
  801. return 1;
  802. case EAlignment::EVIL:
  803. return 0;
  804. case EAlignment::NEUTRAL:
  805. return 2;
  806. default:
  807. throw std::runtime_error("Wrong alignment!");
  808. }
  809. }
  810. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  811. {
  812. // FIXME: Offsets need to be fixed once we get rid of convertPosition
  813. // Check issue 515 for details
  814. offsets =
  815. {
  816. 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)
  817. };
  818. }
  819. int32_t CGHeroInstance::getSpellCost(const spells::Spell * sp) const
  820. {
  821. return sp->getCost(getSpellSchoolLevel(sp));
  822. }
  823. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  824. {
  825. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  826. .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL))));
  827. addNewBonus(std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  828. }
  829. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  830. {
  831. return type->heroClass->getAlignment();
  832. }
  833. void CGHeroInstance::initExp(CRandomGenerator & rand)
  834. {
  835. exp = rand.nextInt(40, 89);
  836. }
  837. std::string CGHeroInstance::nodeName() const
  838. {
  839. return "Hero " + getNameTextID();
  840. }
  841. std::string CGHeroInstance::getNameTranslated() const
  842. {
  843. return VLC->generaltexth->translate(getNameTextID());
  844. }
  845. std::string CGHeroInstance::getNameTextID() const
  846. {
  847. if (!nameCustom.empty())
  848. return nameCustom;
  849. if (type)
  850. return type->getNameTextID();
  851. assert(0);
  852. return "";
  853. }
  854. std::string CGHeroInstance::getBiographyTranslated() const
  855. {
  856. return VLC->generaltexth->translate(getBiographyTextID());
  857. }
  858. std::string CGHeroInstance::getBiographyTextID() const
  859. {
  860. if (!biographyCustom.empty())
  861. return biographyCustom;
  862. if (type)
  863. return type->getBiographyTextID();
  864. assert(0);
  865. return "";
  866. }
  867. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  868. {
  869. assert(!getArt(pos));
  870. art->putAt(ArtifactLocation(this, pos));
  871. }
  872. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  873. {
  874. putArtifact(art->firstBackpackSlot(this), art);
  875. }
  876. bool CGHeroInstance::hasSpellbook() const
  877. {
  878. return getArt(ArtifactPosition::SPELLBOOK);
  879. }
  880. void CGHeroInstance::addSpellToSpellbook(SpellID spell)
  881. {
  882. spells.insert(spell);
  883. }
  884. void CGHeroInstance::removeSpellFromSpellbook(SpellID spell)
  885. {
  886. spells.erase(spell);
  887. }
  888. bool CGHeroInstance::spellbookContainsSpell(SpellID spell) const
  889. {
  890. return vstd::contains(spells, spell);
  891. }
  892. void CGHeroInstance::removeSpellbook()
  893. {
  894. spells.clear();
  895. if(hasSpellbook())
  896. {
  897. ArtifactLocation(this, ArtifactPosition(ArtifactPosition::SPELLBOOK)).removeArtifact();
  898. }
  899. }
  900. const std::set<SpellID> & CGHeroInstance::getSpellsInSpellbook() const
  901. {
  902. return spells;
  903. }
  904. int CGHeroInstance::maxSpellLevel() const
  905. {
  906. return std::min(GameConstants::SPELL_LEVELS, 2 + valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::WISDOM)));
  907. }
  908. void CGHeroInstance::deserializationFix()
  909. {
  910. artDeserializationFix(this);
  911. }
  912. CBonusSystemNode * CGHeroInstance::whereShouldBeAttachedOnSiege(const bool isBattleOutsideTown) const
  913. {
  914. if(!visitedTown)
  915. return nullptr;
  916. return isBattleOutsideTown ? (CBonusSystemNode *)(& visitedTown->townAndVis)
  917. : (CBonusSystemNode *)(visitedTown.get());
  918. }
  919. CBonusSystemNode * CGHeroInstance::whereShouldBeAttachedOnSiege(CGameState * gs)
  920. {
  921. if(visitedTown)
  922. return whereShouldBeAttachedOnSiege(visitedTown->isBattleOutsideTown(this));
  923. return &CArmedInstance::whereShouldBeAttached(gs);
  924. }
  925. CBonusSystemNode & CGHeroInstance::whereShouldBeAttached(CGameState * gs)
  926. {
  927. if(visitedTown)
  928. {
  929. if(inTownGarrison)
  930. return *visitedTown;
  931. else
  932. return visitedTown->townAndVis;
  933. }
  934. else
  935. return CArmedInstance::whereShouldBeAttached(gs);
  936. }
  937. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const
  938. {
  939. int ret = 0; //take all MPs by default
  940. bool localTi = false;
  941. if(!ti)
  942. {
  943. localTi = true;
  944. ti = new TurnInfo(this);
  945. }
  946. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL);
  947. int mp2 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  948. if(ti->hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  949. ret = static_cast<int>((MPsBefore - basicCost) * static_cast<double>(mp1) / mp2);
  950. if(localTi)
  951. delete ti;
  952. return ret;
  953. }
  954. EDiggingStatus CGHeroInstance::diggingStatus() const
  955. {
  956. if((int)movement < maxMovePoints(true))
  957. return EDiggingStatus::LACK_OF_MOVEMENT;
  958. return cb->getTile(visitablePos())->getDiggingStatus();
  959. }
  960. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  961. {
  962. return ArtBearer::HERO;
  963. }
  964. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
  965. {
  966. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  967. if (!skillsInfo.wisdomCounter)
  968. {
  969. if (canLearnSkill(SecondarySkill::WISDOM))
  970. obligatorySkills.push_back(SecondarySkill::WISDOM);
  971. }
  972. if (!skillsInfo.magicSchoolCounter)
  973. {
  974. std::vector<SecondarySkill> ss =
  975. {
  976. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC
  977. };
  978. std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());
  979. for (auto skill : ss)
  980. {
  981. if (canLearnSkill(skill)) //only schools hero doesn't know yet
  982. {
  983. obligatorySkills.push_back(skill);
  984. break; //only one
  985. }
  986. }
  987. }
  988. std::vector<SecondarySkill> skills;
  989. //picking sec. skills for choice
  990. std::set<SecondarySkill> basicAndAdv, expert, none;
  991. for(int i = 0; i < VLC->skillh->size(); i++)
  992. if (canLearnSkill(SecondarySkill(i)))
  993. none.insert(SecondarySkill(i));
  994. for(auto & elem : secSkills)
  995. {
  996. if(elem.second < SecSkillLevel::EXPERT)
  997. basicAndAdv.insert(elem.first);
  998. else
  999. expert.insert(elem.first);
  1000. none.erase(elem.first);
  1001. }
  1002. for (auto s : obligatorySkills) //don't duplicate them
  1003. {
  1004. none.erase (s);
  1005. basicAndAdv.erase (s);
  1006. expert.erase (s);
  1007. }
  1008. //first offered skill:
  1009. // 1) give obligatory skill
  1010. // 2) give any other new skill
  1011. // 3) upgrade existing
  1012. if (canLearnSkill() && obligatorySkills.size() > 0)
  1013. {
  1014. skills.push_back (obligatorySkills[0]);
  1015. }
  1016. else if(none.size() && canLearnSkill()) //hero have free skill slot
  1017. {
  1018. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
  1019. none.erase(skills.back());
  1020. }
  1021. else if(!basicAndAdv.empty())
  1022. {
  1023. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
  1024. basicAndAdv.erase(skills.back());
  1025. }
  1026. //second offered skill:
  1027. //1) upgrade existing
  1028. //2) give obligatory skill
  1029. //3) give any other new skill
  1030. if(!basicAndAdv.empty())
  1031. {
  1032. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
  1033. skills.push_back(s);
  1034. basicAndAdv.erase(s);
  1035. }
  1036. else if (canLearnSkill() && obligatorySkills.size() > 1)
  1037. {
  1038. skills.push_back (obligatorySkills[1]);
  1039. }
  1040. else if(none.size() && canLearnSkill())
  1041. {
  1042. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
  1043. none.erase(skills.back());
  1044. }
  1045. if (skills.size() == 2) // Fix for #1868 to avoid changing logic (possibly causing bugs in process)
  1046. std::swap(skills[0], skills[1]);
  1047. return skills;
  1048. }
  1049. PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill(CRandomGenerator & rand) const
  1050. {
  1051. assert(gainsLevel());
  1052. int randomValue = rand.nextInt(99), pom = 0, primarySkill = 0;
  1053. const auto isLowLevelHero = level < GameConstants::HERO_HIGH_LEVEL;
  1054. const auto & skillChances = isLowLevelHero ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;
  1055. for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
  1056. {
  1057. pom += skillChances[primarySkill];
  1058. if(randomValue < pom)
  1059. {
  1060. break;
  1061. }
  1062. }
  1063. if(primarySkill >= GameConstants::PRIMARY_SKILLS)
  1064. {
  1065. primarySkill = rand.nextInt(GameConstants::PRIMARY_SKILLS - 1);
  1066. logGlobal->error("Wrong values in primarySkill%sLevel for hero class %s", isLowLevelHero ? "Low" : "High", type->heroClass->getNameTranslated());
  1067. randomValue = 100 / GameConstants::PRIMARY_SKILLS;
  1068. }
  1069. logGlobal->trace("The hero gets the primary skill %d with a probability of %d %%.", primarySkill, randomValue);
  1070. return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
  1071. }
  1072. boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(CRandomGenerator & rand) const
  1073. {
  1074. assert(gainsLevel());
  1075. boost::optional<SecondarySkill> chosenSecondarySkill;
  1076. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1077. if(!proposedSecondarySkills.empty())
  1078. {
  1079. std::vector<SecondarySkill> learnedSecondarySkills;
  1080. for(auto secondarySkill : proposedSecondarySkills)
  1081. {
  1082. if(getSecSkillLevel(secondarySkill) > 0)
  1083. {
  1084. learnedSecondarySkills.push_back(secondarySkill);
  1085. }
  1086. }
  1087. if(learnedSecondarySkills.empty())
  1088. {
  1089. // there are only new skills to learn, so choose anyone of them
  1090. chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand));
  1091. }
  1092. else
  1093. {
  1094. // preferably upgrade a already learned secondary skill
  1095. chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand));
  1096. }
  1097. }
  1098. return chosenSecondarySkill;
  1099. }
  1100. void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
  1101. {
  1102. if(primarySkill < PrimarySkill::EXPERIENCE)
  1103. {
  1104. auto skill = getBonusLocalFirst(Selector::type()(Bonus::PRIMARY_SKILL)
  1105. .And(Selector::subtype()(primarySkill))
  1106. .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)));
  1107. assert(skill);
  1108. if(abs)
  1109. {
  1110. skill->val = static_cast<si32>(value);
  1111. }
  1112. else
  1113. {
  1114. skill->val += static_cast<si32>(value);
  1115. }
  1116. CBonusSystemNode::treeHasChanged();
  1117. }
  1118. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1119. {
  1120. if(abs)
  1121. {
  1122. exp = value;
  1123. }
  1124. else
  1125. {
  1126. exp += value;
  1127. }
  1128. }
  1129. }
  1130. bool CGHeroInstance::gainsLevel() const
  1131. {
  1132. return exp >= static_cast<TExpType>(VLC->heroh->reqExp(level+1));
  1133. }
  1134. void CGHeroInstance::levelUp(std::vector<SecondarySkill> skills)
  1135. {
  1136. ++level;
  1137. //deterministic secondary skills
  1138. skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
  1139. skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
  1140. if(vstd::contains(skills, SecondarySkill::WISDOM))
  1141. {
  1142. skillsInfo.resetWisdomCounter();
  1143. }
  1144. SecondarySkill spellSchools[] = {
  1145. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
  1146. for(auto skill : spellSchools)
  1147. {
  1148. if(vstd::contains(skills, skill))
  1149. {
  1150. skillsInfo.resetMagicSchoolCounter();
  1151. break;
  1152. }
  1153. }
  1154. //update specialty and other bonuses that scale with level
  1155. treeHasChanged();
  1156. }
  1157. void CGHeroInstance::levelUpAutomatically(CRandomGenerator & rand)
  1158. {
  1159. while(gainsLevel())
  1160. {
  1161. const auto primarySkill = nextPrimarySkill(rand);
  1162. setPrimarySkill(primarySkill, 1, false);
  1163. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1164. const auto secondarySkill = nextSecondarySkill(rand);
  1165. if(secondarySkill)
  1166. {
  1167. setSecSkillLevel(*secondarySkill, 1, false);
  1168. }
  1169. //TODO why has the secondary skills to be passed to the method?
  1170. levelUp(proposedSecondarySkills);
  1171. }
  1172. }
  1173. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, const int subtype) const
  1174. {
  1175. //VISIONS spell support
  1176. const std::string cached = boost::to_string((boost::format("type_%d__subtype_%d") % Bonus::VISIONS % subtype));
  1177. const int visionsMultiplier = valOfBonuses(Selector::typeSubtype(Bonus::VISIONS,subtype), cached);
  1178. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1179. if (visionsMultiplier > 0)
  1180. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1181. const int distance = static_cast<int>(target->pos.dist2d(visitablePos()));
  1182. //logGlobal->debug(boost::to_string(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1183. return (distance < visionsRange) && (target->pos.z == pos.z);
  1184. }
  1185. std::string CGHeroInstance::getHeroTypeName() const
  1186. {
  1187. if(ID == Obj::HERO || ID == Obj::PRISON)
  1188. {
  1189. if(type)
  1190. {
  1191. return type->getJsonKey();
  1192. }
  1193. else
  1194. {
  1195. return VLC->heroh->objects[subID]->getJsonKey();
  1196. }
  1197. }
  1198. return "";
  1199. }
  1200. void CGHeroInstance::afterAddToMap(CMap * map)
  1201. {
  1202. if(ID == Obj::HERO)
  1203. map->heroesOnMap.push_back(this);
  1204. }
  1205. void CGHeroInstance::afterRemoveFromMap(CMap* map)
  1206. {
  1207. if (ID == Obj::HERO)
  1208. vstd::erase_if_present(map->heroesOnMap, this);
  1209. }
  1210. void CGHeroInstance::setHeroTypeName(const std::string & identifier)
  1211. {
  1212. if(ID == Obj::HERO || ID == Obj::PRISON)
  1213. {
  1214. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "hero", identifier);
  1215. if(rawId)
  1216. subID = rawId.get();
  1217. else
  1218. {
  1219. throw std::runtime_error("Couldn't resolve hero identifier " + identifier);
  1220. }
  1221. }
  1222. }
  1223. void CGHeroInstance::updateFrom(const JsonNode & data)
  1224. {
  1225. CGObjectInstance::updateFrom(data);
  1226. }
  1227. void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
  1228. {
  1229. handler.serializeString("biography", biographyCustom);
  1230. handler.serializeInt("experience", exp, 0);
  1231. if(!handler.saving && exp != 0xffffffff) //do not gain levels if experience is not initialized
  1232. {
  1233. while (gainsLevel())
  1234. {
  1235. ++level;
  1236. }
  1237. }
  1238. handler.serializeString("name", nameCustom);
  1239. handler.serializeBool<ui8>("female", sex, 1, 0, 0xFF);
  1240. {
  1241. const int legacyHeroes = static_cast<int>(VLC->modh->settings.data["textData"]["hero"].Integer());
  1242. const int moddedStart = legacyHeroes + GameConstants::HERO_PORTRAIT_SHIFT;
  1243. if(handler.saving)
  1244. {
  1245. if(portrait >= 0)
  1246. {
  1247. if(portrait < legacyHeroes || portrait >= moddedStart)
  1248. handler.serializeId<si32, si32, HeroTypeID>("portrait", portrait, -1);
  1249. else
  1250. handler.serializeInt("portrait", portrait, -1);
  1251. }
  1252. }
  1253. else
  1254. {
  1255. const JsonNode & portraitNode = handler.getCurrent()["portrait"];
  1256. if(portraitNode.getType() == JsonNode::JsonType::DATA_STRING)
  1257. handler.serializeId<si32, si32, HeroTypeID>("portrait", portrait, -1);
  1258. else
  1259. handler.serializeInt("portrait", portrait, -1);
  1260. }
  1261. }
  1262. //primary skills
  1263. if(handler.saving)
  1264. {
  1265. const bool haveSkills = hasBonus(Selector::type()(Bonus::PRIMARY_SKILL).And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)));
  1266. if(haveSkills)
  1267. {
  1268. auto primarySkills = handler.enterStruct("primarySkills");
  1269. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1270. {
  1271. int value = valOfBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, i).And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)));
  1272. handler.serializeInt(PrimarySkill::names[i], value, 0);
  1273. }
  1274. }
  1275. }
  1276. else
  1277. {
  1278. auto primarySkills = handler.enterStruct("primarySkills");
  1279. if(handler.getCurrent().getType() == JsonNode::JsonType::DATA_STRUCT)
  1280. {
  1281. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1282. {
  1283. int value = 0;
  1284. handler.serializeInt(PrimarySkill::names[i], value, 0);
  1285. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(i), value);
  1286. }
  1287. }
  1288. }
  1289. //secondary skills
  1290. if(handler.saving)
  1291. {
  1292. //does hero have default skills?
  1293. bool defaultSkills = false;
  1294. bool normalSkills = false;
  1295. for(const auto & p : secSkills)
  1296. {
  1297. if(p.first == SecondarySkill(SecondarySkill::DEFAULT))
  1298. defaultSkills = true;
  1299. else
  1300. normalSkills = true;
  1301. }
  1302. if(defaultSkills && normalSkills)
  1303. logGlobal->error("Mixed default and normal secondary skills");
  1304. //in json default skills means no field/null
  1305. if(!defaultSkills)
  1306. {
  1307. //enter structure here as handler initialize it
  1308. auto secondarySkills = handler.enterStruct("secondarySkills");
  1309. for(auto & p : secSkills)
  1310. {
  1311. const si32 rawId = p.first.num;
  1312. if(rawId < 0 || rawId >= VLC->skillh->size())
  1313. logGlobal->error("Invalid secondary skill %d", rawId);
  1314. handler.serializeEnum((*VLC->skillh)[SecondarySkill(rawId)]->getJsonKey(), p.second, 0, NSecondarySkill::levels);
  1315. }
  1316. }
  1317. }
  1318. else
  1319. {
  1320. auto secondarySkills = handler.enterStruct("secondarySkills");
  1321. const JsonNode & skillMap = handler.getCurrent();
  1322. secSkills.clear();
  1323. if(skillMap.getType() == JsonNode::JsonType::DATA_NULL)
  1324. {
  1325. secSkills.push_back(std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1));
  1326. }
  1327. else
  1328. {
  1329. for(const auto & p : skillMap.Struct())
  1330. {
  1331. const std::string skillId = p.first;
  1332. const std::string levelId = p.second.String();
  1333. const int rawId = CSkillHandler::decodeSkill(skillId);
  1334. if(rawId < 0)
  1335. {
  1336. logGlobal->error("Invalid secondary skill %s", skillId);
  1337. continue;
  1338. }
  1339. const int level = vstd::find_pos(NSecondarySkill::levels, levelId);
  1340. if(level < 0)
  1341. {
  1342. logGlobal->error("Invalid secondary skill level%s", levelId);
  1343. continue;
  1344. }
  1345. secSkills.push_back(std::pair<SecondarySkill,ui8>(SecondarySkill(rawId), level));
  1346. }
  1347. }
  1348. }
  1349. handler.serializeIdArray("spellBook", spells);
  1350. if(handler.saving)
  1351. CArtifactSet::serializeJsonArtifacts(handler, "artifacts", nullptr);
  1352. }
  1353. void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1354. {
  1355. serializeCommonOptions(handler);
  1356. serializeJsonOwner(handler);
  1357. if(ID == Obj::HERO || ID == Obj::PRISON)
  1358. {
  1359. std::string typeName;
  1360. if(handler.saving)
  1361. typeName = getHeroTypeName();
  1362. handler.serializeString("type", typeName);
  1363. if(!handler.saving)
  1364. setHeroTypeName(typeName);
  1365. }
  1366. CCreatureSet::serializeJson(handler, "army", 7);
  1367. handler.serializeBool<ui8>("tightFormation", formation, 1, 0, 0);
  1368. {
  1369. static const int NO_PATROLING = -1;
  1370. int rawPatrolRadius = NO_PATROLING;
  1371. if(handler.saving)
  1372. {
  1373. rawPatrolRadius = patrol.patrolling ? patrol.patrolRadius : NO_PATROLING;
  1374. }
  1375. handler.serializeInt("patrolRadius", rawPatrolRadius, NO_PATROLING);
  1376. if(!handler.saving)
  1377. {
  1378. patrol.patrolling = (rawPatrolRadius > NO_PATROLING);
  1379. patrol.initialPos = visitablePos();
  1380. patrol.patrolRadius = (rawPatrolRadius > NO_PATROLING) ? rawPatrolRadius : 0;
  1381. }
  1382. }
  1383. }
  1384. void CGHeroInstance::serializeJsonDefinition(JsonSerializeFormat & handler)
  1385. {
  1386. serializeCommonOptions(handler);
  1387. }
  1388. bool CGHeroInstance::isMissionCritical() const
  1389. {
  1390. for(const TriggeredEvent & event : IObjectInterface::cb->getMapHeader()->triggeredEvents)
  1391. {
  1392. if(event.trigger.test([&](const EventCondition & condition)
  1393. {
  1394. if ((condition.condition == EventCondition::CONTROL || condition.condition == EventCondition::HAVE_0) && condition.object)
  1395. {
  1396. auto hero = dynamic_cast<const CGHeroInstance*>(condition.object);
  1397. return (hero != this);
  1398. }
  1399. else if(condition.condition == EventCondition::IS_HUMAN)
  1400. {
  1401. return true;
  1402. }
  1403. return false;
  1404. }))
  1405. {
  1406. return true;
  1407. }
  1408. }
  1409. return false;
  1410. }
  1411. VCMI_LIB_NAMESPACE_END