scene_rpc_interface.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /**************************************************************************/
  2. /* scene_rpc_interface.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "scene_rpc_interface.h"
  31. #include "scene_multiplayer.h"
  32. #include "core/debugger/engine_debugger.h"
  33. #include "core/io/marshalls.h"
  34. #include "scene/main/multiplayer_api.h"
  35. #include "scene/main/node.h"
  36. #include "scene/main/window.h"
  37. // The RPC meta is composed by a single byte that contains (starting from the least significant bit):
  38. // - `NetworkCommands` in the first four bits.
  39. // - `NetworkNodeIdCompression` in the next 2 bits.
  40. // - `NetworkNameIdCompression` in the next 1 bit.
  41. // - `byte_only_or_no_args` in the next 1 bit.
  42. #define NODE_ID_COMPRESSION_SHIFT SceneMultiplayer::CMD_FLAG_0_SHIFT
  43. #define NAME_ID_COMPRESSION_SHIFT SceneMultiplayer::CMD_FLAG_2_SHIFT
  44. #define BYTE_ONLY_OR_NO_ARGS_SHIFT SceneMultiplayer::CMD_FLAG_3_SHIFT
  45. #define NODE_ID_COMPRESSION_FLAG ((1 << NODE_ID_COMPRESSION_SHIFT) | (1 << (NODE_ID_COMPRESSION_SHIFT + 1)))
  46. #define NAME_ID_COMPRESSION_FLAG (1 << NAME_ID_COMPRESSION_SHIFT)
  47. #define BYTE_ONLY_OR_NO_ARGS_FLAG (1 << BYTE_ONLY_OR_NO_ARGS_SHIFT)
  48. #ifdef DEBUG_ENABLED
  49. _FORCE_INLINE_ void SceneRPCInterface::_profile_node_data(const String &p_what, ObjectID p_id, int p_size) {
  50. if (EngineDebugger::is_profiling("multiplayer:rpc")) {
  51. Array values;
  52. values.push_back(p_what);
  53. values.push_back(p_id);
  54. values.push_back(p_size);
  55. EngineDebugger::profiler_add_frame_data("multiplayer:rpc", values);
  56. }
  57. }
  58. #endif
  59. // Returns the packet size stripping the node path added when the node is not yet cached.
  60. int get_packet_len(uint32_t p_node_target, int p_packet_len) {
  61. if (p_node_target & 0x80000000) {
  62. int ofs = p_node_target & 0x7FFFFFFF;
  63. return p_packet_len - (p_packet_len - ofs);
  64. } else {
  65. return p_packet_len;
  66. }
  67. }
  68. bool SceneRPCInterface::_sort_rpc_names(const Variant &p_l, const Variant &p_r) {
  69. if (likely(p_l.is_string() && p_r.is_string())) {
  70. return p_l.operator String() < p_r.operator String();
  71. }
  72. bool valid = false;
  73. Variant res;
  74. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  75. return valid ? res.operator bool() : false;
  76. }
  77. void SceneRPCInterface::_parse_rpc_config(const Variant &p_config, bool p_for_node, RPCConfigCache &r_cache) {
  78. if (p_config.get_type() == Variant::NIL) {
  79. return;
  80. }
  81. ERR_FAIL_COND(p_config.get_type() != Variant::DICTIONARY);
  82. const Dictionary config = p_config;
  83. Array names = config.keys();
  84. names.sort_custom(callable_mp_static(&SceneRPCInterface::_sort_rpc_names)); // Ensure ID order
  85. for (int i = 0; i < names.size(); i++) {
  86. ERR_CONTINUE(!names[i].is_string());
  87. String name = names[i].operator String();
  88. ERR_CONTINUE(config[name].get_type() != Variant::DICTIONARY);
  89. ERR_CONTINUE(!config[name].operator Dictionary().has("rpc_mode"));
  90. Dictionary dict = config[name];
  91. RPCConfig cfg;
  92. cfg.name = name;
  93. cfg.rpc_mode = ((MultiplayerAPI::RPCMode)dict.get("rpc_mode", MultiplayerAPI::RPC_MODE_AUTHORITY).operator int());
  94. cfg.transfer_mode = ((MultiplayerPeer::TransferMode)dict.get("transfer_mode", MultiplayerPeer::TRANSFER_MODE_RELIABLE).operator int());
  95. cfg.call_local = dict.get("call_local", false).operator bool();
  96. cfg.channel = dict.get("channel", 0).operator int();
  97. uint16_t id = ((uint16_t)i);
  98. if (p_for_node) {
  99. id |= (1 << 15);
  100. }
  101. r_cache.configs[id] = cfg;
  102. r_cache.ids[name] = id;
  103. }
  104. }
  105. const SceneRPCInterface::RPCConfigCache &SceneRPCInterface::_get_node_config(const Node *p_node) {
  106. const ObjectID oid = p_node->get_instance_id();
  107. if (rpc_cache.has(oid)) {
  108. return rpc_cache[oid];
  109. }
  110. RPCConfigCache cache;
  111. _parse_rpc_config(p_node->get_node_rpc_config(), true, cache);
  112. if (p_node->get_script_instance()) {
  113. _parse_rpc_config(p_node->get_script_instance()->get_rpc_config(), false, cache);
  114. }
  115. rpc_cache[oid] = cache;
  116. return rpc_cache[oid];
  117. }
  118. String SceneRPCInterface::get_rpc_md5(const Object *p_obj) {
  119. const Node *node = Object::cast_to<Node>(p_obj);
  120. ERR_FAIL_NULL_V(node, "");
  121. const RPCConfigCache cache = _get_node_config(node);
  122. String rpc_list;
  123. for (const KeyValue<uint16_t, RPCConfig> &config : cache.configs) {
  124. rpc_list += String(config.value.name);
  125. }
  126. return rpc_list.md5_text();
  127. }
  128. Node *SceneRPCInterface::_process_get_node(int p_from, const uint8_t *p_packet, uint32_t p_node_target, int p_packet_len) {
  129. Node *root_node = SceneTree::get_singleton()->get_root()->get_node(multiplayer->get_root_path());
  130. ERR_FAIL_NULL_V(root_node, nullptr);
  131. Node *node = nullptr;
  132. if (p_node_target & 0x80000000) {
  133. // Use full path (not cached yet).
  134. int ofs = p_node_target & 0x7FFFFFFF;
  135. ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, nullptr, "Invalid packet received. Size smaller than declared.");
  136. String paths;
  137. paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
  138. NodePath np = paths;
  139. node = root_node->get_node(np);
  140. if (!node) {
  141. ERR_PRINT("Failed to get path from RPC: " + String(np) + ".");
  142. }
  143. return node;
  144. } else {
  145. // Use cached path.
  146. return Object::cast_to<Node>(multiplayer_cache->get_cached_object(p_from, p_node_target));
  147. }
  148. }
  149. void SceneRPCInterface::process_rpc(int p_from, const uint8_t *p_packet, int p_packet_len) {
  150. // Extract packet meta
  151. int packet_min_size = 1;
  152. int name_id_offset = 1;
  153. ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");
  154. // Compute the meta size, which depends on the compression level.
  155. int node_id_compression = (p_packet[0] & NODE_ID_COMPRESSION_FLAG) >> NODE_ID_COMPRESSION_SHIFT;
  156. int name_id_compression = (p_packet[0] & NAME_ID_COMPRESSION_FLAG) >> NAME_ID_COMPRESSION_SHIFT;
  157. switch (node_id_compression) {
  158. case NETWORK_NODE_ID_COMPRESSION_8:
  159. packet_min_size += 1;
  160. name_id_offset += 1;
  161. break;
  162. case NETWORK_NODE_ID_COMPRESSION_16:
  163. packet_min_size += 2;
  164. name_id_offset += 2;
  165. break;
  166. case NETWORK_NODE_ID_COMPRESSION_32:
  167. packet_min_size += 4;
  168. name_id_offset += 4;
  169. break;
  170. default:
  171. ERR_FAIL_MSG("Was not possible to extract the node id compression mode.");
  172. }
  173. switch (name_id_compression) {
  174. case NETWORK_NAME_ID_COMPRESSION_8:
  175. packet_min_size += 1;
  176. break;
  177. case NETWORK_NAME_ID_COMPRESSION_16:
  178. packet_min_size += 2;
  179. break;
  180. default:
  181. ERR_FAIL_MSG("Was not possible to extract the name id compression mode.");
  182. }
  183. ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");
  184. uint32_t node_target = 0;
  185. switch (node_id_compression) {
  186. case NETWORK_NODE_ID_COMPRESSION_8:
  187. node_target = p_packet[1];
  188. break;
  189. case NETWORK_NODE_ID_COMPRESSION_16:
  190. node_target = decode_uint16(p_packet + 1);
  191. break;
  192. case NETWORK_NODE_ID_COMPRESSION_32:
  193. node_target = decode_uint32(p_packet + 1);
  194. break;
  195. default:
  196. // Unreachable, checked before.
  197. CRASH_NOW();
  198. }
  199. Node *node = _process_get_node(p_from, p_packet, node_target, p_packet_len);
  200. ERR_FAIL_NULL_MSG(node, "Invalid packet received. Requested node was not found.");
  201. uint16_t name_id = 0;
  202. switch (name_id_compression) {
  203. case NETWORK_NAME_ID_COMPRESSION_8:
  204. name_id = p_packet[name_id_offset];
  205. break;
  206. case NETWORK_NAME_ID_COMPRESSION_16:
  207. name_id = decode_uint16(p_packet + name_id_offset);
  208. break;
  209. default:
  210. // Unreachable, checked before.
  211. CRASH_NOW();
  212. }
  213. const int packet_len = get_packet_len(node_target, p_packet_len);
  214. _process_rpc(node, name_id, p_from, p_packet, packet_len, packet_min_size);
  215. }
  216. void SceneRPCInterface::_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) {
  217. ERR_FAIL_COND_MSG(p_offset > p_packet_len, "Invalid packet received. Size too small.");
  218. // Check that remote can call the RPC on this node.
  219. const RPCConfigCache &cache_config = _get_node_config(p_node);
  220. ERR_FAIL_COND(!cache_config.configs.has(p_rpc_method_id));
  221. const RPCConfig &config = cache_config.configs[p_rpc_method_id];
  222. bool can_call = false;
  223. switch (config.rpc_mode) {
  224. case MultiplayerAPI::RPC_MODE_DISABLED: {
  225. can_call = false;
  226. } break;
  227. case MultiplayerAPI::RPC_MODE_ANY_PEER: {
  228. can_call = true;
  229. } break;
  230. case MultiplayerAPI::RPC_MODE_AUTHORITY: {
  231. can_call = p_from == p_node->get_multiplayer_authority();
  232. } break;
  233. }
  234. 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) + ", authority is " + itos(p_node->get_multiplayer_authority()) + ".");
  235. int argc = 0;
  236. const bool byte_only_or_no_args = p_packet[0] & BYTE_ONLY_OR_NO_ARGS_FLAG;
  237. if (byte_only_or_no_args) {
  238. if (p_offset < p_packet_len) {
  239. // This packet contains only bytes.
  240. argc = 1;
  241. }
  242. } else {
  243. // Normal variant, takes the argument count from the packet.
  244. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  245. argc = p_packet[p_offset];
  246. p_offset += 1;
  247. }
  248. Vector<Variant> args;
  249. Vector<const Variant *> argp;
  250. args.resize(argc);
  251. argp.resize(argc);
  252. #ifdef DEBUG_ENABLED
  253. _profile_node_data("rpc_in", p_node->get_instance_id(), p_packet_len);
  254. #endif
  255. int out;
  256. MultiplayerAPI::decode_and_decompress_variants(args, &p_packet[p_offset], p_packet_len - p_offset, out, byte_only_or_no_args, multiplayer->is_object_decoding_allowed());
  257. for (int i = 0; i < argc; i++) {
  258. argp.write[i] = &args[i];
  259. }
  260. Callable::CallError ce;
  261. p_node->callp(config.name, (const Variant **)argp.ptr(), argc, ce);
  262. if (ce.error != Callable::CallError::CALL_OK) {
  263. String error = Variant::get_call_error_text(p_node, config.name, (const Variant **)argp.ptr(), argc, ce);
  264. error = "RPC - " + error;
  265. ERR_PRINT(error);
  266. }
  267. }
  268. void SceneRPCInterface::_send_rpc(Node *p_node, int p_to, uint16_t p_rpc_id, const RPCConfig &p_config, const StringName &p_name, const Variant **p_arg, int p_argcount) {
  269. Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();
  270. ERR_FAIL_COND_MSG(peer.is_null(), "Attempt to call RPC without active multiplayer peer.");
  271. ERR_FAIL_COND_MSG(peer->get_connection_status() == MultiplayerPeer::CONNECTION_CONNECTING, "Attempt to call RPC while multiplayer peer is not connected yet.");
  272. ERR_FAIL_COND_MSG(peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to call RPC while multiplayer peer is disconnected.");
  273. ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments (>255).");
  274. if (p_to != 0 && !multiplayer->get_connected_peers().has(ABS(p_to))) {
  275. ERR_FAIL_COND_MSG(p_to == multiplayer->get_unique_id(), "Attempt to call RPC on yourself! Peer unique ID: " + itos(multiplayer->get_unique_id()) + ".");
  276. ERR_FAIL_MSG("Attempt to call RPC with unknown peer ID: " + itos(p_to) + ".");
  277. }
  278. // See if all peers have cached path (if so, call can be fast) while building the RPC target list.
  279. HashSet<int> targets;
  280. int psc_id = -1;
  281. bool has_all_peers = true;
  282. const ObjectID oid = p_node->get_instance_id();
  283. if (p_to > 0) {
  284. ERR_FAIL_COND_MSG(!multiplayer_replicator->is_rpc_visible(oid, p_to), "Attempt to call an RPC to a peer that cannot see this node. Peer ID: " + itos(p_to));
  285. targets.insert(p_to);
  286. has_all_peers = multiplayer_cache->send_object_cache(p_node, p_to, psc_id);
  287. } else {
  288. bool restricted = !multiplayer_replicator->is_rpc_visible(oid, 0);
  289. for (const int &P : multiplayer->get_connected_peers()) {
  290. if (p_to < 0 && P == -p_to) {
  291. continue; // Excluded peer.
  292. }
  293. if (restricted && !multiplayer_replicator->is_rpc_visible(oid, P)) {
  294. continue; // Not visible to this peer.
  295. }
  296. targets.insert(P);
  297. bool has_peer = multiplayer_cache->send_object_cache(p_node, P, psc_id);
  298. has_all_peers = has_all_peers && has_peer;
  299. }
  300. }
  301. if (targets.is_empty()) {
  302. return; // No one in sight.
  303. }
  304. // Create base packet, lots of hardcode because it must be tight.
  305. int ofs = 0;
  306. #define MAKE_ROOM(m_amount) \
  307. if (packet_cache.size() < m_amount) \
  308. packet_cache.resize(m_amount);
  309. // Encode meta.
  310. uint8_t command_type = SceneMultiplayer::NETWORK_COMMAND_REMOTE_CALL;
  311. uint8_t node_id_compression = UINT8_MAX;
  312. uint8_t name_id_compression = UINT8_MAX;
  313. bool byte_only_or_no_args = false;
  314. MAKE_ROOM(1);
  315. // The meta is composed along the way, so just set 0 for now.
  316. packet_cache.write[0] = 0;
  317. ofs += 1;
  318. // Encode Node ID.
  319. if (has_all_peers) {
  320. // Compress the node ID only if all the target peers already know it.
  321. if (psc_id >= 0 && psc_id <= 255) {
  322. // We can encode the id in 1 byte
  323. node_id_compression = NETWORK_NODE_ID_COMPRESSION_8;
  324. MAKE_ROOM(ofs + 1);
  325. packet_cache.write[ofs] = static_cast<uint8_t>(psc_id);
  326. ofs += 1;
  327. } else if (psc_id >= 0 && psc_id <= 65535) {
  328. // We can encode the id in 2 bytes
  329. node_id_compression = NETWORK_NODE_ID_COMPRESSION_16;
  330. MAKE_ROOM(ofs + 2);
  331. encode_uint16(static_cast<uint16_t>(psc_id), &(packet_cache.write[ofs]));
  332. ofs += 2;
  333. } else {
  334. // Too big, let's use 4 bytes.
  335. node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;
  336. MAKE_ROOM(ofs + 4);
  337. encode_uint32(psc_id, &(packet_cache.write[ofs]));
  338. ofs += 4;
  339. }
  340. } else {
  341. // The targets don't know the node yet, so we need to use 32 bits int.
  342. node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;
  343. MAKE_ROOM(ofs + 4);
  344. encode_uint32(psc_id, &(packet_cache.write[ofs]));
  345. ofs += 4;
  346. }
  347. // Encode method ID
  348. if (p_rpc_id <= UINT8_MAX) {
  349. // The ID fits in 1 byte
  350. name_id_compression = NETWORK_NAME_ID_COMPRESSION_8;
  351. MAKE_ROOM(ofs + 1);
  352. packet_cache.write[ofs] = static_cast<uint8_t>(p_rpc_id);
  353. ofs += 1;
  354. } else {
  355. // The ID is larger, let's use 2 bytes
  356. name_id_compression = NETWORK_NAME_ID_COMPRESSION_16;
  357. MAKE_ROOM(ofs + 2);
  358. encode_uint16(p_rpc_id, &(packet_cache.write[ofs]));
  359. ofs += 2;
  360. }
  361. int len;
  362. Error err = MultiplayerAPI::encode_and_compress_variants(p_arg, p_argcount, nullptr, len, &byte_only_or_no_args, multiplayer->is_object_decoding_allowed());
  363. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC arguments. THIS IS LIKELY A BUG IN THE ENGINE!");
  364. if (byte_only_or_no_args) {
  365. MAKE_ROOM(ofs + len);
  366. } else {
  367. MAKE_ROOM(ofs + 1 + len);
  368. packet_cache.write[ofs] = p_argcount;
  369. ofs += 1;
  370. }
  371. if (len) {
  372. MultiplayerAPI::encode_and_compress_variants(p_arg, p_argcount, &packet_cache.write[ofs], len, &byte_only_or_no_args, multiplayer->is_object_decoding_allowed());
  373. ofs += len;
  374. }
  375. ERR_FAIL_COND(command_type > 7);
  376. ERR_FAIL_COND(node_id_compression > 3);
  377. ERR_FAIL_COND(name_id_compression > 1);
  378. #ifdef DEBUG_ENABLED
  379. _profile_node_data("rpc_out", p_node->get_instance_id(), ofs);
  380. #endif
  381. // We can now set the meta
  382. 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 ? BYTE_ONLY_OR_NO_ARGS_FLAG : 0);
  383. // Take chance and set transfer mode, since all send methods will use it.
  384. peer->set_transfer_channel(p_config.channel);
  385. peer->set_transfer_mode(p_config.transfer_mode);
  386. if (has_all_peers) {
  387. for (const int P : targets) {
  388. multiplayer->send_command(P, packet_cache.ptr(), ofs);
  389. }
  390. } else {
  391. // Unreachable because the node ID is never compressed if the peers doesn't know it.
  392. CRASH_COND(node_id_compression != NETWORK_NODE_ID_COMPRESSION_32);
  393. // Not all verified path, so send one by one.
  394. // Append path at the end, since we will need it for some packets.
  395. CharString pname = String(multiplayer->get_root_path().rel_path_to(p_node->get_path())).utf8();
  396. int path_len = encode_cstring(pname.get_data(), nullptr);
  397. MAKE_ROOM(ofs + path_len);
  398. encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));
  399. // Not all verified path, so check which needs the longer packet.
  400. for (const int P : targets) {
  401. bool confirmed = multiplayer_cache->is_cache_confirmed(p_node, P);
  402. if (confirmed) {
  403. // This one confirmed path, so use id.
  404. encode_uint32(psc_id, &(packet_cache.write[1]));
  405. multiplayer->send_command(P, packet_cache.ptr(), ofs);
  406. } else {
  407. // This one did not confirm path yet, so use entire path (sorry!).
  408. encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
  409. multiplayer->send_command(P, packet_cache.ptr(), ofs + path_len);
  410. }
  411. }
  412. }
  413. }
  414. Error SceneRPCInterface::rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  415. Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();
  416. ERR_FAIL_COND_V_MSG(!peer.is_valid(), ERR_UNCONFIGURED, "Trying to call an RPC while no multiplayer peer is active.");
  417. Node *node = Object::cast_to<Node>(p_obj);
  418. ERR_FAIL_COND_V_MSG(!node || !node->is_inside_tree(), ERR_INVALID_PARAMETER, "The object must be a valid Node inside the SceneTree");
  419. ERR_FAIL_COND_V_MSG(peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_CONNECTION_ERROR, "Trying to call an RPC via a multiplayer peer which is not connected.");
  420. int caller_id = multiplayer->get_unique_id();
  421. bool call_local_native = false;
  422. bool call_local_script = false;
  423. const RPCConfigCache &config_cache = _get_node_config(node);
  424. uint16_t rpc_id = config_cache.ids.has(p_method) ? config_cache.ids[p_method] : UINT16_MAX;
  425. ERR_FAIL_COND_V_MSG(rpc_id == UINT16_MAX, ERR_INVALID_PARAMETER,
  426. vformat("Unable to get the RPC configuration for the function \"%s\" at path: \"%s\". This happens when the method is missing or not marked for RPCs in the local script.", p_method, node->get_path()));
  427. const RPCConfig &config = config_cache.configs[rpc_id];
  428. ERR_FAIL_COND_V_MSG(p_peer_id == caller_id && !config.call_local, ERR_INVALID_PARAMETER, "RPC '" + p_method + "' on yourself is not allowed by selected mode.");
  429. if (p_peer_id == 0 || p_peer_id == caller_id || (p_peer_id < 0 && p_peer_id != -caller_id)) {
  430. if (rpc_id & (1 << 15)) {
  431. call_local_native = config.call_local;
  432. } else {
  433. call_local_script = config.call_local;
  434. }
  435. }
  436. if (p_peer_id != caller_id) {
  437. _send_rpc(node, p_peer_id, rpc_id, config, p_method, p_arg, p_argcount);
  438. }
  439. if (call_local_native) {
  440. Callable::CallError ce;
  441. multiplayer->set_remote_sender_override(multiplayer->get_unique_id());
  442. node->callp(p_method, p_arg, p_argcount, ce);
  443. multiplayer->set_remote_sender_override(0);
  444. if (ce.error != Callable::CallError::CALL_OK) {
  445. String error = Variant::get_call_error_text(node, p_method, p_arg, p_argcount, ce);
  446. error = "rpc() aborted in local call: - " + error + ".";
  447. ERR_PRINT(error);
  448. return FAILED;
  449. }
  450. }
  451. if (call_local_script) {
  452. Callable::CallError ce;
  453. ce.error = Callable::CallError::CALL_OK;
  454. multiplayer->set_remote_sender_override(multiplayer->get_unique_id());
  455. node->get_script_instance()->callp(p_method, p_arg, p_argcount, ce);
  456. multiplayer->set_remote_sender_override(0);
  457. if (ce.error != Callable::CallError::CALL_OK) {
  458. String error = Variant::get_call_error_text(node, p_method, p_arg, p_argcount, ce);
  459. error = "rpc() aborted in script local call: - " + error + ".";
  460. ERR_PRINT(error);
  461. return FAILED;
  462. }
  463. }
  464. return OK;
  465. }