BattleState.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #pragma once
  2. #include "BattleHex.h"
  3. #include "HeroBonus.h"
  4. #include "CCreatureSet.h"
  5. #include "CObjectHandler.h"
  6. #include "CCreatureHandler.h"
  7. #include "CObstacleInstance.h"
  8. #include "ConstTransitivePtr.h"
  9. #include "GameConstants.h"
  10. /*
  11. * BattleState.h, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. class CGHeroInstance;
  20. class CStack;
  21. class CArmedInstance;
  22. class CGTownInstance;
  23. class CStackInstance;
  24. struct BattleStackAttacked;
  25. //only for use in BattleInfo
  26. struct DLL_LINKAGE SiegeInfo
  27. {
  28. ui8 wallState[8]; //[0] - keep, [1] - bottom tower, [2] - bottom wall, [3] - below gate, [4] - over gate, [5] - upper wall, [6] - uppert tower, [7] - gate; 1 - intact, 2 - damaged, 3 - destroyed
  29. template <typename Handler> void serialize(Handler &h, const int version)
  30. {
  31. h & wallState;
  32. }
  33. };
  34. struct DLL_LINKAGE AttackableTiles
  35. {
  36. std::set<BattleHex> hostileCreaturePositions;
  37. std::set<BattleHex> friendlyCreaturePositions; //for Dragon Breath
  38. template <typename Handler> void serialize(Handler &h, const int version)
  39. {
  40. h & hostileCreaturePositions & friendlyCreaturePositions;
  41. }
  42. };
  43. struct DLL_LINKAGE BattleInfo : public CBonusSystemNode
  44. {
  45. ui8 sides[2]; //sides[0] - attacker, sides[1] - defender
  46. si32 round, activeStack, selectedStack;
  47. ui8 siege; // = 0 ordinary battle = 1 a siege with a Fort = 2 a siege with a Citadel = 3 a siege with a Castle
  48. const CGTownInstance * town; //used during town siege - id of attacked town; -1 if not town defence
  49. int3 tile; //for background and bonuses
  50. CGHeroInstance* heroes[2];
  51. CArmedInstance *belligerents[2]; //may be same as heroes
  52. std::vector<CStack*> stacks;
  53. std::vector<shared_ptr<CObstacleInstance> > obstacles;
  54. ui8 castSpells[2]; //how many spells each side has cast this turn [0] - attacker, [1] - defender
  55. std::vector<const CSpell *> usedSpellsHistory[2]; //each time hero casts spell, it's inserted here -> eagle eye skill
  56. si16 enchanterCounter[2]; //tends to pass through 0, so sign is needed
  57. SiegeInfo si;
  58. si32 battlefieldType; //like !!BA:B
  59. ui8 terrainType; //used for some stack nativity checks (not the bonus limiters though that have their own copy)
  60. ui8 tacticsSide; //which side is requested to play tactics phase
  61. ui8 tacticDistance; //how many hexes we can go forward (1 = only hexes adjacent to margin line)
  62. template <typename Handler> void serialize(Handler &h, const int version)
  63. {
  64. h & sides & round & activeStack & selectedStack & siege & town & tile & stacks & belligerents & obstacles
  65. & castSpells & si & battlefieldType & terrainType;
  66. h & heroes;
  67. h & usedSpellsHistory & enchanterCounter;
  68. h & tacticsSide & tacticDistance;
  69. h & static_cast<CBonusSystemNode&>(*this);
  70. }
  71. //////////////////////////////////////////////////////////////////////////
  72. //void getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root = NULL) const;
  73. //////////////////////////////////////////////////////////////////////////
  74. const CStack *getStackIf(boost::function<bool(const CStack*)> pred) const;
  75. const CStack * getNextStack() const; //which stack will have turn after current one
  76. void getStackQueue(std::vector<const CStack *> &out, int howMany, int turn = 0, int lastMoved = -1) const; //returns stack in order of their movement action
  77. CStack * getStack(int stackID, bool onlyAlive = true);
  78. const CStack * getStack(int stackID, bool onlyAlive = true) const;
  79. CStack * getStackT(BattleHex tileID, bool onlyAlive = true);
  80. const CStack * getStackT(BattleHex tileID, bool onlyAlive = true) const;
  81. void getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<BattleHex> & occupyable, bool flying, const CStack* stackToOmmit = NULL) const; //send pointer to at least 187 allocated bytes
  82. static bool isAccessible(BattleHex hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos); //helper for makeBFS
  83. BattleHex getClosestTile (bool attackerOwned, int initialPos, std::set<BattleHex> & possibilities) const; //TODO: vector or set? copying one to another is bad
  84. int getAvaliableHex(TCreature creID, bool attackerOwned, int initialPos = -1) const; //find place for summon / clone effects
  85. void makeBFS(BattleHex start, bool*accessibility, BattleHex *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const; //*accessibility must be prepared bool[187] array; last two pointers must point to the at least 187-elements int arrays - there is written result
  86. std::pair< std::vector<BattleHex>, int > getPath(BattleHex start, BattleHex dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned); //returned value: pair<path, length>; length may be different than number of elements in path since flying vreatures jump between distant hexes
  87. std::vector<BattleHex> getAccessibility(const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable = NULL, bool forPassingBy = false) const; //returns vector of accessible tiles (taking into account the creature range)
  88. bool isObstacleVisibleForSide(const CObstacleInstance &obstacle, ui8 side) const;
  89. shared_ptr<CObstacleInstance> getObstacleOnTile(BattleHex tile) const;
  90. bool isStackBlocked(const CStack * stack) const; //returns true if there is neighboring enemy stack
  91. std::set<BattleHex> getStoppers(bool whichSidePerspective) const;
  92. ui32 calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg); //charge - number of hexes travelled before attack (for champion's jousting)
  93. TDmgRange calculateDmgRange(const CStack* attacker, const CStack* defender, TQuantity attackerCount, TQuantity defenderCount, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg) const; //charge - number of hexes travelled before attack (for champion's jousting); returns pair <min dmg, max dmg>
  94. TDmgRange calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg) const; //charge - number of hexes travelled before attack (for champion's jousting); returns pair <min dmg, max dmg>
  95. void calculateCasualties(std::map<ui32,si32> *casualties) const; //casualties are array of maps size 2 (attacker, defeneder), maps are (crid => amount)
  96. std::set<CStack*> getAttackedCreatures(const CSpell * s, int skillLevel, ui8 attackerOwner, BattleHex destinationTile); //calculates stack affected by given spell
  97. void getPotentiallyAttackableHexes(AttackableTiles &at, const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos); //hexes around target that could be attacked in melee
  98. std::set<CStack*> getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos = BattleHex::INVALID); //calculates range of multi-hex attacks
  99. std::set<BattleHex> getAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos = BattleHex::INVALID); //calculates range of multi-hex attacks
  100. std::set<CStack*> getAdjacentCreatures (const CStack * stack) const;
  101. static int calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower);
  102. CStack * generateNewStack(const CStackInstance &base, bool attackerOwned, int slot, BattleHex position) const; //helper for CGameHandler::setupBattle and spells addign new stacks to the battlefield
  103. CStack * generateNewStack(const CStackBasicDescriptor &base, bool attackerOwned, int slot, BattleHex position) const; //helper for CGameHandler::setupBattle and spells addign new stacks to the battlefield
  104. int getIdForNewStack() const; //suggest a currently unused ID that'd suitable for generating a new stack
  105. ui32 getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const; //returns cost of given spell
  106. int hexToWallPart(BattleHex hex) const; //returns part of destructible wall / gate / keep under given hex or -1 if not found
  107. int lineToWallHex(int line) const; //returns hex with wall in given line
  108. std::pair<const CStack *, BattleHex> getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const; //if attackerOwned is indetermnate, returened stack is of any owner; hex is the number of hex we should be looking from; returns (nerarest creature, predecessorHex)
  109. ui32 calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const;
  110. ui32 calculateSpellDmg(const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const; //calculates damage inflicted by spell
  111. ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack, const CStack * sacrificedStack = NULL) const;
  112. ui32 calculateHealedHP(int healedHealth, const CSpell * spell, const CStack * stack) const; //for Archangel
  113. ui32 calculateHealedHP(const CSpell * spell, int usedSpellPower, int spellSchoolLevel, const CStack * stack) const; //unused
  114. bool resurrects(TSpell spellid) const; //TODO: move it to spellHandler?
  115. si8 hasDistancePenalty(const CStack * stackID, BattleHex destHex) const; //determines if given stack has distance penalty shooting given pos
  116. si8 sameSideOfWall(int pos1, int pos2) const; //determines if given positions are on the same side of wall
  117. si8 hasWallPenalty(const CStack * stack, BattleHex destHex) const; //determines if given stack has wall penalty shooting given pos
  118. si8 canTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const; //determines if given stack can teleport to given place
  119. bool battleCanShoot(const CStack * stack, BattleHex dest) const; //determines if stack with given ID shoot at the selected destination
  120. const CGHeroInstance * getHero(int player) const; //returns fighting hero that belongs to given player
  121. ESpellCastProblem::ESpellCastProblem battleCanCastSpell(int player, ECastingMode::ECastingMode mode) const; //returns true if there are no general issues preventing from casting a spell
  122. ESpellCastProblem::ESpellCastProblem battleCanCastThisSpell(int player, const CSpell * spell, ECastingMode::ECastingMode mode) const; //checks if given player can cast given spell
  123. ESpellCastProblem::ESpellCastProblem battleIsImmune(const CGHeroInstance * caster, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const; //checks for creature immunity / anything that prevent casting *at given hex* - doesn't take into acount general problems such as not having spellbook or mana points etc.
  124. ESpellCastProblem::ESpellCastProblem battleCanCastThisSpellHere(int player, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const; //checks if given player can cast given spell at given tile in given mode
  125. bool battleTestElementalImmunity(const CStack * subject, const CSpell * spell, Bonus::BonusType element, bool damageSpell) const;
  126. TSpell getRandomBeneficialSpell(const CStack * subject) const;
  127. TSpell getRandomCastedSpell(const CStack * caster) const; //called at the beginning of turn for Faerie Dragon
  128. std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures, int casterSideOwner, ECastingMode::ECastingMode mode, int usedSpellPower, int spellLevel) const;
  129. bool battleCanFlee(int player) const; //returns true if player can flee from the battle
  130. const CStack * battleGetStack(BattleHex pos, bool onlyAlive); //returns stack at given tile
  131. const CGHeroInstance * battleGetOwner(const CStack * stack) const; //returns hero that owns given stack; NULL if none
  132. si8 battleMinSpellLevel() const; //calculates minimum spell level possible to be cast on battlefield - takes into account artifacts of both heroes; if no effects are set, 0 is returned
  133. void localInit();
  134. void localInitStack(CStack * s);
  135. static BattleInfo * setupBattle( int3 tile, int terrain, int battlefieldType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town );
  136. bool isInTacticRange( BattleHex dest ) const;
  137. int getSurrenderingCost(int player) const;
  138. bool hasNativeStack(ui8 side) const;
  139. int theOtherPlayer(int player) const;
  140. ui8 whatSide(int player) const;
  141. static int battlefieldTypeToBI(int bfieldType); //converts above to ERM BI format
  142. static int battlefieldTypeToTerrain(int bfieldType); //converts above to ERM BI format
  143. };
  144. class DLL_LINKAGE CStack : public CBonusSystemNode, public CStackBasicDescriptor
  145. {
  146. public:
  147. const CStackInstance *base;
  148. ui32 ID; //unique ID of stack
  149. ui32 baseAmount;
  150. ui32 firstHPleft; //HP of first creature in stack
  151. ui8 owner, slot; //owner - player colour (255 for neutrals), slot - position in garrison (may be 255 for neutrals/called creatures)
  152. ui8 attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
  153. BattleHex position; //position on battlefield; -2 - keep, -3 - lower tower, -4 - upper tower
  154. ui8 counterAttacks; //how many counter attacks can be performed more in this turn (by default set at the beginning of the round to 1)
  155. si16 shots; //how many shots left
  156. ui8 casts; //how many casts left
  157. std::set<EBattleStackState::EBattleStackState> state;
  158. //overrides
  159. const CCreature* getCreature() const {return type;}
  160. CStack(const CStackInstance *base, int O, int I, bool AO, int S); //c-tor
  161. CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S = 255); //c-tor
  162. CStack(); //c-tor
  163. ~CStack();
  164. std::string nodeName() const OVERRIDE;
  165. void init(); //set initial (invalid) values
  166. void postInit(); //used to finish initialization when inheriting creature parameters is working
  167. std::string getName() const; //plural or singular
  168. const Bonus * getEffect(ui16 id, int turn = 0) const; //effect id (SP)
  169. ui8 howManyEffectsSet(ui16 id) const; //returns amount of effects with given id set for this stack
  170. bool willMove(int turn = 0) const; //if stack has remaining move this turn
  171. bool ableToRetaliate() const; //if stack can retaliate after attacked
  172. bool moved(int turn = 0) const; //if stack was already moved this turn
  173. bool canMove(int turn = 0) const; //if stack can move
  174. bool canBeHealed() const; //for first aid tent - only harmed stacks that are not war machines
  175. ui32 Speed(int turn = 0, bool useBind = false) const; //get speed of creature with all modificators
  176. si32 magicResistance() const; //include aura of resistance
  177. static void stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse);
  178. std::vector<si32> activeSpells() const; //returns vector of active spell IDs sorted by time of cast
  179. const CGHeroInstance *getMyHero() const; //if stack belongs to hero (directly or was by him summoned) returns hero, NULL otherwise
  180. static inline Bonus featureGenerator(Bonus::BonusType type, si16 subtype, si32 value, ui16 turnsRemain, si32 additionalInfo = 0, si32 limit = Bonus::NO_LIMIT)
  181. {
  182. Bonus hb = makeFeatureVal(type, Bonus::N_TURNS, subtype, value, Bonus::SPELL_EFFECT, turnsRemain, additionalInfo);
  183. hb.effectRange = limit;
  184. hb.source = Bonus::SPELL_EFFECT;
  185. return hb;
  186. }
  187. static inline Bonus featureGeneratorVT(Bonus::BonusType type, si16 subtype, si32 value, ui16 turnsRemain, ui8 valType)
  188. {
  189. Bonus ret = makeFeatureVal(type, Bonus::N_TURNS, subtype, value, Bonus::SPELL_EFFECT, turnsRemain);
  190. ret.valType = valType;
  191. ret.source = Bonus::SPELL_EFFECT;
  192. return ret;
  193. }
  194. static bool isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos = BattleHex::INVALID, BattleHex defenderPos = BattleHex::INVALID);
  195. bool doubleWide() const;
  196. BattleHex occupiedHex() const; //returns number of occupied hex (not the position) if stack is double wide; otherwise -1
  197. std::vector<BattleHex> getHexes() const; //up to two occupied hexes, starting from front
  198. bool coversPos(BattleHex position) const; //checks also if unit is double-wide
  199. std::vector<BattleHex> getSurroundingHexes(BattleHex attackerPos = BattleHex::INVALID) const; // get six or 8 surrounding hexes depending on creature size
  200. void prepareAttacked(BattleStackAttacked &bsa) const; //requires bsa.damageAmout filled
  201. template <typename Handler> void serialize(Handler &h, const int version)
  202. {
  203. assert(isIndependentNode());
  204. h & static_cast<CBonusSystemNode&>(*this);
  205. h & static_cast<CStackBasicDescriptor&>(*this);
  206. h & ID & baseAmount & firstHPleft & owner & slot & attackerOwned & position & state & counterAttacks
  207. & shots & casts & count;
  208. TSlot slot = (base ? base->armyObj->findStack(base) : -1);
  209. const CArmedInstance *army = (base ? base->armyObj : NULL);
  210. if(h.saving)
  211. {
  212. h & army & slot;
  213. }
  214. else
  215. {
  216. h & army & slot;
  217. if(!army || slot == -1 || !army->hasStackAtSlot(slot))
  218. {
  219. base = NULL;
  220. tlog3 << type->nameSing << " doesn't have a base stack!\n";
  221. }
  222. else
  223. {
  224. base = &army->getStack(slot);
  225. }
  226. }
  227. }
  228. bool alive() const //determines if stack is alive
  229. {
  230. return vstd::contains(state,EBattleStackState::ALIVE);
  231. }
  232. bool isValidTarget(bool allowDead = false) const; //alive non-turret stacks (can be attacked or be object of magic effect)
  233. };
  234. class DLL_LINKAGE CMP_stack
  235. {
  236. int phase; //rules of which phase will be used
  237. int turn;
  238. public:
  239. bool operator ()(const CStack* a, const CStack* b);
  240. CMP_stack(int Phase = 1, int Turn = 0);
  241. };