scene_multiplayer.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. /**************************************************************************/
  2. /* scene_multiplayer.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. #include "scene_multiplayer.h"
  31. #include "core/debugger/engine_debugger.h"
  32. #include "core/io/marshalls.h"
  33. #ifdef DEBUG_ENABLED
  34. #include "core/os/os.h"
  35. #endif
  36. #include <stdint.h>
  37. #ifdef DEBUG_ENABLED
  38. _FORCE_INLINE_ void SceneMultiplayer::_profile_bandwidth(const String &p_what, int p_value) {
  39. if (EngineDebugger::is_profiling("multiplayer:bandwidth")) {
  40. Array values;
  41. values.push_back(p_what);
  42. values.push_back(OS::get_singleton()->get_ticks_msec());
  43. values.push_back(p_value);
  44. EngineDebugger::profiler_add_frame_data("multiplayer:bandwidth", values);
  45. }
  46. }
  47. #endif
  48. void SceneMultiplayer::_update_status() {
  49. MultiplayerPeer::ConnectionStatus status = multiplayer_peer.is_valid() ? multiplayer_peer->get_connection_status() : MultiplayerPeer::CONNECTION_DISCONNECTED;
  50. if (last_connection_status != status) {
  51. if (status == MultiplayerPeer::CONNECTION_DISCONNECTED) {
  52. if (last_connection_status == MultiplayerPeer::CONNECTION_CONNECTING) {
  53. emit_signal(SNAME("connection_failed"));
  54. } else {
  55. emit_signal(SNAME("server_disconnected"));
  56. }
  57. clear();
  58. }
  59. last_connection_status = status;
  60. }
  61. }
  62. Error SceneMultiplayer::poll() {
  63. _update_status();
  64. if (last_connection_status == MultiplayerPeer::CONNECTION_DISCONNECTED) {
  65. return OK;
  66. }
  67. multiplayer_peer->poll();
  68. _update_status();
  69. if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) {
  70. // We might be still connecting, or polling might have resulted in a disconnection.
  71. return OK;
  72. }
  73. while (multiplayer_peer->get_available_packet_count()) {
  74. int sender = multiplayer_peer->get_packet_peer();
  75. const uint8_t *packet;
  76. int len;
  77. int channel = multiplayer_peer->get_packet_channel();
  78. MultiplayerPeer::TransferMode mode = multiplayer_peer->get_packet_mode();
  79. Error err = multiplayer_peer->get_packet(&packet, len);
  80. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Error getting packet! %d", err));
  81. #ifdef DEBUG_ENABLED
  82. _profile_bandwidth("in", len);
  83. #endif
  84. if (pending_peers.has(sender)) {
  85. ERR_CONTINUE(len < 2 || (packet[0] & CMD_MASK) != NETWORK_COMMAND_SYS || packet[1] != SYS_COMMAND_AUTH);
  86. // Auth message.
  87. PackedByteArray pba;
  88. pba.resize(len - 2);
  89. if (pba.size()) {
  90. memcpy(pba.ptrw(), &packet[2], len - 2);
  91. // User callback
  92. const Variant sv = sender;
  93. const Variant pbav = pba;
  94. const Variant *argv[2] = { &sv, &pbav };
  95. Variant ret;
  96. Callable::CallError ce;
  97. auth_callback.callp(argv, 2, ret, ce);
  98. ERR_CONTINUE_MSG(ce.error != Callable::CallError::CALL_OK, "Failed to call authentication callback");
  99. } else {
  100. // Remote complete notification.
  101. pending_peers[sender].remote = true;
  102. if (pending_peers[sender].local) {
  103. pending_peers.erase(sender);
  104. _admit_peer(sender);
  105. }
  106. }
  107. continue; // Auth in progress.
  108. }
  109. ERR_CONTINUE(!connected_peers.has(sender));
  110. if (len && (packet[0] & CMD_MASK) == NETWORK_COMMAND_SYS) {
  111. // Sys messages are processed separately since they might call _process_packet themselves.
  112. if (len > 1 && packet[1] == SYS_COMMAND_AUTH) {
  113. ERR_CONTINUE(len != 2);
  114. // If we are here, we already admitted the peer locally, and this is just a confirmation packet.
  115. continue;
  116. }
  117. _process_sys(sender, packet, len, mode, channel);
  118. } else {
  119. remote_sender_id = sender;
  120. _process_packet(sender, packet, len);
  121. remote_sender_id = 0;
  122. }
  123. _update_status();
  124. if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) { // It's possible that processing a packet might have resulted in a disconnection, so check here.
  125. return OK;
  126. }
  127. }
  128. if (pending_peers.size() && auth_timeout) {
  129. HashSet<int> to_drop;
  130. uint64_t time = OS::get_singleton()->get_ticks_msec();
  131. for (const KeyValue<int, PendingPeer> &pending : pending_peers) {
  132. if (pending.value.time + auth_timeout <= time) {
  133. multiplayer_peer->disconnect_peer(pending.key);
  134. to_drop.insert(pending.key);
  135. }
  136. }
  137. for (const int &P : to_drop) {
  138. // Each signal might trigger a disconnection.
  139. pending_peers.erase(P);
  140. emit_signal(SNAME("peer_authentication_failed"), P);
  141. }
  142. }
  143. _update_status();
  144. if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) { // Signals might have triggered disconnection.
  145. return OK;
  146. }
  147. replicator->on_network_process();
  148. return OK;
  149. }
  150. void SceneMultiplayer::clear() {
  151. last_connection_status = MultiplayerPeer::CONNECTION_DISCONNECTED;
  152. pending_peers.clear();
  153. connected_peers.clear();
  154. packet_cache.clear();
  155. replicator->on_reset();
  156. cache->clear();
  157. relay_buffer->clear();
  158. }
  159. void SceneMultiplayer::set_root_path(const NodePath &p_path) {
  160. ERR_FAIL_COND_MSG(!p_path.is_absolute() && !p_path.is_empty(), "SceneMultiplayer root path must be absolute.");
  161. root_path = p_path;
  162. }
  163. NodePath SceneMultiplayer::get_root_path() const {
  164. return root_path;
  165. }
  166. void SceneMultiplayer::set_multiplayer_peer(const Ref<MultiplayerPeer> &p_peer) {
  167. if (p_peer == multiplayer_peer) {
  168. return; // Nothing to do
  169. }
  170. ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED,
  171. "Supplied MultiplayerPeer must be connecting or connected.");
  172. if (multiplayer_peer.is_valid()) {
  173. multiplayer_peer->disconnect("peer_connected", callable_mp(this, &SceneMultiplayer::_add_peer));
  174. multiplayer_peer->disconnect("peer_disconnected", callable_mp(this, &SceneMultiplayer::_del_peer));
  175. clear();
  176. }
  177. multiplayer_peer = p_peer;
  178. if (multiplayer_peer.is_valid()) {
  179. multiplayer_peer->connect("peer_connected", callable_mp(this, &SceneMultiplayer::_add_peer));
  180. multiplayer_peer->connect("peer_disconnected", callable_mp(this, &SceneMultiplayer::_del_peer));
  181. }
  182. _update_status();
  183. }
  184. Ref<MultiplayerPeer> SceneMultiplayer::get_multiplayer_peer() {
  185. return multiplayer_peer;
  186. }
  187. void SceneMultiplayer::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  188. ERR_FAIL_COND_MSG(root_path.is_empty(), "Multiplayer root was not initialized. If you are using custom multiplayer, remember to set the root path via SceneMultiplayer.set_root_path before using it.");
  189. ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
  190. // Extract the `packet_type` from the LSB three bits:
  191. uint8_t packet_type = p_packet[0] & CMD_MASK;
  192. switch (packet_type) {
  193. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  194. cache->process_simplify_path(p_from, p_packet, p_packet_len);
  195. } break;
  196. case NETWORK_COMMAND_CONFIRM_PATH: {
  197. cache->process_confirm_path(p_from, p_packet, p_packet_len);
  198. } break;
  199. case NETWORK_COMMAND_REMOTE_CALL: {
  200. rpc->process_rpc(p_from, p_packet, p_packet_len);
  201. } break;
  202. case NETWORK_COMMAND_RAW: {
  203. _process_raw(p_from, p_packet, p_packet_len);
  204. } break;
  205. case NETWORK_COMMAND_SPAWN: {
  206. replicator->on_spawn_receive(p_from, p_packet, p_packet_len);
  207. } break;
  208. case NETWORK_COMMAND_DESPAWN: {
  209. replicator->on_despawn_receive(p_from, p_packet, p_packet_len);
  210. } break;
  211. case NETWORK_COMMAND_SYNC: {
  212. replicator->on_sync_receive(p_from, p_packet, p_packet_len);
  213. } break;
  214. default: {
  215. ERR_FAIL_MSG("Invalid network command from " + itos(p_from));
  216. } break;
  217. }
  218. }
  219. #ifdef DEBUG_ENABLED
  220. _FORCE_INLINE_ Error SceneMultiplayer::_send(const uint8_t *p_packet, int p_packet_len) {
  221. _profile_bandwidth("out", p_packet_len);
  222. return multiplayer_peer->put_packet(p_packet, p_packet_len);
  223. }
  224. #endif
  225. Error SceneMultiplayer::send_command(int p_to, const uint8_t *p_packet, int p_packet_len) {
  226. if (server_relay && get_unique_id() != 1 && p_to != 1 && multiplayer_peer->is_server_relay_supported()) {
  227. // Send relay packet.
  228. relay_buffer->seek(0);
  229. relay_buffer->put_u8(NETWORK_COMMAND_SYS);
  230. relay_buffer->put_u8(SYS_COMMAND_RELAY);
  231. relay_buffer->put_32(p_to); // Set the destination.
  232. relay_buffer->put_data(p_packet, p_packet_len);
  233. multiplayer_peer->set_target_peer(1);
  234. const Vector<uint8_t> data = relay_buffer->get_data_array();
  235. return _send(data.ptr(), relay_buffer->get_position());
  236. }
  237. if (p_to > 0) {
  238. ERR_FAIL_COND_V(!connected_peers.has(p_to), ERR_BUG);
  239. multiplayer_peer->set_target_peer(p_to);
  240. return _send(p_packet, p_packet_len);
  241. } else {
  242. for (const int &pid : connected_peers) {
  243. if (p_to && pid == -p_to) {
  244. continue;
  245. }
  246. multiplayer_peer->set_target_peer(pid);
  247. _send(p_packet, p_packet_len);
  248. }
  249. return OK;
  250. }
  251. }
  252. void SceneMultiplayer::_process_sys(int p_from, const uint8_t *p_packet, int p_packet_len, MultiplayerPeer::TransferMode p_mode, int p_channel) {
  253. ERR_FAIL_COND_MSG(p_packet_len < SYS_CMD_SIZE, "Invalid packet received. Size too small.");
  254. uint8_t sys_cmd_type = p_packet[1];
  255. int32_t peer = int32_t(decode_uint32(&p_packet[2]));
  256. switch (sys_cmd_type) {
  257. case SYS_COMMAND_ADD_PEER: {
  258. ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported() || get_unique_id() == 1 || p_from != 1);
  259. _admit_peer(peer); // Relayed peers are automatically accepted.
  260. } break;
  261. case SYS_COMMAND_DEL_PEER: {
  262. ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported() || get_unique_id() == 1 || p_from != 1);
  263. _del_peer(peer);
  264. } break;
  265. case SYS_COMMAND_RELAY: {
  266. ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported());
  267. ERR_FAIL_COND(p_packet_len < SYS_CMD_SIZE + 1);
  268. const uint8_t *packet = p_packet + SYS_CMD_SIZE;
  269. int len = p_packet_len - SYS_CMD_SIZE;
  270. bool should_process = false;
  271. if (get_unique_id() == 1) { // I am the server.
  272. // Direct messages to server should not go through relay.
  273. ERR_FAIL_COND(peer > 0 && !connected_peers.has(peer));
  274. // Send relay packet.
  275. relay_buffer->seek(0);
  276. relay_buffer->put_u8(NETWORK_COMMAND_SYS);
  277. relay_buffer->put_u8(SYS_COMMAND_RELAY);
  278. relay_buffer->put_32(p_from); // Set the source.
  279. relay_buffer->put_data(packet, len);
  280. const Vector<uint8_t> data = relay_buffer->get_data_array();
  281. multiplayer_peer->set_transfer_mode(p_mode);
  282. multiplayer_peer->set_transfer_channel(p_channel);
  283. if (peer > 0) {
  284. multiplayer_peer->set_target_peer(peer);
  285. _send(data.ptr(), relay_buffer->get_position());
  286. } else {
  287. for (const int &P : connected_peers) {
  288. // Not to sender, nor excluded.
  289. if (P == p_from || (peer < 0 && P != -peer)) {
  290. continue;
  291. }
  292. multiplayer_peer->set_target_peer(P);
  293. _send(data.ptr(), relay_buffer->get_position());
  294. }
  295. }
  296. if (peer == 0 || peer == -1) {
  297. should_process = true;
  298. peer = p_from; // Process as the source.
  299. }
  300. } else {
  301. ERR_FAIL_COND(p_from != 1); // Bug.
  302. should_process = true;
  303. }
  304. if (should_process) {
  305. remote_sender_id = peer;
  306. _process_packet(peer, packet, len);
  307. remote_sender_id = 0;
  308. }
  309. } break;
  310. default: {
  311. ERR_FAIL();
  312. }
  313. }
  314. }
  315. void SceneMultiplayer::_add_peer(int p_id) {
  316. if (auth_callback.is_valid()) {
  317. pending_peers[p_id] = PendingPeer();
  318. pending_peers[p_id].time = OS::get_singleton()->get_ticks_msec();
  319. emit_signal(SNAME("peer_authenticating"), p_id);
  320. return;
  321. } else {
  322. _admit_peer(p_id);
  323. }
  324. }
  325. void SceneMultiplayer::_admit_peer(int p_id) {
  326. if (server_relay && get_unique_id() == 1 && multiplayer_peer->is_server_relay_supported()) {
  327. // Notify others of connection, and send connected peers to newly connected one.
  328. uint8_t buf[SYS_CMD_SIZE];
  329. buf[0] = NETWORK_COMMAND_SYS;
  330. buf[1] = SYS_COMMAND_ADD_PEER;
  331. multiplayer_peer->set_transfer_channel(0);
  332. multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  333. for (const int &P : connected_peers) {
  334. // Send new peer to already connected.
  335. encode_uint32(p_id, &buf[2]);
  336. multiplayer_peer->set_target_peer(P);
  337. _send(buf, sizeof(buf));
  338. // Send already connected to new peer.
  339. encode_uint32(P, &buf[2]);
  340. multiplayer_peer->set_target_peer(p_id);
  341. _send(buf, sizeof(buf));
  342. }
  343. }
  344. connected_peers.insert(p_id);
  345. cache->on_peer_change(p_id, true);
  346. replicator->on_peer_change(p_id, true);
  347. if (p_id == 1) {
  348. emit_signal(SNAME("connected_to_server"));
  349. }
  350. emit_signal(SNAME("peer_connected"), p_id);
  351. }
  352. void SceneMultiplayer::_del_peer(int p_id) {
  353. if (pending_peers.has(p_id)) {
  354. pending_peers.erase(p_id);
  355. emit_signal(SNAME("peer_authentication_failed"), p_id);
  356. return;
  357. } else if (!connected_peers.has(p_id)) {
  358. return;
  359. }
  360. if (server_relay && get_unique_id() == 1 && multiplayer_peer->is_server_relay_supported()) {
  361. // Notify others of disconnection.
  362. uint8_t buf[SYS_CMD_SIZE];
  363. buf[0] = NETWORK_COMMAND_SYS;
  364. buf[1] = SYS_COMMAND_DEL_PEER;
  365. multiplayer_peer->set_transfer_channel(0);
  366. multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  367. encode_uint32(p_id, &buf[2]);
  368. for (const int &P : connected_peers) {
  369. if (P == p_id) {
  370. continue;
  371. }
  372. multiplayer_peer->set_target_peer(P);
  373. _send(buf, sizeof(buf));
  374. }
  375. }
  376. replicator->on_peer_change(p_id, false);
  377. cache->on_peer_change(p_id, false);
  378. connected_peers.erase(p_id);
  379. emit_signal(SNAME("peer_disconnected"), p_id);
  380. }
  381. void SceneMultiplayer::disconnect_peer(int p_id) {
  382. ERR_FAIL_COND(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED);
  383. if (pending_peers.has(p_id)) {
  384. pending_peers.erase(p_id);
  385. } else if (connected_peers.has(p_id)) {
  386. connected_peers.erase(p_id);
  387. }
  388. multiplayer_peer->disconnect_peer(p_id);
  389. }
  390. Error SceneMultiplayer::send_bytes(Vector<uint8_t> p_data, int p_to, MultiplayerPeer::TransferMode p_mode, int p_channel) {
  391. ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet.");
  392. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no multiplayer peer is active.");
  393. ERR_FAIL_COND_V_MSG(multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a multiplayer peer which is not connected.");
  394. if (packet_cache.size() < p_data.size() + 1) {
  395. packet_cache.resize(p_data.size() + 1);
  396. }
  397. const uint8_t *r = p_data.ptr();
  398. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  399. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  400. multiplayer_peer->set_transfer_channel(p_channel);
  401. multiplayer_peer->set_transfer_mode(p_mode);
  402. return send_command(p_to, packet_cache.ptr(), p_data.size() + 1);
  403. }
  404. Error SceneMultiplayer::send_auth(int p_to, Vector<uint8_t> p_data) {
  405. ERR_FAIL_COND_V(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  406. ERR_FAIL_COND_V(!pending_peers.has(p_to), ERR_INVALID_PARAMETER);
  407. ERR_FAIL_COND_V(p_data.size() < 1, ERR_INVALID_PARAMETER);
  408. ERR_FAIL_COND_V_MSG(pending_peers[p_to].local, ERR_FILE_CANT_WRITE, "The authentication session was previously marked as completed, no more authentication data can be sent.");
  409. ERR_FAIL_COND_V_MSG(pending_peers[p_to].remote, ERR_FILE_CANT_WRITE, "The remote peer notified that the authentication session was completed, no more authentication data can be sent.");
  410. if (packet_cache.size() < p_data.size() + 2) {
  411. packet_cache.resize(p_data.size() + 2);
  412. }
  413. packet_cache.write[0] = NETWORK_COMMAND_SYS;
  414. packet_cache.write[1] = SYS_COMMAND_AUTH;
  415. memcpy(&packet_cache.write[2], p_data.ptr(), p_data.size());
  416. multiplayer_peer->set_target_peer(p_to);
  417. multiplayer_peer->set_transfer_channel(0);
  418. multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  419. return _send(packet_cache.ptr(), p_data.size() + 2);
  420. }
  421. Error SceneMultiplayer::complete_auth(int p_peer) {
  422. ERR_FAIL_COND_V(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  423. ERR_FAIL_COND_V(!pending_peers.has(p_peer), ERR_INVALID_PARAMETER);
  424. ERR_FAIL_COND_V_MSG(pending_peers[p_peer].local, ERR_FILE_CANT_WRITE, "The authentication session was already marked as completed.");
  425. pending_peers[p_peer].local = true;
  426. // Notify the remote peer that the authentication has completed.
  427. uint8_t buf[2] = { NETWORK_COMMAND_SYS, SYS_COMMAND_AUTH };
  428. multiplayer_peer->set_target_peer(p_peer);
  429. multiplayer_peer->set_transfer_channel(0);
  430. multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  431. Error err = _send(buf, 2);
  432. // The remote peer already reported the authentication as completed, so admit the peer.
  433. // May generate new packets, so it must happen after sending confirmation.
  434. if (pending_peers[p_peer].remote) {
  435. pending_peers.erase(p_peer);
  436. _admit_peer(p_peer);
  437. }
  438. return err;
  439. }
  440. void SceneMultiplayer::set_auth_callback(Callable p_callback) {
  441. auth_callback = p_callback;
  442. }
  443. Callable SceneMultiplayer::get_auth_callback() const {
  444. return auth_callback;
  445. }
  446. void SceneMultiplayer::set_auth_timeout(double p_timeout) {
  447. ERR_FAIL_COND_MSG(p_timeout < 0, "Timeout must be greater or equal to 0 (where 0 means no timeout)");
  448. auth_timeout = uint64_t(p_timeout * 1000);
  449. }
  450. double SceneMultiplayer::get_auth_timeout() const {
  451. return double(auth_timeout) / 1000.0;
  452. }
  453. void SceneMultiplayer::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  454. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  455. Vector<uint8_t> out;
  456. int len = p_packet_len - 1;
  457. out.resize(len);
  458. {
  459. uint8_t *w = out.ptrw();
  460. memcpy(&w[0], &p_packet[1], len);
  461. }
  462. emit_signal(SNAME("peer_packet"), p_from, out);
  463. }
  464. int SceneMultiplayer::get_unique_id() {
  465. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), 0, "No multiplayer peer is assigned. Unable to get unique ID.");
  466. return multiplayer_peer->get_unique_id();
  467. }
  468. void SceneMultiplayer::set_refuse_new_connections(bool p_refuse) {
  469. ERR_FAIL_COND_MSG(!multiplayer_peer.is_valid(), "No multiplayer peer is assigned. Unable to set 'refuse_new_connections'.");
  470. multiplayer_peer->set_refuse_new_connections(p_refuse);
  471. }
  472. bool SceneMultiplayer::is_refusing_new_connections() const {
  473. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), false, "No multiplayer peer is assigned. Unable to get 'refuse_new_connections'.");
  474. return multiplayer_peer->is_refusing_new_connections();
  475. }
  476. Vector<int> SceneMultiplayer::get_peer_ids() {
  477. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), Vector<int>(), "No multiplayer peer is assigned. Assume no peers are connected.");
  478. Vector<int> ret;
  479. for (const int &E : connected_peers) {
  480. ret.push_back(E);
  481. }
  482. return ret;
  483. }
  484. Vector<int> SceneMultiplayer::get_authenticating_peer_ids() {
  485. Vector<int> out;
  486. out.resize(pending_peers.size());
  487. int idx = 0;
  488. for (const KeyValue<int, PendingPeer> &E : pending_peers) {
  489. out.write[idx++] = E.key;
  490. }
  491. return out;
  492. }
  493. void SceneMultiplayer::set_allow_object_decoding(bool p_enable) {
  494. allow_object_decoding = p_enable;
  495. }
  496. bool SceneMultiplayer::is_object_decoding_allowed() const {
  497. return allow_object_decoding;
  498. }
  499. String SceneMultiplayer::get_rpc_md5(const Object *p_obj) {
  500. return rpc->get_rpc_md5(p_obj);
  501. }
  502. Error SceneMultiplayer::rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  503. return rpc->rpcp(p_obj, p_peer_id, p_method, p_arg, p_argcount);
  504. }
  505. Error SceneMultiplayer::object_configuration_add(Object *p_obj, Variant p_config) {
  506. if (p_obj == nullptr && p_config.get_type() == Variant::NODE_PATH) {
  507. set_root_path(p_config);
  508. return OK;
  509. }
  510. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  511. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  512. if (spawner) {
  513. return replicator->on_spawn(p_obj, p_config);
  514. } else if (sync) {
  515. return replicator->on_replication_start(p_obj, p_config);
  516. }
  517. return ERR_INVALID_PARAMETER;
  518. }
  519. Error SceneMultiplayer::object_configuration_remove(Object *p_obj, Variant p_config) {
  520. if (p_obj == nullptr && p_config.get_type() == Variant::NODE_PATH) {
  521. ERR_FAIL_COND_V(root_path != p_config.operator NodePath(), ERR_INVALID_PARAMETER);
  522. set_root_path(NodePath());
  523. return OK;
  524. }
  525. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  526. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  527. if (spawner) {
  528. return replicator->on_despawn(p_obj, p_config);
  529. }
  530. if (sync) {
  531. return replicator->on_replication_stop(p_obj, p_config);
  532. }
  533. return ERR_INVALID_PARAMETER;
  534. }
  535. void SceneMultiplayer::set_server_relay_enabled(bool p_enabled) {
  536. server_relay = p_enabled;
  537. }
  538. bool SceneMultiplayer::is_server_relay_enabled() const {
  539. return server_relay;
  540. }
  541. void SceneMultiplayer::set_max_sync_packet_size(int p_size) {
  542. replicator->set_max_sync_packet_size(p_size);
  543. }
  544. int SceneMultiplayer::get_max_sync_packet_size() const {
  545. return replicator->get_max_sync_packet_size();
  546. }
  547. void SceneMultiplayer::set_max_delta_packet_size(int p_size) {
  548. replicator->set_max_delta_packet_size(p_size);
  549. }
  550. int SceneMultiplayer::get_max_delta_packet_size() const {
  551. return replicator->get_max_delta_packet_size();
  552. }
  553. void SceneMultiplayer::_bind_methods() {
  554. ClassDB::bind_method(D_METHOD("set_root_path", "path"), &SceneMultiplayer::set_root_path);
  555. ClassDB::bind_method(D_METHOD("get_root_path"), &SceneMultiplayer::get_root_path);
  556. ClassDB::bind_method(D_METHOD("clear"), &SceneMultiplayer::clear);
  557. ClassDB::bind_method(D_METHOD("disconnect_peer", "id"), &SceneMultiplayer::disconnect_peer);
  558. ClassDB::bind_method(D_METHOD("get_authenticating_peers"), &SceneMultiplayer::get_authenticating_peer_ids);
  559. ClassDB::bind_method(D_METHOD("send_auth", "id", "data"), &SceneMultiplayer::send_auth);
  560. ClassDB::bind_method(D_METHOD("complete_auth", "id"), &SceneMultiplayer::complete_auth);
  561. ClassDB::bind_method(D_METHOD("set_auth_callback", "callback"), &SceneMultiplayer::set_auth_callback);
  562. ClassDB::bind_method(D_METHOD("get_auth_callback"), &SceneMultiplayer::get_auth_callback);
  563. ClassDB::bind_method(D_METHOD("set_auth_timeout", "timeout"), &SceneMultiplayer::set_auth_timeout);
  564. ClassDB::bind_method(D_METHOD("get_auth_timeout"), &SceneMultiplayer::get_auth_timeout);
  565. ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "refuse"), &SceneMultiplayer::set_refuse_new_connections);
  566. ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &SceneMultiplayer::is_refusing_new_connections);
  567. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &SceneMultiplayer::set_allow_object_decoding);
  568. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &SceneMultiplayer::is_object_decoding_allowed);
  569. ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &SceneMultiplayer::set_server_relay_enabled);
  570. ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &SceneMultiplayer::is_server_relay_enabled);
  571. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode", "channel"), &SceneMultiplayer::send_bytes, DEFVAL(MultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(MultiplayerPeer::TRANSFER_MODE_RELIABLE), DEFVAL(0));
  572. ClassDB::bind_method(D_METHOD("get_max_sync_packet_size"), &SceneMultiplayer::get_max_sync_packet_size);
  573. ClassDB::bind_method(D_METHOD("set_max_sync_packet_size", "size"), &SceneMultiplayer::set_max_sync_packet_size);
  574. ClassDB::bind_method(D_METHOD("get_max_delta_packet_size"), &SceneMultiplayer::get_max_delta_packet_size);
  575. ClassDB::bind_method(D_METHOD("set_max_delta_packet_size", "size"), &SceneMultiplayer::set_max_delta_packet_size);
  576. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_path"), "set_root_path", "get_root_path");
  577. ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "auth_callback"), "set_auth_callback", "get_auth_callback");
  578. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "auth_timeout", PROPERTY_HINT_RANGE, "0,30,0.1,or_greater,suffix:s"), "set_auth_timeout", "get_auth_timeout");
  579. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  580. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_connections"), "set_refuse_new_connections", "is_refusing_new_connections");
  581. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled");
  582. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_sync_packet_size"), "set_max_sync_packet_size", "get_max_sync_packet_size");
  583. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_delta_packet_size"), "set_max_delta_packet_size", "get_max_delta_packet_size");
  584. ADD_PROPERTY_DEFAULT("refuse_new_connections", false);
  585. ADD_SIGNAL(MethodInfo("peer_authenticating", PropertyInfo(Variant::INT, "id")));
  586. ADD_SIGNAL(MethodInfo("peer_authentication_failed", PropertyInfo(Variant::INT, "id")));
  587. ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packet")));
  588. }
  589. SceneMultiplayer::SceneMultiplayer() {
  590. relay_buffer.instantiate();
  591. cache = Ref<SceneCacheInterface>(memnew(SceneCacheInterface(this)));
  592. replicator = Ref<SceneReplicationInterface>(memnew(SceneReplicationInterface(this, cache.ptr())));
  593. rpc = Ref<SceneRPCInterface>(memnew(SceneRPCInterface(this, cache.ptr(), replicator.ptr())));
  594. set_multiplayer_peer(Ref<OfflineMultiplayerPeer>(memnew(OfflineMultiplayerPeer)));
  595. }
  596. SceneMultiplayer::~SceneMultiplayer() {
  597. clear();
  598. // Ensure unref in reverse order for safety (we shouldn't use those pointers in the deconstructors anyway).
  599. rpc.unref();
  600. replicator.unref();
  601. cache.unref();
  602. }