2
0

CGameState.h 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 "../callback/CNonConstInfoCallback.h"
  13. #include "../callback/GameCallbackHolder.h"
  14. #include "../entities/artifact/EArtifactClass.h"
  15. #include "../LoadProgress.h"
  16. #include "GameStatistics.h"
  17. #include "RumorState.h"
  18. #include "mapObjects/CGObjectInstance.h"
  19. VCMI_LIB_NAMESPACE_BEGIN
  20. class EVictoryLossCheckResult;
  21. class Services;
  22. class IGameRandomizer;
  23. class IMapService;
  24. class CMap;
  25. class CSaveFile;
  26. class CLoadFile;
  27. struct CPackForClient;
  28. class CHeroClass;
  29. struct EventCondition;
  30. struct CampaignTravel;
  31. class CStackInstance;
  32. class CGameStateCampaign;
  33. class TavernHeroesPool;
  34. struct SThievesGuildInfo;
  35. class CRandomGenerator;
  36. class GameSettings;
  37. class BattleInfo;
  38. class UpgradeInfo;
  39. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  40. class DLL_LINKAGE CGameState : public CNonConstInfoCallback, public Serializeable
  41. {
  42. friend class CGameStateCampaign;
  43. std::shared_ptr<StartInfo> initialOpts; //copy of settings received from pregame (not randomized)
  44. std::shared_ptr<StartInfo> scenarioOps;
  45. std::unique_ptr<CMap> map;
  46. void saveCompatibilityRegisterMissingArtifacts();
  47. public:
  48. ArtifactInstanceID saveCompatibilityLastAllocatedArtifactID;
  49. std::vector<std::shared_ptr<CArtifactInstance>> saveCompatibilityUnregisteredArtifacts;
  50. /// List of currently ongoing battles
  51. std::vector<std::unique_ptr<BattleInfo>> currentBattles;
  52. /// ID that can be allocated to next battle
  53. BattleID nextBattleID = BattleID(0);
  54. //we have here all heroes available on this map that are not hired
  55. std::unique_ptr<TavernHeroesPool> heroesPool;
  56. /// list of players currently making turn. Usually - just one, except for simturns
  57. std::set<PlayerColor> actingPlayers;
  58. CGameState();
  59. virtual ~CGameState();
  60. CGameState & gameState() final { return *this; }
  61. const CGameState & gameState() const final { return *this; }
  62. void preInit(Services * services);
  63. void init(const IMapService * mapService, StartInfo * si, IGameRandomizer & gameRandomizer, Load::ProgressAccumulator &, bool allowSavingRandomMap = true);
  64. void updateOnLoad(const StartInfo & si);
  65. ui32 day; //total number of days in game
  66. std::map<PlayerColor, PlayerState> players;
  67. std::map<TeamID, TeamState> teams;
  68. CBonusSystemNode globalEffects;
  69. RumorState currentRumor;
  70. // NOTE: effectively AI mutex, only used by adventure map AI
  71. static std::shared_mutex mutex;
  72. void updateEntity(Metatype metatype, int32_t index, const JsonNode & data) override;
  73. bool giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid);
  74. /// picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  75. HeroTypeID pickNextHeroType(vstd::RNG & randomGenerator, const PlayerColor & owner);
  76. void apply(CPackForClient & pack);
  77. BattleField battleGetBattlefieldType(int3 tile, vstd::RNG & randomGenerator) const;
  78. PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2) const override;
  79. void calculatePaths(const std::shared_ptr<PathfinderConfig> & config) const override;
  80. std::vector<const CGObjectInstance*> guardingCreatures (int3 pos) const;
  81. /// Creates instance of spell scroll artifact with provided spell
  82. CArtifactInstance * createScroll(const SpellID & spellId);
  83. /// Creates instance of requested artifact
  84. /// For combined artifact this method will also create alll required components
  85. /// For scrolls this method will also initialize its spell
  86. CArtifactInstance * createArtifact(const ArtifactID & artId, const SpellID & spellId = SpellID::NONE);
  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. //fills tgi with info about other players that is available at given level of thieves' guild
  99. void obtainPlayersStats(SThievesGuildInfo & tgi, int level) const;
  100. const IGameSettings & getSettings() const override;
  101. StartInfo * getStartInfo()
  102. {
  103. return scenarioOps.get();
  104. }
  105. const StartInfo * getStartInfo() const final
  106. {
  107. return scenarioOps.get();
  108. }
  109. const StartInfo * getInitialStartInfo() const
  110. {
  111. return initialOpts.get();
  112. }
  113. CMap & getMap()
  114. {
  115. return *map;
  116. }
  117. const CMap & getMap() const
  118. {
  119. return *map;
  120. }
  121. bool isVisibleFor(int3 pos, const PlayerColor player) const override;
  122. bool isVisibleFor(const CGObjectInstance * obj, const PlayerColor player) const override;
  123. template<class BoolPredicate>
  124. static bool iteratePositionsUntilTrue(const CGObjectInstance * obj, BoolPredicate && boolPredicate)
  125. {
  126. for(int fy = 0; fy < obj->getHeight(); ++fy)
  127. {
  128. for(int fx = 0; fx < obj->getWidth(); ++fx)
  129. {
  130. int3 pos = obj->anchorPos() + int3(-fx, -fy, 0);
  131. if(boolPredicate(pos))
  132. return true;
  133. }
  134. }
  135. return false;
  136. }
  137. static int getDate(int day, Date mode);
  138. 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
  139. #if SCRIPTING_ENABLED
  140. scripting::Pool * getGlobalContextPool() const override;
  141. #endif
  142. void saveGame(CSaveFile & file) const;
  143. void loadGame(CLoadFile & file);
  144. template <typename Handler> void serialize(Handler &h)
  145. {
  146. h & scenarioOps;
  147. h & initialOpts;
  148. h & actingPlayers;
  149. h & day;
  150. h & map;
  151. if (!h.hasFeature(Handler::Version::NO_RAW_POINTERS_IN_SERIALIZER))
  152. saveCompatibilityRegisterMissingArtifacts();
  153. h & players;
  154. h & teams;
  155. if (h.hasFeature(Handler::Version::NO_RAW_POINTERS_IN_SERIALIZER))
  156. h & *heroesPool;
  157. else
  158. h & heroesPool;
  159. h & globalEffects;
  160. h & currentRumor;
  161. h & campaign;
  162. if (!h.hasFeature(Handler::Version::RANDOMIZATION_REWORK))
  163. {
  164. std::map<ArtifactID, int> allocatedArtifactsUnused;
  165. h & allocatedArtifactsUnused;
  166. }
  167. if (!h.hasFeature(Handler::Version::SERVER_STATISTICS))
  168. {
  169. StatisticDataSet statistic;
  170. h & statistic;
  171. }
  172. if(!h.saving && h.loadingGamestate)
  173. restoreBonusSystemTree();
  174. }
  175. private:
  176. // ----- initialization -----
  177. void initNewGame(const IMapService * mapService, vstd::RNG & randomGenerator, bool allowSavingRandomMap, Load::ProgressAccumulator & progressTracking);
  178. void initGlobalBonuses();
  179. void initGrailPosition(vstd::RNG & randomGenerator);
  180. void initRandomFactionsForPlayers(vstd::RNG & randomGenerator);
  181. void initOwnedObjects();
  182. void randomizeMapObjects(IGameRandomizer & gameRandomizer);
  183. void initPlayerStates();
  184. void placeStartingHeroes(vstd::RNG & randomGenerator);
  185. void placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos);
  186. void removeHeroPlaceholders();
  187. void initDifficulty();
  188. void initHeroes(IGameRandomizer & gameRandomizer);
  189. void placeHeroesInTowns();
  190. void initFogOfWar();
  191. void initStartingBonus(IGameRandomizer & gameRandomizer);
  192. void initTowns(vstd::RNG & randomGenerator);
  193. void initTownNames(vstd::RNG & randomGenerator);
  194. void initMapObjects(IGameRandomizer & gameRandomizer);
  195. void initVisitingAndGarrisonedHeroes();
  196. void initCampaign();
  197. // ----- bonus system handling -----
  198. void buildBonusSystemTree();
  199. void buildGlobalTeamPlayerTree();
  200. void restoreBonusSystemTree();
  201. // ---- misc helpers -----
  202. CGHeroInstance * getUsedHero(const HeroTypeID & hid) const;
  203. bool isUsedHero(const HeroTypeID & hid) const; //looks in heroes and prisons
  204. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  205. HeroTypeID pickUnusedHeroTypeRandomly(vstd::RNG & randomGenerator, const PlayerColor & owner); // picks a unused hero type randomly
  206. // ---- data -----
  207. Services * services;
  208. /// Pointer to campaign state manager. Nullptr for single scenarios
  209. std::unique_ptr<CGameStateCampaign> campaign;
  210. friend class IGameInfoCallback;
  211. friend class CMapHandler;
  212. friend class CGameHandler;
  213. };
  214. VCMI_LIB_NAMESPACE_END