multiplayer_api.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. /*************************************************************************/
  2. /* multiplayer_api.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 "multiplayer_api.h"
  31. #include "core/debugger/engine_debugger.h"
  32. #include "core/io/marshalls.h"
  33. #include "scene/main/node.h"
  34. #include "scene/resources/packed_scene.h"
  35. #include <stdint.h>
  36. #define NODE_ID_COMPRESSION_SHIFT 3
  37. #define NAME_ID_COMPRESSION_SHIFT 5
  38. #define BYTE_ONLY_OR_NO_ARGS_SHIFT 6
  39. #ifdef DEBUG_ENABLED
  40. #include "core/os/os.h"
  41. #endif
  42. String _get_rpc_md5(const Node *p_node) {
  43. String rpc_list;
  44. const Vector<MultiplayerAPI::RPCConfig> node_config = p_node->get_node_rpc_methods();
  45. for (int i = 0; i < node_config.size(); i++) {
  46. rpc_list += String(node_config[i].name);
  47. }
  48. if (p_node->get_script_instance()) {
  49. const Vector<MultiplayerAPI::RPCConfig> script_config = p_node->get_script_instance()->get_rpc_methods();
  50. for (int i = 0; i < script_config.size(); i++) {
  51. rpc_list += String(script_config[i].name);
  52. }
  53. }
  54. return rpc_list.md5_text();
  55. }
  56. const MultiplayerAPI::RPCConfig _get_rpc_config(const Node *p_node, const StringName &p_method, uint16_t &r_id) {
  57. const Vector<MultiplayerAPI::RPCConfig> node_config = p_node->get_node_rpc_methods();
  58. for (int i = 0; i < node_config.size(); i++) {
  59. if (node_config[i].name == p_method) {
  60. r_id = ((uint16_t)i) | (1 << 15);
  61. return node_config[i];
  62. }
  63. }
  64. if (p_node->get_script_instance()) {
  65. const Vector<MultiplayerAPI::RPCConfig> script_config = p_node->get_script_instance()->get_rpc_methods();
  66. for (int i = 0; i < script_config.size(); i++) {
  67. if (script_config[i].name == p_method) {
  68. r_id = (uint16_t)i;
  69. return script_config[i];
  70. }
  71. }
  72. }
  73. return MultiplayerAPI::RPCConfig();
  74. }
  75. const MultiplayerAPI::RPCConfig _get_rpc_config_by_id(Node *p_node, uint16_t p_id) {
  76. Vector<MultiplayerAPI::RPCConfig> config;
  77. uint16_t id = p_id;
  78. if (id & (1 << 15)) {
  79. id = id & ~(1 << 15);
  80. config = p_node->get_node_rpc_methods();
  81. } else if (p_node->get_script_instance()) {
  82. config = p_node->get_script_instance()->get_rpc_methods();
  83. }
  84. if (id < config.size()) {
  85. return config[id];
  86. }
  87. return MultiplayerAPI::RPCConfig();
  88. }
  89. _FORCE_INLINE_ bool _can_call_mode(Node *p_node, MultiplayerAPI::RPCMode mode, int p_remote_id) {
  90. switch (mode) {
  91. case MultiplayerAPI::RPC_MODE_DISABLED: {
  92. return false;
  93. } break;
  94. case MultiplayerAPI::RPC_MODE_REMOTE: {
  95. return true;
  96. } break;
  97. case MultiplayerAPI::RPC_MODE_MASTER: {
  98. return p_node->is_network_master();
  99. } break;
  100. case MultiplayerAPI::RPC_MODE_PUPPET: {
  101. return !p_node->is_network_master() && p_remote_id == p_node->get_network_master();
  102. } break;
  103. }
  104. return false;
  105. }
  106. void MultiplayerAPI::poll() {
  107. if (!network_peer.is_valid() || network_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED) {
  108. return;
  109. }
  110. network_peer->poll();
  111. if (!network_peer.is_valid()) { // It's possible that polling might have resulted in a disconnection, so check here.
  112. return;
  113. }
  114. while (network_peer->get_available_packet_count()) {
  115. int sender = network_peer->get_packet_peer();
  116. const uint8_t *packet;
  117. int len;
  118. Error err = network_peer->get_packet(&packet, len);
  119. if (err != OK) {
  120. ERR_PRINT("Error getting packet!");
  121. break; // Something is wrong!
  122. }
  123. rpc_sender_id = sender;
  124. _process_packet(sender, packet, len);
  125. rpc_sender_id = 0;
  126. if (!network_peer.is_valid()) {
  127. break; // It's also possible that a packet or RPC caused a disconnection, so also check here.
  128. }
  129. }
  130. }
  131. void MultiplayerAPI::clear() {
  132. replicated_nodes.clear();
  133. connected_peers.clear();
  134. path_get_cache.clear();
  135. path_send_cache.clear();
  136. packet_cache.clear();
  137. last_send_cache_id = 1;
  138. }
  139. void MultiplayerAPI::set_root_node(Node *p_node) {
  140. root_node = p_node;
  141. }
  142. Node *MultiplayerAPI::get_root_node() {
  143. return root_node;
  144. }
  145. void MultiplayerAPI::set_network_peer(const Ref<MultiplayerPeer> &p_peer) {
  146. if (p_peer == network_peer) {
  147. return; // Nothing to do
  148. }
  149. ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED,
  150. "Supplied MultiplayerPeer must be connecting or connected.");
  151. if (network_peer.is_valid()) {
  152. network_peer->disconnect("peer_connected", callable_mp(this, &MultiplayerAPI::_add_peer));
  153. network_peer->disconnect("peer_disconnected", callable_mp(this, &MultiplayerAPI::_del_peer));
  154. network_peer->disconnect("connection_succeeded", callable_mp(this, &MultiplayerAPI::_connected_to_server));
  155. network_peer->disconnect("connection_failed", callable_mp(this, &MultiplayerAPI::_connection_failed));
  156. network_peer->disconnect("server_disconnected", callable_mp(this, &MultiplayerAPI::_server_disconnected));
  157. clear();
  158. }
  159. network_peer = p_peer;
  160. if (network_peer.is_valid()) {
  161. network_peer->connect("peer_connected", callable_mp(this, &MultiplayerAPI::_add_peer));
  162. network_peer->connect("peer_disconnected", callable_mp(this, &MultiplayerAPI::_del_peer));
  163. network_peer->connect("connection_succeeded", callable_mp(this, &MultiplayerAPI::_connected_to_server));
  164. network_peer->connect("connection_failed", callable_mp(this, &MultiplayerAPI::_connection_failed));
  165. network_peer->connect("server_disconnected", callable_mp(this, &MultiplayerAPI::_server_disconnected));
  166. }
  167. }
  168. Ref<MultiplayerPeer> MultiplayerAPI::get_network_peer() const {
  169. return network_peer;
  170. }
  171. #ifdef DEBUG_ENABLED
  172. void _profile_node_data(const String &p_what, ObjectID p_id) {
  173. if (EngineDebugger::is_profiling("multiplayer")) {
  174. Array values;
  175. values.push_back("node");
  176. values.push_back(p_id);
  177. values.push_back(p_what);
  178. EngineDebugger::profiler_add_frame_data("multiplayer", values);
  179. }
  180. }
  181. void _profile_bandwidth_data(const String &p_inout, int p_size) {
  182. if (EngineDebugger::is_profiling("multiplayer")) {
  183. Array values;
  184. values.push_back("bandwidth");
  185. values.push_back(p_inout);
  186. values.push_back(OS::get_singleton()->get_ticks_msec());
  187. values.push_back(p_size);
  188. EngineDebugger::profiler_add_frame_data("multiplayer", values);
  189. }
  190. }
  191. #endif
  192. // Returns the packet size stripping the node path added when the node is not yet cached.
  193. int get_packet_len(uint32_t p_node_target, int p_packet_len) {
  194. if (p_node_target & 0x80000000) {
  195. int ofs = p_node_target & 0x7FFFFFFF;
  196. return p_packet_len - (p_packet_len - ofs);
  197. } else {
  198. return p_packet_len;
  199. }
  200. }
  201. void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  202. ERR_FAIL_COND_MSG(root_node == nullptr, "Multiplayer root node was not initialized. If you are using custom multiplayer, remember to set the root node via MultiplayerAPI.set_root_node before using it.");
  203. ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
  204. #ifdef DEBUG_ENABLED
  205. _profile_bandwidth_data("in", p_packet_len);
  206. #endif
  207. // Extract the `packet_type` from the LSB three bits:
  208. uint8_t packet_type = p_packet[0] & 7;
  209. switch (packet_type) {
  210. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  211. _process_simplify_path(p_from, p_packet, p_packet_len);
  212. } break;
  213. case NETWORK_COMMAND_CONFIRM_PATH: {
  214. _process_confirm_path(p_from, p_packet, p_packet_len);
  215. } break;
  216. case NETWORK_COMMAND_REMOTE_CALL: {
  217. // Extract packet meta
  218. int packet_min_size = 1;
  219. int name_id_offset = 1;
  220. ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");
  221. // Compute the meta size, which depends on the compression level.
  222. int node_id_compression = (p_packet[0] & 24) >> NODE_ID_COMPRESSION_SHIFT;
  223. int name_id_compression = (p_packet[0] & 32) >> NAME_ID_COMPRESSION_SHIFT;
  224. switch (node_id_compression) {
  225. case NETWORK_NODE_ID_COMPRESSION_8:
  226. packet_min_size += 1;
  227. name_id_offset += 1;
  228. break;
  229. case NETWORK_NODE_ID_COMPRESSION_16:
  230. packet_min_size += 2;
  231. name_id_offset += 2;
  232. break;
  233. case NETWORK_NODE_ID_COMPRESSION_32:
  234. packet_min_size += 4;
  235. name_id_offset += 4;
  236. break;
  237. default:
  238. ERR_FAIL_MSG("Was not possible to extract the node id compression mode.");
  239. }
  240. switch (name_id_compression) {
  241. case NETWORK_NAME_ID_COMPRESSION_8:
  242. packet_min_size += 1;
  243. break;
  244. case NETWORK_NAME_ID_COMPRESSION_16:
  245. packet_min_size += 2;
  246. break;
  247. default:
  248. ERR_FAIL_MSG("Was not possible to extract the name id compression mode.");
  249. }
  250. ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");
  251. uint32_t node_target = 0;
  252. switch (node_id_compression) {
  253. case NETWORK_NODE_ID_COMPRESSION_8:
  254. node_target = p_packet[1];
  255. break;
  256. case NETWORK_NODE_ID_COMPRESSION_16:
  257. node_target = decode_uint16(p_packet + 1);
  258. break;
  259. case NETWORK_NODE_ID_COMPRESSION_32:
  260. node_target = decode_uint32(p_packet + 1);
  261. break;
  262. default:
  263. // Unreachable, checked before.
  264. CRASH_NOW();
  265. }
  266. Node *node = _process_get_node(p_from, p_packet, node_target, p_packet_len);
  267. ERR_FAIL_COND_MSG(node == nullptr, "Invalid packet received. Requested node was not found.");
  268. uint16_t name_id = 0;
  269. switch (name_id_compression) {
  270. case NETWORK_NAME_ID_COMPRESSION_8:
  271. name_id = p_packet[name_id_offset];
  272. break;
  273. case NETWORK_NAME_ID_COMPRESSION_16:
  274. name_id = decode_uint16(p_packet + name_id_offset);
  275. break;
  276. default:
  277. // Unreachable, checked before.
  278. CRASH_NOW();
  279. }
  280. const int packet_len = get_packet_len(node_target, p_packet_len);
  281. _process_rpc(node, name_id, p_from, p_packet, packet_len, packet_min_size);
  282. } break;
  283. case NETWORK_COMMAND_RAW: {
  284. _process_raw(p_from, p_packet, p_packet_len);
  285. } break;
  286. case NETWORK_COMMAND_SPAWN: {
  287. _process_spawn_despawn(p_from, p_packet, p_packet_len, true);
  288. } break;
  289. case NETWORK_COMMAND_DESPAWN: {
  290. _process_spawn_despawn(p_from, p_packet, p_packet_len, false);
  291. } break;
  292. }
  293. }
  294. Node *MultiplayerAPI::_process_get_node(int p_from, const uint8_t *p_packet, uint32_t p_node_target, int p_packet_len) {
  295. Node *node = nullptr;
  296. if (p_node_target & 0x80000000) {
  297. // Use full path (not cached yet).
  298. int ofs = p_node_target & 0x7FFFFFFF;
  299. ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, nullptr, "Invalid packet received. Size smaller than declared.");
  300. String paths;
  301. paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
  302. NodePath np = paths;
  303. node = root_node->get_node(np);
  304. if (!node) {
  305. ERR_PRINT("Failed to get path from RPC: " + String(np) + ".");
  306. }
  307. } else {
  308. // Use cached path.
  309. int id = p_node_target;
  310. Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
  311. ERR_FAIL_COND_V_MSG(!E, nullptr, "Invalid packet received. Requests invalid peer cache.");
  312. Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(id);
  313. ERR_FAIL_COND_V_MSG(!F, nullptr, "Invalid packet received. Unabled to find requested cached node.");
  314. PathGetCache::NodeInfo *ni = &F->get();
  315. // Do proper caching later.
  316. node = root_node->get_node(ni->path);
  317. if (!node) {
  318. ERR_PRINT("Failed to get cached path from RPC: " + String(ni->path) + ".");
  319. }
  320. }
  321. return node;
  322. }
  323. void MultiplayerAPI::_process_rpc(Node *p_node, const uint16_t p_rpc_method_id, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  324. ERR_FAIL_COND_MSG(p_offset > p_packet_len, "Invalid packet received. Size too small.");
  325. // Check that remote can call the RPC on this node.
  326. const RPCConfig config = _get_rpc_config_by_id(p_node, p_rpc_method_id);
  327. ERR_FAIL_COND(config.name == StringName());
  328. bool can_call = _can_call_mode(p_node, config.rpc_mode, p_from);
  329. ERR_FAIL_COND_MSG(!can_call, "RPC '" + String(config.name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)config.rpc_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  330. int argc = 0;
  331. bool byte_only = false;
  332. const bool byte_only_or_no_args = ((p_packet[0] & 64) >> BYTE_ONLY_OR_NO_ARGS_SHIFT) == 1;
  333. if (byte_only_or_no_args) {
  334. if (p_offset < p_packet_len) {
  335. // This packet contains only bytes.
  336. argc = 1;
  337. byte_only = true;
  338. } else {
  339. // This rpc calls a method without parameters.
  340. }
  341. } else {
  342. // Normal variant, takes the argument count from the packet.
  343. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  344. argc = p_packet[p_offset];
  345. p_offset += 1;
  346. }
  347. Vector<Variant> args;
  348. Vector<const Variant *> argp;
  349. args.resize(argc);
  350. argp.resize(argc);
  351. #ifdef DEBUG_ENABLED
  352. _profile_node_data("in_rpc", p_node->get_instance_id());
  353. #endif
  354. if (byte_only) {
  355. Vector<uint8_t> pure_data;
  356. const int len = p_packet_len - p_offset;
  357. pure_data.resize(len);
  358. memcpy(pure_data.ptrw(), &p_packet[p_offset], len);
  359. args.write[0] = pure_data;
  360. argp.write[0] = &args[0];
  361. p_offset += len;
  362. } else {
  363. for (int i = 0; i < argc; i++) {
  364. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  365. int vlen;
  366. Error err = _decode_and_decompress_variant(args.write[i], &p_packet[p_offset], p_packet_len - p_offset, &vlen);
  367. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RPC argument.");
  368. argp.write[i] = &args[i];
  369. p_offset += vlen;
  370. }
  371. }
  372. Callable::CallError ce;
  373. p_node->call(config.name, (const Variant **)argp.ptr(), argc, ce);
  374. if (ce.error != Callable::CallError::CALL_OK) {
  375. String error = Variant::get_call_error_text(p_node, config.name, (const Variant **)argp.ptr(), argc, ce);
  376. error = "RPC - " + error;
  377. ERR_PRINT(error);
  378. }
  379. }
  380. void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  381. ERR_FAIL_COND_MSG(p_packet_len < 38, "Invalid packet received. Size too small.");
  382. int ofs = 1;
  383. String methods_md5;
  384. methods_md5.parse_utf8((const char *)(p_packet + ofs), 32);
  385. ofs += 33;
  386. int id = decode_uint32(&p_packet[ofs]);
  387. ofs += 4;
  388. String paths;
  389. paths.parse_utf8((const char *)(p_packet + ofs), p_packet_len - ofs);
  390. NodePath path = paths;
  391. if (!path_get_cache.has(p_from)) {
  392. path_get_cache[p_from] = PathGetCache();
  393. }
  394. Node *node = root_node->get_node(path);
  395. ERR_FAIL_COND(node == nullptr);
  396. const bool valid_rpc_checksum = _get_rpc_md5(node) == methods_md5;
  397. if (valid_rpc_checksum == false) {
  398. ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + path);
  399. }
  400. PathGetCache::NodeInfo ni;
  401. ni.path = path;
  402. path_get_cache[p_from].nodes[id] = ni;
  403. // Encode path to send ack.
  404. CharString pname = String(path).utf8();
  405. int len = encode_cstring(pname.get_data(), nullptr);
  406. Vector<uint8_t> packet;
  407. packet.resize(1 + 1 + len);
  408. packet.write[0] = NETWORK_COMMAND_CONFIRM_PATH;
  409. packet.write[1] = valid_rpc_checksum;
  410. encode_cstring(pname.get_data(), &packet.write[2]);
  411. network_peer->set_transfer_channel(0);
  412. network_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  413. network_peer->set_target_peer(p_from);
  414. network_peer->put_packet(packet.ptr(), packet.size());
  415. }
  416. void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  417. ERR_FAIL_COND_MSG(p_packet_len < 3, "Invalid packet received. Size too small.");
  418. const bool valid_rpc_checksum = p_packet[1];
  419. String paths;
  420. paths.parse_utf8((const char *)&p_packet[2], p_packet_len - 2);
  421. NodePath path = paths;
  422. if (valid_rpc_checksum == false) {
  423. ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + path);
  424. }
  425. PathSentCache *psc = path_send_cache.getptr(path);
  426. ERR_FAIL_COND_MSG(!psc, "Invalid packet received. Tries to confirm a path which was not found in cache.");
  427. Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
  428. ERR_FAIL_COND_MSG(!E, "Invalid packet received. Source peer was not found in cache for the given path.");
  429. E->get() = true;
  430. }
  431. void MultiplayerAPI::_process_spawn_despawn(int p_from, const uint8_t *p_packet, int p_packet_len, bool p_spawn) {
  432. ERR_FAIL_COND_MSG(p_packet_len < 18, "Invalid spawn packet received");
  433. int ofs = 1;
  434. ResourceUID::ID id = decode_uint64(&p_packet[ofs]);
  435. ofs += 8;
  436. ERR_FAIL_COND_MSG(!spawnables.has(id), "Invalid spawn ID received " + itos(id));
  437. uint32_t node_target = decode_uint32(&p_packet[ofs]);
  438. Node *parent = _process_get_node(p_from, nullptr, node_target, 0);
  439. ofs += 4;
  440. ERR_FAIL_COND_MSG(parent == nullptr, "Invalid packet received. Requested node was not found.");
  441. uint32_t name_len = decode_uint32(&p_packet[ofs]);
  442. ofs += 4;
  443. ERR_FAIL_COND_MSG(name_len > uint32_t(p_packet_len - ofs), vformat("Invalid spawn packet size: %d, wants: %d", p_packet_len, ofs + name_len));
  444. ERR_FAIL_COND_MSG(name_len < 1, "Zero spawn name size.");
  445. const String name = String::utf8((const char *)&p_packet[ofs], name_len);
  446. // We need to make sure no trickery happens here (e.g. despawning a subpath), but we want to allow autogenerated ("@") node names.
  447. ERR_FAIL_COND_MSG(name.validate_node_name() != name.replace("@", ""), vformat("Invalid node name received: '%s'", name));
  448. ofs += name_len;
  449. PackedByteArray data;
  450. if (p_packet_len > ofs) {
  451. data.resize(p_packet_len - ofs);
  452. memcpy(data.ptrw(), &p_packet[ofs], data.size());
  453. }
  454. SpawnMode mode = spawnables[id];
  455. if (mode == SPAWN_MODE_SERVER && p_from == 1) {
  456. String scene_path = ResourceUID::get_singleton()->get_id_path(id);
  457. if (p_spawn) {
  458. ERR_FAIL_COND_MSG(parent->has_node(name), vformat("Unable to spawn node. Node already exists: %s/%s", parent->get_path(), name));
  459. RES res = ResourceLoader::load(scene_path);
  460. ERR_FAIL_COND_MSG(!res.is_valid(), "Unable to load scene to spawn at path: " + scene_path);
  461. PackedScene *scene = Object::cast_to<PackedScene>(res.ptr());
  462. ERR_FAIL_COND(!scene);
  463. Node *node = scene->instantiate();
  464. ERR_FAIL_COND(!node);
  465. replicated_nodes[node->get_instance_id()] = id;
  466. parent->_add_child_nocheck(node, name);
  467. emit_signal(SNAME("network_spawn"), p_from, id, node, data);
  468. } else {
  469. ERR_FAIL_COND_MSG(!parent->has_node(name), vformat("Path not found: %s/%s", parent->get_path(), name));
  470. Node *node = parent->get_node(name);
  471. ERR_FAIL_COND_MSG(!replicated_nodes.has(node->get_instance_id()), vformat("Trying to despawn a Node that was not replicated: %s/%s", parent->get_path(), name));
  472. emit_signal(SNAME("network_despawn"), p_from, id, node, data);
  473. replicated_nodes.erase(node->get_instance_id());
  474. node->queue_delete();
  475. }
  476. } else {
  477. if (p_spawn) {
  478. emit_signal(SNAME("network_spawn_request"), p_from, id, parent, name, data);
  479. } else {
  480. emit_signal(SNAME("network_despawn_request"), p_from, id, parent, name, data);
  481. }
  482. }
  483. }
  484. bool MultiplayerAPI::_send_confirm_path(Node *p_node, NodePath p_path, PathSentCache *psc, int p_target) {
  485. bool has_all_peers = true;
  486. List<int> peers_to_add; // If one is missing, take note to add it.
  487. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  488. if (p_target < 0 && E->get() == -p_target) {
  489. continue; // Continue, excluded.
  490. }
  491. if (p_target > 0 && E->get() != p_target) {
  492. continue; // Continue, not for this peer.
  493. }
  494. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  495. if (!F || !F->get()) {
  496. // Path was not cached, or was cached but is unconfirmed.
  497. if (!F) {
  498. // Not cached at all, take note.
  499. peers_to_add.push_back(E->get());
  500. }
  501. has_all_peers = false;
  502. }
  503. }
  504. if (peers_to_add.size() > 0) {
  505. // Those that need to be added, send a message for this.
  506. // Encode function name.
  507. const CharString path = String(p_path).utf8();
  508. const int path_len = encode_cstring(path.get_data(), nullptr);
  509. // Extract MD5 from rpc methods list.
  510. const String methods_md5 = _get_rpc_md5(p_node);
  511. const int methods_md5_len = 33; // 32 + 1 for the `0` that is added by the encoder.
  512. Vector<uint8_t> packet;
  513. packet.resize(1 + 4 + path_len + methods_md5_len);
  514. int ofs = 0;
  515. packet.write[ofs] = NETWORK_COMMAND_SIMPLIFY_PATH;
  516. ofs += 1;
  517. ofs += encode_cstring(methods_md5.utf8().get_data(), &packet.write[ofs]);
  518. ofs += encode_uint32(psc->id, &packet.write[ofs]);
  519. ofs += encode_cstring(path.get_data(), &packet.write[ofs]);
  520. for (int &E : peers_to_add) {
  521. network_peer->set_target_peer(E); // To all of you.
  522. network_peer->set_transfer_channel(0);
  523. network_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  524. network_peer->put_packet(packet.ptr(), packet.size());
  525. psc->confirmed_peers.insert(E, false); // Insert into confirmed, but as false since it was not confirmed.
  526. }
  527. }
  528. return has_all_peers;
  529. }
  530. // The variant is compressed and encoded; The first byte contains all the meta
  531. // information and the format is:
  532. // - The first LSB 5 bits are used for the variant type.
  533. // - The next two bits are used to store the encoding mode.
  534. // - The most significant is used to store the boolean value.
  535. #define VARIANT_META_TYPE_MASK 0x1F
  536. #define VARIANT_META_EMODE_MASK 0x60
  537. #define VARIANT_META_BOOL_MASK 0x80
  538. #define ENCODE_8 0 << 5
  539. #define ENCODE_16 1 << 5
  540. #define ENCODE_32 2 << 5
  541. #define ENCODE_64 3 << 5
  542. Error MultiplayerAPI::_encode_and_compress_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len) {
  543. // Unreachable because `VARIANT_MAX` == 27 and `ENCODE_VARIANT_MASK` == 31
  544. CRASH_COND(p_variant.get_type() > VARIANT_META_TYPE_MASK);
  545. uint8_t *buf = r_buffer;
  546. r_len = 0;
  547. uint8_t encode_mode = 0;
  548. switch (p_variant.get_type()) {
  549. case Variant::BOOL: {
  550. if (buf) {
  551. // We still have 1 free bit in the meta, so let's use it.
  552. buf[0] = (p_variant.operator bool()) ? (1 << 7) : 0;
  553. buf[0] |= encode_mode | p_variant.get_type();
  554. }
  555. r_len += 1;
  556. } break;
  557. case Variant::INT: {
  558. if (buf) {
  559. // Reserve the first byte for the meta.
  560. buf += 1;
  561. }
  562. r_len += 1;
  563. int64_t val = p_variant;
  564. if (val <= (int64_t)INT8_MAX && val >= (int64_t)INT8_MIN) {
  565. // Use 8 bit
  566. encode_mode = ENCODE_8;
  567. if (buf) {
  568. buf[0] = val;
  569. }
  570. r_len += 1;
  571. } else if (val <= (int64_t)INT16_MAX && val >= (int64_t)INT16_MIN) {
  572. // Use 16 bit
  573. encode_mode = ENCODE_16;
  574. if (buf) {
  575. encode_uint16(val, buf);
  576. }
  577. r_len += 2;
  578. } else if (val <= (int64_t)INT32_MAX && val >= (int64_t)INT32_MIN) {
  579. // Use 32 bit
  580. encode_mode = ENCODE_32;
  581. if (buf) {
  582. encode_uint32(val, buf);
  583. }
  584. r_len += 4;
  585. } else {
  586. // Use 64 bit
  587. encode_mode = ENCODE_64;
  588. if (buf) {
  589. encode_uint64(val, buf);
  590. }
  591. r_len += 8;
  592. }
  593. // Store the meta
  594. if (buf) {
  595. buf -= 1;
  596. buf[0] = encode_mode | p_variant.get_type();
  597. }
  598. } break;
  599. default:
  600. // Any other case is not yet compressed.
  601. Error err = encode_variant(p_variant, r_buffer, r_len, allow_object_decoding);
  602. if (err != OK) {
  603. return err;
  604. }
  605. if (r_buffer) {
  606. // The first byte is not used by the marshalling, so store the type
  607. // so we know how to decompress and decode this variant.
  608. r_buffer[0] = p_variant.get_type();
  609. }
  610. }
  611. return OK;
  612. }
  613. Error MultiplayerAPI::_decode_and_decompress_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len) {
  614. const uint8_t *buf = p_buffer;
  615. int len = p_len;
  616. ERR_FAIL_COND_V(len < 1, ERR_INVALID_DATA);
  617. uint8_t type = buf[0] & VARIANT_META_TYPE_MASK;
  618. uint8_t encode_mode = buf[0] & VARIANT_META_EMODE_MASK;
  619. ERR_FAIL_COND_V(type >= Variant::VARIANT_MAX, ERR_INVALID_DATA);
  620. switch (type) {
  621. case Variant::BOOL: {
  622. bool val = (buf[0] & VARIANT_META_BOOL_MASK) > 0;
  623. r_variant = val;
  624. if (r_len) {
  625. *r_len = 1;
  626. }
  627. } break;
  628. case Variant::INT: {
  629. buf += 1;
  630. len -= 1;
  631. if (r_len) {
  632. *r_len = 1;
  633. }
  634. if (encode_mode == ENCODE_8) {
  635. // 8 bits.
  636. ERR_FAIL_COND_V(len < 1, ERR_INVALID_DATA);
  637. int8_t val = buf[0];
  638. r_variant = val;
  639. if (r_len) {
  640. (*r_len) += 1;
  641. }
  642. } else if (encode_mode == ENCODE_16) {
  643. // 16 bits.
  644. ERR_FAIL_COND_V(len < 2, ERR_INVALID_DATA);
  645. int16_t val = decode_uint16(buf);
  646. r_variant = val;
  647. if (r_len) {
  648. (*r_len) += 2;
  649. }
  650. } else if (encode_mode == ENCODE_32) {
  651. // 32 bits.
  652. ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
  653. int32_t val = decode_uint32(buf);
  654. r_variant = val;
  655. if (r_len) {
  656. (*r_len) += 4;
  657. }
  658. } else {
  659. // 64 bits.
  660. ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA);
  661. int64_t val = decode_uint64(buf);
  662. r_variant = val;
  663. if (r_len) {
  664. (*r_len) += 8;
  665. }
  666. }
  667. } break;
  668. default:
  669. Error err = decode_variant(r_variant, p_buffer, p_len, r_len, allow_object_decoding);
  670. if (err != OK) {
  671. return err;
  672. }
  673. }
  674. return OK;
  675. }
  676. void MultiplayerAPI::_send_rpc(Node *p_from, int p_to, uint16_t p_rpc_id, const RPCConfig &p_config, const StringName &p_name, const Variant **p_arg, int p_argcount) {
  677. ERR_FAIL_COND_MSG(network_peer.is_null(), "Attempt to remote call/set when networking is not active in SceneTree.");
  678. ERR_FAIL_COND_MSG(network_peer->get_connection_status() == MultiplayerPeer::CONNECTION_CONNECTING, "Attempt to remote call/set when networking is not connected yet in SceneTree.");
  679. ERR_FAIL_COND_MSG(network_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to remote call/set when networking is disconnected.");
  680. ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments >255.");
  681. if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
  682. ERR_FAIL_COND_MSG(p_to == network_peer->get_unique_id(), "Attempt to remote call/set yourself! unique ID: " + itos(network_peer->get_unique_id()) + ".");
  683. ERR_FAIL_MSG("Attempt to remote call unexisting ID: " + itos(p_to) + ".");
  684. }
  685. NodePath from_path = (root_node->get_path()).rel_path_to(p_from->get_path());
  686. ERR_FAIL_COND_MSG(from_path.is_empty(), "Unable to send RPC. Relative path is empty. THIS IS LIKELY A BUG IN THE ENGINE!");
  687. // See if the path is cached.
  688. PathSentCache *psc = path_send_cache.getptr(from_path);
  689. if (!psc) {
  690. // Path is not cached, create.
  691. path_send_cache[from_path] = PathSentCache();
  692. psc = path_send_cache.getptr(from_path);
  693. psc->id = last_send_cache_id++;
  694. }
  695. // See if all peers have cached path (if so, call can be fast).
  696. const bool has_all_peers = _send_confirm_path(p_from, from_path, psc, p_to);
  697. // Create base packet, lots of hardcode because it must be tight.
  698. int ofs = 0;
  699. #define MAKE_ROOM(m_amount) \
  700. if (packet_cache.size() < m_amount) \
  701. packet_cache.resize(m_amount);
  702. // Encode meta.
  703. // The meta is composed by a single byte that contains (starting from the least significant bit):
  704. // - `NetworkCommands` in the first three bits.
  705. // - `NetworkNodeIdCompression` in the next 2 bits.
  706. // - `NetworkNameIdCompression` in the next 1 bit.
  707. // - `byte_only_or_no_args` in the next 1 bit.
  708. // - So we still have the last bit free!
  709. uint8_t command_type = NETWORK_COMMAND_REMOTE_CALL;
  710. uint8_t node_id_compression = UINT8_MAX;
  711. uint8_t name_id_compression = UINT8_MAX;
  712. bool byte_only_or_no_args = false;
  713. MAKE_ROOM(1);
  714. // The meta is composed along the way, so just set 0 for now.
  715. packet_cache.write[0] = 0;
  716. ofs += 1;
  717. // Encode Node ID.
  718. if (has_all_peers) {
  719. // Compress the node ID only if all the target peers already know it.
  720. if (psc->id >= 0 && psc->id <= 255) {
  721. // We can encode the id in 1 byte
  722. node_id_compression = NETWORK_NODE_ID_COMPRESSION_8;
  723. MAKE_ROOM(ofs + 1);
  724. packet_cache.write[ofs] = static_cast<uint8_t>(psc->id);
  725. ofs += 1;
  726. } else if (psc->id >= 0 && psc->id <= 65535) {
  727. // We can encode the id in 2 bytes
  728. node_id_compression = NETWORK_NODE_ID_COMPRESSION_16;
  729. MAKE_ROOM(ofs + 2);
  730. encode_uint16(static_cast<uint16_t>(psc->id), &(packet_cache.write[ofs]));
  731. ofs += 2;
  732. } else {
  733. // Too big, let's use 4 bytes.
  734. node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;
  735. MAKE_ROOM(ofs + 4);
  736. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  737. ofs += 4;
  738. }
  739. } else {
  740. // The targets don't know the node yet, so we need to use 32 bits int.
  741. node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;
  742. MAKE_ROOM(ofs + 4);
  743. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  744. ofs += 4;
  745. }
  746. // Encode method ID
  747. if (p_rpc_id <= UINT8_MAX) {
  748. // The ID fits in 1 byte
  749. name_id_compression = NETWORK_NAME_ID_COMPRESSION_8;
  750. MAKE_ROOM(ofs + 1);
  751. packet_cache.write[ofs] = static_cast<uint8_t>(p_rpc_id);
  752. ofs += 1;
  753. } else {
  754. // The ID is larger, let's use 2 bytes
  755. name_id_compression = NETWORK_NAME_ID_COMPRESSION_16;
  756. MAKE_ROOM(ofs + 2);
  757. encode_uint16(p_rpc_id, &(packet_cache.write[ofs]));
  758. ofs += 2;
  759. }
  760. if (p_argcount == 0) {
  761. byte_only_or_no_args = true;
  762. } else if (p_argcount == 1 && p_arg[0]->get_type() == Variant::PACKED_BYTE_ARRAY) {
  763. byte_only_or_no_args = true;
  764. // Special optimization when only the byte vector is sent.
  765. const Vector<uint8_t> data = *p_arg[0];
  766. MAKE_ROOM(ofs + data.size());
  767. memcpy(&(packet_cache.write[ofs]), data.ptr(), sizeof(uint8_t) * data.size());
  768. ofs += data.size();
  769. } else {
  770. // Arguments
  771. MAKE_ROOM(ofs + 1);
  772. packet_cache.write[ofs] = p_argcount;
  773. ofs += 1;
  774. for (int i = 0; i < p_argcount; i++) {
  775. int len(0);
  776. Error err = _encode_and_compress_variant(*p_arg[i], nullptr, len);
  777. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC argument. THIS IS LIKELY A BUG IN THE ENGINE!");
  778. MAKE_ROOM(ofs + len);
  779. _encode_and_compress_variant(*p_arg[i], &(packet_cache.write[ofs]), len);
  780. ofs += len;
  781. }
  782. }
  783. ERR_FAIL_COND(command_type > 7);
  784. ERR_FAIL_COND(node_id_compression > 3);
  785. ERR_FAIL_COND(name_id_compression > 1);
  786. // We can now set the meta
  787. packet_cache.write[0] = command_type + (node_id_compression << NODE_ID_COMPRESSION_SHIFT) + (name_id_compression << NAME_ID_COMPRESSION_SHIFT) + ((byte_only_or_no_args ? 1 : 0) << BYTE_ONLY_OR_NO_ARGS_SHIFT);
  788. #ifdef DEBUG_ENABLED
  789. _profile_bandwidth_data("out", ofs);
  790. #endif
  791. // Take chance and set transfer mode, since all send methods will use it.
  792. network_peer->set_transfer_channel(p_config.channel);
  793. network_peer->set_transfer_mode(p_config.transfer_mode);
  794. if (has_all_peers) {
  795. // They all have verified paths, so send fast.
  796. network_peer->set_target_peer(p_to); // To all of you.
  797. network_peer->put_packet(packet_cache.ptr(), ofs); // A message with love.
  798. } else {
  799. // Unreachable because the node ID is never compressed if the peers doesn't know it.
  800. CRASH_COND(node_id_compression != NETWORK_NODE_ID_COMPRESSION_32);
  801. // Not all verified path, so send one by one.
  802. // Append path at the end, since we will need it for some packets.
  803. CharString pname = String(from_path).utf8();
  804. int path_len = encode_cstring(pname.get_data(), nullptr);
  805. MAKE_ROOM(ofs + path_len);
  806. encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));
  807. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  808. if (p_to < 0 && E->get() == -p_to) {
  809. continue; // Continue, excluded.
  810. }
  811. if (p_to > 0 && E->get() != p_to) {
  812. continue; // Continue, not for this peer.
  813. }
  814. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  815. ERR_CONTINUE(!F); // Should never happen.
  816. network_peer->set_target_peer(E->get()); // To this one specifically.
  817. if (F->get()) {
  818. // This one confirmed path, so use id.
  819. encode_uint32(psc->id, &(packet_cache.write[1]));
  820. network_peer->put_packet(packet_cache.ptr(), ofs);
  821. } else {
  822. // This one did not confirm path yet, so use entire path (sorry!).
  823. encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
  824. network_peer->put_packet(packet_cache.ptr(), ofs + path_len);
  825. }
  826. }
  827. }
  828. }
  829. void MultiplayerAPI::_add_peer(int p_id) {
  830. connected_peers.insert(p_id);
  831. path_get_cache.insert(p_id, PathGetCache());
  832. if (is_network_server()) {
  833. for (const KeyValue<ObjectID, ResourceUID::ID> &E : replicated_nodes) {
  834. // Only server mode adds to replicated_nodes, no need to check it.
  835. Object *obj = ObjectDB::get_instance(E.key);
  836. ERR_CONTINUE(!obj);
  837. Node *node = Object::cast_to<Node>(obj);
  838. ERR_CONTINUE(!node);
  839. _send_spawn_despawn(p_id, E.value, node->get_path(), nullptr, 0, true);
  840. }
  841. }
  842. emit_signal(SNAME("network_peer_connected"), p_id);
  843. }
  844. void MultiplayerAPI::_del_peer(int p_id) {
  845. connected_peers.erase(p_id);
  846. // Cleanup get cache.
  847. path_get_cache.erase(p_id);
  848. // Cleanup sent cache.
  849. // Some refactoring is needed to make this faster and do paths GC.
  850. List<NodePath> keys;
  851. path_send_cache.get_key_list(&keys);
  852. for (const NodePath &E : keys) {
  853. PathSentCache *psc = path_send_cache.getptr(E);
  854. psc->confirmed_peers.erase(p_id);
  855. }
  856. if (p_id == 1) {
  857. // Erase server replicated nodes, but do not queue them for deletion.
  858. replicated_nodes.clear();
  859. }
  860. emit_signal(SNAME("network_peer_disconnected"), p_id);
  861. }
  862. void MultiplayerAPI::_connected_to_server() {
  863. emit_signal(SNAME("connected_to_server"));
  864. }
  865. void MultiplayerAPI::_connection_failed() {
  866. emit_signal(SNAME("connection_failed"));
  867. }
  868. void MultiplayerAPI::_server_disconnected() {
  869. emit_signal(SNAME("server_disconnected"));
  870. }
  871. void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  872. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to call an RPC while no network peer is active.");
  873. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to call an RPC on a node which is not inside SceneTree.");
  874. ERR_FAIL_COND_MSG(network_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, "Trying to call an RPC via a network peer which is not connected.");
  875. int node_id = network_peer->get_unique_id();
  876. bool call_local_native = false;
  877. bool call_local_script = false;
  878. uint16_t rpc_id = UINT16_MAX;
  879. const RPCConfig config = _get_rpc_config(p_node, p_method, rpc_id);
  880. ERR_FAIL_COND_MSG(config.name == StringName(),
  881. vformat("Unable to get the RPC configuration for the function \"%s\" at path: \"%s\". This happens when the method is not marked for RPCs.", p_method, p_node->get_path()));
  882. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  883. if (rpc_id & (1 << 15)) {
  884. call_local_native = config.sync;
  885. } else {
  886. call_local_script = config.sync;
  887. }
  888. }
  889. if (p_peer_id != node_id) {
  890. #ifdef DEBUG_ENABLED
  891. _profile_node_data("out_rpc", p_node->get_instance_id());
  892. #endif
  893. _send_rpc(p_node, p_peer_id, rpc_id, config, p_method, p_arg, p_argcount);
  894. }
  895. if (call_local_native) {
  896. int temp_id = rpc_sender_id;
  897. rpc_sender_id = get_network_unique_id();
  898. Callable::CallError ce;
  899. p_node->call(p_method, p_arg, p_argcount, ce);
  900. rpc_sender_id = temp_id;
  901. if (ce.error != Callable::CallError::CALL_OK) {
  902. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  903. error = "rpc() aborted in local call: - " + error + ".";
  904. ERR_PRINT(error);
  905. return;
  906. }
  907. }
  908. if (call_local_script) {
  909. int temp_id = rpc_sender_id;
  910. rpc_sender_id = get_network_unique_id();
  911. Callable::CallError ce;
  912. ce.error = Callable::CallError::CALL_OK;
  913. p_node->get_script_instance()->call(p_method, p_arg, p_argcount, ce);
  914. rpc_sender_id = temp_id;
  915. if (ce.error != Callable::CallError::CALL_OK) {
  916. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  917. error = "rpc() aborted in script local call: - " + error + ".";
  918. ERR_PRINT(error);
  919. return;
  920. }
  921. }
  922. ERR_FAIL_COND_MSG(p_peer_id == node_id && !config.sync, "RPC '" + p_method + "' on yourself is not allowed by selected mode.");
  923. }
  924. Error MultiplayerAPI::send_bytes(Vector<uint8_t> p_data, int p_to, MultiplayerPeer::TransferMode p_mode, int p_channel) {
  925. ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet.");
  926. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no network peer is active.");
  927. ERR_FAIL_COND_V_MSG(network_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a network peer which is not connected.");
  928. MAKE_ROOM(p_data.size() + 1);
  929. const uint8_t *r = p_data.ptr();
  930. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  931. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  932. network_peer->set_target_peer(p_to);
  933. network_peer->set_transfer_channel(p_channel);
  934. network_peer->set_transfer_mode(p_mode);
  935. return network_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
  936. }
  937. void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  938. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  939. Vector<uint8_t> out;
  940. int len = p_packet_len - 1;
  941. out.resize(len);
  942. {
  943. uint8_t *w = out.ptrw();
  944. memcpy(&w[0], &p_packet[1], len);
  945. }
  946. emit_signal(SNAME("network_peer_packet"), p_from, out);
  947. }
  948. int MultiplayerAPI::get_network_unique_id() const {
  949. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), 0, "No network peer is assigned. Unable to get unique network ID.");
  950. return network_peer->get_unique_id();
  951. }
  952. bool MultiplayerAPI::is_network_server() const {
  953. return network_peer.is_valid() && network_peer->is_server();
  954. }
  955. void MultiplayerAPI::set_refuse_new_network_connections(bool p_refuse) {
  956. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "No network peer is assigned. Unable to set 'refuse_new_connections'.");
  957. network_peer->set_refuse_new_connections(p_refuse);
  958. }
  959. bool MultiplayerAPI::is_refusing_new_network_connections() const {
  960. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. Unable to get 'refuse_new_connections'.");
  961. return network_peer->is_refusing_new_connections();
  962. }
  963. Vector<int> MultiplayerAPI::get_network_connected_peers() const {
  964. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), Vector<int>(), "No network peer is assigned. Assume no peers are connected.");
  965. Vector<int> ret;
  966. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  967. ret.push_back(E->get());
  968. }
  969. return ret;
  970. }
  971. void MultiplayerAPI::set_allow_object_decoding(bool p_enable) {
  972. allow_object_decoding = p_enable;
  973. }
  974. bool MultiplayerAPI::is_object_decoding_allowed() const {
  975. return allow_object_decoding;
  976. }
  977. Error MultiplayerAPI::spawnable_config(const ResourceUID::ID &p_id, SpawnMode p_mode) {
  978. ERR_FAIL_COND_V(p_mode < SPAWN_MODE_NONE || p_mode > SPAWN_MODE_CUSTOM, ERR_INVALID_PARAMETER);
  979. ERR_FAIL_COND_V(!ResourceUID::get_singleton()->has_id(p_id), ERR_INVALID_PARAMETER);
  980. #ifdef TOOLS_ENABLED
  981. String path = ResourceUID::get_singleton()->get_id_path(p_id);
  982. RES res = ResourceLoader::load(path);
  983. ERR_FAIL_COND_V(!res->is_class("PackedScene"), ERR_INVALID_PARAMETER);
  984. #endif
  985. if (p_mode == SPAWN_MODE_NONE) {
  986. if (spawnables.has(p_id)) {
  987. spawnables.erase(p_id);
  988. }
  989. } else {
  990. spawnables[p_id] = p_mode;
  991. }
  992. return OK;
  993. }
  994. Error MultiplayerAPI::send_despawn(int p_peer_id, const ResourceUID::ID &p_scene_id, const NodePath &p_path, const PackedByteArray &p_data) {
  995. return _send_spawn_despawn(p_peer_id, p_scene_id, p_path, p_data.ptr(), p_data.size(), false);
  996. }
  997. Error MultiplayerAPI::send_spawn(int p_peer_id, const ResourceUID::ID &p_scene_id, const NodePath &p_path, const PackedByteArray &p_data) {
  998. return _send_spawn_despawn(p_peer_id, p_scene_id, p_path, p_data.ptr(), p_data.size(), true);
  999. }
  1000. Error MultiplayerAPI::_send_spawn_despawn(int p_peer_id, const ResourceUID::ID &p_scene_id, const NodePath &p_path, const uint8_t *p_data, int p_data_len, bool p_spawn) {
  1001. ERR_FAIL_COND_V(!root_node, ERR_UNCONFIGURED);
  1002. ERR_FAIL_COND_V_MSG(!spawnables.has(p_scene_id), ERR_INVALID_PARAMETER, vformat("Spawnable not found: %d", p_scene_id));
  1003. NodePath rel_path = (root_node->get_path()).rel_path_to(p_path);
  1004. const Vector<StringName> names = rel_path.get_names();
  1005. ERR_FAIL_COND_V(names.size() < 2, ERR_INVALID_PARAMETER);
  1006. NodePath parent = NodePath(names.subarray(0, names.size() - 2), false);
  1007. ERR_FAIL_COND_V_MSG(!root_node->has_node(parent), ERR_INVALID_PARAMETER, "Path not found: " + parent);
  1008. // See if the path is cached.
  1009. PathSentCache *psc = path_send_cache.getptr(parent);
  1010. if (!psc) {
  1011. // Path is not cached, create.
  1012. path_send_cache[parent] = PathSentCache();
  1013. psc = path_send_cache.getptr(parent);
  1014. psc->id = last_send_cache_id++;
  1015. }
  1016. _send_confirm_path(root_node->get_node(parent), parent, psc, p_peer_id);
  1017. const CharString cname = String(names[names.size() - 1]).utf8();
  1018. int nlen = encode_cstring(cname.get_data(), nullptr);
  1019. MAKE_ROOM(1 + 8 + 4 + 4 + nlen + p_data_len);
  1020. uint8_t *ptr = packet_cache.ptrw();
  1021. ptr[0] = p_spawn ? NETWORK_COMMAND_SPAWN : NETWORK_COMMAND_DESPAWN;
  1022. int ofs = 1;
  1023. ofs += encode_uint64(p_scene_id, &ptr[ofs]);
  1024. ofs += encode_uint32(psc->id, &ptr[ofs]);
  1025. ofs += encode_uint32(nlen, &ptr[ofs]);
  1026. ofs += encode_cstring(cname.get_data(), &ptr[ofs]);
  1027. memcpy(&ptr[ofs], p_data, p_data_len);
  1028. network_peer->set_target_peer(p_peer_id);
  1029. network_peer->set_transfer_channel(0);
  1030. network_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  1031. return network_peer->put_packet(ptr, ofs + p_data_len);
  1032. }
  1033. void MultiplayerAPI::scene_enter_exit_notify(const String &p_scene, const Node *p_node, bool p_enter) {
  1034. if (!has_network_peer()) {
  1035. return;
  1036. }
  1037. ERR_FAIL_COND(!p_node || !p_node->get_parent() || !root_node);
  1038. NodePath path = (root_node->get_path()).rel_path_to(p_node->get_parent()->get_path());
  1039. if (path.is_empty()) {
  1040. return;
  1041. }
  1042. ResourceUID::ID id = ResourceLoader::get_resource_uid(p_scene);
  1043. if (!spawnables.has(id)) {
  1044. return;
  1045. }
  1046. SpawnMode mode = spawnables[id];
  1047. if (p_enter) {
  1048. if (mode == SPAWN_MODE_SERVER && is_network_server()) {
  1049. replicated_nodes[p_node->get_instance_id()] = id;
  1050. _send_spawn_despawn(0, id, p_node->get_path(), nullptr, 0, true);
  1051. }
  1052. emit_signal(SNAME("network_spawnable_added"), id, p_node);
  1053. } else {
  1054. if (mode == SPAWN_MODE_SERVER && is_network_server() && replicated_nodes.has(p_node->get_instance_id())) {
  1055. replicated_nodes.erase(p_node->get_instance_id());
  1056. _send_spawn_despawn(0, id, p_node->get_path(), nullptr, 0, false);
  1057. }
  1058. emit_signal(SNAME("network_spawnable_removed"), id, p_node);
  1059. }
  1060. }
  1061. void MultiplayerAPI::_bind_methods() {
  1062. ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node);
  1063. ClassDB::bind_method(D_METHOD("get_root_node"), &MultiplayerAPI::get_root_node);
  1064. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode", "channel"), &MultiplayerAPI::send_bytes, DEFVAL(MultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(MultiplayerPeer::TRANSFER_MODE_RELIABLE), DEFVAL(0));
  1065. ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer);
  1066. ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer);
  1067. ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id);
  1068. ClassDB::bind_method(D_METHOD("is_network_server"), &MultiplayerAPI::is_network_server);
  1069. ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &MultiplayerAPI::get_rpc_sender_id);
  1070. ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &MultiplayerAPI::set_network_peer);
  1071. ClassDB::bind_method(D_METHOD("poll"), &MultiplayerAPI::poll);
  1072. ClassDB::bind_method(D_METHOD("clear"), &MultiplayerAPI::clear);
  1073. ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &MultiplayerAPI::get_network_connected_peers);
  1074. ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &MultiplayerAPI::set_refuse_new_network_connections);
  1075. ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &MultiplayerAPI::is_refusing_new_network_connections);
  1076. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &MultiplayerAPI::set_allow_object_decoding);
  1077. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &MultiplayerAPI::is_object_decoding_allowed);
  1078. ClassDB::bind_method(D_METHOD("spawnable_config", "scene_id", "spawn_mode"), &MultiplayerAPI::spawnable_config);
  1079. ClassDB::bind_method(D_METHOD("send_despawn", "peer_id", "scene_id", "path", "data"), &MultiplayerAPI::send_despawn, DEFVAL(PackedByteArray()));
  1080. ClassDB::bind_method(D_METHOD("send_spawn", "peer_id", "scene_id", "path", "data"), &MultiplayerAPI::send_spawn, DEFVAL(PackedByteArray()));
  1081. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  1082. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections");
  1083. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "MultiplayerPeer", PROPERTY_USAGE_NONE), "set_network_peer", "get_network_peer");
  1084. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "root_node", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "set_root_node", "get_root_node");
  1085. ADD_PROPERTY_DEFAULT("refuse_new_network_connections", false);
  1086. ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
  1087. ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
  1088. ADD_SIGNAL(MethodInfo("network_peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packet")));
  1089. ADD_SIGNAL(MethodInfo("connected_to_server"));
  1090. ADD_SIGNAL(MethodInfo("connection_failed"));
  1091. ADD_SIGNAL(MethodInfo("server_disconnected"));
  1092. ADD_SIGNAL(MethodInfo("network_despawn", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::INT, "scene_id"), PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "data")));
  1093. ADD_SIGNAL(MethodInfo("network_spawn", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::INT, "scene_id"), PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "data")));
  1094. ADD_SIGNAL(MethodInfo("network_despawn_request", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::INT, "scene_id"), PropertyInfo(Variant::OBJECT, "parent", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "data")));
  1095. ADD_SIGNAL(MethodInfo("network_spawn_request", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::INT, "scene_id"), PropertyInfo(Variant::OBJECT, "parent", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "data")));
  1096. ADD_SIGNAL(MethodInfo("network_spawnable_added", PropertyInfo(Variant::INT, "scene_id"), PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  1097. ADD_SIGNAL(MethodInfo("network_spawnable_removed", PropertyInfo(Variant::INT, "scene_id"), PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  1098. BIND_ENUM_CONSTANT(RPC_MODE_DISABLED);
  1099. BIND_ENUM_CONSTANT(RPC_MODE_REMOTE);
  1100. BIND_ENUM_CONSTANT(RPC_MODE_MASTER);
  1101. BIND_ENUM_CONSTANT(RPC_MODE_PUPPET);
  1102. BIND_ENUM_CONSTANT(SPAWN_MODE_NONE);
  1103. BIND_ENUM_CONSTANT(SPAWN_MODE_SERVER);
  1104. BIND_ENUM_CONSTANT(SPAWN_MODE_CUSTOM);
  1105. }
  1106. MultiplayerAPI::MultiplayerAPI() {
  1107. clear();
  1108. }
  1109. MultiplayerAPI::~MultiplayerAPI() {
  1110. clear();
  1111. }