CGameState.h 14 KB

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