CGameState.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. #pragma once
  2. //#ifndef _MSC_VER
  3. #include "CCreatureHandler.h"
  4. #include "VCMI_Lib.h"
  5. #include "mapping/CMap.h"
  6. //#endif
  7. #include "HeroBonus.h"
  8. #include "CCreatureSet.h"
  9. #include "ConstTransitivePtr.h"
  10. #include "IGameCallback.h"
  11. #include "ResourceSet.h"
  12. #include "int3.h"
  13. #include "CObjectHandler.h"
  14. #include "IGameCallback.h"
  15. /*
  16. * CGameState.h, part of VCMI engine
  17. *
  18. * Authors: listed in file AUTHORS in main folder
  19. *
  20. * License: GNU General Public License v2.0 or later
  21. * Full text of license available in license.txt file, in main folder
  22. *
  23. */
  24. class CTown;
  25. class CScriptCallback;
  26. class CCallback;
  27. class IGameCallback;
  28. class CLuaCallback;
  29. class CCPPObjectScript;
  30. class CCreatureSet;
  31. class CStack;
  32. class CQuest;
  33. class CGHeroInstance;
  34. class CGTownInstance;
  35. class CArmedInstance;
  36. class CGDwelling;
  37. class CObjectScript;
  38. class CGObjectInstance;
  39. class CCreature;
  40. class CMap;
  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. class CHeroClass;
  51. class CCampaign;
  52. class CCampaignState;
  53. class IModableArt;
  54. class CGGarrison;
  55. class CGameInfo;
  56. struct QuestInfo;
  57. class CQuest;
  58. namespace boost
  59. {
  60. class shared_mutex;
  61. }
  62. //numbers of creatures are exact numbers if detailed else they are quantity ids (0 - a few, 1 - several and so on; additionally -1 - unknown)
  63. struct ArmyDescriptor : public std::map<SlotID, CStackBasicDescriptor>
  64. {
  65. bool isDetailed;
  66. DLL_LINKAGE ArmyDescriptor(const CArmedInstance *army, bool detailed); //not detailed -> quantity ids as count
  67. DLL_LINKAGE ArmyDescriptor();
  68. DLL_LINKAGE int getStrength() const;
  69. };
  70. struct DLL_LINKAGE InfoAboutArmy
  71. {
  72. PlayerColor owner;
  73. std::string name;
  74. ArmyDescriptor army;
  75. InfoAboutArmy();
  76. InfoAboutArmy(const CArmedInstance *Army, bool detailed);
  77. void initFromArmy(const CArmedInstance *Army, bool detailed);
  78. };
  79. struct DLL_LINKAGE InfoAboutHero : public InfoAboutArmy
  80. {
  81. private:
  82. void assign(const InfoAboutHero & iah);
  83. public:
  84. struct DLL_LINKAGE Details
  85. {
  86. std::vector<si32> primskills;
  87. si32 mana, luck, morale;
  88. } *details;
  89. const CHeroClass *hclass;
  90. int portrait;
  91. InfoAboutHero();
  92. InfoAboutHero(const InfoAboutHero & iah);
  93. InfoAboutHero(const CGHeroInstance *h, bool detailed);
  94. ~InfoAboutHero();
  95. InfoAboutHero & operator=(const InfoAboutHero & iah);
  96. void initFromHero(const CGHeroInstance *h, bool detailed);
  97. };
  98. /// Struct which holds a int information about a town
  99. struct DLL_LINKAGE InfoAboutTown : public InfoAboutArmy
  100. {
  101. struct DLL_LINKAGE Details
  102. {
  103. si32 hallLevel, goldIncome;
  104. bool customRes;
  105. bool garrisonedHero;
  106. } *details;
  107. CTown *tType;
  108. si32 built;
  109. si32 fortLevel; //0 - none
  110. InfoAboutTown();
  111. InfoAboutTown(const CGTownInstance *t, bool detailed);
  112. ~InfoAboutTown();
  113. void initFromTown(const CGTownInstance *t, bool detailed);
  114. };
  115. // typedef si32 TResourceUnit;
  116. // typedef std::vector<si32> TResourceVector;
  117. // typedef std::set<si32> TResourceSet;
  118. struct DLL_LINKAGE SThievesGuildInfo
  119. {
  120. std::vector<PlayerColor> playerColors; //colors of players that are in-game
  121. std::vector< std::vector< PlayerColor > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  122. std::map<PlayerColor, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  123. std::map<PlayerColor, EAiTactic::EAiTactic> personality; // color to personality // ai tactic
  124. std::map<PlayerColor, si32> bestCreature; // color to ID // id or -1 if not known
  125. // template <typename Handler> void serialize(Handler &h, const int version)
  126. // {
  127. // h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income;
  128. // h & colorToBestHero & personality & bestCreature;
  129. // }
  130. };
  131. struct DLL_LINKAGE PlayerState : public CBonusSystemNode
  132. {
  133. public:
  134. PlayerColor color;
  135. bool human; //true if human controlled player, false for AI
  136. ObjectInstanceID currentSelection; //id of hero/town, 0xffffffff if none
  137. TeamID team;
  138. TResources resources;
  139. std::vector<ConstTransitivePtr<CGHeroInstance> > heroes;
  140. std::vector<ConstTransitivePtr<CGTownInstance> > towns;
  141. std::vector<ConstTransitivePtr<CGHeroInstance> > availableHeroes; //heroes available in taverns
  142. std::vector<ConstTransitivePtr<CGDwelling> > dwellings; //used for town growth
  143. std::vector<QuestInfo> quests; //store info about all received quests
  144. bool enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory
  145. EPlayerStatus::EStatus status;
  146. ui8 daysWithoutCastle;
  147. PlayerState();
  148. std::string nodeName() const override;
  149. template <typename Handler> void serialize(Handler &h, const int version)
  150. {
  151. h & color & human & currentSelection & team & resources & status;
  152. h & heroes & towns & availableHeroes & dwellings;
  153. h & getBonusList(); //FIXME FIXME FIXME
  154. h & status & daysWithoutCastle;
  155. h & enteredLosingCheatCode & enteredWinningCheatCode;
  156. h & static_cast<CBonusSystemNode&>(*this);
  157. }
  158. };
  159. struct DLL_LINKAGE TeamState : public CBonusSystemNode
  160. {
  161. public:
  162. TeamID id; //position in gameState::teams
  163. std::set<PlayerColor> players; // members of this team
  164. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  165. TeamState();
  166. template <typename Handler> void serialize(Handler &h, const int version)
  167. {
  168. h & id & players & fogOfWarMap;
  169. h & static_cast<CBonusSystemNode&>(*this);
  170. }
  171. };
  172. struct UpgradeInfo
  173. {
  174. CreatureID oldID; //creature to be upgraded
  175. std::vector<CreatureID> newID; //possible upgrades
  176. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  177. UpgradeInfo(){oldID = CreatureID::NONE;};
  178. };
  179. struct DLL_LINKAGE CGPathNode
  180. {
  181. enum EAccessibility
  182. {
  183. NOT_SET = 0,
  184. ACCESSIBLE = 1, //tile can be entered and passed
  185. VISITABLE, //tile can be entered as the last tile in path
  186. BLOCKVIS, //visitable from neighbouring tile but not passable
  187. BLOCKED //tile can't be entered nor visited
  188. };
  189. EAccessibility accessible;
  190. ui8 land;
  191. ui8 turns;
  192. ui32 moveRemains;
  193. CGPathNode * theNodeBefore;
  194. int3 coord; //coordinates
  195. CGPathNode();
  196. bool reachable() const;
  197. };
  198. struct DLL_LINKAGE CGPath
  199. {
  200. std::vector<CGPathNode> nodes; //just get node by node
  201. int3 startPos() const; // start point
  202. int3 endPos() const; //destination point
  203. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  204. };
  205. struct DLL_LINKAGE CPathsInfo
  206. {
  207. bool isValid;
  208. const CGHeroInstance *hero;
  209. int3 hpos;
  210. int3 sizes;
  211. CGPathNode ***nodes; //[w][h][level]
  212. bool getPath(const int3 &dst, CGPath &out);
  213. CPathsInfo(const int3 &Sizes);
  214. ~CPathsInfo();
  215. };
  216. struct DLL_EXPORT DuelParameters
  217. {
  218. ETerrainType terType;
  219. BFieldType bfieldType;
  220. struct DLL_EXPORT SideSettings
  221. {
  222. struct DLL_EXPORT StackSettings
  223. {
  224. CreatureID type;
  225. si32 count;
  226. template <typename Handler> void serialize(Handler &h, const int version)
  227. {
  228. h & type & count;
  229. }
  230. StackSettings();
  231. StackSettings(CreatureID Type, si32 Count);
  232. } stacks[GameConstants::ARMY_SIZE];
  233. si32 heroId; //-1 if none
  234. std::vector<si32> heroPrimSkills; //may be empty
  235. std::map<si32, CArtifactInstance*> artifacts;
  236. std::vector<std::pair<si32, si8> > heroSecSkills; //may be empty; pairs <id, level>, level [0-3]
  237. std::set<SpellID> spells;
  238. SideSettings();
  239. template <typename Handler> void serialize(Handler &h, const int version)
  240. {
  241. h & stacks & heroId & heroPrimSkills & artifacts & heroSecSkills & spells;
  242. }
  243. } sides[2];
  244. std::vector<shared_ptr<CObstacleInstance> > obstacles;
  245. static DuelParameters fromJSON(const std::string &fname);
  246. struct CusomCreature
  247. {
  248. int id;
  249. int attack, defense, dmg, HP, speed, shoots;
  250. CusomCreature()
  251. {
  252. id = attack = defense = dmg = HP = speed = shoots = -1;
  253. }
  254. template <typename Handler> void serialize(Handler &h, const int version)
  255. {
  256. h & id & attack & defense & dmg & HP & speed & shoots;
  257. }
  258. };
  259. std::vector<CusomCreature> creatures;
  260. DuelParameters();
  261. template <typename Handler> void serialize(Handler &h, const int version)
  262. {
  263. h & terType & bfieldType & sides & obstacles & creatures;
  264. }
  265. };
  266. class CPathfinder : private CGameInfoCallback
  267. {
  268. private:
  269. bool useSubterraneanGates;
  270. bool allowEmbarkAndDisembark;
  271. CPathsInfo &out;
  272. const CGHeroInstance *hero;
  273. const std::vector<std::vector<std::vector<ui8> > > &FoW;
  274. std::list<CGPathNode*> mq; //BFS queue -> nodes to be checked
  275. int3 curPos;
  276. CGPathNode *cp; //current (source) path node -> we took it from the queue
  277. CGPathNode *dp; //destination node -> it's a neighbour of cp that we consider
  278. const TerrainTile *ct, *dt; //tile info for both nodes
  279. ui8 useEmbarkCost; //0 - usual movement; 1 - embark; 2 - disembark
  280. int destTopVisObjID;
  281. CGPathNode *getNode(const int3 &coord);
  282. void initializeGraph();
  283. 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
  284. CGPathNode::EAccessibility evaluateAccessibility(const TerrainTile *tinfo) const;
  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. public:
  287. CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero);
  288. 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 nullptr if path does not exists
  289. };
  290. struct BattleInfo;
  291. class DLL_LINKAGE CGameState : public CNonConstInfoCallback
  292. {
  293. public:
  294. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  295. PlayerColor currentPlayer; //ID of player currently having turn
  296. ConstTransitivePtr<BattleInfo> curB; //current battle
  297. ui32 day; //total number of days in game
  298. ConstTransitivePtr<CMap> map;
  299. bmap<PlayerColor, PlayerState> players;
  300. bmap<TeamID, TeamState> teams;
  301. CBonusSystemNode globalEffects;
  302. struct DLL_LINKAGE HeroesPool
  303. {
  304. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; nullptr if not available
  305. bmap<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  306. CGHeroInstance * pickHeroFor(bool native, PlayerColor player, const CTown *town, bmap<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass = nullptr) const;
  307. template <typename Handler> void serialize(Handler &h, const int version)
  308. {
  309. h & heroesPool & pavailable;
  310. }
  311. } hpool; //we have here all heroes available on this map that are not hired
  312. boost::shared_mutex *mx;
  313. void init(StartInfo * si);
  314. bool isUsedHero(HeroTypeID hid) const; //looks in heroes and prisons
  315. void placeCampaignHeroes(const std::vector<std::pair<CGHeroInstance*, ObjectInstanceID> > &campHeroReplacements);
  316. std::vector<std::pair<CGHeroInstance*, ObjectInstanceID> > campaignHeroesToReplace(); //returns heroes and placeholders in where heroes will be put; may remove some placeholders
  317. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  318. void initDuel();
  319. void randomizeObject(CGObjectInstance *cur);
  320. std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  321. int pickHero(PlayerColor owner);
  322. void giveHeroArtifact(CGHeroInstance *h, ArtifactID aid);
  323. void apply(CPack *pack);
  324. BFieldType battleGetBattlefieldType(int3 tile) const;
  325. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  326. PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2);
  327. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  328. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  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 nullptr if path does not exists
  330. int3 guardingCreaturePosition (int3 pos) const;
  331. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  332. int victoryCheck(PlayerColor player) const; //checks if given player is winner; -1 if std victory, 1 if special victory, 0 else
  333. int lossCheck(PlayerColor player) const; //checks if given player is loser; -1 if std loss, 1 if special, 0 else
  334. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  335. bool checkForStandardLoss(PlayerColor player) const; //checks if given player lost the game
  336. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  337. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  338. BattleInfo * setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town);
  339. void buildBonusSystemTree();
  340. void attachArmedObjects();
  341. void buildGlobalTeamPlayerTree();
  342. void deserializationFix();
  343. bool isVisible(int3 pos, PlayerColor player);
  344. bool isVisible(const CGObjectInstance *obj, boost::optional<PlayerColor> player);
  345. CGameState(); //c-tor
  346. virtual ~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(Date::EDateType mode=Date::DAY) 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 & currentPlayer & day & map & players & teams & hpool & globalEffects;
  353. BONUS_TREE_DESERIALIZATION_FIX
  354. }
  355. friend class CCallback;
  356. friend class CLuaCallback;
  357. friend class CClient;
  358. friend void initGameState(CMap * map, CGameInfo * cgi);
  359. friend class IGameCallback;
  360. friend class CMapHandler;
  361. friend class CGameHandler;
  362. };
  363. struct DLL_LINKAGE QuestInfo //universal interface for human and AI
  364. {
  365. const CQuest * quest;
  366. const CGObjectInstance * obj; //related object, most likely Seer Hut
  367. int3 tile;
  368. QuestInfo(){};
  369. QuestInfo (const CQuest * Quest, const CGObjectInstance * Obj, int3 Tile) :
  370. quest (Quest), obj (Obj), tile (Tile){};
  371. bool operator= (const QuestInfo &qi)
  372. {
  373. quest = qi.quest;
  374. obj = qi.obj;
  375. tile = qi.tile;
  376. return true;
  377. }
  378. bool operator== (const QuestInfo & qi) const
  379. {
  380. return (quest == qi.quest && obj == qi.obj);
  381. }
  382. //std::vector<std::string> > texts //allow additional info for quest log?
  383. template <typename Handler> void serialize(Handler &h, const int version)
  384. {
  385. h & quest & obj & tile;
  386. }
  387. };