CGameState.h 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /*
  2. * CGameState.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include "../bonuses/CBonusSystemNode.h"
  12. #include "../IGameCallback.h"
  13. #include "../LoadProgress.h"
  14. #include "../ConstTransitivePtr.h"
  15. #include "RumorState.h"
  16. #include "GameStatistics.h"
  17. namespace boost
  18. {
  19. class shared_mutex;
  20. }
  21. VCMI_LIB_NAMESPACE_BEGIN
  22. class EVictoryLossCheckResult;
  23. class Services;
  24. class IMapService;
  25. class CMap;
  26. struct CPack;
  27. class CHeroClass;
  28. struct EventCondition;
  29. struct CampaignTravel;
  30. class CStackInstance;
  31. class CGameStateCampaign;
  32. class TavernHeroesPool;
  33. struct SThievesGuildInfo;
  34. class CRandomGenerator;
  35. class GameSettings;
  36. class BattleInfo;
  37. class UpgradeInfo;
  38. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  39. class DLL_LINKAGE CGameState : public CNonConstInfoCallback, public Serializeable
  40. {
  41. friend class CGameStateCampaign;
  42. public:
  43. /// Stores number of times each artifact was placed on map via randomization
  44. std::map<ArtifactID, int> allocatedArtifacts;
  45. /// List of currently ongoing battles
  46. std::vector<std::unique_ptr<BattleInfo>> currentBattles;
  47. /// ID that can be allocated to next battle
  48. BattleID nextBattleID = BattleID(0);
  49. //we have here all heroes available on this map that are not hired
  50. std::unique_ptr<TavernHeroesPool> heroesPool;
  51. /// list of players currently making turn. Usually - just one, except for simturns
  52. std::set<PlayerColor> actingPlayers;
  53. IGameCallback * callback;
  54. CGameState();
  55. virtual ~CGameState();
  56. void preInit(Services * services, IGameCallback * callback);
  57. void init(const IMapService * mapService, StartInfo * si, Load::ProgressAccumulator &, bool allowSavingRandomMap = true);
  58. void updateOnLoad(StartInfo * si);
  59. ConstTransitivePtr<StartInfo> scenarioOps;
  60. ConstTransitivePtr<StartInfo> initialOpts; //copy of settings received from pregame (not randomized)
  61. ui32 day; //total number of days in game
  62. ConstTransitivePtr<CMap> map;
  63. std::map<PlayerColor, PlayerState> players;
  64. std::map<TeamID, TeamState> teams;
  65. CBonusSystemNode globalEffects;
  66. RumorState currentRumor;
  67. StatisticDataSet statistic;
  68. static boost::shared_mutex mutex;
  69. void updateEntity(Metatype metatype, int32_t index, const JsonNode & data) override;
  70. bool giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid);
  71. /// picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  72. HeroTypeID pickNextHeroType(const PlayerColor & owner);
  73. void apply(CPackForClient & pack);
  74. BattleField battleGetBattlefieldType(int3 tile, vstd::RNG & rand);
  75. void fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const override;
  76. PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2) const override;
  77. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  78. void calculatePaths(const CGHeroInstance *hero, CPathsInfo &out) override; //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
  79. void calculatePaths(const std::shared_ptr<PathfinderConfig> & config) override;
  80. int3 guardingCreaturePosition (int3 pos) const override;
  81. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  82. /// Gets a artifact ID randomly and removes the selected artifact from this handler.
  83. ArtifactID pickRandomArtifact(vstd::RNG & rand, int flags);
  84. ArtifactID pickRandomArtifact(vstd::RNG & rand, std::function<bool(ArtifactID)> accepts);
  85. ArtifactID pickRandomArtifact(vstd::RNG & rand, int flags, std::function<bool(ArtifactID)> accepts);
  86. ArtifactID pickRandomArtifact(vstd::RNG & rand, std::set<ArtifactID> filtered);
  87. /// Returns battle in which selected player is engaged, or nullptr if none.
  88. /// Can NOT be used with neutral player, use battle by ID instead
  89. const BattleInfo * getBattle(const PlayerColor & player) const;
  90. /// Returns battle by its unique identifier, or nullptr if not found
  91. const BattleInfo * getBattle(const BattleID & battle) const;
  92. BattleInfo * getBattle(const BattleID & battle);
  93. // ----- victory, loss condition checks -----
  94. EVictoryLossCheckResult checkForVictoryAndLoss(const PlayerColor & player) const;
  95. bool checkForVictory(const PlayerColor & player, const EventCondition & condition) const; //checks if given player is winner
  96. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  97. bool checkForStandardLoss(const PlayerColor & player) const; //checks if given player lost the game
  98. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  99. const IGameSettings & getSettings() const;
  100. bool isVisible(int3 pos, const std::optional<PlayerColor> & player) const override;
  101. bool isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const override;
  102. static int getDate(int day, Date mode);
  103. int getDate(Date mode=Date::DAY) const override; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
  104. // ----- getters, setters -----
  105. /// This RNG should only be used inside GS or CPackForClient-derived applyGs
  106. /// If this doesn't work for your code that mean you need a new netpack
  107. ///
  108. /// Client-side must use vstd::RNG::getDefault which is not serialized
  109. ///
  110. /// CGameHandler have it's own getter for vstd::RNG::getDefault
  111. /// Any server-side code outside of GH must use vstd::RNG::getDefault
  112. vstd::RNG & getRandomGenerator();
  113. template <typename Handler> void serialize(Handler &h)
  114. {
  115. h & scenarioOps;
  116. h & initialOpts;
  117. h & actingPlayers;
  118. h & day;
  119. h & map;
  120. h & players;
  121. if (h.version < Handler::Version::PLAYER_STATE_OWNED_OBJECTS)
  122. generateOwnedObjectsAfterDeserialize();
  123. h & teams;
  124. h & heroesPool;
  125. h & globalEffects;
  126. if (h.version < Handler::Version::REMOVE_LIB_RNG)
  127. {
  128. std::string oldStateOfRNG;
  129. h & oldStateOfRNG;
  130. }
  131. h & currentRumor;
  132. h & campaign;
  133. h & allocatedArtifacts;
  134. if (h.version >= Handler::Version::STATISTICS)
  135. h & statistic;
  136. BONUS_TREE_DESERIALIZATION_FIX
  137. }
  138. private:
  139. // ----- initialization -----
  140. void initNewGame(const IMapService * mapService, bool allowSavingRandomMap, Load::ProgressAccumulator & progressTracking);
  141. void initGlobalBonuses();
  142. void initGrailPosition();
  143. void initRandomFactionsForPlayers();
  144. void initOwnedObjects();
  145. void randomizeMapObjects();
  146. void initPlayerStates();
  147. void placeStartingHeroes();
  148. void placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos);
  149. void removeHeroPlaceholders();
  150. void initDifficulty();
  151. void initHeroes();
  152. void placeHeroesInTowns();
  153. void initFogOfWar();
  154. void initStartingBonus();
  155. void initTowns();
  156. void initTownNames();
  157. void initMapObjects();
  158. void initVisitingAndGarrisonedHeroes();
  159. void initCampaign();
  160. void generateOwnedObjectsAfterDeserialize();
  161. // ----- bonus system handling -----
  162. void buildBonusSystemTree();
  163. void attachArmedObjects();
  164. void buildGlobalTeamPlayerTree();
  165. void deserializationFix();
  166. // ---- misc helpers -----
  167. CGHeroInstance * getUsedHero(const HeroTypeID & hid) const;
  168. bool isUsedHero(const HeroTypeID & hid) const; //looks in heroes and prisons
  169. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  170. HeroTypeID pickUnusedHeroTypeRandomly(const PlayerColor & owner); // picks a unused hero type randomly
  171. UpgradeInfo fillUpgradeInfo(const CStackInstance &stack) const;
  172. // ---- data -----
  173. Services * services;
  174. /// Pointer to campaign state manager. Nullptr for single scenarios
  175. std::unique_ptr<CGameStateCampaign> campaign;
  176. friend class IGameCallback;
  177. friend class CMapHandler;
  178. friend class CGameHandler;
  179. };
  180. VCMI_LIB_NAMESPACE_END