CGHeroInstance.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  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 "CObjectClassesHandler.h"
  19. #include "../IGameCallback.h"
  20. #include "../CGameState.h"
  21. #include "../CCreatureHandler.h"
  22. #include "../BattleState.h"
  23. ///helpers
  24. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID)
  25. {
  26. InfoWindow iw;
  27. iw.soundID = soundID;
  28. iw.player = playerID;
  29. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  30. IObjectInterface::cb->sendAndApply(&iw);
  31. }
  32. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID)
  33. {
  34. const PlayerColor playerID = h->getOwner();
  35. showInfoDialog(playerID,txtID,soundID);
  36. }
  37. static int lowestSpeed(const CGHeroInstance * chi)
  38. {
  39. if(!chi->Slots().size())
  40. {
  41. logGlobal->errorStream() << "Error! Hero " << chi->id.getNum() << " ("<<chi->name<<") has no army!";
  42. return 20;
  43. }
  44. auto i = chi->Slots().begin();
  45. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  46. int ret = (i++)->second->valOfBonuses(Bonus::STACKS_SPEED);
  47. for (;i!=chi->Slots().end();i++)
  48. {
  49. ret = std::min(ret, i->second->valOfBonuses(Bonus::STACKS_SPEED));
  50. }
  51. return ret;
  52. }
  53. ui32 CGHeroInstance::getTileCost(const TerrainTile &dest, const TerrainTile &from, const TurnInfo * ti) const
  54. {
  55. unsigned ret = GameConstants::BASE_MOVEMENT_COST;
  56. //if there is road both on dest and src tiles - use road movement cost
  57. if(dest.roadType != ERoadType::NO_ROAD && from.roadType != ERoadType::NO_ROAD)
  58. {
  59. int road = std::min(dest.roadType,from.roadType); //used road ID
  60. switch(road)
  61. {
  62. case ERoadType::DIRT_ROAD:
  63. ret = 75;
  64. break;
  65. case ERoadType::GRAVEL_ROAD:
  66. ret = 65;
  67. break;
  68. case ERoadType::COBBLESTONE_ROAD:
  69. ret = 50;
  70. break;
  71. default:
  72. logGlobal->errorStream() << "Unknown road type: " << road << "... Something wrong!";
  73. break;
  74. }
  75. }
  76. else if(!ti->hasBonusOfType(Bonus::NO_TERRAIN_PENALTY, from.terType))
  77. {
  78. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  79. // This is clearly bug in H3 however intended behaviour is not clear.
  80. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  81. // will always have best penalty without any influence from player-defined stacks order
  82. for(auto stack : stacks)
  83. {
  84. int nativeTerrain = VLC->townh->factions[stack.second->type->faction]->nativeTerrain;
  85. if(nativeTerrain != -1 && nativeTerrain != from.terType)
  86. {
  87. ret = VLC->heroh->terrCosts[from.terType];
  88. ret -= getSecSkillLevel(SecondarySkill::PATHFINDING) * 25;
  89. if(ret < GameConstants::BASE_MOVEMENT_COST)
  90. ret = GameConstants::BASE_MOVEMENT_COST;
  91. break;
  92. }
  93. }
  94. }
  95. return ret;
  96. }
  97. int3 CGHeroInstance::convertPosition(int3 src, bool toh3m) //toh3m=true: manifest->h3m; toh3m=false: h3m->manifest
  98. {
  99. if (toh3m)
  100. {
  101. src.x+=1;
  102. return src;
  103. }
  104. else
  105. {
  106. src.x-=1;
  107. return src;
  108. }
  109. }
  110. int3 CGHeroInstance::getPosition(bool h3m) const //h3m=true - returns position of hero object; h3m=false - returns position of hero 'manifestation'
  111. {
  112. if (h3m)
  113. {
  114. return pos;
  115. }
  116. else
  117. {
  118. return convertPosition(pos,false);
  119. }
  120. }
  121. ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
  122. {
  123. for(auto & elem : secSkills)
  124. if(elem.first == skill)
  125. return elem.second;
  126. return 0;
  127. }
  128. void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
  129. {
  130. if(getSecSkillLevel(which) == 0)
  131. {
  132. secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
  133. updateSkill(which, val);
  134. }
  135. else
  136. {
  137. for (auto & elem : secSkills)
  138. {
  139. if(elem.first == which)
  140. {
  141. if(abs)
  142. elem.second = val;
  143. else
  144. elem.second += val;
  145. if(elem.second > 3) //workaround to avoid crashes when same sec skill is given more than once
  146. {
  147. logGlobal->warnStream() << "Warning: Skill " << which << " increased over limit! Decreasing to Expert.";
  148. elem.second = 3;
  149. }
  150. updateSkill(which, elem.second); //when we know final value
  151. }
  152. }
  153. }
  154. }
  155. bool CGHeroInstance::canLearnSkill() const
  156. {
  157. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  158. }
  159. int CGHeroInstance::maxMovePoints(bool onLand, const TurnInfo * ti) const
  160. {
  161. if(!ti)
  162. ti = new TurnInfo(this);
  163. int base;
  164. if(onLand)
  165. {
  166. // used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
  167. static const int baseSpeed = 1300; // base speed from creature with 0 speed
  168. int armySpeed = lowestSpeed(this) * 20 / 3;
  169. base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
  170. vstd::abetween(base, 1500, 2000); // base speed is limited by these values
  171. }
  172. else
  173. {
  174. base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
  175. }
  176. const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
  177. const int bonus = ti->valOfBonuses(Bonus::MOVEMENT) + ti->valOfBonuses(bt);
  178. const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
  179. const double modifier = ti->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;
  180. return int(base* (1+modifier)) + bonus;
  181. }
  182. CGHeroInstance::CGHeroInstance()
  183. : IBoatGenerator(this)
  184. {
  185. setNodeType(HERO);
  186. ID = Obj::HERO;
  187. tacticFormationEnabled = inTownGarrison = false;
  188. mana = movement = portrait = -1;
  189. isStanding = true;
  190. moveDir = 4;
  191. level = 1;
  192. exp = 0xffffffff;
  193. visitedTown = nullptr;
  194. type = nullptr;
  195. boat = nullptr;
  196. commander = nullptr;
  197. sex = 0xff;
  198. secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
  199. }
  200. void CGHeroInstance::initHero(HeroTypeID SUBID)
  201. {
  202. subID = SUBID.getNum();
  203. initHero();
  204. }
  205. void CGHeroInstance::setType(si32 ID, si32 subID)
  206. {
  207. assert(ID == Obj::HERO); // just in case
  208. type = VLC->heroh->heroes[subID];
  209. portrait = type->imageIndex;
  210. CGObjectInstance::setType(ID, type->heroClass->id);
  211. randomizeArmy(type->heroClass->faction);
  212. }
  213. void CGHeroInstance::initHero()
  214. {
  215. assert(validTypes(true));
  216. if(!type)
  217. type = VLC->heroh->heroes[subID];
  218. if (ID == Obj::HERO)
  219. appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, type->heroClass->id)->getTemplates().front();
  220. if(!vstd::contains(spells, SpellID::PRESET)) //hero starts with a spell
  221. {
  222. for(auto spellID : type->spells)
  223. spells.insert(spellID);
  224. }
  225. else //remove placeholder
  226. spells -= SpellID::PRESET;
  227. if(!getArt(ArtifactPosition::MACH4) && !getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook) //no catapult means we haven't read pre-existent set -> use default rules for spellbook
  228. putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(ArtifactID::SPELLBOOK));
  229. if(!getArt(ArtifactPosition::MACH4))
  230. putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createNewArtifactInstance(ArtifactID::CATAPULT)); //everyone has a catapult
  231. if(portrait < 0 || portrait == 255)
  232. portrait = type->imageIndex;
  233. if(!hasBonus(Selector::sourceType(Bonus::HERO_BASE_SKILL)))
  234. {
  235. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  236. {
  237. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(g), type->heroClass->primarySkillInitial[g]);
  238. }
  239. }
  240. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1)) //set secondary skills to default
  241. secSkills = type->secSkillsInit;
  242. if (!name.length())
  243. name = type->name;
  244. if (sex == 0xFF)//sex is default
  245. sex = type->sex;
  246. setFormation(false);
  247. if (!stacksCount()) //standard army//initial army
  248. {
  249. initArmy();
  250. }
  251. assert(validTypes());
  252. if(exp == 0xffffffff)
  253. {
  254. initExp();
  255. }
  256. else
  257. {
  258. levelUpAutomatically();
  259. }
  260. if (VLC->modh->modules.COMMANDERS && !commander)
  261. {
  262. commander = new CCommanderInstance(type->heroClass->commander->idNumber);
  263. commander->setArmyObj (castToArmyObj()); //TODO: separate function for setting commanders
  264. commander->giveStackExp (exp); //after our exp is set
  265. }
  266. if (mana < 0)
  267. mana = manaLimit();
  268. }
  269. void CGHeroInstance::initArmy(IArmyDescriptor *dst /*= nullptr*/)
  270. {
  271. if(!dst)
  272. dst = this;
  273. int howManyStacks = 0; //how many stacks will hero receives <1 - 3>
  274. int pom = cb->gameState()->getRandomGenerator().nextInt(99);
  275. int warMachinesGiven = 0;
  276. if(pom < 9)
  277. howManyStacks = 1;
  278. else if(pom < 79)
  279. howManyStacks = 2;
  280. else
  281. howManyStacks = 3;
  282. vstd::amin(howManyStacks, type->initialArmy.size());
  283. for(int stackNo=0; stackNo < howManyStacks; stackNo++)
  284. {
  285. auto & stack = type->initialArmy[stackNo];
  286. int count = cb->gameState()->getRandomGenerator().nextInt(stack.minAmount, stack.maxAmount);
  287. if(stack.creature >= CreatureID::CATAPULT &&
  288. stack.creature <= CreatureID::ARROW_TOWERS) //war machine
  289. {
  290. warMachinesGiven++;
  291. if(dst != this)
  292. continue;
  293. int slot = -1;
  294. ArtifactID aid = ArtifactID::NONE;
  295. switch (stack.creature)
  296. {
  297. case CreatureID::CATAPULT:
  298. slot = ArtifactPosition::MACH4;
  299. aid = ArtifactID::CATAPULT;
  300. break;
  301. default:
  302. aid = CArtHandler::creatureToMachineID(stack.creature);
  303. slot = 9 + aid;
  304. break;
  305. }
  306. auto convSlot = ArtifactPosition(slot);
  307. if(!getArt(convSlot))
  308. putArtifact(convSlot, CArtifactInstance::createNewArtifactInstance(aid));
  309. else
  310. logGlobal->warnStream() << "Hero " << name << " already has artifact at " << slot << ", omitting giving " << aid;
  311. }
  312. else
  313. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  314. }
  315. }
  316. CGHeroInstance::~CGHeroInstance()
  317. {
  318. commander.dellNull();
  319. }
  320. bool CGHeroInstance::needsLastStack() const
  321. {
  322. return true;
  323. }
  324. void CGHeroInstance::onHeroVisit(const CGHeroInstance * h) const
  325. {
  326. if(h == this) return; //exclude potential self-visiting
  327. if (ID == Obj::HERO)
  328. {
  329. if( cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner)) //our or ally hero
  330. {
  331. //exchange
  332. cb->heroExchange(h->id, id);
  333. }
  334. else //battle
  335. {
  336. if(visitedTown) //we're in town
  337. visitedTown->onHeroVisit(h); //town will handle attacking
  338. else
  339. cb->startBattleI(h, this);
  340. }
  341. }
  342. else if(ID == Obj::PRISON)
  343. {
  344. int txt_id;
  345. if (cb->getHeroCount(h->tempOwner, false) < VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)//GameConstants::MAX_HEROES_PER_PLAYER) //free hero slot
  346. {
  347. cb->changeObjPos(id,pos+int3(1,0,0),0);
  348. //update hero parameters
  349. SetMovePoints smp;
  350. smp.hid = id;
  351. smp.val = maxMovePoints (true); //TODO: hota prison on water?
  352. cb->setMovePoints (&smp);
  353. cb->setManaPoints (id, manaLimit());
  354. cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
  355. cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player
  356. txt_id = 102;
  357. }
  358. else //already 8 wandering heroes
  359. {
  360. txt_id = 103;
  361. }
  362. showInfoDialog(h,txt_id,soundBase::ROGUE);
  363. }
  364. }
  365. std::string CGHeroInstance::getObjectName() const
  366. {
  367. if(ID != Obj::PRISON)
  368. {
  369. std::string hoverName = VLC->generaltexth->allTexts[15];
  370. boost::algorithm::replace_first(hoverName,"%s",name);
  371. boost::algorithm::replace_first(hoverName,"%s", type->heroClass->name);
  372. return hoverName;
  373. }
  374. else
  375. return CGObjectInstance::getObjectName();
  376. }
  377. const std::string & CGHeroInstance::getBiography() const
  378. {
  379. if (biography.length())
  380. return biography;
  381. return type->biography;
  382. }
  383. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  384. {
  385. return type->heroClass->isMagicHero() ? 3 : 4;
  386. }
  387. ui8 CGHeroInstance::maxlevelsToWisdom() const
  388. {
  389. return type->heroClass->isMagicHero() ? 3 : 6;
  390. }
  391. void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
  392. {
  393. magicSchoolCounter = 1;
  394. }
  395. void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
  396. {
  397. wisdomCounter = 1;
  398. }
  399. void CGHeroInstance::initObj()
  400. {
  401. blockVisit = true;
  402. auto hs = new HeroSpecial();
  403. hs->setNodeType(CBonusSystemNode::SPECIALTY);
  404. attachTo(hs); //do we ever need to detach it?
  405. if(!type)
  406. initHero(); //TODO: set up everything for prison before specialties are configured
  407. skillsInfo.rand.setSeed(cb->gameState()->getRandomGenerator().nextInt());
  408. skillsInfo.resetMagicSchoolCounter();
  409. skillsInfo.resetWisdomCounter();
  410. if (ID != Obj::PRISON)
  411. {
  412. auto customApp = VLC->objtypeh->getHandlerFor(ID, type->heroClass->id)->getOverride(cb->gameState()->getTile(visitablePos())->terType, this);
  413. if (customApp)
  414. appearance = customApp.get();
  415. }
  416. for(const auto &spec : type->spec) //TODO: unfity with bonus system
  417. {
  418. auto bonus = new Bonus();
  419. bonus->val = spec.val;
  420. bonus->sid = id.getNum(); //from the hero, specialty has no unique id
  421. bonus->duration = Bonus::PERMANENT;
  422. bonus->source = Bonus::HERO_SPECIAL;
  423. switch (spec.type)
  424. {
  425. case 1:// creature specialty
  426. {
  427. hs->growsWithLevel = true;
  428. const CCreature &specCreature = *VLC->creh->creatures[spec.additionalinfo]; //creature in which we have specialty
  429. //int creLevel = specCreature.level;
  430. //if(!creLevel)
  431. //{
  432. // if(spec.additionalinfo == 146)
  433. // creLevel = 5; //treat ballista as 5-level
  434. // else
  435. // {
  436. // logGlobal->warnStream() << "Warning: unknown level of " << specCreature.namePl;
  437. // continue;
  438. // }
  439. //}
  440. //bonus->additionalInfo = spec.additionalinfo; //creature id, should not be used again - this works only with limiter
  441. bonus->limiter.reset(new CCreatureTypeLimiter (specCreature, true)); //with upgrades
  442. bonus->type = Bonus::PRIMARY_SKILL;
  443. bonus->valType = Bonus::ADDITIVE_VALUE;
  444. bonus->subtype = PrimarySkill::ATTACK;
  445. hs->addNewBonus(bonus);
  446. bonus = new Bonus(*bonus);
  447. bonus->subtype = PrimarySkill::DEFENSE;
  448. hs->addNewBonus(bonus);
  449. //values will be calculated later
  450. bonus = new Bonus(*bonus);
  451. bonus->type = Bonus::STACKS_SPEED;
  452. bonus->val = 1; //+1 speed
  453. hs->addNewBonus(bonus);
  454. }
  455. break;
  456. case 2://secondary skill
  457. hs->growsWithLevel = true;
  458. bonus->type = Bonus::SPECIAL_SECONDARY_SKILL; //needs to be recalculated with level, based on this value
  459. bonus->valType = Bonus::BASE_NUMBER; // to receive nonzero value
  460. bonus->subtype = spec.subtype; //skill id
  461. bonus->val = spec.val; //value per level, in percent
  462. hs->addNewBonus(bonus);
  463. bonus = new Bonus(*bonus);
  464. switch (spec.additionalinfo)
  465. {
  466. case 0: //normal
  467. bonus->valType = Bonus::PERCENT_TO_BASE;
  468. break;
  469. case 1: //when it's navigation or there's no 'base' at all
  470. bonus->valType = Bonus::PERCENT_TO_ALL;
  471. break;
  472. }
  473. bonus->type = Bonus::SECONDARY_SKILL_PREMY; //value will be calculated later
  474. hs->addNewBonus(bonus);
  475. break;
  476. case 3://spell damage bonus, level dependent but calculated elsewhere
  477. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  478. bonus->subtype = spec.subtype;
  479. hs->addNewBonus(bonus);
  480. break;
  481. case 4://creature stat boost
  482. switch (spec.subtype)
  483. {
  484. case 1://attack
  485. bonus->type = Bonus::PRIMARY_SKILL;
  486. bonus->subtype = PrimarySkill::ATTACK;
  487. break;
  488. case 2://defense
  489. bonus->type = Bonus::PRIMARY_SKILL;
  490. bonus->subtype = PrimarySkill::DEFENSE;
  491. break;
  492. case 3:
  493. bonus->type = Bonus::CREATURE_DAMAGE;
  494. bonus->subtype = 0; //both min and max
  495. break;
  496. case 4://hp
  497. bonus->type = Bonus::STACK_HEALTH;
  498. break;
  499. case 5:
  500. bonus->type = Bonus::STACKS_SPEED;
  501. break;
  502. default:
  503. continue;
  504. }
  505. bonus->additionalInfo = spec.additionalinfo; //creature id
  506. bonus->valType = Bonus::ADDITIVE_VALUE;
  507. bonus->limiter.reset(new CCreatureTypeLimiter (*VLC->creh->creatures[spec.additionalinfo], true));
  508. hs->addNewBonus(bonus);
  509. break;
  510. case 5://spell damage bonus in percent
  511. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  512. bonus->valType = Bonus::BASE_NUMBER; // current spell system is screwed
  513. bonus->subtype = spec.subtype; //spell id
  514. hs->addNewBonus(bonus);
  515. break;
  516. case 6://damage bonus for bless (Adela)
  517. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  518. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  519. bonus->additionalInfo = spec.additionalinfo; //damage factor
  520. hs->addNewBonus(bonus);
  521. break;
  522. case 7://maxed mastery for spell
  523. bonus->type = Bonus::MAXED_SPELL;
  524. bonus->subtype = spec.subtype; //spell i
  525. hs->addNewBonus(bonus);
  526. break;
  527. case 8://peculiar spells - enchantments
  528. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  529. bonus->subtype = spec.subtype; //spell id
  530. bonus->additionalInfo = spec.additionalinfo;//0, 1 for Coronius
  531. hs->addNewBonus(bonus);
  532. break;
  533. case 9://upgrade creatures
  534. {
  535. const auto &creatures = VLC->creh->creatures;
  536. bonus->type = Bonus::SPECIAL_UPGRADE;
  537. bonus->subtype = spec.subtype; //base id
  538. bonus->additionalInfo = spec.additionalinfo; //target id
  539. hs->addNewBonus(bonus);
  540. bonus = new Bonus(*bonus);
  541. for(auto cre_id : creatures[spec.subtype]->upgrades)
  542. {
  543. bonus->subtype = cre_id; //propagate for regular upgrades of base creature
  544. hs->addNewBonus(bonus);
  545. bonus = new Bonus(*bonus);
  546. }
  547. vstd::clear_pointer(bonus);
  548. break;
  549. }
  550. case 10://resource generation
  551. bonus->type = Bonus::GENERATE_RESOURCE;
  552. bonus->subtype = spec.subtype;
  553. hs->addNewBonus(bonus);
  554. break;
  555. case 11://starting skill with mastery (Adrienne)
  556. setSecSkillLevel(SecondarySkill(spec.val), spec.additionalinfo, true);
  557. break;
  558. case 12://army speed
  559. bonus->type = Bonus::STACKS_SPEED;
  560. hs->addNewBonus(bonus);
  561. break;
  562. case 13://Dragon bonuses (Mutare)
  563. bonus->type = Bonus::PRIMARY_SKILL;
  564. bonus->valType = Bonus::ADDITIVE_VALUE;
  565. switch (spec.subtype)
  566. {
  567. case 1:
  568. bonus->subtype = PrimarySkill::ATTACK;
  569. break;
  570. case 2:
  571. bonus->subtype = PrimarySkill::DEFENSE;
  572. break;
  573. }
  574. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  575. hs->addNewBonus(bonus);
  576. break;
  577. default:
  578. logGlobal->warnStream() << "Unexpected hero specialty " << type;
  579. }
  580. }
  581. specialty.push_back(hs); //will it work?
  582. for (auto hs2 : type->specialty) //copy active (probably growing) bonuses from hero prootype to hero object
  583. {
  584. auto hs = new HeroSpecial();
  585. attachTo(hs); //do we ever need to detach it?
  586. hs->setNodeType(CBonusSystemNode::SPECIALTY);
  587. for (auto bonus : hs2.bonuses)
  588. {
  589. hs->addNewBonus (bonus);
  590. }
  591. hs->growsWithLevel = hs2.growsWithLevel;
  592. specialty.push_back(hs); //will it work?
  593. }
  594. //initialize bonuses
  595. recreateSecondarySkillsBonuses();
  596. Updatespecialty();
  597. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  598. type->name = name;
  599. }
  600. void CGHeroInstance::Updatespecialty() //TODO: calculate special value of bonuses on-the-fly?
  601. {
  602. for (auto hs : specialty)
  603. {
  604. if (hs->growsWithLevel)
  605. {
  606. //const auto &creatures = VLC->creh->creatures;
  607. for(Bonus * b : hs->getBonusList())
  608. {
  609. switch (b->type)
  610. {
  611. case Bonus::SECONDARY_SKILL_PREMY:
  612. b->val = (hs->valOfBonuses(Bonus::SPECIAL_SECONDARY_SKILL, b->subtype) * level);
  613. break; //use only hero skills as bonuses to avoid feedback loop
  614. case Bonus::PRIMARY_SKILL: //for creatures, that is
  615. {
  616. const CCreature * cre = nullptr;
  617. int creLevel = 0;
  618. if (auto creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(b->limiter)) //TODO: more general eveluation of bonuses?
  619. {
  620. cre = creatureLimiter->creature;
  621. creLevel = cre->level;
  622. if (!creLevel)
  623. {
  624. creLevel = 5; //treat ballista as tier 5
  625. }
  626. }
  627. else //no creature found, can't calculate value
  628. {
  629. logGlobal->warnStream() << "Primary skill specialty growth supported only with creature type limiters";
  630. break;
  631. }
  632. double primSkillModifier = (int)(level / creLevel) / 20.0;
  633. int param;
  634. switch (b->subtype)
  635. {
  636. case PrimarySkill::ATTACK:
  637. param = cre->Attack();
  638. break;
  639. case PrimarySkill::DEFENSE:
  640. param = cre->Defense();
  641. break;
  642. default:
  643. continue;
  644. }
  645. b->val = ceil(param * (1 + primSkillModifier)) - param; //yep, overcomplicated but matches original
  646. break;
  647. }
  648. }
  649. }
  650. }
  651. }
  652. }
  653. void CGHeroInstance::recreateSecondarySkillsBonuses()
  654. {
  655. auto secondarySkillsBonuses = getBonuses(Selector::sourceType(Bonus::SECONDARY_SKILL));
  656. for(auto bonus : *secondarySkillsBonuses)
  657. removeBonus(bonus);
  658. for(auto skill_info : secSkills)
  659. updateSkill(SecondarySkill(skill_info.first), skill_info.second);
  660. }
  661. void CGHeroInstance::updateSkill(SecondarySkill which, int val)
  662. {
  663. if(which == SecondarySkill::LEADERSHIP || which == SecondarySkill::LUCK)
  664. { //luck-> VLC->generaltexth->arraytxt[73+luckSkill]; VLC->generaltexth->arraytxt[104+moraleSkill]
  665. bool luck = which == SecondarySkill::LUCK;
  666. Bonus::BonusType type[] = {Bonus::MORALE, Bonus::LUCK};
  667. Bonus *b = getBonusLocalFirst(Selector::type(type[luck]).And(Selector::sourceType(Bonus::SECONDARY_SKILL)));
  668. if(!b)
  669. {
  670. b = new Bonus(Bonus::PERMANENT, type[luck], Bonus::SECONDARY_SKILL, +val, which, which, Bonus::BASE_NUMBER);
  671. addNewBonus(b);
  672. }
  673. else
  674. b->val = +val;
  675. }
  676. else if(which == SecondarySkill::DIPLOMACY) //surrender discount: 20% per level
  677. {
  678. if(Bonus *b = getBonusLocalFirst(Selector::type(Bonus::SURRENDER_DISCOUNT).And(Selector::sourceType(Bonus::SECONDARY_SKILL))))
  679. b->val = +val;
  680. else
  681. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::SURRENDER_DISCOUNT, Bonus::SECONDARY_SKILL, val * 20, which));
  682. }
  683. int skillVal = 0;
  684. switch (which)
  685. {
  686. case SecondarySkill::ARCHERY:
  687. switch (val)
  688. {
  689. case 1:
  690. skillVal = 10; break;
  691. case 2:
  692. skillVal = 25; break;
  693. case 3:
  694. skillVal = 50; break;
  695. }
  696. break;
  697. case SecondarySkill::LOGISTICS:
  698. skillVal = 10 * val; break;
  699. case SecondarySkill::NAVIGATION:
  700. skillVal = 50 * val; break;
  701. case SecondarySkill::MYSTICISM:
  702. skillVal = val; break;
  703. case SecondarySkill::EAGLE_EYE:
  704. skillVal = 30 + 10 * val; break;
  705. case SecondarySkill::NECROMANCY:
  706. skillVal = 10 * val; break;
  707. case SecondarySkill::LEARNING:
  708. skillVal = 5 * val; break;
  709. case SecondarySkill::OFFENCE:
  710. skillVal = 10 * val; break;
  711. case SecondarySkill::ARMORER:
  712. skillVal = 5 * val; break;
  713. case SecondarySkill::INTELLIGENCE:
  714. skillVal = 25 << (val-1); break;
  715. case SecondarySkill::SORCERY:
  716. skillVal = 5 * val; break;
  717. case SecondarySkill::RESISTANCE:
  718. skillVal = 5 << (val-1); break;
  719. case SecondarySkill::FIRST_AID:
  720. skillVal = 25 + 25*val; break;
  721. case SecondarySkill::ESTATES:
  722. skillVal = 125 << (val-1); break;
  723. }
  724. Bonus::ValueType skillValType = skillVal ? Bonus::BASE_NUMBER : Bonus::INDEPENDENT_MIN;
  725. if(Bonus * b = getBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which)
  726. .And(Selector::sourceType(Bonus::SECONDARY_SKILL)))) //only local hero bonus
  727. {
  728. b->val = skillVal;
  729. b->valType = skillValType;
  730. }
  731. else
  732. {
  733. auto bonus = new Bonus(Bonus::PERMANENT, Bonus::SECONDARY_SKILL_PREMY, Bonus::SECONDARY_SKILL, skillVal, id.getNum(), which, skillValType);
  734. bonus->source = Bonus::SECONDARY_SKILL;
  735. addNewBonus(bonus);
  736. }
  737. }
  738. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  739. {
  740. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  741. setStackCount(SlotID(0), val);
  742. }
  743. double CGHeroInstance::getFightingStrength() const
  744. {
  745. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  746. }
  747. double CGHeroInstance::getMagicStrength() const
  748. {
  749. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::KNOWLEDGE)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::SPELL_POWER)));
  750. }
  751. double CGHeroInstance::getHeroStrength() const
  752. {
  753. return sqrt(pow(getFightingStrength(), 2.0) * pow(getMagicStrength(), 2.0));
  754. }
  755. ui64 CGHeroInstance::getTotalStrength() const
  756. {
  757. double ret = getFightingStrength() * getArmyStrength();
  758. return (ui64) ret;
  759. }
  760. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  761. {
  762. return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
  763. }
  764. ui8 CGHeroInstance::getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool) const
  765. {
  766. si16 skill = -1; //skill level
  767. spell->forEachSchool([&, this](const SpellSchoolInfo & cnf, bool & stop)
  768. {
  769. int thisSchool = std::max<int>(getSecSkillLevel(cnf.skill), valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << ((ui8)cnf.id))); //FIXME: Bonus shouldn't be additive (Witchking Artifacts : Crown of Skies)
  770. if(thisSchool > skill)
  771. {
  772. skill = thisSchool;
  773. if(outSelectedSchool)
  774. *outSelectedSchool = (ui8)cnf.id;
  775. }
  776. });
  777. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  778. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect
  779. vstd::amax(skill, 0); //in case we don't know any school
  780. vstd::amin(skill, 3);
  781. return skill;
  782. }
  783. ui32 CGHeroInstance::getSpellBonus(const CSpell * spell, ui32 base, const CStack * affectedStack) const
  784. {
  785. //applying sorcery secondary skill
  786. base *= (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
  787. base *= (100.0 + valOfBonuses(Bonus::SPELL_DAMAGE) + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->id.toEnum())) / 100.0;
  788. spell->forEachSchool([&base, this](const SpellSchoolInfo & cnf, bool & stop)
  789. {
  790. base *= (100.0 + valOfBonuses(cnf.damagePremyBonus)) / 100.0;
  791. stop = true; //only bonus from one school is used
  792. });
  793. if (affectedStack && affectedStack->getCreature()->level) //Hero specials like Solmyr, Deemer
  794. base *= (100. + ((valOfBonuses(Bonus::SPECIAL_SPELL_LEV, spell->id.toEnum()) * level) / affectedStack->getCreature()->level)) / 100.0;
  795. return base;
  796. }
  797. int CGHeroInstance::getEffectLevel(const CSpell * spell) const
  798. {
  799. if(hasBonusOfType(Bonus::MAXED_SPELL, spell->id))
  800. return 3;//todo: recheck specialty from where this bonus is. possible bug
  801. else
  802. return getSpellSchoolLevel(spell);
  803. }
  804. int CGHeroInstance::getEffectPower(const CSpell * spell) const
  805. {
  806. return getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  807. }
  808. int CGHeroInstance::getEnchantPower(const CSpell * spell) const
  809. {
  810. return getPrimSkillLevel(PrimarySkill::SPELL_POWER) + valOfBonuses(Bonus::SPELL_DURATION);
  811. }
  812. int CGHeroInstance::getEffectValue(const CSpell * spell) const
  813. {
  814. return 0;
  815. }
  816. const PlayerColor CGHeroInstance::getOwner() const
  817. {
  818. return tempOwner;
  819. }
  820. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  821. {
  822. if(nullptr == getArt(ArtifactPosition::SPELLBOOK))
  823. return false;
  824. const bool isAllowed = IObjectInterface::cb->isAllowed(0, spell->id);
  825. const bool inSpellBook = vstd::contains(spells, spell->id);
  826. const bool specificBonus = hasBonusOfType(Bonus::SPELL, spell->id);
  827. bool schoolBonus = false;
  828. spell->forEachSchool([this, &schoolBonus](const SpellSchoolInfo & cnf, bool & stop)
  829. {
  830. if(hasBonusOfType(cnf.knoledgeBonus))
  831. {
  832. schoolBonus = stop = true;
  833. }
  834. });
  835. const bool levelBonus = hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level);
  836. if (spell->isSpecialSpell())
  837. {
  838. if (inSpellBook)
  839. {//hero has this spell in spellbook
  840. logGlobal->errorStream() << "Special spell " << spell->name << "in spellbook.";
  841. }
  842. return specificBonus;
  843. }
  844. else if(!isAllowed)
  845. {
  846. if (inSpellBook)
  847. {//hero has this spell in spellbook
  848. logGlobal->errorStream() << "Banned spell " << spell->name << " in spellbook.";
  849. }
  850. return specificBonus || schoolBonus || levelBonus;
  851. }
  852. else
  853. {
  854. return inSpellBook || schoolBonus || specificBonus || levelBonus;
  855. }
  856. }
  857. /**
  858. * Calculates what creatures and how many to be raised from a battle.
  859. * @param battleResult The results of the battle.
  860. * @return Returns a pair with the first value indicating the ID of the creature
  861. * type and second value the amount. Both values are returned as -1 if necromancy
  862. * could not be applied.
  863. */
  864. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  865. {
  866. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  867. // Hero knows necromancy or has Necromancer Cloak
  868. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  869. {
  870. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  871. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  872. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  873. ui32 raisedUnits = 0;
  874. // Figure out what to raise and how many.
  875. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  876. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  877. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  878. const ui32 raisedUnitHP = raisedUnitType->valOfBonuses(Bonus::STACK_HEALTH);
  879. //calculate creatures raised from each defeated stack
  880. for (auto & casualtie : casualties)
  881. {
  882. // Get lost enemy hit points convertible to units.
  883. CCreature * c = VLC->creh->creatures[casualtie.first];
  884. const ui32 raisedHP = c->valOfBonuses(Bonus::STACK_HEALTH) * casualtie.second * necromancySkill;
  885. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, casualtie.second * necromancySkill); //limit to % of HP and % of original stack count
  886. }
  887. // Make room for new units.
  888. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  889. if (slot == SlotID())
  890. {
  891. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  892. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  893. raisedUnits = (raisedUnits*2)/3;
  894. slot = getSlotFor(raisedUnitType->idNumber);
  895. }
  896. if (raisedUnits <= 0)
  897. raisedUnits = 1;
  898. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  899. }
  900. return CStackBasicDescriptor();
  901. }
  902. /**
  903. * Show the necromancy dialog with information about units raised.
  904. * @param raisedStack Pair where the first element represents ID of the raised creature
  905. * and the second element the amount.
  906. */
  907. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack) const
  908. {
  909. InfoWindow iw;
  910. iw.soundID = soundBase::pickup01 + cb->gameState()->getRandomGenerator().nextInt(6);
  911. iw.player = tempOwner;
  912. iw.components.push_back(Component(raisedStack));
  913. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  914. {
  915. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  916. iw.text.addReplacement(raisedStack.count);
  917. }
  918. else // Practicing the dark arts of necromancy, ... (singular)
  919. {
  920. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  921. }
  922. iw.text.addReplacement(raisedStack);
  923. cb->showInfoDialog(&iw);
  924. }
  925. /*
  926. int3 CGHeroInstance::getSightCenter() const
  927. {
  928. return getPosition(false);
  929. }*/
  930. int CGHeroInstance::getSightRadious() const
  931. {
  932. return 5 + getSecSkillLevel(SecondarySkill::SCOUTING) + valOfBonuses(Bonus::SIGHT_RADIOUS); //default + scouting
  933. }
  934. si32 CGHeroInstance::manaRegain() const
  935. {
  936. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  937. return manaLimit();
  938. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 8) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  939. }
  940. // /**
  941. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  942. // * or discards it if it cannot be equipped.
  943. // */
  944. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  945. // {
  946. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  947. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  948. // ai->putAt(this, ai->firstAvailableSlot(this));
  949. // }
  950. int CGHeroInstance::getBoatType() const
  951. {
  952. switch(type->heroClass->getAlignment())
  953. {
  954. case EAlignment::GOOD:
  955. return 1;
  956. case EAlignment::EVIL:
  957. return 0;
  958. case EAlignment::NEUTRAL:
  959. return 2;
  960. default:
  961. throw std::runtime_error("Wrong alignment!");
  962. }
  963. }
  964. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  965. {
  966. offsets =
  967. {
  968. int3(0,1,0), int3(0,-1,0), int3(-1,0,0), int3(+1,0,0), int3(1,1,0), int3(-1,1,0), int3(1,-1,0), int3(-1,-1,0)
  969. };
  970. }
  971. int CGHeroInstance::getSpellCost(const CSpell *sp) const
  972. {
  973. return sp->getCost(getSpellSchoolLevel(sp));
  974. }
  975. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  976. {
  977. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  978. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL))));
  979. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  980. }
  981. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  982. {
  983. return type->heroClass->getAlignment();
  984. }
  985. void CGHeroInstance::initExp()
  986. {
  987. exp = cb->gameState()->getRandomGenerator().nextInt(40, 89);
  988. }
  989. std::string CGHeroInstance::nodeName() const
  990. {
  991. return "Hero " + name;
  992. }
  993. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  994. {
  995. assert(!getArt(pos));
  996. art->putAt(ArtifactLocation(this, pos));
  997. }
  998. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  999. {
  1000. putArtifact(art->firstBackpackSlot(this), art);
  1001. }
  1002. bool CGHeroInstance::hasSpellbook() const
  1003. {
  1004. return getArt(ArtifactPosition::SPELLBOOK);
  1005. }
  1006. void CGHeroInstance::deserializationFix()
  1007. {
  1008. artDeserializationFix(this);
  1009. for (auto hs : specialty)
  1010. {
  1011. attachTo (hs);
  1012. }
  1013. }
  1014. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  1015. {
  1016. if(visitedTown)
  1017. {
  1018. if(inTownGarrison)
  1019. return visitedTown;
  1020. else
  1021. return &visitedTown->townAndVis;
  1022. }
  1023. else
  1024. return CArmedInstance::whereShouldBeAttached(gs);
  1025. }
  1026. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark /*= false*/, const TurnInfo * ti) const
  1027. {
  1028. if(!ti)
  1029. ti = new TurnInfo(this);
  1030. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL);
  1031. int mp2 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  1032. if(ti->hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  1033. return (MPsBefore - basicCost) * static_cast<double>(mp1) / mp2;
  1034. return 0; //take all MPs otherwise
  1035. }
  1036. CGHeroInstance::ECanDig CGHeroInstance::diggingStatus() const
  1037. {
  1038. if(movement < maxMovePoints(true))
  1039. return LACK_OF_MOVEMENT;
  1040. else if(cb->getTile(getPosition(false))->terType == ETerrainType::WATER)
  1041. return WRONG_TERRAIN;
  1042. else
  1043. {
  1044. const TerrainTile *t = cb->getTile(getPosition());
  1045. //TODO look for hole
  1046. //CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  1047. if(/*hlp.length() || */t->blockingObjects.size() > 1)
  1048. return TILE_OCCUPIED;
  1049. else
  1050. return CAN_DIG;
  1051. }
  1052. }
  1053. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1054. {
  1055. return ArtBearer::HERO;
  1056. }
  1057. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
  1058. {
  1059. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  1060. if (!skillsInfo.wisdomCounter)
  1061. {
  1062. if (cb->isAllowed(2, SecondarySkill::WISDOM) && !getSecSkillLevel(SecondarySkill::WISDOM))
  1063. obligatorySkills.push_back(SecondarySkill::WISDOM);
  1064. }
  1065. if (!skillsInfo.magicSchoolCounter)
  1066. {
  1067. std::vector<SecondarySkill> ss =
  1068. {
  1069. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC
  1070. };
  1071. std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());
  1072. for (auto skill : ss)
  1073. {
  1074. if (cb->isAllowed(2, skill) && !getSecSkillLevel(skill)) //only schools hero doesn't know yet
  1075. {
  1076. obligatorySkills.push_back(skill);
  1077. break; //only one
  1078. }
  1079. }
  1080. }
  1081. std::vector<SecondarySkill> skills;
  1082. //picking sec. skills for choice
  1083. std::set<SecondarySkill> basicAndAdv, expert, none;
  1084. for(int i=0;i<GameConstants::SKILL_QUANTITY;i++)
  1085. if (cb->isAllowed(2,i))
  1086. none.insert(SecondarySkill(i));
  1087. for(auto & elem : secSkills)
  1088. {
  1089. if(elem.second < SecSkillLevel::EXPERT)
  1090. basicAndAdv.insert(elem.first);
  1091. else
  1092. expert.insert(elem.first);
  1093. none.erase(elem.first);
  1094. }
  1095. for (auto s : obligatorySkills) //don't duplicate them
  1096. {
  1097. none.erase (s);
  1098. basicAndAdv.erase (s);
  1099. expert.erase (s);
  1100. }
  1101. //first offered skill:
  1102. // 1) give obligatory skill
  1103. // 2) give any other new skill
  1104. // 3) upgrade existing
  1105. if (canLearnSkill() && obligatorySkills.size() > 0)
  1106. {
  1107. skills.push_back (obligatorySkills[0]);
  1108. }
  1109. else if(none.size() && canLearnSkill()) //hero have free skill slot
  1110. {
  1111. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
  1112. none.erase(skills.back());
  1113. }
  1114. else if(!basicAndAdv.empty())
  1115. {
  1116. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
  1117. basicAndAdv.erase(skills.back());
  1118. }
  1119. //second offered skill:
  1120. //1) upgrade existing
  1121. //2) give obligatory skill
  1122. //3) give any other new skill
  1123. if(!basicAndAdv.empty())
  1124. {
  1125. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
  1126. skills.push_back(s);
  1127. basicAndAdv.erase(s);
  1128. }
  1129. else if (canLearnSkill() && obligatorySkills.size() > 1)
  1130. {
  1131. skills.push_back (obligatorySkills[1]);
  1132. }
  1133. else if(none.size() && canLearnSkill())
  1134. {
  1135. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
  1136. none.erase(skills.back());
  1137. }
  1138. if (skills.size() == 2) // Fix for #1868 to avoid changing logic (possibly causing bugs in process)
  1139. std::swap(skills[0], skills[1]);
  1140. return skills;
  1141. }
  1142. PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill() const
  1143. {
  1144. assert(gainsLevel());
  1145. int randomValue = cb->gameState()->getRandomGenerator().nextInt(99), pom = 0, primarySkill = 0;
  1146. const auto & skillChances = (level > 9) ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;
  1147. for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
  1148. {
  1149. pom += skillChances[primarySkill];
  1150. if(randomValue < pom)
  1151. {
  1152. break;
  1153. }
  1154. }
  1155. logGlobal->traceStream() << "The hero gets the primary skill " << primarySkill << " with a probability of " << randomValue << "%.";
  1156. return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
  1157. }
  1158. boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill() const
  1159. {
  1160. assert(gainsLevel());
  1161. boost::optional<SecondarySkill> chosenSecondarySkill;
  1162. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1163. if(!proposedSecondarySkills.empty())
  1164. {
  1165. std::vector<SecondarySkill> learnedSecondarySkills;
  1166. for(auto secondarySkill : proposedSecondarySkills)
  1167. {
  1168. if(getSecSkillLevel(secondarySkill) > 0)
  1169. {
  1170. learnedSecondarySkills.push_back(secondarySkill);
  1171. }
  1172. }
  1173. auto & rand = cb->gameState()->getRandomGenerator();
  1174. if(learnedSecondarySkills.empty())
  1175. {
  1176. // there are only new skills to learn, so choose anyone of them
  1177. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand);
  1178. }
  1179. else
  1180. {
  1181. // preferably upgrade a already learned secondary skill
  1182. chosenSecondarySkill = *RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand);
  1183. }
  1184. }
  1185. return chosenSecondarySkill;
  1186. }
  1187. void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
  1188. {
  1189. if(primarySkill < PrimarySkill::EXPERIENCE)
  1190. {
  1191. Bonus * skill = getBonusLocalFirst(Selector::type(Bonus::PRIMARY_SKILL)
  1192. .And(Selector::subtype(primarySkill))
  1193. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));
  1194. assert(skill);
  1195. if(abs)
  1196. {
  1197. skill->val = value;
  1198. }
  1199. else
  1200. {
  1201. skill->val += value;
  1202. }
  1203. }
  1204. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1205. {
  1206. if(abs)
  1207. {
  1208. exp = value;
  1209. }
  1210. else
  1211. {
  1212. exp += value;
  1213. }
  1214. }
  1215. }
  1216. bool CGHeroInstance::gainsLevel() const
  1217. {
  1218. return exp >= VLC->heroh->reqExp(level+1);
  1219. }
  1220. void CGHeroInstance::levelUp(std::vector<SecondarySkill> skills)
  1221. {
  1222. ++level;
  1223. //deterministic secondary skills
  1224. skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
  1225. skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
  1226. if(vstd::contains(skills, SecondarySkill::WISDOM))
  1227. {
  1228. skillsInfo.resetWisdomCounter();
  1229. }
  1230. SecondarySkill spellSchools[] = {
  1231. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
  1232. for(auto skill : spellSchools)
  1233. {
  1234. if(vstd::contains(skills, skill))
  1235. {
  1236. skillsInfo.resetMagicSchoolCounter();
  1237. break;
  1238. }
  1239. }
  1240. //specialty
  1241. Updatespecialty();
  1242. }
  1243. void CGHeroInstance::levelUpAutomatically()
  1244. {
  1245. while(gainsLevel())
  1246. {
  1247. const auto primarySkill = nextPrimarySkill();
  1248. setPrimarySkill(primarySkill, 1, false);
  1249. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
  1250. const auto secondarySkill = nextSecondarySkill();
  1251. if(secondarySkill)
  1252. {
  1253. setSecSkillLevel(*secondarySkill, 1, false);
  1254. }
  1255. //TODO why has the secondary skills to be passed to the method?
  1256. levelUp(proposedSecondarySkills);
  1257. }
  1258. }
  1259. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, const int subtype) const
  1260. {
  1261. //VISIONS spell support
  1262. const std::string cached = boost::to_string((boost::format("type_%d__subtype_%d") % Bonus::VISIONS % subtype));
  1263. const int visionsMultiplier = valOfBonuses(Selector::typeSubtype(Bonus::VISIONS,subtype), cached);
  1264. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1265. if (visionsMultiplier > 0)
  1266. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1267. const int distance = target->pos.dist2d(getPosition(false));
  1268. //logGlobal->debug(boost::to_string(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1269. return (distance < visionsRange) && (target->pos.z == pos.z);
  1270. }