CGameState.h 11 KB

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