CGameState.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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 "CObjectHandler.h"
  14. #include "IGameCallback.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. namespace boost
  58. {
  59. class shared_mutex;
  60. }
  61. //numbers of creatures are exact numbers if detailed else they are quantity ids (0 - a few, 1 - several and so on; additionally -1 - unknown)
  62. struct ArmyDescriptor : public std::map<SlotID, CStackBasicDescriptor>
  63. {
  64. bool isDetailed;
  65. DLL_LINKAGE ArmyDescriptor(const CArmedInstance *army, bool detailed); //not detailed -> quantity ids as count
  66. DLL_LINKAGE ArmyDescriptor();
  67. DLL_LINKAGE int getStrength() const;
  68. };
  69. struct DLL_LINKAGE InfoAboutArmy
  70. {
  71. PlayerColor owner;
  72. std::string name;
  73. ArmyDescriptor army;
  74. InfoAboutArmy();
  75. InfoAboutArmy(const CArmedInstance *Army, bool detailed);
  76. void initFromArmy(const CArmedInstance *Army, bool detailed);
  77. };
  78. struct DLL_LINKAGE InfoAboutHero : public InfoAboutArmy
  79. {
  80. private:
  81. void assign(const InfoAboutHero & iah);
  82. public:
  83. struct DLL_LINKAGE Details
  84. {
  85. std::vector<si32> primskills;
  86. si32 mana, luck, morale;
  87. } *details;
  88. const CHeroClass *hclass;
  89. int portrait;
  90. InfoAboutHero();
  91. InfoAboutHero(const InfoAboutHero & iah);
  92. InfoAboutHero(const CGHeroInstance *h, bool detailed);
  93. ~InfoAboutHero();
  94. InfoAboutHero & operator=(const InfoAboutHero & iah);
  95. void initFromHero(const CGHeroInstance *h, bool detailed);
  96. };
  97. /// Struct which holds a int information about a town
  98. struct DLL_LINKAGE InfoAboutTown : public InfoAboutArmy
  99. {
  100. struct DLL_LINKAGE Details
  101. {
  102. si32 hallLevel, goldIncome;
  103. bool customRes;
  104. bool garrisonedHero;
  105. } *details;
  106. const CTown *tType;
  107. si32 built;
  108. si32 fortLevel; //0 - none
  109. InfoAboutTown();
  110. InfoAboutTown(const CGTownInstance *t, bool detailed);
  111. ~InfoAboutTown();
  112. void initFromTown(const CGTownInstance *t, bool detailed);
  113. };
  114. // typedef si32 TResourceUnit;
  115. // typedef std::vector<si32> TResourceVector;
  116. // typedef std::set<si32> TResourceSet;
  117. struct DLL_LINKAGE SThievesGuildInfo
  118. {
  119. std::vector<PlayerColor> playerColors; //colors of players that are in-game
  120. std::vector< std::vector< PlayerColor > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  121. std::map<PlayerColor, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  122. std::map<PlayerColor, EAiTactic::EAiTactic> personality; // color to personality // ai tactic
  123. std::map<PlayerColor, si32> bestCreature; // color to ID // id or -1 if not known
  124. // template <typename Handler> void serialize(Handler &h, const int version)
  125. // {
  126. // h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income;
  127. // h & colorToBestHero & personality & bestCreature;
  128. // }
  129. };
  130. struct DLL_LINKAGE PlayerState : public CBonusSystemNode
  131. {
  132. public:
  133. PlayerColor color;
  134. bool human; //true if human controlled player, false for AI
  135. ObjectInstanceID currentSelection; //id of hero/town, 0xffffffff if none
  136. TeamID team;
  137. TResources resources;
  138. std::vector<ConstTransitivePtr<CGHeroInstance> > heroes;
  139. std::vector<ConstTransitivePtr<CGTownInstance> > towns;
  140. std::vector<ConstTransitivePtr<CGHeroInstance> > availableHeroes; //heroes available in taverns
  141. std::vector<ConstTransitivePtr<CGDwelling> > dwellings; //used for town growth
  142. std::vector<QuestInfo> quests; //store info about all received quests
  143. bool enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory
  144. EPlayerStatus::EStatus status;
  145. boost::optional<ui8> daysWithoutCastle;
  146. PlayerState();
  147. std::string nodeName() const override;
  148. template <typename Handler> void serialize(Handler &h, const int version)
  149. {
  150. h & color & human & currentSelection & team & resources & status;
  151. h & heroes & towns & availableHeroes & dwellings;
  152. h & getBonusList(); //FIXME FIXME FIXME
  153. h & status & daysWithoutCastle;
  154. h & enteredLosingCheatCode & enteredWinningCheatCode;
  155. h & static_cast<CBonusSystemNode&>(*this);
  156. }
  157. };
  158. struct DLL_LINKAGE TeamState : public CBonusSystemNode
  159. {
  160. public:
  161. TeamID id; //position in gameState::teams
  162. std::set<PlayerColor> players; // members of this team
  163. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  164. TeamState();
  165. template <typename Handler> void serialize(Handler &h, const int version)
  166. {
  167. h & id & players & fogOfWarMap;
  168. h & static_cast<CBonusSystemNode&>(*this);
  169. }
  170. };
  171. struct UpgradeInfo
  172. {
  173. CreatureID oldID; //creature to be upgraded
  174. std::vector<CreatureID> newID; //possible upgrades
  175. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  176. UpgradeInfo(){oldID = CreatureID::NONE;};
  177. };
  178. struct DLL_LINKAGE CGPathNode
  179. {
  180. enum EAccessibility
  181. {
  182. NOT_SET = 0,
  183. ACCESSIBLE = 1, //tile can be entered and passed
  184. VISITABLE, //tile can be entered as the last tile in path
  185. BLOCKVIS, //visitable from neighbouring tile but not passable
  186. BLOCKED //tile can't be entered nor visited
  187. };
  188. EAccessibility accessible;
  189. ui8 land;
  190. ui8 turns; //how many turns we have to wait before reachng the tile - 0 means current turn
  191. ui32 moveRemains; //remaining tiles after hero reaches the tile
  192. CGPathNode * theNodeBefore;
  193. int3 coord; //coordinates
  194. CGPathNode();
  195. bool reachable() const;
  196. };
  197. struct DLL_LINKAGE CGPath
  198. {
  199. std::vector<CGPathNode> nodes; //just get node by node
  200. int3 startPos() const; // start point
  201. int3 endPos() const; //destination point
  202. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  203. };
  204. struct DLL_LINKAGE CPathsInfo
  205. {
  206. bool isValid;
  207. const CGHeroInstance *hero;
  208. int3 hpos;
  209. int3 sizes;
  210. CGPathNode ***nodes; //[w][h][level]
  211. bool getPath(const int3 &dst, CGPath &out);
  212. CPathsInfo(const int3 &Sizes);
  213. ~CPathsInfo();
  214. };
  215. struct DLL_EXPORT DuelParameters
  216. {
  217. ETerrainType terType;
  218. BFieldType bfieldType;
  219. struct DLL_EXPORT SideSettings
  220. {
  221. struct DLL_EXPORT StackSettings
  222. {
  223. CreatureID type;
  224. si32 count;
  225. template <typename Handler> void serialize(Handler &h, const int version)
  226. {
  227. h & type & count;
  228. }
  229. StackSettings();
  230. StackSettings(CreatureID Type, si32 Count);
  231. } stacks[GameConstants::ARMY_SIZE];
  232. si32 heroId; //-1 if none
  233. std::vector<si32> heroPrimSkills; //may be empty
  234. std::map<si32, CArtifactInstance*> artifacts;
  235. std::vector<std::pair<si32, si8> > heroSecSkills; //may be empty; pairs <id, level>, level [0-3]
  236. std::set<SpellID> spells;
  237. SideSettings();
  238. template <typename Handler> void serialize(Handler &h, const int version)
  239. {
  240. h & stacks & heroId & heroPrimSkills & artifacts & heroSecSkills & spells;
  241. }
  242. } sides[2];
  243. std::vector<shared_ptr<CObstacleInstance> > obstacles;
  244. static DuelParameters fromJSON(const std::string &fname);
  245. struct CusomCreature
  246. {
  247. int id;
  248. int attack, defense, dmg, HP, speed, shoots;
  249. CusomCreature()
  250. {
  251. id = attack = defense = dmg = HP = speed = shoots = -1;
  252. }
  253. template <typename Handler> void serialize(Handler &h, const int version)
  254. {
  255. h & id & attack & defense & dmg & HP & speed & shoots;
  256. }
  257. };
  258. std::vector<CusomCreature> creatures;
  259. DuelParameters();
  260. template <typename Handler> void serialize(Handler &h, const int version)
  261. {
  262. h & terType & bfieldType & sides & obstacles & creatures;
  263. }
  264. };
  265. class CPathfinder : private CGameInfoCallback
  266. {
  267. private:
  268. bool useSubterraneanGates;
  269. bool allowEmbarkAndDisembark;
  270. CPathsInfo &out;
  271. const CGHeroInstance *hero;
  272. const std::vector<std::vector<std::vector<ui8> > > &FoW;
  273. std::list<CGPathNode*> mq; //BFS queue -> nodes to be checked
  274. int3 curPos;
  275. CGPathNode *cp; //current (source) path node -> we took it from the queue
  276. CGPathNode *dp; //destination node -> it's a neighbour of cp that we consider
  277. const TerrainTile *ct, *dt; //tile info for both nodes
  278. ui8 useEmbarkCost; //0 - usual movement; 1 - embark; 2 - disembark
  279. int destTopVisObjID;
  280. CGPathNode *getNode(const int3 &coord);
  281. void initializeGraph();
  282. bool goodForLandSeaTransition(); //checks if current move will be between sea<->land. If so, checks it legality (returns false if movement is not possible) and sets useEmbarkCost
  283. CGPathNode::EAccessibility evaluateAccessibility(const TerrainTile *tinfo) const;
  284. 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)
  285. public:
  286. CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero);
  287. void calculatePaths(int3 src = int3(-1,-1,-1), int movement = -1); //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
  288. };
  289. struct BattleInfo;
  290. class DLL_LINKAGE EVictoryLossCheckResult
  291. {
  292. public:
  293. static EVictoryLossCheckResult victory(std::string toSelf, std::string toOthers);
  294. static EVictoryLossCheckResult defeat(std::string toSelf, std::string toOthers);
  295. EVictoryLossCheckResult();
  296. bool operator==(EVictoryLossCheckResult const & other) const;
  297. bool operator!=(EVictoryLossCheckResult const & other) const;
  298. bool victory() const;
  299. bool loss() const;
  300. EVictoryLossCheckResult invert();
  301. std::string messageToSelf;
  302. std::string messageToOthers;
  303. template <typename Handler> void serialize(Handler &h, const int version)
  304. {
  305. h & intValue & messageToSelf & messageToOthers;
  306. }
  307. private:
  308. enum EResult
  309. {
  310. DEFEAT = -1,
  311. INGAME = 0,
  312. VICTORY= +1
  313. };
  314. EVictoryLossCheckResult(si32 intValue, std::string toSelf, std::string toOthers);
  315. si32 intValue; // uses EResult
  316. };
  317. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  318. class DLL_LINKAGE CGameState : public CNonConstInfoCallback
  319. {
  320. public:
  321. struct DLL_LINKAGE HeroesPool
  322. {
  323. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; nullptr if not available
  324. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  325. CGHeroInstance * pickHeroFor(bool native, PlayerColor player, const CTown *town, std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass = nullptr) const;
  326. template <typename Handler> void serialize(Handler &h, const int version)
  327. {
  328. h & heroesPool & pavailable;
  329. }
  330. } hpool; //we have here all heroes available on this map that are not hired
  331. CGameState();
  332. virtual ~CGameState();
  333. void init(StartInfo * si);
  334. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  335. PlayerColor currentPlayer; //ID of player currently having turn
  336. ConstTransitivePtr<BattleInfo> curB; //current battle
  337. ui32 day; //total number of days in game
  338. ConstTransitivePtr<CMap> map;
  339. std::map<PlayerColor, PlayerState> players;
  340. std::map<TeamID, TeamState> teams;
  341. CBonusSystemNode globalEffects;
  342. boost::shared_mutex *mx;
  343. void giveHeroArtifact(CGHeroInstance *h, ArtifactID aid);
  344. void apply(CPack *pack);
  345. BFieldType battleGetBattlefieldType(int3 tile) const;
  346. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  347. PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2);
  348. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  349. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  350. void calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src = int3(-1,-1,-1), int movement = -1); //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
  351. int3 guardingCreaturePosition (int3 pos) const;
  352. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  353. // ----- victory, loss condition checks -----
  354. EVictoryLossCheckResult checkForVictoryAndLoss(PlayerColor player) const;
  355. bool checkForVictory(PlayerColor player, const EventCondition & condition) const; //checks if given player is winner
  356. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  357. bool checkForStandardLoss(PlayerColor player) const; //checks if given player lost the game
  358. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  359. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  360. BattleInfo * setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town);
  361. bool isVisible(int3 pos, PlayerColor player);
  362. bool isVisible(const CGObjectInstance *obj, boost::optional<PlayerColor> player);
  363. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing);
  364. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  365. 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
  366. template <typename Handler> void serialize(Handler &h, const int version)
  367. {
  368. h & scenarioOps & initialOpts & currentPlayer & day & map & players & teams & hpool & globalEffects;
  369. BONUS_TREE_DESERIALIZATION_FIX
  370. }
  371. private:
  372. // ----- initialization -----
  373. void initNewGame();
  374. void initCampaign();
  375. void initDuel();
  376. void checkMapChecksum();
  377. void initGrailPosition();
  378. void initRandomFactionsForPlayers();
  379. void randomizeMapObjects();
  380. void randomizeObject(CGObjectInstance *cur);
  381. void initPlayerStates();
  382. void placeCampaignHeroes();
  383. const CCampaignScenario * getCampaignScenarioForCrossoverHeroes() const;
  384. std::vector<CGHeroInstance *> prepareCrossoverHeroes(const CCampaignScenario * campaignScenario);
  385. // returns heroes and placeholders in where heroes will be put
  386. std::vector<std::pair<CGHeroInstance*, ObjectInstanceID> > generateCampaignHeroesToReplace(std::vector<CGHeroInstance *> & crossoverHeroes);
  387. void replaceHeroesPlaceholders(const std::vector<std::pair<CGHeroInstance*, ObjectInstanceID> > &campHeroReplacements);
  388. void placeStartingHeroes();
  389. void placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos);
  390. void initStartingResources();
  391. void initHeroes();
  392. void giveCampaignBonusToHero(CGHeroInstance * hero);
  393. void initFogOfWar();
  394. void initStartingBonus();
  395. void initTowns();
  396. void initMapObjects();
  397. void initVisitingAndGarrisonedHeroes();
  398. // ----- bonus system handling -----
  399. void buildBonusSystemTree();
  400. void attachArmedObjects();
  401. void buildGlobalTeamPlayerTree();
  402. void deserializationFix();
  403. // ---- misc helpers -----
  404. CGHeroInstance * getUsedHero(HeroTypeID hid) const;
  405. bool isUsedHero(HeroTypeID hid) const; //looks in heroes and prisons
  406. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  407. std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  408. int pickUnusedHeroTypeRandomly(PlayerColor owner) const; // picks a unused hero type randomly
  409. int pickNextHeroType(PlayerColor owner) const; // picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  410. friend class CCallback;
  411. friend class CClient;
  412. friend class IGameCallback;
  413. friend class CMapHandler;
  414. friend class CGameHandler;
  415. };
  416. struct DLL_LINKAGE QuestInfo //universal interface for human and AI
  417. {
  418. const CQuest * quest;
  419. const CGObjectInstance * obj; //related object, most likely Seer Hut
  420. int3 tile;
  421. QuestInfo(){};
  422. QuestInfo (const CQuest * Quest, const CGObjectInstance * Obj, int3 Tile) :
  423. quest (Quest), obj (Obj), tile (Tile){};
  424. //FIXME: assignment operator should return QuestInfo &
  425. bool operator= (const QuestInfo &qi)
  426. {
  427. quest = qi.quest;
  428. obj = qi.obj;
  429. tile = qi.tile;
  430. return true;
  431. }
  432. bool operator== (const QuestInfo & qi) const
  433. {
  434. return (quest == qi.quest && obj == qi.obj);
  435. }
  436. //std::vector<std::string> > texts //allow additional info for quest log?
  437. template <typename Handler> void serialize(Handler &h, const int version)
  438. {
  439. h & quest & obj & tile;
  440. }
  441. };