CGHeroInstance.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 "../CArtHandler.h" // For CArtifactSet
  14. VCMI_LIB_NAMESPACE_BEGIN
  15. class CHero;
  16. class CGBoat;
  17. class CGTownInstance;
  18. class CMap;
  19. struct TerrainTile;
  20. struct TurnInfo;
  21. enum class EHeroGender : uint8_t;
  22. class DLL_LINKAGE CGHeroPlaceholder : public CGObjectInstance
  23. {
  24. public:
  25. /// if this is placeholder by power, then power rank of desired hero
  26. std::optional<ui8> powerRank;
  27. /// if this is placeholder by type, then hero type of desired hero
  28. std::optional<HeroTypeID> heroType;
  29. template <typename Handler> void serialize(Handler &h, const int version)
  30. {
  31. h & static_cast<CGObjectInstance&>(*this);
  32. h & powerRank;
  33. h & heroType;
  34. }
  35. protected:
  36. void serializeJsonOptions(JsonSerializeFormat & handler) override;
  37. };
  38. class DLL_LINKAGE CGHeroInstance : public CArmedInstance, public IBoatGenerator, public CArtifactSet, public spells::Caster, public AFactionMember, public ICreatureUpgrader
  39. {
  40. // We serialize heroes into JSON for crossover
  41. friend class CampaignState;
  42. friend class CMapLoaderH3M;
  43. friend class CMapFormatJson;
  44. private:
  45. std::set<SpellID> spells; //known spells (spell IDs)
  46. mutable int lowestCreatureSpeed;
  47. ui32 movement; //remaining movement points
  48. public:
  49. //////////////////////////////////////////////////////////////////////////
  50. //format: 123
  51. // 8 4
  52. // 765
  53. ui8 moveDir;
  54. mutable ui8 tacticFormationEnabled;
  55. //////////////////////////////////////////////////////////////////////////
  56. const CHero * type;
  57. TExpType exp; //experience points
  58. ui32 level; //current level of hero
  59. /// If not NONE - then hero should use portrait from referenced hero type
  60. HeroTypeID customPortraitSource;
  61. si32 mana; // remaining spell points
  62. 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
  63. EHeroGender gender;
  64. std::string nameCustomTextId;
  65. std::string biographyCustomTextId;
  66. bool inTownGarrison; // if hero is in town garrison
  67. ConstTransitivePtr<CGTownInstance> visitedTown; //set if hero is visiting town or in the town garrison
  68. ConstTransitivePtr<CCommanderInstance> commander;
  69. const CGBoat * boat = nullptr; //set to CGBoat when sailing
  70. static constexpr si32 UNINITIALIZED_MANA = -1;
  71. static constexpr ui32 UNINITIALIZED_MOVEMENT = -1;
  72. static constexpr auto UNINITIALIZED_EXPERIENCE = std::numeric_limits<TExpType>::max();
  73. //std::vector<const CArtifact*> artifacts; //hero's artifacts from bag
  74. //std::map<ui16, const CArtifact*> artifWorn; //map<position,artifact_id>; positions: 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5
  75. std::set<ObjectInstanceID> visitedObjects;
  76. struct DLL_LINKAGE Patrol
  77. {
  78. Patrol(){patrolling=false;initialPos=int3();patrolRadius=-1;};
  79. bool patrolling;
  80. int3 initialPos;
  81. ui32 patrolRadius;
  82. template <typename Handler> void serialize(Handler &h, const int version)
  83. {
  84. h & patrolling;
  85. h & initialPos;
  86. h & patrolRadius;
  87. }
  88. } patrol;
  89. struct DLL_LINKAGE SecondarySkillsInfo
  90. {
  91. ui8 magicSchoolCounter;
  92. ui8 wisdomCounter;
  93. SecondarySkillsInfo();
  94. void resetMagicSchoolCounter();
  95. void resetWisdomCounter();
  96. template <typename Handler> void serialize(Handler &h, const int version)
  97. {
  98. h & magicSchoolCounter;
  99. h & wisdomCounter;
  100. }
  101. } skillsInfo;
  102. inline bool isInitialized() const
  103. { // has this hero been on the map at least once?
  104. return movement != UNINITIALIZED_MOVEMENT && mana != UNINITIALIZED_MANA;
  105. }
  106. //int3 getSightCenter() const; //"center" tile from which the sight distance is calculated
  107. int getSightRadius() const override; //sight distance (should be used if player-owned structure)
  108. //////////////////////////////////////////////////////////////////////////
  109. BoatId getBoatType() const override; //0 - evil (if a ship can be evil...?), 1 - good, 2 - neutral
  110. void getOutOffsets(std::vector<int3> &offsets) const override; //offsets to obj pos when we boat can be placed
  111. const IObjectInterface * getObject() const override;
  112. //////////////////////////////////////////////////////////////////////////
  113. std::string getBiographyTranslated() const;
  114. std::string getNameTranslated() const;
  115. HeroTypeID getPortraitSource() const;
  116. int32_t getIconIndex() const;
  117. private:
  118. std::string getNameTextID() const;
  119. std::string getBiographyTextID() const;
  120. public:
  121. bool hasSpellbook() const;
  122. int maxSpellLevel() const;
  123. void addSpellToSpellbook(const SpellID & spell);
  124. void removeSpellFromSpellbook(const SpellID & spell);
  125. bool spellbookContainsSpell(const SpellID & spell) const;
  126. void removeSpellbook();
  127. const std::set<SpellID> & getSpellsInSpellbook() const;
  128. EAlignment getAlignment() const;
  129. bool needsLastStack()const override;
  130. //INativeTerrainProvider
  131. FactionID getFaction() const override;
  132. TerrainId getNativeTerrain() const override;
  133. int getLowestCreatureSpeed() const;
  134. si32 manaRegain() const; //how many points of mana can hero regain "naturally" in one day
  135. si32 getManaNewTurn() const; //calculate how much mana this hero is going to have the next day
  136. int getCurrentLuck(int stack=-1, bool town=false) const;
  137. int32_t getSpellCost(const spells::Spell * sp) const; //do not use during battles -> bonuses from army would be ignored
  138. bool canLearnSpell(const spells::Spell * spell, bool allowBanned = false) const;
  139. 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
  140. /// convert given position between map position (CGObjectInstance::pos) and visitable position used for hero interactions
  141. int3 convertToVisitablePos(const int3 & position) const;
  142. int3 convertFromVisitablePos(const int3 & position) const;
  143. // ----- primary and secondary skill, experience, level handling -----
  144. /// Returns true if hero has lower level than should upon his experience.
  145. bool gainsLevel() const;
  146. /// Returns the next primary skill on level up. Can only be called if hero can gain a level up.
  147. PrimarySkill nextPrimarySkill(CRandomGenerator & rand) const;
  148. /// Returns the next secondary skill randomly on level up. Can only be called if hero can gain a level up.
  149. std::optional<SecondarySkill> nextSecondarySkill(CRandomGenerator & rand) const;
  150. /// Gets 0, 1 or 2 secondary skills which are proposed on hero level up.
  151. std::vector<SecondarySkill> getLevelUpProposedSecondarySkills(CRandomGenerator & rand) const;
  152. ui8 getSecSkillLevel(const SecondarySkill & skill) const; //0 - no skill
  153. /// Returns true if hero has free secondary skill slot.
  154. bool canLearnSkill() const;
  155. bool canLearnSkill(const SecondarySkill & which) const;
  156. void setPrimarySkill(PrimarySkill primarySkill, si64 value, ui8 abs);
  157. void setSecSkillLevel(const SecondarySkill & which, int val, bool abs); // abs == 0 - changes by value; 1 - sets to value
  158. void levelUp(const std::vector<SecondarySkill> & skills);
  159. /// returns base movement cost for movement between specific tiles. Does not accounts for diagonal movement or last tile exception
  160. ui32 getTileMovementCost(const TerrainTile & dest, const TerrainTile & from, const TurnInfo * ti) const;
  161. void setMovementPoints(int points);
  162. int movementPointsRemaining() const;
  163. int movementPointsLimit(bool onLand) const;
  164. //cached version is much faster, TurnInfo construction is costly
  165. int movementPointsLimitCached(bool onLand, const TurnInfo * ti) const;
  166. //update army movement bonus
  167. void updateArmyMovementBonus(bool onLand, const TurnInfo * ti) const;
  168. int movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark = false, const TurnInfo * ti = nullptr) const;
  169. double getFightingStrength() const; // takes attack / defense skill into account
  170. double getMagicStrength() const; // takes knowledge / spell power skill into account
  171. double getHeroStrength() const; // includes fighting and magic strength
  172. ui64 getTotalStrength() const; // includes fighting strength and army strength
  173. TExpType calculateXp(TExpType exp) const; //apply learning skill
  174. CStackBasicDescriptor calculateNecromancy (const BattleResult &battleResult) const;
  175. void showNecromancyDialog(const CStackBasicDescriptor &raisedStack, CRandomGenerator & rand) const;
  176. EDiggingStatus diggingStatus() const;
  177. //////////////////////////////////////////////////////////////////////////
  178. HeroTypeID getHeroType() const;
  179. void setHeroType(HeroTypeID type);
  180. void initHero(CRandomGenerator & rand);
  181. void initHero(CRandomGenerator & rand, const HeroTypeID & SUBID);
  182. ArtPlacementMap putArtifact(ArtifactPosition pos, CArtifactInstance * art) override;
  183. void removeArtifact(ArtifactPosition pos) override;
  184. void initExp(CRandomGenerator & rand);
  185. void initArmy(CRandomGenerator & rand, IArmyDescriptor *dst = nullptr);
  186. void pushPrimSkill(PrimarySkill which, int val);
  187. ui8 maxlevelsToMagicSchool() const;
  188. ui8 maxlevelsToWisdom() const;
  189. void recreateSecondarySkillsBonuses();
  190. void updateSkillBonus(const SecondarySkill & which, int val);
  191. void fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const override;
  192. bool hasVisions(const CGObjectInstance * target, BonusSubtypeID masteryLevel) const;
  193. /// If this hero perishes, the scenario is failed
  194. bool isMissionCritical() const;
  195. CGHeroInstance();
  196. virtual ~CGHeroInstance();
  197. PlayerColor getOwner() const override;
  198. ///ArtBearer
  199. ArtBearer::ArtBearer bearerType() const override;
  200. ///IBonusBearer
  201. CBonusSystemNode & whereShouldBeAttached(CGameState * gs) override;
  202. std::string nodeName() const override;
  203. si32 manaLimit() const override;
  204. ///IConstBonusProvider
  205. const IBonusBearer* getBonusBearer() const override;
  206. CBonusSystemNode * whereShouldBeAttachedOnSiege(const bool isBattleOutsideTown) const;
  207. CBonusSystemNode * whereShouldBeAttachedOnSiege(CGameState * gs);
  208. ///spells::Caster
  209. int32_t getCasterUnitId() const override;
  210. int32_t getSpellSchoolLevel(const spells::Spell * spell, SpellSchool * outSelectedSchool = nullptr) const override;
  211. int64_t getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const override;
  212. int64_t getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const override;
  213. int32_t getEffectLevel(const spells::Spell * spell) const override;
  214. int32_t getEffectPower(const spells::Spell * spell) const override;
  215. int32_t getEnchantPower(const spells::Spell * spell) const override;
  216. int64_t getEffectValue(const spells::Spell * spell) const override;
  217. PlayerColor getCasterOwner() const override;
  218. const CGHeroInstance * getHeroCaster() const override;
  219. void getCasterName(MetaString & text) const override;
  220. void getCastDescription(const spells::Spell * spell, const std::vector<const battle::Unit *> & attacked, MetaString & text) const override;
  221. void spendMana(ServerCallback * server, const int spellCost) const override;
  222. void attachToBoat(CGBoat* newBoat);
  223. void boatDeserializationFix();
  224. void deserializationFix();
  225. void initObj(CRandomGenerator & rand) override;
  226. void pickRandomObject(CRandomGenerator & rand) override;
  227. void onHeroVisit(const CGHeroInstance * h) const override;
  228. std::string getObjectName() const override;
  229. void afterAddToMap(CMap * map) override;
  230. void afterRemoveFromMap(CMap * map) override;
  231. void updateFrom(const JsonNode & data) override;
  232. bool isCoastVisitable() const override;
  233. bool isBlockedVisitable() const override;
  234. BattleField getBattlefield() const override;
  235. protected:
  236. void setPropertyDer(ObjProperty what, ObjPropertyID identifier) override;//synchr
  237. ///common part of hero instance and hero definition
  238. void serializeCommonOptions(JsonSerializeFormat & handler);
  239. void serializeJsonOptions(JsonSerializeFormat & handler) override;
  240. private:
  241. void levelUpAutomatically(CRandomGenerator & rand);
  242. public:
  243. std::string getHeroTypeName() const;
  244. void setHeroTypeName(const std::string & identifier);
  245. void serializeJsonDefinition(JsonSerializeFormat & handler);
  246. template <typename Handler> void serialize(Handler &h, const int version)
  247. {
  248. h & static_cast<CArmedInstance&>(*this);
  249. h & static_cast<CArtifactSet&>(*this);
  250. h & exp;
  251. h & level;
  252. h & nameCustomTextId;
  253. h & biographyCustomTextId;
  254. h & customPortraitSource;
  255. h & mana;
  256. h & secSkills;
  257. h & movement;
  258. h & gender;
  259. h & inTownGarrison;
  260. h & spells;
  261. h & patrol;
  262. h & moveDir;
  263. h & skillsInfo;
  264. h & visitedTown;
  265. h & boat;
  266. h & type;
  267. h & commander;
  268. h & visitedObjects;
  269. BONUS_TREE_DESERIALIZATION_FIX
  270. }
  271. };
  272. VCMI_LIB_NAMESPACE_END