CGameState.h 17 KB

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