multiplayer_api.cpp 40 KB

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