CGHeroInstance.h 13 KB

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