Connection.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "../Container/HashSet.h"
  24. #include "../Core/Object.h"
  25. #include "../Core/Timer.h"
  26. #include "../Input/Controls.h"
  27. #include "../IO/VectorBuffer.h"
  28. #include "../Scene/ReplicationState.h"
  29. // ATOMIC BEGIN
  30. #include <kNet/include/kNetFwd.h>
  31. #include <kNet/include/kNet/SharedPtr.h>
  32. // ATOMIC END
  33. #ifdef SendMessage
  34. #undef SendMessage
  35. #endif
  36. namespace Atomic
  37. {
  38. class File;
  39. class MemoryBuffer;
  40. class Node;
  41. class Scene;
  42. class Serializable;
  43. class PackageFile;
  44. /// Queued remote event.
  45. struct RemoteEvent
  46. {
  47. /// Remote sender node ID (0 if not a remote node event.)
  48. unsigned senderID_;
  49. /// Event type.
  50. StringHash eventType_;
  51. /// Event data.
  52. VariantMap eventData_;
  53. /// In order flag.
  54. bool inOrder_;
  55. };
  56. /// Package file receive transfer.
  57. struct PackageDownload
  58. {
  59. /// Construct with defaults.
  60. PackageDownload();
  61. /// Destination file.
  62. SharedPtr<File> file_;
  63. /// Already received fragments.
  64. HashSet<unsigned> receivedFragments_;
  65. /// Package name.
  66. String name_;
  67. /// Total number of fragments.
  68. unsigned totalFragments_;
  69. /// Checksum.
  70. unsigned checksum_;
  71. /// Download initiated flag.
  72. bool initiated_;
  73. };
  74. /// Package file send transfer.
  75. struct PackageUpload
  76. {
  77. /// Construct with defaults.
  78. PackageUpload();
  79. /// Source file.
  80. SharedPtr<File> file_;
  81. /// Current fragment index.
  82. unsigned fragment_;
  83. /// Total number of fragments
  84. unsigned totalFragments_;
  85. };
  86. /// Send modes for observer position/rotation. Activated by the client setting either position or rotation.
  87. enum ObserverPositionSendMode
  88. {
  89. OPSM_NONE = 0,
  90. OPSM_POSITION,
  91. OPSM_POSITION_ROTATION
  92. };
  93. /// %Connection to a remote network host.
  94. class ATOMIC_API Connection : public Object
  95. {
  96. ATOMIC_OBJECT(Connection, Object);
  97. public:
  98. // ATOMIC BEGIN
  99. Connection(Context* context);
  100. // ATOMIC END
  101. /// Construct with context and kNet message connection pointers.
  102. Connection(Context* context, bool isClient, kNet::SharedPtr<kNet::MessageConnection> connection);
  103. /// Destruct.
  104. ~Connection();
  105. /// Send a message.
  106. void SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID = 0);
  107. /// Send a message.
  108. void SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes, unsigned contentID = 0);
  109. /// Send a remote event.
  110. void SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  111. /// Send a remote event with the specified node as sender.
  112. void SendRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  113. /// Assign scene. On the server, this will cause the client to load it.
  114. void SetScene(Scene* newScene);
  115. /// Assign identity. Called by Network.
  116. void SetIdentity(const VariantMap& identity);
  117. /// Set new controls.
  118. void SetControls(const Controls& newControls);
  119. /// Set the observer position for interest management, to be sent to the server.
  120. void SetPosition(const Vector3& position);
  121. /// Set the observer rotation for interest management, to be sent to the server. Note: not used by the NetworkPriority component.
  122. void SetRotation(const Quaternion& rotation);
  123. /// Set the connection pending status. Called by Network.
  124. void SetConnectPending(bool connectPending);
  125. /// Set whether to log data in/out statistics.
  126. void SetLogStatistics(bool enable);
  127. /// Disconnect. If wait time is non-zero, will block while waiting for disconnect to finish.
  128. void Disconnect(int waitMSec = 0);
  129. /// Send scene update messages. Called by Network.
  130. void SendServerUpdate();
  131. /// Send latest controls from the client. Called by Network.
  132. void SendClientUpdate();
  133. /// Send queued remote events. Called by Network.
  134. void SendRemoteEvents();
  135. /// Send package files to client. Called by network.
  136. void SendPackages();
  137. /// Process pending latest data for nodes and components.
  138. void ProcessPendingLatestData();
  139. /// Process a message from the server or client. Called by Network.
  140. bool ProcessMessage(int msgID, MemoryBuffer& msg);
  141. /// Return the kNet message connection.
  142. kNet::MessageConnection* GetMessageConnection() const;
  143. /// Return client identity.
  144. VariantMap& GetIdentity() { return identity_; }
  145. /// Return the scene used by this connection.
  146. Scene* GetScene() const;
  147. /// Return the client controls of this connection.
  148. const Controls& GetControls() const { return controls_; }
  149. /// Return the controls timestamp, sent from client to server along each control update.
  150. unsigned char GetTimeStamp() const { return timeStamp_; }
  151. /// Return the observer position sent by the client for interest management.
  152. const Vector3& GetPosition() const { return position_; }
  153. /// Return the observer rotation sent by the client for interest management.
  154. const Quaternion& GetRotation() const { return rotation_; }
  155. /// Return whether is a client connection.
  156. bool IsClient() const { return isClient_; }
  157. /// Return whether is fully connected.
  158. bool IsConnected() const;
  159. /// Return whether connection is pending.
  160. bool IsConnectPending() const { return connectPending_; }
  161. /// Return whether the scene is loaded and ready to receive server updates.
  162. bool IsSceneLoaded() const { return sceneLoaded_; }
  163. /// Return whether to log data in/out statistics.
  164. bool GetLogStatistics() const { return logStatistics_; }
  165. /// Return remote address.
  166. String GetAddress() const { return address_; }
  167. /// Return remote port.
  168. unsigned short GetPort() const { return port_; }
  169. /// Return the connection's round trip time in milliseconds.
  170. float GetRoundTripTime() const;
  171. /// Return the time since last received data from the remote host in milliseconds.
  172. float GetLastHeardTime() const;
  173. /// Return bytes received per second.
  174. float GetBytesInPerSec() const;
  175. /// Return bytes sent per second.
  176. float GetBytesOutPerSec() const;
  177. /// Return packets received per second.
  178. float GetPacketsInPerSec() const;
  179. /// Return packets sent per second.
  180. float GetPacketsOutPerSec() const;
  181. /// Return an address:port string.
  182. String ToString() const;
  183. /// Return number of package downloads remaining.
  184. unsigned GetNumDownloads() const;
  185. /// Return name of current package download, or empty if no downloads.
  186. const String& GetDownloadName() const;
  187. /// Return progress of current package download, or 1.0 if no downloads.
  188. float GetDownloadProgress() const;
  189. /// Trigger client connection to download a package file from the server. Can be used to download additional resource packages when client is already joined in a scene. The package must have been added as a requirement to the scene the client is joined in, or else the eventual download will fail.
  190. void SendPackageToClient(PackageFile* package);
  191. /// Set network simulation parameters. Called by Network.
  192. void ConfigureNetworkSimulator(int latencyMs, float packetLoss);
  193. /// Current controls.
  194. Controls controls_;
  195. /// Controls timestamp. Incremented after each sent update.
  196. unsigned char timeStamp_;
  197. /// Identity map.
  198. VariantMap identity_;
  199. // ATOMIC BEGIN
  200. /// Expose control methods for current controls
  201. void SetControlButtons(unsigned buttons, bool down = true);
  202. /// Check if a button is held down.
  203. bool IsControlButtonDown(unsigned button) const;
  204. void SetControlDataInt(const String& key, int value);
  205. int GetControlDataInt(const String& key);
  206. /// Send a message.
  207. void SendStringMessage(const String& message);
  208. // ATOMIC END
  209. private:
  210. /// Handle scene loaded event.
  211. void HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData);
  212. /// Process a LoadScene message from the server. Called by Network.
  213. void ProcessLoadScene(int msgID, MemoryBuffer& msg);
  214. /// Process a SceneChecksumError message from the server. Called by Network.
  215. void ProcessSceneChecksumError(int msgID, MemoryBuffer& msg);
  216. /// Process a scene update message from the server. Called by Network.
  217. void ProcessSceneUpdate(int msgID, MemoryBuffer& msg);
  218. /// Process package download related messages. Called by Network.
  219. void ProcessPackageDownload(int msgID, MemoryBuffer& msg);
  220. /// Process an Identity message from the client. Called by Network.
  221. void ProcessIdentity(int msgID, MemoryBuffer& msg);
  222. /// Process a Controls message from the client. Called by Network.
  223. void ProcessControls(int msgID, MemoryBuffer& msg);
  224. /// Process a SceneLoaded message from the client. Called by Network.
  225. void ProcessSceneLoaded(int msgID, MemoryBuffer& msg);
  226. /// Process a remote event message from the client or server. Called by Network.
  227. void ProcessRemoteEvent(int msgID, MemoryBuffer& msg);
  228. /// Process a node for sending a network update. Recurses to process depended on node(s) first.
  229. void ProcessNode(unsigned nodeID);
  230. /// Process a node that the client has not yet received.
  231. void ProcessNewNode(Node* node);
  232. /// Process a node that the client has already received.
  233. void ProcessExistingNode(Node* node, NodeReplicationState& nodeState);
  234. /// Process a SyncPackagesInfo message from server.
  235. void ProcessPackageInfo(int msgID, MemoryBuffer& msg);
  236. /// Check a package list received from server and initiate package downloads as necessary. Return true on success, or false if failed to initialze downloads (cache dir not set)
  237. bool RequestNeededPackages(unsigned numPackages, MemoryBuffer& msg);
  238. /// Initiate a package download.
  239. void RequestPackage(const String& name, unsigned fileSize, unsigned checksum);
  240. /// Send an error reply for a package download.
  241. void SendPackageError(const String& name);
  242. /// Handle scene load failure on the server or client.
  243. void OnSceneLoadFailed();
  244. /// Handle a package download failure on the client.
  245. void OnPackageDownloadFailed(const String& name);
  246. /// Handle all packages loaded successfully. Also called directly on MSG_LOADSCENE if there are none.
  247. void OnPackagesReady();
  248. // ATOMIC BEGIN
  249. void ProcessStringMessage(int msgID, MemoryBuffer& msg);
  250. void HandleComponentRemoved(StringHash eventType, VariantMap& eventData);
  251. // ATOMIC END
  252. /// kNet message connection.
  253. kNet::SharedPtr<kNet::MessageConnection> connection_;
  254. /// Scene.
  255. WeakPtr<Scene> scene_;
  256. /// Network replication state of the scene.
  257. SceneReplicationState sceneState_;
  258. /// Waiting or ongoing package file receive transfers.
  259. HashMap<StringHash, PackageDownload> downloads_;
  260. /// Ongoing package send transfers.
  261. HashMap<StringHash, PackageUpload> uploads_;
  262. /// Pending latest data for not yet received nodes.
  263. HashMap<unsigned, PODVector<unsigned char> > nodeLatestData_;
  264. /// Pending latest data for not yet received components.
  265. HashMap<unsigned, PODVector<unsigned char> > componentLatestData_;
  266. /// Node ID's to process during a replication update.
  267. HashSet<unsigned> nodesToProcess_;
  268. /// Reusable message buffer.
  269. VectorBuffer msg_;
  270. /// Queued remote events.
  271. Vector<RemoteEvent> remoteEvents_;
  272. /// Scene file to load once all packages (if any) have been downloaded.
  273. String sceneFileName_;
  274. /// Statistics timer.
  275. Timer statsTimer_;
  276. /// Remote endpoint address.
  277. String address_;
  278. /// Remote endpoint port.
  279. unsigned short port_;
  280. /// Observer position for interest management.
  281. Vector3 position_;
  282. /// Observer rotation for interest management.
  283. Quaternion rotation_;
  284. /// Send mode for the observer position & rotation.
  285. ObserverPositionSendMode sendMode_;
  286. /// Client connection flag.
  287. bool isClient_;
  288. /// Connection pending flag.
  289. bool connectPending_;
  290. /// Scene loaded flag.
  291. bool sceneLoaded_;
  292. /// Show statistics flag.
  293. bool logStatistics_;
  294. };
  295. }