Merge pull request #29755 from Faless/webrtc/multiplayer_server_pr
WebRTC Multiplayer peer, documentation
This commit is contained in:
commit
146c1612ed
8 changed files with 697 additions and 10 deletions
|
@ -7,7 +7,8 @@ def configure(env):
|
|||
def get_doc_classes():
|
||||
return [
|
||||
"WebRTCPeerConnection",
|
||||
"WebRTCDataChannel"
|
||||
"WebRTCDataChannel",
|
||||
"WebRTCMultiplayer"
|
||||
]
|
||||
|
||||
def get_doc_path():
|
||||
|
|
|
@ -11,85 +11,106 @@
|
|||
<return type="void">
|
||||
</return>
|
||||
<description>
|
||||
Closes this data channel, notifying the other peer.
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_id" qualifiers="const">
|
||||
<return type="int">
|
||||
</return>
|
||||
<description>
|
||||
Returns the id assigned to this channel during creation (or auto-assigned during negotiation).
|
||||
If the channel is not negotiated out-of-band the id will only be available after the connection is established (will return [code]65535[/code] until then).
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_label" qualifiers="const">
|
||||
<return type="String">
|
||||
</return>
|
||||
<description>
|
||||
Returns the label assigned to this channel during creation.
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_max_packet_life_time" qualifiers="const">
|
||||
<return type="int">
|
||||
</return>
|
||||
<description>
|
||||
Returns the maxPacketLifeTime value assigned to this channel during creation.
|
||||
Will be [code]65535[/code] if not specified.
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_max_retransmits" qualifiers="const">
|
||||
<return type="int">
|
||||
</return>
|
||||
<description>
|
||||
Returns the maxRetransmits value assigned to this channel during creation.
|
||||
Will be [code]65535[/code] if not specified.
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_protocol" qualifiers="const">
|
||||
<return type="String">
|
||||
</return>
|
||||
<description>
|
||||
Returns the sub-proctocol assigned to this channel during creation. An empty string if not specified.
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_ready_state" qualifiers="const">
|
||||
<return type="int" enum="WebRTCDataChannel.ChannelState">
|
||||
</return>
|
||||
<description>
|
||||
Returns the current state of this channel, see [enum WebRTCDataChannel.ChannelState].
|
||||
</description>
|
||||
</method>
|
||||
<method name="is_negotiated" qualifiers="const">
|
||||
<return type="bool">
|
||||
</return>
|
||||
<description>
|
||||
Returns [code]true[/code] if this channel was created with out-of-band configuration.
|
||||
</description>
|
||||
</method>
|
||||
<method name="is_ordered" qualifiers="const">
|
||||
<return type="bool">
|
||||
</return>
|
||||
<description>
|
||||
Returns [code]true[/code] if this channel was created with ordering enabled (default).
|
||||
</description>
|
||||
</method>
|
||||
<method name="poll">
|
||||
<return type="int" enum="Error">
|
||||
</return>
|
||||
<description>
|
||||
Reserved, but not used for now.
|
||||
</description>
|
||||
</method>
|
||||
<method name="was_string_packet" qualifiers="const">
|
||||
<return type="bool">
|
||||
</return>
|
||||
<description>
|
||||
Returns [code]true[/code] if the last received packet was transfered as text. See [property write_mode].
|
||||
</description>
|
||||
</method>
|
||||
</methods>
|
||||
<members>
|
||||
<member name="write_mode" type="int" setter="set_write_mode" getter="get_write_mode" enum="WebRTCDataChannel.WriteMode">
|
||||
The transfer mode to use when sending outgoing packet. Either text or binary.
|
||||
</member>
|
||||
</members>
|
||||
<constants>
|
||||
<constant name="WRITE_MODE_TEXT" value="0" enum="WriteMode">
|
||||
Tells the channel to send data over this channel as text. An external peer (non-godot) would receive this as a string.
|
||||
</constant>
|
||||
<constant name="WRITE_MODE_BINARY" value="1" enum="WriteMode">
|
||||
Tells the channel to send data over this channel as binary. An external peer (non-godot) would receive this as arraybuffer or blob.
|
||||
</constant>
|
||||
<constant name="STATE_CONNECTING" value="0" enum="ChannelState">
|
||||
The channel was created, but it's still trying to connect.
|
||||
</constant>
|
||||
<constant name="STATE_OPEN" value="1" enum="ChannelState">
|
||||
The channel is currently open, and data can flow over it.
|
||||
</constant>
|
||||
<constant name="STATE_CLOSING" value="2" enum="ChannelState">
|
||||
The channel is being closed, no new messages will be accepted, but those already in queue will be flushed.
|
||||
</constant>
|
||||
<constant name="STATE_CLOSED" value="3" enum="ChannelState">
|
||||
The channel was closed, or connection failed.
|
||||
</constant>
|
||||
</constants>
|
||||
</class>
|
||||
|
|
85
modules/webrtc/doc_classes/WebRTCMultiplayer.xml
Normal file
85
modules/webrtc/doc_classes/WebRTCMultiplayer.xml
Normal file
|
@ -0,0 +1,85 @@
|
|||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<class name="WebRTCMultiplayer" inherits="NetworkedMultiplayerPeer" category="Core" version="3.2">
|
||||
<brief_description>
|
||||
A simple interface to create a peer-to-peer mesh network composed of [WebRTCPeerConnection] that is compatible with the [MultiplayerAPI].
|
||||
</brief_description>
|
||||
<description>
|
||||
This class constructs a full mesh of [WebRTCPeerConnection] (one connection for each peer) that can be used as a [member MultiplayerAPI.network_peer].
|
||||
You can add each [WebRTCPeerConnection] via [method add_peer] or remove them via [method remove_peer]. Peers must be added in [constant WebRTCPeerConnection.STATE_NEW] state to allow it to create the appropriate channels. This class will not create offers nor set descriptions, it will only poll them, and notify connections and disconnections.
|
||||
[signal NetworkedMultiplayerPeer.connection_succeeded] and [signal NetworkedMultiplayerPeer.server_disconnected] will not be emitted unless [code]server_compatibility[/code] is [code]true[/code] in [method initialize]. Beside that data transfer works like in a [NetworkedMultiplayerPeer].
|
||||
</description>
|
||||
<tutorials>
|
||||
</tutorials>
|
||||
<methods>
|
||||
<method name="add_peer">
|
||||
<return type="int" enum="Error">
|
||||
</return>
|
||||
<argument index="0" name="peer" type="WebRTCPeerConnection">
|
||||
</argument>
|
||||
<argument index="1" name="peer_id" type="int">
|
||||
</argument>
|
||||
<argument index="2" name="unreliable_lifetime" type="int" default="1">
|
||||
</argument>
|
||||
<description>
|
||||
Add a new peer to the mesh with the given [code]peer_id[/code]. The [WebRTCPeerConnection] must be in state [constant WebRTCPeerConnection.STATE_NEW].
|
||||
Three channels will be created for reliable, unreliable, and ordered transport. The value of [code]unreliable_lifetime[/code] will be passed to the [code]maxPacketLifetime[/code] option when creating unreliable and ordered channels (see [method WebRTCPeerConnection.create_data_channel]).
|
||||
</description>
|
||||
</method>
|
||||
<method name="close">
|
||||
<return type="void">
|
||||
</return>
|
||||
<description>
|
||||
Close all the add peer connections and channels, freeing all resources.
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_peer">
|
||||
<return type="Dictionary">
|
||||
</return>
|
||||
<argument index="0" name="peer_id" type="int">
|
||||
</argument>
|
||||
<description>
|
||||
Return a dictionary representation of the peer with given [code]peer_id[/code] with three keys. [code]connection[/code] containing the [WebRTCPeerConnection] to this peer, [code]channels[/code] an array of three [WebRTCDataChannel], and [code]connected[/code] a boolean representing if the peer connection is currently connected (all three channels are open).
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_peers">
|
||||
<return type="Dictionary">
|
||||
</return>
|
||||
<description>
|
||||
Returns a dictionary which keys are the peer ids and values the peer representation as in [method get_peer]
|
||||
</description>
|
||||
</method>
|
||||
<method name="has_peer">
|
||||
<return type="bool">
|
||||
</return>
|
||||
<argument index="0" name="peer_id" type="int">
|
||||
</argument>
|
||||
<description>
|
||||
Returns [code]true[/code] if the given [code]peer_id[/code] is in the peers map (it might not be connected though).
|
||||
</description>
|
||||
</method>
|
||||
<method name="initialize">
|
||||
<return type="int" enum="Error">
|
||||
</return>
|
||||
<argument index="0" name="peer_id" type="int">
|
||||
</argument>
|
||||
<argument index="1" name="server_compatibility" type="bool" default="false">
|
||||
</argument>
|
||||
<description>
|
||||
Initialize the multiplayer peer with the given [code]peer_id[/code] (must be between 1 and 2147483647).
|
||||
If [code]server_compatibilty[/code] is [code]false[/code] (default), the multiplayer peer will be immediately in state [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED] and [signal NetworkedMultiplayerPeer.connection_succeeded] will not be emitted.
|
||||
If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal NetworkedMultiplayerPeer.peer_connected] signals until a peer with id [constant NetworkedMultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal NetworkedMultiplayerPeer.connection_succeeded]. After that the signal [signal NetworkedMultiplayerPeer.peer_connected] will be emitted for every already connected peer, and any new peer that might connect. If the server peer disconnects after that, signal [signal NetworkedMultiplayerPeer.server_disconnected] will be emitted and state will become [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED].
|
||||
</description>
|
||||
</method>
|
||||
<method name="remove_peer">
|
||||
<return type="void">
|
||||
</return>
|
||||
<argument index="0" name="peer_id" type="int">
|
||||
</argument>
|
||||
<description>
|
||||
Remove the peer with given [code]peer_id[/code] from the mesh. If the peer was connected, and [signal NetworkedMultiplayerPeer.peer_connected] was emitted for it, then [signal NetworkedMultiplayerPeer.peer_disconnected] will be emitted.
|
||||
</description>
|
||||
</method>
|
||||
</methods>
|
||||
<constants>
|
||||
</constants>
|
||||
</class>
|
|
@ -1,8 +1,17 @@
|
|||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<class name="WebRTCPeerConnection" inherits="Reference" category="Core" version="3.2">
|
||||
<brief_description>
|
||||
Interface to a WebRTC peer connection.
|
||||
</brief_description>
|
||||
<description>
|
||||
A WebRTC connection between the local computer and a remote peer. Provides an interface to connect, maintain and monitor the connection.
|
||||
|
||||
Setting up a WebRTC connection between two peers from now on) may not seem a trival task, but it can be broken down into 3 main steps:
|
||||
- The peer that wants to initiate the connection ([code]A[/code] from now on) creates an offer and send it to the other peer ([code]B[/code] from now on).
|
||||
- [code]B[/code] receives the offer, generate and answer, and sends it to [code]B[/code]).
|
||||
- [code]A[/code] and [code]B[/code] then generates and exchange ICE candiates with each other.
|
||||
|
||||
After these steps, the connection should become connected. Keep on reading or look into the tutorial for more information.
|
||||
</description>
|
||||
<tutorials>
|
||||
</tutorials>
|
||||
|
@ -17,12 +26,14 @@
|
|||
<argument index="2" name="name" type="String">
|
||||
</argument>
|
||||
<description>
|
||||
Add an ice candidate generated by a remote peer (and received over the signaling server). See [signal ice_candidate_created].
|
||||
</description>
|
||||
</method>
|
||||
<method name="close">
|
||||
<return type="void">
|
||||
</return>
|
||||
<description>
|
||||
Close the peer connection and all data channels associated with it. Note, you cannot reuse this object for a new connection unless you call [method initialize].
|
||||
</description>
|
||||
</method>
|
||||
<method name="create_data_channel">
|
||||
|
@ -35,18 +46,38 @@
|
|||
}">
|
||||
</argument>
|
||||
<description>
|
||||
Returns a new [WebRTCDataChannel] (or [code]null[/code] on failure) with given [code]label[/code] and optionally configured via the [code]options[/code] dictionary. This method can only be called when the connection is in state [constant STATE_NEW].
|
||||
There are two ways to create a working data channel: either call [method create_data_channel] on only one of the peer and listen to [signal data_channel_received] on the other, or call [method create_data_channel] on both peers, with the same values, and the [code]negotiated[/code] option set to [code]true[/code].
|
||||
Valid [code]options[/code] are:
|
||||
[code]
|
||||
{
|
||||
"negotiated": true, # When set to true (default off), means the channel is negotiated out of band. "id" must be set too. data_channel_received will not be called.
|
||||
"id": 1, # When "negotiated" is true this value must also be set to the same value on both peer.
|
||||
|
||||
# Only one of maxRetransmits and maxPacketLifeTime can be specified, not both. They make the channel unreliable (but also better at real time).
|
||||
"maxRetransmits": 1, # Specify the maximum number of attempt the peer will make to retransmits packets if they are not acknowledged.
|
||||
"maxPacketLifeTime": 100, # Specify the maximum amount of time before giving up retransmitions of unacknowledged packets (in milliseconds).
|
||||
"ordered": true, # When in unreliable mode (i.e. either "maxRetransmits" or "maxPacketLifetime" is set), "ordered" (true by default) specify if packet ordering is to be enforced.
|
||||
|
||||
"protocol": "my-custom-protocol", # A custom sub-protocol string for this channel.
|
||||
}
|
||||
[/code]
|
||||
NOTE: You must keep a reference to channels created this way, or it will be closed.
|
||||
</description>
|
||||
</method>
|
||||
<method name="create_offer">
|
||||
<return type="int" enum="Error">
|
||||
</return>
|
||||
<description>
|
||||
Creates a new SDP offer to start a WebRTC connection with a remote peer. At least one [WebRTCDataChannel] must have been created before calling this method.
|
||||
If this functions returns [code]OK[/code], [signal session_description_created] will be called when the session is ready to be sent.
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_connection_state" qualifiers="const">
|
||||
<return type="int" enum="WebRTCPeerConnection.ConnectionState">
|
||||
</return>
|
||||
<description>
|
||||
Returns the connection state. See [enum ConnectionState].
|
||||
</description>
|
||||
</method>
|
||||
<method name="initialize">
|
||||
|
@ -57,12 +88,29 @@
|
|||
}">
|
||||
</argument>
|
||||
<description>
|
||||
Re-initialize this peer connection, closing any previously active connection, and going back to state [constant STATE_NEW]. A dictionary of [code]options[/code] can be passed to configure the peer connection.
|
||||
Valid [code]options[/code] are:
|
||||
[code]
|
||||
{
|
||||
"iceServers": [
|
||||
{
|
||||
"urls": [ "stun:stun.example.com:3478" ], # One or more STUN servers.
|
||||
},
|
||||
{
|
||||
"urls": [ "turn:turn.example.com:3478" ], # One or more TURN servers.
|
||||
"username": "a_username", # Optional username for the TURN server.
|
||||
"credentials": "a_password", # Optional password for the TURN server.
|
||||
}
|
||||
]
|
||||
}
|
||||
[/code]
|
||||
</description>
|
||||
</method>
|
||||
<method name="poll">
|
||||
<return type="int" enum="Error">
|
||||
</return>
|
||||
<description>
|
||||
Call this method frequently (e.g. in [method Node._process] or [method Node._fixed_process]) to properly receive signals.
|
||||
</description>
|
||||
</method>
|
||||
<method name="set_local_description">
|
||||
|
@ -73,6 +121,8 @@
|
|||
<argument index="1" name="sdp" type="String">
|
||||
</argument>
|
||||
<description>
|
||||
Sets the SDP description of the local peer. This should be called in response to [signal session_description_created].
|
||||
If [code]type[/code] is [code]answer[/code] the peer will start emitting [signal ice_candidate_created].
|
||||
</description>
|
||||
</method>
|
||||
<method name="set_remote_description">
|
||||
|
@ -83,6 +133,9 @@
|
|||
<argument index="1" name="sdp" type="String">
|
||||
</argument>
|
||||
<description>
|
||||
Sets the SDP description of the remote peer. This should be called with the values generated by a remote peer and received over the signaling server.
|
||||
If [code]type[/code] is [code]offer[/code] the peer will emit [signal session_description_created] with the appropriate answer.
|
||||
If [code]type[/code] is [code]answer[/code] the peer will start emitting [signal ice_candidate_created].
|
||||
</description>
|
||||
</method>
|
||||
</methods>
|
||||
|
@ -91,6 +144,8 @@
|
|||
<argument index="0" name="channel" type="Object">
|
||||
</argument>
|
||||
<description>
|
||||
Emitted when a new in-band channel is received, i.e. when the channel was created with [code]negotiated: false[/code] (default).
|
||||
The object will be an instance of [WebRTCDataChannel]. You must keep a reference of it or it will be closed automatically. See [method create_data_channel]
|
||||
</description>
|
||||
</signal>
|
||||
<signal name="ice_candidate_created">
|
||||
|
@ -101,6 +156,7 @@
|
|||
<argument index="2" name="name" type="String">
|
||||
</argument>
|
||||
<description>
|
||||
Emitted when a new ICE candidate has been created. The three parameters are meant to be passed to the remote peer over the signaling server.
|
||||
</description>
|
||||
</signal>
|
||||
<signal name="session_description_created">
|
||||
|
@ -109,21 +165,28 @@
|
|||
<argument index="1" name="sdp" type="String">
|
||||
</argument>
|
||||
<description>
|
||||
Emitted after a successful call to [method create_offer] or [method set_remote_description] (when it generates an answer). The parameters are meant to be passed to [method set_local_description] on this object, and sent to the remote peer over the signaling server.
|
||||
</description>
|
||||
</signal>
|
||||
</signals>
|
||||
<constants>
|
||||
<constant name="STATE_NEW" value="0" enum="ConnectionState">
|
||||
The connection is new, data channels and an offer can be created in this state.
|
||||
</constant>
|
||||
<constant name="STATE_CONNECTING" value="1" enum="ConnectionState">
|
||||
The peer is connecting, ICE is in progress, non of the transports has failed.
|
||||
</constant>
|
||||
<constant name="STATE_CONNECTED" value="2" enum="ConnectionState">
|
||||
The peer is connected, all ICE transports are connected.
|
||||
</constant>
|
||||
<constant name="STATE_DISCONNECTED" value="3" enum="ConnectionState">
|
||||
At least one ICE transport is disconnected.
|
||||
</constant>
|
||||
<constant name="STATE_FAILED" value="4" enum="ConnectionState">
|
||||
One or more of the ICE transports failed.
|
||||
</constant>
|
||||
<constant name="STATE_CLOSED" value="5" enum="ConnectionState">
|
||||
The peer connection is closed (after calling [method close] for example).
|
||||
</constant>
|
||||
</constants>
|
||||
</class>
|
||||
|
|
|
@ -40,6 +40,7 @@
|
|||
#include "webrtc_data_channel_gdnative.h"
|
||||
#include "webrtc_peer_connection_gdnative.h"
|
||||
#endif
|
||||
#include "webrtc_multiplayer.h"
|
||||
|
||||
void register_webrtc_types() {
|
||||
#ifdef JAVASCRIPT_ENABLED
|
||||
|
@ -54,6 +55,7 @@ void register_webrtc_types() {
|
|||
ClassDB::register_class<WebRTCDataChannelGDNative>();
|
||||
#endif
|
||||
ClassDB::register_virtual_class<WebRTCDataChannel>();
|
||||
ClassDB::register_class<WebRTCMultiplayer>();
|
||||
}
|
||||
|
||||
void unregister_webrtc_types() {}
|
||||
|
|
|
@ -205,30 +205,45 @@ String WebRTCDataChannelJS::get_label() const {
|
|||
}
|
||||
|
||||
/* clang-format off */
|
||||
#define _JS_GET(PROP) \
|
||||
#define _JS_GET(PROP, DEF) \
|
||||
EM_ASM_INT({ \
|
||||
var dict = Module.IDHandler.get($0); \
|
||||
if (!dict || !dict["channel"]) { \
|
||||
return 0; \
|
||||
}; \
|
||||
return dict["channel"].PROP; \
|
||||
return DEF; \
|
||||
} \
|
||||
var out = dict["channel"].PROP; \
|
||||
return out === null ? DEF : out; \
|
||||
}, _js_id)
|
||||
/* clang-format on */
|
||||
|
||||
bool WebRTCDataChannelJS::is_ordered() const {
|
||||
return _JS_GET(ordered);
|
||||
return _JS_GET(ordered, true);
|
||||
}
|
||||
|
||||
int WebRTCDataChannelJS::get_id() const {
|
||||
return _JS_GET(id);
|
||||
return _JS_GET(id, 65535);
|
||||
}
|
||||
|
||||
int WebRTCDataChannelJS::get_max_packet_life_time() const {
|
||||
return _JS_GET(maxPacketLifeTime);
|
||||
// Can't use macro, webkit workaround.
|
||||
/* clang-format off */
|
||||
return EM_ASM_INT({
|
||||
var dict = Module.IDHandler.get($0);
|
||||
if (!dict || !dict["channel"]) {
|
||||
return 65535;
|
||||
}
|
||||
if (dict["channel"].maxRetransmitTime !== undefined) {
|
||||
// Guess someone didn't appreciate the standardization process.
|
||||
return dict["channel"].maxRetransmitTime;
|
||||
}
|
||||
var out = dict["channel"].maxPacketLifeTime;
|
||||
return out === null ? 65535 : out;
|
||||
}, _js_id);
|
||||
/* clang-format on */
|
||||
}
|
||||
|
||||
int WebRTCDataChannelJS::get_max_retransmits() const {
|
||||
return _JS_GET(maxRetransmits);
|
||||
return _JS_GET(maxRetransmits, 65535);
|
||||
}
|
||||
|
||||
String WebRTCDataChannelJS::get_protocol() const {
|
||||
|
@ -236,7 +251,7 @@ String WebRTCDataChannelJS::get_protocol() const {
|
|||
}
|
||||
|
||||
bool WebRTCDataChannelJS::is_negotiated() const {
|
||||
return _JS_GET(negotiated);
|
||||
return _JS_GET(negotiated, false);
|
||||
}
|
||||
|
||||
WebRTCDataChannelJS::WebRTCDataChannelJS() {
|
||||
|
|
384
modules/webrtc/webrtc_multiplayer.cpp
Normal file
384
modules/webrtc/webrtc_multiplayer.cpp
Normal file
|
@ -0,0 +1,384 @@
|
|||
/*************************************************************************/
|
||||
/* webrtc_multiplayer.cpp */
|
||||
/*************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/*************************************************************************/
|
||||
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
|
||||
/* Copyright (c) 2014-2019 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 "webrtc_multiplayer.h"
|
||||
|
||||
#include "core/io/marshalls.h"
|
||||
#include "core/os/os.h"
|
||||
|
||||
void WebRTCMultiplayer::_bind_methods() {
|
||||
ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility"), &WebRTCMultiplayer::initialize, DEFVAL(false));
|
||||
ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayer::add_peer, DEFVAL(1));
|
||||
ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayer::remove_peer);
|
||||
ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayer::has_peer);
|
||||
ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayer::get_peer);
|
||||
ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayer::get_peers);
|
||||
ClassDB::bind_method(D_METHOD("close"), &WebRTCMultiplayer::close);
|
||||
}
|
||||
|
||||
void WebRTCMultiplayer::set_transfer_mode(TransferMode p_mode) {
|
||||
transfer_mode = p_mode;
|
||||
}
|
||||
|
||||
NetworkedMultiplayerPeer::TransferMode WebRTCMultiplayer::get_transfer_mode() const {
|
||||
return transfer_mode;
|
||||
}
|
||||
|
||||
void WebRTCMultiplayer::set_target_peer(int p_peer_id) {
|
||||
target_peer = p_peer_id;
|
||||
}
|
||||
|
||||
/* Returns the ID of the NetworkedMultiplayerPeer who sent the most recent packet: */
|
||||
int WebRTCMultiplayer::get_packet_peer() const {
|
||||
return next_packet_peer;
|
||||
}
|
||||
|
||||
bool WebRTCMultiplayer::is_server() const {
|
||||
return unique_id == TARGET_PEER_SERVER;
|
||||
}
|
||||
|
||||
void WebRTCMultiplayer::poll() {
|
||||
if (peer_map.size() == 0)
|
||||
return;
|
||||
|
||||
List<int> remove;
|
||||
List<int> add;
|
||||
for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) {
|
||||
Ref<ConnectedPeer> peer = E->get();
|
||||
peer->connection->poll();
|
||||
// Check peer state
|
||||
switch (peer->connection->get_connection_state()) {
|
||||
case WebRTCPeerConnection::STATE_NEW:
|
||||
case WebRTCPeerConnection::STATE_CONNECTING:
|
||||
// Go to next peer, not ready yet.
|
||||
continue;
|
||||
case WebRTCPeerConnection::STATE_CONNECTED:
|
||||
// Good to go, go ahead and check channel state.
|
||||
break;
|
||||
default:
|
||||
// Peer is closed or in error state. Got to next peer.
|
||||
remove.push_back(E->key());
|
||||
continue;
|
||||
}
|
||||
// Check channels state
|
||||
int ready = 0;
|
||||
for (List<Ref<WebRTCDataChannel> >::Element *C = peer->channels.front(); C && C->get().is_valid(); C = C->next()) {
|
||||
Ref<WebRTCDataChannel> ch = C->get();
|
||||
switch (ch->get_ready_state()) {
|
||||
case WebRTCDataChannel::STATE_CONNECTING:
|
||||
continue;
|
||||
case WebRTCDataChannel::STATE_OPEN:
|
||||
ready++;
|
||||
continue;
|
||||
default:
|
||||
// Channel was closed or in error state, remove peer id.
|
||||
remove.push_back(E->key());
|
||||
}
|
||||
// We got a closed channel break out, the peer will be removed.
|
||||
break;
|
||||
}
|
||||
// This peer has newly connected, and all channels are now open.
|
||||
if (ready == peer->channels.size() && !peer->connected) {
|
||||
peer->connected = true;
|
||||
add.push_back(E->key());
|
||||
}
|
||||
}
|
||||
// Remove disconnected peers
|
||||
for (List<int>::Element *E = remove.front(); E; E = E->next()) {
|
||||
remove_peer(E->get());
|
||||
if (next_packet_peer == E->get())
|
||||
next_packet_peer = 0;
|
||||
}
|
||||
// Signal newly connected peers
|
||||
for (List<int>::Element *E = add.front(); E; E = E->next()) {
|
||||
// Already connected to server: simply notify new peer.
|
||||
// NOTE: Mesh is always connected.
|
||||
if (connection_status == CONNECTION_CONNECTED)
|
||||
emit_signal("peer_connected", E->get());
|
||||
|
||||
// Server emulation mode suppresses peer_conencted until server connects.
|
||||
if (server_compat && E->get() == TARGET_PEER_SERVER) {
|
||||
// Server connected.
|
||||
connection_status = CONNECTION_CONNECTED;
|
||||
emit_signal("peer_connected", TARGET_PEER_SERVER);
|
||||
emit_signal("connection_succeeded");
|
||||
// Notify of all previously connected peers
|
||||
for (Map<int, Ref<ConnectedPeer> >::Element *F = peer_map.front(); F; F = F->next()) {
|
||||
if (F->key() != 1 && F->get()->connected)
|
||||
emit_signal("peer_connected", F->key());
|
||||
}
|
||||
break; // Because we already notified of all newly added peers.
|
||||
}
|
||||
}
|
||||
// Fetch next packet
|
||||
if (next_packet_peer == 0)
|
||||
_find_next_peer();
|
||||
}
|
||||
|
||||
void WebRTCMultiplayer::_find_next_peer() {
|
||||
Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.find(next_packet_peer);
|
||||
if (E) E = E->next();
|
||||
// After last.
|
||||
while (E) {
|
||||
for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) {
|
||||
if (F->get()->get_available_packet_count()) {
|
||||
next_packet_peer = E->key();
|
||||
return;
|
||||
}
|
||||
}
|
||||
E = E->next();
|
||||
}
|
||||
E = peer_map.front();
|
||||
// Before last
|
||||
while (E) {
|
||||
for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) {
|
||||
if (F->get()->get_available_packet_count()) {
|
||||
next_packet_peer = E->key();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (E->key() == (int)next_packet_peer)
|
||||
break;
|
||||
E = E->next();
|
||||
}
|
||||
// No packet found
|
||||
next_packet_peer = 0;
|
||||
}
|
||||
|
||||
void WebRTCMultiplayer::set_refuse_new_connections(bool p_enable) {
|
||||
refuse_connections = p_enable;
|
||||
}
|
||||
|
||||
bool WebRTCMultiplayer::is_refusing_new_connections() const {
|
||||
return refuse_connections;
|
||||
}
|
||||
|
||||
NetworkedMultiplayerPeer::ConnectionStatus WebRTCMultiplayer::get_connection_status() const {
|
||||
return connection_status;
|
||||
}
|
||||
|
||||
Error WebRTCMultiplayer::initialize(int p_self_id, bool p_server_compat) {
|
||||
ERR_FAIL_COND_V(p_self_id < 0 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER);
|
||||
unique_id = p_self_id;
|
||||
server_compat = p_server_compat;
|
||||
|
||||
// Mesh and server are always connected
|
||||
if (!server_compat || p_self_id == 1)
|
||||
connection_status = CONNECTION_CONNECTED;
|
||||
else
|
||||
connection_status = CONNECTION_CONNECTING;
|
||||
return OK;
|
||||
}
|
||||
|
||||
int WebRTCMultiplayer::get_unique_id() const {
|
||||
ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1);
|
||||
return unique_id;
|
||||
}
|
||||
|
||||
void WebRTCMultiplayer::_peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict) {
|
||||
Array channels;
|
||||
for (List<Ref<WebRTCDataChannel> >::Element *F = p_connected_peer->channels.front(); F; F = F->next()) {
|
||||
channels.push_back(F->get());
|
||||
}
|
||||
r_dict["connection"] = p_connected_peer->connection;
|
||||
r_dict["connected"] = p_connected_peer->connected;
|
||||
r_dict["channels"] = channels;
|
||||
}
|
||||
|
||||
bool WebRTCMultiplayer::has_peer(int p_peer_id) {
|
||||
return peer_map.has(p_peer_id);
|
||||
}
|
||||
|
||||
Dictionary WebRTCMultiplayer::get_peer(int p_peer_id) {
|
||||
ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary());
|
||||
Dictionary out;
|
||||
_peer_to_dict(peer_map[p_peer_id], out);
|
||||
return out;
|
||||
}
|
||||
|
||||
Dictionary WebRTCMultiplayer::get_peers() {
|
||||
Dictionary out;
|
||||
for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) {
|
||||
Dictionary d;
|
||||
_peer_to_dict(E->get(), d);
|
||||
out[E->key()] = d;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Error WebRTCMultiplayer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) {
|
||||
ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER);
|
||||
ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER);
|
||||
ERR_FAIL_COND_V(refuse_connections, ERR_UNAUTHORIZED);
|
||||
// Peer must be valid, and in new state (to create data channels)
|
||||
ERR_FAIL_COND_V(!p_peer.is_valid(), ERR_INVALID_PARAMETER);
|
||||
ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER);
|
||||
|
||||
Ref<ConnectedPeer> peer = memnew(ConnectedPeer);
|
||||
peer->connection = p_peer;
|
||||
|
||||
// Initialize data channels
|
||||
Dictionary cfg;
|
||||
cfg["negotiated"] = true;
|
||||
cfg["ordered"] = true;
|
||||
|
||||
cfg["id"] = 1;
|
||||
peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg);
|
||||
ERR_FAIL_COND_V(!peer->channels[CH_RELIABLE].is_valid(), FAILED);
|
||||
|
||||
cfg["id"] = 2;
|
||||
cfg["maxPacketLifetime"] = p_unreliable_lifetime;
|
||||
peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg);
|
||||
ERR_FAIL_COND_V(!peer->channels[CH_ORDERED].is_valid(), FAILED);
|
||||
|
||||
cfg["id"] = 3;
|
||||
cfg["ordered"] = false;
|
||||
peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg);
|
||||
ERR_FAIL_COND_V(!peer->channels[CH_UNRELIABLE].is_valid(), FAILED);
|
||||
|
||||
peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map
|
||||
|
||||
return OK;
|
||||
}
|
||||
|
||||
void WebRTCMultiplayer::remove_peer(int p_peer_id) {
|
||||
ERR_FAIL_COND(!peer_map.has(p_peer_id));
|
||||
Ref<ConnectedPeer> peer = peer_map[p_peer_id];
|
||||
peer_map.erase(p_peer_id);
|
||||
if (peer->connected) {
|
||||
peer->connected = false;
|
||||
emit_signal("peer_disconnected", p_peer_id);
|
||||
if (server_compat && p_peer_id == TARGET_PEER_SERVER) {
|
||||
emit_signal("server_disconnected");
|
||||
connection_status = CONNECTION_DISCONNECTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Error WebRTCMultiplayer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
|
||||
// Peer not available
|
||||
if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) {
|
||||
_find_next_peer();
|
||||
ERR_FAIL_V(ERR_UNAVAILABLE);
|
||||
}
|
||||
for (List<Ref<WebRTCDataChannel> >::Element *E = peer_map[next_packet_peer]->channels.front(); E; E = E->next()) {
|
||||
if (E->get()->get_available_packet_count()) {
|
||||
Error err = E->get()->get_packet(r_buffer, r_buffer_size);
|
||||
_find_next_peer();
|
||||
return err;
|
||||
}
|
||||
}
|
||||
// Channels for that peer were empty. Bug?
|
||||
_find_next_peer();
|
||||
ERR_FAIL_V(ERR_BUG);
|
||||
}
|
||||
|
||||
Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
|
||||
ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED);
|
||||
|
||||
int ch = CH_RELIABLE;
|
||||
switch (transfer_mode) {
|
||||
case TRANSFER_MODE_RELIABLE:
|
||||
ch = CH_RELIABLE;
|
||||
break;
|
||||
case TRANSFER_MODE_UNRELIABLE_ORDERED:
|
||||
ch = CH_ORDERED;
|
||||
break;
|
||||
case TRANSFER_MODE_UNRELIABLE:
|
||||
ch = CH_UNRELIABLE;
|
||||
break;
|
||||
}
|
||||
|
||||
Map<int, Ref<ConnectedPeer> >::Element *E = NULL;
|
||||
|
||||
if (target_peer > 0) {
|
||||
|
||||
E = peer_map.find(target_peer);
|
||||
if (!E) {
|
||||
ERR_EXPLAIN("Invalid Target Peer: " + itos(target_peer));
|
||||
ERR_FAIL_V(ERR_INVALID_PARAMETER);
|
||||
}
|
||||
ERR_FAIL_COND_V(E->value()->channels.size() <= ch, ERR_BUG);
|
||||
ERR_FAIL_COND_V(!E->value()->channels[ch].is_valid(), ERR_BUG);
|
||||
return E->value()->channels[ch]->put_packet(p_buffer, p_buffer_size);
|
||||
|
||||
} else {
|
||||
int exclude = -target_peer;
|
||||
|
||||
for (Map<int, Ref<ConnectedPeer> >::Element *F = peer_map.front(); F; F = F->next()) {
|
||||
|
||||
// Exclude packet. If target_peer == 0 then don't exclude any packets
|
||||
if (target_peer != 0 && F->key() == exclude)
|
||||
continue;
|
||||
|
||||
ERR_CONTINUE(F->value()->channels.size() <= ch || !F->value()->channels[ch].is_valid());
|
||||
F->value()->channels[ch]->put_packet(p_buffer, p_buffer_size);
|
||||
}
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
int WebRTCMultiplayer::get_available_packet_count() const {
|
||||
if (next_packet_peer == 0)
|
||||
return 0; // To be sure next call to get_packet works if size > 0 .
|
||||
int size = 0;
|
||||
for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) {
|
||||
for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) {
|
||||
size += F->get()->get_available_packet_count();
|
||||
}
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
int WebRTCMultiplayer::get_max_packet_size() const {
|
||||
return 1200;
|
||||
}
|
||||
|
||||
void WebRTCMultiplayer::close() {
|
||||
peer_map.clear();
|
||||
unique_id = 0;
|
||||
next_packet_peer = 0;
|
||||
target_peer = 0;
|
||||
connection_status = CONNECTION_DISCONNECTED;
|
||||
}
|
||||
|
||||
WebRTCMultiplayer::WebRTCMultiplayer() {
|
||||
unique_id = 0;
|
||||
next_packet_peer = 0;
|
||||
target_peer = 0;
|
||||
transfer_mode = TRANSFER_MODE_RELIABLE;
|
||||
refuse_connections = false;
|
||||
connection_status = CONNECTION_DISCONNECTED;
|
||||
server_compat = false;
|
||||
}
|
||||
|
||||
WebRTCMultiplayer::~WebRTCMultiplayer() {
|
||||
close();
|
||||
}
|
116
modules/webrtc/webrtc_multiplayer.h
Normal file
116
modules/webrtc/webrtc_multiplayer.h
Normal file
|
@ -0,0 +1,116 @@
|
|||
/*************************************************************************/
|
||||
/* webrtc_multiplayer.h */
|
||||
/*************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/*************************************************************************/
|
||||
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
|
||||
/* Copyright (c) 2014-2019 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 WEBRTC_MULTIPLAYER_H
|
||||
#define WEBRTC_MULTIPLAYER_H
|
||||
|
||||
#include "core/io/networked_multiplayer_peer.h"
|
||||
#include "webrtc_peer_connection.h"
|
||||
|
||||
class WebRTCMultiplayer : public NetworkedMultiplayerPeer {
|
||||
|
||||
GDCLASS(WebRTCMultiplayer, NetworkedMultiplayerPeer);
|
||||
|
||||
protected:
|
||||
static void _bind_methods();
|
||||
|
||||
private:
|
||||
enum {
|
||||
CH_RELIABLE = 0,
|
||||
CH_ORDERED = 1,
|
||||
CH_UNRELIABLE = 2,
|
||||
CH_RESERVED_MAX = 3
|
||||
};
|
||||
|
||||
class ConnectedPeer : public Reference {
|
||||
|
||||
public:
|
||||
Ref<WebRTCPeerConnection> connection;
|
||||
List<Ref<WebRTCDataChannel> > channels;
|
||||
bool connected;
|
||||
|
||||
ConnectedPeer() {
|
||||
connected = false;
|
||||
for (int i = 0; i < CH_RESERVED_MAX; i++)
|
||||
channels.push_front(Ref<WebRTCDataChannel>());
|
||||
}
|
||||
};
|
||||
|
||||
uint32_t unique_id;
|
||||
int target_peer;
|
||||
int client_count;
|
||||
bool refuse_connections;
|
||||
ConnectionStatus connection_status;
|
||||
TransferMode transfer_mode;
|
||||
int next_packet_peer;
|
||||
bool server_compat;
|
||||
|
||||
Map<int, Ref<ConnectedPeer> > peer_map;
|
||||
|
||||
void _peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict);
|
||||
void _find_next_peer();
|
||||
|
||||
public:
|
||||
WebRTCMultiplayer();
|
||||
~WebRTCMultiplayer();
|
||||
|
||||
Error initialize(int p_self_id, bool p_server_compat = false);
|
||||
Error add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime = 1);
|
||||
void remove_peer(int p_peer_id);
|
||||
bool has_peer(int p_peer_id);
|
||||
Dictionary get_peer(int p_peer_id);
|
||||
Dictionary get_peers();
|
||||
void close();
|
||||
|
||||
// PacketPeer
|
||||
Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet
|
||||
Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
|
||||
int get_available_packet_count() const;
|
||||
int get_max_packet_size() const;
|
||||
|
||||
// NetworkedMultiplayerPeer
|
||||
void set_transfer_mode(TransferMode p_mode);
|
||||
TransferMode get_transfer_mode() const;
|
||||
void set_target_peer(int p_peer_id);
|
||||
|
||||
int get_unique_id() const;
|
||||
int get_packet_peer() const;
|
||||
|
||||
bool is_server() const;
|
||||
|
||||
void poll();
|
||||
|
||||
void set_refuse_new_connections(bool p_enable);
|
||||
bool is_refusing_new_connections() const;
|
||||
|
||||
ConnectionStatus get_connection_status() const;
|
||||
};
|
||||
|
||||
#endif
|
Loading…
Reference in a new issue