1/**************************************************************************/
2/* webrtc_multiplayer_peer.cpp */
3/**************************************************************************/
4/* This file is part of: */
5/* GODOT ENGINE */
6/* https://godotengine.org */
7/**************************************************************************/
8/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10/* */
11/* Permission is hereby granted, free of charge, to any person obtaining */
12/* a copy of this software and associated documentation files (the */
13/* "Software"), to deal in the Software without restriction, including */
14/* without limitation the rights to use, copy, modify, merge, publish, */
15/* distribute, sublicense, and/or sell copies of the Software, and to */
16/* permit persons to whom the Software is furnished to do so, subject to */
17/* the following conditions: */
18/* */
19/* The above copyright notice and this permission notice shall be */
20/* included in all copies or substantial portions of the Software. */
21/* */
22/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29/**************************************************************************/
30
31#include "webrtc_multiplayer_peer.h"
32
33#include "core/io/marshalls.h"
34#include "core/os/os.h"
35
36void WebRTCMultiplayerPeer::_bind_methods() {
37 ClassDB::bind_method(D_METHOD("create_server", "channels_config"), &WebRTCMultiplayerPeer::create_server, DEFVAL(Array()));
38 ClassDB::bind_method(D_METHOD("create_client", "peer_id", "channels_config"), &WebRTCMultiplayerPeer::create_client, DEFVAL(Array()));
39 ClassDB::bind_method(D_METHOD("create_mesh", "peer_id", "channels_config"), &WebRTCMultiplayerPeer::create_mesh, DEFVAL(Array()));
40 ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayerPeer::add_peer, DEFVAL(1));
41 ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayerPeer::remove_peer);
42 ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayerPeer::has_peer);
43 ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayerPeer::get_peer);
44 ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayerPeer::get_peers);
45}
46
47void WebRTCMultiplayerPeer::set_target_peer(int p_peer_id) {
48 target_peer = p_peer_id;
49}
50
51/* Returns the ID of the MultiplayerPeer who sent the most recent packet: */
52int WebRTCMultiplayerPeer::get_packet_peer() const {
53 return next_packet_peer;
54}
55
56int WebRTCMultiplayerPeer::get_packet_channel() const {
57 return next_packet_channel < CH_RESERVED_MAX ? 0 : next_packet_channel - CH_RESERVED_MAX + 1;
58}
59
60MultiplayerPeer::TransferMode WebRTCMultiplayerPeer::get_packet_mode() const {
61 ERR_FAIL_INDEX_V(next_packet_channel, channels_modes.size(), TRANSFER_MODE_RELIABLE);
62 return channels_modes[next_packet_channel];
63}
64
65bool WebRTCMultiplayerPeer::is_server() const {
66 return unique_id == TARGET_PEER_SERVER;
67}
68
69void WebRTCMultiplayerPeer::poll() {
70 if (peer_map.size() == 0) {
71 return;
72 }
73
74 List<int> remove;
75 List<int> add;
76 for (KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
77 Ref<ConnectedPeer> peer = E.value;
78 peer->connection->poll();
79 // Check peer state
80 switch (peer->connection->get_connection_state()) {
81 case WebRTCPeerConnection::STATE_NEW:
82 case WebRTCPeerConnection::STATE_CONNECTING:
83 // Go to next peer, not ready yet.
84 continue;
85 case WebRTCPeerConnection::STATE_CONNECTED:
86 // Good to go, go ahead and check channel state.
87 break;
88 default:
89 // Peer is closed or in error state. Got to next peer.
90 remove.push_back(E.key);
91 continue;
92 }
93 // Check channels state
94 int ready = 0;
95 for (List<Ref<WebRTCDataChannel>>::Element *C = peer->channels.front(); C && C->get().is_valid(); C = C->next()) {
96 Ref<WebRTCDataChannel> ch = C->get();
97 switch (ch->get_ready_state()) {
98 case WebRTCDataChannel::STATE_CONNECTING:
99 continue;
100 case WebRTCDataChannel::STATE_OPEN:
101 ready++;
102 continue;
103 default:
104 // Channel was closed or in error state, remove peer id.
105 remove.push_back(E.key);
106 }
107 // We got a closed channel break out, the peer will be removed.
108 break;
109 }
110 // This peer has newly connected, and all channels are now open.
111 if (ready == peer->channels.size() && !peer->connected) {
112 peer->connected = true;
113 add.push_back(E.key);
114 }
115 }
116 // Remove disconnected peers
117 for (int &E : remove) {
118 remove_peer(E);
119 if (next_packet_peer == E) {
120 next_packet_peer = 0;
121 }
122 }
123 // Signal newly connected peers
124 for (int &E : add) {
125 // Already connected to server: simply notify new peer.
126 if (network_mode == MODE_CLIENT) {
127 ERR_CONTINUE(E != TARGET_PEER_SERVER); // Bug.
128 // Server connected.
129 connection_status = CONNECTION_CONNECTED;
130 emit_signal(SNAME("peer_connected"), TARGET_PEER_SERVER);
131 } else {
132 emit_signal(SNAME("peer_connected"), E);
133 }
134 }
135 // Fetch next packet
136 if (next_packet_peer == 0) {
137 _find_next_peer();
138 }
139}
140
141void WebRTCMultiplayerPeer::_find_next_peer() {
142 HashMap<int, Ref<ConnectedPeer>>::Iterator E = peer_map.find(next_packet_peer);
143 if (E) {
144 ++E;
145 }
146 // After last.
147 while (E) {
148 if (!E->value->connected) {
149 ++E;
150 continue;
151 }
152 int idx = 0;
153 for (const Ref<WebRTCDataChannel> &F : E->value->channels) {
154 if (F->get_available_packet_count()) {
155 next_packet_channel = idx;
156 next_packet_peer = E->key;
157 return;
158 }
159 idx++;
160 }
161 ++E;
162 }
163 E = peer_map.begin();
164 // Before last
165 while (E) {
166 if (!E->value->connected) {
167 ++E;
168 continue;
169 }
170 int idx = 0;
171 for (const Ref<WebRTCDataChannel> &F : E->value->channels) {
172 if (F->get_available_packet_count()) {
173 next_packet_channel = idx;
174 next_packet_peer = E->key;
175 return;
176 }
177 idx++;
178 }
179 if (E->key == (int)next_packet_peer) {
180 break;
181 }
182 ++E;
183 }
184 // No packet found
185 next_packet_channel = 0;
186 next_packet_peer = 0;
187}
188
189MultiplayerPeer::ConnectionStatus WebRTCMultiplayerPeer::get_connection_status() const {
190 return connection_status;
191}
192
193Error WebRTCMultiplayerPeer::create_server(Array p_channels_config) {
194 return _initialize(1, MODE_SERVER, p_channels_config);
195}
196
197Error WebRTCMultiplayerPeer::create_client(int p_self_id, Array p_channels_config) {
198 ERR_FAIL_COND_V_MSG(p_self_id == 1, ERR_INVALID_PARAMETER, "Clients cannot have ID 1.");
199 return _initialize(p_self_id, MODE_CLIENT, p_channels_config);
200}
201
202Error WebRTCMultiplayerPeer::create_mesh(int p_self_id, Array p_channels_config) {
203 return _initialize(p_self_id, MODE_MESH, p_channels_config);
204}
205
206Error WebRTCMultiplayerPeer::_initialize(int p_self_id, NetworkMode p_mode, Array p_channels_config) {
207 ERR_FAIL_COND_V(p_self_id < 1 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER);
208 channels_config.clear();
209 channels_modes.clear();
210 channels_modes.push_back(TRANSFER_MODE_RELIABLE);
211 channels_modes.push_back(TRANSFER_MODE_UNRELIABLE_ORDERED);
212 channels_modes.push_back(TRANSFER_MODE_UNRELIABLE);
213 for (int i = 0; i < p_channels_config.size(); i++) {
214 ERR_FAIL_COND_V_MSG(p_channels_config[i].get_type() != Variant::INT, ERR_INVALID_PARAMETER, "The 'channels_config' array must contain only enum values from 'MultiplayerPeer.TransferMode'");
215 int mode = p_channels_config[i].operator int();
216 // Initialize data channel configurations.
217 Dictionary cfg;
218 cfg["id"] = CH_RESERVED_MAX + i + 1;
219 cfg["negotiated"] = true;
220 cfg["ordered"] = true;
221
222 switch (mode) {
223 case TRANSFER_MODE_UNRELIABLE_ORDERED:
224 cfg["maxPacketLifetime"] = 1;
225 break;
226 case TRANSFER_MODE_UNRELIABLE:
227 cfg["maxPacketLifetime"] = 1;
228 cfg["ordered"] = false;
229 break;
230 case TRANSFER_MODE_RELIABLE:
231 break;
232 default:
233 ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("The 'channels_config' array must contain only enum values from 'MultiplayerPeer.TransferMode'. Got: %d", mode));
234 }
235 channels_config.push_back(cfg);
236 channels_modes.push_back((TransferMode)mode);
237 }
238
239 unique_id = p_self_id;
240 network_mode = p_mode;
241
242 // Mesh and server are always connected
243 if (p_mode != MODE_CLIENT) {
244 connection_status = CONNECTION_CONNECTED;
245 } else {
246 connection_status = CONNECTION_CONNECTING;
247 }
248 return OK;
249}
250
251bool WebRTCMultiplayerPeer::is_server_relay_supported() const {
252 return network_mode == MODE_SERVER || network_mode == MODE_CLIENT;
253}
254
255int WebRTCMultiplayerPeer::get_unique_id() const {
256 ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1);
257 return unique_id;
258}
259
260void WebRTCMultiplayerPeer::_peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict) {
261 Array channels;
262 for (Ref<WebRTCDataChannel> &F : p_connected_peer->channels) {
263 channels.push_back(F);
264 }
265 r_dict["connection"] = p_connected_peer->connection;
266 r_dict["connected"] = p_connected_peer->connected;
267 r_dict["channels"] = channels;
268}
269
270bool WebRTCMultiplayerPeer::has_peer(int p_peer_id) {
271 return peer_map.has(p_peer_id);
272}
273
274Dictionary WebRTCMultiplayerPeer::get_peer(int p_peer_id) {
275 ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary());
276 Dictionary out;
277 _peer_to_dict(peer_map[p_peer_id], out);
278 return out;
279}
280
281Dictionary WebRTCMultiplayerPeer::get_peers() {
282 Dictionary out;
283 for (const KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
284 Dictionary d;
285 _peer_to_dict(E.value, d);
286 out[E.key] = d;
287 }
288 return out;
289}
290
291Error WebRTCMultiplayerPeer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) {
292 ERR_FAIL_COND_V(network_mode == MODE_NONE, ERR_UNCONFIGURED);
293 ERR_FAIL_COND_V(network_mode == MODE_CLIENT && p_peer_id != 1, ERR_INVALID_PARAMETER);
294 ERR_FAIL_COND_V(network_mode == MODE_SERVER && p_peer_id == 1, ERR_INVALID_PARAMETER);
295 ERR_FAIL_COND_V(p_peer_id < 1 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER);
296 ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER);
297 ERR_FAIL_COND_V(is_refusing_new_connections(), ERR_UNAUTHORIZED);
298 // Peer must be valid, and in new state (to create data channels)
299 ERR_FAIL_COND_V(!p_peer.is_valid(), ERR_INVALID_PARAMETER);
300 ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER);
301
302 Ref<ConnectedPeer> peer = memnew(ConnectedPeer);
303 peer->connection = p_peer;
304
305 // Initialize data channels
306 Dictionary cfg;
307 cfg["negotiated"] = true;
308 cfg["ordered"] = true;
309
310 cfg["id"] = 1;
311 peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg);
312 ERR_FAIL_COND_V(peer->channels[CH_RELIABLE].is_null(), FAILED);
313
314 cfg["id"] = 2;
315 cfg["maxPacketLifetime"] = p_unreliable_lifetime;
316 peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg);
317 ERR_FAIL_COND_V(peer->channels[CH_ORDERED].is_null(), FAILED);
318
319 cfg["id"] = 3;
320 cfg["ordered"] = false;
321 peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg);
322 ERR_FAIL_COND_V(peer->channels[CH_UNRELIABLE].is_null(), FAILED);
323
324 for (const Dictionary &dict : channels_config) {
325 Ref<WebRTCDataChannel> ch = p_peer->create_data_channel(String::num_int64(dict["id"]), dict);
326 ERR_FAIL_COND_V(ch.is_null(), FAILED);
327 peer->channels.push_back(ch);
328 }
329
330 peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map
331
332 return OK;
333}
334
335void WebRTCMultiplayerPeer::remove_peer(int p_peer_id) {
336 ERR_FAIL_COND(!peer_map.has(p_peer_id));
337 Ref<ConnectedPeer> peer = peer_map[p_peer_id];
338 peer_map.erase(p_peer_id);
339 if (peer->connected) {
340 peer->connected = false;
341 emit_signal(SNAME("peer_disconnected"), p_peer_id);
342 if (network_mode == MODE_CLIENT && p_peer_id == TARGET_PEER_SERVER) {
343 connection_status = CONNECTION_DISCONNECTED;
344 }
345 }
346}
347
348void WebRTCMultiplayerPeer::disconnect_peer(int p_peer_id, bool p_force) {
349 ERR_FAIL_COND(!peer_map.has(p_peer_id));
350 if (p_force) {
351 peer_map.erase(p_peer_id);
352 if (network_mode == MODE_CLIENT && p_peer_id == TARGET_PEER_SERVER) {
353 connection_status = CONNECTION_DISCONNECTED;
354 }
355 } else {
356 peer_map[p_peer_id]->connection->close(); // Will be removed during next poll.
357 }
358}
359
360Error WebRTCMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
361 // Peer not available
362 if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) {
363 _find_next_peer();
364 ERR_FAIL_V(ERR_UNAVAILABLE);
365 }
366 for (Ref<WebRTCDataChannel> &E : peer_map[next_packet_peer]->channels) {
367 if (E->get_available_packet_count()) {
368 Error err = E->get_packet(r_buffer, r_buffer_size);
369 _find_next_peer();
370 return err;
371 }
372 }
373 // Channels for that peer were empty. Bug?
374 _find_next_peer();
375 ERR_FAIL_V(ERR_BUG);
376}
377
378Error WebRTCMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
379 ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED);
380
381 int ch = get_transfer_channel();
382 if (ch == 0) {
383 switch (get_transfer_mode()) {
384 case TRANSFER_MODE_RELIABLE:
385 ch = CH_RELIABLE;
386 break;
387 case TRANSFER_MODE_UNRELIABLE_ORDERED:
388 ch = CH_ORDERED;
389 break;
390 case TRANSFER_MODE_UNRELIABLE:
391 ch = CH_UNRELIABLE;
392 break;
393 }
394 } else {
395 ch += CH_RESERVED_MAX - 1;
396 }
397
398 if (target_peer > 0) {
399 HashMap<int, Ref<ConnectedPeer>>::Iterator E = peer_map.find(target_peer);
400 ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer: " + itos(target_peer) + ".");
401
402 ERR_FAIL_COND_V_MSG(E->value->channels.size() <= ch, ERR_INVALID_PARAMETER, vformat("Unable to send packet on channel %d, max channels: %d", ch, E->value->channels.size()));
403 ERR_FAIL_COND_V(E->value->channels[ch].is_null(), ERR_BUG);
404 return E->value->channels[ch]->put_packet(p_buffer, p_buffer_size);
405
406 } else {
407 int exclude = -target_peer;
408
409 for (KeyValue<int, Ref<ConnectedPeer>> &F : peer_map) {
410 // Exclude packet. If target_peer == 0 then don't exclude any packets
411 if (target_peer != 0 && F.key == exclude) {
412 continue;
413 }
414
415 ERR_CONTINUE_MSG(F.value->channels.size() <= ch, vformat("Unable to send packet on channel %d, max channels: %d", ch, F.value->channels.size()));
416 ERR_CONTINUE(F.value->channels[ch].is_null());
417 F.value->channels[ch]->put_packet(p_buffer, p_buffer_size);
418 }
419 }
420 return OK;
421}
422
423int WebRTCMultiplayerPeer::get_available_packet_count() const {
424 if (next_packet_peer == 0) {
425 return 0; // To be sure next call to get_packet works if size > 0 .
426 }
427 int size = 0;
428 for (const KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
429 if (!E.value->connected) {
430 continue;
431 }
432 for (const Ref<WebRTCDataChannel> &F : E.value->channels) {
433 size += F->get_available_packet_count();
434 }
435 }
436 return size;
437}
438
439int WebRTCMultiplayerPeer::get_max_packet_size() const {
440 return 1200;
441}
442
443void WebRTCMultiplayerPeer::close() {
444 peer_map.clear();
445 channels_config.clear();
446 unique_id = 0;
447 next_packet_peer = 0;
448 next_packet_channel = 0;
449 target_peer = 0;
450 network_mode = MODE_NONE;
451 connection_status = CONNECTION_DISCONNECTED;
452}
453
454WebRTCMultiplayerPeer::~WebRTCMultiplayerPeer() {
455 close();
456}
457