multiplayer_api.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. /*************************************************************************/
  2. /* multiplayer_api.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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. _FORCE_INLINE_ bool _should_call_local(MultiplayerAPI::RPCMode mode, bool is_master, bool &r_skip_rpc) {
  34. switch (mode) {
  35. case MultiplayerAPI::RPC_MODE_DISABLED: {
  36. // Do nothing.
  37. } break;
  38. case MultiplayerAPI::RPC_MODE_REMOTE: {
  39. // Do nothing also. Remote cannot produce a local call.
  40. } break;
  41. case MultiplayerAPI::RPC_MODE_MASTERSYNC: {
  42. if (is_master)
  43. r_skip_rpc = true; // I am the master, so skip remote call.
  44. FALLTHROUGH;
  45. }
  46. case MultiplayerAPI::RPC_MODE_REMOTESYNC:
  47. case MultiplayerAPI::RPC_MODE_PUPPETSYNC: {
  48. // Call it, sync always results in a local call.
  49. return true;
  50. } break;
  51. case MultiplayerAPI::RPC_MODE_MASTER: {
  52. if (is_master)
  53. r_skip_rpc = true; // I am the master, so skip remote call.
  54. return is_master;
  55. } break;
  56. case MultiplayerAPI::RPC_MODE_PUPPET: {
  57. return !is_master;
  58. } break;
  59. }
  60. return false;
  61. }
  62. _FORCE_INLINE_ bool _can_call_mode(Node *p_node, MultiplayerAPI::RPCMode mode, int p_remote_id) {
  63. switch (mode) {
  64. case MultiplayerAPI::RPC_MODE_DISABLED: {
  65. return false;
  66. } break;
  67. case MultiplayerAPI::RPC_MODE_REMOTE:
  68. case MultiplayerAPI::RPC_MODE_REMOTESYNC: {
  69. return true;
  70. } break;
  71. case MultiplayerAPI::RPC_MODE_MASTERSYNC:
  72. case MultiplayerAPI::RPC_MODE_MASTER: {
  73. return p_node->is_network_master();
  74. } break;
  75. case MultiplayerAPI::RPC_MODE_PUPPETSYNC:
  76. case MultiplayerAPI::RPC_MODE_PUPPET: {
  77. return !p_node->is_network_master() && p_remote_id == p_node->get_network_master();
  78. } break;
  79. }
  80. return false;
  81. }
  82. void MultiplayerAPI::poll() {
  83. if (!network_peer.is_valid() || network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED)
  84. return;
  85. network_peer->poll();
  86. if (!network_peer.is_valid()) // It's possible that polling might have resulted in a disconnection, so check here.
  87. return;
  88. while (network_peer->get_available_packet_count()) {
  89. int sender = network_peer->get_packet_peer();
  90. const uint8_t *packet;
  91. int len;
  92. Error err = network_peer->get_packet(&packet, len);
  93. if (err != OK) {
  94. ERR_PRINT("Error getting packet!");
  95. }
  96. rpc_sender_id = sender;
  97. _process_packet(sender, packet, len);
  98. rpc_sender_id = 0;
  99. if (!network_peer.is_valid()) {
  100. break; // It's also possible that a packet or RPC caused a disconnection, so also check here.
  101. }
  102. }
  103. }
  104. void MultiplayerAPI::clear() {
  105. connected_peers.clear();
  106. path_get_cache.clear();
  107. path_send_cache.clear();
  108. packet_cache.clear();
  109. last_send_cache_id = 1;
  110. }
  111. void MultiplayerAPI::set_root_node(Node *p_node) {
  112. root_node = p_node;
  113. }
  114. void MultiplayerAPI::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_peer) {
  115. if (p_peer == network_peer) return; // Nothing to do
  116. if (network_peer.is_valid()) {
  117. network_peer->disconnect("peer_connected", this, "_add_peer");
  118. network_peer->disconnect("peer_disconnected", this, "_del_peer");
  119. network_peer->disconnect("connection_succeeded", this, "_connected_to_server");
  120. network_peer->disconnect("connection_failed", this, "_connection_failed");
  121. network_peer->disconnect("server_disconnected", this, "_server_disconnected");
  122. clear();
  123. }
  124. network_peer = p_peer;
  125. ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, "Supplied NetworkedNetworkPeer must be connecting or connected.");
  126. if (network_peer.is_valid()) {
  127. network_peer->connect("peer_connected", this, "_add_peer");
  128. network_peer->connect("peer_disconnected", this, "_del_peer");
  129. network_peer->connect("connection_succeeded", this, "_connected_to_server");
  130. network_peer->connect("connection_failed", this, "_connection_failed");
  131. network_peer->connect("server_disconnected", this, "_server_disconnected");
  132. }
  133. }
  134. Ref<NetworkedMultiplayerPeer> MultiplayerAPI::get_network_peer() const {
  135. return network_peer;
  136. }
  137. void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  138. 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.");
  139. ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
  140. uint8_t packet_type = p_packet[0];
  141. switch (packet_type) {
  142. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  143. _process_simplify_path(p_from, p_packet, p_packet_len);
  144. } break;
  145. case NETWORK_COMMAND_CONFIRM_PATH: {
  146. _process_confirm_path(p_from, p_packet, p_packet_len);
  147. } break;
  148. case NETWORK_COMMAND_REMOTE_CALL:
  149. case NETWORK_COMMAND_REMOTE_SET: {
  150. ERR_FAIL_COND_MSG(p_packet_len < 6, "Invalid packet received. Size too small.");
  151. Node *node = _process_get_node(p_from, p_packet, p_packet_len);
  152. ERR_FAIL_COND_MSG(node == NULL, "Invalid packet received. Requested node was not found.");
  153. // Detect cstring end.
  154. int len_end = 5;
  155. for (; len_end < p_packet_len; len_end++) {
  156. if (p_packet[len_end] == 0) {
  157. break;
  158. }
  159. }
  160. ERR_FAIL_COND_MSG(len_end >= p_packet_len, "Invalid packet received. Size too small.");
  161. StringName name = String::utf8((const char *)&p_packet[5]);
  162. if (packet_type == NETWORK_COMMAND_REMOTE_CALL) {
  163. _process_rpc(node, name, p_from, p_packet, p_packet_len, len_end + 1);
  164. } else {
  165. _process_rset(node, name, p_from, p_packet, p_packet_len, len_end + 1);
  166. }
  167. } break;
  168. case NETWORK_COMMAND_RAW: {
  169. _process_raw(p_from, p_packet, p_packet_len);
  170. } break;
  171. }
  172. }
  173. Node *MultiplayerAPI::_process_get_node(int p_from, const uint8_t *p_packet, int p_packet_len) {
  174. uint32_t target = decode_uint32(&p_packet[1]);
  175. Node *node = NULL;
  176. if (target & 0x80000000) {
  177. // Use full path (not cached yet).
  178. int ofs = target & 0x7FFFFFFF;
  179. ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, NULL, "Invalid packet received. Size smaller than declared.");
  180. String paths;
  181. paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
  182. NodePath np = paths;
  183. node = root_node->get_node(np);
  184. if (!node)
  185. ERR_PRINTS("Failed to get path from RPC: " + String(np) + ".");
  186. } else {
  187. // Use cached path.
  188. int id = target;
  189. Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
  190. ERR_FAIL_COND_V_MSG(!E, NULL, "Invalid packet received. Requests invalid peer cache.");
  191. Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(id);
  192. ERR_FAIL_COND_V_MSG(!F, NULL, "Invalid packet received. Unabled to find requested cached node.");
  193. PathGetCache::NodeInfo *ni = &F->get();
  194. // Do proper caching later.
  195. node = root_node->get_node(ni->path);
  196. if (!node)
  197. ERR_PRINTS("Failed to get cached path from RPC: " + String(ni->path) + ".");
  198. }
  199. return node;
  200. }
  201. 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) {
  202. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  203. // Check that remote can call the RPC on this node.
  204. RPCMode rpc_mode = RPC_MODE_DISABLED;
  205. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rpc_mode(p_name);
  206. if (E) {
  207. rpc_mode = E->get();
  208. } else if (p_node->get_script_instance()) {
  209. rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_name);
  210. }
  211. bool can_call = _can_call_mode(p_node, rpc_mode, p_from);
  212. 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()) + ".");
  213. int argc = p_packet[p_offset];
  214. Vector<Variant> args;
  215. Vector<const Variant *> argp;
  216. args.resize(argc);
  217. argp.resize(argc);
  218. p_offset++;
  219. for (int i = 0; i < argc; i++) {
  220. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  221. int vlen;
  222. 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());
  223. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RPC argument.");
  224. argp.write[i] = &args[i];
  225. p_offset += vlen;
  226. }
  227. Variant::CallError ce;
  228. p_node->call(p_name, (const Variant **)argp.ptr(), argc, ce);
  229. if (ce.error != Variant::CallError::CALL_OK) {
  230. String error = Variant::get_call_error_text(p_node, p_name, (const Variant **)argp.ptr(), argc, ce);
  231. error = "RPC - " + error;
  232. ERR_PRINTS(error);
  233. }
  234. }
  235. 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) {
  236. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  237. // Check that remote can call the RSET on this node.
  238. RPCMode rset_mode = RPC_MODE_DISABLED;
  239. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rset_mode(p_name);
  240. if (E) {
  241. rset_mode = E->get();
  242. } else if (p_node->get_script_instance()) {
  243. rset_mode = p_node->get_script_instance()->get_rset_mode(p_name);
  244. }
  245. bool can_call = _can_call_mode(p_node, rset_mode, p_from);
  246. 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()) + ".");
  247. Variant value;
  248. Error err = decode_variant(value, &p_packet[p_offset], p_packet_len - p_offset, NULL, allow_object_decoding || network_peer->is_object_decoding_allowed());
  249. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RSET value.");
  250. bool valid;
  251. p_node->set(p_name, value, &valid);
  252. if (!valid) {
  253. String error = "Error setting remote property '" + String(p_name) + "', not found in object of type " + p_node->get_class() + ".";
  254. ERR_PRINTS(error);
  255. }
  256. }
  257. void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  258. ERR_FAIL_COND_MSG(p_packet_len < 5, "Invalid packet received. Size too small.");
  259. int id = decode_uint32(&p_packet[1]);
  260. String paths;
  261. paths.parse_utf8((const char *)&p_packet[5], p_packet_len - 5);
  262. NodePath path = paths;
  263. if (!path_get_cache.has(p_from)) {
  264. path_get_cache[p_from] = PathGetCache();
  265. }
  266. PathGetCache::NodeInfo ni;
  267. ni.path = path;
  268. ni.instance = 0;
  269. path_get_cache[p_from].nodes[id] = ni;
  270. // Encode path to send ack.
  271. CharString pname = String(path).utf8();
  272. int len = encode_cstring(pname.get_data(), NULL);
  273. Vector<uint8_t> packet;
  274. packet.resize(1 + len);
  275. packet.write[0] = NETWORK_COMMAND_CONFIRM_PATH;
  276. encode_cstring(pname.get_data(), &packet.write[1]);
  277. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  278. network_peer->set_target_peer(p_from);
  279. network_peer->put_packet(packet.ptr(), packet.size());
  280. }
  281. void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  282. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  283. String paths;
  284. paths.parse_utf8((const char *)&p_packet[1], p_packet_len - 1);
  285. NodePath path = paths;
  286. PathSentCache *psc = path_send_cache.getptr(path);
  287. ERR_FAIL_COND_MSG(!psc, "Invalid packet received. Tries to confirm a path which was not found in cache.");
  288. Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
  289. ERR_FAIL_COND_MSG(!E, "Invalid packet received. Source peer was not found in cache for the given path.");
  290. E->get() = true;
  291. }
  292. bool MultiplayerAPI::_send_confirm_path(NodePath p_path, PathSentCache *psc, int p_target) {
  293. bool has_all_peers = true;
  294. List<int> peers_to_add; // If one is missing, take note to add it.
  295. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  296. if (p_target < 0 && E->get() == -p_target)
  297. continue; // Continue, excluded.
  298. if (p_target > 0 && E->get() != p_target)
  299. continue; // Continue, not for this peer.
  300. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  301. if (!F || !F->get()) {
  302. // Path was not cached, or was cached but is unconfirmed.
  303. if (!F) {
  304. // Not cached at all, take note.
  305. peers_to_add.push_back(E->get());
  306. }
  307. has_all_peers = false;
  308. }
  309. }
  310. // Those that need to be added, send a message for this.
  311. for (List<int>::Element *E = peers_to_add.front(); E; E = E->next()) {
  312. // Encode function name.
  313. CharString pname = String(p_path).utf8();
  314. int len = encode_cstring(pname.get_data(), NULL);
  315. Vector<uint8_t> packet;
  316. packet.resize(1 + 4 + len);
  317. packet.write[0] = NETWORK_COMMAND_SIMPLIFY_PATH;
  318. encode_uint32(psc->id, &packet.write[1]);
  319. encode_cstring(pname.get_data(), &packet.write[5]);
  320. network_peer->set_target_peer(E->get()); // To all of you.
  321. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  322. network_peer->put_packet(packet.ptr(), packet.size());
  323. psc->confirmed_peers.insert(E->get(), false); // Insert into confirmed, but as false since it was not confirmed.
  324. }
  325. return has_all_peers;
  326. }
  327. 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) {
  328. ERR_FAIL_COND_MSG(network_peer.is_null(), "Attempt to remote call/set when networking is not active in SceneTree.");
  329. 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.");
  330. ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to remote call/set when networking is disconnected.");
  331. ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments >255.");
  332. if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
  333. 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()) + ".");
  334. ERR_FAIL_MSG("Attempt to remote call unexisting ID: " + itos(p_to) + ".");
  335. }
  336. NodePath from_path = (root_node->get_path()).rel_path_to(p_from->get_path());
  337. ERR_FAIL_COND_MSG(from_path.is_empty(), "Unable to send RPC. Relative path is empty. THIS IS LIKELY A BUG IN THE ENGINE!");
  338. // See if the path is cached.
  339. PathSentCache *psc = path_send_cache.getptr(from_path);
  340. if (!psc) {
  341. // Path is not cached, create.
  342. path_send_cache[from_path] = PathSentCache();
  343. psc = path_send_cache.getptr(from_path);
  344. psc->id = last_send_cache_id++;
  345. }
  346. // Create base packet, lots of hardcode because it must be tight.
  347. int ofs = 0;
  348. #define MAKE_ROOM(m_amount) \
  349. if (packet_cache.size() < m_amount) packet_cache.resize(m_amount);
  350. // Encode type.
  351. MAKE_ROOM(1);
  352. packet_cache.write[0] = p_set ? NETWORK_COMMAND_REMOTE_SET : NETWORK_COMMAND_REMOTE_CALL;
  353. ofs += 1;
  354. // Encode ID.
  355. MAKE_ROOM(ofs + 4);
  356. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  357. ofs += 4;
  358. // Encode function name.
  359. CharString name = String(p_name).utf8();
  360. int len = encode_cstring(name.get_data(), NULL);
  361. MAKE_ROOM(ofs + len);
  362. encode_cstring(name.get_data(), &(packet_cache.write[ofs]));
  363. ofs += len;
  364. if (p_set) {
  365. // Set argument.
  366. Error err = encode_variant(*p_arg[0], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  367. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RSET value. THIS IS LIKELY A BUG IN THE ENGINE!");
  368. MAKE_ROOM(ofs + len);
  369. encode_variant(*p_arg[0], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  370. ofs += len;
  371. } else {
  372. // Call arguments.
  373. MAKE_ROOM(ofs + 1);
  374. packet_cache.write[ofs] = p_argcount;
  375. ofs += 1;
  376. for (int i = 0; i < p_argcount; i++) {
  377. Error err = encode_variant(*p_arg[i], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  378. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC argument. THIS IS LIKELY A BUG IN THE ENGINE!");
  379. MAKE_ROOM(ofs + len);
  380. encode_variant(*p_arg[i], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  381. ofs += len;
  382. }
  383. }
  384. // See if all peers have cached path (is so, call can be fast).
  385. bool has_all_peers = _send_confirm_path(from_path, psc, p_to);
  386. // Take chance and set transfer mode, since all send methods will use it.
  387. network_peer->set_transfer_mode(p_unreliable ? NetworkedMultiplayerPeer::TRANSFER_MODE_UNRELIABLE : NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  388. if (has_all_peers) {
  389. // They all have verified paths, so send fast.
  390. network_peer->set_target_peer(p_to); // To all of you.
  391. network_peer->put_packet(packet_cache.ptr(), ofs); // A message with love.
  392. } else {
  393. // Not all verified path, so send one by one.
  394. // Append path at the end, since we will need it for some packets.
  395. CharString pname = String(from_path).utf8();
  396. int path_len = encode_cstring(pname.get_data(), NULL);
  397. MAKE_ROOM(ofs + path_len);
  398. encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));
  399. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  400. if (p_to < 0 && E->get() == -p_to)
  401. continue; // Continue, excluded.
  402. if (p_to > 0 && E->get() != p_to)
  403. continue; // Continue, not for this peer.
  404. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  405. ERR_CONTINUE(!F); // Should never happen.
  406. network_peer->set_target_peer(E->get()); // To this one specifically.
  407. if (F->get()) {
  408. // This one confirmed path, so use id.
  409. encode_uint32(psc->id, &(packet_cache.write[1]));
  410. network_peer->put_packet(packet_cache.ptr(), ofs);
  411. } else {
  412. // This one did not confirm path yet, so use entire path (sorry!).
  413. encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
  414. network_peer->put_packet(packet_cache.ptr(), ofs + path_len);
  415. }
  416. }
  417. }
  418. }
  419. void MultiplayerAPI::_add_peer(int p_id) {
  420. connected_peers.insert(p_id);
  421. path_get_cache.insert(p_id, PathGetCache());
  422. emit_signal("network_peer_connected", p_id);
  423. }
  424. void MultiplayerAPI::_del_peer(int p_id) {
  425. connected_peers.erase(p_id);
  426. path_get_cache.erase(p_id); // I no longer need your cache, sorry.
  427. emit_signal("network_peer_disconnected", p_id);
  428. }
  429. void MultiplayerAPI::_connected_to_server() {
  430. emit_signal("connected_to_server");
  431. }
  432. void MultiplayerAPI::_connection_failed() {
  433. emit_signal("connection_failed");
  434. }
  435. void MultiplayerAPI::_server_disconnected() {
  436. emit_signal("server_disconnected");
  437. }
  438. void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  439. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to call an RPC while no network peer is active.");
  440. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to call an RPC on a node which is not inside SceneTree.");
  441. 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.");
  442. int node_id = network_peer->get_unique_id();
  443. bool skip_rpc = node_id == p_peer_id;
  444. bool call_local_native = false;
  445. bool call_local_script = false;
  446. bool is_master = p_node->is_network_master();
  447. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  448. // Check that send mode can use local call.
  449. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rpc_mode(p_method);
  450. if (E) {
  451. call_local_native = _should_call_local(E->get(), is_master, skip_rpc);
  452. }
  453. if (call_local_native) {
  454. // Done below.
  455. } else if (p_node->get_script_instance()) {
  456. // Attempt with script.
  457. RPCMode rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_method);
  458. call_local_script = _should_call_local(rpc_mode, is_master, skip_rpc);
  459. }
  460. }
  461. if (!skip_rpc) {
  462. _send_rpc(p_node, p_peer_id, p_unreliable, false, p_method, p_arg, p_argcount);
  463. }
  464. if (call_local_native) {
  465. int temp_id = rpc_sender_id;
  466. rpc_sender_id = get_network_unique_id();
  467. Variant::CallError ce;
  468. p_node->call(p_method, p_arg, p_argcount, ce);
  469. rpc_sender_id = temp_id;
  470. if (ce.error != Variant::CallError::CALL_OK) {
  471. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  472. error = "rpc() aborted in local call: - " + error + ".";
  473. ERR_PRINTS(error);
  474. return;
  475. }
  476. }
  477. if (call_local_script) {
  478. int temp_id = rpc_sender_id;
  479. rpc_sender_id = get_network_unique_id();
  480. Variant::CallError ce;
  481. ce.error = Variant::CallError::CALL_OK;
  482. p_node->get_script_instance()->call(p_method, p_arg, p_argcount, ce);
  483. rpc_sender_id = temp_id;
  484. if (ce.error != Variant::CallError::CALL_OK) {
  485. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  486. error = "rpc() aborted in script local call: - " + error + ".";
  487. ERR_PRINTS(error);
  488. return;
  489. }
  490. }
  491. ERR_FAIL_COND_MSG(skip_rpc && !(call_local_native || call_local_script), "RPC '" + p_method + "' on yourself is not allowed by selected mode.");
  492. }
  493. void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_property, const Variant &p_value) {
  494. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to RSET while no network peer is active.");
  495. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to RSET on a node which is not inside SceneTree.");
  496. 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.");
  497. int node_id = network_peer->get_unique_id();
  498. bool is_master = p_node->is_network_master();
  499. bool skip_rset = node_id == p_peer_id;
  500. bool set_local = false;
  501. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  502. // Check that send mode can use local call.
  503. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rset_mode(p_property);
  504. if (E) {
  505. set_local = _should_call_local(E->get(), is_master, skip_rset);
  506. }
  507. if (set_local) {
  508. bool valid;
  509. int temp_id = rpc_sender_id;
  510. rpc_sender_id = get_network_unique_id();
  511. p_node->set(p_property, p_value, &valid);
  512. rpc_sender_id = temp_id;
  513. if (!valid) {
  514. String error = "rset() aborted in local set, property not found: - " + String(p_property) + ".";
  515. ERR_PRINTS(error);
  516. return;
  517. }
  518. } else if (p_node->get_script_instance()) {
  519. // Attempt with script.
  520. RPCMode rpc_mode = p_node->get_script_instance()->get_rset_mode(p_property);
  521. set_local = _should_call_local(rpc_mode, is_master, skip_rset);
  522. if (set_local) {
  523. int temp_id = rpc_sender_id;
  524. rpc_sender_id = get_network_unique_id();
  525. bool valid = p_node->get_script_instance()->set(p_property, p_value);
  526. rpc_sender_id = temp_id;
  527. if (!valid) {
  528. String error = "rset() aborted in local script set, property not found: - " + String(p_property) + ".";
  529. ERR_PRINTS(error);
  530. return;
  531. }
  532. }
  533. }
  534. }
  535. if (skip_rset) {
  536. ERR_FAIL_COND_MSG(!set_local, "RSET for '" + p_property + "' on yourself is not allowed by selected mode.");
  537. return;
  538. }
  539. const Variant *vptr = &p_value;
  540. _send_rpc(p_node, p_peer_id, p_unreliable, true, p_property, &vptr, 1);
  541. }
  542. Error MultiplayerAPI::send_bytes(PoolVector<uint8_t> p_data, int p_to, NetworkedMultiplayerPeer::TransferMode p_mode) {
  543. ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet.");
  544. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no network peer is active.");
  545. 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.");
  546. MAKE_ROOM(p_data.size() + 1);
  547. PoolVector<uint8_t>::Read r = p_data.read();
  548. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  549. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  550. network_peer->set_target_peer(p_to);
  551. network_peer->set_transfer_mode(p_mode);
  552. return network_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
  553. }
  554. void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  555. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  556. PoolVector<uint8_t> out;
  557. int len = p_packet_len - 1;
  558. out.resize(len);
  559. {
  560. PoolVector<uint8_t>::Write w = out.write();
  561. memcpy(&w[0], &p_packet[1], len);
  562. }
  563. emit_signal("network_peer_packet", p_from, out);
  564. }
  565. int MultiplayerAPI::get_network_unique_id() const {
  566. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), 0, "No network peer is assigned. Unable to get unique network ID.");
  567. return network_peer->get_unique_id();
  568. }
  569. bool MultiplayerAPI::is_network_server() const {
  570. // XXX Maybe fail silently? Maybe should actually return true to make development of both local and online multiplayer easier?
  571. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. I can't be a server.");
  572. return network_peer->is_server();
  573. }
  574. void MultiplayerAPI::set_refuse_new_network_connections(bool p_refuse) {
  575. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "No network peer is assigned. Unable to set 'refuse_new_connections'.");
  576. network_peer->set_refuse_new_connections(p_refuse);
  577. }
  578. bool MultiplayerAPI::is_refusing_new_network_connections() const {
  579. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. Unable to get 'refuse_new_connections'.");
  580. return network_peer->is_refusing_new_connections();
  581. }
  582. Vector<int> MultiplayerAPI::get_network_connected_peers() const {
  583. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), Vector<int>(), "No network peer is assigned. Assume no peers are connected.");
  584. Vector<int> ret;
  585. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  586. ret.push_back(E->get());
  587. }
  588. return ret;
  589. }
  590. void MultiplayerAPI::set_allow_object_decoding(bool p_enable) {
  591. allow_object_decoding = p_enable;
  592. }
  593. bool MultiplayerAPI::is_object_decoding_allowed() const {
  594. return allow_object_decoding;
  595. }
  596. void MultiplayerAPI::_bind_methods() {
  597. ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node);
  598. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode"), &MultiplayerAPI::send_bytes, DEFVAL(NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE));
  599. ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer);
  600. ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer);
  601. ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id);
  602. ClassDB::bind_method(D_METHOD("is_network_server"), &MultiplayerAPI::is_network_server);
  603. ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &MultiplayerAPI::get_rpc_sender_id);
  604. ClassDB::bind_method(D_METHOD("_add_peer", "id"), &MultiplayerAPI::_add_peer);
  605. ClassDB::bind_method(D_METHOD("_del_peer", "id"), &MultiplayerAPI::_del_peer);
  606. ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &MultiplayerAPI::set_network_peer);
  607. ClassDB::bind_method(D_METHOD("poll"), &MultiplayerAPI::poll);
  608. ClassDB::bind_method(D_METHOD("clear"), &MultiplayerAPI::clear);
  609. ClassDB::bind_method(D_METHOD("_connected_to_server"), &MultiplayerAPI::_connected_to_server);
  610. ClassDB::bind_method(D_METHOD("_connection_failed"), &MultiplayerAPI::_connection_failed);
  611. ClassDB::bind_method(D_METHOD("_server_disconnected"), &MultiplayerAPI::_server_disconnected);
  612. ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &MultiplayerAPI::get_network_connected_peers);
  613. ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &MultiplayerAPI::set_refuse_new_network_connections);
  614. ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &MultiplayerAPI::is_refusing_new_network_connections);
  615. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &MultiplayerAPI::set_allow_object_decoding);
  616. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &MultiplayerAPI::is_object_decoding_allowed);
  617. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  618. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections");
  619. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "NetworkedMultiplayerPeer", 0), "set_network_peer", "get_network_peer");
  620. ADD_PROPERTY_DEFAULT("refuse_new_network_connections", false);
  621. ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
  622. ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
  623. ADD_SIGNAL(MethodInfo("network_peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::POOL_BYTE_ARRAY, "packet")));
  624. ADD_SIGNAL(MethodInfo("connected_to_server"));
  625. ADD_SIGNAL(MethodInfo("connection_failed"));
  626. ADD_SIGNAL(MethodInfo("server_disconnected"));
  627. BIND_ENUM_CONSTANT(RPC_MODE_DISABLED);
  628. BIND_ENUM_CONSTANT(RPC_MODE_REMOTE);
  629. BIND_ENUM_CONSTANT(RPC_MODE_MASTER);
  630. BIND_ENUM_CONSTANT(RPC_MODE_PUPPET);
  631. BIND_ENUM_CONSTANT(RPC_MODE_SLAVE); // Deprecated.
  632. BIND_ENUM_CONSTANT(RPC_MODE_REMOTESYNC);
  633. BIND_ENUM_CONSTANT(RPC_MODE_SYNC); // Deprecated.
  634. BIND_ENUM_CONSTANT(RPC_MODE_MASTERSYNC);
  635. BIND_ENUM_CONSTANT(RPC_MODE_PUPPETSYNC);
  636. }
  637. MultiplayerAPI::MultiplayerAPI() :
  638. allow_object_decoding(false) {
  639. rpc_sender_id = 0;
  640. root_node = NULL;
  641. clear();
  642. }
  643. MultiplayerAPI::~MultiplayerAPI() {
  644. clear();
  645. }