CGameState.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #ifndef __CGAMESTATE_H__
  2. #define __CGAMESTATE_H__
  3. #include "../global.h"
  4. #include <cassert>
  5. #ifndef _MSC_VER
  6. #include "CCreatureHandler.h"
  7. #include "VCMI_Lib.h"
  8. #include "map.h"
  9. #endif
  10. #include <set>
  11. #include <vector>
  12. #include <list>
  13. #include "HeroBonus.h"
  14. #include "CCreatureSet.h"
  15. #ifdef _WIN32
  16. #include <tchar.h>
  17. #else
  18. #include "../tchar_amigaos4.h"
  19. #endif
  20. #include "ConstTransitivePtr.h"
  21. #include "IGameCallback.h"
  22. #include "ResourceSet.h"
  23. /*
  24. * CGameState.h, part of VCMI engine
  25. *
  26. * Authors: listed in file AUTHORS in main folder
  27. *
  28. * License: GNU General Public License v2.0 or later
  29. * Full text of license available in license.txt file, in main folder
  30. *
  31. */
  32. class CTown;
  33. class CScriptCallback;
  34. class CCallback;
  35. class IGameCallback;
  36. class CLuaCallback;
  37. class CCPPObjectScript;
  38. class CCreatureSet;
  39. class CStack;
  40. class CGHeroInstance;
  41. class CGTownInstance;
  42. class CArmedInstance;
  43. class CGDwelling;
  44. class CGDefInfo;
  45. class CObjectScript;
  46. class CGObjectInstance;
  47. class CCreature;
  48. struct Mapa;
  49. struct StartInfo;
  50. struct SDL_Surface;
  51. class CMapHandler;
  52. class CPathfinder;
  53. struct SetObjectProperty;
  54. struct MetaString;
  55. struct CPack;
  56. class CSpell;
  57. struct TerrainTile;
  58. class CHeroClass;
  59. class CCampaign;
  60. class CCampaignState;
  61. class IModableArt;
  62. class CGGarrison;
  63. struct MakeAction;
  64. namespace boost
  65. {
  66. class shared_mutex;
  67. }
  68. //numbers of creatures are exact numbers if detailed else they are quantity ids (0 - a few, 1 - several and so on; additionally -1 - unknown)
  69. struct ArmyDescriptor : public std::map<TSlot, CStackBasicDescriptor>
  70. {
  71. bool isDetailed;
  72. DLL_EXPORT ArmyDescriptor(const CArmedInstance *army, bool detailed); //not detailed -> quantity ids as count
  73. DLL_EXPORT ArmyDescriptor();
  74. DLL_EXPORT int getStrength() const;
  75. };
  76. struct DLL_EXPORT InfoAboutHero
  77. {
  78. private:
  79. void assign(const InfoAboutHero & iah);
  80. public:
  81. struct DLL_EXPORT Details
  82. {
  83. std::vector<int> primskills;
  84. int mana, luck, morale;
  85. } *details;
  86. char owner;
  87. const CHeroClass *hclass;
  88. std::string name;
  89. int portrait;
  90. ArmyDescriptor army;
  91. InfoAboutHero();
  92. InfoAboutHero(const InfoAboutHero & iah);
  93. InfoAboutHero & operator=(const InfoAboutHero & iah);
  94. ~InfoAboutHero();
  95. void initFromHero(const CGHeroInstance *h, bool detailed);
  96. };
  97. /// Struct which holds a short information about a town
  98. struct DLL_EXPORT InfoAboutTown
  99. {
  100. struct Details
  101. {
  102. int hallLevel, goldIncome;
  103. bool customRes;
  104. bool garrisonedHero;
  105. } *details;
  106. const CArmedInstance * obj;
  107. char fortLevel; //0 - none
  108. char owner;
  109. std::string name;
  110. CTown *tType;
  111. bool built;
  112. ArmyDescriptor army; //numbers of creatures are valid only if details
  113. InfoAboutTown();
  114. ~InfoAboutTown();
  115. void initFromTown(const CGTownInstance *t, bool detailed);
  116. void initFromGarrison(const CGGarrison *garr, bool detailed);
  117. };
  118. // typedef si32 TResourceUnit;
  119. // typedef std::vector<si32> TResourceVector;
  120. // typedef std::set<si32> TResourceSet;
  121. struct DLL_EXPORT SThievesGuildInfo
  122. {
  123. std::vector<ui8> playerColors; //colors of players that are in-game
  124. std::vector< std::list< ui8 > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  125. std::map<ui8, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  126. std::map<ui8, si8> personality; // color to personality // -1 - human, AI -> (00 - random, 01 - warrior, 02 - builder, 03 - explorer)
  127. std::map<ui8, si32> bestCreature; // color to ID // id or -1 if not known
  128. // template <typename Handler> void serialize(Handler &h, const int version)
  129. // {
  130. // h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income;
  131. // h & colorToBestHero & personality & bestCreature;
  132. // }
  133. };
  134. struct DLL_EXPORT PlayerState : public CBonusSystemNode
  135. {
  136. public:
  137. enum EStatus {INGAME, LOSER, WINNER};
  138. ui8 color;
  139. ui8 human; //true if human controlled player, false for AI
  140. ui32 currentSelection; //id of hero/town, 0xffffffff if none
  141. ui8 team;
  142. TResources resources;
  143. std::vector<ConstTransitivePtr<CGHeroInstance> > heroes;
  144. std::vector<ConstTransitivePtr<CGTownInstance> > towns;
  145. std::vector<ConstTransitivePtr<CGHeroInstance> > availableHeroes; //heroes available in taverns
  146. std::vector<ConstTransitivePtr<CGDwelling> > dwellings; //used for town growth
  147. ui8 enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory
  148. ui8 status; //0 - in game, 1 - loser, 2 - winner <- uses EStatus enum
  149. ui8 daysWithoutCastle;
  150. PlayerState();
  151. std::string nodeName() const OVERRIDE;
  152. //override
  153. //void getParents(TCNodes &out, const CBonusSystemNode *root = NULL) const;
  154. //void getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root = NULL) const;
  155. template <typename Handler> void serialize(Handler &h, const int version)
  156. {
  157. h & color & human & currentSelection & team & resources & status;
  158. h & heroes & towns & availableHeroes & dwellings & getBonusList();
  159. h & status & daysWithoutCastle;
  160. h & enteredLosingCheatCode & enteredWinningCheatCode;
  161. h & static_cast<CBonusSystemNode&>(*this);
  162. }
  163. };
  164. struct DLL_EXPORT TeamState : public CBonusSystemNode
  165. {
  166. public:
  167. ui8 id; //position in gameState::teams
  168. std::set<ui8> players; // members of this team
  169. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  170. TeamState();
  171. template <typename Handler> void serialize(Handler &h, const int version)
  172. {
  173. h & id & players & fogOfWarMap;
  174. h & static_cast<CBonusSystemNode&>(*this);
  175. }
  176. };
  177. struct UpgradeInfo
  178. {
  179. int oldID; //creature to be upgraded
  180. std::vector<int> newID; //possible upgrades
  181. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  182. UpgradeInfo(){oldID = -1;};
  183. };
  184. struct CPathNode
  185. {
  186. bool accessible; //true if a hero can be on this node
  187. int dist; //distance from the first node of searching; -1 is infinity
  188. CPathNode * theNodeBefore;
  189. int3 coord; //coordiantes
  190. bool visited;
  191. };
  192. struct CGPathNode
  193. {
  194. enum EAccessibility
  195. {
  196. ACCESSIBLE=1, //tile can be entered and passed
  197. VISITABLE, //tile can be entered as the last tile in path
  198. BLOCKVIS, //visitable from neighbouring tile but not passable
  199. BLOCKED //tile can't be entered nor visited
  200. };
  201. ui8 accessible; //the enum above
  202. ui8 land;
  203. ui8 turns;
  204. ui32 moveRemains;
  205. CGPathNode * theNodeBefore;
  206. int3 coord; //coordinates
  207. CGPathNode();
  208. };
  209. struct DLL_EXPORT CPath
  210. {
  211. std::vector<CPathNode> nodes; //just get node by node
  212. int3 startPos() const; // start point
  213. int3 endPos() const; //destination point
  214. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  215. };
  216. struct DLL_EXPORT CGPath
  217. {
  218. std::vector<CGPathNode> nodes; //just get node by node
  219. int3 startPos() const; // start point
  220. int3 endPos() const; //destination point
  221. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  222. };
  223. struct DLL_EXPORT CPathsInfo
  224. {
  225. bool isValid;
  226. const CGHeroInstance *hero;
  227. int3 hpos;
  228. int3 sizes;
  229. CGPathNode ***nodes; //[w][h][level]
  230. bool getPath(const int3 &dst, CGPath &out);
  231. CPathsInfo(const int3 &Sizes);
  232. ~CPathsInfo();
  233. };
  234. struct DLL_EXPORT DuelParameters
  235. {
  236. si32 terType, bfieldType;
  237. struct SideSettings
  238. {
  239. struct StackSettings
  240. {
  241. si32 type;
  242. si32 count;
  243. template <typename Handler> void serialize(Handler &h, const int version)
  244. {
  245. h & type & count;
  246. }
  247. StackSettings();
  248. StackSettings(si32 Type, si32 Count);
  249. } stacks[ARMY_SIZE];
  250. si32 heroId; //-1 if none
  251. std::set<si32> spells;
  252. SideSettings();
  253. template <typename Handler> void serialize(Handler &h, const int version)
  254. {
  255. h & stacks & heroId & spells;
  256. }
  257. } sides[2];
  258. static DuelParameters fromJSON(const std::string &fname);
  259. DuelParameters();
  260. template <typename Handler> void serialize(Handler &h, const int version)
  261. {
  262. h & terType & bfieldType & sides;
  263. }
  264. };
  265. class CPathfinder : private CGameInfoCallback
  266. {
  267. public:
  268. bool useSubterraneanGates;
  269. bool allowEmbarkAndDisembark;
  270. CPathsInfo &out;
  271. const CGHeroInstance *hero;
  272. const std::vector<std::vector<std::vector<ui8> > > &FoW;
  273. std::list<CGPathNode*> mq; //BFS queue -> nodes to be checked
  274. int3 curPos;
  275. CGPathNode *cp; //current (source) path node -> we took it from the queue
  276. CGPathNode *dp; //destination node -> it's a neighbour of cp that we consider
  277. const TerrainTile *ct, *dt; //tile info for both nodes
  278. ui8 useEmbarkCost; //0 - usual movement; 1 - embark; 2 - disembark
  279. int destTopVisObjID;
  280. CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero);;
  281. CGPathNode *getNode(const int3 &coord);
  282. void initializeGraph();
  283. CGPathNode::EAccessibility evaluateAccessibility(const TerrainTile *tinfo) const;
  284. void calculatePaths(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
  285. bool canMoveBetween(const int3 &a, const int3 &b) const; //checks only for visitable objects that may make moving between tiles impossible, not other conditions (like tiles itself accessibility)
  286. bool canStepOntoDst() const;
  287. bool goodForLandSeaTransition(); //checks if current move will be between sea<->land. If so, checks it legality (returns false if movement is not possible) and sets useEmbarkCost
  288. };
  289. struct BattleInfo;
  290. class DLL_EXPORT CGameState : public CNonConstInfoCallback
  291. {
  292. public:
  293. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  294. ConstTransitivePtr<CCampaignState> campaign;
  295. ui32 seed;
  296. ui8 currentPlayer; //ID of player currently having turn
  297. ConstTransitivePtr<BattleInfo> curB; //current battle
  298. ui32 day; //total number of days in game
  299. ConstTransitivePtr<Mapa> map;
  300. bmap<ui8, PlayerState> players; //ID <-> player state
  301. bmap<ui8, TeamState> teams; //ID <-> team state
  302. bmap<int, ConstTransitivePtr<CGDefInfo> > villages, forts, capitols; //def-info for town graphics
  303. CBonusSystemNode globalEffects;
  304. bmap<const CGHeroInstance*, const CGObjectInstance*> ongoingVisits;
  305. struct DLL_EXPORT HeroesPool
  306. {
  307. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; NULL if not available
  308. bmap<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  309. CGHeroInstance * pickHeroFor(bool native, int player, const CTown *town, bmap<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass = NULL) const;
  310. template <typename Handler> void serialize(Handler &h, const int version)
  311. {
  312. h & heroesPool & pavailable;
  313. }
  314. } hpool; //we have here all heroes available on this map that are not hired
  315. boost::shared_mutex *mx;
  316. void init(StartInfo * si, ui32 checksum, int Seed);
  317. void loadTownDInfos();
  318. void randomizeObject(CGObjectInstance *cur);
  319. std::pair<int,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  320. int pickHero(int owner);
  321. void apply(CPack *pack);
  322. 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
  323. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  324. int getPlayerRelations(ui8 color1, ui8 color2);// 0 = enemy, 1 = ally, 2 = same player
  325. //float getMarketEfficiency(int player, int mode=0);
  326. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  327. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  328. 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
  329. 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
  330. int3 guardingCreaturePosition (int3 pos) const;
  331. int victoryCheck(ui8 player) const; //checks if given player is winner; -1 if std victory, 1 if special victory, 0 else
  332. int lossCheck(ui8 player) const; //checks if given player is loser; -1 if std loss, 1 if special, 0 else
  333. ui8 checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 if no winner
  334. bool checkForStandardLoss(ui8 player) const; //checks if given player lost the game
  335. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  336. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  337. BattleInfo * setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town);
  338. bool isValidAction(const MakeAction &ma, bool verbose) const;
  339. void buildBonusSystemTree();
  340. void attachArmedObjects();
  341. void buildGlobalTeamPlayerTree();
  342. void deserializationFix();
  343. bool isVisible(int3 pos, int player);
  344. bool isVisible(const CGObjectInstance *obj, int player);
  345. CGameState(); //c-tor
  346. ~CGameState(); //d-tor
  347. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing);
  348. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  349. 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
  350. template <typename Handler> void serialize(Handler &h, const int version)
  351. {
  352. h & scenarioOps & initialOpts & seed & currentPlayer & day & map & players & teams & hpool & globalEffects & campaign;
  353. h & villages & forts & capitols;
  354. if(!h.saving)
  355. {
  356. loadTownDInfos();
  357. }
  358. BONUS_TREE_DESERIALIZATION_FIX
  359. }
  360. friend class CCallback;
  361. friend class CLuaCallback;
  362. friend class CClient;
  363. friend void initGameState(Mapa * map, CGameInfo * cgi);
  364. friend class IGameCallback;
  365. friend class CMapHandler;
  366. friend class CGameHandler;
  367. };
  368. #endif // __CGAMESTATE_H__