CGHeroInstance.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. * CGHeroInstance.h, 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. #pragma once
  11. #include <vcmi/spells/Caster.h>
  12. #include "CArmedInstance.h"
  13. #include "IOwnableObject.h"
  14. #include "../bonuses/BonusCache.h"
  15. #include "../entities/hero/EHeroGender.h"
  16. VCMI_LIB_NAMESPACE_BEGIN
  17. class CHero;
  18. class CGBoat;
  19. class CGTownInstance;
  20. class CMap;
  21. class UpgradeInfo;
  22. class TurnInfo;
  23. struct TerrainTile;
  24. struct TurnInfoCache;
  25. class DLL_LINKAGE CGHeroPlaceholder : public CGObjectInstance
  26. {
  27. public:
  28. using CGObjectInstance::CGObjectInstance;
  29. /// if this is placeholder by power, then power rank of desired hero
  30. std::optional<ui8> powerRank;
  31. /// if this is placeholder by type, then hero type of desired hero
  32. std::optional<HeroTypeID> heroType;
  33. template <typename Handler> void serialize(Handler &h)
  34. {
  35. h & static_cast<CGObjectInstance&>(*this);
  36. h & powerRank;
  37. h & heroType;
  38. }
  39. protected:
  40. void serializeJsonOptions(JsonSerializeFormat & handler) override;
  41. };
  42. class DLL_LINKAGE CGHeroInstance : public CArmedInstance, public IBoatGenerator, public CArtifactSet, public spells::Caster, public AFactionMember, public ICreatureUpgrader, public IOwnableObject
  43. {
  44. // We serialize heroes into JSON for crossover
  45. friend class CampaignState;
  46. friend class CMapLoaderH3M;
  47. friend class CMapFormatJson;
  48. PrimarySkillsCache primarySkills;
  49. MagicSchoolMasteryCache magicSchoolMastery;
  50. BonusValueCache manaPerKnowledgeCached;
  51. std::unique_ptr<TurnInfoCache> turnInfoCache;
  52. std::unique_ptr<CCommanderInstance> commander;
  53. std::set<SpellID> spells; //known spells (spell IDs)
  54. ObjectInstanceID visitedTown; //set if hero is visiting town or in the town garrison
  55. ObjectInstanceID boardedBoat; //set to CGBoat when sailing
  56. ui32 movement; //remaining movement points
  57. bool inTownGarrison; // if hero is in town garrison
  58. IGameInfoCallback * getCallback() const final { return cb; }
  59. public:
  60. //////////////////////////////////////////////////////////////////////////
  61. //format: 123
  62. // 8 4
  63. // 765
  64. ui8 moveDir;
  65. mutable ui8 tacticFormationEnabled;
  66. //////////////////////////////////////////////////////////////////////////
  67. TExpType exp; //experience points
  68. ui32 level; //current level of hero
  69. /// If not NONE - then hero should use portrait from referenced hero type
  70. HeroTypeID customPortraitSource;
  71. si32 mana; // remaining spell points
  72. std::vector<std::pair<SecondarySkill,ui8> > secSkills; //first - ID of skill, second - level of skill (1 - basic, 2 - adv., 3 - expert); if hero has ability (-1, -1) it meansthat it should have default secondary abilities
  73. EHeroGender gender;
  74. std::string nameCustomTextId;
  75. std::string biographyCustomTextId;
  76. static constexpr si32 UNINITIALIZED_MANA = -1;
  77. static constexpr ui32 UNINITIALIZED_MOVEMENT = -1;
  78. static constexpr auto UNINITIALIZED_EXPERIENCE = std::numeric_limits<TExpType>::max();
  79. static const ui32 NO_PATROLLING;
  80. std::set<ObjectInstanceID> visitedObjects;
  81. struct DLL_LINKAGE Patrol
  82. {
  83. bool patrolling{false};
  84. int3 initialPos;
  85. ui32 patrolRadius{NO_PATROLLING};
  86. template <typename Handler> void serialize(Handler &h)
  87. {
  88. h & patrolling;
  89. h & initialPos;
  90. h & patrolRadius;
  91. }
  92. } patrol;
  93. inline bool isInitialized() const
  94. { // has this hero been on the map at least once?
  95. return movement != UNINITIALIZED_MOVEMENT && mana != UNINITIALIZED_MANA;
  96. }
  97. //int3 getSightCenter() const; //"center" tile from which the sight distance is calculated
  98. int getSightRadius() const override; //sight distance (should be used if player-owned structure)
  99. //////////////////////////////////////////////////////////////////////////
  100. BoatId getBoatType() const override; //0 - evil (if a ship can be evil...?), 1 - good, 2 - neutral
  101. void getOutOffsets(std::vector<int3> &offsets) const override; //offsets to obj pos when we boat can be placed
  102. const IObjectInterface * getObject() const override;
  103. //////////////////////////////////////////////////////////////////////////
  104. std::string getBiographyTranslated() const;
  105. std::string getBiographyTextID() const;
  106. std::string getNameTextID() const;
  107. std::string getNameTranslated() const;
  108. HeroTypeID getPortraitSource() const;
  109. int32_t getIconIndex() const;
  110. std::string getClassNameTranslated() const;
  111. std::string getClassNameTextID() const;
  112. bool inBoat() const;
  113. CGBoat * getBoat();
  114. const CGBoat * getBoat() const;
  115. void setBoat(CGBoat * getBoat);
  116. bool hasSpellbook() const;
  117. int maxSpellLevel() const;
  118. void addSpellToSpellbook(const SpellID & spell);
  119. void removeSpellFromSpellbook(const SpellID & spell);
  120. bool spellbookContainsSpell(const SpellID & spell) const;
  121. std::vector<BonusSourceID> getSourcesForSpell(const SpellID & spell) const;
  122. void removeSpellbook();
  123. const std::set<SpellID> & getSpellsInSpellbook() const;
  124. EAlignment getAlignment() const;
  125. bool needsLastStack()const override;
  126. ResourceSet dailyIncome() const override;
  127. std::vector<CreatureID> providedCreatures() const override;
  128. const IOwnableObject * asOwnable() const final;
  129. //INativeTerrainProvider
  130. FactionID getFactionID() const override;
  131. TerrainId getNativeTerrain() const override;
  132. int getLowestCreatureSpeed() const;
  133. si32 manaRegain() const; //how many points of mana can hero regain "naturally" in one day
  134. si32 getManaNewTurn() const; //calculate how much mana this hero is going to have the next day
  135. int getCurrentLuck(int stack=-1, bool town=false) const;
  136. int32_t getSpellCost(const spells::Spell * sp) const; //do not use during battles -> bonuses from army would be ignored
  137. bool canLearnSpell(const spells::Spell * spell, bool allowBanned = false) const;
  138. bool canCastThisSpell(const spells::Spell * spell) const; //determines if this hero can cast given spell; takes into account existing spell in spellbook, existing spellbook and artifact bonuses
  139. /// convert given position between map position (CGObjectInstance::pos) and visitable position used for hero interactions
  140. int3 convertToVisitablePos(const int3 & position) const;
  141. int3 convertFromVisitablePos(const int3 & position) const;
  142. // ----- primary and secondary skill, experience, level handling -----
  143. /// Returns true if hero has lower level than should upon his experience.
  144. bool gainsLevel() const;
  145. /// Selects 0-2 skills for player to select on levelup
  146. std::vector<SecondarySkill> getLevelupSkillCandidates(IGameRandomizer & gameRandomizer) const;
  147. ui8 getSecSkillLevel(const SecondarySkill & skill) const; //0 - no skill
  148. int getPrimSkillLevel(PrimarySkill id) const;
  149. /// Returns true if hero has free secondary skill slot.
  150. bool canLearnSkill() const;
  151. bool canLearnSkill(const SecondarySkill & which) const;
  152. void setExperience(si64 value, ChangeValueMode mode);
  153. void setPrimarySkill(PrimarySkill primarySkill, si64 value, ChangeValueMode mode);
  154. void setSecSkillLevel(const SecondarySkill & which, int val, ChangeValueMode mode); // abs == 0 - changes by value; 1 - sets to value
  155. void levelUp();
  156. void setMovementPoints(int points);
  157. int movementPointsRemaining() const;
  158. int movementPointsLimit(bool onLand) const;
  159. //cached version is much faster, TurnInfo construction is costly
  160. int movementPointsLimitCached(bool onLand, const TurnInfo * ti) const;
  161. int movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const;
  162. std::unique_ptr<TurnInfo> getTurnInfo(int days) const;
  163. double getFightingStrength() const; // takes attack / defense skill into account
  164. double getMagicStrength() const; // takes knowledge / spell power skill but also current mana, whether the hero owns a spell-book and whether that books contains anything into account
  165. double getHeroStrength() const; // includes fighting and magic strength
  166. /// Returns true if 'left' hero is stronger than 'right' when considering campaign transfer priority
  167. static bool compareCampaignValue(const CGHeroInstance * left, const CGHeroInstance * right);
  168. uint64_t getValueForDiplomacy() const;
  169. ui64 getTotalStrength() const; // includes fighting strength and army strength
  170. TExpType calculateXp(TExpType exp) const; //apply learning skill
  171. int getBasePrimarySkillValue(PrimarySkill which) const; //the value of a base-skill without items or temporary bonuses
  172. CStackBasicDescriptor calculateNecromancy (const BattleResult &battleResult) const;
  173. EDiggingStatus diggingStatus() const;
  174. //////////////////////////////////////////////////////////////////////////
  175. const CHeroClass * getHeroClass() const;
  176. HeroClassID getHeroClassID() const;
  177. const CHero * getHeroType() const;
  178. HeroTypeID getHeroTypeID() const;
  179. void setHeroType(HeroTypeID type);
  180. bool isGarrisoned() const;
  181. const CGTownInstance * getVisitedTown() const;
  182. CGTownInstance * getVisitedTown();
  183. void setVisitedTown(const CGTownInstance * town, bool garrisoned);
  184. const CCommanderInstance * getCommander() const;
  185. CCommanderInstance * getCommander();
  186. void initObj(IGameRandomizer & gameRandomizer) override;
  187. void initHero(IGameRandomizer & gameRandomizer);
  188. void initHero(IGameRandomizer & gameRandomizer, const HeroTypeID & SUBID);
  189. ArtPlacementMap putArtifact(const ArtifactPosition & pos, const CArtifactInstance * art) override;
  190. void removeArtifact(const ArtifactPosition & pos) override;
  191. void initExp(vstd::RNG & rand);
  192. void initArmy(vstd::RNG & rand, IArmyDescriptor *dst = nullptr);
  193. void pushPrimSkill(PrimarySkill which, int val);
  194. ui8 maxlevelsToMagicSchool() const;
  195. ui8 maxlevelsToWisdom() const;
  196. void recreateSecondarySkillsBonuses();
  197. void updateSkillBonus(const SecondarySkill & which, int val);
  198. void fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const override;
  199. bool hasVisions(const CGObjectInstance * target, BonusSubtypeID masteryLevel) const;
  200. /// If this hero perishes, the scenario is failed
  201. bool isMissionCritical() const;
  202. CGHeroInstance(IGameInfoCallback *cb);
  203. virtual ~CGHeroInstance();
  204. PlayerColor getOwner() const override;
  205. ///ArtBearer
  206. ArtBearer bearerType() const override;
  207. ///IBonusBearer
  208. CBonusSystemNode & whereShouldBeAttached(CGameState & gs) override;
  209. std::string nodeName() const override;
  210. si32 manaLimit() const override;
  211. ///IConstBonusProvider
  212. const IBonusBearer* getBonusBearer() const override;
  213. ///spells::Caster
  214. int32_t getCasterUnitId() const override;
  215. int32_t getSpellSchoolLevel(const spells::Spell * spell, SpellSchool * outSelectedSchool = nullptr) const override;
  216. int64_t getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const override;
  217. int64_t getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const override;
  218. int32_t getEffectLevel(const spells::Spell * spell) const override;
  219. int32_t getEffectPower(const spells::Spell * spell) const override;
  220. int32_t getEnchantPower(const spells::Spell * spell) const override;
  221. int64_t getEffectValue(const spells::Spell * spell) const override;
  222. PlayerColor getCasterOwner() const override;
  223. const CGHeroInstance * getHeroCaster() const override;
  224. void getCasterName(MetaString & text) const override;
  225. void getCastDescription(const spells::Spell * spell, const battle::Units & attacked, MetaString & text) const override;
  226. void spendMana(ServerCallback * server, const int spellCost) const override;
  227. void updateAppearance();
  228. void pickRandomObject(IGameRandomizer & gameRandomizer) override;
  229. void onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const override;
  230. std::string getObjectName() const override;
  231. std::string getHoverText(PlayerColor player) const override;
  232. std::string getMovementPointsTextIfOwner(PlayerColor player) const;
  233. TObjectTypeHandler getObjectHandler() const override;
  234. void afterAddToMap(CMap * map) override;
  235. void afterRemoveFromMap(CMap * map) override;
  236. void attachToBonusSystem(CGameState & gs) override;
  237. void detachFromBonusSystem(CGameState & gs) override;
  238. void restoreBonusSystem(CGameState & gs) override;
  239. void updateFrom(const JsonNode & data) override;
  240. bool isCoastVisitable() const override;
  241. bool isBlockedVisitable() const override;
  242. BattleField getBattlefield() const override;
  243. bool isCampaignYog() const;
  244. bool isCampaignGem() const;
  245. protected:
  246. void setPropertyDer(ObjProperty what, ObjPropertyID identifier) override;//synchr
  247. ///common part of hero instance and hero definition
  248. void serializeCommonOptions(JsonSerializeFormat & handler);
  249. void serializeJsonOptions(JsonSerializeFormat & handler) override;
  250. private:
  251. void levelUpAutomatically(IGameRandomizer & gameRandomizer);
  252. void attachCommanderToArmy();
  253. public:
  254. std::string getHeroTypeName() const;
  255. void setHeroTypeName(const std::string & identifier);
  256. void serializeJsonDefinition(JsonSerializeFormat & handler);
  257. template <typename Handler> void serialize(Handler &h)
  258. {
  259. h & static_cast<CArmedInstance&>(*this);
  260. h & static_cast<CArtifactSet&>(*this);
  261. h & exp;
  262. h & level;
  263. h & nameCustomTextId;
  264. h & biographyCustomTextId;
  265. h & customPortraitSource;
  266. h & mana;
  267. h & secSkills;
  268. h & movement;
  269. h & gender;
  270. h & inTownGarrison;
  271. h & spells;
  272. h & patrol;
  273. h & moveDir;
  274. if (!h.hasFeature(Handler::Version::RANDOMIZATION_REWORK))
  275. {
  276. ui8 magicSchoolCounter = 0;
  277. ui8 wisdomCounter = 0;
  278. h & magicSchoolCounter;
  279. h & wisdomCounter;
  280. }
  281. if (h.hasFeature(Handler::Version::NO_RAW_POINTERS_IN_SERIALIZER))
  282. {
  283. h & visitedTown;
  284. h & boardedBoat;
  285. }
  286. else
  287. {
  288. std::shared_ptr<CGObjectInstance> ptrTown;
  289. std::shared_ptr<CGObjectInstance> ptrBoat;
  290. h & ptrTown;
  291. h & ptrBoat;
  292. visitedTown = ptrTown ? ptrTown->id : ObjectInstanceID();
  293. boardedBoat = ptrBoat ? ptrBoat->id : ObjectInstanceID();
  294. }
  295. h & commander;
  296. h & visitedObjects;
  297. if(!h.saving && h.loadingGamestate)
  298. attachCommanderToArmy();
  299. }
  300. };
  301. VCMI_LIB_NAMESPACE_END