Merge pull request #50710 from Faless/enet/4.x_refactor

This commit is contained in:
Rémi Verschelde 2021-07-29 12:40:04 +02:00 committed by GitHub
commit 1c68be9c8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 2032 additions and 916 deletions

View File

@ -30,6 +30,29 @@
#include "multiplayer_peer.h"
#include "core/os/os.h"
uint32_t MultiplayerPeer::generate_unique_id() const {
uint32_t hash = 0;
while (hash == 0 || hash == 1) {
hash = hash_djb2_one_32(
(uint32_t)OS::get_singleton()->get_ticks_usec());
hash = hash_djb2_one_32(
(uint32_t)OS::get_singleton()->get_unix_time(), hash);
hash = hash_djb2_one_32(
(uint32_t)OS::get_singleton()->get_user_data_dir().hash64(), hash);
hash = hash_djb2_one_32(
(uint32_t)((uint64_t)this), hash); // Rely on ASLR heap
hash = hash_djb2_one_32(
(uint32_t)((uint64_t)&hash), hash); // Rely on ASLR stack
hash = hash & 0x7FFFFFFF; // Make it compatible with unsigned, since negative ID is used for exclusion
}
return hash;
}
void MultiplayerPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_transfer_mode", "mode"), &MultiplayerPeer::set_transfer_mode);
ClassDB::bind_method(D_METHOD("get_transfer_mode"), &MultiplayerPeer::get_transfer_mode);
@ -41,6 +64,7 @@ void MultiplayerPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_connection_status"), &MultiplayerPeer::get_connection_status);
ClassDB::bind_method(D_METHOD("get_unique_id"), &MultiplayerPeer::get_unique_id);
ClassDB::bind_method(D_METHOD("generate_unique_id"), &MultiplayerPeer::generate_unique_id);
ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "enable"), &MultiplayerPeer::set_refuse_new_connections);
ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &MultiplayerPeer::is_refusing_new_connections);

View File

@ -72,6 +72,7 @@ public:
virtual bool is_refusing_new_connections() const = 0;
virtual ConnectionStatus get_connection_status() const = 0;
uint32_t generate_unique_id() const;
MultiplayerPeer() {}
};

View File

@ -12,6 +12,13 @@
<link title="WebRTC Signaling Demo">https://godotengine.org/asset-library/asset/537</link>
</tutorials>
<methods>
<method name="generate_unique_id" qualifiers="const">
<return type="int">
</return>
<description>
Returns a randomly generated integer that can be used as a network unique ID.
</description>
</method>
<method name="get_connection_status" qualifiers="const">
<return type="int" enum="MultiplayerPeer.ConnectionStatus">
</return>

View File

@ -9,6 +9,8 @@ def configure(env):
def get_doc_classes():
return [
"ENetMultiplayerPeer",
"ENetConnection",
"ENetPacketPeer",
]

View File

@ -0,0 +1,240 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="ENetConnection" inherits="RefCounted" version="4.0">
<brief_description>
A wrapper class for an [url=http://enet.bespin.org/group__host.html]ENetHost[/url].
</brief_description>
<description>
ENet's purpose is to provide a relatively thin, simple and robust network communication layer on top of UDP (User Datagram Protocol).
</description>
<tutorials>
<link title="API documentation on the ENet website">http://enet.bespin.org/usergroup0.html</link>
</tutorials>
<methods>
<method name="bandwidth_limit">
<return type="void">
</return>
<argument index="0" name="in_bandwidth" type="int" default="0">
</argument>
<argument index="1" name="out_bandwidth" type="int" default="0">
</argument>
<description>
Adjusts the bandwidth limits of a host.
</description>
</method>
<method name="broadcast">
<return type="void">
</return>
<argument index="0" name="channel" type="int">
</argument>
<argument index="1" name="packet" type="PackedByteArray">
</argument>
<argument index="2" name="flags" type="int">
</argument>
<description>
Queues a [code]packet[/code] to be sent to all peers associated with the host over the specified [code]channel[/code]. See [ENetPacketPeer] [code]FLAG_*[/code] constants for available packet flags.
</description>
</method>
<method name="channel_limit">
<return type="void">
</return>
<argument index="0" name="limit" type="int">
</argument>
<description>
Limits the maximum allowed channels of future incoming connections.
</description>
</method>
<method name="compress">
<return type="void">
</return>
<argument index="0" name="mode" type="int" enum="ENetConnection.CompressionMode">
</argument>
<description>
Sets the compression method used for network packets. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all.
[b]Note:[/b] Most games' network design involve sending many small packets frequently (smaller than 4 KB each). If in doubt, it is recommended to keep the default compression algorithm as it works best on these small packets.
</description>
</method>
<method name="connect_to_host">
<return type="ENetPacketPeer">
</return>
<argument index="0" name="address" type="String">
</argument>
<argument index="1" name="port" type="int">
</argument>
<argument index="2" name="channels" type="int" default="0">
</argument>
<argument index="3" name="data" type="int" default="0">
</argument>
<description>
Initiates a connection to a foreign [code]address[/code] using the specified [code]port[/code] and allocting the requested [code]channels[/code]. Optional [code]data[/code] can be passed during connection in the form of a 32 bit integer.
Note: You must call either [method create_host] or [method create_host_bound] before calling this method.
</description>
</method>
<method name="create_host">
<return type="int" enum="Error">
</return>
<argument index="0" name="max_peers" type="int" default="32">
</argument>
<argument index="1" name="max_channels" type="int" default="0">
</argument>
<argument index="2" name="in_bandwidth" type="int" default="0">
</argument>
<argument index="3" name="out_bandwidth" type="int" default="0">
</argument>
<description>
Create an ENetHost that will allow up to [code]max_peers[/code] connected peers, each allocating up to [code]max_channels[/code] channels, optionally limiting bandwith to [code]in_bandwidth[/code] and [code]out_bandwidth[/code].
</description>
</method>
<method name="create_host_bound">
<return type="int" enum="Error">
</return>
<argument index="0" name="bind_address" type="String">
</argument>
<argument index="1" name="bind_port" type="int">
</argument>
<argument index="2" name="max_peers" type="int" default="32">
</argument>
<argument index="3" name="max_channels" type="int" default="0">
</argument>
<argument index="4" name="in_bandwidth" type="int" default="0">
</argument>
<argument index="5" name="out_bandwidth" type="int" default="0">
</argument>
<description>
Create an ENetHost like [method create_host] which is also bound to the given [code]bind_address[/code] and [code]bind_port[/code].
</description>
</method>
<method name="destroy">
<return type="void">
</return>
<description>
Destroys the host and all resources associated with it.
</description>
</method>
<method name="dtls_client_setup">
<return type="int" enum="Error">
</return>
<argument index="0" name="certificate" type="X509Certificate">
</argument>
<argument index="1" name="hostname" type="String">
</argument>
<argument index="2" name="verify" type="bool" default="true">
</argument>
<description>
Configure this ENetHost to use the custom Godot extension allowing DTLS encryption for ENet clients. Call this before [method connect_to_host] to have ENet connect using DTLS with [code]certificate[/code] and [code]hostname[/code] verification. Verification can be optionally turned off via the [code]verify[/code] parameter.
</description>
</method>
<method name="dtls_server_setup">
<return type="int" enum="Error">
</return>
<argument index="0" name="key" type="CryptoKey">
</argument>
<argument index="1" name="certificate" type="X509Certificate">
</argument>
<description>
Configure this ENetHost to use the custom Godot extension allowing DTLS encryption for ENet servers. Call this right after [method create_host_bound] to have ENet expect peers to connect using DTLS.
</description>
</method>
<method name="flush">
<return type="void">
</return>
<description>
Sends any queued packets on the host specified to its designated peers.
</description>
</method>
<method name="get_local_port" qualifiers="const">
<return type="int">
</return>
<description>
Returns the local port to which this peer is bound.
</description>
</method>
<method name="get_max_channels" qualifiers="const">
<return type="int">
</return>
<description>
Returns the maximum number of channels allowed for connected peers.
</description>
</method>
<method name="get_peers">
<return type="Array">
</return>
<description>
Returns the list of peers associated with this host.
Note: This list might include some peers that are not fully connected or are still being disconnected.
</description>
</method>
<method name="pop_statistic">
<return type="float">
</return>
<argument index="0" name="statistic" type="int" enum="ENetConnection.HostStatistic">
</argument>
<description>
Returns and resets host statistics. See [enum HostStatistic] for more info.
</description>
</method>
<method name="refuse_new_connections">
<return type="void">
</return>
<argument index="0" name="refuse" type="bool">
</argument>
<description>
Configures the DTLS server to automatically drop new connections.
Note: This method is only relevant after calling [method dtls_server_setup].
</description>
</method>
<method name="service">
<return type="Array">
</return>
<argument index="0" name="timeout" type="int" default="0">
</argument>
<description>
Waits for events on the host specified and shuttles packets between the host and its peers. The returned [Array] will have 4 elements. An [enum EventType], the [ENetPacketPeer] which generated the event, the event associated data (if any), the event associated channel (if any). If the generated event is [constant EVENT_RECEIVE], the received packet will be queued to the associated [ENetPacketPeer].
Call this function regularly to handle connections, disconnections, and to receive new packets.
</description>
</method>
</methods>
<constants>
<constant name="COMPRESS_NONE" value="0" enum="CompressionMode">
No compression. This uses the most bandwidth, but has the upside of requiring the fewest CPU resources. This option may also be used to make network debugging using tools like Wireshark easier.
</constant>
<constant name="COMPRESS_RANGE_CODER" value="1" enum="CompressionMode">
ENet's built-in range encoding. Works well on small packets, but is not the most efficient algorithm on packets larger than 4 KB.
</constant>
<constant name="COMPRESS_FASTLZ" value="2" enum="CompressionMode">
[url=http://fastlz.org/]FastLZ[/url] compression. This option uses less CPU resources compared to [constant COMPRESS_ZLIB], at the expense of using more bandwidth.
</constant>
<constant name="COMPRESS_ZLIB" value="3" enum="CompressionMode">
[url=https://www.zlib.net/]Zlib[/url] compression. This option uses less bandwidth compared to [constant COMPRESS_FASTLZ], at the expense of using more CPU resources.
</constant>
<constant name="COMPRESS_ZSTD" value="4" enum="CompressionMode">
[url=https://facebook.github.io/zstd/]Zstandard[/url] compression. Note that this algorithm is not very efficient on packets smaller than 4 KB. Therefore, it's recommended to use other compression algorithms in most cases.
</constant>
<constant name="EVENT_ERROR" value="-1" enum="EventType">
An error occurred during [method service]. You will likely need to [method destroy] the host and recreate it.
</constant>
<constant name="EVENT_NONE" value="0" enum="EventType">
No event occurred within the specified time limit.
</constant>
<constant name="EVENT_CONNECT" value="1" enum="EventType">
A connection request initiated by enet_host_connect has completed. The array will contain the peer which successfully connected.
</constant>
<constant name="EVENT_DISCONNECT" value="2" enum="EventType">
A peer has disconnected. This event is generated on a successful completion of a disconnect initiated by [method ENetPacketPeer.peer_disconnect], if a peer has timed out, or if a connection request intialized by [method connect_to_host] has timed out. The array will contain the peer which disconnected. The data field contains user supplied data describing the disconnection, or 0, if none is available.
</constant>
<constant name="EVENT_RECEIVE" value="3" enum="EventType">
A packet has been received from a peer. The array will contain the peer which sent the packet, the channel number upon which the packet was received, and the received packet.
</constant>
<constant name="HOST_TOTAL_SENT_DATA" value="0" enum="HostStatistic">
Total data sent.
</constant>
<constant name="HOST_TOTAL_SENT_PACKETS" value="1" enum="HostStatistic">
Total UDP packets sent.
</constant>
<constant name="HOST_TOTAL_RECEIVED_DATA" value="2" enum="HostStatistic">
Total data received.
</constant>
<constant name="HOST_TOTAL_RECEIVED_PACKETS" value="3" enum="HostStatistic">
Total UDP packets received.
</constant>
</constants>
</class>

View File

@ -1,11 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="ENetMultiplayerPeer" inherits="MultiplayerPeer" version="4.0">
<brief_description>
PacketPeer implementation using the [url=http://enet.bespin.org/index.html]ENet[/url] library.
A MultiplayerPeer implementation using the [url=http://enet.bespin.org/index.html]ENet[/url] library.
</brief_description>
<description>
A PacketPeer implementation that should be passed to [member MultiplayerAPI.network_peer] after being initialized as either a client or server. Events can then be handled by connecting to [SceneTree] signals.
ENet's purpose is to provide a relatively thin, simple and robust network communication layer on top of UDP (User Datagram Protocol).
A MultiplayerPeer implementation that should be passed to [member MultiplayerAPI.network_peer] after being initialized as either a client, server, or mesh. Events can then be handled by connecting to [MultiplayerAPI] signals. See [ENetConnection] for more information on the ENet library wrapper.
[b]Note:[/b] ENet only uses UDP, not TCP. When forwarding the server port to make your server accessible on the public Internet, you only need to forward the server port in UDP. You can use the [UPNP] class to try to forward the server port automatically when starting the server.
</description>
<tutorials>
@ -13,6 +12,18 @@
<link title="API documentation on the ENet website">http://enet.bespin.org/usergroup0.html</link>
</tutorials>
<methods>
<method name="add_mesh_peer">
<return type="int" enum="Error">
</return>
<argument index="0" name="peer_id" type="int">
</argument>
<argument index="1" name="host" type="ENetConnection">
</argument>
<description>
Add a new remote peer with the given [code]peer_id[/code] connected to the given [code]host[/code].
Note: The [code]host[/code] must have exactly one peer in the [constant ENetPacketPeer.STATE_CONNECTED] state.
</description>
</method>
<method name="close_connection">
<return type="void">
</return>
@ -29,14 +40,25 @@
</argument>
<argument index="1" name="port" type="int">
</argument>
<argument index="2" name="in_bandwidth" type="int" default="0">
<argument index="2" name="channel_count" type="int" default="0">
</argument>
<argument index="3" name="out_bandwidth" type="int" default="0">
<argument index="3" name="in_bandwidth" type="int" default="0">
</argument>
<argument index="4" name="local_port" type="int" default="0">
<argument index="4" name="out_bandwidth" type="int" default="0">
</argument>
<argument index="5" name="local_port" type="int" default="0">
</argument>
<description>
Create client that connects to a server at [code]address[/code] using specified [code]port[/code]. The given address needs to be either a fully qualified domain name (e.g. [code]"www.example.com"[/code]) or an IP address in IPv4 or IPv6 format (e.g. [code]"192.168.1.1"[/code]). The [code]port[/code] is the port the server is listening on. The [code]in_bandwidth[/code] and [code]out_bandwidth[/code] parameters can be used to limit the incoming and outgoing bandwidth to the given number of bytes per second. The default of 0 means unlimited bandwidth. Note that ENet will strategically drop packets on specific sides of a connection between peers to ensure the peer's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. Returns [constant OK] if a client was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the client could not be created. If [code]local_port[/code] is specified, the client will also listen to the given port; this is useful for some NAT traversal techniques.
Create client that connects to a server at [code]address[/code] using specified [code]port[/code]. The given address needs to be either a fully qualified domain name (e.g. [code]"www.example.com"[/code]) or an IP address in IPv4 or IPv6 format (e.g. [code]"192.168.1.1"[/code]). The [code]port[/code] is the port the server is listening on. The [code]channel_count[/code] parameter can be used to specify the number of ENet channels allocated for the connection. The [code]in_bandwidth[/code] and [code]out_bandwidth[/code] parameters can be used to limit the incoming and outgoing bandwidth to the given number of bytes per second. The default of 0 means unlimited bandwidth. Note that ENet will strategically drop packets on specific sides of a connection between peers to ensure the peer's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. Returns [constant OK] if a client was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the client could not be created. If [code]local_port[/code] is specified, the client will also listen to the given port; this is useful for some NAT traversal techniques.
</description>
</method>
<method name="create_mesh">
<return type="int" enum="Error">
</return>
<argument index="0" name="unique_id" type="int">
</argument>
<description>
Initialize this [MultiplayerPeer] in mesh mode. The provided [code]unique_id[/code] will be used as the local peer network unique ID once assigned as the [member MultiplayerAPI.network_peer]. In the mesh configuration you will need to set up each new peer manually using [ENetConnection] before calling [method add_mesh_peer]. While this technique is more advanced, it allows for better control over the connection process (e.g. when dealing with NAT punch-through) and for better distribution of the network load (which would otherwise be more taxing on the server).
</description>
</method>
<method name="create_server">
@ -46,62 +68,23 @@
</argument>
<argument index="1" name="max_clients" type="int" default="32">
</argument>
<argument index="2" name="in_bandwidth" type="int" default="0">
<argument index="2" name="max_channels" type="int" default="0">
</argument>
<argument index="3" name="out_bandwidth" type="int" default="0">
<argument index="3" name="in_bandwidth" type="int" default="0">
</argument>
<argument index="4" name="out_bandwidth" type="int" default="0">
</argument>
<description>
Create server that listens to connections via [code]port[/code]. The port needs to be an available, unused port between 0 and 65535. Note that ports below 1024 are privileged and may require elevated permissions depending on the platform. To change the interface the server listens on, use [method set_bind_ip]. The default IP is the wildcard [code]"*"[/code], which listens on all available interfaces. [code]max_clients[/code] is the maximum number of clients that are allowed at once, any number up to 4095 may be used, although the achievable number of simultaneous clients may be far lower and depends on the application. For additional details on the bandwidth parameters, see [method create_client]. Returns [constant OK] if a server was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the server could not be created.
</description>
</method>
<method name="disconnect_peer">
<return type="void">
</return>
<argument index="0" name="id" type="int">
</argument>
<argument index="1" name="now" type="bool" default="false">
</argument>
<description>
Disconnect the given peer. If "now" is set to [code]true[/code], the connection will be closed immediately without flushing queued messages.
</description>
</method>
<method name="get_last_packet_channel" qualifiers="const">
<return type="int">
</return>
<description>
Returns the channel of the last packet fetched via [method PacketPeer.get_packet].
</description>
</method>
<method name="get_local_port" qualifiers="const">
<return type="int">
</return>
<description>
Returns the local port to which this peer is bound.
</description>
</method>
<method name="get_packet_channel" qualifiers="const">
<return type="int">
</return>
<description>
Returns the channel of the next packet that will be retrieved via [method PacketPeer.get_packet].
</description>
</method>
<method name="get_peer_address" qualifiers="const">
<return type="String">
<method name="get_peer" qualifiers="const">
<return type="ENetPacketPeer">
</return>
<argument index="0" name="id" type="int">
</argument>
<description>
Returns the IP address of the given peer.
</description>
</method>
<method name="get_peer_port" qualifiers="const">
<return type="int">
</return>
<argument index="0" name="id" type="int">
</argument>
<description>
Returns the remote port of the given peer.
Return the [ENetPacketPeer] associated to the given [code]id[/code].
</description>
</method>
<method name="set_bind_ip">
@ -113,83 +96,17 @@
The IP used when creating a server. This is set to the wildcard [code]"*"[/code] by default, which binds to all available interfaces. The given IP needs to be in IPv4 or IPv6 address format, for example: [code]"192.168.1.1"[/code].
</description>
</method>
<method name="set_dtls_certificate">
<return type="void">
</return>
<argument index="0" name="certificate" type="X509Certificate">
</argument>
<description>
Configure the [X509Certificate] to use when [member use_dtls] is [code]true[/code]. For servers, you must also setup the [CryptoKey] via [method set_dtls_key].
</description>
</method>
<method name="set_dtls_key">
<return type="void">
</return>
<argument index="0" name="key" type="CryptoKey">
</argument>
<description>
Configure the [CryptoKey] to use when [member use_dtls] is [code]true[/code]. Remember to also call [method set_dtls_certificate] to setup your [X509Certificate].
</description>
</method>
<method name="set_peer_timeout">
<return type="void">
</return>
<argument index="0" name="id" type="int">
</argument>
<argument index="1" name="timeout_limit" type="int">
</argument>
<argument index="2" name="timeout_min" type="int">
</argument>
<argument index="3" name="timeout_max" type="int">
</argument>
<description>
Sets the timeout parameters for a peer. The timeout parameters control how and when a peer will timeout from a failure to acknowledge reliable traffic. Timeout values are expressed in milliseconds.
The [code]timeout_limit[/code] is a factor that, multiplied by a value based on the average round trip time, will determine the timeout limit for a reliable packet. When that limit is reached, the timeout will be doubled, and the peer will be disconnected if that limit has reached [code]timeout_min[/code]. The [code]timeout_max[/code] parameter, on the other hand, defines a fixed timeout for which any packet must be acknowledged or the peer will be dropped.
</description>
</method>
</methods>
<members>
<member name="always_ordered" type="bool" setter="set_always_ordered" getter="is_always_ordered" default="false">
Enforce ordered packets when using [constant MultiplayerPeer.TRANSFER_MODE_UNRELIABLE] (thus behaving similarly to [constant MultiplayerPeer.TRANSFER_MODE_UNRELIABLE_ORDERED]). This is the only way to use ordering with the RPC system.
</member>
<member name="channel_count" type="int" setter="set_channel_count" getter="get_channel_count" default="3">
The number of channels to be used by ENet. Channels are used to separate different kinds of data. In reliable or ordered mode, for example, the packet delivery order is ensured on a per-channel basis. This is done to combat latency and reduces ordering restrictions on packets. The delivery status of a packet in one channel won't stall the delivery of other packets in another channel.
</member>
<member name="compression_mode" type="int" setter="set_compression_mode" getter="get_compression_mode" enum="ENetMultiplayerPeer.CompressionMode" default="1">
The compression method used for network packets. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all.
[b]Note:[/b] Most games' network design involve sending many small packets frequently (smaller than 4 KB each). If in doubt, it is recommended to keep the default compression algorithm as it works best on these small packets.
</member>
<member name="dtls_verify" type="bool" setter="set_dtls_verify_enabled" getter="is_dtls_verify_enabled" default="true">
Enable or disable certificate verification when [member use_dtls] [code]true[/code].
<member name="host" type="ENetConnection" setter="" getter="get_host">
The underlying [ENetConnection] created after [method create_client] and [method create_server].
</member>
<member name="refuse_new_connections" type="bool" setter="set_refuse_new_connections" getter="is_refusing_new_connections" override="true" default="false" />
<member name="server_relay" type="bool" setter="set_server_relay_enabled" getter="is_server_relay_enabled" default="true">
Enable or disable the server feature that notifies clients of other peers' connection/disconnection, and relays messages between them. When this option is [code]false[/code], clients won't be automatically notified of other peers and won't be able to send them packets through the server.
</member>
<member name="transfer_channel" type="int" setter="set_transfer_channel" getter="get_transfer_channel" default="-1">
Set the default channel to be used to transfer data. By default, this value is [code]-1[/code] which means that ENet will only use 2 channels: one for reliable packets, and one for unreliable packets. The channel [code]0[/code] is reserved and cannot be used. Setting this member to any value between [code]0[/code] and [member channel_count] (excluded) will force ENet to use that channel for sending data. See [member channel_count] for more information about ENet channels.
</member>
<member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="MultiplayerPeer.TransferMode" default="2" />
<member name="use_dtls" type="bool" setter="set_dtls_enabled" getter="is_dtls_enabled" default="false">
When enabled, the client or server created by this peer, will use [PacketPeerDTLS] instead of raw UDP sockets for communicating with the remote peer. This will make the communication encrypted with DTLS at the cost of higher resource usage and potentially larger packet size.
Note: When creating a DTLS server, make sure you setup the key/certificate pair via [method set_dtls_key] and [method set_dtls_certificate]. For DTLS clients, have a look at the [member dtls_verify] option, and configure the certificate accordingly via [method set_dtls_certificate].
</member>
</members>
<constants>
<constant name="COMPRESS_NONE" value="0" enum="CompressionMode">
No compression. This uses the most bandwidth, but has the upside of requiring the fewest CPU resources. This option may also be used to make network debugging using tools like Wireshark easier.
</constant>
<constant name="COMPRESS_RANGE_CODER" value="1" enum="CompressionMode">
ENet's built-in range encoding. Works well on small packets, but is not the most efficient algorithm on packets larger than 4 KB.
</constant>
<constant name="COMPRESS_FASTLZ" value="2" enum="CompressionMode">
[url=http://fastlz.org/]FastLZ[/url] compression. This option uses less CPU resources compared to [constant COMPRESS_ZLIB], at the expense of using more bandwidth.
</constant>
<constant name="COMPRESS_ZLIB" value="3" enum="CompressionMode">
[url=https://www.zlib.net/]Zlib[/url] compression. This option uses less bandwidth compared to [constant COMPRESS_FASTLZ], at the expense of using more CPU resources.
</constant>
<constant name="COMPRESS_ZSTD" value="4" enum="CompressionMode">
[url=https://facebook.github.io/zstd/]Zstandard[/url] compression. Note that this algorithm is not very efficient on packets smaller than 4 KB. Therefore, it's recommended to use other compression algorithms in most cases.
</constant>
</constants>
</class>

View File

@ -0,0 +1,210 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="ENetPacketPeer" inherits="PacketPeer" version="4.0">
<brief_description>
A wrapper class for an [url=http://enet.bespin.org/group__peer.html]ENetPeer[/url].
</brief_description>
<description>
A PacketPeer implementation representing a peer of an [ENetConnection].
This class cannot be instantiated directly but can be retrieved during [method ENetConnection.service] or via [method ENetConnection.get_peers].
</description>
<tutorials>
<link title="API documentation on the ENet website">http://enet.bespin.org/usergroup0.html</link>
</tutorials>
<methods>
<method name="get_channels" qualifiers="const">
<return type="int">
</return>
<description>
Returns the number of channels allocated for communication with peer.
</description>
</method>
<method name="get_state" qualifiers="const">
<return type="int" enum="ENetPacketPeer.PeerState">
</return>
<description>
Returns the current peer state. See [enum PeerState].
</description>
</method>
<method name="get_statistic">
<return type="float">
</return>
<argument index="0" name="statistic" type="int" enum="ENetPacketPeer.PeerStatistic">
</argument>
<description>
Returns the requested [code]statistic[/code] for this peer. See [enum PeerStatistic].
</description>
</method>
<method name="is_active" qualifiers="const">
<return type="bool">
</return>
<description>
Returns [code]true[/code] if the peer is currently active (i.e. the associated [ENetConnection] is still valid).
</description>
</method>
<method name="peer_disconnect">
<return type="void">
</return>
<argument index="0" name="data" type="int" default="0">
</argument>
<description>
Request a disconnection from a peer. An [constant ENetConnection.EVENT_DISCONNECT] will be generated during [method ENetConnection.service] once the disconnection is complete.
</description>
</method>
<method name="peer_disconnect_later">
<return type="void">
</return>
<argument index="0" name="data" type="int" default="0">
</argument>
<description>
Request a disconnection from a peer, but only after all queued outgoing packets are sent. An [constant ENetConnection.EVENT_DISCONNECT] will be generated during [method ENetConnection.service] once the disconnection is complete.
</description>
</method>
<method name="peer_disconnect_now">
<return type="void">
</return>
<argument index="0" name="data" type="int" default="0">
</argument>
<description>
Force an immediate disconnection from a peer. No [constant ENetConnection.EVENT_DISCONNECT] will be generated. The foreign peer is not guaranteed to receive the disconnect notification, and is reset immediately upon return from this function.
</description>
</method>
<method name="ping">
<return type="void">
</return>
<description>
Sends a ping request to a peer. ENet automatically pings all connected peers at regular intervals, however, this function may be called to ensure more frequent ping requests.
</description>
</method>
<method name="ping_interval">
<return type="void">
</return>
<argument index="0" name="ping_interval" type="int">
</argument>
<description>
Sets the [code]ping_interval[/code] in milliseconds at which pings will be sent to a peer. Pings are used both to monitor the liveness of the connection and also to dynamically adjust the throttle during periods of low traffic so that the throttle has reasonable responsiveness during traffic spikes.
</description>
</method>
<method name="reset">
<return type="void">
</return>
<description>
Forcefully disconnects a peer. The foreign host represented by the peer is not notified of the disconnection and will timeout on its connection to the local host.
</description>
</method>
<method name="send">
<return type="int" enum="Error">
</return>
<argument index="0" name="channel" type="int">
</argument>
<argument index="1" name="packet" type="PackedByteArray">
</argument>
<argument index="2" name="flags" type="int">
</argument>
<description>
Queues a [code]packet[/code] to be sent over the specified [code]channel[/code]. See [code]FLAG_*[/code] constants for available packet flags.
</description>
</method>
<method name="set_timeout">
<return type="void">
</return>
<argument index="0" name="timeout" type="int">
</argument>
<argument index="1" name="timeout_min" type="int">
</argument>
<argument index="2" name="timeout_max" type="int">
</argument>
<description>
Sets the timeout parameters for a peer. The timeout parameters control how and when a peer will timeout from a failure to acknowledge reliable traffic. Timeout values are expressed in milliseconds.
The [code]timeout_limit[/code] is a factor that, multiplied by a value based on the average round trip time, will determine the timeout limit for a reliable packet. When that limit is reached, the timeout will be doubled, and the peer will be disconnected if that limit has reached [code]timeout_min[/code]. The [code]timeout_max[/code] parameter, on the other hand, defines a fixed timeout for which any packet must be acknowledged or the peer will be dropped.
</description>
</method>
<method name="throttle_configure">
<return type="void">
</return>
<argument index="0" name="interval" type="int">
</argument>
<argument index="1" name="acceleration" type="int">
</argument>
<argument index="2" name="deceleration" type="int">
</argument>
<description>
Configures throttle parameter for a peer.
Unreliable packets are dropped by ENet in response to the varying conditions of the Internet connection to the peer. The throttle represents a probability that an unreliable packet should not be dropped and thus sent by ENet to the peer. By measuring fluctuations in round trip times of reliable packets over the specified [code]interval[/code], ENet will either increase the probably by the amount specified in the [code]acceleration[/code] parameter, or decrease it by the amount specified in the [code]deceleration[/code] parameter (both are ratios to [constant PACKET_THROTTLE_SCALE]).
When the throttle has a value of [constant PACKET_THROTTLE_SCALE], no unreliable packets are dropped by ENet, and so 100% of all unreliable packets will be sent.
When the throttle has a value of 0, all unreliable packets are dropped by ENet, and so 0% of all unreliable packets will be sent.
Intermediate values for the throttle represent intermediate probabilities between 0% and 100% of unreliable packets being sent. The bandwidth limits of the local and foreign hosts are taken into account to determine a sensible limit for the throttle probability above which it should not raise even in the best of conditions.
</description>
</method>
</methods>
<constants>
<constant name="STATE_DISCONNECTED" value="0" enum="PeerState">
</constant>
<constant name="STATE_CONNECTING" value="1" enum="PeerState">
</constant>
<constant name="STATE_ACKNOWLEDGING_CONNECT" value="2" enum="PeerState">
</constant>
<constant name="STATE_CONNECTION_PENDING" value="3" enum="PeerState">
</constant>
<constant name="STATE_CONNECTION_SUCCEEDED" value="4" enum="PeerState">
</constant>
<constant name="STATE_CONNECTED" value="5" enum="PeerState">
</constant>
<constant name="STATE_DISCONNECT_LATER" value="6" enum="PeerState">
</constant>
<constant name="STATE_DISCONNECTING" value="7" enum="PeerState">
</constant>
<constant name="STATE_ACKNOWLEDGING_DISCONNECT" value="8" enum="PeerState">
</constant>
<constant name="STATE_ZOMBIE" value="9" enum="PeerState">
</constant>
<constant name="PEER_PACKET_LOSS" value="0" enum="PeerStatistic">
Mean packet loss of reliable packets as a ratio with respect to the [constant PACKET_LOSS_SCALE].
</constant>
<constant name="PEER_PACKET_LOSS_VARIANCE" value="1" enum="PeerStatistic">
Packet loss variance.
</constant>
<constant name="PEER_PACKET_LOSS_EPOCH" value="2" enum="PeerStatistic">
</constant>
<constant name="PEER_ROUND_TRIP_TIME" value="3" enum="PeerStatistic">
Mean packet round trip time for reliable packets.
</constant>
<constant name="PEER_ROUND_TRIP_TIME_VARIANCE" value="4" enum="PeerStatistic">
Variance of the mean round trip time.
</constant>
<constant name="PEER_LAST_ROUND_TRIP_TIME" value="5" enum="PeerStatistic">
Last recorded round trip time for a reliable packet.
</constant>
<constant name="PEER_LAST_ROUND_TRIP_TIME_VARIANCE" value="6" enum="PeerStatistic">
Variance of the last trip time recorded.
</constant>
<constant name="PEER_PACKET_THROTTLE" value="7" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_LIMIT" value="8" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_COUNTER" value="9" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_EPOCH" value="10" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_ACCELERATION" value="11" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_DECELERATION" value="12" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_INTERVAL" value="13" enum="PeerStatistic">
</constant>
<constant name="PACKET_LOSS_SCALE" value="65536">
The reference scale for packet loss. See [method get_statistic] and [constant PEER_PACKET_LOSS].
</constant>
<constant name="PACKET_THROTTLE_SCALE" value="32">
The reference value for throttle configuration. See [method throttle_configure].
</constant>
<constant name="FLAG_RELIABLE" value="1">
Mark the packet to be sent as reliable.
</constant>
<constant name="FLAG_UNSEQUENCED" value="2">
Mark the packet to be sent unsequenced (unreliable).
</constant>
<constant name="FLAG_UNRELIABLE_FRAGMENT" value="8">
Mark the packet to be sent unreliable even if the packet is too big and needs fragmentation (increasing the chance of it being dropped).
</constant>
</constants>
</class>

View File

@ -0,0 +1,470 @@
/*************************************************************************/
/* enet_connection.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "enet_connection.h"
#include "enet_packet_peer.h"
#include "core/io/compression.h"
#include "core/io/ip.h"
void ENetConnection::broadcast(enet_uint8 p_channel, ENetPacket *p_packet) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
ERR_FAIL_COND_MSG(p_channel >= host->channelLimit, vformat("Unable to send packet on channel %d, max channels: %d", p_channel, (int)host->channelLimit));
enet_host_broadcast(host, p_channel, p_packet);
}
Error ENetConnection::create_host_bound(const IPAddress &p_bind_address, int p_port, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
ERR_FAIL_COND_V_MSG(!p_bind_address.is_valid() && !p_bind_address.is_wildcard(), ERR_INVALID_PARAMETER, "Invalid bind IP.");
ERR_FAIL_COND_V_MSG(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER, "The local port number must be between 0 and 65535 (inclusive).");
ENetAddress address;
memset(&address, 0, sizeof(address));
address.port = p_port;
#ifdef GODOT_ENET
if (p_bind_address.is_wildcard()) {
address.wildcard = 1;
} else {
enet_address_set_ip(&address, p_bind_address.get_ipv6(), 16);
}
#else
if (p_bind_address.is_wildcard()) {
address.host = 0;
} else {
ERR_FAIL_COND_V(!p_bind_address.is_ipv4(), ERR_INVALID_PARAMETER);
address.host = *(uint32_t *)p_bind_address.get_ipv4();
}
#endif
return _create(&address, p_max_peers, p_max_channels, p_in_bandwidth, p_out_bandwidth);
}
Error ENetConnection::create_host(int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
return _create(nullptr, p_max_peers, p_max_channels, p_in_bandwidth, p_out_bandwidth);
}
void ENetConnection::destroy() {
ERR_FAIL_COND_MSG(!host, "Host already destroyed");
for (List<Ref<ENetPacketPeer>>::Element *E = peers.front(); E; E = E->next()) {
E->get()->_on_disconnect();
}
peers.clear();
enet_host_destroy(host);
host = nullptr;
}
Ref<ENetPacketPeer> ENetConnection::connect_to_host(const String &p_address, int p_port, int p_channels, int p_data) {
Ref<ENetPacketPeer> out;
ERR_FAIL_COND_V_MSG(!host, out, "The ENetConnection instance isn't currently active.");
ERR_FAIL_COND_V_MSG(peers.size(), out, "The ENetConnection is already connected to a peer.");
ERR_FAIL_COND_V_MSG(p_port < 1 || p_port > 65535, out, "The remote port number must be between 1 and 65535 (inclusive).");
IPAddress ip;
if (p_address.is_valid_ip_address()) {
ip = p_address;
} else {
#ifdef GODOT_ENET
ip = IP::get_singleton()->resolve_hostname(p_address);
#else
ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4);
#endif
ERR_FAIL_COND_V_MSG(!ip.is_valid(), out, "Couldn't resolve the server IP address or domain name.");
}
ENetAddress address;
#ifdef GODOT_ENET
enet_address_set_ip(&address, ip.get_ipv6(), 16);
#else
ERR_FAIL_COND_V_MSG(!ip.is_ipv4(), out, "Connecting to an IPv6 server isn't supported when using vanilla ENet. Recompile Godot with the bundled ENet library.");
address.host = *(uint32_t *)ip.get_ipv4();
#endif
address.port = p_port;
// Initiate connection, allocating enough channels
ENetPeer *peer = enet_host_connect(host, &address, p_channels, p_data);
if (peer == nullptr) {
return nullptr;
}
out = Ref<ENetPacketPeer>(memnew(ENetPacketPeer(peer)));
peers.push_back(out);
return out;
}
ENetConnection::EventType ENetConnection::service(int p_timeout, Event &r_event) {
ERR_FAIL_COND_V_MSG(!host, EVENT_ERROR, "The ENetConnection instance isn't currently active.");
ERR_FAIL_COND_V(r_event.peer.is_valid(), EVENT_ERROR);
// Drop peers that have already been disconnected.
// NOTE: Forcibly disconnected peers (i.e. peers disconnected via
// enet_peer_disconnect*) do not trigger DISCONNECTED events.
List<Ref<ENetPacketPeer>>::Element *E = peers.front();
while (E) {
if (!E->get()->is_active()) {
peers.erase(E->get());
}
E = E->next();
}
ENetEvent event;
int ret = enet_host_service(host, &event, p_timeout);
if (ret < 0) {
return EVENT_ERROR;
} else if (ret == 0) {
return EVENT_NONE;
}
switch (event.type) {
case ENET_EVENT_TYPE_CONNECT: {
if (event.peer->data == nullptr) {
Ref<ENetPacketPeer> pp = memnew(ENetPacketPeer(event.peer));
peers.push_back(pp);
}
r_event.peer = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data);
r_event.data = event.data;
return EVENT_CONNECT;
} break;
case ENET_EVENT_TYPE_DISCONNECT: {
// A peer disconnected.
if (event.peer->data != nullptr) {
Ref<ENetPacketPeer> pp = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data);
pp->_on_disconnect();
peers.erase(pp);
r_event.peer = pp;
r_event.data = event.data;
return EVENT_DISCONNECT;
}
return EVENT_ERROR;
} break;
case ENET_EVENT_TYPE_RECEIVE: {
// Packet reveived.
if (event.peer->data != nullptr) {
Ref<ENetPacketPeer> pp = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data);
r_event.peer = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data);
r_event.channel_id = event.channelID;
r_event.packet = event.packet;
return EVENT_RECEIVE;
}
return EVENT_ERROR;
} break;
case ENET_EVENT_TYPE_NONE:
return EVENT_NONE;
default:
return EVENT_NONE;
}
}
void ENetConnection::flush() {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
enet_host_flush(host);
}
void ENetConnection::bandwidth_limit(int p_in_bandwidth, int p_out_bandwidth) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
enet_host_bandwidth_limit(host, p_in_bandwidth, p_out_bandwidth);
}
void ENetConnection::channel_limit(int p_max_channels) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
enet_host_channel_limit(host, p_max_channels);
}
void ENetConnection::bandwidth_throttle() {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
enet_host_bandwidth_throttle(host);
}
void ENetConnection::compress(CompressionMode p_mode) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
Compressor::setup(host, p_mode);
}
double ENetConnection::pop_statistic(HostStatistic p_stat) {
ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active.");
uint32_t *ptr = nullptr;
switch (p_stat) {
case HOST_TOTAL_SENT_DATA:
ptr = &(host->totalSentData);
break;
case HOST_TOTAL_SENT_PACKETS:
ptr = &(host->totalSentPackets);
break;
case HOST_TOTAL_RECEIVED_DATA:
ptr = &(host->totalReceivedData);
break;
case HOST_TOTAL_RECEIVED_PACKETS:
ptr = &(host->totalReceivedPackets);
break;
}
ERR_FAIL_COND_V_MSG(ptr == nullptr, 0, "Invalid statistic: " + itos(p_stat));
uint32_t ret = *ptr;
*ptr = 0;
return ret;
}
int ENetConnection::get_max_channels() const {
ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active.");
return host->channelLimit;
}
int ENetConnection::get_local_port() const {
ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active.");
ERR_FAIL_COND_V_MSG(!(host->socket), 0, "The ENetConnection instance isn't currently bound");
ENetAddress address;
ERR_FAIL_COND_V_MSG(enet_socket_get_address(host->socket, &address), 0, "Unable to get socket address");
return address.port;
}
void ENetConnection::get_peers(List<Ref<ENetPacketPeer>> &r_peers) {
for (const Ref<ENetPacketPeer> &I : peers) {
r_peers.push_back(I);
}
}
Array ENetConnection::_get_peers() {
ERR_FAIL_COND_V_MSG(!host, Array(), "The ENetConnection instance isn't currently active.");
Array out;
for (const Ref<ENetPacketPeer> &I : peers) {
out.push_back(I);
}
return out;
}
Error ENetConnection::dtls_server_setup(Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert) {
#ifdef GODOT_ENET
ERR_FAIL_COND_V_MSG(!host, ERR_UNCONFIGURED, "The ENetConnection instance isn't currently active.");
return enet_host_dtls_server_setup(host, p_key.ptr(), p_cert.ptr()) ? FAILED : OK;
#else
ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "ENet DTLS support not available in this build.");
#endif
}
void ENetConnection::refuse_new_connections(bool p_refuse) {
#ifdef GODOT_ENET
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
enet_host_refuse_new_connections(host, p_refuse);
#else
ERR_FAIL_MSG("ENet DTLS support not available in this build.");
#endif
}
Error ENetConnection::dtls_client_setup(Ref<X509Certificate> p_cert, const String &p_hostname, bool p_verify) {
#ifdef GODOT_ENET
ERR_FAIL_COND_V_MSG(!host, ERR_UNCONFIGURED, "The ENetConnection instance isn't currently active.");
return enet_host_dtls_client_setup(host, p_cert.ptr(), p_verify, p_hostname.utf8().get_data()) ? FAILED : OK;
#else
ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "ENet DTLS support not available in this build.");
#endif
}
Error ENetConnection::_create(ENetAddress *p_address, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
ERR_FAIL_COND_V_MSG(host != nullptr, ERR_ALREADY_IN_USE, "The ENetConnection instance is already active.");
ERR_FAIL_COND_V_MSG(p_max_peers < 1 || p_max_peers > 4095, ERR_INVALID_PARAMETER, "The number of clients must be set between 1 and 4095 (inclusive).");
ERR_FAIL_COND_V_MSG(p_max_channels < 0 || p_max_channels > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT, ERR_INVALID_PARAMETER, "Invalid channel count. Must be between 0 and 255 (0 means maximum, i.e. 255)");
ERR_FAIL_COND_V_MSG(p_in_bandwidth < 0, ERR_INVALID_PARAMETER, "The incoming bandwidth limit must be greater than or equal to 0 (0 disables the limit).");
ERR_FAIL_COND_V_MSG(p_out_bandwidth < 0, ERR_INVALID_PARAMETER, "The outgoing bandwidth limit must be greater than or equal to 0 (0 disables the limit).");
host = enet_host_create(p_address /* the address to bind the server host to */,
p_max_peers /* allow up to p_max_peers connections */,
p_max_channels /* allow up to p_max_channel to be used */,
p_in_bandwidth /* limit incoming bandwidth if > 0 */,
p_out_bandwidth /* limit outgoing bandwidth if > 0 */);
ERR_FAIL_COND_V_MSG(!host, ERR_CANT_CREATE, "Couldn't create an ENet host.");
return OK;
}
Array ENetConnection::_service(int p_timeout) {
Array out;
Event event;
Ref<ENetPacketPeer> peer;
EventType ret = service(p_timeout, event);
out.push_back(ret);
out.push_back(event.peer);
out.push_back(event.data);
out.push_back(event.channel_id);
if (event.packet && event.peer.is_valid()) {
event.peer->_queue_packet(event.packet);
}
return out;
}
void ENetConnection::_broadcast(int p_channel, PackedByteArray p_packet, int p_flags) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
ERR_FAIL_COND_MSG(p_channel < 0 || p_channel > (int)host->channelLimit, "Invalid channel");
ERR_FAIL_COND_MSG(p_flags & ~ENetPacketPeer::FLAG_ALLOWED, "Invalid flags");
ENetPacket *pkt = enet_packet_create(p_packet.ptr(), p_packet.size(), p_flags);
broadcast(p_channel, pkt);
}
void ENetConnection::_bind_methods() {
ClassDB::bind_method(D_METHOD("create_host_bound", "bind_address", "bind_port", "max_peers", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetConnection::create_host_bound, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("create_host", "max_peers", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetConnection::create_host, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("destroy"), &ENetConnection::destroy);
ClassDB::bind_method(D_METHOD("connect_to_host", "address", "port", "channels", "data"), &ENetConnection::connect_to_host, DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("service", "timeout"), &ENetConnection::_service, DEFVAL(0));
ClassDB::bind_method(D_METHOD("flush"), &ENetConnection::flush);
ClassDB::bind_method(D_METHOD("bandwidth_limit", "in_bandwidth", "out_bandwidth"), &ENetConnection::bandwidth_limit, DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("channel_limit", "limit"), &ENetConnection::channel_limit);
ClassDB::bind_method(D_METHOD("broadcast", "channel", "packet", "flags"), &ENetConnection::_broadcast);
ClassDB::bind_method(D_METHOD("compress", "mode"), &ENetConnection::compress);
ClassDB::bind_method(D_METHOD("dtls_server_setup", "key", "certificate"), &ENetConnection::dtls_server_setup);
ClassDB::bind_method(D_METHOD("dtls_client_setup", "certificate", "hostname", "verify"), &ENetConnection::dtls_client_setup, DEFVAL(true));
ClassDB::bind_method(D_METHOD("refuse_new_connections", "refuse"), &ENetConnection::refuse_new_connections);
ClassDB::bind_method(D_METHOD("pop_statistic", "statistic"), &ENetConnection::pop_statistic);
ClassDB::bind_method(D_METHOD("get_max_channels"), &ENetConnection::get_max_channels);
ClassDB::bind_method(D_METHOD("get_local_port"), &ENetConnection::get_local_port);
ClassDB::bind_method(D_METHOD("get_peers"), &ENetConnection::_get_peers);
BIND_ENUM_CONSTANT(COMPRESS_NONE);
BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER);
BIND_ENUM_CONSTANT(COMPRESS_FASTLZ);
BIND_ENUM_CONSTANT(COMPRESS_ZLIB);
BIND_ENUM_CONSTANT(COMPRESS_ZSTD);
BIND_ENUM_CONSTANT(EVENT_ERROR);
BIND_ENUM_CONSTANT(EVENT_NONE);
BIND_ENUM_CONSTANT(EVENT_CONNECT);
BIND_ENUM_CONSTANT(EVENT_DISCONNECT);
BIND_ENUM_CONSTANT(EVENT_RECEIVE);
BIND_ENUM_CONSTANT(HOST_TOTAL_SENT_DATA);
BIND_ENUM_CONSTANT(HOST_TOTAL_SENT_PACKETS);
BIND_ENUM_CONSTANT(HOST_TOTAL_RECEIVED_DATA);
BIND_ENUM_CONSTANT(HOST_TOTAL_RECEIVED_PACKETS);
}
ENetConnection::~ENetConnection() {
if (host) {
destroy();
}
}
size_t ENetConnection::Compressor::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
Compressor *compressor = (Compressor *)(context);
if (size_t(compressor->src_mem.size()) < inLimit) {
compressor->src_mem.resize(inLimit);
}
int total = inLimit;
int ofs = 0;
while (total) {
for (size_t i = 0; i < inBufferCount; i++) {
int to_copy = MIN(total, int(inBuffers[i].dataLength));
memcpy(&compressor->src_mem.write[ofs], inBuffers[i].data, to_copy);
ofs += to_copy;
total -= to_copy;
}
}
Compression::Mode mode;
switch (compressor->mode) {
case COMPRESS_FASTLZ: {
mode = Compression::MODE_FASTLZ;
} break;
case COMPRESS_ZLIB: {
mode = Compression::MODE_DEFLATE;
} break;
case COMPRESS_ZSTD: {
mode = Compression::MODE_ZSTD;
} break;
default: {
ERR_FAIL_V_MSG(0, vformat("Invalid ENet compression mode: %d", compressor->mode));
}
}
int req_size = Compression::get_max_compressed_buffer_size(ofs, mode);
if (compressor->dst_mem.size() < req_size) {
compressor->dst_mem.resize(req_size);
}
int ret = Compression::compress(compressor->dst_mem.ptrw(), compressor->src_mem.ptr(), ofs, mode);
if (ret < 0) {
return 0;
}
if (ret > int(outLimit)) {
return 0; // Do not bother
}
memcpy(outData, compressor->dst_mem.ptr(), ret);
return ret;
}
size_t ENetConnection::Compressor::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
Compressor *compressor = (Compressor *)(context);
int ret = -1;
switch (compressor->mode) {
case COMPRESS_FASTLZ: {
ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ);
} break;
case COMPRESS_ZLIB: {
ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE);
} break;
case COMPRESS_ZSTD: {
ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD);
} break;
default: {
}
}
if (ret < 0) {
return 0;
} else {
return ret;
}
}
void ENetConnection::Compressor::setup(ENetHost *p_host, CompressionMode p_mode) {
ERR_FAIL_COND(!p_host);
switch (p_mode) {
case COMPRESS_NONE: {
enet_host_compress(p_host, nullptr);
} break;
case COMPRESS_RANGE_CODER: {
enet_host_compress_with_range_coder(p_host);
} break;
case COMPRESS_FASTLZ:
case COMPRESS_ZLIB:
case COMPRESS_ZSTD: {
Compressor *compressor = memnew(Compressor(p_mode));
enet_host_compress(p_host, &(compressor->enet_compressor));
} break;
}
}
ENetConnection::Compressor::Compressor(CompressionMode p_mode) {
mode = p_mode;
enet_compressor.context = this;
enet_compressor.compress = enet_compress;
enet_compressor.decompress = enet_decompress;
enet_compressor.destroy = enet_compressor_destroy;
}

View File

@ -0,0 +1,138 @@
/*************************************************************************/
/* enet_connection.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef ENET_CONNECTION_H
#define ENET_CONNECTION_H
#include "core/object/ref_counted.h"
#include "core/crypto/crypto.h"
#include "enet_packet_peer.h"
#include <enet/enet.h>
class ENetConnection : public RefCounted {
GDCLASS(ENetConnection, RefCounted);
public:
enum CompressionMode {
COMPRESS_NONE = 0,
COMPRESS_RANGE_CODER,
COMPRESS_FASTLZ,
COMPRESS_ZLIB,
COMPRESS_ZSTD,
};
enum HostStatistic {
HOST_TOTAL_SENT_DATA,
HOST_TOTAL_SENT_PACKETS,
HOST_TOTAL_RECEIVED_DATA,
HOST_TOTAL_RECEIVED_PACKETS,
};
enum EventType {
EVENT_ERROR = -1,
EVENT_NONE = 0,
EVENT_CONNECT,
EVENT_DISCONNECT,
EVENT_RECEIVE,
};
struct Event {
Ref<ENetPacketPeer> peer;
enet_uint8 channel_id = 0;
enet_uint32 data = 0;
ENetPacket *packet = nullptr;
};
protected:
static void _bind_methods();
private:
ENetHost *host = nullptr;
List<Ref<ENetPacketPeer>> peers;
Error _create(ENetAddress *p_address, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth);
Array _service(int p_timeout = 0);
void _broadcast(int p_channel, PackedByteArray p_packet, int p_flags);
Array _get_peers();
class Compressor {
private:
CompressionMode mode = COMPRESS_NONE;
Vector<uint8_t> src_mem;
Vector<uint8_t> dst_mem;
ENetCompressor enet_compressor;
Compressor(CompressionMode mode);
static size_t enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit);
static size_t enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit);
static void enet_compressor_destroy(void *context) {
memdelete((Compressor *)context);
}
public:
static void setup(ENetHost *p_host, CompressionMode p_mode);
};
public:
void broadcast(enet_uint8 p_channel, ENetPacket *p_packet);
Error create_host_bound(const IPAddress &p_bind_address = IPAddress("*"), int p_port = 0, int p_max_peers = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0);
Error create_host(int p_max_peers = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0);
void destroy();
Ref<ENetPacketPeer> connect_to_host(const String &p_address, int p_port, int p_channels, int p_data = 0);
EventType service(int p_timeout, Event &r_event);
void flush();
void bandwidth_limit(int p_in_bandwidth = 0, int p_out_bandwidth = 0);
void channel_limit(int p_max_channels);
void bandwidth_throttle();
void compress(CompressionMode p_mode);
double pop_statistic(HostStatistic p_stat);
int get_max_channels() const;
// Extras
void get_peers(List<Ref<ENetPacketPeer>> &r_peers);
int get_local_port() const;
// Godot additions
Error dtls_server_setup(Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert);
Error dtls_client_setup(Ref<X509Certificate> p_cert, const String &p_hostname, bool p_verify = true);
void refuse_new_connections(bool p_refuse);
ENetConnection() {}
~ENetConnection();
};
VARIANT_ENUM_CAST(ENetConnection::CompressionMode);
VARIANT_ENUM_CAST(ENetConnection::EventType);
VARIANT_ENUM_CAST(ENetConnection::HostStatistic);
#endif // ENET_CONNECTION_H

File diff suppressed because it is too large Load Diff

View File

@ -32,23 +32,14 @@
#define NETWORKED_MULTIPLAYER_ENET_H
#include "core/crypto/crypto.h"
#include "core/io/compression.h"
#include "core/io/multiplayer_peer.h"
#include "enet_connection.h"
#include <enet/enet.h>
class ENetMultiplayerPeer : public MultiplayerPeer {
GDCLASS(ENetMultiplayerPeer, MultiplayerPeer);
public:
enum CompressionMode {
COMPRESS_NONE,
COMPRESS_RANGE_CODER,
COMPRESS_FASTLZ,
COMPRESS_ZLIB,
COMPRESS_ZSTD
};
private:
enum {
SYSMSG_ADD_PEER,
@ -62,27 +53,27 @@ private:
SYSCH_MAX
};
bool active = false;
bool server = false;
enum Mode {
MODE_NONE,
MODE_SERVER,
MODE_CLIENT,
MODE_MESH,
};
Mode active_mode = MODE_NONE;
uint32_t unique_id = 0;
int target_peer = 0;
TransferMode transfer_mode = TRANSFER_MODE_RELIABLE;
int transfer_channel = -1;
int channel_count = SYSCH_MAX;
bool always_ordered = false;
ENetEvent event;
ENetPeer *peer = nullptr;
ENetHost *host = nullptr;
bool refuse_connections = false;
bool server_relay = true;
ConnectionStatus connection_status = CONNECTION_DISCONNECTED;
Map<int, ENetPeer *> peer_map;
Map<int, Ref<ENetConnection>> hosts;
Map<int, Ref<ENetPacketPeer>> peers;
struct Packet {
ENetPacket *packet = nullptr;
@ -90,31 +81,21 @@ private:
int channel = 0;
};
CompressionMode compression_mode = COMPRESS_RANGE_CODER;
List<Packet> incoming_packets;
Packet current_packet;
uint32_t _gen_unique_id() const;
void _pop_current_packet();
Vector<uint8_t> src_compressor_mem;
Vector<uint8_t> dst_compressor_mem;
ENetCompressor enet_compressor;
static size_t enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit);
static size_t enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit);
static void enet_compressor_destroy(void *context);
void _setup_compressor();
bool _poll_server();
bool _poll_client();
bool _poll_mesh();
void _relay(int p_from, int p_to, enet_uint8 p_channel, ENetPacket *p_packet);
void _notify_peers(int p_id, bool p_connected);
void _destroy_unused(ENetPacket *p_packet);
_FORCE_INLINE_ bool _is_active() const { return active_mode != MODE_NONE; }
IPAddress bind_ip;
bool dtls_enabled = false;
Ref<CryptoKey> dtls_key;
Ref<X509Certificate> dtls_cert;
bool dtls_verify = true;
protected:
static void _bind_methods();
@ -125,13 +106,10 @@ public:
virtual int get_packet_peer() const override;
virtual IPAddress get_peer_address(int p_peer_id) const;
virtual int get_peer_port(int p_peer_id) const;
virtual int get_local_port() const;
void set_peer_timeout(int p_peer_id, int p_timeout_limit, int p_timeout_min, int p_timeout_max);
Error create_server(int p_port, int p_max_clients = 32, int p_in_bandwidth = 0, int p_out_bandwidth = 0);
Error create_client(const String &p_address, int p_port, int p_in_bandwidth = 0, int p_out_bandwidth = 0, int p_local_port = 0);
Error create_server(int p_port, int p_max_clients = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0);
Error create_client(const String &p_address, int p_port, int p_channel_count = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0, int p_local_port = 0);
Error create_mesh(int p_id);
Error add_mesh_peer(int p_id, Ref<ENetConnection> p_host);
void close_connection(uint32_t wait_usec = 100);
@ -154,32 +132,15 @@ public:
virtual int get_unique_id() const override;
void set_compression_mode(CompressionMode p_mode);
CompressionMode get_compression_mode() const;
int get_packet_channel() const;
int get_last_packet_channel() const;
void set_transfer_channel(int p_channel);
int get_transfer_channel() const;
void set_channel_count(int p_channel);
int get_channel_count() const;
void set_always_ordered(bool p_ordered);
bool is_always_ordered() const;
void set_bind_ip(const IPAddress &p_ip);
void set_server_relay_enabled(bool p_enabled);
bool is_server_relay_enabled() const;
Ref<ENetConnection> get_host() const;
Ref<ENetPacketPeer> get_peer(int p_id) const;
ENetMultiplayerPeer();
~ENetMultiplayerPeer();
void set_bind_ip(const IPAddress &p_ip);
void set_dtls_enabled(bool p_enabled);
bool is_dtls_enabled() const;
void set_dtls_verify_enabled(bool p_enabled);
bool is_dtls_verify_enabled() const;
void set_dtls_key(Ref<CryptoKey> p_key);
void set_dtls_certificate(Ref<X509Certificate> p_cert);
};
VARIANT_ENUM_CAST(ENetMultiplayerPeer::CompressionMode);
#endif // NETWORKED_MULTIPLAYER_ENET_H

View File

@ -0,0 +1,263 @@
/*************************************************************************/
/* enet_packet_peer.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "enet_packet_peer.h"
void ENetPacketPeer::peer_disconnect(int p_data) {
ERR_FAIL_COND(!peer);
enet_peer_disconnect(peer, p_data);
}
void ENetPacketPeer::peer_disconnect_later(int p_data) {
ERR_FAIL_COND(!peer);
enet_peer_disconnect_later(peer, p_data);
}
void ENetPacketPeer::peer_disconnect_now(int p_data) {
ERR_FAIL_COND(!peer);
enet_peer_disconnect_now(peer, p_data);
_on_disconnect();
}
void ENetPacketPeer::ping() {
ERR_FAIL_COND(!peer);
enet_peer_ping(peer);
}
void ENetPacketPeer::ping_interval(int p_interval) {
ERR_FAIL_COND(!peer);
enet_peer_ping_interval(peer, p_interval);
}
int ENetPacketPeer::send(uint8_t p_channel, ENetPacket *p_packet) {
ERR_FAIL_COND_V(peer == nullptr, -1);
ERR_FAIL_COND_V(p_packet == nullptr, -1);
ERR_FAIL_COND_V_MSG(p_channel >= peer->channelCount, -1, vformat("Unable to send packet on channel %d, max channels: %d", p_channel, (int)peer->channelCount));
return enet_peer_send(peer, p_channel, p_packet);
}
void ENetPacketPeer::reset() {
ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected");
enet_peer_reset(peer);
_on_disconnect();
}
void ENetPacketPeer::throttle_configure(int p_interval, int p_acceleration, int p_deceleration) {
ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected");
enet_peer_throttle_configure(peer, p_interval, p_acceleration, p_deceleration);
}
void ENetPacketPeer::set_timeout(int p_timeout, int p_timeout_min, int p_timeout_max) {
ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected");
ERR_FAIL_COND_MSG(p_timeout > p_timeout_min || p_timeout_min > p_timeout_max, "Timeout limit must be less than minimum timeout, which itself must be less then maximum timeout");
enet_peer_timeout(peer, p_timeout, p_timeout_min, p_timeout_max);
}
int ENetPacketPeer::get_max_packet_size() const {
return 1 << 24;
}
int ENetPacketPeer::get_available_packet_count() const {
return packet_queue.size();
}
Error ENetPacketPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
ERR_FAIL_COND_V(!peer, ERR_UNCONFIGURED);
ERR_FAIL_COND_V(!packet_queue.size(), ERR_UNAVAILABLE);
if (last_packet) {
enet_packet_destroy(last_packet);
last_packet = nullptr;
}
last_packet = packet_queue.front()->get();
packet_queue.pop_front();
*r_buffer = (const uint8_t *)(last_packet->data);
r_buffer_size = last_packet->dataLength;
return OK;
}
Error ENetPacketPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
ERR_FAIL_COND_V(!peer, ERR_UNCONFIGURED);
ENetPacket *packet = enet_packet_create(p_buffer, p_buffer_size, ENET_PACKET_FLAG_RELIABLE);
return send(0, packet) < 0 ? FAILED : OK;
}
IPAddress ENetPacketPeer::get_remote_address() const {
ERR_FAIL_COND_V(!peer, IPAddress());
IPAddress out;
#ifdef GODOT_ENET
out.set_ipv6((uint8_t *)&(peer->address.host));
#else
out.set_ipv4((uint8_t *)&(peer->address.host));
#endif
return out;
}
int ENetPacketPeer::get_remote_port() const {
ERR_FAIL_COND_V(!peer, 0);
return peer->address.port;
}
bool ENetPacketPeer::is_active() const {
return peer != nullptr;
}
double ENetPacketPeer::get_statistic(PeerStatistic p_stat) {
ERR_FAIL_COND_V(!peer, 0);
switch (p_stat) {
case PEER_PACKET_LOSS:
return peer->packetLoss;
case PEER_PACKET_LOSS_VARIANCE:
return peer->packetLossVariance;
case PEER_PACKET_LOSS_EPOCH:
return peer->packetLossEpoch;
case PEER_ROUND_TRIP_TIME:
return peer->roundTripTime;
case PEER_ROUND_TRIP_TIME_VARIANCE:
return peer->roundTripTimeVariance;
case PEER_LAST_ROUND_TRIP_TIME:
return peer->lastRoundTripTime;
case PEER_LAST_ROUND_TRIP_TIME_VARIANCE:
return peer->lastRoundTripTimeVariance;
case PEER_PACKET_THROTTLE:
return peer->packetThrottle;
case PEER_PACKET_THROTTLE_LIMIT:
return peer->packetThrottleLimit;
case PEER_PACKET_THROTTLE_COUNTER:
return peer->packetThrottleCounter;
case PEER_PACKET_THROTTLE_EPOCH:
return peer->packetThrottleEpoch;
case PEER_PACKET_THROTTLE_ACCELERATION:
return peer->packetThrottleAcceleration;
case PEER_PACKET_THROTTLE_DECELERATION:
return peer->packetThrottleDeceleration;
case PEER_PACKET_THROTTLE_INTERVAL:
return peer->packetThrottleInterval;
}
ERR_FAIL_V(0);
}
ENetPacketPeer::PeerState ENetPacketPeer::get_state() const {
if (!is_active()) {
return STATE_DISCONNECTED;
}
return (PeerState)peer->state;
}
int ENetPacketPeer::get_channels() const {
ERR_FAIL_COND_V_MSG(!peer, 0, "The ENetConnection instance isn't currently active.");
return peer->channelCount;
}
void ENetPacketPeer::_on_disconnect() {
if (peer) {
peer->data = nullptr;
}
peer = nullptr;
}
void ENetPacketPeer::_queue_packet(ENetPacket *p_packet) {
ERR_FAIL_COND(!peer);
packet_queue.push_back(p_packet);
}
Error ENetPacketPeer::_send(int p_channel, PackedByteArray p_packet, int p_flags) {
ERR_FAIL_COND_V_MSG(peer == nullptr, ERR_UNCONFIGURED, "Peer not connected");
ERR_FAIL_COND_V_MSG(p_channel < 0 || p_channel > (int)peer->channelCount, ERR_INVALID_PARAMETER, "Invalid channel");
ERR_FAIL_COND_V_MSG(p_flags & ~FLAG_ALLOWED, ERR_INVALID_PARAMETER, "Invalid flags");
ENetPacket *packet = enet_packet_create(p_packet.ptr(), p_packet.size(), p_flags);
return send(p_channel, packet) == 0 ? OK : FAILED;
}
void ENetPacketPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("peer_disconnect", "data"), &ENetPacketPeer::peer_disconnect, DEFVAL(0));
ClassDB::bind_method(D_METHOD("peer_disconnect_later", "data"), &ENetPacketPeer::peer_disconnect_later, DEFVAL(0));
ClassDB::bind_method(D_METHOD("peer_disconnect_now", "data"), &ENetPacketPeer::peer_disconnect_now, DEFVAL(0));
ClassDB::bind_method(D_METHOD("ping"), &ENetPacketPeer::ping);
ClassDB::bind_method(D_METHOD("ping_interval", "ping_interval"), &ENetPacketPeer::ping_interval);
ClassDB::bind_method(D_METHOD("reset"), &ENetPacketPeer::reset);
ClassDB::bind_method(D_METHOD("send", "channel", "packet", "flags"), &ENetPacketPeer::_send);
ClassDB::bind_method(D_METHOD("throttle_configure", "interval", "acceleration", "deceleration"), &ENetPacketPeer::throttle_configure);
ClassDB::bind_method(D_METHOD("set_timeout", "timeout", "timeout_min", "timeout_max"), &ENetPacketPeer::set_timeout);
ClassDB::bind_method(D_METHOD("get_statistic", "statistic"), &ENetPacketPeer::get_statistic);
ClassDB::bind_method(D_METHOD("get_state"), &ENetPacketPeer::get_state);
ClassDB::bind_method(D_METHOD("get_channels"), &ENetPacketPeer::get_channels);
ClassDB::bind_method(D_METHOD("is_active"), &ENetPacketPeer::is_active);
BIND_ENUM_CONSTANT(STATE_DISCONNECTED);
BIND_ENUM_CONSTANT(STATE_CONNECTING);
BIND_ENUM_CONSTANT(STATE_ACKNOWLEDGING_CONNECT);
BIND_ENUM_CONSTANT(STATE_CONNECTION_PENDING);
BIND_ENUM_CONSTANT(STATE_CONNECTION_SUCCEEDED);
BIND_ENUM_CONSTANT(STATE_CONNECTED);
BIND_ENUM_CONSTANT(STATE_DISCONNECT_LATER);
BIND_ENUM_CONSTANT(STATE_DISCONNECTING);
BIND_ENUM_CONSTANT(STATE_ACKNOWLEDGING_DISCONNECT);
BIND_ENUM_CONSTANT(STATE_ZOMBIE);
BIND_ENUM_CONSTANT(PEER_PACKET_LOSS);
BIND_ENUM_CONSTANT(PEER_PACKET_LOSS_VARIANCE);
BIND_ENUM_CONSTANT(PEER_PACKET_LOSS_EPOCH);
BIND_ENUM_CONSTANT(PEER_ROUND_TRIP_TIME);
BIND_ENUM_CONSTANT(PEER_ROUND_TRIP_TIME_VARIANCE);
BIND_ENUM_CONSTANT(PEER_LAST_ROUND_TRIP_TIME);
BIND_ENUM_CONSTANT(PEER_LAST_ROUND_TRIP_TIME_VARIANCE);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_LIMIT);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_COUNTER);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_EPOCH);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_ACCELERATION);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_DECELERATION);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_INTERVAL);
BIND_CONSTANT(PACKET_LOSS_SCALE);
BIND_CONSTANT(PACKET_THROTTLE_SCALE);
BIND_CONSTANT(FLAG_RELIABLE);
BIND_CONSTANT(FLAG_UNSEQUENCED);
BIND_CONSTANT(FLAG_UNRELIABLE_FRAGMENT);
}
ENetPacketPeer::ENetPacketPeer(ENetPeer *p_peer) {
peer = p_peer;
peer->data = this;
}
ENetPacketPeer::~ENetPacketPeer() {
_on_disconnect();
if (last_packet) {
enet_packet_destroy(last_packet);
last_packet = nullptr;
}
for (List<ENetPacket *>::Element *E = packet_queue.front(); E; E = E->next()) {
enet_packet_destroy(E->get());
}
packet_queue.clear();
}

View File

@ -0,0 +1,131 @@
/*************************************************************************/
/* enet_packet_peer.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef ENET_PACKET_PEER_H
#define ENET_PACKET_PEER_H
#include "core/io/packet_peer.h"
#include <enet/enet.h>
class ENetPacketPeer : public PacketPeer {
GDCLASS(ENetPacketPeer, PacketPeer);
private:
ENetPeer *peer = nullptr;
List<ENetPacket *> packet_queue;
ENetPacket *last_packet = nullptr;
static void _bind_methods();
Error _send(int p_channel, PackedByteArray p_packet, int p_flags);
protected:
friend class ENetConnection;
// Internally used by ENetConnection during service, destroy, etc.
void _on_disconnect();
void _queue_packet(ENetPacket *p_packet);
public:
enum {
PACKET_THROTTLE_SCALE = ENET_PEER_PACKET_THROTTLE_SCALE,
PACKET_LOSS_SCALE = ENET_PEER_PACKET_LOSS_SCALE,
};
enum {
FLAG_RELIABLE = ENET_PACKET_FLAG_RELIABLE,
FLAG_UNSEQUENCED = ENET_PACKET_FLAG_UNSEQUENCED,
FLAG_UNRELIABLE_FRAGMENT = ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT,
FLAG_ALLOWED = ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNSEQUENCED | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT,
};
enum PeerState {
STATE_DISCONNECTED = ENET_PEER_STATE_DISCONNECTED,
STATE_CONNECTING = ENET_PEER_STATE_CONNECTING,
STATE_ACKNOWLEDGING_CONNECT = ENET_PEER_STATE_ACKNOWLEDGING_CONNECT,
STATE_CONNECTION_PENDING = ENET_PEER_STATE_CONNECTION_PENDING,
STATE_CONNECTION_SUCCEEDED = ENET_PEER_STATE_CONNECTION_SUCCEEDED,
STATE_CONNECTED = ENET_PEER_STATE_CONNECTED,
STATE_DISCONNECT_LATER = ENET_PEER_STATE_DISCONNECT_LATER,
STATE_DISCONNECTING = ENET_PEER_STATE_DISCONNECTING,
STATE_ACKNOWLEDGING_DISCONNECT = ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT,
STATE_ZOMBIE = ENET_PEER_STATE_ZOMBIE,
};
enum PeerStatistic {
PEER_PACKET_LOSS,
PEER_PACKET_LOSS_VARIANCE,
PEER_PACKET_LOSS_EPOCH,
PEER_ROUND_TRIP_TIME,
PEER_ROUND_TRIP_TIME_VARIANCE,
PEER_LAST_ROUND_TRIP_TIME,
PEER_LAST_ROUND_TRIP_TIME_VARIANCE,
PEER_PACKET_THROTTLE,
PEER_PACKET_THROTTLE_LIMIT,
PEER_PACKET_THROTTLE_COUNTER,
PEER_PACKET_THROTTLE_EPOCH,
PEER_PACKET_THROTTLE_ACCELERATION,
PEER_PACKET_THROTTLE_DECELERATION,
PEER_PACKET_THROTTLE_INTERVAL,
};
int get_max_packet_size() const override;
int get_available_packet_count() const override;
Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet
Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
void peer_disconnect(int p_data = 0);
void peer_disconnect_later(int p_data = 0);
void peer_disconnect_now(int p_data = 0);
void ping();
void ping_interval(int p_interval);
void reset();
int send(uint8_t p_channel, ENetPacket *p_packet);
void throttle_configure(int interval, int acceleration, int deceleration);
void set_timeout(int p_timeout, int p_timeout_min, int p_timeout_max);
double get_statistic(PeerStatistic p_stat);
PeerState get_state() const;
int get_channels() const;
// Extras
IPAddress get_remote_address() const;
int get_remote_port() const;
// Used by ENetMultiplayer (TODO use meta? If only they where StringNames)
bool is_active() const;
ENetPacketPeer(ENetPeer *p_peer);
~ENetPacketPeer();
};
VARIANT_ENUM_CAST(ENetPacketPeer::PeerState);
VARIANT_ENUM_CAST(ENetPacketPeer::PeerStatistic);
#endif // ENET_PACKET_PEER_H

View File

@ -30,7 +30,9 @@
#include "register_types.h"
#include "core/error/error_macros.h"
#include "enet_connection.h"
#include "enet_multiplayer_peer.h"
#include "enet_packet_peer.h"
static bool enet_ok = false;
@ -42,6 +44,8 @@ void register_enet_types() {
}
GDREGISTER_CLASS(ENetMultiplayerPeer);
GDREGISTER_VIRTUAL_CLASS(ENetPacketPeer);
GDREGISTER_CLASS(ENetConnection);
}
void unregister_enet_types() {

View File

@ -39,26 +39,6 @@ WebSocketMultiplayerPeer::~WebSocketMultiplayerPeer() {
_clear();
}
int WebSocketMultiplayerPeer::_gen_unique_id() const {
uint32_t hash = 0;
while (hash == 0 || hash == 1) {
hash = hash_djb2_one_32(
(uint32_t)OS::get_singleton()->get_ticks_usec());
hash = hash_djb2_one_32(
(uint32_t)OS::get_singleton()->get_unix_time(), hash);
hash = hash_djb2_one_32(
(uint32_t)OS::get_singleton()->get_data_path().hash64(), hash);
hash = hash_djb2_one_32(
(uint32_t)((uint64_t)this), hash); //rely on aslr heap
hash = hash_djb2_one_32(
(uint32_t)((uint64_t)&hash), hash); //rely on aslr stack
hash = hash & 0x7FFFFFFF; // make it compatible with unsigned, since negative id is used for exclusion
}
return hash;
}
void WebSocketMultiplayerPeer::_clear() {
_peer_map.clear();
if (_current_packet.data != nullptr) {

View File

@ -75,7 +75,6 @@ protected:
void _send_add(int32_t p_peer_id);
void _send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_type, int32_t p_peer_id);
void _send_del(int32_t p_peer_id);
int _gen_unique_id() const;
public:
/* MultiplayerPeer */

View File

@ -207,7 +207,7 @@ void WSLServer::poll() {
continue;
}
// Creating new peer
int32_t id = _gen_unique_id();
int32_t id = generate_unique_id();
WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
data->obj = this;

View File

@ -11,8 +11,8 @@
*/
ENET_API void enet_address_set_ip(ENetAddress * address, const uint8_t * ip, size_t size);
ENET_API void enet_host_dtls_server_setup (ENetHost *, void *, void *);
ENET_API void enet_host_dtls_client_setup (ENetHost *, void *, uint8_t, const char *);
ENET_API int enet_host_dtls_server_setup (ENetHost *, void *, void *);
ENET_API int enet_host_dtls_client_setup (ENetHost *, void *, uint8_t, const char *);
ENET_API void enet_host_refuse_new_connections (ENetHost *, int);
#endif // __ENET_GODOT_EXT_H__

View File

@ -52,6 +52,7 @@ public:
virtual int set_option(ENetSocketOption p_option, int p_value) = 0;
virtual void close() = 0;
virtual void set_refuse_new_connections(bool p_enable) {} /* Only used by dtls server */
virtual bool can_upgrade() { return false; } /* Only true in ENetUDP */
virtual ~ENetGodotSocket() {}
};
@ -79,6 +80,10 @@ public:
sock->close();
}
bool can_upgrade() {
return true;
}
Error bind(IPAddress p_ip, uint16_t p_port) {
local_address = p_ip;
bound = true;
@ -86,7 +91,11 @@ public:
}
Error get_socket_address(IPAddress *r_ip, uint16_t *r_port) {
return sock->get_socket_address(r_ip, r_port);
Error err = sock->get_socket_address(r_ip, r_port);
if (bound) {
*r_ip = local_address;
}
return err;
}
Error sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) {
@ -195,7 +204,9 @@ public:
Error sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) {
if (!connected) {
udp->connect_to_host(p_ip, p_port);
dtls->connect_to_peer(udp, verify, for_hostname, cert);
if (dtls->connect_to_peer(udp, verify, for_hostname, cert)) {
return FAILED;
}
connected = true;
}
dtls->poll();
@ -424,16 +435,24 @@ ENetSocket enet_socket_create(ENetSocketType type) {
return socket;
}
void enet_host_dtls_server_setup(ENetHost *host, void *p_key, void *p_cert) {
ENetUDP *sock = (ENetUDP *)host->socket;
host->socket = memnew(ENetDTLSServer(sock, Ref<CryptoKey>((CryptoKey *)p_key), Ref<X509Certificate>((X509Certificate *)p_cert)));
int enet_host_dtls_server_setup(ENetHost *host, void *p_key, void *p_cert) {
ENetGodotSocket *sock = (ENetGodotSocket *)host->socket;
if (!sock->can_upgrade()) {
return -1;
}
host->socket = memnew(ENetDTLSServer((ENetUDP *)sock, Ref<CryptoKey>((CryptoKey *)p_key), Ref<X509Certificate>((X509Certificate *)p_cert)));
memdelete(sock);
return 0;
}
void enet_host_dtls_client_setup(ENetHost *host, void *p_cert, uint8_t p_verify, const char *p_for_hostname) {
ENetUDP *sock = (ENetUDP *)host->socket;
host->socket = memnew(ENetDTLSClient(sock, Ref<X509Certificate>((X509Certificate *)p_cert), p_verify, String(p_for_hostname)));
int enet_host_dtls_client_setup(ENetHost *host, void *p_cert, uint8_t p_verify, const char *p_for_hostname) {
ENetGodotSocket *sock = (ENetGodotSocket *)host->socket;
if (!sock->can_upgrade()) {
return -1;
}
host->socket = memnew(ENetDTLSClient((ENetUDP *)sock, Ref<X509Certificate>((X509Certificate *)p_cert), p_verify, String::utf8(p_for_hostname)));
memdelete(sock);
return 0;
}
void enet_host_refuse_new_connections(ENetHost *host, int p_refuse) {