CGameState.h 8.2 KB

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