CGameState.h 8.4 KB

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