CGHeroInstance.cpp 49 KB

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