CGameState.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #ifndef __CGAMESTATE_H__
  2. #define __CGAMESTATE_H__
  3. #include "../global.h"
  4. #ifndef _MSC_VER
  5. #include "../hch/CCreatureHandler.h"
  6. #include "VCMI_Lib.h"
  7. #include "map.h"
  8. #endif
  9. #include <set>
  10. #include <vector>
  11. #include "StackFeature.h"
  12. #ifdef _WIN32
  13. #include <tchar.h>
  14. #else
  15. #include "../tchar_amigaos4.h"
  16. #endif
  17. /*
  18. * CGameState.h, part of VCMI engine
  19. *
  20. * Authors: listed in file AUTHORS in main folder
  21. *
  22. * License: GNU General Public License v2.0 or later
  23. * Full text of license available in license.txt file, in main folder
  24. *
  25. */
  26. class CTown;
  27. class CScriptCallback;
  28. class CCallback;
  29. class CLuaCallback;
  30. class CCPPObjectScript;
  31. class CCreatureSet;
  32. class CStack;
  33. class CGHeroInstance;
  34. class CGTownInstance;
  35. class CArmedInstance;
  36. class CGDefInfo;
  37. class CObjectScript;
  38. class CGObjectInstance;
  39. class CCreature;
  40. struct Mapa;
  41. struct StartInfo;
  42. struct SDL_Surface;
  43. class CMapHandler;
  44. class CPathfinder;
  45. struct SetObjectProperty;
  46. struct MetaString;
  47. struct CPack;
  48. class CSpell;
  49. struct TerrainTile;
  50. namespace boost
  51. {
  52. class shared_mutex;
  53. }
  54. struct DLL_EXPORT PlayerState
  55. {
  56. public:
  57. ui8 color, serial;
  58. ui8 human; //true if human controlled player, false for AI
  59. ui32 currentSelection; //id of hero/town, 0xffffffff if none
  60. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  61. std::vector<si32> resources;
  62. std::vector<CGHeroInstance *> heroes;
  63. std::vector<CGTownInstance *> towns;
  64. std::vector<CGHeroInstance *> availableHeroes; //heroes available in taverns
  65. PlayerState():color(-1),currentSelection(0xffffffff){};
  66. template <typename Handler> void serialize(Handler &h, const int version)
  67. {
  68. h & color & serial & human & currentSelection & fogOfWarMap & resources;
  69. ui32 size;
  70. if(h.saving) //write subids of available heroes
  71. {
  72. size = availableHeroes.size();
  73. h & size;
  74. for(size_t i=0; i < size; i++)
  75. h & availableHeroes[i]->subID;
  76. }
  77. else
  78. {
  79. ui32 hid;
  80. h & size;
  81. for(size_t i=0; i < size; i++)
  82. {
  83. //fill availableHeroes with dummy hero instances, holding subids
  84. h & hid;
  85. availableHeroes.push_back(new CGHeroInstance);
  86. availableHeroes[availableHeroes.size()-1]->subID = hid;
  87. }
  88. }
  89. }
  90. };
  91. struct DLL_EXPORT CObstacleInstance
  92. {
  93. int uniqueID;
  94. int ID; //ID of obstacle (defines type of it)
  95. int pos; //position on battlefield
  96. template <typename Handler> void serialize(Handler &h, const int version)
  97. {
  98. h & ID & pos & uniqueID;
  99. }
  100. };
  101. //only for use in BattleInfo
  102. struct DLL_EXPORT SiegeInfo
  103. {
  104. 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
  105. template <typename Handler> void serialize(Handler &h, const int version)
  106. {
  107. h & wallState;
  108. }
  109. };
  110. struct DLL_EXPORT BattleInfo
  111. {
  112. ui8 side1, side2; //side1 - attacker, side2 - defender
  113. si32 round, activeStack;
  114. ui8 siege; // = 0 ordinary battle = 1 a siege with a Fort = 2 a siege with a Citadel = 3 a siege with a Castle
  115. si32 tid; //used during town siege - id of attacked town; -1 if not town defence
  116. int3 tile; //for background and bonuses
  117. si32 hero1, hero2;
  118. CCreatureSet army1, army2;
  119. std::vector<CStack*> stacks;
  120. std::vector<CObstacleInstance> obstacles;
  121. ui8 castSpells[2]; //[0] - attacker, [1] - defender
  122. SiegeInfo si;
  123. template <typename Handler> void serialize(Handler &h, const int version)
  124. {
  125. h & side1 & side2 & round & activeStack & siege & tid & tile & stacks & army1 & army2 & hero1 & hero2 & obstacles
  126. & castSpells & si;
  127. }
  128. CStack * getNextStack(); //which stack will have turn after current one
  129. std::vector<CStack> getStackQueue(); //returns stack in order of their movement action
  130. CStack * getStack(int stackID, bool onlyAlive = true);
  131. const CStack * getStack(int stackID, bool onlyAlive = true) const;
  132. CStack * getStackT(int tileID, bool onlyAlive = true);
  133. const CStack * getStackT(int tileID, bool onlyAlive = true) const;
  134. void getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit=-1) const; //send pointer to at least 187 allocated bytes
  135. static bool isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos); //helper for makeBFS
  136. void makeBFS(int start, bool*accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying) 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
  137. std::pair< std::vector<int>, int > getPath(int start, int 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
  138. std::vector<int> getAccessibility(int stackID, bool addOccupiable) const; //returns vector of accessible tiles (taking into account the creature range)
  139. bool isStackBlocked(int ID); //returns true if there is neighbouring enemy stack
  140. static signed char mutualPosition(int hex1, int hex2); //returns info about mutual position of given hexes (-1 - they're distant, 0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left)
  141. static std::vector<int> neighbouringTiles(int hex);
  142. static ui32 calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge); //charge - number of hexes travelled before attack (for champion's jousting)
  143. static std::pair<ui32, ui32> calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge); //charge - number of hexes travelled before attack (for champion's jousting); returns pair <min dmg, max dmg>
  144. void calculateCasualties(std::set<std::pair<ui32,si32> > *casualties) const;
  145. std::set<CStack*> getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile); //calculates stack affected by given spell
  146. static int calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster);
  147. CStack * generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const; //helper for CGameHandler::setupBattle and spells addign new stacks to the battlefield
  148. ui32 getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const; //returns cost of given spell
  149. int hexToWallPart(int hex) const; //returns part of destructible wall / gate / keep under given hex or -1 if not found
  150. std::pair<const CStack *, int> 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)
  151. };
  152. class DLL_EXPORT CStack
  153. {
  154. public:
  155. ui32 ID; //unique ID of stack
  156. CCreature * creature;
  157. ui32 amount, baseAmount;
  158. ui32 firstHPleft; //HP of first creature in stack
  159. ui8 owner, slot; //owner - player colour (255 for neutrals), slot - position in garrison (may be 255 for neutrals/called creatures)
  160. ui8 attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
  161. ui16 position; //position on battlefield
  162. ui8 counterAttacks; //how many counter attacks can be performed more in this turn (by default set at the beginning of the round to 1)
  163. si16 shots; //how many shots left
  164. si8 morale, luck; //base stack luck/morale
  165. std::vector<StackFeature> features;
  166. std::set<ECombatInfo> state;
  167. struct StackEffect
  168. {
  169. ui16 id; //spell id
  170. ui8 level; //skill level
  171. ui16 turnsRemain;
  172. template <typename Handler> void serialize(Handler &h, const int version)
  173. {
  174. h & id & level & turnsRemain;
  175. }
  176. };
  177. std::vector<StackEffect> effects;
  178. int valOfFeatures(StackFeature::ECombatFeatures type, int subtype = -1024) const;//subtype -> subtype of bonus, if -1024 then any
  179. bool hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype = -1024) const; //determines if stack has a bonus of given type (and optionally subtype)
  180. CStack(CCreature * C, int A, int O, int I, bool AO, int S); //c-tor
  181. CStack() : ID(-1), creature(NULL), amount(-1), baseAmount(-1), firstHPleft(-1), owner(255), slot(255), attackerOwned(true), position(-1), counterAttacks(1) {} //c-tor
  182. const StackEffect * getEffect(ui16 id) const; //effect id (SP)
  183. ui8 howManyEffectsSet(ui16 id) const; //returns amount of effects with given id set for this stack
  184. bool willMove(); //if stack has remaining move this turn
  185. ui32 Speed() const; //get speed of creature with all modificators
  186. si8 Morale() const; //get morale of stack with all modificators
  187. si8 Luck() const; //get luck of stack with all modificators
  188. si32 Attack() const; //get attack of stack with all modificators
  189. si32 Defense(bool withFrenzy = true) const; //get defense of stack with all modificators
  190. ui16 MaxHealth() const; //get max HP of stack with all modifiers
  191. template <typename Handler> void save(Handler &h, const int version)
  192. {
  193. h & creature->idNumber;
  194. }
  195. template <typename Handler> void load(Handler &h, const int version)
  196. {
  197. ui32 id;
  198. h & id;
  199. creature = &VLC->creh->creatures[id];
  200. //features = creature->abilities;
  201. }
  202. template <typename Handler> void serialize(Handler &h, const int version)
  203. {
  204. h & ID & amount & baseAmount & firstHPleft & owner & slot & attackerOwned & position & state & counterAttacks
  205. & shots & morale & luck & features;
  206. if(h.saving)
  207. save(h,version);
  208. else
  209. load(h,version);
  210. }
  211. bool alive() const //determines if stack is alive
  212. {
  213. return vstd::contains(state,ALIVE);
  214. }
  215. };
  216. struct UpgradeInfo
  217. {
  218. int oldID; //creature to be upgraded
  219. std::vector<int> newID; //possible upgrades
  220. std::vector<std::set<std::pair<int,int> > > cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>
  221. UpgradeInfo(){oldID = -1;};
  222. };
  223. struct CPathNode
  224. {
  225. bool accesible; //true if a hero can be on this node
  226. int dist; //distance from the first node of searching; -1 is infinity
  227. CPathNode * theNodeBefore;
  228. int3 coord; //coordiantes
  229. bool visited;
  230. };
  231. struct CGPathNode
  232. {
  233. enum {ACCESSIBLE=1, VISITABLE, BLOCKVIS, BLOCKED}; //BLOCKVIS - visitable from neighbouring tile but not passable
  234. ui8 accessible; //the enum above
  235. ui8 land;
  236. ui8 turns;
  237. ui32 moveRemains;
  238. CGPathNode * theNodeBefore;
  239. int3 coord; //coordinates
  240. CGPathNode();
  241. };
  242. struct DLL_EXPORT CPath
  243. {
  244. std::vector<CPathNode> nodes; //just get node by node
  245. int3 startPos() const; // start point
  246. int3 endPos() const; //destination point
  247. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  248. };
  249. struct DLL_EXPORT CGPath
  250. {
  251. std::vector<CGPathNode> nodes; //just get node by node
  252. int3 startPos() const; // start point
  253. int3 endPos() const; //destination point
  254. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  255. };
  256. struct DLL_EXPORT CPathsInfo
  257. {
  258. int3 sizes;
  259. CGPathNode ***nodes; //[w][h][level]
  260. bool getPath(const int3 &dst, CGPath &out);
  261. CPathsInfo(const int3 &Sizes);
  262. ~CPathsInfo();
  263. };
  264. class DLL_EXPORT CGameState
  265. {
  266. public:
  267. StartInfo* scenarioOps;
  268. ui32 seed;
  269. ui8 currentPlayer; //ID of player currently having turn
  270. BattleInfo *curB; //current battle
  271. ui32 day; //total number of days in game
  272. Mapa * map;
  273. std::map<ui8,PlayerState> players; //ID <-> player state
  274. std::map<int, CGDefInfo*> villages, forts, capitols; //def-info for town graphics
  275. std::vector<ui32> resVals; //default values of resources in gold
  276. struct DLL_EXPORT HeroesPool
  277. {
  278. std::map<ui32,CGHeroInstance *> heroesPool; //[subID] - heroes available to buy; NULL if not available
  279. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero
  280. CGHeroInstance * pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const;
  281. template <typename Handler> void serialize(Handler &h, const int version)
  282. {
  283. h & heroesPool & pavailable;
  284. }
  285. } hpool; //we have here all heroes available on this map that are not hired
  286. boost::shared_mutex *mx;
  287. PlayerState *getPlayer(ui8 color);
  288. void init(StartInfo * si, Mapa * map, int Seed);
  289. void loadTownDInfos();
  290. void randomizeObject(CGObjectInstance *cur);
  291. std::pair<int,int> pickObject(CGObjectInstance *obj);
  292. int pickHero(int owner);
  293. void apply(CPack *pack);
  294. CGHeroInstance *getHero(int objid);
  295. CGTownInstance *getTown(int objid);
  296. bool battleMoveCreatureStack(int ID, int dest);
  297. bool battleAttackCreatureStack(int ID, int dest);
  298. bool battleShootCreatureStack(int ID, int dest);
  299. bool battleCanFlee(int player); //returns true if player can flee from the battle
  300. int battleGetStack(int pos, bool onlyAlive); //returns ID of stack at given tile
  301. int battleGetBattlefieldType(int3 tile = int3());// 1. sand/shore 2. sand/mesas 3. dirt/birches 4. dirt/hills 5. dirt/pines 6. grass/hills 7. grass/pines 8. lava 9. magic plains 10. snow/mountains 11. snow/trees 12. subterranean 13. swamp/trees 14. fiery fields 15. rock lands 16. magic clouds 17. lucid pools 18. holy ground 19. clover field 20. evil fog 21. "favourable winds" text on magic plains background 22. cursed ground 23. rough 24. ship to ship 25. ship
  302. si8 battleMaxSpellLevel(); //calculates maximum spell level possible to be cast on battlefield - takes into account artifacts of both heroes; if no effects are set, SPELL_LEVELS is returned
  303. UpgradeInfo getUpgradeInfo(CArmedInstance *obj, int stackPos);
  304. float getMarketEfficiency(int player, int mode=0);
  305. int canBuildStructure(const CGTownInstance *t, int ID);// 0 - no more than one capitol, 1 - lack of water, 2 - forbidden, 3 - Add another level to Mage Guild, 4 - already built, 5 - cannot build, 6 - cannot afford, 7 - build, 8 - lack of requirements
  306. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  307. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  308. bool getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret); //calculates path between src and dest; returns pointer to newly allocated CPath or NULL if path does not exists
  309. void calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src = int3(-1,-1,-1), int movement = -1); //calculates possible paths for hero, by default uses current hero position and movement left; returns pointer to newly allocated CPath or NULL if path does not exists
  310. bool isVisible(int3 pos, int player);
  311. bool isVisible(const CGObjectInstance *obj, int player);
  312. CGameState(); //c-tor
  313. ~CGameState(); //d-tor
  314. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand);
  315. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  316. int getDate(int mode=0) const; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
  317. template <typename Handler> void serialize(Handler &h, const int version)
  318. {
  319. h & scenarioOps & seed & currentPlayer & day & map & players & resVals & hpool;
  320. if(!h.saving)
  321. {
  322. loadTownDInfos();
  323. //recreating towns/heroes vectors in players entries
  324. for(int i=0; i<map->towns.size(); i++)
  325. if(map->towns[i]->tempOwner < PLAYER_LIMIT)
  326. getPlayer(map->towns[i]->tempOwner)->towns.push_back(map->towns[i]);
  327. for(int i=0; i<map->heroes.size(); i++)
  328. if(map->heroes[i]->tempOwner < PLAYER_LIMIT)
  329. getPlayer(map->heroes[i]->tempOwner)->heroes.push_back(map->heroes[i]);
  330. //recreating available heroes
  331. for(std::map<ui8,PlayerState>::iterator i=players.begin(); i!=players.end(); i++)
  332. {
  333. for(size_t j=0; j < i->second.availableHeroes.size(); j++)
  334. {
  335. ui32 hlp = i->second.availableHeroes[j]->subID;
  336. delete i->second.availableHeroes[j];
  337. i->second.availableHeroes[j] = hpool.heroesPool[hlp];
  338. }
  339. }
  340. }
  341. }
  342. friend class CCallback;
  343. friend class CLuaCallback;
  344. friend class CClient;
  345. friend void initGameState(Mapa * map, CGameInfo * cgi);
  346. friend class IGameCallback;
  347. friend class CMapHandler;
  348. friend class CGameHandler;
  349. };
  350. #endif // __CGAMESTATE_H__