multiplayer_api.cpp 35 KB

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