multiplayer_api.cpp 44 KB

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