CGameState.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 "CCreatureHandler.h"
  12. #include "VCMI_Lib.h"
  13. #include "HeroBonus.h"
  14. #include "CCreatureSet.h"
  15. #include "ConstTransitivePtr.h"
  16. #include "IGameCallback.h"
  17. #include "ResourceSet.h"
  18. #include "int3.h"
  19. #include "CRandomGenerator.h"
  20. #include "CGameStateFwd.h"
  21. #include "CPathfinder.h"
  22. namespace boost
  23. {
  24. class shared_mutex;
  25. }
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. class CTown;
  28. class IGameCallback;
  29. class CCreatureSet;
  30. class CQuest;
  31. class CGHeroInstance;
  32. class CGTownInstance;
  33. class CArmedInstance;
  34. class CGDwelling;
  35. class CObjectScript;
  36. class CGObjectInstance;
  37. class CCreature;
  38. class CMap;
  39. struct StartInfo;
  40. struct SetObjectProperty;
  41. struct MetaString;
  42. struct CPack;
  43. class CSpell;
  44. struct TerrainTile;
  45. class CHeroClass;
  46. class CCampaign;
  47. class CCampaignState;
  48. class IModableArt;
  49. class CGGarrison;
  50. struct QuestInfo;
  51. class CQuest;
  52. class CCampaignScenario;
  53. struct EventCondition;
  54. class CScenarioTravel;
  55. class IMapService;
  56. template<typename T> class CApplier;
  57. class CBaseForGSApply;
  58. struct DLL_LINKAGE SThievesGuildInfo
  59. {
  60. std::vector<PlayerColor> playerColors; //colors of players that are in-game
  61. std::vector< std::vector< PlayerColor > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  62. std::map<PlayerColor, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  63. std::map<PlayerColor, EAiTactic::EAiTactic> personality; // color to personality // ai tactic
  64. std::map<PlayerColor, si32> bestCreature; // color to ID // id or -1 if not known
  65. // template <typename Handler> void serialize(Handler &h, const int version)
  66. // {
  67. // h & playerColors;
  68. // h & numOfTowns;
  69. // h & numOfHeroes;
  70. // h & gold;
  71. // h & woodOre;
  72. // h & mercSulfCrystGems;
  73. // h & obelisks;
  74. // h & artifacts;
  75. // h & army;
  76. // h & income;
  77. // h & colorToBestHero;
  78. // h & personality;
  79. // h & bestCreature;
  80. // }
  81. };
  82. struct DLL_LINKAGE RumorState
  83. {
  84. enum ERumorType : ui8
  85. {
  86. TYPE_NONE = 0, TYPE_RAND, TYPE_SPECIAL, TYPE_MAP
  87. };
  88. enum ERumorTypeSpecial : ui8
  89. {
  90. RUMOR_OBELISKS = 208,
  91. RUMOR_ARTIFACTS = 209,
  92. RUMOR_ARMY = 210,
  93. RUMOR_INCOME = 211,
  94. RUMOR_GRAIL = 212
  95. };
  96. ERumorType type;
  97. std::map<ERumorType, std::pair<int, int>> last;
  98. RumorState(){type = TYPE_NONE;};
  99. bool update(int id, int extra);
  100. template <typename Handler> void serialize(Handler &h, const int version)
  101. {
  102. h & type;
  103. h & last;
  104. }
  105. };
  106. struct UpgradeInfo
  107. {
  108. CreatureID oldID; //creature to be upgraded
  109. std::vector<CreatureID> newID; //possible upgrades
  110. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  111. UpgradeInfo(){oldID = CreatureID::NONE;};
  112. };
  113. class BattleInfo;
  114. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  115. class DLL_LINKAGE CGameState : public CNonConstInfoCallback
  116. {
  117. public:
  118. struct DLL_LINKAGE HeroesPool
  119. {
  120. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; nullptr if not available
  121. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  122. CGHeroInstance * pickHeroFor(bool native, PlayerColor player, const CTown *town,
  123. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, CRandomGenerator & rand, const CHeroClass *bannedClass = nullptr) const;
  124. template <typename Handler> void serialize(Handler &h, const int version)
  125. {
  126. h & heroesPool;
  127. h & pavailable;
  128. }
  129. } hpool; //we have here all heroes available on this map that are not hired
  130. CGameState();
  131. virtual ~CGameState();
  132. void preInit(Services * services);
  133. void init(const IMapService * mapService, StartInfo * si, bool allowSavingRandomMap = false);
  134. void updateOnLoad(StartInfo * si);
  135. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  136. PlayerColor currentPlayer; //ID of player currently having turn
  137. ConstTransitivePtr<BattleInfo> curB; //current battle
  138. ui32 day; //total number of days in game
  139. ConstTransitivePtr<CMap> map;
  140. std::map<PlayerColor, PlayerState> players;
  141. std::map<TeamID, TeamState> teams;
  142. CBonusSystemNode globalEffects;
  143. RumorState rumor;
  144. static boost::shared_mutex mutex;
  145. void updateEntity(Metatype metatype, int32_t index, const JsonNode & data) override;
  146. void giveHeroArtifact(CGHeroInstance *h, ArtifactID aid);
  147. void apply(CPack *pack);
  148. BattleField battleGetBattlefieldType(int3 tile, CRandomGenerator & rand);
  149. void getUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const override;
  150. PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2) const override;
  151. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  152. 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
  153. void calculatePaths(std::shared_ptr<PathfinderConfig> config) override;
  154. int3 guardingCreaturePosition (int3 pos) const override;
  155. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  156. void updateRumor();
  157. // ----- victory, loss condition checks -----
  158. EVictoryLossCheckResult checkForVictoryAndLoss(PlayerColor player) const;
  159. bool checkForVictory(PlayerColor player, const EventCondition & condition) const; //checks if given player is winner
  160. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  161. bool checkForStandardLoss(PlayerColor player) const; //checks if given player lost the game
  162. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  163. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  164. bool isVisible(int3 pos, boost::optional<PlayerColor> player) const override;
  165. bool isVisible(const CGObjectInstance *obj, boost::optional<PlayerColor> player) const override;
  166. int getDate(Date::EDateType mode=Date::DAY) const override; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
  167. // ----- getters, setters -----
  168. /// This RNG should only be used inside GS or CPackForClient-derived applyGs
  169. /// If this doesn't work for your code that mean you need a new netpack
  170. ///
  171. /// Client-side must use CRandomGenerator::getDefault which is not serialized
  172. ///
  173. /// CGameHandler have it's own getter for CRandomGenerator::getDefault
  174. /// Any server-side code outside of GH must use CRandomGenerator::getDefault
  175. CRandomGenerator & getRandomGenerator();
  176. template <typename Handler> void serialize(Handler &h, const int version)
  177. {
  178. h & scenarioOps;
  179. h & initialOpts;
  180. h & currentPlayer;
  181. h & day;
  182. h & map;
  183. h & players;
  184. h & teams;
  185. h & hpool;
  186. h & globalEffects;
  187. h & rand;
  188. h & rumor;
  189. BONUS_TREE_DESERIALIZATION_FIX
  190. }
  191. private:
  192. struct CrossoverHeroesList
  193. {
  194. std::vector<CGHeroInstance *> heroesFromPreviousScenario, heroesFromAnyPreviousScenarios;
  195. void addHeroToBothLists(CGHeroInstance * hero);
  196. void removeHeroFromBothLists(CGHeroInstance * hero);
  197. };
  198. struct CampaignHeroReplacement
  199. {
  200. CampaignHeroReplacement(CGHeroInstance * hero, ObjectInstanceID heroPlaceholderId);
  201. CGHeroInstance * hero;
  202. ObjectInstanceID heroPlaceholderId;
  203. };
  204. // ----- initialization -----
  205. void preInitAuto();
  206. void initNewGame(const IMapService * mapService, bool allowSavingRandomMap);
  207. void initCampaign();
  208. void checkMapChecksum();
  209. void initGrailPosition();
  210. void initRandomFactionsForPlayers();
  211. void randomizeMapObjects();
  212. void randomizeObject(CGObjectInstance *cur);
  213. void initPlayerStates();
  214. void placeCampaignHeroes();
  215. CrossoverHeroesList getCrossoverHeroesFromPreviousScenarios() const;
  216. /// returns heroes and placeholders in where heroes will be put
  217. std::vector<CampaignHeroReplacement> generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes);
  218. /// gets prepared and copied hero instances with crossover heroes from prev. scenario and travel options from current scenario
  219. void prepareCrossoverHeroes(std::vector<CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions);
  220. void replaceHeroesPlaceholders(const std::vector<CampaignHeroReplacement> & campaignHeroReplacements);
  221. void placeStartingHeroes();
  222. void placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos);
  223. void initStartingResources();
  224. void initHeroes();
  225. void placeHeroesInTowns();
  226. void giveCampaignBonusToHero(CGHeroInstance * hero);
  227. void initFogOfWar();
  228. void initStartingBonus();
  229. void initTowns();
  230. void initMapObjects();
  231. void initVisitingAndGarrisonedHeroes();
  232. // ----- bonus system handling -----
  233. void buildBonusSystemTree();
  234. void attachArmedObjects();
  235. void buildGlobalTeamPlayerTree();
  236. void deserializationFix();
  237. // ---- misc helpers -----
  238. CGHeroInstance * getUsedHero(HeroTypeID hid) const;
  239. bool isUsedHero(HeroTypeID hid) const; //looks in heroes and prisons
  240. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  241. std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  242. int pickUnusedHeroTypeRandomly(PlayerColor owner); // picks a unused hero type randomly
  243. int pickNextHeroType(PlayerColor owner); // picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  244. UpgradeInfo getUpgradeInfo(const CStackInstance &stack) const;
  245. // ---- data -----
  246. std::shared_ptr<CApplier<CBaseForGSApply>> applier;
  247. CRandomGenerator rand;
  248. Services * services;
  249. friend class CCallback;
  250. friend class CClient;
  251. friend class IGameCallback;
  252. friend class CMapHandler;
  253. friend class CGameHandler;
  254. };
  255. VCMI_LIB_NAMESPACE_END