CGHeroInstance.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 "CObjectHandler.h"
  12. #include "CArmedInstance.h"
  13. #include "../spells/Magic.h"
  14. #include "../CArtHandler.h" // For CArtifactSet
  15. #include "../CRandomGenerator.h"
  16. class CHero;
  17. class CGBoat;
  18. class CGTownInstance;
  19. class CMap;
  20. struct TerrainTile;
  21. struct TurnInfo;
  22. class CGHeroPlaceholder : public CGObjectInstance
  23. {
  24. public:
  25. //subID stores id of hero type. If it's 0xff then following field is used
  26. ui8 power;
  27. template <typename Handler> void serialize(Handler &h, const int version)
  28. {
  29. h & static_cast<CGObjectInstance&>(*this);
  30. h & power;
  31. }
  32. };
  33. class DLL_LINKAGE CGHeroInstance : public CArmedInstance, public IBoatGenerator, public CArtifactSet, public spells::Caster
  34. {
  35. // We serialize heroes into JSON for crossover
  36. friend class CCampaignState;
  37. friend class CMapLoaderH3M;
  38. private:
  39. std::set<SpellID> spells; //known spells (spell IDs)
  40. public:
  41. //////////////////////////////////////////////////////////////////////////
  42. ui8 moveDir; //format: 123
  43. // 8 4
  44. // 765
  45. mutable ui8 isStanding, tacticFormationEnabled;
  46. //////////////////////////////////////////////////////////////////////////
  47. ConstTransitivePtr<CHero> type;
  48. TExpType exp; //experience points
  49. ui32 level; //current level of hero
  50. std::string name; //may be custom
  51. std::string biography; //if custom
  52. si32 portrait; //may be custom
  53. si32 mana; // remaining spell points
  54. 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
  55. ui32 movement; //remaining movement points
  56. ui8 sex;
  57. bool inTownGarrison; // if hero is in town garrison
  58. ConstTransitivePtr<CGTownInstance> visitedTown; //set if hero is visiting town or in the town garrison
  59. ConstTransitivePtr<CCommanderInstance> commander;
  60. const CGBoat *boat; //set to CGBoat when sailing
  61. static const si32 UNINITIALIZED_PORTRAIT = -1;
  62. static const si32 UNINITIALIZED_MANA = -1;
  63. static const ui32 UNINITIALIZED_MOVEMENT = -1;
  64. //std::vector<const CArtifact*> artifacts; //hero's artifacts from bag
  65. //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
  66. std::set<ObjectInstanceID> visitedObjects;
  67. struct DLL_LINKAGE Patrol
  68. {
  69. Patrol(){patrolling=false;initialPos=int3();patrolRadius=-1;};
  70. bool patrolling;
  71. int3 initialPos;
  72. ui32 patrolRadius;
  73. template <typename Handler> void serialize(Handler &h, const int version)
  74. {
  75. h & patrolling;
  76. if(version >= 755) //save format backward compatibility
  77. {
  78. h & initialPos;
  79. }
  80. else if(!h.saving)
  81. {
  82. patrolling = false;
  83. initialPos = int3();
  84. }
  85. h & patrolRadius;
  86. }
  87. } patrol;
  88. // deprecated - used only for loading of old saves
  89. struct HeroSpecial : CBonusSystemNode
  90. {
  91. bool growsWithLevel;
  92. HeroSpecial(){growsWithLevel = false;};
  93. template <typename Handler> void serialize(Handler &h, const int version)
  94. {
  95. h & static_cast<CBonusSystemNode&>(*this);
  96. h & growsWithLevel;
  97. }
  98. };
  99. struct DLL_LINKAGE SecondarySkillsInfo
  100. {
  101. //skills are determined, initialized at map start
  102. //FIXME remove mutable
  103. mutable CRandomGenerator rand;
  104. ui8 magicSchoolCounter;
  105. ui8 wisdomCounter;
  106. SecondarySkillsInfo();
  107. void resetMagicSchoolCounter();
  108. void resetWisdomCounter();
  109. template <typename Handler> void serialize(Handler &h, const int version)
  110. {
  111. h & magicSchoolCounter;
  112. h & wisdomCounter;
  113. h & rand;
  114. }
  115. } skillsInfo;
  116. inline bool isInitialized() const
  117. { // has this hero been on the map at least once?
  118. return movement != UNINITIALIZED_MOVEMENT && mana != UNINITIALIZED_MANA;
  119. }
  120. //int3 getSightCenter() const; //"center" tile from which the sight distance is calculated
  121. int getSightRadius() const override; //sight distance (should be used if player-owned structure)
  122. //////////////////////////////////////////////////////////////////////////
  123. int getBoatType() const override; //0 - evil (if a ship can be evil...?), 1 - good, 2 - neutral
  124. void getOutOffsets(std::vector<int3> &offsets) const override; //offsets to obj pos when we boat can be placed
  125. //////////////////////////////////////////////////////////////////////////
  126. bool hasSpellbook() const;
  127. int maxSpellLevel() const;
  128. void addSpellToSpellbook(SpellID spell);
  129. void removeSpellFromSpellbook(SpellID spell);
  130. bool spellbookContainsSpell(SpellID spell) const;
  131. void removeSpellbook();
  132. const std::set<SpellID> & getSpellsInSpellbook() const;
  133. EAlignment::EAlignment getAlignment() const;
  134. const std::string &getBiography() const;
  135. bool needsLastStack()const override;
  136. TFaction getFaction() const;
  137. ui32 getTileCost(const TerrainTile &dest, const TerrainTile &from, const TurnInfo * ti) const; //move cost - applying pathfinding skill, road and terrain modifiers. NOT includes diagonal move penalty, last move levelling
  138. int getNativeTerrain() const;
  139. ui32 getLowestCreatureSpeed() const;
  140. int3 getPosition(bool h3m = false) const; //h3m=true - returns position of hero object; h3m=false - returns position of hero 'manifestation'
  141. si32 manaRegain() const; //how many points of mana can hero regain "naturally" in one day
  142. si32 getManaNewTurn() const; //calculate how much mana this hero is going to have the next day
  143. int getCurrentLuck(int stack=-1, bool town=false) const;
  144. int getSpellCost(const CSpell *sp) const; //do not use during battles -> bonuses from army would be ignored
  145. bool canLearnSpell(const CSpell * spell) const;
  146. // ----- primary and secondary skill, experience, level handling -----
  147. /// Returns true if hero has lower level than should upon his experience.
  148. bool gainsLevel() const;
  149. /// Returns the next primary skill on level up. Can only be called if hero can gain a level up.
  150. PrimarySkill::PrimarySkill nextPrimarySkill(CRandomGenerator & rand) const;
  151. /// Returns the next secondary skill randomly on level up. Can only be called if hero can gain a level up.
  152. boost::optional<SecondarySkill> nextSecondarySkill(CRandomGenerator & rand) const;
  153. /// Gets 0, 1 or 2 secondary skills which are proposed on hero level up.
  154. std::vector<SecondarySkill> getLevelUpProposedSecondarySkills() const;
  155. ui8 getSecSkillLevel(SecondarySkill skill) const; //0 - no skill
  156. /// Returns true if hero has free secondary skill slot.
  157. bool canLearnSkill() const;
  158. void setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs);
  159. void setSecSkillLevel(SecondarySkill which, int val, bool abs);// abs == 0 - changes by value; 1 - sets to value
  160. void levelUp(std::vector<SecondarySkill> skills);
  161. int maxMovePoints(bool onLand) const;
  162. //cached version is much faster, TurnInfo construction is costly
  163. int maxMovePointsCached(bool onLand, const TurnInfo * ti) const;
  164. int movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark = false, const TurnInfo * ti = nullptr) const;
  165. static int3 convertPosition(int3 src, bool toh3m); //toh3m=true: manifest->h3m; toh3m=false: h3m->manifest
  166. double getFightingStrength() const; // takes attack / defense skill into account
  167. double getMagicStrength() const; // takes knowledge / spell power skill into account
  168. double getHeroStrength() const; // includes fighting and magic strength
  169. ui64 getTotalStrength() const; // includes fighting strength and army strength
  170. TExpType calculateXp(TExpType exp) const; //apply learning skill
  171. bool canCastThisSpell(const CSpell * spell) const; //determines if this hero can cast given spell; takes into account existing spell in spellbook, existing spellbook and artifact bonuses
  172. CStackBasicDescriptor calculateNecromancy (const BattleResult &battleResult) const;
  173. void showNecromancyDialog(const CStackBasicDescriptor &raisedStack, CRandomGenerator & rand) const;
  174. EDiggingStatus diggingStatus() const;
  175. //////////////////////////////////////////////////////////////////////////
  176. void setType(si32 ID, si32 subID) override;
  177. void initHero(CRandomGenerator & rand);
  178. void initHero(CRandomGenerator & rand, HeroTypeID SUBID);
  179. void putArtifact(ArtifactPosition pos, CArtifactInstance * art) override;
  180. void putInBackpack(CArtifactInstance *art);
  181. void initExp(CRandomGenerator & rand);
  182. void initArmy(CRandomGenerator & rand, IArmyDescriptor *dst = nullptr);
  183. //void giveArtifact (ui32 aid);
  184. void pushPrimSkill(PrimarySkill::PrimarySkill which, int val);
  185. ui8 maxlevelsToMagicSchool() const;
  186. ui8 maxlevelsToWisdom() const;
  187. void recreateSecondarySkillsBonuses();
  188. void updateSkillBonus(SecondarySkill which, int val);
  189. bool hasVisions(const CGObjectInstance * target, const int subtype) const;
  190. /// If this hero perishes, the scenario is failed
  191. bool isMissionCritical() const;
  192. CGHeroInstance();
  193. virtual ~CGHeroInstance();
  194. ///ArtBearer
  195. ArtBearer::ArtBearer bearerType() const override;
  196. ///IBonusBearer
  197. CBonusSystemNode *whereShouldBeAttached(CGameState *gs) override;
  198. std::string nodeName() const override;
  199. ///spells::Caster
  200. int32_t getCasterUnitId() const override;
  201. ui8 getSpellSchoolLevel(const spells::Spell * spell, int * outSelectedSchool = nullptr) const override;
  202. int64_t getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const override;
  203. int64_t getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const override;
  204. int getEffectLevel(const spells::Spell * spell) const override;
  205. int getEffectPower(const spells::Spell * spell) const override;
  206. int getEnchantPower(const spells::Spell * spell) const override;
  207. int64_t getEffectValue(const spells::Spell * spell) const override;
  208. const PlayerColor getOwner() const override;
  209. void getCasterName(MetaString & text) const override;
  210. void getCastDescription(const spells::Spell * spell, const std::vector<const battle::Unit *> & attacked, MetaString & text) const override;
  211. void spendMana(const spells::PacketSender * server, const int spellCost) const override;
  212. void deserializationFix();
  213. void initObj(CRandomGenerator & rand) override;
  214. void onHeroVisit(const CGHeroInstance * h) const override;
  215. std::string getObjectName() const override;
  216. void afterAddToMap(CMap * map) override;
  217. protected:
  218. void setPropertyDer(ui8 what, ui32 val) override;//synchr
  219. ///common part of hero instance and hero definition
  220. void serializeCommonOptions(JsonSerializeFormat & handler);
  221. void serializeJsonOptions(JsonSerializeFormat & handler) override;
  222. private:
  223. void levelUpAutomatically(CRandomGenerator & rand);
  224. void recreateSpecialtyBonuses(std::vector<HeroSpecial*> & specialtyDeprecated);
  225. public:
  226. std::string getHeroTypeName() const;
  227. void setHeroTypeName(const std::string & identifier);
  228. void serializeJsonDefinition(JsonSerializeFormat & handler);
  229. template <typename Handler> void serialize(Handler &h, const int version)
  230. {
  231. h & static_cast<CArmedInstance&>(*this);
  232. h & static_cast<CArtifactSet&>(*this);
  233. h & exp;
  234. h & level;
  235. h & name;
  236. h & biography;
  237. h & portrait;
  238. h & mana;
  239. h & secSkills;
  240. h & movement;
  241. h & sex;
  242. h & inTownGarrison;
  243. h & spells;
  244. h & patrol;
  245. h & moveDir;
  246. h & skillsInfo;
  247. h & visitedTown;
  248. h & boat;
  249. h & type;
  250. if(version < 781)
  251. {
  252. std::vector<HeroSpecial*> specialtyDeprecated;
  253. h & specialtyDeprecated;
  254. if(!h.saving)
  255. recreateSpecialtyBonuses(specialtyDeprecated);
  256. }
  257. h & commander;
  258. h & visitedObjects;
  259. BONUS_TREE_DESERIALIZATION_FIX
  260. //visitied town pointer will be restored by map serialization method
  261. if(version < 777 && !h.saving)
  262. recreateSecondarySkillsBonuses();
  263. }
  264. };