2
0

CGHeroInstance.cpp 45 KB

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