CGHeroInstance.cpp 49 KB

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