BattleState.h 14 KB

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