multiplayer_api.cpp 44 KB

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