Client.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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<PlayerColor,shared_ptr<CCallback> > callbacks; //callbacks given to player interfaces
  99. std::map<PlayerColor,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<PlayerColor,CGameInterface *> playerint;
  103. std::map<PlayerColor,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(PlayerColor 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 campaignMapFinished( shared_ptr<CCampaignState> camp );
  127. void finishCampaign( shared_ptr<CCampaignState> camp );
  128. void proposeNextMission(shared_ptr<CCampaignState> camp);
  129. 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
  130. void calculatePaths(const CGHeroInstance *h);
  131. void updatePaths(); //calls calculatePaths for same hero for which we previously calculated paths
  132. bool terminate; // tell to terminate
  133. boost::thread *connectionHandler; //thread running run() method
  134. //////////////////////////////////////////////////////////////////////////
  135. virtual PlayerColor getLocalPlayer() const OVERRIDE;
  136. //////////////////////////////////////////////////////////////////////////
  137. //not working yet, will be implement somewhen later with support for local-sim-based gameplay
  138. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) OVERRIDE {};
  139. bool removeObject(const CGObjectInstance * obj) OVERRIDE {return false;};
  140. void setBlockVis(ObjectInstanceID objid, bool bv) OVERRIDE {};
  141. void setOwner(const CGObjectInstance * obj, PlayerColor owner) OVERRIDE {};
  142. void setHoverName(const CGObjectInstance * obj, MetaString * name) OVERRIDE {};
  143. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) OVERRIDE {};
  144. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) OVERRIDE {};
  145. void showBlockingDialog(BlockingDialog *iw, const CFunctionList<void(ui32)> &callback) OVERRIDE {};
  146. ui32 showBlockingDialog(BlockingDialog *iw) OVERRIDE {return 0;}; //synchronous version of above
  147. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits, const boost::function<void()> &cb) OVERRIDE {};
  148. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) OVERRIDE {};
  149. void giveResource(PlayerColor player, Res::ERes which, int val) OVERRIDE {};
  150. void giveCreatures(const CArmedInstance * objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) OVERRIDE {};
  151. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) OVERRIDE {};
  152. bool changeStackType(const StackLocation &sl, CCreature *c) OVERRIDE {return false;};
  153. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) OVERRIDE {return false;};
  154. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) OVERRIDE {return false;};
  155. bool eraseStack(const StackLocation &sl, bool forceRemoval = false){return false;};
  156. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) OVERRIDE {return false;}
  157. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) OVERRIDE {return false;}
  158. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) OVERRIDE {}
  159. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) OVERRIDE {return false;}
  160. void giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition pos) OVERRIDE {};
  161. void giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition pos) OVERRIDE {};
  162. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) OVERRIDE {};
  163. void removeArtifact(const ArtifactLocation &al) OVERRIDE {};
  164. bool moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2) OVERRIDE {return false;};
  165. void synchronizeArtifactHandlerLists() OVERRIDE {};
  166. void showCompInfo(ShowInInfobox * comp) OVERRIDE {};
  167. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) OVERRIDE {};
  168. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) OVERRIDE {};
  169. //void giveHeroArtifact(int artid, int hid, int position){};
  170. //void giveNewArtifact(int hid, int position){};
  171. 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
  172. 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
  173. 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
  174. void setAmount(ObjectInstanceID objid, ui32 val) OVERRIDE {};
  175. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 instant, PlayerColor asker = PlayerColor::NEUTRAL) OVERRIDE {return false;};
  176. void giveHeroBonus(GiveBonus * bonus) OVERRIDE {};
  177. void setMovePoints(SetMovePoints * smp) OVERRIDE {};
  178. void setManaPoints(ObjectInstanceID hid, int val) OVERRIDE {};
  179. void giveHero(ObjectInstanceID id, PlayerColor player) OVERRIDE {};
  180. void changeObjPos(ObjectInstanceID objid, int3 newPos, ui8 flags) OVERRIDE {};
  181. void sendAndApply(CPackForClient * info) OVERRIDE {};
  182. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) OVERRIDE {};
  183. //////////////////////////////////////////////////////////////////////////
  184. friend class CCallback; //handling players actions
  185. friend class CBattleCallback; //handling players actions
  186. friend void processCommand(const std::string &message, CClient *&client); //handling console
  187. int sendRequest(const CPack *request, PlayerColor player); //returns ID given to that request
  188. void handlePack( CPack * pack ); //applies the given pack and deletes it
  189. void battleStarted(const BattleInfo * info);
  190. void commenceTacticPhaseForInt(CBattleGameInterface *battleInt); //will be called as separate thread
  191. void commitPackage(CPackForClient *pack) OVERRIDE;
  192. //////////////////////////////////////////////////////////////////////////
  193. template <typename Handler> void serialize(Handler &h, const int version);
  194. void battleFinished();
  195. };