multiplayer_api.cpp 36 KB

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