File: CGHeroInstance.h

package info (click to toggle)
vcmi 1.6.5%2Bdfsg-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 32,060 kB
  • sloc: cpp: 238,971; python: 265; sh: 224; xml: 157; ansic: 78; objc: 61; makefile: 49
file content (390 lines) | stat: -rw-r--r-- 14,212 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*
 * CGHeroInstance.h, part of VCMI engine
 *
 * Authors: listed in file AUTHORS in main folder
 *
 * License: GNU General Public License v2.0 or later
 * Full text of license available in license.txt file, in main folder
 *
 */
#pragma once

#include <vcmi/spells/Caster.h>

#include "CArmedInstance.h"
#include "IOwnableObject.h"

#include "../bonuses/BonusCache.h"
#include "../entities/hero/EHeroGender.h"
#include "../CArtHandler.h" // For CArtifactSet

VCMI_LIB_NAMESPACE_BEGIN

class CHero;
class CGBoat;
class CGTownInstance;
class CMap;
class UpgradeInfo;
class TurnInfo;

struct TerrainTile;
struct TurnInfoCache;

class DLL_LINKAGE CGHeroPlaceholder : public CGObjectInstance
{
public:
	using CGObjectInstance::CGObjectInstance;

	/// if this is placeholder by power, then power rank of desired hero
	std::optional<ui8> powerRank;

	/// if this is placeholder by type, then hero type of desired hero
	std::optional<HeroTypeID> heroType;

	template <typename Handler> void serialize(Handler &h)
	{
		h & static_cast<CGObjectInstance&>(*this);
		h & powerRank;
		h & heroType;
	}
	
protected:
	void serializeJsonOptions(JsonSerializeFormat & handler) override;
};


class DLL_LINKAGE CGHeroInstance : public CArmedInstance, public IBoatGenerator, public CArtifactSet, public spells::Caster, public AFactionMember, public ICreatureUpgrader, public IOwnableObject
{
	// We serialize heroes into JSON for crossover
	friend class CampaignState;
	friend class CMapLoaderH3M;
	friend class CMapFormatJson;

private:
	PrimarySkillsCache primarySkills;
	MagicSchoolMasteryCache magicSchoolMastery;
	BonusValueCache manaPerKnowledgeCached;
	std::unique_ptr<TurnInfoCache> turnInfoCache;

	std::set<SpellID> spells; //known spells (spell IDs)
	ui32 movement; //remaining movement points

public:

	//////////////////////////////////////////////////////////////////////////
	//format:   123
	//          8 4
	//          765
	ui8 moveDir;
	mutable ui8 tacticFormationEnabled;

	//////////////////////////////////////////////////////////////////////////

	TExpType exp; //experience points
	ui32 level; //current level of hero

	/// If not NONE - then hero should use portrait from referenced hero type
	HeroTypeID customPortraitSource;
	si32 mana; // remaining spell points
	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
	EHeroGender gender;

	std::string nameCustomTextId;
	std::string biographyCustomTextId;

	bool inTownGarrison; // if hero is in town garrison
	ConstTransitivePtr<CGTownInstance> visitedTown; //set if hero is visiting town or in the town garrison
	ConstTransitivePtr<CCommanderInstance> commander;
	const CGBoat * boat = nullptr; //set to CGBoat when sailing

	static constexpr si32 UNINITIALIZED_MANA = -1;
	static constexpr ui32 UNINITIALIZED_MOVEMENT = -1;
	static constexpr auto UNINITIALIZED_EXPERIENCE = std::numeric_limits<TExpType>::max();
	static const ui32 NO_PATROLLING;

	//std::vector<const CArtifact*> artifacts; //hero's artifacts from bag
	//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
	std::set<ObjectInstanceID> visitedObjects;

	struct DLL_LINKAGE Patrol
	{
		bool patrolling{false};
		int3 initialPos;
		ui32 patrolRadius{NO_PATROLLING};
		template <typename Handler> void serialize(Handler &h)
		{
			h & patrolling;
			h & initialPos;
			h & patrolRadius;
		}
	} patrol;

	struct DLL_LINKAGE SecondarySkillsInfo
	{
		ui8 magicSchoolCounter;
		ui8 wisdomCounter;

		SecondarySkillsInfo();

		void resetMagicSchoolCounter();
		void resetWisdomCounter();

		template <typename Handler> void serialize(Handler &h)
		{
			h & magicSchoolCounter;
			h & wisdomCounter;
		}
	} skillsInfo;

	inline bool isInitialized() const
	{ // has this hero been on the map at least once?
		return movement != UNINITIALIZED_MOVEMENT && mana != UNINITIALIZED_MANA;
	}

	//int3 getSightCenter() const; //"center" tile from which the sight distance is calculated
	int getSightRadius() const override; //sight distance (should be used if player-owned structure)
	//////////////////////////////////////////////////////////////////////////

	BoatId getBoatType() const override; //0 - evil (if a ship can be evil...?), 1 - good, 2 - neutral
	void getOutOffsets(std::vector<int3> &offsets) const override; //offsets to obj pos when we boat can be placed
	const IObjectInterface * getObject() const override;

	//////////////////////////////////////////////////////////////////////////

	std::string getBiographyTranslated() const;
	std::string getBiographyTextID() const;

	std::string getNameTextID() const;
	std::string getNameTranslated() const;

	HeroTypeID getPortraitSource() const;
	int32_t getIconIndex() const;

	std::string getClassNameTranslated() const;
	std::string getClassNameTextID() const;

	bool hasSpellbook() const;
	int maxSpellLevel() const;
	void addSpellToSpellbook(const SpellID & spell);
	void removeSpellFromSpellbook(const SpellID & spell);
	bool spellbookContainsSpell(const SpellID & spell) const;
	void removeSpellbook();
	const std::set<SpellID> & getSpellsInSpellbook() const;
	EAlignment getAlignment() const;
	bool needsLastStack()const override;

	ResourceSet dailyIncome() const override;
	std::vector<CreatureID> providedCreatures() const override;
	const IOwnableObject * asOwnable() const final;

	//INativeTerrainProvider
	FactionID getFactionID() const override;
	TerrainId getNativeTerrain() const override;
	int getLowestCreatureSpeed() const;
	si32 manaRegain() const; //how many points of mana can hero regain "naturally" in one day
	si32 getManaNewTurn() const; //calculate how much mana this hero is going to have the next day
	int getCurrentLuck(int stack=-1, bool town=false) const;
	int32_t getSpellCost(const spells::Spell * sp) const; //do not use during battles -> bonuses from army would be ignored

	bool canLearnSpell(const spells::Spell * spell,  bool allowBanned = false) const;
	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

	/// convert given position between map position (CGObjectInstance::pos) and visitable position used for hero interactions
	int3 convertToVisitablePos(const int3 & position) const;
	int3 convertFromVisitablePos(const int3 & position) const;

	// ----- primary and secondary skill, experience, level handling -----

	/// Returns true if hero has lower level than should upon his experience.
	bool gainsLevel() const;

	/// Returns the next primary skill on level up. Can only be called if hero can gain a level up.
	PrimarySkill nextPrimarySkill(vstd::RNG & rand) const;

	/// Returns the next secondary skill randomly on level up. Can only be called if hero can gain a level up.
	std::optional<SecondarySkill> nextSecondarySkill(vstd::RNG & rand) const;

	/// Gets 0, 1 or 2 secondary skills which are proposed on hero level up.
	std::vector<SecondarySkill> getLevelUpProposedSecondarySkills(vstd::RNG & rand) const;

	ui8 getSecSkillLevel(const SecondarySkill & skill) const; //0 - no skill
	int getPrimSkillLevel(PrimarySkill id) const;

	/// Returns true if hero has free secondary skill slot.
	bool canLearnSkill() const;
	bool canLearnSkill(const SecondarySkill & which) const;

	void setPrimarySkill(PrimarySkill primarySkill, si64 value, ui8 abs);
	void setSecSkillLevel(const SecondarySkill & which, int val, bool abs); // abs == 0 - changes by value; 1 - sets to value
	void levelUp(const std::vector<SecondarySkill> & skills);

	/// returns base movement cost for movement between specific tiles. Does not accounts for diagonal movement or last tile exception
	ui32 getTileMovementCost(const TerrainTile & dest, const TerrainTile & from, const TurnInfo * ti) const;

	void setMovementPoints(int points);
	int movementPointsRemaining() const;
	int movementPointsLimit(bool onLand) const;
	//cached version is much faster, TurnInfo construction is costly
	int movementPointsLimitCached(bool onLand, const TurnInfo * ti) const;

	int movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const;

	std::unique_ptr<TurnInfo> getTurnInfo(int days) const;

	double getFightingStrength() const; // takes attack / defense skill into account
	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
	double getHeroStrength() const; // includes fighting and magic strength

	uint32_t getValueForCampaign() const;
	uint64_t getValueForDiplomacy() const;
	
	ui64 getTotalStrength() const; // includes fighting strength and army strength
	TExpType calculateXp(TExpType exp) const; //apply learning skill
	int getBasePrimarySkillValue(PrimarySkill which) const; //the value of a base-skill without items or temporary bonuses

	CStackBasicDescriptor calculateNecromancy (const BattleResult &battleResult) const;
	void showNecromancyDialog(const CStackBasicDescriptor &raisedStack, vstd::RNG & rand) const;
	EDiggingStatus diggingStatus() const;

	//////////////////////////////////////////////////////////////////////////

	const CHeroClass * getHeroClass() const;
	HeroClassID getHeroClassID() const;

	const CHero * getHeroType() const;
	HeroTypeID getHeroTypeID() const;
	void setHeroType(HeroTypeID type);

	void initObj(vstd::RNG & rand) override;
	void initHero(vstd::RNG & rand);
	void initHero(vstd::RNG & rand, const HeroTypeID & SUBID);

	ArtPlacementMap putArtifact(const ArtifactPosition & pos, CArtifactInstance * art) override;
	void removeArtifact(const ArtifactPosition & pos) override;
	void initExp(vstd::RNG & rand);
	void initArmy(vstd::RNG & rand, IArmyDescriptor *dst = nullptr);
	void pushPrimSkill(PrimarySkill which, int val);
	ui8 maxlevelsToMagicSchool() const;
	ui8 maxlevelsToWisdom() const;
	void recreateSecondarySkillsBonuses();
	void updateSkillBonus(const SecondarySkill & which, int val);

	void fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const override;

	bool hasVisions(const CGObjectInstance * target, BonusSubtypeID masteryLevel) const;
	/// If this hero perishes, the scenario is failed
	bool isMissionCritical() const;

	CGHeroInstance(IGameCallback *cb);
	virtual ~CGHeroInstance();

	PlayerColor getOwner() const override;

	///ArtBearer
	ArtBearer::ArtBearer bearerType() const override;

	///IBonusBearer
	CBonusSystemNode & whereShouldBeAttached(CGameState * gs) override;
	std::string nodeName() const override;
	si32 manaLimit() const override;

	///IConstBonusProvider
	const IBonusBearer* getBonusBearer() const override;

	CBonusSystemNode * whereShouldBeAttachedOnSiege(const bool isBattleOutsideTown) const;
	CBonusSystemNode * whereShouldBeAttachedOnSiege(CGameState * gs);

	///spells::Caster
	int32_t getCasterUnitId() const override;
	int32_t getSpellSchoolLevel(const spells::Spell * spell, SpellSchool * outSelectedSchool = nullptr) const override;
	int64_t getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const override;
	int64_t getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const override;

	int32_t getEffectLevel(const spells::Spell * spell) const override;
	int32_t getEffectPower(const spells::Spell * spell) const override;
	int32_t getEnchantPower(const spells::Spell * spell) const override;
	int64_t getEffectValue(const spells::Spell * spell) const override;

	PlayerColor getCasterOwner() const override;
	const CGHeroInstance * getHeroCaster() const override;

	void getCasterName(MetaString & text) const override;
	void getCastDescription(const spells::Spell * spell, const battle::Units & attacked, MetaString & text) const override;
	void spendMana(ServerCallback * server, const int spellCost) const override;

	void attachToBoat(CGBoat* newBoat);
	void boatDeserializationFix();
	void deserializationFix();
	void updateAppearance();

	void pickRandomObject(vstd::RNG & rand) override;
	void onHeroVisit(const CGHeroInstance * h) const override;
	std::string getObjectName() const override;
	std::string getHoverText(PlayerColor player) const override;
	std::string getMovementPointsTextIfOwner(PlayerColor player) const;

	TObjectTypeHandler getObjectHandler() const override;

	void afterAddToMap(CMap * map) override;
	void afterRemoveFromMap(CMap * map) override;

	void updateFrom(const JsonNode & data) override;

	bool isCoastVisitable() const override;
	bool isBlockedVisitable() const override;
	BattleField getBattlefield() const override;

	bool isCampaignYog() const;
	bool isCampaignGem() const;

protected:
	void setPropertyDer(ObjProperty what, ObjPropertyID identifier) override;//synchr
	///common part of hero instance and hero definition
	void serializeCommonOptions(JsonSerializeFormat & handler);

	void serializeJsonOptions(JsonSerializeFormat & handler) override;

private:
	void levelUpAutomatically(vstd::RNG & rand);

public:
	std::string getHeroTypeName() const;
	void setHeroTypeName(const std::string & identifier);

	void serializeJsonDefinition(JsonSerializeFormat & handler);

	template <typename Handler> void serialize(Handler &h)
	{
		h & static_cast<CArmedInstance&>(*this);
		h & static_cast<CArtifactSet&>(*this);
		h & exp;
		h & level;
		h & nameCustomTextId;
		h & biographyCustomTextId;
		h & customPortraitSource;
		h & mana;
		h & secSkills;
		h & movement;
		h & gender;
		h & inTownGarrison;
		h & spells;
		h & patrol;
		h & moveDir;
		h & skillsInfo;
		h & visitedTown;
		h & boat;
		if (h.version < Handler::Version::REMOVE_TOWN_PTR)
		{
			HeroTypeID type;
			bool isNull = false;
			h & isNull;
			if(!isNull)
				h & type;
		}
		h & commander;
		h & visitedObjects;
		BONUS_TREE_DESERIALIZATION_FIX
	}
};

VCMI_LIB_NAMESPACE_END