webrtc_multiplayer.cpp 13 KB

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