networked_multiplayer_enet.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. /*************************************************************************/
  2. /* networked_multiplayer_enet.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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 "networked_multiplayer_enet.h"
  31. #include "io/ip.h"
  32. #include "io/marshalls.h"
  33. #include "os/os.h"
  34. void NetworkedMultiplayerENet::set_transfer_mode(TransferMode p_mode) {
  35. transfer_mode = p_mode;
  36. }
  37. NetworkedMultiplayerPeer::TransferMode NetworkedMultiplayerENet::get_transfer_mode() const {
  38. return transfer_mode;
  39. }
  40. void NetworkedMultiplayerENet::set_target_peer(int p_peer) {
  41. target_peer = p_peer;
  42. }
  43. int NetworkedMultiplayerENet::get_packet_peer() const {
  44. ERR_FAIL_COND_V(!active, 1);
  45. ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
  46. return incoming_packets.front()->get().from;
  47. }
  48. Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth) {
  49. ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
  50. ENetAddress address;
  51. #ifdef GODOT_ENET
  52. if (bind_ip.is_wildcard()) {
  53. address.wildcard = 1;
  54. } else {
  55. enet_address_set_ip(&address, bind_ip.get_ipv6(), 16);
  56. }
  57. #else
  58. if (bind_ip.is_wildcard()) {
  59. address.host = 0;
  60. } else {
  61. ERR_FAIL_COND_V(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER);
  62. address.host = *(uint32_t *)bind_ip.get_ipv4();
  63. }
  64. #endif
  65. address.port = p_port;
  66. host = enet_host_create(&address /* the address to bind the server host to */,
  67. p_max_clients /* allow up to 32 clients and/or outgoing connections */,
  68. SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
  69. p_in_bandwidth /* assume any amount of incoming bandwidth */,
  70. p_out_bandwidth /* assume any amount of outgoing bandwidth */);
  71. ERR_FAIL_COND_V(!host, ERR_CANT_CREATE);
  72. _setup_compressor();
  73. active = true;
  74. server = true;
  75. refuse_connections = false;
  76. unique_id = 1;
  77. connection_status = CONNECTION_CONNECTED;
  78. return OK;
  79. }
  80. Error NetworkedMultiplayerENet::create_client(const String &p_address, int p_port, int p_in_bandwidth, int p_out_bandwidth) {
  81. ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
  82. host = enet_host_create(NULL /* create a client host */,
  83. 1 /* only allow 1 outgoing connection */,
  84. SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
  85. p_in_bandwidth /* limit incoming bandwith if > 0 */,
  86. p_out_bandwidth /* limit outgoing bandwith if > 0 */);
  87. ERR_FAIL_COND_V(!host, ERR_CANT_CREATE);
  88. _setup_compressor();
  89. IP_Address ip;
  90. if (p_address.is_valid_ip_address()) {
  91. ip = p_address;
  92. } else {
  93. #ifdef GODOT_ENET
  94. ip = IP::get_singleton()->resolve_hostname(p_address);
  95. #else
  96. ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4);
  97. #endif
  98. ERR_FAIL_COND_V(!ip.is_valid(), ERR_CANT_RESOLVE);
  99. }
  100. ENetAddress address;
  101. #ifdef GODOT_ENET
  102. enet_address_set_ip(&address, ip.get_ipv6(), 16);
  103. #else
  104. ERR_FAIL_COND_V(!ip.is_ipv4(), ERR_INVALID_PARAMETER);
  105. address.host = *(uint32_t *)ip.get_ipv4();
  106. #endif
  107. address.port = p_port;
  108. unique_id = _gen_unique_id();
  109. /* Initiate the connection, allocating the enough channels */
  110. ENetPeer *peer = enet_host_connect(host, &address, SYSCH_MAX, unique_id);
  111. if (peer == NULL) {
  112. enet_host_destroy(host);
  113. ERR_FAIL_COND_V(!peer, ERR_CANT_CREATE);
  114. }
  115. // Technically safe to ignore the peer or anything else.
  116. connection_status = CONNECTION_CONNECTING;
  117. active = true;
  118. server = false;
  119. refuse_connections = false;
  120. return OK;
  121. }
  122. void NetworkedMultiplayerENet::poll() {
  123. ERR_FAIL_COND(!active);
  124. _pop_current_packet();
  125. ENetEvent event;
  126. /* Wait up to 1000 milliseconds for an event. */
  127. while (true) {
  128. if (!host || !active) // Might have been disconnected while emitting a notification
  129. return;
  130. int ret = enet_host_service(host, &event, 1);
  131. if (ret < 0) {
  132. // Error, do something?
  133. break;
  134. } else if (ret == 0) {
  135. break;
  136. }
  137. switch (event.type) {
  138. case ENET_EVENT_TYPE_CONNECT: {
  139. /* Store any relevant client information here. */
  140. if (server && refuse_connections) {
  141. enet_peer_reset(event.peer);
  142. break;
  143. }
  144. int *new_id = memnew(int);
  145. *new_id = event.data;
  146. if (*new_id == 0) { // Data zero is sent by server (enet won't let you configure this). Server is always 1
  147. *new_id = 1;
  148. }
  149. event.peer->data = new_id;
  150. peer_map[*new_id] = event.peer;
  151. connection_status = CONNECTION_CONNECTED; // If connecting, this means it connected to something!
  152. emit_signal("peer_connected", *new_id);
  153. if (server) {
  154. // Someone connected, notify all the peers available
  155. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  156. if (E->key() == *new_id)
  157. continue;
  158. // Send existing peers to new peer
  159. ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  160. encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
  161. encode_uint32(E->key(), &packet->data[4]);
  162. enet_peer_send(event.peer, SYSCH_CONFIG, packet);
  163. // Send the new peer to existing peers
  164. packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  165. encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
  166. encode_uint32(*new_id, &packet->data[4]);
  167. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  168. }
  169. } else {
  170. emit_signal("connection_succeeded");
  171. }
  172. } break;
  173. case ENET_EVENT_TYPE_DISCONNECT: {
  174. /* Reset the peer's client information. */
  175. int *id = (int *)event.peer->data;
  176. if (!id) {
  177. if (!server) {
  178. emit_signal("connection_failed");
  179. }
  180. } else {
  181. if (server) {
  182. // Someone disconnected, notify everyone else
  183. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  184. if (E->key() == *id)
  185. continue;
  186. ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  187. encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
  188. encode_uint32(*id, &packet->data[4]);
  189. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  190. }
  191. } else if (!server) {
  192. emit_signal("server_disconnected");
  193. close_connection();
  194. return;
  195. }
  196. emit_signal("peer_disconnected", *id);
  197. peer_map.erase(*id);
  198. memdelete(id);
  199. }
  200. } break;
  201. case ENET_EVENT_TYPE_RECEIVE: {
  202. if (event.channelID == SYSCH_CONFIG) {
  203. // Some config message
  204. ERR_CONTINUE(event.packet->dataLength < 8);
  205. // Only server can send config messages
  206. ERR_CONTINUE(server);
  207. int msg = decode_uint32(&event.packet->data[0]);
  208. int id = decode_uint32(&event.packet->data[4]);
  209. switch (msg) {
  210. case SYSMSG_ADD_PEER: {
  211. peer_map[id] = NULL;
  212. emit_signal("peer_connected", id);
  213. } break;
  214. case SYSMSG_REMOVE_PEER: {
  215. peer_map.erase(id);
  216. emit_signal("peer_disconnected", id);
  217. } break;
  218. }
  219. enet_packet_destroy(event.packet);
  220. } else if (event.channelID < SYSCH_MAX) {
  221. Packet packet;
  222. packet.packet = event.packet;
  223. uint32_t *id = (uint32_t *)event.peer->data;
  224. ERR_CONTINUE(event.packet->dataLength < 12)
  225. uint32_t source = decode_uint32(&event.packet->data[0]);
  226. int target = decode_uint32(&event.packet->data[4]);
  227. uint32_t flags = decode_uint32(&event.packet->data[8]);
  228. packet.from = source;
  229. if (server) {
  230. // Someone is cheating and trying to fake the source!
  231. ERR_CONTINUE(source != *id);
  232. packet.from = *id;
  233. if (target == 0) {
  234. // Re-send to everyone but sender :|
  235. incoming_packets.push_back(packet);
  236. // And make copies for sending
  237. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  238. if (uint32_t(E->key()) == source) // Do not resend to self
  239. continue;
  240. ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags);
  241. enet_peer_send(E->get(), event.channelID, packet2);
  242. }
  243. } else if (target < 0) {
  244. // To all but one
  245. // And make copies for sending
  246. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  247. if (uint32_t(E->key()) == source || E->key() == -target) // Do not resend to self, also do not send to excluded
  248. continue;
  249. ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags);
  250. enet_peer_send(E->get(), event.channelID, packet2);
  251. }
  252. if (-target != 1) {
  253. // Server is not excluded
  254. incoming_packets.push_back(packet);
  255. } else {
  256. // Server is excluded, erase packet
  257. enet_packet_destroy(packet.packet);
  258. }
  259. } else if (target == 1) {
  260. // To myself and only myself
  261. incoming_packets.push_back(packet);
  262. } else {
  263. // To someone else, specifically
  264. ERR_CONTINUE(!peer_map.has(target));
  265. enet_peer_send(peer_map[target], event.channelID, packet.packet);
  266. }
  267. } else {
  268. incoming_packets.push_back(packet);
  269. }
  270. // Destroy packet later..
  271. } else {
  272. ERR_CONTINUE(true);
  273. }
  274. } break;
  275. case ENET_EVENT_TYPE_NONE: {
  276. // Do nothing
  277. } break;
  278. }
  279. }
  280. }
  281. bool NetworkedMultiplayerENet::is_server() const {
  282. ERR_FAIL_COND_V(!active, false);
  283. return server;
  284. }
  285. void NetworkedMultiplayerENet::close_connection() {
  286. if (!active)
  287. return;
  288. _pop_current_packet();
  289. bool peers_disconnected = false;
  290. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  291. if (E->get()) {
  292. enet_peer_disconnect_now(E->get(), unique_id);
  293. peers_disconnected = true;
  294. }
  295. }
  296. if (peers_disconnected) {
  297. enet_host_flush(host);
  298. OS::get_singleton()->delay_usec(100); // Wait 100ms for disconnection packets to send
  299. }
  300. enet_host_destroy(host);
  301. active = false;
  302. incoming_packets.clear();
  303. unique_id = 1; // Server is 1
  304. connection_status = CONNECTION_DISCONNECTED;
  305. }
  306. void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) {
  307. ERR_FAIL_COND(!active);
  308. ERR_FAIL_COND(!is_server());
  309. ERR_FAIL_COND(!peer_map.has(p_peer))
  310. if (now) {
  311. enet_peer_disconnect_now(peer_map[p_peer], 0);
  312. // enet_peer_disconnect_now doesn't generate ENET_EVENT_TYPE_DISCONNECT,
  313. // notify everyone else, send disconnect signal & remove from peer_map like in poll()
  314. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  315. if (E->key() == p_peer)
  316. continue;
  317. ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  318. encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
  319. encode_uint32(p_peer, &packet->data[4]);
  320. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  321. }
  322. emit_signal("peer_disconnected", p_peer);
  323. peer_map.erase(p_peer);
  324. } else {
  325. enet_peer_disconnect_later(peer_map[p_peer], 0);
  326. }
  327. }
  328. int NetworkedMultiplayerENet::get_available_packet_count() const {
  329. return incoming_packets.size();
  330. }
  331. Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  332. ERR_FAIL_COND_V(incoming_packets.size() == 0, ERR_UNAVAILABLE);
  333. _pop_current_packet();
  334. current_packet = incoming_packets.front()->get();
  335. incoming_packets.pop_front();
  336. *r_buffer = (const uint8_t *)(&current_packet.packet->data[12]);
  337. r_buffer_size = current_packet.packet->dataLength - 12;
  338. return OK;
  339. }
  340. Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  341. ERR_FAIL_COND_V(!active, ERR_UNCONFIGURED);
  342. ERR_FAIL_COND_V(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  343. int packet_flags = 0;
  344. int channel = SYSCH_RELIABLE;
  345. switch (transfer_mode) {
  346. case TRANSFER_MODE_UNRELIABLE: {
  347. packet_flags = ENET_PACKET_FLAG_UNSEQUENCED;
  348. channel = SYSCH_UNRELIABLE;
  349. } break;
  350. case TRANSFER_MODE_UNRELIABLE_ORDERED: {
  351. packet_flags = 0;
  352. channel = SYSCH_UNRELIABLE;
  353. } break;
  354. case TRANSFER_MODE_RELIABLE: {
  355. packet_flags = ENET_PACKET_FLAG_RELIABLE;
  356. channel = SYSCH_RELIABLE;
  357. } break;
  358. }
  359. Map<int, ENetPeer *>::Element *E = NULL;
  360. if (target_peer != 0) {
  361. E = peer_map.find(ABS(target_peer));
  362. if (!E) {
  363. ERR_EXPLAIN("Invalid Target Peer: " + itos(target_peer));
  364. ERR_FAIL_V(ERR_INVALID_PARAMETER);
  365. }
  366. }
  367. ENetPacket *packet = enet_packet_create(NULL, p_buffer_size + 12, packet_flags);
  368. encode_uint32(unique_id, &packet->data[0]); // Source ID
  369. encode_uint32(target_peer, &packet->data[4]); // Dest ID
  370. encode_uint32(packet_flags, &packet->data[8]); // Dest ID
  371. copymem(&packet->data[12], p_buffer, p_buffer_size);
  372. if (server) {
  373. if (target_peer == 0) {
  374. enet_host_broadcast(host, channel, packet);
  375. } else if (target_peer < 0) {
  376. // Send to all but one
  377. // and make copies for sending
  378. int exclude = -target_peer;
  379. for (Map<int, ENetPeer *>::Element *F = peer_map.front(); F; F = F->next()) {
  380. if (F->key() == exclude) // Exclude packet
  381. continue;
  382. ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags);
  383. enet_peer_send(F->get(), channel, packet2);
  384. }
  385. enet_packet_destroy(packet); // Original packet no longer needed
  386. } else {
  387. enet_peer_send(E->get(), channel, packet);
  388. }
  389. } else {
  390. ERR_FAIL_COND_V(!peer_map.has(1), ERR_BUG);
  391. enet_peer_send(peer_map[1], channel, packet); // Send to server for broadcast..
  392. }
  393. enet_host_flush(host);
  394. return OK;
  395. }
  396. int NetworkedMultiplayerENet::get_max_packet_size() const {
  397. return 1 << 24; // Anything is good
  398. }
  399. void NetworkedMultiplayerENet::_pop_current_packet() {
  400. if (current_packet.packet) {
  401. enet_packet_destroy(current_packet.packet);
  402. current_packet.packet = NULL;
  403. current_packet.from = 0;
  404. }
  405. }
  406. NetworkedMultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const {
  407. return connection_status;
  408. }
  409. uint32_t NetworkedMultiplayerENet::_gen_unique_id() const {
  410. uint32_t hash = 0;
  411. while (hash == 0 || hash == 1) {
  412. hash = hash_djb2_one_32(
  413. (uint32_t)OS::get_singleton()->get_ticks_usec());
  414. hash = hash_djb2_one_32(
  415. (uint32_t)OS::get_singleton()->get_unix_time(), hash);
  416. hash = hash_djb2_one_32(
  417. (uint32_t)OS::get_singleton()->get_user_data_dir().hash64(), hash);
  418. hash = hash_djb2_one_32(
  419. (uint32_t)((uint64_t)this), hash); // Rely on ASLR heap
  420. hash = hash_djb2_one_32(
  421. (uint32_t)((uint64_t)&hash), hash); // Rely on ASLR stack
  422. hash = hash & 0x7FFFFFFF; // Make it compatible with unsigned, since negative ID is used for exclusion
  423. }
  424. return hash;
  425. }
  426. int NetworkedMultiplayerENet::get_unique_id() const {
  427. ERR_FAIL_COND_V(!active, 0);
  428. return unique_id;
  429. }
  430. void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) {
  431. refuse_connections = p_enable;
  432. }
  433. bool NetworkedMultiplayerENet::is_refusing_new_connections() const {
  434. return refuse_connections;
  435. }
  436. void NetworkedMultiplayerENet::set_compression_mode(CompressionMode p_mode) {
  437. compression_mode = p_mode;
  438. }
  439. NetworkedMultiplayerENet::CompressionMode NetworkedMultiplayerENet::get_compression_mode() const {
  440. return compression_mode;
  441. }
  442. size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
  443. NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
  444. if (size_t(enet->src_compressor_mem.size()) < inLimit) {
  445. enet->src_compressor_mem.resize(inLimit);
  446. }
  447. int total = inLimit;
  448. int ofs = 0;
  449. while (total) {
  450. for (size_t i = 0; i < inBufferCount; i++) {
  451. int to_copy = MIN(total, int(inBuffers[i].dataLength));
  452. copymem(&enet->src_compressor_mem[ofs], inBuffers[i].data, to_copy);
  453. ofs += to_copy;
  454. total -= to_copy;
  455. }
  456. }
  457. Compression::Mode mode;
  458. switch (enet->compression_mode) {
  459. case COMPRESS_FASTLZ: {
  460. mode = Compression::MODE_FASTLZ;
  461. } break;
  462. case COMPRESS_ZLIB: {
  463. mode = Compression::MODE_DEFLATE;
  464. } break;
  465. case COMPRESS_ZSTD: {
  466. mode = Compression::MODE_ZSTD;
  467. } break;
  468. default: { ERR_FAIL_V(0); }
  469. }
  470. int req_size = Compression::get_max_compressed_buffer_size(ofs, mode);
  471. if (enet->dst_compressor_mem.size() < req_size) {
  472. enet->dst_compressor_mem.resize(req_size);
  473. }
  474. int ret = Compression::compress(enet->dst_compressor_mem.ptrw(), enet->src_compressor_mem.ptr(), ofs, mode);
  475. if (ret < 0)
  476. return 0;
  477. if (ret > int(outLimit))
  478. return 0; // Do not bother
  479. copymem(outData, enet->dst_compressor_mem.ptr(), ret);
  480. return ret;
  481. }
  482. size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
  483. NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
  484. int ret = -1;
  485. switch (enet->compression_mode) {
  486. case COMPRESS_FASTLZ: {
  487. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ);
  488. } break;
  489. case COMPRESS_ZLIB: {
  490. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE);
  491. } break;
  492. case COMPRESS_ZSTD: {
  493. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD);
  494. } break;
  495. default: {}
  496. }
  497. if (ret < 0) {
  498. return 0;
  499. } else {
  500. return ret;
  501. }
  502. }
  503. void NetworkedMultiplayerENet::_setup_compressor() {
  504. switch (compression_mode) {
  505. case COMPRESS_NONE: {
  506. enet_host_compress(host, NULL);
  507. } break;
  508. case COMPRESS_RANGE_CODER: {
  509. enet_host_compress_with_range_coder(host);
  510. } break;
  511. case COMPRESS_FASTLZ:
  512. case COMPRESS_ZLIB:
  513. case COMPRESS_ZSTD: {
  514. enet_host_compress(host, &enet_compressor);
  515. } break;
  516. }
  517. }
  518. void NetworkedMultiplayerENet::enet_compressor_destroy(void *context) {
  519. // Nothing to do
  520. }
  521. IP_Address NetworkedMultiplayerENet::get_peer_address(int p_peer_id) const {
  522. ERR_FAIL_COND_V(!peer_map.has(p_peer_id), IP_Address());
  523. ERR_FAIL_COND_V(!is_server() && p_peer_id != 1, IP_Address());
  524. ERR_FAIL_COND_V(peer_map[p_peer_id] == NULL, IP_Address());
  525. IP_Address out;
  526. #ifdef GODOT_ENET
  527. out.set_ipv6((uint8_t *)&(peer_map[p_peer_id]->address.host));
  528. #else
  529. out.set_ipv4((uint8_t *)&(peer_map[p_peer_id]->address.host));
  530. #endif
  531. return out;
  532. }
  533. int NetworkedMultiplayerENet::get_peer_port(int p_peer_id) const {
  534. ERR_FAIL_COND_V(!peer_map.has(p_peer_id), 0);
  535. ERR_FAIL_COND_V(!is_server() && p_peer_id != 1, 0);
  536. ERR_FAIL_COND_V(peer_map[p_peer_id] == NULL, 0);
  537. #ifdef GODOT_ENET
  538. return peer_map[p_peer_id]->address.port;
  539. #else
  540. return peer_map[p_peer_id]->address.port;
  541. #endif
  542. }
  543. void NetworkedMultiplayerENet::_bind_methods() {
  544. ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0));
  545. ClassDB::bind_method(D_METHOD("create_client", "address", "port", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_client, DEFVAL(0), DEFVAL(0));
  546. ClassDB::bind_method(D_METHOD("close_connection"), &NetworkedMultiplayerENet::close_connection);
  547. ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "now"), &NetworkedMultiplayerENet::disconnect_peer, DEFVAL(false));
  548. ClassDB::bind_method(D_METHOD("set_compression_mode", "mode"), &NetworkedMultiplayerENet::set_compression_mode);
  549. ClassDB::bind_method(D_METHOD("get_compression_mode"), &NetworkedMultiplayerENet::get_compression_mode);
  550. ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &NetworkedMultiplayerENet::set_bind_ip);
  551. ClassDB::bind_method(D_METHOD("get_peer_address"), &NetworkedMultiplayerENet::get_peer_address);
  552. ClassDB::bind_method(D_METHOD("get_peer_port"), &NetworkedMultiplayerENet::get_peer_port);
  553. ADD_PROPERTY(PropertyInfo(Variant::INT, "compression_mode", PROPERTY_HINT_ENUM, "None,Range Coder,FastLZ,ZLib,ZStd"), "set_compression_mode", "get_compression_mode");
  554. BIND_ENUM_CONSTANT(COMPRESS_NONE);
  555. BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER);
  556. BIND_ENUM_CONSTANT(COMPRESS_FASTLZ);
  557. BIND_ENUM_CONSTANT(COMPRESS_ZLIB);
  558. BIND_ENUM_CONSTANT(COMPRESS_ZSTD);
  559. }
  560. NetworkedMultiplayerENet::NetworkedMultiplayerENet() {
  561. active = false;
  562. server = false;
  563. refuse_connections = false;
  564. unique_id = 0;
  565. target_peer = 0;
  566. current_packet.packet = NULL;
  567. transfer_mode = TRANSFER_MODE_RELIABLE;
  568. connection_status = CONNECTION_DISCONNECTED;
  569. compression_mode = COMPRESS_NONE;
  570. enet_compressor.context = this;
  571. enet_compressor.compress = enet_compress;
  572. enet_compressor.decompress = enet_decompress;
  573. enet_compressor.destroy = enet_compressor_destroy;
  574. bind_ip = IP_Address("*");
  575. }
  576. NetworkedMultiplayerENet::~NetworkedMultiplayerENet() {
  577. close_connection();
  578. }
  579. // Sets IP for ENet to bind when using create_server
  580. // if no IP is set, then ENet bind to ENET_HOST_ANY
  581. void NetworkedMultiplayerENet::set_bind_ip(const IP_Address &p_ip) {
  582. ERR_FAIL_COND(!p_ip.is_valid() && !p_ip.is_wildcard());
  583. bind_ip = p_ip;
  584. }