CGameState.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. /*
  16. * CGameState.h, part of VCMI engine
  17. *
  18. * Authors: listed in file AUTHORS in main folder
  19. *
  20. * License: GNU General Public License v2.0 or later
  21. * Full text of license available in license.txt file, in main folder
  22. *
  23. */
  24. class CTown;
  25. class CCallback;
  26. class IGameCallback;
  27. class CCreatureSet;
  28. class CStack;
  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 SDL_Surface;
  40. class CMapHandler;
  41. class CPathfinder;
  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. class CPathfinder : private CGameInfoCallback
  230. {
  231. private:
  232. struct PathfinderOptions
  233. {
  234. bool useFlying;
  235. bool useWaterWalking;
  236. bool useEmbarkAndDisembark;
  237. bool useTeleportTWoWay; // Two-way monoliths and Subterranean Gate
  238. bool useTeleportOneWay; // One-way monoliths with one known exit only
  239. bool useTeleportOneWayRandom; // One-way monoliths with more than one known exit
  240. bool useTeleportWhirlpool; // Force enabled if hero protected or unaffected (have one stack of one creature)
  241. PathfinderOptions();
  242. };
  243. PathfinderOptions options;
  244. CPathsInfo &out;
  245. const CGHeroInstance *hero;
  246. const std::vector<std::vector<std::vector<ui8> > > &FoW;
  247. std::list<CGPathNode*> mq; //BFS queue -> nodes to be checked
  248. std::vector<int3> neighbours;
  249. int3 curPos;
  250. CGPathNode *cp; //current (source) path node -> we took it from the queue
  251. CGPathNode *dp; //destination node -> it's a neighbour of cp that we consider
  252. const TerrainTile *ct, *dt; //tile info for both nodes
  253. ui8 useEmbarkCost; //0 - usual movement; 1 - embark; 2 - disembark
  254. CGObjectInstance *sTileObj;
  255. CGObjectInstance *dTileObj;
  256. const CGTeleport *sTileTeleport;
  257. const CGTeleport *dTileTeleport;
  258. CGPathNode *getNode(const int3 &coord);
  259. void initializeGraph();
  260. bool isMovementPossible(); //checks if current move will be between sea<->land. If so, checks it legality (returns false if movement is not possible) and sets useEmbarkCost
  261. int3 getSourceGuardPosition();
  262. bool isSourceGuarded();
  263. bool isDestinationGuarded();
  264. bool isDestinationGuardian();
  265. void getNeighbours(const int3 &coord);
  266. void getTeleportExits(bool noTeleportExcludes = false);
  267. bool checkDestinationTile();
  268. CGPathNode::EAccessibility evaluateAccessibility(const TerrainTile *tinfo) const;
  269. bool canMoveBetween(const int3 &a, const int3 &b) const; //checks only for visitable objects that may make moving between tiles impossible, not other conditions (like tiles itself accessibility)
  270. bool addTeleportTwoWay(const CGTeleport * obj) const;
  271. bool addTeleportOneWay(const CGTeleport * obj) const;
  272. bool addTeleportOneWayRandom(const CGTeleport * obj) const;
  273. bool addTeleportWhirlpool(const CGWhirlpool * obj) const;
  274. public:
  275. CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero);
  276. void calculatePaths(); //calculates possible paths for hero, uses current hero position and movement left; returns pointer to newly allocated CPath or nullptr if path does not exists
  277. };
  278. struct BattleInfo;
  279. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  280. class DLL_LINKAGE CGameState : public CNonConstInfoCallback
  281. {
  282. public:
  283. struct DLL_LINKAGE HeroesPool
  284. {
  285. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; nullptr if not available
  286. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  287. CGHeroInstance * pickHeroFor(bool native, PlayerColor player, const CTown *town,
  288. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, CRandomGenerator & rand, const CHeroClass *bannedClass = nullptr) const;
  289. template <typename Handler> void serialize(Handler &h, const int version)
  290. {
  291. h & heroesPool & pavailable;
  292. }
  293. } hpool; //we have here all heroes available on this map that are not hired
  294. CGameState();
  295. virtual ~CGameState();
  296. void init(StartInfo * si);
  297. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  298. PlayerColor currentPlayer; //ID of player currently having turn
  299. ConstTransitivePtr<BattleInfo> curB; //current battle
  300. ui32 day; //total number of days in game
  301. ConstTransitivePtr<CMap> map;
  302. std::map<PlayerColor, PlayerState> players;
  303. std::map<TeamID, TeamState> teams;
  304. CBonusSystemNode globalEffects;
  305. boost::shared_mutex *mx;
  306. void giveHeroArtifact(CGHeroInstance *h, ArtifactID aid);
  307. void apply(CPack *pack);
  308. BFieldType battleGetBattlefieldType(int3 tile);
  309. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  310. PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2);
  311. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  312. 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
  313. int3 guardingCreaturePosition (int3 pos) const;
  314. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  315. // ----- victory, loss condition checks -----
  316. EVictoryLossCheckResult checkForVictoryAndLoss(PlayerColor player) const;
  317. bool checkForVictory(PlayerColor player, const EventCondition & condition) const; //checks if given player is winner
  318. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  319. bool checkForStandardLoss(PlayerColor player) const; //checks if given player lost the game
  320. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  321. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  322. BattleInfo * setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town);
  323. bool isVisible(int3 pos, PlayerColor player);
  324. bool isVisible(const CGObjectInstance *obj, boost::optional<PlayerColor> player);
  325. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing);
  326. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  327. 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
  328. // ----- getters, setters -----
  329. CRandomGenerator & getRandomGenerator();
  330. template <typename Handler> void serialize(Handler &h, const int version)
  331. {
  332. h & scenarioOps & initialOpts & currentPlayer & day & map & players & teams & hpool & globalEffects & rand;
  333. BONUS_TREE_DESERIALIZATION_FIX
  334. }
  335. private:
  336. struct CrossoverHeroesList
  337. {
  338. std::vector<CGHeroInstance *> heroesFromPreviousScenario, heroesFromAnyPreviousScenarios;
  339. void addHeroToBothLists(CGHeroInstance * hero);
  340. void removeHeroFromBothLists(CGHeroInstance * hero);
  341. };
  342. struct CampaignHeroReplacement
  343. {
  344. CampaignHeroReplacement(CGHeroInstance * hero, ObjectInstanceID heroPlaceholderId);
  345. CGHeroInstance * hero;
  346. ObjectInstanceID heroPlaceholderId;
  347. };
  348. // ----- initialization -----
  349. void initNewGame();
  350. void initCampaign();
  351. void initDuel();
  352. void checkMapChecksum();
  353. void initGrailPosition();
  354. void initRandomFactionsForPlayers();
  355. void randomizeMapObjects();
  356. void randomizeObject(CGObjectInstance *cur);
  357. void initPlayerStates();
  358. void placeCampaignHeroes();
  359. CrossoverHeroesList getCrossoverHeroesFromPreviousScenarios() const;
  360. /// returns heroes and placeholders in where heroes will be put
  361. std::vector<CampaignHeroReplacement> generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes);
  362. /// gets prepared and copied hero instances with crossover heroes from prev. scenario and travel options from current scenario
  363. void prepareCrossoverHeroes(std::vector<CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions) const;
  364. void replaceHeroesPlaceholders(const std::vector<CampaignHeroReplacement> & campaignHeroReplacements);
  365. void placeStartingHeroes();
  366. void placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos);
  367. void initStartingResources();
  368. void initHeroes();
  369. void giveCampaignBonusToHero(CGHeroInstance * hero);
  370. void initFogOfWar();
  371. void initStartingBonus();
  372. void initTowns();
  373. void initMapObjects();
  374. void initVisitingAndGarrisonedHeroes();
  375. // ----- bonus system handling -----
  376. void buildBonusSystemTree();
  377. void attachArmedObjects();
  378. void buildGlobalTeamPlayerTree();
  379. void deserializationFix();
  380. // ---- misc helpers -----
  381. CGHeroInstance * getUsedHero(HeroTypeID hid) const;
  382. bool isUsedHero(HeroTypeID hid) const; //looks in heroes and prisons
  383. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  384. std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  385. int pickUnusedHeroTypeRandomly(PlayerColor owner); // picks a unused hero type randomly
  386. int pickNextHeroType(PlayerColor owner); // picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  387. // ---- data -----
  388. CRandomGenerator rand;
  389. friend class CCallback;
  390. friend class CClient;
  391. friend class IGameCallback;
  392. friend class CMapHandler;
  393. friend class CGameHandler;
  394. };