2
0

webrtc_multiplayer.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /*************************************************************************/
  2. /* webrtc_multiplayer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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. #include "webrtc_multiplayer.h"
  31. #include "core/io/marshalls.h"
  32. #include "core/os/os.h"
  33. void WebRTCMultiplayer::_bind_methods() {
  34. ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility"), &WebRTCMultiplayer::initialize, DEFVAL(false));
  35. ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayer::add_peer, DEFVAL(1));
  36. ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayer::remove_peer);
  37. ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayer::has_peer);
  38. ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayer::get_peer);
  39. ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayer::get_peers);
  40. ClassDB::bind_method(D_METHOD("close"), &WebRTCMultiplayer::close);
  41. }
  42. void WebRTCMultiplayer::set_transfer_mode(TransferMode p_mode) {
  43. transfer_mode = p_mode;
  44. }
  45. NetworkedMultiplayerPeer::TransferMode WebRTCMultiplayer::get_transfer_mode() const {
  46. return transfer_mode;
  47. }
  48. void WebRTCMultiplayer::set_target_peer(int p_peer_id) {
  49. target_peer = p_peer_id;
  50. }
  51. /* Returns the ID of the NetworkedMultiplayerPeer who sent the most recent packet: */
  52. int WebRTCMultiplayer::get_packet_peer() const {
  53. return next_packet_peer;
  54. }
  55. bool WebRTCMultiplayer::is_server() const {
  56. return unique_id == TARGET_PEER_SERVER;
  57. }
  58. void WebRTCMultiplayer::poll() {
  59. if (peer_map.size() == 0)
  60. return;
  61. List<int> remove;
  62. List<int> add;
  63. for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) {
  64. Ref<ConnectedPeer> peer = E->get();
  65. peer->connection->poll();
  66. // Check peer state
  67. switch (peer->connection->get_connection_state()) {
  68. case WebRTCPeerConnection::STATE_NEW:
  69. case WebRTCPeerConnection::STATE_CONNECTING:
  70. // Go to next peer, not ready yet.
  71. continue;
  72. case WebRTCPeerConnection::STATE_CONNECTED:
  73. // Good to go, go ahead and check channel state.
  74. break;
  75. default:
  76. // Peer is closed or in error state. Got to next peer.
  77. remove.push_back(E->key());
  78. continue;
  79. }
  80. // Check channels state
  81. int ready = 0;
  82. for (List<Ref<WebRTCDataChannel> >::Element *C = peer->channels.front(); C && C->get().is_valid(); C = C->next()) {
  83. Ref<WebRTCDataChannel> ch = C->get();
  84. switch (ch->get_ready_state()) {
  85. case WebRTCDataChannel::STATE_CONNECTING:
  86. continue;
  87. case WebRTCDataChannel::STATE_OPEN:
  88. ready++;
  89. continue;
  90. default:
  91. // Channel was closed or in error state, remove peer id.
  92. remove.push_back(E->key());
  93. }
  94. // We got a closed channel break out, the peer will be removed.
  95. break;
  96. }
  97. // This peer has newly connected, and all channels are now open.
  98. if (ready == peer->channels.size() && !peer->connected) {
  99. peer->connected = true;
  100. add.push_back(E->key());
  101. }
  102. }
  103. // Remove disconnected peers
  104. for (List<int>::Element *E = remove.front(); E; E = E->next()) {
  105. remove_peer(E->get());
  106. if (next_packet_peer == E->get())
  107. next_packet_peer = 0;
  108. }
  109. // Signal newly connected peers
  110. for (List<int>::Element *E = add.front(); E; E = E->next()) {
  111. // Already connected to server: simply notify new peer.
  112. // NOTE: Mesh is always connected.
  113. if (connection_status == CONNECTION_CONNECTED)
  114. emit_signal("peer_connected", E->get());
  115. // Server emulation mode suppresses peer_conencted until server connects.
  116. if (server_compat && E->get() == TARGET_PEER_SERVER) {
  117. // Server connected.
  118. connection_status = CONNECTION_CONNECTED;
  119. emit_signal("peer_connected", TARGET_PEER_SERVER);
  120. emit_signal("connection_succeeded");
  121. // Notify of all previously connected peers
  122. for (Map<int, Ref<ConnectedPeer> >::Element *F = peer_map.front(); F; F = F->next()) {
  123. if (F->key() != 1 && F->get()->connected)
  124. emit_signal("peer_connected", F->key());
  125. }
  126. break; // Because we already notified of all newly added peers.
  127. }
  128. }
  129. // Fetch next packet
  130. if (next_packet_peer == 0)
  131. _find_next_peer();
  132. }
  133. void WebRTCMultiplayer::_find_next_peer() {
  134. Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.find(next_packet_peer);
  135. if (E) E = E->next();
  136. // After last.
  137. while (E) {
  138. for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) {
  139. if (F->get()->get_available_packet_count()) {
  140. next_packet_peer = E->key();
  141. return;
  142. }
  143. }
  144. E = E->next();
  145. }
  146. E = peer_map.front();
  147. // Before last
  148. while (E) {
  149. for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) {
  150. if (F->get()->get_available_packet_count()) {
  151. next_packet_peer = E->key();
  152. return;
  153. }
  154. }
  155. if (E->key() == (int)next_packet_peer)
  156. break;
  157. E = E->next();
  158. }
  159. // No packet found
  160. next_packet_peer = 0;
  161. }
  162. void WebRTCMultiplayer::set_refuse_new_connections(bool p_enable) {
  163. refuse_connections = p_enable;
  164. }
  165. bool WebRTCMultiplayer::is_refusing_new_connections() const {
  166. return refuse_connections;
  167. }
  168. NetworkedMultiplayerPeer::ConnectionStatus WebRTCMultiplayer::get_connection_status() const {
  169. return connection_status;
  170. }
  171. Error WebRTCMultiplayer::initialize(int p_self_id, bool p_server_compat) {
  172. ERR_FAIL_COND_V(p_self_id < 0 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER);
  173. unique_id = p_self_id;
  174. server_compat = p_server_compat;
  175. // Mesh and server are always connected
  176. if (!server_compat || p_self_id == 1)
  177. connection_status = CONNECTION_CONNECTED;
  178. else
  179. connection_status = CONNECTION_CONNECTING;
  180. return OK;
  181. }
  182. int WebRTCMultiplayer::get_unique_id() const {
  183. ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1);
  184. return unique_id;
  185. }
  186. void WebRTCMultiplayer::_peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict) {
  187. Array channels;
  188. for (List<Ref<WebRTCDataChannel> >::Element *F = p_connected_peer->channels.front(); F; F = F->next()) {
  189. channels.push_back(F->get());
  190. }
  191. r_dict["connection"] = p_connected_peer->connection;
  192. r_dict["connected"] = p_connected_peer->connected;
  193. r_dict["channels"] = channels;
  194. }
  195. bool WebRTCMultiplayer::has_peer(int p_peer_id) {
  196. return peer_map.has(p_peer_id);
  197. }
  198. Dictionary WebRTCMultiplayer::get_peer(int p_peer_id) {
  199. ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary());
  200. Dictionary out;
  201. _peer_to_dict(peer_map[p_peer_id], out);
  202. return out;
  203. }
  204. Dictionary WebRTCMultiplayer::get_peers() {
  205. Dictionary out;
  206. for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) {
  207. Dictionary d;
  208. _peer_to_dict(E->get(), d);
  209. out[E->key()] = d;
  210. }
  211. return out;
  212. }
  213. Error WebRTCMultiplayer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) {
  214. ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER);
  215. ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER);
  216. ERR_FAIL_COND_V(refuse_connections, ERR_UNAUTHORIZED);
  217. // Peer must be valid, and in new state (to create data channels)
  218. ERR_FAIL_COND_V(!p_peer.is_valid(), ERR_INVALID_PARAMETER);
  219. ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER);
  220. Ref<ConnectedPeer> peer = memnew(ConnectedPeer);
  221. peer->connection = p_peer;
  222. // Initialize data channels
  223. Dictionary cfg;
  224. cfg["negotiated"] = true;
  225. cfg["ordered"] = true;
  226. cfg["id"] = 1;
  227. peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg);
  228. ERR_FAIL_COND_V(!peer->channels[CH_RELIABLE].is_valid(), FAILED);
  229. cfg["id"] = 2;
  230. cfg["maxPacketLifetime"] = p_unreliable_lifetime;
  231. peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg);
  232. ERR_FAIL_COND_V(!peer->channels[CH_ORDERED].is_valid(), FAILED);
  233. cfg["id"] = 3;
  234. cfg["ordered"] = false;
  235. peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg);
  236. ERR_FAIL_COND_V(!peer->channels[CH_UNRELIABLE].is_valid(), FAILED);
  237. peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map
  238. return OK;
  239. }
  240. void WebRTCMultiplayer::remove_peer(int p_peer_id) {
  241. ERR_FAIL_COND(!peer_map.has(p_peer_id));
  242. Ref<ConnectedPeer> peer = peer_map[p_peer_id];
  243. peer_map.erase(p_peer_id);
  244. if (peer->connected) {
  245. peer->connected = false;
  246. emit_signal("peer_disconnected", p_peer_id);
  247. if (server_compat && p_peer_id == TARGET_PEER_SERVER) {
  248. emit_signal("server_disconnected");
  249. connection_status = CONNECTION_DISCONNECTED;
  250. }
  251. }
  252. }
  253. Error WebRTCMultiplayer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  254. // Peer not available
  255. if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) {
  256. _find_next_peer();
  257. ERR_FAIL_V(ERR_UNAVAILABLE);
  258. }
  259. for (List<Ref<WebRTCDataChannel> >::Element *E = peer_map[next_packet_peer]->channels.front(); E; E = E->next()) {
  260. if (E->get()->get_available_packet_count()) {
  261. Error err = E->get()->get_packet(r_buffer, r_buffer_size);
  262. _find_next_peer();
  263. return err;
  264. }
  265. }
  266. // Channels for that peer were empty. Bug?
  267. _find_next_peer();
  268. ERR_FAIL_V(ERR_BUG);
  269. }
  270. Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  271. ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED);
  272. int ch = CH_RELIABLE;
  273. switch (transfer_mode) {
  274. case TRANSFER_MODE_RELIABLE:
  275. ch = CH_RELIABLE;
  276. break;
  277. case TRANSFER_MODE_UNRELIABLE_ORDERED:
  278. ch = CH_ORDERED;
  279. break;
  280. case TRANSFER_MODE_UNRELIABLE:
  281. ch = CH_UNRELIABLE;
  282. break;
  283. }
  284. Map<int, Ref<ConnectedPeer> >::Element *E = NULL;
  285. if (target_peer > 0) {
  286. E = peer_map.find(target_peer);
  287. ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer: " + itos(target_peer) + ".");
  288. ERR_FAIL_COND_V(E->value()->channels.size() <= ch, ERR_BUG);
  289. ERR_FAIL_COND_V(!E->value()->channels[ch].is_valid(), ERR_BUG);
  290. return E->value()->channels[ch]->put_packet(p_buffer, p_buffer_size);
  291. } else {
  292. int exclude = -target_peer;
  293. for (Map<int, Ref<ConnectedPeer> >::Element *F = peer_map.front(); F; F = F->next()) {
  294. // Exclude packet. If target_peer == 0 then don't exclude any packets
  295. if (target_peer != 0 && F->key() == exclude)
  296. continue;
  297. ERR_CONTINUE(F->value()->channels.size() <= ch || !F->value()->channels[ch].is_valid());
  298. F->value()->channels[ch]->put_packet(p_buffer, p_buffer_size);
  299. }
  300. }
  301. return OK;
  302. }
  303. int WebRTCMultiplayer::get_available_packet_count() const {
  304. if (next_packet_peer == 0)
  305. return 0; // To be sure next call to get_packet works if size > 0 .
  306. int size = 0;
  307. for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) {
  308. for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) {
  309. size += F->get()->get_available_packet_count();
  310. }
  311. }
  312. return size;
  313. }
  314. int WebRTCMultiplayer::get_max_packet_size() const {
  315. return 1200;
  316. }
  317. void WebRTCMultiplayer::close() {
  318. peer_map.clear();
  319. unique_id = 0;
  320. next_packet_peer = 0;
  321. target_peer = 0;
  322. connection_status = CONNECTION_DISCONNECTED;
  323. }
  324. WebRTCMultiplayer::WebRTCMultiplayer() {
  325. unique_id = 0;
  326. next_packet_peer = 0;
  327. target_peer = 0;
  328. transfer_mode = TRANSFER_MODE_RELIABLE;
  329. refuse_connections = false;
  330. connection_status = CONNECTION_DISCONNECTED;
  331. server_compat = false;
  332. }
  333. WebRTCMultiplayer::~WebRTCMultiplayer() {
  334. close();
  335. }