Client.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #pragma once
  2. #include "../lib/IGameCallback.h"
  3. #include "../lib/BattleAction.h"
  4. #include "../lib/CStopWatch.h"
  5. #include "../lib/int3.h"
  6. /*
  7. * Client.h, part of VCMI engine
  8. *
  9. * Authors: listed in file AUTHORS in main folder
  10. *
  11. * License: GNU General Public License v2.0 or later
  12. * Full text of license available in license.txt file, in main folder
  13. *
  14. */
  15. struct CPack;
  16. class CCampaignState;
  17. class CBattleCallback;
  18. class IGameEventsReceiver;
  19. class IBattleEventsReceiver;
  20. class CBattleGameInterface;
  21. struct StartInfo;
  22. class CGameState;
  23. class CGameInterface;
  24. class CConnection;
  25. class CCallback;
  26. struct BattleAction;
  27. struct SharedMem;
  28. class CClient;
  29. class CScriptingModule;
  30. struct CPathsInfo;
  31. class CISer;
  32. class COSer;
  33. namespace boost { class thread; }
  34. /// structure to handle running server and connecting to it
  35. class CServerHandler
  36. {
  37. private:
  38. void callServer(); //calls server via system(), should be called as thread
  39. public:
  40. static bool DO_NOT_START_SERVER;
  41. CStopWatch th;
  42. boost::thread *serverThread; //thread that called system to run server
  43. SharedMem *shared; //interprocess memory (for waiting for server)
  44. bool verbose; //whether to print log msgs
  45. std::string port; //port number in text form
  46. //functions setting up local server
  47. void startServer(); //creates a thread with callServer
  48. void waitForServer(); //waits till server is ready
  49. CConnection * connectToServer(); //connects to server
  50. //////////////////////////////////////////////////////////////////////////
  51. static CConnection * justConnectToServer(const std::string &host = "", const std::string &port = ""); //connects to given host without taking any other actions (like setting up server)
  52. CServerHandler(bool runServer = false);
  53. ~CServerHandler();
  54. };
  55. template<typename T>
  56. class ThreadSafeVector
  57. {
  58. typedef std::vector<T> TVector;
  59. typedef boost::unique_lock<boost::mutex> TLock;
  60. TVector items;
  61. boost::mutex mx;
  62. boost::condition_variable cond;
  63. public:
  64. void pushBack(const T &item)
  65. {
  66. TLock lock(mx);
  67. items.push_back(item);
  68. cond.notify_all();
  69. }
  70. // //to access list, caller must present a lock used to lock mx
  71. // TVector &getList(TLock &lockedLock)
  72. // {
  73. // assert(lockedLock.owns_lock() && lockedLock.mutex() == &mx);
  74. // return items;
  75. // }
  76. TLock getLock()
  77. {
  78. return TLock(mx);
  79. }
  80. void waitWhileContains(const T &item)
  81. {
  82. auto lock = getLock();
  83. while(vstd::contains(items, item))
  84. cond.wait(lock);
  85. }
  86. bool tryRemovingElement(const T&item) //returns false if element was not present
  87. {
  88. auto lock = getLock();
  89. auto itr = vstd::find(items, item);
  90. if(itr == items.end()) //not in container
  91. {
  92. return false;
  93. }
  94. items.erase(itr);
  95. cond.notify_all();
  96. return true;
  97. }
  98. };
  99. /// Class which handles client - server logic
  100. class CClient : public IGameCallback
  101. {
  102. std::unique_ptr<CPathsInfo> pathInfo;
  103. public:
  104. std::map<PlayerColor,std::shared_ptr<CCallback> > callbacks; //callbacks given to player interfaces
  105. std::map<PlayerColor,std::shared_ptr<CBattleCallback> > battleCallbacks; //callbacks given to player interfaces
  106. std::vector<std::shared_ptr<IGameEventsReceiver>> privilagedGameEventReceivers; //scripting modules, spectator interfaces
  107. std::vector<std::shared_ptr<IBattleEventsReceiver>> privilagedBattleEventReceivers; //scripting modules, spectator interfaces
  108. std::map<PlayerColor, std::shared_ptr<CGameInterface>> playerint;
  109. std::map<PlayerColor, std::shared_ptr<CBattleGameInterface>> battleints;
  110. std::map<PlayerColor,std::vector<std::shared_ptr<IGameEventsReceiver>>> additionalPlayerInts;
  111. std::map<PlayerColor,std::vector<std::shared_ptr<IBattleEventsReceiver>>> additionalBattleInts;
  112. bool hotSeat;
  113. CConnection *serv;
  114. boost::optional<BattleAction> curbaction;
  115. CScriptingModule *erm;
  116. ThreadSafeVector<int> waitingRequest;
  117. void waitForMoveAndSend(PlayerColor color);
  118. //void sendRequest(const CPackForServer *request, bool waitForRealization);
  119. CClient(void);
  120. CClient(CConnection *con, StartInfo *si);
  121. ~CClient(void);
  122. void init();
  123. void newGame(CConnection *con, StartInfo *si); //con - connection to server
  124. void loadNeutralBattleAI();
  125. void installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color);
  126. void installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback = true);
  127. std::string aiNameForPlayer(const PlayerSettings &ps, bool battleAI); //empty means no AI -> human
  128. void endGame(bool closeConnection = true);
  129. void stopConnection();
  130. void save(const std::string & fname);
  131. void loadGame(const std::string & fname, const bool server = true, const std::vector<int>& humanplayerindices = std::vector<int>(), const int loadnumplayers = 1, int player_ = -1, const std::string & ipaddr = "", const std::string & port = "");
  132. void run();
  133. void campaignMapFinished( std::shared_ptr<CCampaignState> camp );
  134. void finishCampaign( std::shared_ptr<CCampaignState> camp );
  135. void proposeNextMission(std::shared_ptr<CCampaignState> camp);
  136. void invalidatePaths();
  137. const CPathsInfo * getPathsInfo(const CGHeroInstance *h);
  138. bool terminate; // tell to terminate
  139. boost::thread *connectionHandler; //thread running run() method
  140. //////////////////////////////////////////////////////////////////////////
  141. virtual PlayerColor getLocalPlayer() const override;
  142. //////////////////////////////////////////////////////////////////////////
  143. //not working yet, will be implement somewhen later with support for local-sim-based gameplay
  144. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) override {};
  145. bool removeObject(const CGObjectInstance * obj) override {return false;};
  146. void setBlockVis(ObjectInstanceID objid, bool bv) override {};
  147. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override {};
  148. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) override {};
  149. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override {};
  150. void showBlockingDialog(BlockingDialog *iw) override {};
  151. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override {};
  152. void showTeleportDialog(TeleportDialog *iw) override {};
  153. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) override {};
  154. void giveResource(PlayerColor player, Res::ERes which, int val) override {};
  155. virtual void giveResources(PlayerColor player, TResources resources) override {};
  156. void giveCreatures(const CArmedInstance * objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override {};
  157. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override {};
  158. bool changeStackType(const StackLocation &sl, const CCreature *c) override {return false;};
  159. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override {return false;};
  160. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override {return false;};
  161. bool eraseStack(const StackLocation &sl, bool forceRemoval = false) override{return false;};
  162. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override {return false;}
  163. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override {return false;}
  164. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override {}
  165. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override {return false;}
  166. void removeAfterVisit(const CGObjectInstance *object) override {};
  167. void giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition pos) override {};
  168. void giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition pos) override {};
  169. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) override {};
  170. void removeArtifact(const ArtifactLocation &al) override {};
  171. bool moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2) override {return false;};
  172. void synchronizeArtifactHandlerLists() override {};
  173. void showCompInfo(ShowInInfobox * comp) override {};
  174. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  175. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override {};
  176. //void giveHeroArtifact(int artid, int hid, int position){};
  177. //void giveNewArtifact(int hid, int position){};
  178. void startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank = false, const CGTownInstance *town = nullptr) override {}; //use hero=nullptr for no hero
  179. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) override {}; //if any of armies is hero, hero will be used
  180. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank = false) override {}; //if any of armies is hero, hero will be used, visitable tile of second obj is place of battle
  181. void setAmount(ObjectInstanceID objid, ui32 val) override {};
  182. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override {return false;};
  183. void giveHeroBonus(GiveBonus * bonus) override {};
  184. void setMovePoints(SetMovePoints * smp) override {};
  185. void setManaPoints(ObjectInstanceID hid, int val) override {};
  186. void giveHero(ObjectInstanceID id, PlayerColor player) override {};
  187. void changeObjPos(ObjectInstanceID objid, int3 newPos, ui8 flags) override {};
  188. void sendAndApply(CPackForClient * info) override {};
  189. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override {};
  190. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide) override {}
  191. void changeFogOfWar(std::unordered_set<int3, ShashInt3> &tiles, PlayerColor player, bool hide) override {}
  192. //////////////////////////////////////////////////////////////////////////
  193. friend class CCallback; //handling players actions
  194. friend class CBattleCallback; //handling players actions
  195. int sendRequest(const CPack *request, PlayerColor player); //returns ID given to that request
  196. void handlePack( CPack * pack ); //applies the given pack and deletes it
  197. void battleStarted(const BattleInfo * info);
  198. void commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt); //will be called as separate thread
  199. void commitPackage(CPackForClient *pack) override;
  200. //////////////////////////////////////////////////////////////////////////
  201. void serialize(COSer &h, const int version);
  202. void serialize(CISer &h, const int version);
  203. void serialize(COSer &h, const int version, const std::set<PlayerColor>& playerIDs);
  204. void serialize(CISer &h, const int version, const std::set<PlayerColor>& playerIDs);
  205. void battleFinished();
  206. };