CGHeroInstance.cpp 49 KB

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