Connection.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #pragma once
  24. #include "Controls.h"
  25. #include "HashMap.h"
  26. #include "HashSet.h"
  27. #include "Object.h"
  28. #include "ReplicationState.h"
  29. #include "Timer.h"
  30. #include "VectorBuffer.h"
  31. #include <kNetFwd.h>
  32. #include <kNet/SharedPtr.h>
  33. #ifdef SendMessage
  34. #undef SendMessage
  35. #endif
  36. class File;
  37. class MemoryBuffer;
  38. class Node;
  39. class Scene;
  40. class Serializable;
  41. /// Queued remote event.
  42. struct RemoteEvent
  43. {
  44. /// Receiver node ID (0 if not a remote node event.)
  45. unsigned receiverID_;
  46. /// Event type.
  47. StringHash eventType_;
  48. /// Event data.
  49. VariantMap eventData_;
  50. /// In order flag.
  51. bool inOrder_;
  52. };
  53. /// Package file receive transfer.
  54. struct PackageDownload
  55. {
  56. /// Construct with defaults.
  57. PackageDownload();
  58. /// Destination file.
  59. SharedPtr<File> file_;
  60. /// Already received fragments.
  61. HashSet<unsigned> receivedFragments_;
  62. /// Package name.
  63. String name_;
  64. /// Total number of fragments.
  65. unsigned totalFragments_;
  66. /// Checksum.
  67. unsigned checksum_;
  68. /// Download initiated flag.
  69. bool initiated_;
  70. };
  71. /// Package file send transfer.
  72. struct PackageUpload
  73. {
  74. /// Construct with defaults.
  75. PackageUpload();
  76. /// Source file.
  77. SharedPtr<File> file_;
  78. /// Current fragment index.
  79. unsigned fragment_;
  80. /// Total number of fragments
  81. unsigned totalFragments_;
  82. };
  83. /// %Connection to a remote network host.
  84. class Connection : public Object
  85. {
  86. OBJECT(Connection);
  87. public:
  88. /// Construct with context and kNet message connection pointers.
  89. Connection(Context* context, bool isClient, kNet::SharedPtr<kNet::MessageConnection> connection);
  90. /// Destruct.
  91. ~Connection();
  92. /// Send a message.
  93. void SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned priority = 0, unsigned contentID = 0);
  94. /// Send a message.
  95. void SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes, unsigned priority = 0, unsigned contentID = 0);
  96. /// Send a remote event.
  97. void SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData = VariantMap());
  98. /// Send a remote node event.
  99. void SendRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData = VariantMap());
  100. /// Assign scene. On the server, this will cause the client to load it.
  101. void SetScene(Scene* newScene);
  102. /// Assign identity. Called by Network.
  103. void SetIdentity(const VariantMap& identity);
  104. /// %Set new controls.
  105. void SetControls(const Controls& newControls);
  106. /// %Set the observer position for interest management.
  107. void SetPosition(const Vector3& position);
  108. /// %Set the connection pending status. Called by Network.
  109. void SetConnectPending(bool connectPending);
  110. /// %Set whether to log data in/out statistics.
  111. void SetLogStatistics(bool enable);
  112. /// Disconnect. If wait time is non-zero, will block while waiting for disconnect to finish.
  113. void Disconnect(int waitMSec = 0);
  114. /// Send scene update messages. Called by Network.
  115. void SendServerUpdate();
  116. /// Send latest controls from the client. Called by Network.
  117. void SendClientUpdate();
  118. /// Send queued remote events. Called by Network.
  119. void SendRemoteEvents();
  120. /// Send package files to client. Called by network.
  121. void SendPackages();
  122. /// Process pending latest data for nodes and components.
  123. void ProcessPendingLatestData();
  124. /// Process a LoadScene message from the server. Called by Network.
  125. void ProcessLoadScene(int msgID, MemoryBuffer& msg);
  126. /// Process a SceneChecksumError message from the server. Called by Network.
  127. void ProcessSceneChecksumError(int msgID, MemoryBuffer& msg);
  128. /// Process a scene update message from the server. Called by Network.
  129. void ProcessSceneUpdate(int msgID, MemoryBuffer& msg);
  130. /// Process package download related messages. Called by Network.
  131. void ProcessPackageDownload(int msgID, MemoryBuffer& msg);
  132. /// Process an Identity message from the client. Called by Network.
  133. void ProcessIdentity(int msgID, MemoryBuffer& msg);
  134. /// Process a Controls message from the client. Called by Network.
  135. void ProcessControls(int msgID, MemoryBuffer& msg);
  136. /// Process a SceneLoaded message from the client. Called by Network.
  137. void ProcessSceneLoaded(int msgID, MemoryBuffer& msg);
  138. /// Process a remote event message from the client or server. Called by Network.
  139. void ProcessRemoteEvent(int msgID, MemoryBuffer& msg);
  140. /// Return the kNet message connection.
  141. kNet::MessageConnection* GetMessageConnection() const;
  142. /// Return client identity.
  143. const VariantMap& GetIdentity() const { return identity_; }
  144. /// Return the scene used by this connection.
  145. Scene* GetScene() const;
  146. /// Return the client controls of this connection.
  147. const Controls& GetControls() const { return controls_; }
  148. /// Return the observer position for interest management.
  149. const Vector3& GetPosition() const { return position_; }
  150. /// Return whether is a client connection.
  151. bool IsClient() const { return isClient_; }
  152. /// Return whether is fully connected.
  153. bool IsConnected() const;
  154. /// Return whether connection is pending.
  155. bool IsConnectPending() const { return connectPending_; }
  156. /// Return whether the scene is loaded and ready to receive server updates.
  157. bool IsSceneLoaded() const { return sceneLoaded_; }
  158. /// Return whether to log data in/out statistics.
  159. bool GetLogStatistics() const { return logStatistics_; }
  160. /// Return remote address.
  161. String GetAddress() const;
  162. /// Return remote port.
  163. unsigned short GetPort() const;
  164. /// Return an address:port string.
  165. String ToString() const;
  166. /// Return number of package downloads remaining.
  167. unsigned GetNumDownloads() const;
  168. /// Return name of current package download, or empty if no downloads.
  169. const String& GetDownloadName() const;
  170. /// Return progress of current package download, or 1.0 if no downloads.
  171. float GetDownloadProgress() const;
  172. /// Observer position for interest management.
  173. Vector3 position_;
  174. /// Current controls.
  175. Controls controls_;
  176. /// Identity map.
  177. VariantMap identity_;
  178. private:
  179. /// Handle scene loaded event.
  180. void HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData);
  181. /// Process a node for sending a network update. Recurses to process depended on node(s) first.
  182. void ProcessNode(Node* node);
  183. /// Process a node that the client had not yet received.
  184. void ProcessNewNode(Node* node);
  185. /// Process a node that the client has already received.
  186. void ProcessExistingNode(Node* node);
  187. /// Initiate a package download.
  188. void RequestPackage(const String& name, unsigned fileSize, unsigned checksum);
  189. /// Send an error reply for a package download.
  190. void SendPackageError(const String& name);
  191. /// Handle scene load failure on the server or client.
  192. void OnSceneLoadFailed();
  193. /// Handle a package download failure on the client.
  194. void OnPackageDownloadFailed(const String& name);
  195. /// Handle all packages loaded successfully. Also called directly on MSG_LOADSCENE if there are none.
  196. void OnPackagesReady();
  197. /// kNet message connection.
  198. kNet::SharedPtr<kNet::MessageConnection> connection_;
  199. /// Scene.
  200. WeakPtr<Scene> scene_;
  201. /// Last sent state of the scene for network replication.
  202. Map<unsigned, NodeReplicationState> sceneState_;
  203. /// Preallocated attribute variants per networked object class for sending updates.
  204. Map<ShortStringHash, Vector<Variant> > classCurrentState_;
  205. /// Waiting or ongoing package file receive transfers.
  206. Map<StringHash, PackageDownload> downloads_;
  207. /// Ongoing package send transfers.
  208. Map<StringHash, PackageUpload> uploads_;
  209. /// Pending latest data for not yet received nodes.
  210. HashMap<unsigned, PODVector<unsigned char> > nodeLatestData_;
  211. /// Pending latest data for not yet received components.
  212. HashMap<unsigned, PODVector<unsigned char> > componentLatestData_;
  213. /// Node's changed user variables.
  214. HashSet<ShortStringHash> changedVars_;
  215. /// Already processed nodes during a replication update.
  216. HashSet<Node*> processedNodes_;
  217. /// Reusable message buffer.
  218. VectorBuffer msg_;
  219. /// Reusable delta update bits.
  220. PODVector<unsigned char> deltaUpdateBits_;
  221. /// Queued remote events.
  222. Vector<RemoteEvent> remoteEvents_;
  223. /// Scene file to load once all packages (if any) have been downloaded.
  224. String sceneFileName_;
  225. /// Statistics timer.
  226. Timer statsTimer_;
  227. /// Update frame number.
  228. unsigned frameNumber_;
  229. /// Client connection flag.
  230. bool isClient_;
  231. /// Connection pending flag.
  232. bool connectPending_;
  233. /// Scene loaded flag.
  234. bool sceneLoaded_;
  235. /// Show statistics flag.
  236. bool logStatistics_;
  237. };