Client.h 10 KB

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