BattleState.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. #include "CBattleCallback.h"
  11. /*
  12. * BattleState.h, part of VCMI engine
  13. *
  14. * Authors: listed in file AUTHORS in main folder
  15. *
  16. * License: GNU General Public License v2.0 or later
  17. * Full text of license available in license.txt file, in main folder
  18. *
  19. */
  20. class CGHeroInstance;
  21. class CStack;
  22. class CArmedInstance;
  23. class CGTownInstance;
  24. class CStackInstance;
  25. struct BattleStackAttacked;
  26. //only for use in BattleInfo
  27. struct DLL_LINKAGE SiegeInfo
  28. {
  29. ui8 wallState[EWallParts::PARTS_COUNT];
  30. template <typename Handler> void serialize(Handler &h, const int version)
  31. {
  32. h & wallState;
  33. }
  34. };
  35. struct DLL_LINKAGE BattleInfo : public CBonusSystemNode, public CBattleInfoCallback
  36. {
  37. PlayerColor sides[2]; //sides[0] - attacker, sides[1] - defender
  38. si32 round, activeStack, selectedStack;
  39. CGTownInstance::EFortLevel siege;
  40. const CGTownInstance * town; //used during town siege - id of attacked town; -1 if not town defence
  41. int3 tile; //for background and bonuses
  42. CGHeroInstance* heroes[2];
  43. CArmedInstance *belligerents[2]; //may be same as heroes
  44. std::vector<CStack*> stacks;
  45. std::vector<shared_ptr<CObstacleInstance> > obstacles;
  46. ui8 castSpells[2]; //how many spells each side has cast this turn [0] - attacker, [1] - defender
  47. std::vector<const CSpell *> usedSpellsHistory[2]; //each time hero casts spell, it's inserted here -> eagle eye skill
  48. si16 enchanterCounter[2]; //tends to pass through 0, so sign is needed
  49. SiegeInfo si;
  50. BFieldType battlefieldType; //like !!BA:B
  51. ETerrainType terrainType; //used for some stack nativity checks (not the bonus limiters though that have their own copy)
  52. ui8 tacticsSide; //which side is requested to play tactics phase
  53. ui8 tacticDistance; //how many hexes we can go forward (1 = only hexes adjacent to margin line)
  54. template <typename Handler> void serialize(Handler &h, const int version)
  55. {
  56. h & sides & round & activeStack & selectedStack & siege & town & tile & stacks & belligerents & obstacles
  57. & castSpells & si & battlefieldType & terrainType;
  58. h & heroes;
  59. h & usedSpellsHistory & enchanterCounter;
  60. h & tacticsSide & tacticDistance;
  61. h & static_cast<CBonusSystemNode&>(*this);
  62. }
  63. //////////////////////////////////////////////////////////////////////////
  64. BattleInfo();
  65. ~BattleInfo(){};
  66. //////////////////////////////////////////////////////////////////////////
  67. CStack * getStackT(BattleHex tileID, bool onlyAlive = true);
  68. CStack * getStack(int stackID, bool onlyAlive = true);
  69. const CStack * getNextStack() const; //which stack will have turn after current one
  70. //void getStackQueue(std::vector<const CStack *> &out, int howMany, int turn = 0, int lastMoved = -1) const; //returns stack in order of their movement action
  71. //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
  72. //static bool isAccessible(BattleHex hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos); //helper for makeBFS
  73. int getAvaliableHex(CreatureID creID, bool attackerOwned, int initialPos = -1) const; //find place for summon / clone effects
  74. //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
  75. std::pair< std::vector<BattleHex>, int > getPath(BattleHex start, BattleHex dest, const CStack *stack); //returned value: pair<path, length>; length may be different than number of elements in path since flying vreatures jump between distant hexes
  76. //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)
  77. //bool isObstacleVisibleForSide(const CObstacleInstance &obstacle, ui8 side) const;
  78. shared_ptr<CObstacleInstance> getObstacleOnTile(BattleHex tile) const;
  79. std::set<BattleHex> getStoppers(bool whichSidePerspective) const;
  80. 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)
  81. void calculateCasualties(std::map<ui32,si32> *casualties) const; //casualties are array of maps size 2 (attacker, defeneder), maps are (crid => amount)
  82. //void getPotentiallyAttackableHexes(AttackableTiles &at, const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos); //hexes around target that could be attacked in melee
  83. //std::set<CStack*> getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos = BattleHex::INVALID); //calculates range of multi-hex attacks
  84. //std::set<BattleHex> getAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos = BattleHex::INVALID); //calculates range of multi-hex attacks
  85. static int calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower);
  86. CStack * generateNewStack(const CStackInstance &base, bool attackerOwned, SlotID slot, BattleHex position) const; //helper for CGameHandler::setupBattle and spells addign new stacks to the battlefield
  87. CStack * generateNewStack(const CStackBasicDescriptor &base, bool attackerOwned, SlotID slot, BattleHex position) const; //helper for CGameHandler::setupBattle and spells addign new stacks to the battlefield
  88. int getIdForNewStack() const; //suggest a currently unused ID that'd suitable for generating a new stack
  89. //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)
  90. ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack, const CStack * sacrificedStack = NULL) const; //Sacrifice
  91. ui32 calculateHealedHP(int healedHealth, const CSpell * spell, const CStack * stack) const; //for Archangel
  92. ui32 calculateHealedHP(const CSpell * spell, int usedSpellPower, int spellSchoolLevel, const CStack * stack) const; //healing spells casted by stacks
  93. bool resurrects(SpellID spellid) const; //TODO: move it to spellHandler?
  94. const CGHeroInstance * getHero(PlayerColor player) const; //returns fighting hero that belongs to given player
  95. std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<const CStack*> affectedCreatures, PlayerColor casterSideOwner, ECastingMode::ECastingMode mode, int usedSpellPower, int spellLevel) const;
  96. const CStack * battleGetStack(BattleHex pos, bool onlyAlive); //returns stack at given tile
  97. const CGHeroInstance * battleGetOwner(const CStack * stack) const; //returns hero that owns given stack; NULL if none
  98. void localInit();
  99. void localInitStack(CStack * s);
  100. static BattleInfo * setupBattle( int3 tile, ETerrainType terrain, BFieldType battlefieldType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town );
  101. //bool hasNativeStack(ui8 side) const;
  102. PlayerColor theOtherPlayer(PlayerColor player) const;
  103. ui8 whatSide(PlayerColor player) const;
  104. static BattlefieldBI::BattlefieldBI battlefieldTypeToBI(BFieldType bfieldType); //converts above to ERM BI format
  105. static int battlefieldTypeToTerrain(int bfieldType); //converts above to ERM BI format
  106. };
  107. class DLL_LINKAGE CStack : public CBonusSystemNode, public CStackBasicDescriptor
  108. {
  109. public:
  110. const CStackInstance *base; //garrison slot from which stack originates (NULL for war machines, summoned cres, etc)
  111. ui32 ID; //unique ID of stack
  112. ui32 baseAmount;
  113. ui32 firstHPleft; //HP of first creature in stack
  114. PlayerColor owner; //owner - player colour (255 for neutrals)
  115. SlotID slot; //slot - position in garrison (may be 255 for neutrals/called creatures)
  116. bool attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
  117. BattleHex position; //position on battlefield; -2 - keep, -3 - lower tower, -4 - upper tower
  118. ui8 counterAttacks; //how many counter attacks can be performed more in this turn (by default set at the beginning of the round to 1)
  119. si16 shots; //how many shots left
  120. ui8 casts; //how many casts left
  121. std::set<EBattleStackState::EBattleStackState> state;
  122. //overrides
  123. const CCreature* getCreature() const {return type;}
  124. CStack(const CStackInstance *base, PlayerColor O, int I, bool AO, SlotID S); //c-tor
  125. CStack(const CStackBasicDescriptor *stack, PlayerColor O, int I, bool AO, SlotID S = SlotID(255)); //c-tor
  126. CStack(); //c-tor
  127. ~CStack();
  128. std::string nodeName() const OVERRIDE;
  129. void init(); //set initial (invalid) values
  130. void postInit(); //used to finish initialization when inheriting creature parameters is working
  131. std::string getName() const; //plural or singular
  132. bool willMove(int turn = 0) const; //if stack has remaining move this turn
  133. bool ableToRetaliate() const; //if stack can retaliate after attacked
  134. bool moved(int turn = 0) const; //if stack was already moved this turn
  135. bool waited(int turn = 0) const;
  136. bool canMove(int turn = 0) const; //if stack can move
  137. bool canBeHealed() const; //for first aid tent - only harmed stacks that are not war machines
  138. ui32 Speed(int turn = 0, bool useBind = false) const; //get speed of creature with all modificators
  139. si32 magicResistance() const; //include aura of resistance
  140. static void stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse);
  141. std::vector<si32> activeSpells() const; //returns vector of active spell IDs sorted by time of cast
  142. const CGHeroInstance *getMyHero() const; //if stack belongs to hero (directly or was by him summoned) returns hero, NULL otherwise
  143. static inline Bonus featureGenerator(Bonus::BonusType type, si16 subtype, si32 value, ui16 turnsRemain, si32 additionalInfo = 0, Bonus::LimitEffect limit = Bonus::NO_LIMIT)
  144. {
  145. Bonus hb = makeFeatureVal(type, Bonus::N_TURNS, subtype, value, Bonus::SPELL_EFFECT, turnsRemain, additionalInfo);
  146. hb.effectRange = limit;
  147. return hb;
  148. }
  149. static bool isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos = BattleHex::INVALID, BattleHex defenderPos = BattleHex::INVALID);
  150. bool doubleWide() const;
  151. BattleHex occupiedHex() const; //returns number of occupied hex (not the position) if stack is double wide; otherwise -1
  152. BattleHex occupiedHex(BattleHex assumedPos) const; //returns number of occupied hex (not the position) if stack is double wide and would stand on assumedPos; otherwise -1
  153. std::vector<BattleHex> getHexes() const; //up to two occupied hexes, starting from front
  154. std::vector<BattleHex> getHexes(BattleHex assumedPos) const; //up to two occupied hexes, starting from front
  155. static std::vector<BattleHex> getHexes(BattleHex assumedPos, bool twoHex, bool AttackerOwned); //up to two occupied hexes, starting from front
  156. bool coversPos(BattleHex position) const; //checks also if unit is double-wide
  157. std::vector<BattleHex> getSurroundingHexes(BattleHex attackerPos = BattleHex::INVALID) const; // get six or 8 surrounding hexes depending on creature size
  158. void prepareAttacked(BattleStackAttacked &bsa) const; //requires bsa.damageAmout filled
  159. template <typename Handler> void serialize(Handler &h, const int version)
  160. {
  161. assert(isIndependentNode());
  162. h & static_cast<CBonusSystemNode&>(*this);
  163. h & static_cast<CStackBasicDescriptor&>(*this);
  164. h & ID & baseAmount & firstHPleft & owner & slot & attackerOwned & position & state & counterAttacks
  165. & shots & casts & count;
  166. const CArmedInstance *army = (base ? base->armyObj : NULL);
  167. SlotID slot = (base ? base->armyObj->findStack(base) : SlotID());
  168. if(h.saving)
  169. {
  170. h & army & slot;
  171. }
  172. else
  173. {
  174. h & army & slot;
  175. if (slot == SlotID::COMMANDER_SLOT_PLACEHOLDER) //TODO
  176. {
  177. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  178. assert (hero);
  179. base = hero->commander;
  180. }
  181. else if(!army || slot == SlotID() || !army->hasStackAtSlot(slot))
  182. {
  183. base = NULL;
  184. tlog3 << type->nameSing << " doesn't have a base stack!\n";
  185. }
  186. else
  187. {
  188. base = &army->getStack(slot);
  189. }
  190. }
  191. }
  192. bool alive() const //determines if stack is alive
  193. {
  194. return vstd::contains(state,EBattleStackState::ALIVE);
  195. }
  196. bool isValidTarget(bool allowDead = false) const; //alive non-turret stacks (can be attacked or be object of magic effect)
  197. };
  198. class DLL_LINKAGE CMP_stack
  199. {
  200. int phase; //rules of which phase will be used
  201. int turn;
  202. public:
  203. bool operator ()(const CStack* a, const CStack* b);
  204. CMP_stack(int Phase = 1, int Turn = 0);
  205. };