multiplayer_api.cpp 13 KB

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