CGHeroInstance.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  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 "../NetPacks.h"
  13. #include "../CGeneralTextHandler.h"
  14. #include "../CHeroHandler.h"
  15. #include "../CModHandler.h"
  16. #include "../CSoundBase.h"
  17. #include "../spells/CSpellHandler.h"
  18. #include "../CSkillHandler.h"
  19. #include "CObjectClassesHandler.h"
  20. #include "../IGameCallback.h"
  21. #include "../CGameState.h"
  22. #include "../CCreatureHandler.h"
  23. #include "../CTownHandler.h"
  24. #include "../mapping/CMap.h"
  25. #include "CGTownInstance.h"
  26. #include "../serializer/JsonSerializeFormat.h"
  27. #include "../StringConstants.h"
  28. #include "../battle/Unit.h"
  29. ///helpers
  30. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID = 0)
  31. {
  32. InfoWindow iw;
  33. iw.soundID = soundID;
  34. iw.player = playerID;
  35. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  36. IObjectInterface::cb->sendAndApply(&iw);
  37. }
  38. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID = 0)
  39. {
  40. const PlayerColor playerID = h->getOwner();
  41. showInfoDialog(playerID,txtID,soundID);
  42. }
  43. static int lowestSpeed(const CGHeroInstance * chi)
  44. {
  45. if(!chi->stacksCount())
  46. {
  47. logGlobal->error("Hero %d (%s) has no army!", chi->id.getNum(), chi->name);
  48. return 20;
  49. }
  50. auto i = chi->Slots().begin();
  51. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  52. int ret = (i++)->second->valOfBonuses(Bonus::STACKS_SPEED);
  53. for(; i != chi->Slots().end(); i++)
  54. ret = std::min(ret, i->second->valOfBonuses(Bonus::STACKS_SPEED));
  55. return ret;
  56. }
  57. ui32 CGHeroInstance::getTileCost(const TerrainTile &dest, const TerrainTile &from, const TurnInfo * ti) const
  58. {
  59. unsigned ret = GameConstants::BASE_MOVEMENT_COST;
  60. //if there is road both on dest and src tiles - use road movement cost
  61. if(dest.roadType != ERoadType::NO_ROAD && from.roadType != ERoadType::NO_ROAD)
  62. {
  63. int road = std::min(dest.roadType,from.roadType); //used road ID
  64. switch(road)
  65. {
  66. case ERoadType::DIRT_ROAD:
  67. ret = 75;
  68. break;
  69. case ERoadType::GRAVEL_ROAD:
  70. ret = 65;
  71. break;
  72. case ERoadType::COBBLESTONE_ROAD:
  73. ret = 50;
  74. break;
  75. default:
  76. logGlobal->error("Unknown road type: %d", road);
  77. break;
  78. }
  79. }
  80. else if(ti->nativeTerrain != from.terType && !ti->hasBonusOfType(Bonus::NO_TERRAIN_PENALTY, from.terType))
  81. {
  82. ret = VLC->heroh->terrCosts[from.terType];
  83. ret -= valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::PATHFINDING));
  84. if(ret < GameConstants::BASE_MOVEMENT_COST)
  85. ret = GameConstants::BASE_MOVEMENT_COST;
  86. }
  87. return ret;
  88. }
  89. int CGHeroInstance::getNativeTerrain() const
  90. {
  91. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  92. // This is clearly bug in H3 however intended behaviour is not clear.
  93. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  94. // will always have best penalty without any influence from player-defined stacks order
  95. // TODO: What should we do if all hero stacks are neutral creatures?
  96. int nativeTerrain = -1;
  97. for(auto stack : stacks)
  98. {
  99. int stackNativeTerrain = VLC->townh->factions[stack.second->type->faction]->nativeTerrain;
  100. if(stackNativeTerrain == -1)
  101. continue;
  102. if(nativeTerrain == -1)
  103. nativeTerrain = stackNativeTerrain;
  104. else if(nativeTerrain != stackNativeTerrain)
  105. return -1;
  106. }
  107. return nativeTerrain;
  108. }
  109. int3 CGHeroInstance::convertPosition(int3 src, bool toh3m) //toh3m=true: manifest->h3m; toh3m=false: h3m->manifest
  110. {
  111. if (toh3m)
  112. {
  113. src.x+=1;
  114. return src;
  115. }
  116. else
  117. {
  118. src.x-=1;
  119. return src;
  120. }
  121. }
  122. int3 CGHeroInstance::getPosition(bool h3m) const //h3m=true - returns position of hero object; h3m=false - returns position of hero 'manifestation'
  123. {
  124. if (h3m)
  125. {
  126. return pos;
  127. }
  128. else
  129. {
  130. return convertPosition(pos,false);
  131. }
  132. }
  133. ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
  134. {
  135. for(auto & elem : secSkills)
  136. if(elem.first == skill)
  137. return elem.second;
  138. return 0;
  139. }
  140. void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
  141. {
  142. if(getSecSkillLevel(which) == 0)
  143. {
  144. secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
  145. updateSkillBonus(which, val);
  146. }
  147. else
  148. {
  149. for (auto & elem : secSkills)
  150. {
  151. if(elem.first == which)
  152. {
  153. if(abs)
  154. elem.second = val;
  155. else
  156. elem.second += val;
  157. if(elem.second > 3) //workaround to avoid crashes when same sec skill is given more than once
  158. {
  159. logGlobal->warn("Skill %d increased over limit! Decreasing to Expert.", static_cast<int>(which.toEnum()));
  160. elem.second = 3;
  161. }
  162. updateSkillBonus(which, elem.second); //when we know final value
  163. }
  164. }
  165. }
  166. }
  167. bool CGHeroInstance::canLearnSkill() const
  168. {
  169. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  170. }
  171. int CGHeroInstance::maxMovePoints(bool onLand, const TurnInfo * ti) const
  172. {
  173. bool localTi = false;
  174. if(!ti)
  175. {
  176. localTi = true;
  177. ti = new TurnInfo(this);
  178. }
  179. int base;
  180. if(onLand)
  181. {
  182. // used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
  183. static const int baseSpeed = 1300; // base speed from creature with 0 speed
  184. int armySpeed = lowestSpeed(this) * 20 / 3;
  185. base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
  186. vstd::abetween(base, 1500, 2000); // base speed is limited by these values
  187. }
  188. else
  189. {
  190. base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
  191. }
  192. const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
  193. const int bonus = ti->valOfBonuses(Bonus::MOVEMENT) + ti->valOfBonuses(bt);
  194. const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
  195. const double modifier = ti->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;
  196. if(localTi)
  197. delete ti;
  198. return int(base* (1+modifier)) + bonus;
  199. }
  200. CGHeroInstance::CGHeroInstance()
  201. : IBoatGenerator(this)
  202. {
  203. setNodeType(HERO);
  204. ID = Obj::HERO;
  205. tacticFormationEnabled = inTownGarrison = false;
  206. mana = UNINITIALIZED_MANA;
  207. movement = UNINITIALIZED_MOVEMENT;
  208. portrait = UNINITIALIZED_PORTRAIT;
  209. isStanding = true;
  210. moveDir = 4;
  211. level = 1;
  212. exp = 0xffffffff;
  213. visitedTown = nullptr;
  214. type = nullptr;
  215. boat = nullptr;
  216. commander = nullptr;
  217. sex = 0xff;
  218. secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
  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->heroes[subID];
  229. portrait = type->imageIndex;
  230. CGObjectInstance::setType(ID, type->heroClass->id); // 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->heroes[subID];
  239. if (ID == Obj::HERO)
  240. appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, type->heroClass->id)->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)//GameConstants::MAX_HEROES_PER_PLAYER) //free hero slot
  371. {
  372. cb->changeObjPos(id,pos+int3(1,0,0),0);
  373. //update hero parameters
  374. SetMovePoints smp;
  375. smp.hid = id;
  376. smp.val = maxMovePoints (true); //TODO: hota prison on water?
  377. cb->setMovePoints (&smp);
  378. cb->setManaPoints (id, manaLimit());
  379. cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
  380. cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player
  381. txt_id = 102;
  382. }
  383. else //already 8 wandering heroes
  384. {
  385. txt_id = 103;
  386. }
  387. showInfoDialog(h,txt_id);
  388. }
  389. }
  390. std::string CGHeroInstance::getObjectName() const
  391. {
  392. if(ID != Obj::PRISON)
  393. {
  394. std::string hoverName = VLC->generaltexth->allTexts[15];
  395. boost::algorithm::replace_first(hoverName,"%s",name);
  396. boost::algorithm::replace_first(hoverName,"%s", type->heroClass->name);
  397. return hoverName;
  398. }
  399. else
  400. return CGObjectInstance::getObjectName();
  401. }
  402. const std::string & CGHeroInstance::getBiography() const
  403. {
  404. if (biography.length())
  405. return biography;
  406. return type->biography;
  407. }
  408. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  409. {
  410. return type->heroClass->isMagicHero() ? 3 : 4;
  411. }
  412. ui8 CGHeroInstance::maxlevelsToWisdom() const
  413. {
  414. return type->heroClass->isMagicHero() ? 3 : 6;
  415. }
  416. CGHeroInstance::SecondarySkillsInfo::SecondarySkillsInfo()
  417. {
  418. rand.setSeed(0);
  419. magicSchoolCounter = 1;
  420. wisdomCounter = 1;
  421. }
  422. void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
  423. {
  424. magicSchoolCounter = 1;
  425. }
  426. void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
  427. {
  428. wisdomCounter = 1;
  429. }
  430. void CGHeroInstance::initObj(CRandomGenerator & rand)
  431. {
  432. blockVisit = true;
  433. if(!type)
  434. initHero(rand); //TODO: set up everything for prison before specialties are configured
  435. skillsInfo.rand.setSeed(rand.nextInt());
  436. skillsInfo.resetMagicSchoolCounter();
  437. skillsInfo.resetWisdomCounter();
  438. if (ID != Obj::PRISON)
  439. {
  440. auto customApp = VLC->objtypeh->getHandlerFor(ID, type->heroClass->id)->getOverride(cb->gameState()->getTile(visitablePos())->terType, this);
  441. if (customApp)
  442. appearance = customApp.get();
  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::recreateSpecialtyBonuses(std::vector<HeroSpecial *> & specialtyDeprecated)
  469. {
  470. auto HeroSpecialToSpecialtyBonus = [](HeroSpecial & hs) -> SSpecialtyBonus
  471. {
  472. SSpecialtyBonus sb;
  473. sb.growsWithLevel = hs.growsWithLevel;
  474. sb.bonuses = hs.getBonusList();
  475. return sb;
  476. };
  477. for(HeroSpecial * hs : specialtyDeprecated)
  478. {
  479. for(std::shared_ptr<Bonus> b : SpecialtyBonusToBonuses(HeroSpecialToSpecialtyBonus(*hs)))
  480. addNewBonus(b);
  481. }
  482. }
  483. void CGHeroInstance::updateSkillBonus(SecondarySkill which, int val)
  484. {
  485. removeBonuses(Selector::source(Bonus::SECONDARY_SKILL, which));
  486. auto skillBonus = (*VLC->skillh)[which]->getBonus(val);
  487. for (auto b : skillBonus)
  488. addNewBonus(std::make_shared<Bonus>(*b));
  489. }
  490. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  491. {
  492. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  493. setStackCount(SlotID(0), val);
  494. }
  495. TFaction CGHeroInstance::getFaction() const
  496. {
  497. return type->heroClass->faction;
  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 (ui64) ret;
  515. }
  516. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  517. {
  518. return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
  519. }
  520. int32_t CGHeroInstance::getCasterUnitId() const
  521. {
  522. return -1; //TODO: special value for attacker/defender hero
  523. }
  524. ui8 CGHeroInstance::getSpellSchoolLevel(const spells::Spell * spell, int * outSelectedSchool) const
  525. {
  526. si16 skill = -1; //skill level
  527. spell->forEachSchool([&, this](const spells::SchoolInfo & cnf, bool & stop)
  528. {
  529. int thisSchool = std::max<int>(
  530. valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, cnf.skill),
  531. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << ((ui8)cnf.id))); //FIXME: Bonus shouldn't be additive (Witchking Artifacts : Crown of Skies)
  532. if(thisSchool > skill)
  533. {
  534. skill = thisSchool;
  535. if(outSelectedSchool)
  536. *outSelectedSchool = (ui8)cnf.id;
  537. }
  538. });
  539. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  540. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->getIndex())); //given by artifact or other effect
  541. vstd::amax(skill, 0); //in case we don't know any school
  542. vstd::amin(skill, 3);
  543. return skill;
  544. }
  545. int64_t CGHeroInstance::getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const
  546. {
  547. //applying sorcery secondary skill
  548. base *= (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
  549. base *= (100.0 + valOfBonuses(Bonus::SPELL_DAMAGE) + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0;
  550. int maxSchoolBonus = 0;
  551. spell->forEachSchool([&maxSchoolBonus, this](const spells::SchoolInfo & cnf, bool & stop)
  552. {
  553. vstd::amax(maxSchoolBonus, valOfBonuses(cnf.damagePremyBonus));
  554. });
  555. base *= (100.0 + maxSchoolBonus) / 100.0;
  556. if(affectedStack && affectedStack->creatureLevel() > 0) //Hero specials like Solmyr, Deemer
  557. base *= (100. + valOfBonuses(Bonus::SPECIAL_SPELL_LEV, spell->getIndex()) / affectedStack->creatureLevel()) / 100.0;
  558. return base;
  559. }
  560. int64_t CGHeroInstance::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
  561. {
  562. base *= (100.0 + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0;
  563. return base;
  564. }
  565. int CGHeroInstance::getEffectLevel(const spells::Spell * spell) const
  566. {
  567. if(hasBonusOfType(Bonus::MAXED_SPELL, spell->getIndex()))
  568. return 3;//todo: recheck specialty from where this bonus is. possible bug
  569. else
  570. return getSpellSchoolLevel(spell);
  571. }
  572. int CGHeroInstance::getEffectPower(const spells::Spell * spell) const
  573. {
  574. return getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  575. }
  576. int CGHeroInstance::getEnchantPower(const spells::Spell * spell) const
  577. {
  578. return getPrimSkillLevel(PrimarySkill::SPELL_POWER) + valOfBonuses(Bonus::SPELL_DURATION);
  579. }
  580. int64_t CGHeroInstance::getEffectValue(const spells::Spell * spell) const
  581. {
  582. return 0;
  583. }
  584. const PlayerColor CGHeroInstance::getOwner() const
  585. {
  586. return tempOwner;
  587. }
  588. void CGHeroInstance::getCasterName(MetaString & text) const
  589. {
  590. //FIXME: use local name, MetaString need access to gamestate as hero name is part of map object
  591. text.addReplacement(name);
  592. }
  593. void CGHeroInstance::getCastDescription(const spells::Spell * spell, const std::vector<const battle::Unit *> & attacked, MetaString & text) const
  594. {
  595. const bool singleTarget = attacked.size() == 1;
  596. const int textIndex = singleTarget ? 195 : 196;
  597. text.addTxt(MetaString::GENERAL_TXT, textIndex);
  598. getCasterName(text);
  599. text.addReplacement(MetaString::SPELL_NAME, spell->getIndex());
  600. if(singleTarget)
  601. attacked.at(0)->addNameReplacement(text, true);
  602. }
  603. void CGHeroInstance::spendMana(const spells::PacketSender * 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->sendAndApply(&sm);
  612. }
  613. }
  614. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  615. {
  616. const bool isAllowed = IObjectInterface::cb->isAllowed(0, spell->id);
  617. const bool inSpellBook = vstd::contains(spells, spell->id) && hasSpellbook();
  618. const bool specificBonus = hasBonusOfType(Bonus::SPELL, spell->id);
  619. bool schoolBonus = false;
  620. spell->forEachSchool([this, &schoolBonus](const spells::SchoolInfo & cnf, bool & stop)
  621. {
  622. if(hasBonusOfType(cnf.knoledgeBonus))
  623. {
  624. schoolBonus = stop = true;
  625. }
  626. });
  627. const bool levelBonus = hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level);
  628. if(spell->isSpecialSpell())
  629. {
  630. if(inSpellBook)
  631. {//hero has this spell in spellbook
  632. logGlobal->error("Special spell %s in spellbook.", spell->name);
  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->name);
  643. }
  644. return inSpellBook || specificBonus || schoolBonus || levelBonus;
  645. }
  646. else
  647. {
  648. return inSpellBook || schoolBonus || specificBonus || levelBonus;
  649. }
  650. }
  651. bool CGHeroInstance::canLearnSpell(const CSpell * spell) const
  652. {
  653. if(!hasSpellbook())
  654. return false;
  655. if(spell->level > maxSpellLevel()) //not enough wisdom
  656. return false;
  657. if(vstd::contains(spells, spell->id))//already known
  658. return false;
  659. if(spell->isSpecialSpell())
  660. {
  661. logGlobal->warn("Hero %s try to learn special spell %s", nodeName(), spell->name);
  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->name);
  667. return false;//creature abilities can not be learned
  668. }
  669. if(!IObjectInterface::cb->isAllowed(0, spell->id))
  670. {
  671. logGlobal->warn("Hero %s try to learn banned spell %s", nodeName(), spell->name);
  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. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  686. // Hero knows necromancy or has Necromancer Cloak
  687. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  688. {
  689. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  690. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  691. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  692. ui32 raisedUnits = 0;
  693. // Figure out what to raise and how many.
  694. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  695. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  696. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  697. const ui32 raisedUnitHP = raisedUnitType->MaxHealth();
  698. //calculate creatures raised from each defeated stack
  699. for (auto & casualtie : casualties)
  700. {
  701. // Get lost enemy hit points convertible to units.
  702. CCreature * c = VLC->creh->creatures[casualtie.first];
  703. const ui32 raisedHP = c->MaxHealth() * casualtie.second * necromancySkill;
  704. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, casualtie.second * necromancySkill); //limit to % of HP and % of original stack count
  705. }
  706. // Make room for new units.
  707. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  708. if (slot == SlotID())
  709. {
  710. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  711. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  712. raisedUnits = (raisedUnits*2)/3;
  713. slot = getSlotFor(raisedUnitType->idNumber);
  714. }
  715. if (raisedUnits <= 0)
  716. raisedUnits = 1;
  717. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  718. }
  719. return CStackBasicDescriptor();
  720. }
  721. /**
  722. * Show the necromancy dialog with information about units raised.
  723. * @param raisedStack Pair where the first element represents ID of the raised creature
  724. * and the second element the amount.
  725. */
  726. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack, CRandomGenerator & rand) const
  727. {
  728. InfoWindow iw;
  729. iw.soundID = soundBase::pickup01 + rand.nextInt(6);
  730. iw.player = tempOwner;
  731. iw.components.push_back(Component(raisedStack));
  732. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  733. {
  734. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  735. iw.text.addReplacement(raisedStack.count);
  736. }
  737. else // Practicing the dark arts of necromancy, ... (singular)
  738. {
  739. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  740. }
  741. iw.text.addReplacement(raisedStack);
  742. cb->showInfoDialog(&iw);
  743. }
  744. /*
  745. int3 CGHeroInstance::getSightCenter() const
  746. {
  747. return getPosition(false);
  748. }*/
  749. int CGHeroInstance::getSightRadius() const
  750. {
  751. return 5 + valOfBonuses(Bonus::SIGHT_RADIOUS); // scouting gives SIGHT_RADIUS bonus
  752. }
  753. si32 CGHeroInstance::manaRegain() const
  754. {
  755. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  756. return manaLimit();
  757. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::MYSTICISM) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  758. }
  759. si32 CGHeroInstance::getManaNewTurn() const
  760. {
  761. if(visitedTown && visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  762. {
  763. //if hero starts turn in town with mage guild - restore all mana
  764. return std::max(mana, manaLimit());
  765. }
  766. si32 res = mana + manaRegain();
  767. res = std::min(res, manaLimit());
  768. res = std::max(res, mana);
  769. res = std::max(res, 0);
  770. return res;
  771. }
  772. // /**
  773. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  774. // * or discards it if it cannot be equipped.
  775. // */
  776. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  777. // {
  778. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  779. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  780. // ai->putAt(this, ai->firstAvailableSlot(this));
  781. // }
  782. int CGHeroInstance::getBoatType() const
  783. {
  784. switch(type->heroClass->getAlignment())
  785. {
  786. case EAlignment::GOOD:
  787. return 1;
  788. case EAlignment::EVIL:
  789. return 0;
  790. case EAlignment::NEUTRAL:
  791. return 2;
  792. default:
  793. throw std::runtime_error("Wrong alignment!");
  794. }
  795. }
  796. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  797. {
  798. // FIXME: Offsets need to be fixed once we get rid of convertPosition
  799. // Check issue 515 for details
  800. offsets =
  801. {
  802. 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)
  803. };
  804. }
  805. int CGHeroInstance::getSpellCost(const CSpell * sp) const
  806. {
  807. return sp->getCost(getSpellSchoolLevel(sp));
  808. }
  809. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  810. {
  811. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  812. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL))));
  813. addNewBonus(std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  814. }
  815. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  816. {
  817. return type->heroClass->getAlignment();
  818. }
  819. void CGHeroInstance::initExp(CRandomGenerator & rand)
  820. {
  821. exp = rand.nextInt(40, 89);
  822. }
  823. std::string CGHeroInstance::nodeName() const
  824. {
  825. return "Hero " + name;
  826. }
  827. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  828. {
  829. assert(!getArt(pos));
  830. art->putAt(ArtifactLocation(this, pos));
  831. }
  832. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  833. {
  834. putArtifact(art->firstBackpackSlot(this), art);
  835. }
  836. bool CGHeroInstance::hasSpellbook() const
  837. {
  838. return getArt(ArtifactPosition::SPELLBOOK);
  839. }
  840. int CGHeroInstance::maxSpellLevel() const
  841. {
  842. return std::min(GameConstants::SPELL_LEVELS, 2 + valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::WISDOM)));
  843. }
  844. void CGHeroInstance::deserializationFix()
  845. {
  846. artDeserializationFix(this);
  847. }
  848. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  849. {
  850. if(visitedTown)
  851. {
  852. if(inTownGarrison)
  853. return visitedTown;
  854. else
  855. return &visitedTown->townAndVis;
  856. }
  857. else
  858. return CArmedInstance::whereShouldBeAttached(gs);
  859. }
  860. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const
  861. {
  862. int ret = 0; //take all MPs by default
  863. bool localTi = false;
  864. if(!ti)
  865. {
  866. localTi = true;
  867. ti = new TurnInfo(this);
  868. }
  869. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL);
  870. int mp2 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  871. if(ti->hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  872. ret = (MPsBefore - basicCost) * static_cast<double>(mp1) / mp2;
  873. if(localTi)
  874. delete ti;
  875. return ret;
  876. }
  877. EDiggingStatus CGHeroInstance::diggingStatus() const
  878. {
  879. if(movement < maxMovePoints(true))
  880. return EDiggingStatus::LACK_OF_MOVEMENT;
  881. return cb->getTile(getPosition(false))->getDiggingStatus();
  882. }
  883. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  884. {
  885. return ArtBearer::HERO;
  886. }
  887. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
  888. {
  889. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  890. if (!skillsInfo.wisdomCounter)
  891. {
  892. if (cb->isAllowed(2, SecondarySkill::WISDOM) && !getSecSkillLevel(SecondarySkill::WISDOM))
  893. obligatorySkills.push_back(SecondarySkill::WISDOM);
  894. }
  895. if (!skillsInfo.magicSchoolCounter)
  896. {
  897. std::vector<SecondarySkill> ss =
  898. {
  899. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC
  900. };
  901. std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());
  902. for (auto skill : ss)
  903. {
  904. if (cb->isAllowed(2, skill) && !getSecSkillLevel(skill)) //only schools hero doesn't know yet
  905. {
  906. obligatorySkills.push_back(skill);
  907. break; //only one
  908. }
  909. }
  910. }
  911. std::vector<SecondarySkill> skills;
  912. //picking sec. skills for choice
  913. std::set<SecondarySkill> basicAndAdv, expert, none;
  914. for(int i=0;i<GameConstants::SKILL_QUANTITY;i++)
  915. if (cb->isAllowed(2,i))
  916. none.insert(SecondarySkill(i));
  917. for(auto & elem : secSkills)
  918. {
  919. if(elem.second < SecSkillLevel::EXPERT)
  920. basicAndAdv.insert(elem.first);
  921. else
  922. expert.insert(elem.first);
  923. none.erase(elem.first);
  924. }
  925. for (auto s : obligatorySkills) //don't duplicate them
  926. {
  927. none.erase (s);
  928. basicAndAdv.erase (s);
  929. expert.erase (s);
  930. }
  931. //first offered skill:
  932. // 1) give obligatory skill
  933. // 2) give any other new skill
  934. // 3) upgrade existing
  935. if (canLearnSkill() && obligatorySkills.size() > 0)
  936. {
  937. skills.push_back (obligatorySkills[0]);
  938. }
  939. else if(none.size() && canLearnSkill()) //hero have free skill slot
  940. {
  941. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
  942. none.erase(skills.back());
  943. }
  944. else if(!basicAndAdv.empty())
  945. {
  946. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
  947. basicAndAdv.erase(skills.back());
  948. }
  949. //second offered skill:
  950. //1) upgrade existing
  951. //2) give obligatory skill
  952. //3) give any other new skill
  953. if(!basicAndAdv.empty())
  954. {
  955. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
  956. skills.push_back(s);
  957. basicAndAdv.erase(s);
  958. }
  959. else if (canLearnSkill() && obligatorySkills.size() > 1)
  960. {
  961. skills.push_back (obligatorySkills[1]);
  962. }
  963. else if(none.size() && canLearnSkill())
  964. {
  965. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
  966. none.erase(skills.back());
  967. }
  968. if (skills.size() == 2) // Fix for #1868 to avoid changing logic (possibly causing bugs in process)
  969. std::swap(skills[0], skills[1]);
  970. return skills;
  971. }
  972. PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill(CRandomGenerator & rand) const
  973. {
  974. assert(gainsLevel());
  975. int randomValue = rand.nextInt(99), pom = 0, primarySkill = 0;
  976. const auto & skillChances = (level > 9) ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;
  977. for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
  978. {
  979. pom += skillChances[primarySkill];
  980. if(randomValue < pom)
  981. {
  982. break;
  983. }
  984. }
  985. logGlobal->trace("The hero gets the primary skill %d with a probability of %d %%.", primarySkill, randomValue);
  986. return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
  987. }
  988. boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(CRandomGenerator & rand) const
  989. {
  990. assert(gainsLevel());
  991. boost::optional<SecondarySkill> chosenSecondarySkill;
  992. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  993. if(!proposedSecondarySkills.empty())
  994. {
  995. std::vector<SecondarySkill> learnedSecondarySkills;
  996. for(auto secondarySkill : proposedSecondarySkills)
  997. {
  998. if(getSecSkillLevel(secondarySkill) > 0)
  999. {
  1000. learnedSecondarySkills.push_back(secondarySkill);
  1001. }
  1002. }
  1003. if(learnedSecondarySkills.empty())
  1004. {
  1005. // there are only new skills to learn, so choose anyone of them
  1006. chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand));
  1007. }
  1008. else
  1009. {
  1010. // preferably upgrade a already learned secondary skill
  1011. chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand));
  1012. }
  1013. }
  1014. return chosenSecondarySkill;
  1015. }
  1016. void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
  1017. {
  1018. if(primarySkill < PrimarySkill::EXPERIENCE)
  1019. {
  1020. auto skill = getBonusLocalFirst(Selector::type(Bonus::PRIMARY_SKILL)
  1021. .And(Selector::subtype(primarySkill))
  1022. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));
  1023. assert(skill);
  1024. if(abs)
  1025. {
  1026. skill->val = value;
  1027. }
  1028. else
  1029. {
  1030. skill->val += value;
  1031. }
  1032. CBonusSystemNode::treeHasChanged();
  1033. }
  1034. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1035. {
  1036. if(abs)
  1037. {
  1038. exp = value;
  1039. }
  1040. else
  1041. {
  1042. exp += value;
  1043. }
  1044. }
  1045. }
  1046. bool CGHeroInstance::gainsLevel() const
  1047. {
  1048. return exp >= VLC->heroh->reqExp(level+1);
  1049. }
  1050. void CGHeroInstance::levelUp(std::vector<SecondarySkill> skills)
  1051. {
  1052. ++level;
  1053. //deterministic secondary skills
  1054. skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
  1055. skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
  1056. if(vstd::contains(skills, SecondarySkill::WISDOM))
  1057. {
  1058. skillsInfo.resetWisdomCounter();
  1059. }
  1060. SecondarySkill spellSchools[] = {
  1061. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
  1062. for(auto skill : spellSchools)
  1063. {
  1064. if(vstd::contains(skills, skill))
  1065. {
  1066. skillsInfo.resetMagicSchoolCounter();
  1067. break;
  1068. }
  1069. }
  1070. //update specialty and other bonuses that scale with level
  1071. treeHasChanged();
  1072. }
  1073. void CGHeroInstance::levelUpAutomatically(CRandomGenerator & rand)
  1074. {
  1075. while(gainsLevel())
  1076. {
  1077. const auto primarySkill = nextPrimarySkill(rand);
  1078. setPrimarySkill(primarySkill, 1, false);
  1079. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1080. const auto secondarySkill = nextSecondarySkill(rand);
  1081. if(secondarySkill)
  1082. {
  1083. setSecSkillLevel(*secondarySkill, 1, false);
  1084. }
  1085. //TODO why has the secondary skills to be passed to the method?
  1086. levelUp(proposedSecondarySkills);
  1087. }
  1088. }
  1089. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, const int subtype) const
  1090. {
  1091. //VISIONS spell support
  1092. const std::string cached = boost::to_string((boost::format("type_%d__subtype_%d") % Bonus::VISIONS % subtype));
  1093. const int visionsMultiplier = valOfBonuses(Selector::typeSubtype(Bonus::VISIONS,subtype), cached);
  1094. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1095. if (visionsMultiplier > 0)
  1096. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1097. const int distance = target->pos.dist2d(getPosition(false));
  1098. //logGlobal->debug(boost::to_string(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1099. return (distance < visionsRange) && (target->pos.z == pos.z);
  1100. }
  1101. std::string CGHeroInstance::getHeroTypeName() const
  1102. {
  1103. if(ID == Obj::HERO || ID == Obj::PRISON)
  1104. {
  1105. if(type)
  1106. {
  1107. return type->identifier;
  1108. }
  1109. else
  1110. {
  1111. return VLC->heroh->heroes[subID]->identifier;
  1112. }
  1113. }
  1114. return "";
  1115. }
  1116. void CGHeroInstance::afterAddToMap(CMap * map)
  1117. {
  1118. if(ID == Obj::HERO)
  1119. map->heroesOnMap.push_back(this);
  1120. }
  1121. void CGHeroInstance::setHeroTypeName(const std::string & identifier)
  1122. {
  1123. if(ID == Obj::HERO || ID == Obj::PRISON)
  1124. {
  1125. auto rawId = VLC->modh->identifiers.getIdentifier("core", "hero", identifier);
  1126. if(rawId)
  1127. subID = rawId.get();
  1128. else
  1129. subID = 0; //fallback to Orrin, throw error instead?
  1130. }
  1131. }
  1132. void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
  1133. {
  1134. handler.serializeString("biography", biography);
  1135. handler.serializeInt("experience", exp, 0);
  1136. handler.serializeString("name", name);
  1137. handler.serializeBool<ui8>("female", sex, 1, 0, 0xFF);
  1138. {
  1139. const int legacyHeroes = VLC->modh->settings.data["textData"]["hero"].Integer();
  1140. const int moddedStart = legacyHeroes + GameConstants::HERO_PORTRAIT_SHIFT;
  1141. if(handler.saving)
  1142. {
  1143. if(portrait >= 0)
  1144. {
  1145. if(portrait < legacyHeroes || portrait >= moddedStart)
  1146. handler.serializeId("portrait", portrait, -1, &VLC->heroh->decodeHero, &VLC->heroh->encodeHero);
  1147. else
  1148. handler.serializeInt("portrait", portrait, -1);
  1149. }
  1150. }
  1151. else
  1152. {
  1153. const JsonNode & portraitNode = handler.getCurrent()["portrait"];
  1154. if(portraitNode.getType() == JsonNode::JsonType::DATA_STRING)
  1155. handler.serializeId("portrait", portrait, -1, &VLC->heroh->decodeHero, &VLC->heroh->encodeHero);
  1156. else
  1157. handler.serializeInt("portrait", portrait, -1);
  1158. }
  1159. }
  1160. //primary skills
  1161. if(handler.saving)
  1162. {
  1163. const bool haveSkills = hasBonus(Selector::type(Bonus::PRIMARY_SKILL).And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));
  1164. if(haveSkills)
  1165. {
  1166. auto primarySkills = handler.enterStruct("primarySkills");
  1167. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1168. {
  1169. int value = valOfBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, i).And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));
  1170. handler.serializeInt(PrimarySkill::names[i], value, 0);
  1171. }
  1172. }
  1173. }
  1174. else
  1175. {
  1176. auto primarySkills = handler.enterStruct("primarySkills");
  1177. if(handler.getCurrent().getType() == JsonNode::JsonType::DATA_STRUCT)
  1178. {
  1179. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1180. {
  1181. int value = 0;
  1182. handler.serializeInt(PrimarySkill::names[i], value, 0);
  1183. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(i), value);
  1184. }
  1185. }
  1186. }
  1187. //secondary skills
  1188. if(handler.saving)
  1189. {
  1190. //does hero have default skills?
  1191. bool defaultSkills = false;
  1192. bool normalSkills = false;
  1193. for(const auto & p : secSkills)
  1194. {
  1195. if(p.first == SecondarySkill(SecondarySkill::DEFAULT))
  1196. defaultSkills = true;
  1197. else
  1198. normalSkills = true;
  1199. }
  1200. if(defaultSkills && normalSkills)
  1201. logGlobal->error("Mixed default and normal secondary skills");
  1202. //in json default skills means no field/null
  1203. if(!defaultSkills)
  1204. {
  1205. //enter structure here as handler initialize it
  1206. auto secondarySkills = handler.enterStruct("secondarySkills");
  1207. for(auto & p : secSkills)
  1208. {
  1209. const si32 rawId = p.first.num;
  1210. if(rawId < 0 || rawId >= GameConstants::SKILL_QUANTITY)
  1211. logGlobal->error("Invalid secondary skill %d", rawId);
  1212. handler.serializeEnum(NSecondarySkill::names[rawId], p.second, 0, NSecondarySkill::levels);
  1213. }
  1214. }
  1215. }
  1216. else
  1217. {
  1218. auto secondarySkills = handler.enterStruct("secondarySkills");
  1219. const JsonNode & skillMap = handler.getCurrent();
  1220. secSkills.clear();
  1221. if(skillMap.getType() == JsonNode::JsonType::DATA_NULL)
  1222. {
  1223. secSkills.push_back(std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1));
  1224. }
  1225. else
  1226. {
  1227. for(const auto & p : skillMap.Struct())
  1228. {
  1229. const std::string skillId = p.first;
  1230. const std::string levelId = p.second.String();
  1231. const int rawId = vstd::find_pos(NSecondarySkill::names, skillId);
  1232. if(rawId < 0)
  1233. {
  1234. logGlobal->error("Invalid secondary skill %s", skillId);
  1235. continue;
  1236. }
  1237. const int level = vstd::find_pos(NSecondarySkill::levels, levelId);
  1238. if(level < 0)
  1239. {
  1240. logGlobal->error("Invalid secondary skill level%s", levelId);
  1241. continue;
  1242. }
  1243. secSkills.push_back(std::pair<SecondarySkill,ui8>(SecondarySkill(rawId), level));
  1244. }
  1245. }
  1246. }
  1247. handler.serializeIdArray("spellBook", spells);
  1248. if(handler.saving)
  1249. CArtifactSet::serializeJsonArtifacts(handler, "artifacts", nullptr);
  1250. }
  1251. void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1252. {
  1253. serializeCommonOptions(handler);
  1254. serializeJsonOwner(handler);
  1255. if(ID == Obj::HERO || ID == Obj::PRISON)
  1256. {
  1257. std::string typeName;
  1258. if(handler.saving)
  1259. typeName = getHeroTypeName();
  1260. handler.serializeString("type", typeName);
  1261. if(!handler.saving)
  1262. setHeroTypeName(typeName);
  1263. }
  1264. CCreatureSet::serializeJson(handler, "army", 7);
  1265. handler.serializeBool<ui8>("tightFormation", formation, 1, 0, 0);
  1266. {
  1267. static const int NO_PATROLING = -1;
  1268. int rawPatrolRadius = NO_PATROLING;
  1269. if(handler.saving)
  1270. {
  1271. rawPatrolRadius = patrol.patrolling ? patrol.patrolRadius : NO_PATROLING;
  1272. }
  1273. handler.serializeInt("patrolRadius", rawPatrolRadius, NO_PATROLING);
  1274. if(!handler.saving)
  1275. {
  1276. patrol.patrolling = (rawPatrolRadius > NO_PATROLING);
  1277. patrol.initialPos = convertPosition(pos, false);
  1278. patrol.patrolRadius = (rawPatrolRadius > NO_PATROLING) ? rawPatrolRadius : 0;
  1279. }
  1280. }
  1281. }
  1282. void CGHeroInstance::serializeJsonDefinition(JsonSerializeFormat & handler)
  1283. {
  1284. serializeCommonOptions(handler);
  1285. }
  1286. bool CGHeroInstance::isMissionCritical() const
  1287. {
  1288. for(const TriggeredEvent & event : IObjectInterface::cb->getMapHeader()->triggeredEvents)
  1289. {
  1290. if(event.trigger.test([&](const EventCondition & condition)
  1291. {
  1292. if ((condition.condition == EventCondition::CONTROL || condition.condition == EventCondition::HAVE_0) && condition.object)
  1293. {
  1294. auto hero = dynamic_cast<const CGHeroInstance*>(condition.object);
  1295. return (hero != this);
  1296. }
  1297. else if(condition.condition == EventCondition::IS_HUMAN)
  1298. {
  1299. return true;
  1300. }
  1301. return false;
  1302. }))
  1303. {
  1304. return true;
  1305. }
  1306. }
  1307. return false;
  1308. }