multiplayer_api.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /**************************************************************************/
  2. /* multiplayer_api.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "multiplayer_api.h"
  31. #include "core/debugger/engine_debugger.h"
  32. #include "core/io/marshalls.h"
  33. #include <stdint.h>
  34. #ifdef DEBUG_ENABLED
  35. #include "core/os/os.h"
  36. #endif
  37. StringName MultiplayerAPI::default_interface;
  38. void MultiplayerAPI::set_default_interface(const StringName &p_interface) {
  39. ERR_FAIL_COND_MSG(!ClassDB::is_parent_class(p_interface, MultiplayerAPI::get_class_static()), vformat("Can't make %s the default multiplayer interface since it does not extend MultiplayerAPI.", p_interface));
  40. default_interface = StringName(p_interface, true);
  41. }
  42. StringName MultiplayerAPI::get_default_interface() {
  43. return default_interface;
  44. }
  45. Ref<MultiplayerAPI> MultiplayerAPI::create_default_interface() {
  46. if (default_interface != StringName()) {
  47. return Ref<MultiplayerAPI>(Object::cast_to<MultiplayerAPI>(ClassDB::instantiate(default_interface)));
  48. }
  49. return Ref<MultiplayerAPI>(memnew(MultiplayerAPIExtension));
  50. }
  51. // The variant is compressed and encoded; The first byte contains all the meta
  52. // information and the format is:
  53. // - The first LSB 6 bits are used for the variant type.
  54. // - The next two bits are used to store the encoding mode.
  55. // - Boolean values uses the encoding mode to store the value.
  56. #define VARIANT_META_TYPE_MASK 0x3F
  57. #define VARIANT_META_EMODE_MASK 0xC0
  58. #define VARIANT_META_BOOL_MASK 0x80
  59. #define ENCODE_8 0 << 6
  60. #define ENCODE_16 1 << 6
  61. #define ENCODE_32 2 << 6
  62. #define ENCODE_64 3 << 6
  63. Error MultiplayerAPI::encode_and_compress_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len, bool p_allow_object_decoding) {
  64. // Unreachable because `VARIANT_MAX` == 38 and `ENCODE_VARIANT_MASK` == 77
  65. CRASH_COND(p_variant.get_type() > VARIANT_META_TYPE_MASK);
  66. uint8_t *buf = r_buffer;
  67. r_len = 0;
  68. uint8_t encode_mode = 0;
  69. switch (p_variant.get_type()) {
  70. case Variant::BOOL: {
  71. if (buf) {
  72. // We don't use encode_mode for booleans, so we can use it to store the value.
  73. buf[0] = (p_variant.operator bool()) ? (1 << 7) : 0;
  74. buf[0] |= p_variant.get_type();
  75. }
  76. r_len += 1;
  77. } break;
  78. case Variant::INT: {
  79. if (buf) {
  80. // Reserve the first byte for the meta.
  81. buf += 1;
  82. }
  83. r_len += 1;
  84. int64_t val = p_variant;
  85. if (val <= (int64_t)INT8_MAX && val >= (int64_t)INT8_MIN) {
  86. // Use 8 bit
  87. encode_mode = ENCODE_8;
  88. if (buf) {
  89. buf[0] = val;
  90. }
  91. r_len += 1;
  92. } else if (val <= (int64_t)INT16_MAX && val >= (int64_t)INT16_MIN) {
  93. // Use 16 bit
  94. encode_mode = ENCODE_16;
  95. if (buf) {
  96. encode_uint16(val, buf);
  97. }
  98. r_len += 2;
  99. } else if (val <= (int64_t)INT32_MAX && val >= (int64_t)INT32_MIN) {
  100. // Use 32 bit
  101. encode_mode = ENCODE_32;
  102. if (buf) {
  103. encode_uint32(val, buf);
  104. }
  105. r_len += 4;
  106. } else {
  107. // Use 64 bit
  108. encode_mode = ENCODE_64;
  109. if (buf) {
  110. encode_uint64(val, buf);
  111. }
  112. r_len += 8;
  113. }
  114. // Store the meta
  115. if (buf) {
  116. buf -= 1;
  117. buf[0] = encode_mode | p_variant.get_type();
  118. }
  119. } break;
  120. default:
  121. // Any other case is not yet compressed.
  122. Error err = encode_variant(p_variant, r_buffer, r_len, p_allow_object_decoding);
  123. if (err != OK) {
  124. return err;
  125. }
  126. if (r_buffer) {
  127. // The first byte is not used by the marshaling, so store the type
  128. // so we know how to decompress and decode this variant.
  129. r_buffer[0] = p_variant.get_type();
  130. }
  131. }
  132. return OK;
  133. }
  134. Error MultiplayerAPI::decode_and_decompress_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len, bool p_allow_object_decoding) {
  135. const uint8_t *buf = p_buffer;
  136. int len = p_len;
  137. ERR_FAIL_COND_V(len < 1, ERR_INVALID_DATA);
  138. uint8_t type = buf[0] & VARIANT_META_TYPE_MASK;
  139. uint8_t encode_mode = buf[0] & VARIANT_META_EMODE_MASK;
  140. ERR_FAIL_COND_V(type >= Variant::VARIANT_MAX, ERR_INVALID_DATA);
  141. switch (type) {
  142. case Variant::BOOL: {
  143. bool val = (buf[0] & VARIANT_META_BOOL_MASK) > 0;
  144. r_variant = val;
  145. if (r_len) {
  146. *r_len = 1;
  147. }
  148. } break;
  149. case Variant::INT: {
  150. buf += 1;
  151. len -= 1;
  152. if (r_len) {
  153. *r_len = 1;
  154. }
  155. if (encode_mode == ENCODE_8) {
  156. // 8 bits.
  157. ERR_FAIL_COND_V(len < 1, ERR_INVALID_DATA);
  158. int8_t val = buf[0];
  159. r_variant = val;
  160. if (r_len) {
  161. (*r_len) += 1;
  162. }
  163. } else if (encode_mode == ENCODE_16) {
  164. // 16 bits.
  165. ERR_FAIL_COND_V(len < 2, ERR_INVALID_DATA);
  166. int16_t val = decode_uint16(buf);
  167. r_variant = val;
  168. if (r_len) {
  169. (*r_len) += 2;
  170. }
  171. } else if (encode_mode == ENCODE_32) {
  172. // 32 bits.
  173. ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
  174. int32_t val = decode_uint32(buf);
  175. r_variant = val;
  176. if (r_len) {
  177. (*r_len) += 4;
  178. }
  179. } else {
  180. // 64 bits.
  181. ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA);
  182. int64_t val = decode_uint64(buf);
  183. r_variant = val;
  184. if (r_len) {
  185. (*r_len) += 8;
  186. }
  187. }
  188. } break;
  189. default:
  190. Error err = decode_variant(r_variant, p_buffer, p_len, r_len, p_allow_object_decoding);
  191. if (err != OK) {
  192. return err;
  193. }
  194. }
  195. return OK;
  196. }
  197. Error MultiplayerAPI::encode_and_compress_variants(const Variant **p_variants, int p_count, uint8_t *p_buffer, int &r_len, bool *r_raw, bool p_allow_object_decoding) {
  198. r_len = 0;
  199. int size = 0;
  200. if (p_count == 0) {
  201. if (r_raw) {
  202. *r_raw = true;
  203. }
  204. return OK;
  205. }
  206. // Try raw encoding optimization.
  207. if (r_raw && p_count == 1) {
  208. *r_raw = false;
  209. const Variant &v = *(p_variants[0]);
  210. if (v.get_type() == Variant::PACKED_BYTE_ARRAY) {
  211. *r_raw = true;
  212. const PackedByteArray pba = v;
  213. if (p_buffer) {
  214. memcpy(p_buffer, pba.ptr(), pba.size());
  215. }
  216. r_len += pba.size();
  217. } else {
  218. encode_and_compress_variant(v, p_buffer, size, p_allow_object_decoding);
  219. r_len += size;
  220. }
  221. return OK;
  222. }
  223. // Regular encoding.
  224. for (int i = 0; i < p_count; i++) {
  225. const Variant &v = *(p_variants[i]);
  226. encode_and_compress_variant(v, p_buffer ? p_buffer + r_len : nullptr, size, p_allow_object_decoding);
  227. r_len += size;
  228. }
  229. return OK;
  230. }
  231. Error MultiplayerAPI::decode_and_decompress_variants(Vector<Variant> &r_variants, const uint8_t *p_buffer, int p_len, int &r_len, bool p_raw, bool p_allow_object_decoding) {
  232. r_len = 0;
  233. int argc = r_variants.size();
  234. if (argc == 0 && p_raw) {
  235. return OK;
  236. }
  237. ERR_FAIL_COND_V(p_raw && argc != 1, ERR_INVALID_DATA);
  238. if (p_raw) {
  239. r_len = p_len;
  240. PackedByteArray pba;
  241. pba.resize(p_len);
  242. memcpy(pba.ptrw(), p_buffer, p_len);
  243. r_variants.write[0] = pba;
  244. return OK;
  245. }
  246. for (int i = 0; i < argc; i++) {
  247. ERR_FAIL_COND_V_MSG(r_len >= p_len, ERR_INVALID_DATA, "Invalid packet received. Size too small.");
  248. int vlen;
  249. Error err = MultiplayerAPI::decode_and_decompress_variant(r_variants.write[i], &p_buffer[r_len], p_len - r_len, &vlen, p_allow_object_decoding);
  250. ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid packet received. Unable to decode state variable.");
  251. r_len += vlen;
  252. }
  253. return OK;
  254. }
  255. Error MultiplayerAPI::_rpc_bind(int p_peer, Object *p_object, const StringName &p_method, Array p_args) {
  256. Vector<Variant> args;
  257. Vector<const Variant *> argsp;
  258. args.resize(p_args.size());
  259. argsp.resize(p_args.size());
  260. Variant *ptr = args.ptrw();
  261. const Variant **pptr = argsp.ptrw();
  262. for (int i = 0; i < p_args.size(); i++) {
  263. ptr[i] = p_args[i];
  264. pptr[i] = &ptr[i];
  265. }
  266. return rpcp(p_object, p_peer, p_method, argsp.size() ? argsp.ptrw() : nullptr, argsp.size());
  267. }
  268. void MultiplayerAPI::_bind_methods() {
  269. ClassDB::bind_method(D_METHOD("has_multiplayer_peer"), &MultiplayerAPI::has_multiplayer_peer);
  270. ClassDB::bind_method(D_METHOD("get_multiplayer_peer"), &MultiplayerAPI::get_multiplayer_peer);
  271. ClassDB::bind_method(D_METHOD("set_multiplayer_peer", "peer"), &MultiplayerAPI::set_multiplayer_peer);
  272. ClassDB::bind_method(D_METHOD("get_unique_id"), &MultiplayerAPI::get_unique_id);
  273. ClassDB::bind_method(D_METHOD("is_server"), &MultiplayerAPI::is_server);
  274. ClassDB::bind_method(D_METHOD("get_remote_sender_id"), &MultiplayerAPI::get_remote_sender_id);
  275. ClassDB::bind_method(D_METHOD("poll"), &MultiplayerAPI::poll);
  276. ClassDB::bind_method(D_METHOD("rpc", "peer", "object", "method", "arguments"), &MultiplayerAPI::_rpc_bind, DEFVAL(Array()));
  277. ClassDB::bind_method(D_METHOD("object_configuration_add", "object", "configuration"), &MultiplayerAPI::object_configuration_add);
  278. ClassDB::bind_method(D_METHOD("object_configuration_remove", "object", "configuration"), &MultiplayerAPI::object_configuration_remove);
  279. ClassDB::bind_method(D_METHOD("get_peers"), &MultiplayerAPI::get_peer_ids);
  280. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "multiplayer_peer", PROPERTY_HINT_RESOURCE_TYPE, "MultiplayerPeer", PROPERTY_USAGE_NONE), "set_multiplayer_peer", "get_multiplayer_peer");
  281. ClassDB::bind_static_method("MultiplayerAPI", D_METHOD("set_default_interface", "interface_name"), &MultiplayerAPI::set_default_interface);
  282. ClassDB::bind_static_method("MultiplayerAPI", D_METHOD("get_default_interface"), &MultiplayerAPI::get_default_interface);
  283. ClassDB::bind_static_method("MultiplayerAPI", D_METHOD("create_default_interface"), &MultiplayerAPI::create_default_interface);
  284. ADD_SIGNAL(MethodInfo("peer_connected", PropertyInfo(Variant::INT, "id")));
  285. ADD_SIGNAL(MethodInfo("peer_disconnected", PropertyInfo(Variant::INT, "id")));
  286. ADD_SIGNAL(MethodInfo("connected_to_server"));
  287. ADD_SIGNAL(MethodInfo("connection_failed"));
  288. ADD_SIGNAL(MethodInfo("server_disconnected"));
  289. BIND_ENUM_CONSTANT(RPC_MODE_DISABLED);
  290. BIND_ENUM_CONSTANT(RPC_MODE_ANY_PEER);
  291. BIND_ENUM_CONSTANT(RPC_MODE_AUTHORITY);
  292. }
  293. /// MultiplayerAPIExtension
  294. Error MultiplayerAPIExtension::poll() {
  295. Error err = OK;
  296. GDVIRTUAL_CALL(_poll, err);
  297. return err;
  298. }
  299. void MultiplayerAPIExtension::set_multiplayer_peer(const Ref<MultiplayerPeer> &p_peer) {
  300. GDVIRTUAL_CALL(_set_multiplayer_peer, p_peer);
  301. }
  302. Ref<MultiplayerPeer> MultiplayerAPIExtension::get_multiplayer_peer() {
  303. Ref<MultiplayerPeer> peer;
  304. GDVIRTUAL_CALL(_get_multiplayer_peer, peer);
  305. return peer;
  306. }
  307. int MultiplayerAPIExtension::get_unique_id() {
  308. int id = 1;
  309. GDVIRTUAL_CALL(_get_unique_id, id);
  310. return id;
  311. }
  312. Vector<int> MultiplayerAPIExtension::get_peer_ids() {
  313. Vector<int> ids;
  314. GDVIRTUAL_CALL(_get_peer_ids, ids);
  315. return ids;
  316. }
  317. Error MultiplayerAPIExtension::rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  318. if (!GDVIRTUAL_IS_OVERRIDDEN(_rpc)) {
  319. return ERR_UNAVAILABLE;
  320. }
  321. Array args;
  322. for (int i = 0; i < p_argcount; i++) {
  323. args.push_back(*p_arg[i]);
  324. }
  325. Error ret = FAILED;
  326. GDVIRTUAL_CALL(_rpc, p_peer_id, p_obj, p_method, args, ret);
  327. return ret;
  328. }
  329. int MultiplayerAPIExtension::get_remote_sender_id() {
  330. int id = 0;
  331. GDVIRTUAL_CALL(_get_remote_sender_id, id);
  332. return id;
  333. }
  334. Error MultiplayerAPIExtension::object_configuration_add(Object *p_object, Variant p_config) {
  335. Error err = ERR_UNAVAILABLE;
  336. GDVIRTUAL_CALL(_object_configuration_add, p_object, p_config, err);
  337. return err;
  338. }
  339. Error MultiplayerAPIExtension::object_configuration_remove(Object *p_object, Variant p_config) {
  340. Error err = ERR_UNAVAILABLE;
  341. GDVIRTUAL_CALL(_object_configuration_remove, p_object, p_config, err);
  342. return err;
  343. }
  344. void MultiplayerAPIExtension::_bind_methods() {
  345. GDVIRTUAL_BIND(_poll);
  346. GDVIRTUAL_BIND(_set_multiplayer_peer, "multiplayer_peer");
  347. GDVIRTUAL_BIND(_get_multiplayer_peer);
  348. GDVIRTUAL_BIND(_get_unique_id);
  349. GDVIRTUAL_BIND(_get_peer_ids);
  350. GDVIRTUAL_BIND(_rpc, "peer", "object", "method", "args");
  351. GDVIRTUAL_BIND(_get_remote_sender_id);
  352. GDVIRTUAL_BIND(_object_configuration_add, "object", "configuration");
  353. GDVIRTUAL_BIND(_object_configuration_remove, "object", "configuration");
  354. }