CGHeroInstance.cpp 50 KB

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