multiplayer_api.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. /*************************************************************************/
  2. /* multiplayer_api.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "multiplayer_api.h"
  31. #include "core/io/marshalls.h"
  32. #include "scene/main/node.h"
  33. #ifdef DEBUG_ENABLED
  34. #include "core/os/os.h"
  35. #endif
  36. _FORCE_INLINE_ bool _should_call_local(MultiplayerAPI::RPCMode mode, bool is_master, bool &r_skip_rpc) {
  37. switch (mode) {
  38. case MultiplayerAPI::RPC_MODE_DISABLED: {
  39. // Do nothing.
  40. } break;
  41. case MultiplayerAPI::RPC_MODE_REMOTE: {
  42. // Do nothing also. Remote cannot produce a local call.
  43. } break;
  44. case MultiplayerAPI::RPC_MODE_MASTERSYNC: {
  45. if (is_master)
  46. r_skip_rpc = true; // I am the master, so skip remote call.
  47. FALLTHROUGH;
  48. }
  49. case MultiplayerAPI::RPC_MODE_REMOTESYNC:
  50. case MultiplayerAPI::RPC_MODE_PUPPETSYNC: {
  51. // Call it, sync always results in a local call.
  52. return true;
  53. } break;
  54. case MultiplayerAPI::RPC_MODE_MASTER: {
  55. if (is_master)
  56. r_skip_rpc = true; // I am the master, so skip remote call.
  57. return is_master;
  58. } break;
  59. case MultiplayerAPI::RPC_MODE_PUPPET: {
  60. return !is_master;
  61. } break;
  62. }
  63. return false;
  64. }
  65. _FORCE_INLINE_ bool _can_call_mode(Node *p_node, MultiplayerAPI::RPCMode mode, int p_remote_id) {
  66. switch (mode) {
  67. case MultiplayerAPI::RPC_MODE_DISABLED: {
  68. return false;
  69. } break;
  70. case MultiplayerAPI::RPC_MODE_REMOTE:
  71. case MultiplayerAPI::RPC_MODE_REMOTESYNC: {
  72. return true;
  73. } break;
  74. case MultiplayerAPI::RPC_MODE_MASTERSYNC:
  75. case MultiplayerAPI::RPC_MODE_MASTER: {
  76. return p_node->is_network_master();
  77. } break;
  78. case MultiplayerAPI::RPC_MODE_PUPPETSYNC:
  79. case MultiplayerAPI::RPC_MODE_PUPPET: {
  80. return !p_node->is_network_master() && p_remote_id == p_node->get_network_master();
  81. } break;
  82. }
  83. return false;
  84. }
  85. void MultiplayerAPI::poll() {
  86. if (!network_peer.is_valid() || network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED)
  87. return;
  88. network_peer->poll();
  89. if (!network_peer.is_valid()) // It's possible that polling might have resulted in a disconnection, so check here.
  90. return;
  91. while (network_peer->get_available_packet_count()) {
  92. int sender = network_peer->get_packet_peer();
  93. const uint8_t *packet;
  94. int len;
  95. Error err = network_peer->get_packet(&packet, len);
  96. if (err != OK) {
  97. ERR_PRINT("Error getting packet!");
  98. break; // Something is wrong!
  99. }
  100. rpc_sender_id = sender;
  101. _process_packet(sender, packet, len);
  102. rpc_sender_id = 0;
  103. if (!network_peer.is_valid()) {
  104. break; // It's also possible that a packet or RPC caused a disconnection, so also check here.
  105. }
  106. }
  107. }
  108. void MultiplayerAPI::clear() {
  109. connected_peers.clear();
  110. path_get_cache.clear();
  111. path_send_cache.clear();
  112. packet_cache.clear();
  113. last_send_cache_id = 1;
  114. }
  115. void MultiplayerAPI::set_root_node(Node *p_node) {
  116. root_node = p_node;
  117. }
  118. void MultiplayerAPI::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_peer) {
  119. if (p_peer == network_peer) return; // Nothing to do
  120. ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED,
  121. "Supplied NetworkedMultiplayerPeer must be connecting or connected.");
  122. if (network_peer.is_valid()) {
  123. network_peer->disconnect("peer_connected", this, "_add_peer");
  124. network_peer->disconnect("peer_disconnected", this, "_del_peer");
  125. network_peer->disconnect("connection_succeeded", this, "_connected_to_server");
  126. network_peer->disconnect("connection_failed", this, "_connection_failed");
  127. network_peer->disconnect("server_disconnected", this, "_server_disconnected");
  128. clear();
  129. }
  130. network_peer = p_peer;
  131. if (network_peer.is_valid()) {
  132. network_peer->connect("peer_connected", this, "_add_peer");
  133. network_peer->connect("peer_disconnected", this, "_del_peer");
  134. network_peer->connect("connection_succeeded", this, "_connected_to_server");
  135. network_peer->connect("connection_failed", this, "_connection_failed");
  136. network_peer->connect("server_disconnected", this, "_server_disconnected");
  137. }
  138. }
  139. Ref<NetworkedMultiplayerPeer> MultiplayerAPI::get_network_peer() const {
  140. return network_peer;
  141. }
  142. void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  143. ERR_FAIL_COND_MSG(root_node == NULL, "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.");
  144. ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
  145. #ifdef DEBUG_ENABLED
  146. if (profiling) {
  147. bandwidth_incoming_data.write[bandwidth_incoming_pointer].timestamp = OS::get_singleton()->get_ticks_msec();
  148. bandwidth_incoming_data.write[bandwidth_incoming_pointer].packet_size = p_packet_len;
  149. bandwidth_incoming_pointer = (bandwidth_incoming_pointer + 1) % bandwidth_incoming_data.size();
  150. }
  151. #endif
  152. uint8_t packet_type = p_packet[0];
  153. switch (packet_type) {
  154. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  155. _process_simplify_path(p_from, p_packet, p_packet_len);
  156. } break;
  157. case NETWORK_COMMAND_CONFIRM_PATH: {
  158. _process_confirm_path(p_from, p_packet, p_packet_len);
  159. } break;
  160. case NETWORK_COMMAND_REMOTE_CALL:
  161. case NETWORK_COMMAND_REMOTE_SET: {
  162. ERR_FAIL_COND_MSG(p_packet_len < 6, "Invalid packet received. Size too small.");
  163. Node *node = _process_get_node(p_from, p_packet, p_packet_len);
  164. ERR_FAIL_COND_MSG(node == NULL, "Invalid packet received. Requested node was not found.");
  165. // Detect cstring end.
  166. int len_end = 5;
  167. for (; len_end < p_packet_len; len_end++) {
  168. if (p_packet[len_end] == 0) {
  169. break;
  170. }
  171. }
  172. ERR_FAIL_COND_MSG(len_end >= p_packet_len, "Invalid packet received. Size too small.");
  173. StringName name = String::utf8((const char *)&p_packet[5]);
  174. if (packet_type == NETWORK_COMMAND_REMOTE_CALL) {
  175. _process_rpc(node, name, p_from, p_packet, p_packet_len, len_end + 1);
  176. } else {
  177. _process_rset(node, name, p_from, p_packet, p_packet_len, len_end + 1);
  178. }
  179. } break;
  180. case NETWORK_COMMAND_RAW: {
  181. _process_raw(p_from, p_packet, p_packet_len);
  182. } break;
  183. }
  184. }
  185. Node *MultiplayerAPI::_process_get_node(int p_from, const uint8_t *p_packet, int p_packet_len) {
  186. uint32_t target = decode_uint32(&p_packet[1]);
  187. Node *node = NULL;
  188. if (target & 0x80000000) {
  189. // Use full path (not cached yet).
  190. int ofs = target & 0x7FFFFFFF;
  191. ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, NULL, "Invalid packet received. Size smaller than declared.");
  192. String paths;
  193. paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
  194. NodePath np = paths;
  195. node = root_node->get_node(np);
  196. if (!node)
  197. ERR_PRINTS("Failed to get path from RPC: " + String(np) + ".");
  198. } else {
  199. // Use cached path.
  200. int id = target;
  201. Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
  202. ERR_FAIL_COND_V_MSG(!E, NULL, "Invalid packet received. Requests invalid peer cache.");
  203. Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(id);
  204. ERR_FAIL_COND_V_MSG(!F, NULL, "Invalid packet received. Unabled to find requested cached node.");
  205. PathGetCache::NodeInfo *ni = &F->get();
  206. // Do proper caching later.
  207. node = root_node->get_node(ni->path);
  208. if (!node)
  209. ERR_PRINTS("Failed to get cached path from RPC: " + String(ni->path) + ".");
  210. }
  211. return node;
  212. }
  213. void MultiplayerAPI::_process_rpc(Node *p_node, const StringName &p_name, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  214. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  215. // Check that remote can call the RPC on this node.
  216. RPCMode rpc_mode = RPC_MODE_DISABLED;
  217. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rpc_mode(p_name);
  218. if (E) {
  219. rpc_mode = E->get();
  220. } else if (p_node->get_script_instance()) {
  221. rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_name);
  222. }
  223. bool can_call = _can_call_mode(p_node, rpc_mode, p_from);
  224. ERR_FAIL_COND_MSG(!can_call, "RPC '" + String(p_name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rpc_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  225. int argc = p_packet[p_offset];
  226. Vector<Variant> args;
  227. Vector<const Variant *> argp;
  228. args.resize(argc);
  229. argp.resize(argc);
  230. p_offset++;
  231. #ifdef DEBUG_ENABLED
  232. if (profiling) {
  233. ObjectID id = p_node->get_instance_id();
  234. _init_node_profile(id);
  235. profiler_frame_data[id].incoming_rpc += 1;
  236. }
  237. #endif
  238. for (int i = 0; i < argc; i++) {
  239. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  240. int vlen;
  241. Error err = decode_variant(args.write[i], &p_packet[p_offset], p_packet_len - p_offset, &vlen, allow_object_decoding || network_peer->is_object_decoding_allowed());
  242. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RPC argument.");
  243. argp.write[i] = &args[i];
  244. p_offset += vlen;
  245. }
  246. Variant::CallError ce;
  247. p_node->call(p_name, (const Variant **)argp.ptr(), argc, ce);
  248. if (ce.error != Variant::CallError::CALL_OK) {
  249. String error = Variant::get_call_error_text(p_node, p_name, (const Variant **)argp.ptr(), argc, ce);
  250. error = "RPC - " + error;
  251. ERR_PRINTS(error);
  252. }
  253. }
  254. void MultiplayerAPI::_process_rset(Node *p_node, const StringName &p_name, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  255. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  256. // Check that remote can call the RSET on this node.
  257. RPCMode rset_mode = RPC_MODE_DISABLED;
  258. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rset_mode(p_name);
  259. if (E) {
  260. rset_mode = E->get();
  261. } else if (p_node->get_script_instance()) {
  262. rset_mode = p_node->get_script_instance()->get_rset_mode(p_name);
  263. }
  264. bool can_call = _can_call_mode(p_node, rset_mode, p_from);
  265. ERR_FAIL_COND_MSG(!can_call, "RSET '" + String(p_name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rset_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  266. #ifdef DEBUG_ENABLED
  267. if (profiling) {
  268. ObjectID id = p_node->get_instance_id();
  269. _init_node_profile(id);
  270. profiler_frame_data[id].incoming_rset += 1;
  271. }
  272. #endif
  273. Variant value;
  274. Error err = decode_variant(value, &p_packet[p_offset], p_packet_len - p_offset, NULL, allow_object_decoding || network_peer->is_object_decoding_allowed());
  275. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RSET value.");
  276. bool valid;
  277. p_node->set(p_name, value, &valid);
  278. if (!valid) {
  279. String error = "Error setting remote property '" + String(p_name) + "', not found in object of type " + p_node->get_class() + ".";
  280. ERR_PRINTS(error);
  281. }
  282. }
  283. void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  284. ERR_FAIL_COND_MSG(p_packet_len < 5, "Invalid packet received. Size too small.");
  285. int id = decode_uint32(&p_packet[1]);
  286. String paths;
  287. paths.parse_utf8((const char *)&p_packet[5], p_packet_len - 5);
  288. NodePath path = paths;
  289. if (!path_get_cache.has(p_from)) {
  290. path_get_cache[p_from] = PathGetCache();
  291. }
  292. PathGetCache::NodeInfo ni;
  293. ni.path = path;
  294. ni.instance = 0;
  295. path_get_cache[p_from].nodes[id] = ni;
  296. // Encode path to send ack.
  297. CharString pname = String(path).utf8();
  298. int len = encode_cstring(pname.get_data(), NULL);
  299. Vector<uint8_t> packet;
  300. packet.resize(1 + len);
  301. packet.write[0] = NETWORK_COMMAND_CONFIRM_PATH;
  302. encode_cstring(pname.get_data(), &packet.write[1]);
  303. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  304. network_peer->set_target_peer(p_from);
  305. network_peer->put_packet(packet.ptr(), packet.size());
  306. }
  307. void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  308. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  309. String paths;
  310. paths.parse_utf8((const char *)&p_packet[1], p_packet_len - 1);
  311. NodePath path = paths;
  312. PathSentCache *psc = path_send_cache.getptr(path);
  313. ERR_FAIL_COND_MSG(!psc, "Invalid packet received. Tries to confirm a path which was not found in cache.");
  314. Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
  315. ERR_FAIL_COND_MSG(!E, "Invalid packet received. Source peer was not found in cache for the given path.");
  316. E->get() = true;
  317. }
  318. bool MultiplayerAPI::_send_confirm_path(NodePath p_path, PathSentCache *psc, int p_target) {
  319. bool has_all_peers = true;
  320. List<int> peers_to_add; // If one is missing, take note to add it.
  321. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  322. if (p_target < 0 && E->get() == -p_target)
  323. continue; // Continue, excluded.
  324. if (p_target > 0 && E->get() != p_target)
  325. continue; // Continue, not for this peer.
  326. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  327. if (!F || !F->get()) {
  328. // Path was not cached, or was cached but is unconfirmed.
  329. if (!F) {
  330. // Not cached at all, take note.
  331. peers_to_add.push_back(E->get());
  332. }
  333. has_all_peers = false;
  334. }
  335. }
  336. // Those that need to be added, send a message for this.
  337. for (List<int>::Element *E = peers_to_add.front(); E; E = E->next()) {
  338. // Encode function name.
  339. CharString pname = String(p_path).utf8();
  340. int len = encode_cstring(pname.get_data(), NULL);
  341. Vector<uint8_t> packet;
  342. packet.resize(1 + 4 + len);
  343. packet.write[0] = NETWORK_COMMAND_SIMPLIFY_PATH;
  344. encode_uint32(psc->id, &packet.write[1]);
  345. encode_cstring(pname.get_data(), &packet.write[5]);
  346. network_peer->set_target_peer(E->get()); // To all of you.
  347. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  348. network_peer->put_packet(packet.ptr(), packet.size());
  349. psc->confirmed_peers.insert(E->get(), false); // Insert into confirmed, but as false since it was not confirmed.
  350. }
  351. return has_all_peers;
  352. }
  353. void MultiplayerAPI::_send_rpc(Node *p_from, int p_to, bool p_unreliable, bool p_set, const StringName &p_name, const Variant **p_arg, int p_argcount) {
  354. ERR_FAIL_COND_MSG(network_peer.is_null(), "Attempt to remote call/set when networking is not active in SceneTree.");
  355. ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_CONNECTING, "Attempt to remote call/set when networking is not connected yet in SceneTree.");
  356. ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to remote call/set when networking is disconnected.");
  357. ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments >255.");
  358. if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
  359. 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()) + ".");
  360. ERR_FAIL_MSG("Attempt to remote call unexisting ID: " + itos(p_to) + ".");
  361. }
  362. NodePath from_path = (root_node->get_path()).rel_path_to(p_from->get_path());
  363. ERR_FAIL_COND_MSG(from_path.is_empty(), "Unable to send RPC. Relative path is empty. THIS IS LIKELY A BUG IN THE ENGINE!");
  364. // See if the path is cached.
  365. PathSentCache *psc = path_send_cache.getptr(from_path);
  366. if (!psc) {
  367. // Path is not cached, create.
  368. path_send_cache[from_path] = PathSentCache();
  369. psc = path_send_cache.getptr(from_path);
  370. psc->id = last_send_cache_id++;
  371. }
  372. // Create base packet, lots of hardcode because it must be tight.
  373. int ofs = 0;
  374. #define MAKE_ROOM(m_amount) \
  375. if (packet_cache.size() < m_amount) packet_cache.resize(m_amount);
  376. // Encode type.
  377. MAKE_ROOM(1);
  378. packet_cache.write[0] = p_set ? NETWORK_COMMAND_REMOTE_SET : NETWORK_COMMAND_REMOTE_CALL;
  379. ofs += 1;
  380. // Encode ID.
  381. MAKE_ROOM(ofs + 4);
  382. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  383. ofs += 4;
  384. // Encode function name.
  385. CharString name = String(p_name).utf8();
  386. int len = encode_cstring(name.get_data(), NULL);
  387. MAKE_ROOM(ofs + len);
  388. encode_cstring(name.get_data(), &(packet_cache.write[ofs]));
  389. ofs += len;
  390. if (p_set) {
  391. // Set argument.
  392. Error err = encode_variant(*p_arg[0], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  393. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RSET value. THIS IS LIKELY A BUG IN THE ENGINE!");
  394. MAKE_ROOM(ofs + len);
  395. encode_variant(*p_arg[0], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  396. ofs += len;
  397. } else {
  398. // Call arguments.
  399. MAKE_ROOM(ofs + 1);
  400. packet_cache.write[ofs] = p_argcount;
  401. ofs += 1;
  402. for (int i = 0; i < p_argcount; i++) {
  403. Error err = encode_variant(*p_arg[i], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  404. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC argument. THIS IS LIKELY A BUG IN THE ENGINE!");
  405. MAKE_ROOM(ofs + len);
  406. encode_variant(*p_arg[i], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  407. ofs += len;
  408. }
  409. }
  410. #ifdef DEBUG_ENABLED
  411. if (profiling) {
  412. bandwidth_outgoing_data.write[bandwidth_outgoing_pointer].timestamp = OS::get_singleton()->get_ticks_msec();
  413. bandwidth_outgoing_data.write[bandwidth_outgoing_pointer].packet_size = ofs;
  414. bandwidth_outgoing_pointer = (bandwidth_outgoing_pointer + 1) % bandwidth_outgoing_data.size();
  415. }
  416. #endif
  417. // See if all peers have cached path (is so, call can be fast).
  418. bool has_all_peers = _send_confirm_path(from_path, psc, p_to);
  419. // Take chance and set transfer mode, since all send methods will use it.
  420. network_peer->set_transfer_mode(p_unreliable ? NetworkedMultiplayerPeer::TRANSFER_MODE_UNRELIABLE : NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  421. if (has_all_peers) {
  422. // They all have verified paths, so send fast.
  423. network_peer->set_target_peer(p_to); // To all of you.
  424. network_peer->put_packet(packet_cache.ptr(), ofs); // A message with love.
  425. } else {
  426. // Not all verified path, so send one by one.
  427. // Append path at the end, since we will need it for some packets.
  428. CharString pname = String(from_path).utf8();
  429. int path_len = encode_cstring(pname.get_data(), NULL);
  430. MAKE_ROOM(ofs + path_len);
  431. encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));
  432. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  433. if (p_to < 0 && E->get() == -p_to)
  434. continue; // Continue, excluded.
  435. if (p_to > 0 && E->get() != p_to)
  436. continue; // Continue, not for this peer.
  437. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  438. ERR_CONTINUE(!F); // Should never happen.
  439. network_peer->set_target_peer(E->get()); // To this one specifically.
  440. if (F->get()) {
  441. // This one confirmed path, so use id.
  442. encode_uint32(psc->id, &(packet_cache.write[1]));
  443. network_peer->put_packet(packet_cache.ptr(), ofs);
  444. } else {
  445. // This one did not confirm path yet, so use entire path (sorry!).
  446. encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
  447. network_peer->put_packet(packet_cache.ptr(), ofs + path_len);
  448. }
  449. }
  450. }
  451. }
  452. void MultiplayerAPI::_add_peer(int p_id) {
  453. connected_peers.insert(p_id);
  454. path_get_cache.insert(p_id, PathGetCache());
  455. emit_signal("network_peer_connected", p_id);
  456. }
  457. void MultiplayerAPI::_del_peer(int p_id) {
  458. connected_peers.erase(p_id);
  459. // Cleanup get cache.
  460. path_get_cache.erase(p_id);
  461. // Cleanup sent cache.
  462. // Some refactoring is needed to make this faster and do paths GC.
  463. List<NodePath> keys;
  464. path_send_cache.get_key_list(&keys);
  465. for (List<NodePath>::Element *E = keys.front(); E; E = E->next()) {
  466. PathSentCache *psc = path_send_cache.getptr(E->get());
  467. psc->confirmed_peers.erase(p_id);
  468. }
  469. emit_signal("network_peer_disconnected", p_id);
  470. }
  471. void MultiplayerAPI::_connected_to_server() {
  472. emit_signal("connected_to_server");
  473. }
  474. void MultiplayerAPI::_connection_failed() {
  475. emit_signal("connection_failed");
  476. }
  477. void MultiplayerAPI::_server_disconnected() {
  478. emit_signal("server_disconnected");
  479. }
  480. void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  481. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to call an RPC while no network peer is active.");
  482. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to call an RPC on a node which is not inside SceneTree.");
  483. ERR_FAIL_COND_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, "Trying to call an RPC via a network peer which is not connected.");
  484. int node_id = network_peer->get_unique_id();
  485. bool skip_rpc = node_id == p_peer_id;
  486. bool call_local_native = false;
  487. bool call_local_script = false;
  488. bool is_master = p_node->is_network_master();
  489. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  490. // Check that send mode can use local call.
  491. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rpc_mode(p_method);
  492. if (E) {
  493. call_local_native = _should_call_local(E->get(), is_master, skip_rpc);
  494. }
  495. if (call_local_native) {
  496. // Done below.
  497. } else if (p_node->get_script_instance()) {
  498. // Attempt with script.
  499. RPCMode rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_method);
  500. call_local_script = _should_call_local(rpc_mode, is_master, skip_rpc);
  501. }
  502. }
  503. if (!skip_rpc) {
  504. #ifdef DEBUG_ENABLED
  505. if (profiling) {
  506. ObjectID id = p_node->get_instance_id();
  507. _init_node_profile(id);
  508. profiler_frame_data[id].outgoing_rpc += 1;
  509. }
  510. #endif
  511. _send_rpc(p_node, p_peer_id, p_unreliable, false, p_method, p_arg, p_argcount);
  512. }
  513. if (call_local_native) {
  514. int temp_id = rpc_sender_id;
  515. rpc_sender_id = get_network_unique_id();
  516. Variant::CallError ce;
  517. p_node->call(p_method, p_arg, p_argcount, ce);
  518. rpc_sender_id = temp_id;
  519. if (ce.error != Variant::CallError::CALL_OK) {
  520. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  521. error = "rpc() aborted in local call: - " + error + ".";
  522. ERR_PRINTS(error);
  523. return;
  524. }
  525. }
  526. if (call_local_script) {
  527. int temp_id = rpc_sender_id;
  528. rpc_sender_id = get_network_unique_id();
  529. Variant::CallError ce;
  530. ce.error = Variant::CallError::CALL_OK;
  531. p_node->get_script_instance()->call(p_method, p_arg, p_argcount, ce);
  532. rpc_sender_id = temp_id;
  533. if (ce.error != Variant::CallError::CALL_OK) {
  534. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  535. error = "rpc() aborted in script local call: - " + error + ".";
  536. ERR_PRINTS(error);
  537. return;
  538. }
  539. }
  540. ERR_FAIL_COND_MSG(skip_rpc && !(call_local_native || call_local_script), "RPC '" + p_method + "' on yourself is not allowed by selected mode.");
  541. }
  542. void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_property, const Variant &p_value) {
  543. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to RSET while no network peer is active.");
  544. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to RSET on a node which is not inside SceneTree.");
  545. ERR_FAIL_COND_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, "Trying to send an RSET via a network peer which is not connected.");
  546. int node_id = network_peer->get_unique_id();
  547. bool is_master = p_node->is_network_master();
  548. bool skip_rset = node_id == p_peer_id;
  549. bool set_local = false;
  550. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  551. // Check that send mode can use local call.
  552. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rset_mode(p_property);
  553. if (E) {
  554. set_local = _should_call_local(E->get(), is_master, skip_rset);
  555. }
  556. if (set_local) {
  557. bool valid;
  558. int temp_id = rpc_sender_id;
  559. rpc_sender_id = get_network_unique_id();
  560. p_node->set(p_property, p_value, &valid);
  561. rpc_sender_id = temp_id;
  562. if (!valid) {
  563. String error = "rset() aborted in local set, property not found: - " + String(p_property) + ".";
  564. ERR_PRINTS(error);
  565. return;
  566. }
  567. } else if (p_node->get_script_instance()) {
  568. // Attempt with script.
  569. RPCMode rpc_mode = p_node->get_script_instance()->get_rset_mode(p_property);
  570. set_local = _should_call_local(rpc_mode, is_master, skip_rset);
  571. if (set_local) {
  572. int temp_id = rpc_sender_id;
  573. rpc_sender_id = get_network_unique_id();
  574. bool valid = p_node->get_script_instance()->set(p_property, p_value);
  575. rpc_sender_id = temp_id;
  576. if (!valid) {
  577. String error = "rset() aborted in local script set, property not found: - " + String(p_property) + ".";
  578. ERR_PRINTS(error);
  579. return;
  580. }
  581. }
  582. }
  583. }
  584. if (skip_rset) {
  585. ERR_FAIL_COND_MSG(!set_local, "RSET for '" + p_property + "' on yourself is not allowed by selected mode.");
  586. return;
  587. }
  588. #ifdef DEBUG_ENABLED
  589. if (profiling) {
  590. ObjectID id = p_node->get_instance_id();
  591. _init_node_profile(id);
  592. profiler_frame_data[id].outgoing_rset += 1;
  593. }
  594. #endif
  595. const Variant *vptr = &p_value;
  596. _send_rpc(p_node, p_peer_id, p_unreliable, true, p_property, &vptr, 1);
  597. }
  598. Error MultiplayerAPI::send_bytes(PoolVector<uint8_t> p_data, int p_to, NetworkedMultiplayerPeer::TransferMode p_mode) {
  599. ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet.");
  600. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no network peer is active.");
  601. ERR_FAIL_COND_V_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a network peer which is not connected.");
  602. MAKE_ROOM(p_data.size() + 1);
  603. PoolVector<uint8_t>::Read r = p_data.read();
  604. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  605. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  606. network_peer->set_target_peer(p_to);
  607. network_peer->set_transfer_mode(p_mode);
  608. return network_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
  609. }
  610. void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  611. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  612. PoolVector<uint8_t> out;
  613. int len = p_packet_len - 1;
  614. out.resize(len);
  615. {
  616. PoolVector<uint8_t>::Write w = out.write();
  617. memcpy(&w[0], &p_packet[1], len);
  618. }
  619. emit_signal("network_peer_packet", p_from, out);
  620. }
  621. int MultiplayerAPI::get_network_unique_id() const {
  622. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), 0, "No network peer is assigned. Unable to get unique network ID.");
  623. return network_peer->get_unique_id();
  624. }
  625. bool MultiplayerAPI::is_network_server() const {
  626. // XXX Maybe fail silently? Maybe should actually return true to make development of both local and online multiplayer easier?
  627. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. I can't be a server.");
  628. return network_peer->is_server();
  629. }
  630. void MultiplayerAPI::set_refuse_new_network_connections(bool p_refuse) {
  631. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "No network peer is assigned. Unable to set 'refuse_new_connections'.");
  632. network_peer->set_refuse_new_connections(p_refuse);
  633. }
  634. bool MultiplayerAPI::is_refusing_new_network_connections() const {
  635. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. Unable to get 'refuse_new_connections'.");
  636. return network_peer->is_refusing_new_connections();
  637. }
  638. Vector<int> MultiplayerAPI::get_network_connected_peers() const {
  639. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), Vector<int>(), "No network peer is assigned. Assume no peers are connected.");
  640. Vector<int> ret;
  641. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  642. ret.push_back(E->get());
  643. }
  644. return ret;
  645. }
  646. void MultiplayerAPI::set_allow_object_decoding(bool p_enable) {
  647. allow_object_decoding = p_enable;
  648. }
  649. bool MultiplayerAPI::is_object_decoding_allowed() const {
  650. return allow_object_decoding;
  651. }
  652. void MultiplayerAPI::profiling_start() {
  653. #ifdef DEBUG_ENABLED
  654. profiling = true;
  655. profiler_frame_data.clear();
  656. bandwidth_incoming_pointer = 0;
  657. bandwidth_incoming_data.resize(16384); // ~128kB
  658. for (int i = 0; i < bandwidth_incoming_data.size(); ++i) {
  659. bandwidth_incoming_data.write[i].packet_size = -1;
  660. }
  661. bandwidth_outgoing_pointer = 0;
  662. bandwidth_outgoing_data.resize(16384); // ~128kB
  663. for (int i = 0; i < bandwidth_outgoing_data.size(); ++i) {
  664. bandwidth_outgoing_data.write[i].packet_size = -1;
  665. }
  666. #endif
  667. }
  668. void MultiplayerAPI::profiling_end() {
  669. #ifdef DEBUG_ENABLED
  670. profiling = false;
  671. bandwidth_incoming_data.clear();
  672. bandwidth_outgoing_data.clear();
  673. #endif
  674. }
  675. int MultiplayerAPI::get_profiling_frame(ProfilingInfo *r_info) {
  676. int i = 0;
  677. #ifdef DEBUG_ENABLED
  678. for (Map<ObjectID, ProfilingInfo>::Element *E = profiler_frame_data.front(); E; E = E->next()) {
  679. r_info[i] = E->get();
  680. ++i;
  681. }
  682. profiler_frame_data.clear();
  683. #endif
  684. return i;
  685. }
  686. int MultiplayerAPI::get_incoming_bandwidth_usage() {
  687. #ifdef DEBUG_ENABLED
  688. return _get_bandwidth_usage(bandwidth_incoming_data, bandwidth_incoming_pointer);
  689. #else
  690. return 0;
  691. #endif
  692. }
  693. int MultiplayerAPI::get_outgoing_bandwidth_usage() {
  694. #ifdef DEBUG_ENABLED
  695. return _get_bandwidth_usage(bandwidth_outgoing_data, bandwidth_outgoing_pointer);
  696. #else
  697. return 0;
  698. #endif
  699. }
  700. #ifdef DEBUG_ENABLED
  701. int MultiplayerAPI::_get_bandwidth_usage(const Vector<BandwidthFrame> &p_buffer, int p_pointer) {
  702. int total_bandwidth = 0;
  703. uint32_t timestamp = OS::get_singleton()->get_ticks_msec();
  704. uint32_t final_timestamp = timestamp - 1000;
  705. int i = (p_pointer + p_buffer.size() - 1) % p_buffer.size();
  706. while (i != p_pointer && p_buffer[i].packet_size > 0) {
  707. if (p_buffer[i].timestamp < final_timestamp) {
  708. return total_bandwidth;
  709. }
  710. total_bandwidth += p_buffer[i].packet_size;
  711. i = (i + p_buffer.size() - 1) % p_buffer.size();
  712. }
  713. ERR_FAIL_COND_V_MSG(i == p_pointer, total_bandwidth, "Reached the end of the bandwidth profiler buffer, values might be inaccurate.");
  714. return total_bandwidth;
  715. }
  716. void MultiplayerAPI::_init_node_profile(ObjectID p_node) {
  717. if (profiler_frame_data.has(p_node))
  718. return;
  719. profiler_frame_data.insert(p_node, ProfilingInfo());
  720. profiler_frame_data[p_node].node = p_node;
  721. profiler_frame_data[p_node].node_path = Object::cast_to<Node>(ObjectDB::get_instance(p_node))->get_path();
  722. profiler_frame_data[p_node].incoming_rpc = 0;
  723. profiler_frame_data[p_node].incoming_rset = 0;
  724. profiler_frame_data[p_node].outgoing_rpc = 0;
  725. profiler_frame_data[p_node].outgoing_rset = 0;
  726. }
  727. #endif
  728. void MultiplayerAPI::_bind_methods() {
  729. ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node);
  730. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode"), &MultiplayerAPI::send_bytes, DEFVAL(NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE));
  731. ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer);
  732. ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer);
  733. ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id);
  734. ClassDB::bind_method(D_METHOD("is_network_server"), &MultiplayerAPI::is_network_server);
  735. ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &MultiplayerAPI::get_rpc_sender_id);
  736. ClassDB::bind_method(D_METHOD("_add_peer", "id"), &MultiplayerAPI::_add_peer);
  737. ClassDB::bind_method(D_METHOD("_del_peer", "id"), &MultiplayerAPI::_del_peer);
  738. ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &MultiplayerAPI::set_network_peer);
  739. ClassDB::bind_method(D_METHOD("poll"), &MultiplayerAPI::poll);
  740. ClassDB::bind_method(D_METHOD("clear"), &MultiplayerAPI::clear);
  741. ClassDB::bind_method(D_METHOD("_connected_to_server"), &MultiplayerAPI::_connected_to_server);
  742. ClassDB::bind_method(D_METHOD("_connection_failed"), &MultiplayerAPI::_connection_failed);
  743. ClassDB::bind_method(D_METHOD("_server_disconnected"), &MultiplayerAPI::_server_disconnected);
  744. ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &MultiplayerAPI::get_network_connected_peers);
  745. ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &MultiplayerAPI::set_refuse_new_network_connections);
  746. ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &MultiplayerAPI::is_refusing_new_network_connections);
  747. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &MultiplayerAPI::set_allow_object_decoding);
  748. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &MultiplayerAPI::is_object_decoding_allowed);
  749. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  750. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections");
  751. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "NetworkedMultiplayerPeer", 0), "set_network_peer", "get_network_peer");
  752. ADD_PROPERTY_DEFAULT("refuse_new_network_connections", false);
  753. ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
  754. ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
  755. ADD_SIGNAL(MethodInfo("network_peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::POOL_BYTE_ARRAY, "packet")));
  756. ADD_SIGNAL(MethodInfo("connected_to_server"));
  757. ADD_SIGNAL(MethodInfo("connection_failed"));
  758. ADD_SIGNAL(MethodInfo("server_disconnected"));
  759. BIND_ENUM_CONSTANT(RPC_MODE_DISABLED);
  760. BIND_ENUM_CONSTANT(RPC_MODE_REMOTE);
  761. BIND_ENUM_CONSTANT(RPC_MODE_MASTER);
  762. BIND_ENUM_CONSTANT(RPC_MODE_PUPPET);
  763. BIND_ENUM_CONSTANT(RPC_MODE_SLAVE); // Deprecated.
  764. BIND_ENUM_CONSTANT(RPC_MODE_REMOTESYNC);
  765. BIND_ENUM_CONSTANT(RPC_MODE_SYNC); // Deprecated.
  766. BIND_ENUM_CONSTANT(RPC_MODE_MASTERSYNC);
  767. BIND_ENUM_CONSTANT(RPC_MODE_PUPPETSYNC);
  768. }
  769. MultiplayerAPI::MultiplayerAPI() :
  770. allow_object_decoding(false) {
  771. rpc_sender_id = 0;
  772. root_node = NULL;
  773. #ifdef DEBUG_ENABLED
  774. profiling = false;
  775. #endif
  776. clear();
  777. }
  778. MultiplayerAPI::~MultiplayerAPI() {
  779. clear();
  780. }