CGHeroInstance.cpp 49 KB

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