CGameState.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. #pragma once
  2. #include "CCreatureHandler.h"
  3. #include "VCMI_Lib.h"
  4. #include "HeroBonus.h"
  5. #include "CCreatureSet.h"
  6. #include "ConstTransitivePtr.h"
  7. #include "IGameCallback.h"
  8. #include "ResourceSet.h"
  9. #include "int3.h"
  10. #include "CRandomGenerator.h"
  11. #include "CGameStateFwd.h"
  12. #include "CPathfinder.h"
  13. /*
  14. * CGameState.h, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  22. class CTown;
  23. class CCallback;
  24. class IGameCallback;
  25. class CCreatureSet;
  26. class CStack;
  27. class CQuest;
  28. class CGHeroInstance;
  29. class CGTownInstance;
  30. class CArmedInstance;
  31. class CGDwelling;
  32. class CObjectScript;
  33. class CGObjectInstance;
  34. class CCreature;
  35. class CMap;
  36. struct StartInfo;
  37. struct SDL_Surface;
  38. class CMapHandler;
  39. struct SetObjectProperty;
  40. struct 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. class CGameInfo;
  50. struct QuestInfo;
  51. class CQuest;
  52. class CCampaignScenario;
  53. struct EventCondition;
  54. class CScenarioTravel;
  55. namespace boost
  56. {
  57. class shared_mutex;
  58. }
  59. //numbers of creatures are exact numbers if detailed else they are quantity ids (1 - a few, 2 - several and so on; additionally 0 - unknown)
  60. struct ArmyDescriptor : public std::map<SlotID, CStackBasicDescriptor>
  61. {
  62. bool isDetailed;
  63. DLL_LINKAGE ArmyDescriptor(const CArmedInstance *army, bool detailed); //not detailed -> quantity ids as count
  64. DLL_LINKAGE ArmyDescriptor();
  65. DLL_LINKAGE int getStrength() const;
  66. };
  67. struct DLL_LINKAGE InfoAboutArmy
  68. {
  69. PlayerColor owner;
  70. std::string name;
  71. ArmyDescriptor army;
  72. InfoAboutArmy();
  73. InfoAboutArmy(const CArmedInstance *Army, bool detailed);
  74. void initFromArmy(const CArmedInstance *Army, bool detailed);
  75. };
  76. struct DLL_LINKAGE InfoAboutHero : public InfoAboutArmy
  77. {
  78. private:
  79. void assign(const InfoAboutHero & iah);
  80. public:
  81. struct DLL_LINKAGE Details
  82. {
  83. std::vector<si32> primskills;
  84. si32 mana, luck, morale;
  85. } *details;
  86. const CHeroClass *hclass;
  87. int portrait;
  88. InfoAboutHero();
  89. InfoAboutHero(const InfoAboutHero & iah);
  90. InfoAboutHero(const CGHeroInstance *h, bool detailed);
  91. ~InfoAboutHero();
  92. InfoAboutHero & operator=(const InfoAboutHero & iah);
  93. void initFromHero(const CGHeroInstance *h, bool detailed);
  94. };
  95. /// Struct which holds a int information about a town
  96. struct DLL_LINKAGE InfoAboutTown : public InfoAboutArmy
  97. {
  98. struct DLL_LINKAGE Details
  99. {
  100. si32 hallLevel, goldIncome;
  101. bool customRes;
  102. bool garrisonedHero;
  103. } *details;
  104. const CTown *tType;
  105. si32 built;
  106. si32 fortLevel; //0 - none
  107. InfoAboutTown();
  108. InfoAboutTown(const CGTownInstance *t, bool detailed);
  109. ~InfoAboutTown();
  110. void initFromTown(const CGTownInstance *t, bool detailed);
  111. };
  112. // typedef si32 TResourceUnit;
  113. // typedef std::vector<si32> TResourceVector;
  114. // typedef std::set<si32> TResourceSet;
  115. struct DLL_LINKAGE SThievesGuildInfo
  116. {
  117. std::vector<PlayerColor> playerColors; //colors of players that are in-game
  118. std::vector< std::vector< PlayerColor > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  119. std::map<PlayerColor, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  120. std::map<PlayerColor, EAiTactic::EAiTactic> personality; // color to personality // ai tactic
  121. std::map<PlayerColor, si32> bestCreature; // color to ID // id or -1 if not known
  122. // template <typename Handler> void serialize(Handler &h, const int version)
  123. // {
  124. // h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income;
  125. // h & colorToBestHero & personality & bestCreature;
  126. // }
  127. };
  128. struct DLL_LINKAGE PlayerState : public CBonusSystemNode
  129. {
  130. public:
  131. PlayerColor color;
  132. bool human; //true if human controlled player, false for AI
  133. TeamID team;
  134. TResources resources;
  135. std::set<ObjectInstanceID> visitedObjects; // as a std::set, since most accesses here will be from visited status checks
  136. std::vector<ConstTransitivePtr<CGHeroInstance> > heroes;
  137. std::vector<ConstTransitivePtr<CGTownInstance> > towns;
  138. std::vector<ConstTransitivePtr<CGHeroInstance> > availableHeroes; //heroes available in taverns
  139. std::vector<ConstTransitivePtr<CGDwelling> > dwellings; //used for town growth
  140. std::vector<QuestInfo> quests; //store info about all received quests
  141. bool enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory
  142. EPlayerStatus::EStatus status;
  143. boost::optional<ui8> daysWithoutCastle;
  144. PlayerState();
  145. std::string nodeName() const override;
  146. template <typename Handler> void serialize(Handler &h, const int version)
  147. {
  148. h & color & human & team & resources & status;
  149. h & heroes & towns & availableHeroes & dwellings & quests & visitedObjects;
  150. h & getBonusList(); //FIXME FIXME FIXME
  151. h & status & daysWithoutCastle;
  152. h & enteredLosingCheatCode & enteredWinningCheatCode;
  153. h & static_cast<CBonusSystemNode&>(*this);
  154. }
  155. };
  156. struct DLL_LINKAGE TeamState : public CBonusSystemNode
  157. {
  158. public:
  159. TeamID id; //position in gameState::teams
  160. std::set<PlayerColor> players; // members of this team
  161. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  162. TeamState();
  163. template <typename Handler> void serialize(Handler &h, const int version)
  164. {
  165. h & id & players & fogOfWarMap;
  166. h & static_cast<CBonusSystemNode&>(*this);
  167. }
  168. };
  169. struct UpgradeInfo
  170. {
  171. CreatureID oldID; //creature to be upgraded
  172. std::vector<CreatureID> newID; //possible upgrades
  173. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  174. UpgradeInfo(){oldID = CreatureID::NONE;};
  175. };
  176. struct DLL_EXPORT DuelParameters
  177. {
  178. ETerrainType terType;
  179. BFieldType bfieldType;
  180. struct DLL_EXPORT SideSettings
  181. {
  182. struct DLL_EXPORT StackSettings
  183. {
  184. CreatureID type;
  185. si32 count;
  186. template <typename Handler> void serialize(Handler &h, const int version)
  187. {
  188. h & type & count;
  189. }
  190. StackSettings();
  191. StackSettings(CreatureID Type, si32 Count);
  192. } stacks[GameConstants::ARMY_SIZE];
  193. si32 heroId; //-1 if none
  194. std::vector<si32> heroPrimSkills; //may be empty
  195. std::map<si32, CArtifactInstance*> artifacts;
  196. std::vector<std::pair<si32, si8> > heroSecSkills; //may be empty; pairs <id, level>, level [0-3]
  197. std::set<SpellID> spells;
  198. SideSettings();
  199. template <typename Handler> void serialize(Handler &h, const int version)
  200. {
  201. h & stacks & heroId & heroPrimSkills & artifacts & heroSecSkills & spells;
  202. }
  203. } sides[2];
  204. std::vector<shared_ptr<CObstacleInstance> > obstacles;
  205. static DuelParameters fromJSON(const std::string &fname);
  206. struct CusomCreature
  207. {
  208. int id;
  209. int attack, defense, dmg, HP, speed, shoots;
  210. CusomCreature()
  211. {
  212. id = attack = defense = dmg = HP = speed = shoots = -1;
  213. }
  214. template <typename Handler> void serialize(Handler &h, const int version)
  215. {
  216. h & id & attack & defense & dmg & HP & speed & shoots;
  217. }
  218. };
  219. std::vector<CusomCreature> creatures;
  220. DuelParameters();
  221. template <typename Handler> void serialize(Handler &h, const int version)
  222. {
  223. h & terType & bfieldType & sides & obstacles & creatures;
  224. }
  225. };
  226. struct BattleInfo;
  227. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  228. class DLL_LINKAGE CGameState : public CNonConstInfoCallback
  229. {
  230. public:
  231. struct DLL_LINKAGE HeroesPool
  232. {
  233. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; nullptr if not available
  234. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  235. CGHeroInstance * pickHeroFor(bool native, PlayerColor player, const CTown *town,
  236. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, CRandomGenerator & rand, const CHeroClass *bannedClass = nullptr) const;
  237. template <typename Handler> void serialize(Handler &h, const int version)
  238. {
  239. h & heroesPool & pavailable;
  240. }
  241. } hpool; //we have here all heroes available on this map that are not hired
  242. CGameState();
  243. virtual ~CGameState();
  244. void init(StartInfo * si);
  245. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  246. PlayerColor currentPlayer; //ID of player currently having turn
  247. ConstTransitivePtr<BattleInfo> curB; //current battle
  248. ui32 day; //total number of days in game
  249. ConstTransitivePtr<CMap> map;
  250. std::map<PlayerColor, PlayerState> players;
  251. std::map<TeamID, TeamState> teams;
  252. CBonusSystemNode globalEffects;
  253. boost::shared_mutex *mx;
  254. void giveHeroArtifact(CGHeroInstance *h, ArtifactID aid);
  255. void apply(CPack *pack);
  256. BFieldType battleGetBattlefieldType(int3 tile);
  257. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  258. PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2);
  259. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  260. 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
  261. int3 guardingCreaturePosition (int3 pos) const;
  262. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  263. // ----- victory, loss condition checks -----
  264. EVictoryLossCheckResult checkForVictoryAndLoss(PlayerColor player) const;
  265. bool checkForVictory(PlayerColor player, const EventCondition & condition) const; //checks if given player is winner
  266. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  267. bool checkForStandardLoss(PlayerColor player) const; //checks if given player lost the game
  268. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  269. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  270. BattleInfo * setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town);
  271. bool isVisible(int3 pos, PlayerColor player);
  272. bool isVisible(const CGObjectInstance *obj, boost::optional<PlayerColor> player);
  273. 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
  274. // ----- getters, setters -----
  275. CRandomGenerator & getRandomGenerator();
  276. template <typename Handler> void serialize(Handler &h, const int version)
  277. {
  278. h & scenarioOps & initialOpts & currentPlayer & day & map & players & teams & hpool & globalEffects & rand;
  279. BONUS_TREE_DESERIALIZATION_FIX
  280. }
  281. private:
  282. struct CrossoverHeroesList
  283. {
  284. std::vector<CGHeroInstance *> heroesFromPreviousScenario, heroesFromAnyPreviousScenarios;
  285. void addHeroToBothLists(CGHeroInstance * hero);
  286. void removeHeroFromBothLists(CGHeroInstance * hero);
  287. };
  288. struct CampaignHeroReplacement
  289. {
  290. CampaignHeroReplacement(CGHeroInstance * hero, ObjectInstanceID heroPlaceholderId);
  291. CGHeroInstance * hero;
  292. ObjectInstanceID heroPlaceholderId;
  293. };
  294. // ----- initialization -----
  295. void initNewGame();
  296. void initCampaign();
  297. void initDuel();
  298. void checkMapChecksum();
  299. void initGrailPosition();
  300. void initRandomFactionsForPlayers();
  301. void randomizeMapObjects();
  302. void randomizeObject(CGObjectInstance *cur);
  303. void initPlayerStates();
  304. void placeCampaignHeroes();
  305. CrossoverHeroesList getCrossoverHeroesFromPreviousScenarios() const;
  306. /// returns heroes and placeholders in where heroes will be put
  307. std::vector<CampaignHeroReplacement> generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes);
  308. /// gets prepared and copied hero instances with crossover heroes from prev. scenario and travel options from current scenario
  309. void prepareCrossoverHeroes(std::vector<CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions) const;
  310. void replaceHeroesPlaceholders(const std::vector<CampaignHeroReplacement> & campaignHeroReplacements);
  311. void placeStartingHeroes();
  312. void placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos);
  313. void initStartingResources();
  314. void initHeroes();
  315. void giveCampaignBonusToHero(CGHeroInstance * hero);
  316. void initFogOfWar();
  317. void initStartingBonus();
  318. void initTowns();
  319. void initMapObjects();
  320. void initVisitingAndGarrisonedHeroes();
  321. // ----- bonus system handling -----
  322. void buildBonusSystemTree();
  323. void attachArmedObjects();
  324. void buildGlobalTeamPlayerTree();
  325. void deserializationFix();
  326. // ---- misc helpers -----
  327. CGHeroInstance * getUsedHero(HeroTypeID hid) const;
  328. bool isUsedHero(HeroTypeID hid) const; //looks in heroes and prisons
  329. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  330. std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  331. int pickUnusedHeroTypeRandomly(PlayerColor owner); // picks a unused hero type randomly
  332. int pickNextHeroType(PlayerColor owner); // picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  333. // ---- data -----
  334. CRandomGenerator rand;
  335. friend class CCallback;
  336. friend class CClient;
  337. friend class IGameCallback;
  338. friend class CMapHandler;
  339. friend class CGameHandler;
  340. };