BattleState.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #pragma once
  2. #include "../global.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. /*
  10. * BattleState.h, part of VCMI engine
  11. *
  12. * Authors: listed in file AUTHORS in main folder
  13. *
  14. * License: GNU General Public License v2.0 or later
  15. * Full text of license available in license.txt file, in main folder
  16. *
  17. */
  18. class CGHeroInstance;
  19. class CStack;
  20. class CArmedInstance;
  21. class CGTownInstance;
  22. class CStackInstance;
  23. struct BattleStackAttacked;
  24. //only for use in BattleInfo
  25. struct DLL_EXPORT SiegeInfo
  26. {
  27. 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
  28. template <typename Handler> void serialize(Handler &h, const int version)
  29. {
  30. h & wallState;
  31. }
  32. };
  33. struct DLL_EXPORT AttackableTiles
  34. {
  35. std::set<THex> hostileCreaturePositions;
  36. std::set<THex> friendlyCreaturePositions; //for Dragon Breath
  37. template <typename Handler> void serialize(Handler &h, const int version)
  38. {
  39. h & hostileCreaturePositions & friendlyCreaturePositions;
  40. }
  41. };
  42. struct DLL_EXPORT BattleInfo : public CBonusSystemNode
  43. {
  44. ui8 sides[2]; //sides[0] - attacker, sides[1] - defender
  45. si32 round, activeStack;
  46. ui8 siege; // = 0 ordinary battle = 1 a siege with a Fort = 2 a siege with a Citadel = 3 a siege with a Castle
  47. const CGTownInstance * town; //used during town siege - id of attacked town; -1 if not town defence
  48. int3 tile; //for background and bonuses
  49. CGHeroInstance *heroes[2];
  50. CArmedInstance *belligerents[2]; //may be same as heroes
  51. std::vector<CStack*> stacks;
  52. std::vector<CObstacleInstance> obstacles;
  53. ui8 castSpells[2]; //how many spells each side has cast this turn [0] - attacker, [1] - defender
  54. std::vector<const CSpell *> usedSpellsHistory[2]; //each time hero casts spell, it's inserted here -> eagle eye skill
  55. SiegeInfo si;
  56. si32 battlefieldType;
  57. ui8 tacticsSide; //which side is requested to play tactics phase
  58. ui8 tacticDistance; //how many hexes we can go forward (1 = only hexes adjacent to margin line)
  59. template <typename Handler> void serialize(Handler &h, const int version)
  60. {
  61. h & sides & round & activeStack & siege & town & tile & stacks & belligerents & obstacles
  62. & castSpells & si & battlefieldType;
  63. h & heroes;
  64. h & usedSpellsHistory;
  65. h & tacticsSide & tacticDistance;
  66. h & static_cast<CBonusSystemNode&>(*this);
  67. }
  68. ///////////////////////////////////////////////////////////////////////
  69. //void getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root = NULL) const;
  70. ///////////////////////////////////////////////////////////////////////
  71. const CStack * getNextStack() const; //which stack will have turn after current one
  72. void getStackQueue(std::vector<const CStack *> &out, int howMany, int turn = 0, int lastMoved = -1) const; //returns stack in order of their movement action
  73. CStack * getStack(int stackID, bool onlyAlive = true);
  74. const CStack * getStack(int stackID, bool onlyAlive = true) const;
  75. CStack * getStackT(THex tileID, bool onlyAlive = true);
  76. const CStack * getStackT(THex tileID, bool onlyAlive = true) const;
  77. void getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<THex> & occupyable, bool flying, const CStack* stackToOmmit = NULL) const; //send pointer to at least 187 allocated bytes
  78. static bool isAccessible(THex hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos); //helper for makeBFS
  79. void makeBFS(THex start, bool*accessibility, THex *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
  80. std::pair< std::vector<THex>, int > getPath(THex start, THex 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
  81. std::vector<THex> getAccessibility(const CStack * stack, bool addOccupiable, std::vector<THex> * attackable = NULL) const; //returns vector of accessible tiles (taking into account the creature range)
  82. bool isStackBlocked(const CStack * stack) const; //returns true if there is neighboring enemy stack
  83. 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)
  84. 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>
  85. 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>
  86. void calculateCasualties(std::map<ui32,si32> *casualties) const; //casualties are array of maps size 2 (attacker, defeneder), maps are (crid => amount)
  87. std::set<CStack*> getAttackedCreatures(const CSpell * s, int skillLevel, ui8 attackerOwner, THex destinationTile); //calculates stack affected by given spell
  88. void getPotentiallyAttackableHexes(AttackableTiles &at, const CStack* attacker, THex destinationTile, THex attackerPos); //hexes around target that could be attacked in melee
  89. std::set<CStack*> getAttackedCreatures(const CStack* attacker, THex destinationTile, THex attackerPos = THex::INVALID); //calculates range of multi-hex attacks
  90. std::set<THex> getAttackedHexes(const CStack* attacker, THex destinationTile, THex attackerPos = THex::INVALID); //calculates range of multi-hex attacks
  91. static int calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower);
  92. CStack * generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, THex position) const; //helper for CGameHandler::setupBattle and spells addign new stacks to the battlefield
  93. CStack * generateNewStack(const CStackBasicDescriptor &base, int stackID, bool attackerOwned, int slot, THex position) const; //helper for CGameHandler::setupBattle and spells addign new stacks to the battlefield
  94. ui32 getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const; //returns cost of given spell
  95. int hexToWallPart(THex hex) const; //returns part of destructible wall / gate / keep under given hex or -1 if not found
  96. int lineToWallHex(int line) const; //returns hex with wall in given line
  97. std::pair<const CStack *, THex> 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)
  98. ui32 calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const;
  99. ui32 calculateSpellDmg(const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const; //calculates damage inflicted by spell
  100. ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack) const;
  101. ui32 calculateHealedHP(int healedHealth, const CSpell * spell, const CStack * stack) const; //for Archangel
  102. ui32 calculateHealedHP(const CSpell * spell, int usedSpellPower, int spellSchoolLevel, const CStack * stack) const; //unused
  103. bool resurrects(TSpell spellid) const; //TODO: move it to spellHandler?
  104. si8 hasDistancePenalty(const CStack * stackID, THex destHex) const; //determines if given stack has distance penalty shooting given pos
  105. si8 sameSideOfWall(int pos1, int pos2) const; //determines if given positions are on the same side of wall
  106. si8 hasWallPenalty(const CStack * stack, THex destHex) const; //determines if given stack has wall penalty shooting given pos
  107. si8 canTeleportTo(const CStack * stack, THex destHex, int telportLevel) const; //determines if given stack can teleport to given place
  108. bool battleCanShoot(const CStack * stack, THex dest) const; //determines if stack with given ID shoot at the selected destination
  109. const CGHeroInstance * getHero(int player) const; //returns fighting hero that belongs to given player
  110. SpellCasting::ESpellCastProblem battleCanCastSpell(int player, SpellCasting::ECastingMode mode) const; //returns true if there are no general issues preventing from casting a spell
  111. SpellCasting::ESpellCastProblem battleCanCastThisSpell(int player, const CSpell * spell, SpellCasting::ECastingMode mode) const; //checks if given player can cast given spell
  112. SpellCasting::ESpellCastProblem battleIsImmune(const CGHeroInstance * caster, const CSpell * spell, SpellCasting::ECastingMode mode, THex 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.
  113. SpellCasting::ESpellCastProblem battleCanCastThisSpellHere(int player, const CSpell * spell, SpellCasting::ECastingMode mode, THex dest); //checks if given player can cast given spell at given tile in given mode
  114. bool battleTestElementalImmunity(const CStack * subject, const CSpell * spell, Bonus::BonusType element, bool damageSpell) const;
  115. std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures, int casterSideOwner, SpellCasting::ECastingMode mode) const;
  116. bool battleCanFlee(int player) const; //returns true if player can flee from the battle
  117. const CStack * battleGetStack(THex pos, bool onlyAlive); //returns stack at given tile
  118. const CGHeroInstance * battleGetOwner(const CStack * stack) const; //returns hero that owns given stack; NULL if none
  119. 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
  120. void localInit();
  121. static BattleInfo * setupBattle( int3 tile, int terrain, int terType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town );
  122. bool isInTacticRange( THex dest ) const;
  123. int getSurrenderingCost(int player) const;
  124. int theOtherPlayer(int player) const;
  125. ui8 whatSide(int player) const;
  126. };
  127. class DLL_EXPORT CStack : public CBonusSystemNode, public CStackBasicDescriptor
  128. {
  129. public:
  130. /// pointer to structure describing stack in garrison that was source of this stack, may be NULL (eg. summoned creatures and War Machines)
  131. const CStackInstance *base;
  132. /// unique ID of stack
  133. ui32 ID;
  134. /// how many creatures stack counted at the beginning of battle
  135. ui32 baseAmount;
  136. /// HP of first creature in stack
  137. ui32 firstHPleft;
  138. /// owner - player colour (255 for neutrals), slot - position in garrison (may be 255 for neutrals/called creatures)
  139. ui8 owner, slot;
  140. /// if true, this stack is owned by attakcer (this one from left hand side of battle)
  141. ui8 attackerOwned;
  142. /// position on battlefield; -2 - keep, -3 - lower tower, -4 - upper tower
  143. THex position;
  144. /// how many counter attacks can be performed more in this turn (by default set at the beginning of the round to 1)
  145. ui8 counterAttacks;
  146. /// how many shots left
  147. si16 shots;
  148. /// how many casts left
  149. ui8 casts;
  150. std::set<ECombatInfo> state;
  151. const CCreature* getCreature() const {return type;}
  152. /// c-tor
  153. CStack(const CStackInstance *base, int O, int I, bool AO, int S);
  154. /// c-tor
  155. CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S = 255);
  156. /// c-tor
  157. CStack();
  158. ~CStack();
  159. std::string nodeName() const OVERRIDE;
  160. /// set initial (invalid) values
  161. void init();
  162. /// used to finish initialization when inheriting creature parameters is working
  163. void postInit();
  164. /// effect id (SP)
  165. const Bonus * getEffect(ui16 id, int turn = 0) const;
  166. /// returns amount of effects with given id set for this stack
  167. ui8 howManyEffectsSet(ui16 id) const;
  168. /// if stack has remaining move this turn
  169. bool willMove(int turn = 0) const;
  170. /// if stack can retaliate after attacked
  171. bool ableToRetaliate() const;
  172. /// if stack was already moved this turn
  173. bool moved(int turn = 0) const;
  174. /// if stack can move
  175. bool canMove(int turn = 0) const;
  176. /// get speed of creature with all modificators
  177. ui32 Speed(int turn = 0) const;
  178. static void stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse);
  179. /// returns vector of active spell IDs sorted by time of cast
  180. std::vector<si32> activeSpells() const;
  181. /// if stack belongs to hero (directly or was by him summoned) returns hero, NULL otherwise
  182. const CGHeroInstance *getMyHero() const;
  183. static inline Bonus featureGenerator(Bonus::BonusType type, si16 subtype, si32 value, ui16 turnsRemain, si32 additionalInfo = 0, si32 limit = Bonus::NO_LIMIT)
  184. {
  185. Bonus hb = makeFeatureVal(type, Bonus::N_TURNS, subtype, value, Bonus::SPELL_EFFECT, turnsRemain, additionalInfo);
  186. hb.effectRange = limit;
  187. hb.source = Bonus::SPELL_EFFECT;
  188. return hb;
  189. }
  190. static inline Bonus featureGeneratorVT(Bonus::BonusType type, si16 subtype, si32 value, ui16 turnsRemain, ui8 valType)
  191. {
  192. Bonus ret = makeFeatureVal(type, Bonus::N_TURNS, subtype, value, Bonus::SPELL_EFFECT, turnsRemain);
  193. ret.valType = valType;
  194. ret.source = Bonus::SPELL_EFFECT;
  195. return ret;
  196. }
  197. static bool isMeleeAttackPossible(const CStack * attacker, const CStack * defender, THex attackerPos = THex::INVALID, THex defenderPos = THex::INVALID);
  198. /// checks if stack is double wide (occupies two hexes)
  199. bool doubleWide() const;
  200. /// returns number of occupied hex (not the position) if stack is double wide; otherwise -1
  201. THex occupiedHex() const;
  202. /// up to two occupied hexes, starting from front
  203. std::vector<THex> getHexes() const;
  204. /// checks also if unit is double-wide
  205. bool coversPos(THex position) const;
  206. /// get six or 8 surrounding hexes depending on creature size
  207. std::vector<THex> getSurroundingHexes(THex attackerPos = THex::INVALID) const;
  208. /// requires bsa.damageAmout filled
  209. void prepareAttacked(BattleStackAttacked &bsa) const;
  210. template <typename Handler> void serialize(Handler &h, const int version)
  211. {
  212. assert(isIndependentNode());
  213. h & static_cast<CBonusSystemNode&>(*this);
  214. h & static_cast<CStackBasicDescriptor&>(*this);
  215. h & ID & baseAmount & firstHPleft & owner & slot & attackerOwned & position & state & counterAttacks
  216. & shots & casts & count;
  217. TSlot slot = (base ? base->armyObj->findStack(base) : -1);
  218. const CArmedInstance *army = (base ? base->armyObj : NULL);
  219. if(h.saving)
  220. {
  221. h & army & slot;
  222. }
  223. else
  224. {
  225. h & army & slot;
  226. if(!army || slot == -1 || !army->hasStackAtSlot(slot))
  227. {
  228. base = NULL;
  229. tlog3 << type->nameSing << " doesn't have a base stack!\n";
  230. }
  231. else
  232. {
  233. base = &army->getStack(slot);
  234. }
  235. }
  236. }
  237. /// determines if stack is alive
  238. bool alive() const
  239. {
  240. return vstd::contains(state,ALIVE);
  241. }
  242. };
  243. class DLL_EXPORT CMP_stack
  244. {
  245. int phase; //rules of which phase will be used
  246. int turn;
  247. public:
  248. bool operator ()(const CStack* a, const CStack* b);
  249. CMP_stack(int Phase = 1, int Turn = 0);
  250. };