Connection.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. /// \file
  4. #pragma once
  5. #include "../Container/HashSet.h"
  6. #include "../Core/Object.h"
  7. #include "../Core/Timer.h"
  8. #include "../Input/Controls.h"
  9. #include "../IO/VectorBuffer.h"
  10. #include "../Scene/ReplicationState.h"
  11. namespace SLNet
  12. {
  13. class SystemAddress;
  14. struct AddressOrGUID;
  15. struct RakNetGUID;
  16. struct Packet;
  17. class NatPunchthroughClient;
  18. class RakPeerInterface;
  19. }
  20. namespace Urho3D
  21. {
  22. class File;
  23. class MemoryBuffer;
  24. class Node;
  25. class Scene;
  26. class Serializable;
  27. class PackageFile;
  28. /// Queued remote event.
  29. struct RemoteEvent
  30. {
  31. /// Remote sender node ID (0 if not a remote node event).
  32. unsigned senderID_;
  33. /// Event type.
  34. StringHash eventType_;
  35. /// Event data.
  36. VariantMap eventData_;
  37. /// In order flag.
  38. bool inOrder_;
  39. };
  40. /// Package file receive transfer.
  41. struct PackageDownload
  42. {
  43. /// Construct with defaults.
  44. PackageDownload();
  45. /// Destination file.
  46. SharedPtr<File> file_;
  47. /// Already received fragments.
  48. HashSet<unsigned> receivedFragments_;
  49. /// Package name.
  50. String name_;
  51. /// Total number of fragments.
  52. unsigned totalFragments_;
  53. /// Checksum.
  54. unsigned checksum_;
  55. /// Download initiated flag.
  56. bool initiated_;
  57. };
  58. /// Package file send transfer.
  59. struct PackageUpload
  60. {
  61. /// Construct with defaults.
  62. PackageUpload();
  63. /// Source file.
  64. SharedPtr<File> file_;
  65. /// Current fragment index.
  66. unsigned fragment_;
  67. /// Total number of fragments.
  68. unsigned totalFragments_;
  69. };
  70. /// Send modes for observer position/rotation. Activated by the client setting either position or rotation.
  71. enum ObserverPositionSendMode
  72. {
  73. OPSM_NONE = 0,
  74. OPSM_POSITION,
  75. OPSM_POSITION_ROTATION
  76. };
  77. /// Packet types for outgoing buffers. Outgoing messages are grouped by their type
  78. enum PacketType {
  79. PT_UNRELIABLE_UNORDERED,
  80. PT_UNRELIABLE_ORDERED,
  81. PT_RELIABLE_UNORDERED,
  82. PT_RELIABLE_ORDERED
  83. };
  84. /// %Connection to a remote network host.
  85. class URHO3D_API Connection : public Object
  86. {
  87. URHO3D_OBJECT(Connection, Object);
  88. public:
  89. /// Construct with context, RakNet connection address and Raknet peer pointer.
  90. Connection(Context* context, bool isClient, const SLNet::AddressOrGUID& address, SLNet::RakPeerInterface* peer);
  91. /// Destruct.
  92. ~Connection() override;
  93. /// Get packet type based on the message parameters
  94. PacketType GetPacketType(bool reliable, bool inOrder);
  95. /// Send a message.
  96. void SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID = 0);
  97. /// Send a message.
  98. void SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes, unsigned contentID = 0);
  99. /// Send a remote event.
  100. void SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  101. /// Send a remote event with the specified node as sender.
  102. void SendRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  103. /// Assign scene. On the server, this will cause the client to load it.
  104. /// @property
  105. void SetScene(Scene* newScene);
  106. /// Assign identity. Called by Network.
  107. void SetIdentity(const VariantMap& identity);
  108. /// Set new controls.
  109. void SetControls(const Controls& newControls);
  110. /// Set the observer position for interest management, to be sent to the server.
  111. /// @property
  112. void SetPosition(const Vector3& position);
  113. /// Set the observer rotation for interest management, to be sent to the server. Note: not used by the NetworkPriority component.
  114. /// @property
  115. void SetRotation(const Quaternion& rotation);
  116. /// Set the connection pending status. Called by Network.
  117. void SetConnectPending(bool connectPending);
  118. /// Set whether to log data in/out statistics.
  119. /// @property
  120. void SetLogStatistics(bool enable);
  121. /// Disconnect. If wait time is non-zero, will block while waiting for disconnect to finish.
  122. void Disconnect(int waitMSec = 0);
  123. /// Send scene update messages. Called by Network.
  124. void SendServerUpdate();
  125. /// Send latest controls from the client. Called by Network.
  126. void SendClientUpdate();
  127. /// Send queued remote events. Called by Network.
  128. void SendRemoteEvents();
  129. /// Send package files to client. Called by network.
  130. void SendPackages();
  131. /// Send out buffered messages by their type
  132. void SendBuffer(PacketType type);
  133. /// Send out all buffered messages
  134. void SendAllBuffers();
  135. /// Process pending latest data for nodes and components.
  136. void ProcessPendingLatestData();
  137. /// Process a message from the server or client. Called by Network.
  138. bool ProcessMessage(int msgID, MemoryBuffer& buffer);
  139. /// Ban this connections IP address.
  140. void Ban();
  141. /// Return the RakNet address/guid.
  142. const SLNet::AddressOrGUID& GetAddressOrGUID() const { return *address_; }
  143. /// Set the the RakNet address/guid.
  144. void SetAddressOrGUID(const SLNet::AddressOrGUID& addr);
  145. /// Return client identity.
  146. VariantMap& GetIdentity() { return identity_; }
  147. /// Return the scene used by this connection.
  148. /// @property
  149. Scene* GetScene() const;
  150. /// Return the client controls of this connection.
  151. const Controls& GetControls() const { return controls_; }
  152. /// Return the controls timestamp, sent from client to server along each control update.
  153. unsigned char GetTimeStamp() const { return timeStamp_; }
  154. /// Return the observer position sent by the client for interest management.
  155. /// @property
  156. const Vector3& GetPosition() const { return position_; }
  157. /// Return the observer rotation sent by the client for interest management.
  158. /// @property
  159. const Quaternion& GetRotation() const { return rotation_; }
  160. /// Return whether is a client connection.
  161. /// @property
  162. bool IsClient() const { return isClient_; }
  163. /// Return whether is fully connected.
  164. /// @property
  165. bool IsConnected() const;
  166. /// Return whether connection is pending.
  167. /// @property
  168. bool IsConnectPending() const { return connectPending_; }
  169. /// Return whether the scene is loaded and ready to receive server updates.
  170. /// @property
  171. bool IsSceneLoaded() const { return sceneLoaded_; }
  172. /// Return whether to log data in/out statistics.
  173. /// @property
  174. bool GetLogStatistics() const { return logStatistics_; }
  175. /// Return remote address.
  176. /// @property
  177. String GetAddress() const;
  178. /// Return remote port.
  179. /// @property
  180. unsigned short GetPort() const { return port_; }
  181. /// Return the connection's round trip time in milliseconds.
  182. /// @property
  183. float GetRoundTripTime() const;
  184. /// Return the time since last received data from the remote host in milliseconds.
  185. /// @property
  186. unsigned GetLastHeardTime() const;
  187. /// Return bytes received per second.
  188. /// @property
  189. float GetBytesInPerSec() const;
  190. /// Return bytes sent per second.
  191. /// @property
  192. float GetBytesOutPerSec() const;
  193. /// Return packets received per second.
  194. /// @property
  195. int GetPacketsInPerSec() const;
  196. /// Return packets sent per second.
  197. /// @property
  198. int GetPacketsOutPerSec() const;
  199. /// Return an address:port string.
  200. String ToString() const;
  201. /// Return number of package downloads remaining.
  202. /// @property
  203. unsigned GetNumDownloads() const;
  204. /// Return name of current package download, or empty if no downloads.
  205. /// @property
  206. const String& GetDownloadName() const;
  207. /// Return progress of current package download, or 1.0 if no downloads.
  208. /// @property
  209. float GetDownloadProgress() const;
  210. /// 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.
  211. void SendPackageToClient(PackageFile* package);
  212. /// Set network simulation parameters. Called by Network.
  213. void ConfigureNetworkSimulator(int latencyMs, float packetLoss);
  214. /// Buffered packet size limit, when reached, packet is sent out immediately
  215. void SetPacketSizeLimit(int limit);
  216. /// Current controls.
  217. Controls controls_;
  218. /// Controls timestamp. Incremented after each sent update.
  219. unsigned char timeStamp_;
  220. /// Identity map.
  221. VariantMap identity_;
  222. private:
  223. /// Handle scene loaded event.
  224. void HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData);
  225. /// Process a LoadScene message from the server. Called by Network.
  226. void ProcessLoadScene(int msgID, MemoryBuffer& msg);
  227. /// Process a SceneChecksumError message from the server. Called by Network.
  228. void ProcessSceneChecksumError(int msgID, MemoryBuffer& msg);
  229. /// Process a scene update message from the server. Called by Network.
  230. void ProcessSceneUpdate(int msgID, MemoryBuffer& msg);
  231. /// Process package download related messages. Called by Network.
  232. void ProcessPackageDownload(int msgID, MemoryBuffer& msg);
  233. /// Process an Identity message from the client. Called by Network.
  234. void ProcessIdentity(int msgID, MemoryBuffer& msg);
  235. /// Process a Controls message from the client. Called by Network.
  236. void ProcessControls(int msgID, MemoryBuffer& msg);
  237. /// Process a SceneLoaded message from the client. Called by Network.
  238. void ProcessSceneLoaded(int msgID, MemoryBuffer& msg);
  239. /// Process a remote event message from the client or server. Called by Network.
  240. void ProcessRemoteEvent(int msgID, MemoryBuffer& msg);
  241. /// Process a node for sending a network update. Recurses to process depended on node(s) first.
  242. void ProcessNode(unsigned nodeID);
  243. /// Process a node that the client has not yet received.
  244. void ProcessNewNode(Node* node);
  245. /// Process a node that the client has already received.
  246. void ProcessExistingNode(Node* node, NodeReplicationState& nodeState);
  247. /// Process a SyncPackagesInfo message from server.
  248. void ProcessPackageInfo(int msgID, MemoryBuffer& msg);
  249. /// Process unknown message. All unknown messages are forwarded as an events
  250. void ProcessUnknownMessage(int msgID, MemoryBuffer& msg);
  251. /// 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).
  252. bool RequestNeededPackages(unsigned numPackages, MemoryBuffer& msg);
  253. /// Initiate a package download.
  254. void RequestPackage(const String& name, unsigned fileSize, unsigned checksum);
  255. /// Send an error reply for a package download.
  256. void SendPackageError(const String& name);
  257. /// Handle scene load failure on the server or client.
  258. void OnSceneLoadFailed();
  259. /// Handle a package download failure on the client.
  260. void OnPackageDownloadFailed(const String& name);
  261. /// Handle all packages loaded successfully. Also called directly on MSG_LOADSCENE if there are none.
  262. void OnPackagesReady();
  263. /// Scene.
  264. WeakPtr<Scene> scene_;
  265. /// Network replication state of the scene.
  266. SceneReplicationState sceneState_;
  267. /// Waiting or ongoing package file receive transfers.
  268. HashMap<StringHash, PackageDownload> downloads_;
  269. /// Ongoing package send transfers.
  270. HashMap<StringHash, PackageUpload> uploads_;
  271. /// Pending latest data for not yet received nodes.
  272. HashMap<unsigned, PODVector<unsigned char>> nodeLatestData_;
  273. /// Pending latest data for not yet received components.
  274. HashMap<unsigned, PODVector<unsigned char>> componentLatestData_;
  275. /// Node ID's to process during a replication update.
  276. HashSet<unsigned> nodesToProcess_;
  277. /// Reusable message buffer.
  278. VectorBuffer msg_;
  279. /// Queued remote events.
  280. Vector<RemoteEvent> remoteEvents_;
  281. /// Scene file to load once all packages (if any) have been downloaded.
  282. String sceneFileName_;
  283. /// Statistics timer.
  284. Timer statsTimer_;
  285. /// Remote endpoint port.
  286. unsigned short port_;
  287. /// Observer position for interest management.
  288. Vector3 position_;
  289. /// Observer rotation for interest management.
  290. Quaternion rotation_;
  291. /// Send mode for the observer position & rotation.
  292. ObserverPositionSendMode sendMode_;
  293. /// Client connection flag.
  294. bool isClient_;
  295. /// Connection pending flag.
  296. bool connectPending_;
  297. /// Scene loaded flag.
  298. bool sceneLoaded_;
  299. /// Show statistics flag.
  300. bool logStatistics_;
  301. /// Address of this connection.
  302. SLNet::AddressOrGUID* address_;
  303. /// Raknet peer object.
  304. SLNet::RakPeerInterface* peer_;
  305. /// Temporary variable to hold packet count in the next second, x - packets in, y - packets out.
  306. IntVector2 tempPacketCounter_;
  307. /// Packet count in the last second, x - packets in, y - packets out.
  308. IntVector2 packetCounter_;
  309. /// Packet count timer which resets every 1s.
  310. Timer packetCounterTimer_;
  311. /// Last heard timer, resets when new packet is incoming.
  312. Timer lastHeardTimer_;
  313. /// Outgoing packet buffer which can contain multiple messages
  314. HashMap<int, VectorBuffer> outgoingBuffer_;
  315. /// Outgoing packet size limit
  316. int packedMessageLimit_;
  317. };
  318. }