CGameState.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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 "CRandomGenerator.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 (0 - a few, 1 - several and so on; additionally -1 - 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. ObjectInstanceID currentSelection; //id of hero/town, 0xffffffff if none
  137. TeamID team;
  138. TResources resources;
  139. std::set<ObjectInstanceID> visitedObjects; // as a std::set, since most accesses here will be from visited status checks
  140. std::vector<ConstTransitivePtr<CGHeroInstance> > heroes;
  141. std::vector<ConstTransitivePtr<CGTownInstance> > towns;
  142. std::vector<ConstTransitivePtr<CGHeroInstance> > availableHeroes; //heroes available in taverns
  143. std::vector<ConstTransitivePtr<CGDwelling> > dwellings; //used for town growth
  144. std::vector<QuestInfo> quests; //store info about all received quests
  145. bool enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory
  146. EPlayerStatus::EStatus status;
  147. boost::optional<ui8> daysWithoutCastle;
  148. PlayerState();
  149. std::string nodeName() const override;
  150. template <typename Handler> void serialize(Handler &h, const int version)
  151. {
  152. h & color & human & currentSelection & team & resources & status;
  153. h & heroes & towns & availableHeroes & dwellings & visitedObjects;
  154. h & getBonusList(); //FIXME FIXME FIXME
  155. h & status & daysWithoutCastle;
  156. h & enteredLosingCheatCode & enteredWinningCheatCode;
  157. h & static_cast<CBonusSystemNode&>(*this);
  158. }
  159. };
  160. struct DLL_LINKAGE TeamState : public CBonusSystemNode
  161. {
  162. public:
  163. TeamID id; //position in gameState::teams
  164. std::set<PlayerColor> players; // members of this team
  165. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  166. TeamState();
  167. template <typename Handler> void serialize(Handler &h, const int version)
  168. {
  169. h & id & players & fogOfWarMap;
  170. h & static_cast<CBonusSystemNode&>(*this);
  171. }
  172. };
  173. struct UpgradeInfo
  174. {
  175. CreatureID oldID; //creature to be upgraded
  176. std::vector<CreatureID> newID; //possible upgrades
  177. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  178. UpgradeInfo(){oldID = CreatureID::NONE;};
  179. };
  180. struct DLL_LINKAGE CGPathNode
  181. {
  182. enum EAccessibility
  183. {
  184. NOT_SET = 0,
  185. ACCESSIBLE = 1, //tile can be entered and passed
  186. VISITABLE, //tile can be entered as the last tile in path
  187. BLOCKVIS, //visitable from neighbouring tile but not passable
  188. BLOCKED //tile can't be entered nor visited
  189. };
  190. EAccessibility accessible;
  191. ui8 land;
  192. ui8 turns; //how many turns we have to wait before reachng the tile - 0 means current turn
  193. ui32 moveRemains; //remaining tiles after hero reaches the tile
  194. CGPathNode * theNodeBefore;
  195. int3 coord; //coordinates
  196. CGPathNode();
  197. bool reachable() const;
  198. };
  199. struct DLL_LINKAGE CGPath
  200. {
  201. std::vector<CGPathNode> nodes; //just get node by node
  202. int3 startPos() const; // start point
  203. int3 endPos() const; //destination point
  204. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  205. };
  206. struct DLL_LINKAGE CPathsInfo
  207. {
  208. bool isValid;
  209. const CGHeroInstance *hero;
  210. int3 hpos;
  211. int3 sizes;
  212. CGPathNode ***nodes; //[w][h][level]
  213. bool getPath(const int3 &dst, CGPath &out);
  214. CPathsInfo(const int3 &Sizes);
  215. ~CPathsInfo();
  216. };
  217. struct DLL_EXPORT DuelParameters
  218. {
  219. ETerrainType terType;
  220. BFieldType bfieldType;
  221. struct DLL_EXPORT SideSettings
  222. {
  223. struct DLL_EXPORT StackSettings
  224. {
  225. CreatureID type;
  226. si32 count;
  227. template <typename Handler> void serialize(Handler &h, const int version)
  228. {
  229. h & type & count;
  230. }
  231. StackSettings();
  232. StackSettings(CreatureID Type, si32 Count);
  233. } stacks[GameConstants::ARMY_SIZE];
  234. si32 heroId; //-1 if none
  235. std::vector<si32> heroPrimSkills; //may be empty
  236. std::map<si32, CArtifactInstance*> artifacts;
  237. std::vector<std::pair<si32, si8> > heroSecSkills; //may be empty; pairs <id, level>, level [0-3]
  238. std::set<SpellID> spells;
  239. SideSettings();
  240. template <typename Handler> void serialize(Handler &h, const int version)
  241. {
  242. h & stacks & heroId & heroPrimSkills & artifacts & heroSecSkills & spells;
  243. }
  244. } sides[2];
  245. std::vector<shared_ptr<CObstacleInstance> > obstacles;
  246. static DuelParameters fromJSON(const std::string &fname);
  247. struct CusomCreature
  248. {
  249. int id;
  250. int attack, defense, dmg, HP, speed, shoots;
  251. CusomCreature()
  252. {
  253. id = attack = defense = dmg = HP = speed = shoots = -1;
  254. }
  255. template <typename Handler> void serialize(Handler &h, const int version)
  256. {
  257. h & id & attack & defense & dmg & HP & speed & shoots;
  258. }
  259. };
  260. std::vector<CusomCreature> creatures;
  261. DuelParameters();
  262. template <typename Handler> void serialize(Handler &h, const int version)
  263. {
  264. h & terType & bfieldType & sides & obstacles & creatures;
  265. }
  266. };
  267. class CPathfinder : private CGameInfoCallback
  268. {
  269. private:
  270. bool useSubterraneanGates;
  271. bool allowEmbarkAndDisembark;
  272. CPathsInfo &out;
  273. const CGHeroInstance *hero;
  274. const std::vector<std::vector<std::vector<ui8> > > &FoW;
  275. std::list<CGPathNode*> mq; //BFS queue -> nodes to be checked
  276. int3 curPos;
  277. CGPathNode *cp; //current (source) path node -> we took it from the queue
  278. CGPathNode *dp; //destination node -> it's a neighbour of cp that we consider
  279. const TerrainTile *ct, *dt; //tile info for both nodes
  280. ui8 useEmbarkCost; //0 - usual movement; 1 - embark; 2 - disembark
  281. int destTopVisObjID;
  282. CGPathNode *getNode(const int3 &coord);
  283. void initializeGraph();
  284. 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
  285. CGPathNode::EAccessibility evaluateAccessibility(const TerrainTile *tinfo) const;
  286. 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)
  287. public:
  288. CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero);
  289. 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
  290. };
  291. struct BattleInfo;
  292. class DLL_LINKAGE EVictoryLossCheckResult
  293. {
  294. public:
  295. static EVictoryLossCheckResult victory(std::string toSelf, std::string toOthers);
  296. static EVictoryLossCheckResult defeat(std::string toSelf, std::string toOthers);
  297. EVictoryLossCheckResult();
  298. bool operator==(EVictoryLossCheckResult const & other) const;
  299. bool operator!=(EVictoryLossCheckResult const & other) const;
  300. bool victory() const;
  301. bool loss() const;
  302. EVictoryLossCheckResult invert();
  303. std::string messageToSelf;
  304. std::string messageToOthers;
  305. template <typename Handler> void serialize(Handler &h, const int version)
  306. {
  307. h & intValue & messageToSelf & messageToOthers;
  308. }
  309. private:
  310. enum EResult
  311. {
  312. DEFEAT = -1,
  313. INGAME = 0,
  314. VICTORY= +1
  315. };
  316. EVictoryLossCheckResult(si32 intValue, std::string toSelf, std::string toOthers);
  317. si32 intValue; // uses EResult
  318. };
  319. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  320. class DLL_LINKAGE CGameState : public CNonConstInfoCallback
  321. {
  322. public:
  323. struct DLL_LINKAGE HeroesPool
  324. {
  325. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; nullptr if not available
  326. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  327. CGHeroInstance * pickHeroFor(bool native, PlayerColor player, const CTown *town,
  328. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, CRandomGenerator & rand, const CHeroClass *bannedClass = nullptr) const;
  329. template <typename Handler> void serialize(Handler &h, const int version)
  330. {
  331. h & heroesPool & pavailable;
  332. }
  333. } hpool; //we have here all heroes available on this map that are not hired
  334. CGameState();
  335. virtual ~CGameState();
  336. void init(StartInfo * si);
  337. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  338. PlayerColor currentPlayer; //ID of player currently having turn
  339. ConstTransitivePtr<BattleInfo> curB; //current battle
  340. ui32 day; //total number of days in game
  341. ConstTransitivePtr<CMap> map;
  342. std::map<PlayerColor, PlayerState> players;
  343. std::map<TeamID, TeamState> teams;
  344. CBonusSystemNode globalEffects;
  345. boost::shared_mutex *mx;
  346. void giveHeroArtifact(CGHeroInstance *h, ArtifactID aid);
  347. void apply(CPack *pack);
  348. BFieldType battleGetBattlefieldType(int3 tile);
  349. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  350. PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2);
  351. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  352. 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
  353. int3 guardingCreaturePosition (int3 pos) const;
  354. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  355. // ----- victory, loss condition checks -----
  356. EVictoryLossCheckResult checkForVictoryAndLoss(PlayerColor player) const;
  357. bool checkForVictory(PlayerColor player, const EventCondition & condition) const; //checks if given player is winner
  358. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  359. bool checkForStandardLoss(PlayerColor player) const; //checks if given player lost the game
  360. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  361. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  362. BattleInfo * setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town);
  363. bool isVisible(int3 pos, PlayerColor player);
  364. bool isVisible(const CGObjectInstance *obj, boost::optional<PlayerColor> player);
  365. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing);
  366. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, bool flying, int remainingMovePoints=-1, bool checkLast=true);
  367. 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
  368. // ----- getters, setters -----
  369. CRandomGenerator & getRandomGenerator();
  370. template <typename Handler> void serialize(Handler &h, const int version)
  371. {
  372. h & scenarioOps & initialOpts & currentPlayer & day & map & players & teams & hpool & globalEffects & rand;
  373. BONUS_TREE_DESERIALIZATION_FIX
  374. }
  375. private:
  376. struct CrossoverHeroesList
  377. {
  378. std::vector<CGHeroInstance *> heroesFromPreviousScenario, heroesFromAnyPreviousScenarios;
  379. void addHeroToBothLists(CGHeroInstance * hero);
  380. void removeHeroFromBothLists(CGHeroInstance * hero);
  381. };
  382. struct CampaignHeroReplacement
  383. {
  384. CampaignHeroReplacement(CGHeroInstance * hero, ObjectInstanceID heroPlaceholderId);
  385. CGHeroInstance * hero;
  386. ObjectInstanceID heroPlaceholderId;
  387. };
  388. // ----- initialization -----
  389. void initNewGame();
  390. void initCampaign();
  391. void initDuel();
  392. void checkMapChecksum();
  393. void initGrailPosition();
  394. void initRandomFactionsForPlayers();
  395. void randomizeMapObjects();
  396. void randomizeObject(CGObjectInstance *cur);
  397. void initPlayerStates();
  398. void placeCampaignHeroes();
  399. CrossoverHeroesList getCrossoverHeroesFromPreviousScenarios() const;
  400. /// returns heroes and placeholders in where heroes will be put
  401. std::vector<CampaignHeroReplacement> generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes);
  402. /// gets prepared and copied hero instances with crossover heroes from prev. scenario and travel options from current scenario
  403. void prepareCrossoverHeroes(std::vector<CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions) const;
  404. void replaceHeroesPlaceholders(const std::vector<CampaignHeroReplacement> & campaignHeroReplacements);
  405. void placeStartingHeroes();
  406. void placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos);
  407. void initStartingResources();
  408. void initHeroes();
  409. void giveCampaignBonusToHero(CGHeroInstance * hero);
  410. void initFogOfWar();
  411. void initStartingBonus();
  412. void initTowns();
  413. void initMapObjects();
  414. void initVisitingAndGarrisonedHeroes();
  415. // ----- bonus system handling -----
  416. void buildBonusSystemTree();
  417. void attachArmedObjects();
  418. void buildGlobalTeamPlayerTree();
  419. void deserializationFix();
  420. // ---- misc helpers -----
  421. CGHeroInstance * getUsedHero(HeroTypeID hid) const;
  422. bool isUsedHero(HeroTypeID hid) const; //looks in heroes and prisons
  423. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  424. std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  425. int pickUnusedHeroTypeRandomly(PlayerColor owner); // picks a unused hero type randomly
  426. int pickNextHeroType(PlayerColor owner); // picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  427. // ---- data -----
  428. CRandomGenerator rand;
  429. friend class CCallback;
  430. friend class CClient;
  431. friend class IGameCallback;
  432. friend class CMapHandler;
  433. friend class CGameHandler;
  434. };
  435. struct DLL_LINKAGE QuestInfo //universal interface for human and AI
  436. {
  437. const CQuest * quest;
  438. const CGObjectInstance * obj; //related object, most likely Seer Hut
  439. int3 tile;
  440. QuestInfo(){};
  441. QuestInfo (const CQuest * Quest, const CGObjectInstance * Obj, int3 Tile) :
  442. quest (Quest), obj (Obj), tile (Tile){};
  443. //FIXME: assignment operator should return QuestInfo &
  444. bool operator= (const QuestInfo &qi)
  445. {
  446. quest = qi.quest;
  447. obj = qi.obj;
  448. tile = qi.tile;
  449. return true;
  450. }
  451. bool operator== (const QuestInfo & qi) const
  452. {
  453. return (quest == qi.quest && obj == qi.obj);
  454. }
  455. //std::vector<std::string> > texts //allow additional info for quest log?
  456. template <typename Handler> void serialize(Handler &h, const int version)
  457. {
  458. h & quest & obj & tile;
  459. }
  460. };