multiplayer_api.cpp 35 KB

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