CGameState.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. class CTown;
  23. class CCallback;
  24. class IGameCallback;
  25. class CCreatureSet;
  26. class CQuest;
  27. class CGHeroInstance;
  28. class CGTownInstance;
  29. class CArmedInstance;
  30. class CGDwelling;
  31. class CObjectScript;
  32. class CGObjectInstance;
  33. class CCreature;
  34. class CMap;
  35. struct StartInfo;
  36. class CMapHandler;
  37. struct SetObjectProperty;
  38. struct MetaString;
  39. struct CPack;
  40. class CSpell;
  41. struct TerrainTile;
  42. class CHeroClass;
  43. class CCampaign;
  44. class CCampaignState;
  45. class IModableArt;
  46. class CGGarrison;
  47. class CGameInfo;
  48. struct QuestInfo;
  49. class CQuest;
  50. class CCampaignScenario;
  51. struct EventCondition;
  52. class CScenarioTravel;
  53. class IMapService;
  54. namespace boost
  55. {
  56. class shared_mutex;
  57. }
  58. template<typename T> class CApplier;
  59. class CBaseForGSApply;
  60. struct DLL_LINKAGE SThievesGuildInfo
  61. {
  62. std::vector<PlayerColor> playerColors; //colors of players that are in-game
  63. std::vector< std::vector< PlayerColor > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  64. std::map<PlayerColor, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  65. std::map<PlayerColor, EAiTactic::EAiTactic> personality; // color to personality // ai tactic
  66. std::map<PlayerColor, si32> bestCreature; // color to ID // id or -1 if not known
  67. // template <typename Handler> void serialize(Handler &h, const int version)
  68. // {
  69. // h & playerColors;
  70. // h & numOfTowns;
  71. // h & numOfHeroes;
  72. // h & gold;
  73. // h & woodOre;
  74. // h & mercSulfCrystGems;
  75. // h & obelisks;
  76. // h & artifacts;
  77. // h & army;
  78. // h & income;
  79. // h & colorToBestHero;
  80. // h & personality;
  81. // h & bestCreature;
  82. // }
  83. };
  84. struct DLL_LINKAGE RumorState
  85. {
  86. enum ERumorType : ui8
  87. {
  88. TYPE_NONE = 0, TYPE_RAND, TYPE_SPECIAL, TYPE_MAP
  89. };
  90. enum ERumorTypeSpecial : ui8
  91. {
  92. RUMOR_OBELISKS = 208,
  93. RUMOR_ARTIFACTS = 209,
  94. RUMOR_ARMY = 210,
  95. RUMOR_INCOME = 211,
  96. RUMOR_GRAIL = 212
  97. };
  98. ERumorType type;
  99. std::map<ERumorType, std::pair<int, int>> last;
  100. RumorState(){type = TYPE_NONE;};
  101. bool update(int id, int extra);
  102. template <typename Handler> void serialize(Handler &h, const int version)
  103. {
  104. h & type;
  105. h & last;
  106. }
  107. };
  108. struct UpgradeInfo
  109. {
  110. CreatureID oldID; //creature to be upgraded
  111. std::vector<CreatureID> newID; //possible upgrades
  112. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  113. UpgradeInfo(){oldID = CreatureID::NONE;};
  114. };
  115. class BattleInfo;
  116. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  117. class DLL_LINKAGE CGameState : public CNonConstInfoCallback
  118. {
  119. public:
  120. struct DLL_LINKAGE HeroesPool
  121. {
  122. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; nullptr if not available
  123. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  124. CGHeroInstance * pickHeroFor(bool native, PlayerColor player, const CTown *town,
  125. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, CRandomGenerator & rand, const CHeroClass *bannedClass = nullptr) const;
  126. template <typename Handler> void serialize(Handler &h, const int version)
  127. {
  128. h & heroesPool;
  129. h & pavailable;
  130. }
  131. } hpool; //we have here all heroes available on this map that are not hired
  132. CGameState();
  133. virtual ~CGameState();
  134. void init(const IMapService * mapService, StartInfo * si, bool allowSavingRandomMap = false);
  135. void updateOnLoad(StartInfo * si);
  136. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  137. PlayerColor currentPlayer; //ID of player currently having turn
  138. ConstTransitivePtr<BattleInfo> curB; //current battle
  139. ui32 day; //total number of days in game
  140. ConstTransitivePtr<CMap> map;
  141. std::map<PlayerColor, PlayerState> players;
  142. std::map<TeamID, TeamState> teams;
  143. CBonusSystemNode globalEffects;
  144. RumorState rumor;
  145. static boost::shared_mutex mutex;
  146. void giveHeroArtifact(CGHeroInstance *h, ArtifactID aid);
  147. void apply(CPack *pack);
  148. BFieldType battleGetBattlefieldType(int3 tile, CRandomGenerator & rand);
  149. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  150. PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2);
  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); //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<CPathfinderConfig> config, const CGHeroInstance * hero);
  154. int3 guardingCreaturePosition (int3 pos) const;
  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, PlayerColor player);
  165. bool isVisible(const CGObjectInstance *obj, boost::optional<PlayerColor> player);
  166. int getDate(Date::EDateType mode=Date::DAY) const; //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. if(version >= 755) //save format backward compatibility
  189. {
  190. h & rumor;
  191. }
  192. else if(!h.saving)
  193. {
  194. rumor = RumorState();
  195. }
  196. BONUS_TREE_DESERIALIZATION_FIX
  197. }
  198. private:
  199. struct CrossoverHeroesList
  200. {
  201. std::vector<CGHeroInstance *> heroesFromPreviousScenario, heroesFromAnyPreviousScenarios;
  202. void addHeroToBothLists(CGHeroInstance * hero);
  203. void removeHeroFromBothLists(CGHeroInstance * hero);
  204. };
  205. struct CampaignHeroReplacement
  206. {
  207. CampaignHeroReplacement(CGHeroInstance * hero, ObjectInstanceID heroPlaceholderId);
  208. CGHeroInstance * hero;
  209. ObjectInstanceID heroPlaceholderId;
  210. };
  211. // ----- initialization -----
  212. void initNewGame(const IMapService * mapService, bool allowSavingRandomMap);
  213. void initCampaign();
  214. void checkMapChecksum();
  215. void initGrailPosition();
  216. void initRandomFactionsForPlayers();
  217. void randomizeMapObjects();
  218. void randomizeObject(CGObjectInstance *cur);
  219. void initPlayerStates();
  220. void placeCampaignHeroes();
  221. CrossoverHeroesList getCrossoverHeroesFromPreviousScenarios() const;
  222. /// returns heroes and placeholders in where heroes will be put
  223. std::vector<CampaignHeroReplacement> generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes);
  224. /// gets prepared and copied hero instances with crossover heroes from prev. scenario and travel options from current scenario
  225. void prepareCrossoverHeroes(std::vector<CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions);
  226. void replaceHeroesPlaceholders(const std::vector<CampaignHeroReplacement> & campaignHeroReplacements);
  227. void placeStartingHeroes();
  228. void placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos);
  229. void initStartingResources();
  230. void initHeroes();
  231. void giveCampaignBonusToHero(CGHeroInstance * hero);
  232. void initFogOfWar();
  233. void initStartingBonus();
  234. void initTowns();
  235. void initMapObjects();
  236. void initVisitingAndGarrisonedHeroes();
  237. // ----- bonus system handling -----
  238. void buildBonusSystemTree();
  239. void attachArmedObjects();
  240. void buildGlobalTeamPlayerTree();
  241. void deserializationFix();
  242. // ---- misc helpers -----
  243. CGHeroInstance * getUsedHero(HeroTypeID hid) const;
  244. bool isUsedHero(HeroTypeID hid) const; //looks in heroes and prisons
  245. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  246. std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  247. int pickUnusedHeroTypeRandomly(PlayerColor owner); // picks a unused hero type randomly
  248. int pickNextHeroType(PlayerColor owner); // picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  249. // ---- data -----
  250. std::shared_ptr<CApplier<CBaseForGSApply>> applier;
  251. CRandomGenerator rand;
  252. friend class CCallback;
  253. friend class CClient;
  254. friend class IGameCallback;
  255. friend class CMapHandler;
  256. friend class CGameHandler;
  257. };