multiplayer_api.cpp 40 KB

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