CGHeroInstance.cpp 49 KB

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