CGameState.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. #ifndef __CGAMESTATE_H__
  2. #define __CGAMESTATE_H__
  3. #include "../global.h"
  4. #include <cassert>
  5. #ifndef _MSC_VER
  6. #include "../hch/CCreatureHandler.h"
  7. #include "VCMI_Lib.h"
  8. #include "map.h"
  9. #endif
  10. #include <set>
  11. #include <vector>
  12. #include <list>
  13. #include "StackFeature.h"
  14. #ifdef _WIN32
  15. #include <tchar.h>
  16. #else
  17. #include "../tchar_amigaos4.h"
  18. #endif
  19. /*
  20. * CGameState.h, part of VCMI engine
  21. *
  22. * Authors: listed in file AUTHORS in main folder
  23. *
  24. * License: GNU General Public License v2.0 or later
  25. * Full text of license available in license.txt file, in main folder
  26. *
  27. */
  28. class CTown;
  29. class CScriptCallback;
  30. class CCallback;
  31. class CLuaCallback;
  32. class CCPPObjectScript;
  33. class CCreatureSet;
  34. class CStack;
  35. class CGHeroInstance;
  36. class CGTownInstance;
  37. class CArmedInstance;
  38. class CGDwelling;
  39. class CGDefInfo;
  40. class CObjectScript;
  41. class CGObjectInstance;
  42. class CCreature;
  43. struct Mapa;
  44. struct StartInfo;
  45. struct SDL_Surface;
  46. class CMapHandler;
  47. class CPathfinder;
  48. struct SetObjectProperty;
  49. struct MetaString;
  50. struct CPack;
  51. class CSpell;
  52. struct TerrainTile;
  53. namespace boost
  54. {
  55. class shared_mutex;
  56. }
  57. struct DLL_EXPORT SThievesGuildInfo
  58. {
  59. std::vector<ui8> playerColors; //colors of players that are in-game
  60. std::vector< std::list< ui8 > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  61. //TODO: personality, best monster
  62. struct InfoAboutHero
  63. {
  64. ui32 portrait;
  65. si32 primSkills[PRIMARY_SKILLS]; //-1 if not available; otherwise values
  66. template <typename Handler> void serialize(Handler &h, const int version)
  67. {
  68. h & portrait & primSkills;
  69. }
  70. };
  71. std::map<ui8, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  72. template <typename Handler> void serialize(Handler &h, const int version)
  73. {
  74. h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income;
  75. h & colorToBestHero;
  76. }
  77. };
  78. struct DLL_EXPORT PlayerState
  79. {
  80. public:
  81. enum EStatus {INGAME, LOSER, WINNER};
  82. ui8 color, serial;
  83. ui8 human; //true if human controlled player, false for AI
  84. ui32 currentSelection; //id of hero/town, 0xffffffff if none
  85. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  86. std::vector<si32> resources;
  87. std::vector<CGHeroInstance *> heroes;
  88. std::vector<CGTownInstance *> towns;
  89. std::vector<CGHeroInstance *> availableHeroes; //heroes available in taverns
  90. std::vector<CGDwelling *> dwellings; //used for town growth
  91. ui8 status; //0 - in game, 1 - loser, 2 - winner <- uses EStatus enum
  92. ui8 daysWithoutCastle;
  93. PlayerState();
  94. template <typename Handler> void serialize(Handler &h, const int version)
  95. {
  96. h & color & serial & human & currentSelection & fogOfWarMap & resources & status;
  97. h & heroes & towns & availableHeroes & dwellings & status & daysWithoutCastle;
  98. // ui32 size;
  99. // if(h.saving) //write subids of available heroes
  100. // {
  101. // size = availableHeroes.size();
  102. // h & size;
  103. // for(size_t i=0; i < size; i++)
  104. // {
  105. // if(availableHeroes[i])
  106. // {
  107. // h & availableHeroes[i]->subID;
  108. // }
  109. // else
  110. // {
  111. // ui32 none = 0xffffffff;
  112. // h & none;
  113. // }
  114. // }
  115. // }
  116. // else
  117. // {
  118. // ui32 hid;
  119. // h & size;
  120. // for(size_t i=0; i < size; i++)
  121. // {
  122. // //fill availableHeroes with dummy hero instances, holding subids
  123. // h & hid;
  124. // availableHeroes.push_back(new CGHeroInstance);
  125. // availableHeroes[availableHeroes.size()-1]->subID = hid;
  126. // }
  127. // }
  128. }
  129. };
  130. struct DLL_EXPORT CObstacleInstance
  131. {
  132. int uniqueID;
  133. int ID; //ID of obstacle (defines type of it)
  134. int pos; //position on battlefield
  135. template <typename Handler> void serialize(Handler &h, const int version)
  136. {
  137. h & ID & pos & uniqueID;
  138. }
  139. };
  140. //only for use in BattleInfo
  141. struct DLL_EXPORT SiegeInfo
  142. {
  143. 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
  144. template <typename Handler> void serialize(Handler &h, const int version)
  145. {
  146. h & wallState;
  147. }
  148. };
  149. struct DLL_EXPORT BattleInfo
  150. {
  151. ui8 side1, side2; //side1 - attacker, side2 - defender
  152. si32 round, activeStack;
  153. ui8 siege; // = 0 ordinary battle = 1 a siege with a Fort = 2 a siege with a Citadel = 3 a siege with a Castle
  154. si32 tid; //used during town siege - id of attacked town; -1 if not town defence
  155. int3 tile; //for background and bonuses
  156. CGHeroInstance *heroes[2];
  157. CCreatureSet army1, army2;
  158. std::vector<CStack*> stacks;
  159. std::vector<CObstacleInstance> obstacles;
  160. ui8 castSpells[2]; //[0] - attacker, [1] - defender
  161. SiegeInfo si;
  162. template <typename Handler> void serialize(Handler &h, const int version)
  163. {
  164. h & side1 & side2 & round & activeStack & siege & tid & tile & stacks & army1 & army2 & obstacles
  165. & castSpells & si;
  166. h & heroes;
  167. }
  168. const CStack * getNextStack() const; //which stack will have turn after current one
  169. void getStackQueue(std::vector<const CStack *> &out, int howMany, int turn = 0, int lastMoved = -1) const; //returns stack in order of their movement action
  170. CStack * getStack(int stackID, bool onlyAlive = true);
  171. const CStack * getStack(int stackID, bool onlyAlive = true) const;
  172. CStack * getStackT(int tileID, bool onlyAlive = true);
  173. const CStack * getStackT(int tileID, bool onlyAlive = true) const;
  174. 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
  175. static bool isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos); //helper for makeBFS
  176. void makeBFS(int start, bool*accessibility, int *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
  177. 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
  178. std::vector<int> getAccessibility(int stackID, bool addOccupiable) const; //returns vector of accessible tiles (taking into account the creature range)
  179. bool isStackBlocked(int ID); //returns true if there is neighbouring enemy stack
  180. 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)
  181. static std::vector<int> neighbouringTiles(int hex);
  182. 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)
  183. 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>
  184. void calculateCasualties(std::map<ui32,si32> *casualties) const; //casualties are array of maps size 2 (attacker, defeneder), maps are (crid => amount)
  185. std::set<CStack*> getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile); //calculates stack affected by given spell
  186. static int calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster);
  187. 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
  188. ui32 getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const; //returns cost of given spell
  189. int hexToWallPart(int hex) const; //returns part of destructible wall / gate / keep under given hex or -1 if not found
  190. 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)
  191. ui32 calculateSpellDmg(const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const; //calculates damage inflicted by spell
  192. };
  193. class DLL_EXPORT CStack
  194. {
  195. public:
  196. ui32 ID; //unique ID of stack
  197. CCreature * creature;
  198. ui32 amount, baseAmount;
  199. ui32 firstHPleft; //HP of first creature in stack
  200. ui8 owner, slot; //owner - player colour (255 for neutrals), slot - position in garrison (may be 255 for neutrals/called creatures)
  201. ui8 attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
  202. si16 position; //position on battlefield; -2 - keep, -3 - lower tower, -4 - upper tower
  203. ui8 counterAttacks; //how many counter attacks can be performed more in this turn (by default set at the beginning of the round to 1)
  204. si16 shots; //how many shots left
  205. si8 morale, luck; //base stack luck/morale
  206. std::vector<StackFeature> features;
  207. std::set<ECombatInfo> state;
  208. struct StackEffect
  209. {
  210. ui16 id; //spell id
  211. ui8 level; //skill level
  212. ui16 turnsRemain;
  213. template <typename Handler> void serialize(Handler &h, const int version)
  214. {
  215. h & id & level & turnsRemain;
  216. }
  217. };
  218. std::vector<StackEffect> effects;
  219. int valOfFeatures(StackFeature::ECombatFeatures type, int subtype = -1024, int turn = 0) const;//subtype -> subtype of bonus, if -1024 then any
  220. bool hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype = -1024, int turn = 0) const; //determines if stack has a bonus of given type (and optionally subtype)
  221. CStack(CCreature * C, int A, int O, int I, bool AO, int S); //c-tor
  222. CStack() : ID(-1), creature(NULL), amount(-1), baseAmount(-1), firstHPleft(-1), owner(255), slot(255), attackerOwned(true), position(-1), counterAttacks(1) {} //c-tor
  223. const StackEffect * getEffect(ui16 id, int turn = 0) const; //effect id (SP)
  224. ui8 howManyEffectsSet(ui16 id) const; //returns amount of effects with given id set for this stack
  225. bool willMove(int turn = 0) const; //if stack has remaining move this turn
  226. bool moved(int turn = 0) const; //if stack was already moved this turn
  227. bool canMove(int turn = 0) const; //if stack can move
  228. ui32 Speed(int turn = 0) const; //get speed of creature with all modificators
  229. si8 Morale() const; //get morale of stack with all modificators
  230. si8 Luck() const; //get luck of stack with all modificators
  231. si32 Attack() const; //get attack of stack with all modificators
  232. si32 Defense(bool withFrenzy = true) const; //get defense of stack with all modificators
  233. ui16 MaxHealth() const; //get max HP of stack with all modifiers
  234. template <typename Handler> void save(Handler &h, const int version)
  235. {
  236. h & creature->idNumber;
  237. }
  238. template <typename Handler> void load(Handler &h, const int version)
  239. {
  240. ui32 id;
  241. h & id;
  242. creature = &VLC->creh->creatures[id];
  243. //features = creature->abilities;
  244. }
  245. template <typename Handler> void serialize(Handler &h, const int version)
  246. {
  247. h & ID & amount & baseAmount & firstHPleft & owner & slot & attackerOwned & position & state & counterAttacks
  248. & shots & morale & luck & features;
  249. if(h.saving)
  250. save(h,version);
  251. else
  252. load(h,version);
  253. }
  254. bool alive() const //determines if stack is alive
  255. {
  256. return vstd::contains(state,ALIVE);
  257. }
  258. };
  259. class DLL_EXPORT CMP_stack
  260. {
  261. int phase; //rules of which phase will be used
  262. int turn;
  263. public:
  264. bool operator ()(const CStack* a, const CStack* b);
  265. CMP_stack(int Phase = 1, int Turn = 0);
  266. };
  267. struct UpgradeInfo
  268. {
  269. int oldID; //creature to be upgraded
  270. std::vector<int> newID; //possible upgrades
  271. std::vector<std::set<std::pair<int,int> > > cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>
  272. UpgradeInfo(){oldID = -1;};
  273. };
  274. struct CPathNode
  275. {
  276. bool accessible; //true if a hero can be on this node
  277. int dist; //distance from the first node of searching; -1 is infinity
  278. CPathNode * theNodeBefore;
  279. int3 coord; //coordiantes
  280. bool visited;
  281. };
  282. struct CGPathNode
  283. {
  284. enum
  285. {
  286. ACCESSIBLE=1, //tile can be entered and passed
  287. VISITABLE, //tile can be entered as the last tile in path
  288. BLOCKVIS, //visitable from neighbouring tile but not passable
  289. BLOCKED //tile can't be entered nor visited
  290. };
  291. ui8 accessible; //the enum above
  292. ui8 land;
  293. ui8 turns;
  294. ui32 moveRemains;
  295. CGPathNode * theNodeBefore;
  296. int3 coord; //coordinates
  297. CGPathNode();
  298. };
  299. struct DLL_EXPORT CPath
  300. {
  301. std::vector<CPathNode> nodes; //just get node by node
  302. int3 startPos() const; // start point
  303. int3 endPos() const; //destination point
  304. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  305. };
  306. struct DLL_EXPORT CGPath
  307. {
  308. std::vector<CGPathNode> nodes; //just get node by node
  309. int3 startPos() const; // start point
  310. int3 endPos() const; //destination point
  311. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  312. };
  313. struct DLL_EXPORT CPathsInfo
  314. {
  315. const CGHeroInstance *hero;
  316. int3 hpos;
  317. int3 sizes;
  318. CGPathNode ***nodes; //[w][h][level]
  319. bool getPath(const int3 &dst, CGPath &out);
  320. CPathsInfo(const int3 &Sizes);
  321. ~CPathsInfo();
  322. };
  323. class DLL_EXPORT CGameState
  324. {
  325. public:
  326. StartInfo* scenarioOps;
  327. ui32 seed;
  328. ui8 currentPlayer; //ID of player currently having turn
  329. BattleInfo *curB; //current battle
  330. ui32 day; //total number of days in game
  331. Mapa * map;
  332. std::map<ui8, PlayerState> players; //ID <-> player state
  333. std::map<int, CGDefInfo*> villages, forts, capitols; //def-info for town graphics
  334. std::vector<ui32> resVals; //default values of resources in gold
  335. struct DLL_EXPORT HeroesPool
  336. {
  337. std::map<ui32,CGHeroInstance *> heroesPool; //[subID] - heroes available to buy; NULL if not available
  338. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  339. CGHeroInstance * pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const;
  340. template <typename Handler> void serialize(Handler &h, const int version)
  341. {
  342. h & heroesPool & pavailable;
  343. }
  344. } hpool; //we have here all heroes available on this map that are not hired
  345. boost::shared_mutex *mx;
  346. PlayerState *getPlayer(ui8 color);
  347. const PlayerState *getPlayer(ui8 color) const;
  348. void init(StartInfo * si, Mapa * map, int Seed);
  349. void loadTownDInfos();
  350. void randomizeObject(CGObjectInstance *cur);
  351. std::pair<int,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  352. int pickHero(int owner);
  353. void apply(CPack *pack);
  354. CGHeroInstance *getHero(int objid);
  355. CGTownInstance *getTown(int objid);
  356. const CGHeroInstance *getHero(int objid) const;
  357. const CGTownInstance *getTown(int objid) const;
  358. bool battleMoveCreatureStack(int ID, int dest);
  359. bool battleAttackCreatureStack(int ID, int dest);
  360. bool battleShootCreatureStack(int ID, int dest);
  361. bool battleCanFlee(int player); //returns true if player can flee from the battle
  362. int battleGetStack(int pos, bool onlyAlive); //returns ID of stack at given tile
  363. 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
  364. const CGHeroInstance * battleGetOwner(int stackID); //returns hero that owns given stack; NULL if none
  365. 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
  366. bool battleCanShoot(int ID, int dest); //determines if stack with given ID shoot at the selected destination
  367. UpgradeInfo getUpgradeInfo(const CArmedInstance *obj, int stackPos);
  368. float getMarketEfficiency(int player, int mode=0);
  369. std::set<int> getBuildingRequiments(const CGTownInstance *t, int ID);
  370. 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
  371. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  372. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  373. 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
  374. 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
  375. int victoryCheck(ui8 player) const; //checks if given player is winner; -1 if std victory, 1 if special victory, 0 else
  376. int lossCheck(ui8 player) const; //checks if given player is loser; -1 if std loss, 1 if special, 0 else
  377. ui8 checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 if no winner
  378. bool checkForStandardLoss(ui8 player) const; //checks if given player lost the game
  379. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  380. bool isVisible(int3 pos, int player);
  381. bool isVisible(const CGObjectInstance *obj, int player);
  382. CGameState(); //c-tor
  383. ~CGameState(); //d-tor
  384. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand);
  385. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  386. 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
  387. template <typename Handler> void serialize(Handler &h, const int version)
  388. {
  389. h & scenarioOps & seed & currentPlayer & day & map & players & resVals & hpool;
  390. if(!h.saving)
  391. {
  392. loadTownDInfos();
  393. // //recreating towns/heroes vectors in players entries
  394. // for(int i=0; i<map->towns.size(); i++)
  395. // if(map->towns[i]->tempOwner < PLAYER_LIMIT)
  396. // getPlayer(map->towns[i]->tempOwner)->towns.push_back(map->towns[i]);
  397. // for(int i=0; i<map->heroes.size(); i++)
  398. // if(map->heroes[i]->tempOwner < PLAYER_LIMIT)
  399. // getPlayer(map->heroes[i]->tempOwner)->heroes.push_back(map->heroes[i]);
  400. // //recreating available heroes
  401. // for(std::map<ui8,PlayerState>::iterator i=players.begin(); i!=players.end(); i++)
  402. // {
  403. // for(size_t j=0; j < i->second.availableHeroes.size(); j++)
  404. // {
  405. // ui32 hlp = i->second.availableHeroes[j]->subID;
  406. // delete i->second.availableHeroes[j];
  407. // if(hlp != 0xffffffff)
  408. // {
  409. // assert(vstd::contains(hpool.heroesPool, hlp));
  410. // i->second.availableHeroes[j] = hpool.heroesPool[hlp];
  411. // }
  412. // else
  413. // {
  414. // i->second.availableHeroes[j] = NULL;
  415. // }
  416. // }
  417. // }
  418. }
  419. }
  420. friend class CCallback;
  421. friend class CLuaCallback;
  422. friend class CClient;
  423. friend void initGameState(Mapa * map, CGameInfo * cgi);
  424. friend class IGameCallback;
  425. friend class CMapHandler;
  426. friend class CGameHandler;
  427. };
  428. #endif // __CGAMESTATE_H__