CGHeroInstance.cpp 49 KB

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