2
0

enet_multiplayer_peer.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. /*************************************************************************/
  2. /* enet_multiplayer_peer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "enet_multiplayer_peer.h"
  31. #include "core/io/ip.h"
  32. #include "core/io/marshalls.h"
  33. #include "core/os/os.h"
  34. void ENetMultiplayerPeer::set_target_peer(int p_peer) {
  35. target_peer = p_peer;
  36. }
  37. int ENetMultiplayerPeer::get_packet_peer() const {
  38. ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active.");
  39. ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
  40. return incoming_packets.front()->get().from;
  41. }
  42. Error ENetMultiplayerPeer::create_server(int p_port, int p_max_clients, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
  43. ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
  44. set_refuse_new_connections(false);
  45. Ref<ENetConnection> host;
  46. host.instantiate();
  47. Error err = host->create_host_bound(bind_ip, p_port, p_max_clients, 0, p_max_channels > 0 ? p_max_channels + SYSCH_MAX : 0, p_out_bandwidth);
  48. if (err != OK) {
  49. return err;
  50. }
  51. active_mode = MODE_SERVER;
  52. unique_id = 1;
  53. connection_status = CONNECTION_CONNECTED;
  54. hosts[0] = host;
  55. return OK;
  56. }
  57. Error ENetMultiplayerPeer::create_client(const String &p_address, int p_port, int p_channel_count, int p_in_bandwidth, int p_out_bandwidth, int p_local_port) {
  58. ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
  59. set_refuse_new_connections(false);
  60. Ref<ENetConnection> host;
  61. host.instantiate();
  62. Error err;
  63. if (p_local_port) {
  64. err = host->create_host_bound(bind_ip, p_local_port, 1, 0, p_in_bandwidth, p_out_bandwidth);
  65. } else {
  66. err = host->create_host(1, 0, p_in_bandwidth, p_out_bandwidth);
  67. }
  68. if (err != OK) {
  69. return err;
  70. }
  71. unique_id = generate_unique_id();
  72. Ref<ENetPacketPeer> peer = host->connect_to_host(p_address, p_port, p_channel_count > 0 ? p_channel_count + SYSCH_MAX : 0, unique_id);
  73. if (peer.is_null()) {
  74. host->destroy();
  75. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Couldn't connect to the ENet multiplayer server.");
  76. }
  77. // Need to wait for CONNECT event.
  78. connection_status = CONNECTION_CONNECTING;
  79. active_mode = MODE_CLIENT;
  80. peers[1] = peer;
  81. hosts[0] = host;
  82. return OK;
  83. }
  84. Error ENetMultiplayerPeer::create_mesh(int p_id) {
  85. ERR_FAIL_COND_V_MSG(p_id <= 0, ERR_INVALID_PARAMETER, "The unique ID must be greater then 0");
  86. ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
  87. active_mode = MODE_MESH;
  88. unique_id = p_id;
  89. connection_status = CONNECTION_CONNECTED;
  90. return OK;
  91. }
  92. Error ENetMultiplayerPeer::add_mesh_peer(int p_id, Ref<ENetConnection> p_host) {
  93. ERR_FAIL_COND_V(p_host.is_null(), ERR_INVALID_PARAMETER);
  94. ERR_FAIL_COND_V_MSG(active_mode != MODE_MESH, ERR_UNCONFIGURED, "The multiplayer instance is not configured as a mesh. Call 'create_mesh' first.");
  95. List<Ref<ENetPacketPeer>> host_peers;
  96. p_host->get_peers(host_peers);
  97. ERR_FAIL_COND_V_MSG(host_peers.size() != 1 || host_peers[0]->get_state() != ENetPacketPeer::STATE_CONNECTED, ERR_INVALID_PARAMETER, "The provided host must have excatly one peer in the connected state.");
  98. hosts[p_id] = p_host;
  99. peers[p_id] = host_peers[0];
  100. emit_signal(SNAME("peer_connected"), p_id);
  101. return OK;
  102. }
  103. bool ENetMultiplayerPeer::_poll_server() {
  104. for (const KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  105. if (!(E.value->is_active())) {
  106. emit_signal(SNAME("peer_disconnected"), E.value->get_meta(SNAME("_net_id")));
  107. peers.erase(E.key);
  108. }
  109. }
  110. ENetConnection::Event event;
  111. ENetConnection::EventType ret = hosts[0]->service(0, event);
  112. if (ret == ENetConnection::EVENT_ERROR) {
  113. return true;
  114. }
  115. switch (ret) {
  116. case ENetConnection::EVENT_CONNECT: {
  117. if (is_refusing_new_connections()) {
  118. event.peer->reset();
  119. return false;
  120. }
  121. // Client joined with invalid ID, probably trying to exploit us.
  122. if (event.data < 2 || peers.has((int)event.data)) {
  123. event.peer->reset();
  124. return false;
  125. }
  126. int id = event.data;
  127. event.peer->set_meta(SNAME("_net_id"), id);
  128. peers[id] = event.peer;
  129. emit_signal(SNAME("peer_connected"), id);
  130. if (server_relay) {
  131. _notify_peers(id, true);
  132. }
  133. return false;
  134. }
  135. case ENetConnection::EVENT_DISCONNECT: {
  136. int id = event.peer->get_meta(SNAME("_net_id"));
  137. if (!peers.has(id)) {
  138. // Never fully connected.
  139. return false;
  140. }
  141. emit_signal(SNAME("peer_disconnected"), id);
  142. peers.erase(id);
  143. if (server_relay) {
  144. _notify_peers(id, false);
  145. }
  146. return false;
  147. }
  148. case ENetConnection::EVENT_RECEIVE: {
  149. if (event.channel_id == SYSCH_CONFIG) {
  150. _destroy_unused(event.packet);
  151. ERR_FAIL_V_MSG(false, "Only server can send config messages");
  152. } else {
  153. if (event.packet->dataLength < 8) {
  154. _destroy_unused(event.packet);
  155. ERR_FAIL_V_MSG(false, "Invalid packet size");
  156. }
  157. uint32_t source = decode_uint32(&event.packet->data[0]);
  158. int target = decode_uint32(&event.packet->data[4]);
  159. uint32_t id = event.peer->get_meta(SNAME("_net_id"));
  160. // Someone is cheating and trying to fake the source!
  161. if (source != id) {
  162. _destroy_unused(event.packet);
  163. ERR_FAIL_V_MSG(false, "Someone is cheating and trying to fake the source!");
  164. }
  165. Packet packet;
  166. packet.packet = event.packet;
  167. packet.channel = event.channel_id;
  168. packet.from = id;
  169. // Even if relaying is disabled, these targets are valid as incoming packets.
  170. if (target == 1 || target == 0 || target < -1) {
  171. packet.packet->referenceCount++;
  172. incoming_packets.push_back(packet);
  173. }
  174. if (server_relay && target != 1) {
  175. packet.packet->referenceCount++;
  176. _relay(source, target, event.channel_id, event.packet);
  177. packet.packet->referenceCount--;
  178. _destroy_unused(event.packet);
  179. }
  180. // Destroy packet later
  181. }
  182. return false;
  183. }
  184. default:
  185. return true;
  186. }
  187. }
  188. bool ENetMultiplayerPeer::_poll_client() {
  189. if (peers.has(1) && !peers[1]->is_active()) {
  190. if (connection_status == CONNECTION_CONNECTED) {
  191. // Client just disconnected from server.
  192. emit_signal(SNAME("server_disconnected"));
  193. } else {
  194. emit_signal(SNAME("connection_failed"));
  195. }
  196. close_connection();
  197. return true;
  198. }
  199. ENetConnection::Event event;
  200. ENetConnection::EventType ret = hosts[0]->service(0, event);
  201. if (ret == ENetConnection::EVENT_ERROR) {
  202. return true;
  203. }
  204. switch (ret) {
  205. case ENetConnection::EVENT_CONNECT: {
  206. connection_status = CONNECTION_CONNECTED;
  207. emit_signal(SNAME("peer_connected"), 1);
  208. emit_signal(SNAME("connection_succeeded"));
  209. return false;
  210. }
  211. case ENetConnection::EVENT_DISCONNECT: {
  212. if (connection_status == CONNECTION_CONNECTED) {
  213. // Client just disconnected from server.
  214. emit_signal(SNAME("server_disconnected"));
  215. } else {
  216. emit_signal(SNAME("connection_failed"));
  217. }
  218. close_connection();
  219. return true;
  220. }
  221. case ENetConnection::EVENT_RECEIVE: {
  222. if (event.channel_id == SYSCH_CONFIG) {
  223. // Config message
  224. if (event.packet->dataLength != 8) {
  225. _destroy_unused(event.packet);
  226. ERR_FAIL_V(false);
  227. }
  228. int msg = decode_uint32(&event.packet->data[0]);
  229. int id = decode_uint32(&event.packet->data[4]);
  230. switch (msg) {
  231. case SYSMSG_ADD_PEER: {
  232. peers[id] = Ref<ENetPacketPeer>();
  233. emit_signal(SNAME("peer_connected"), id);
  234. } break;
  235. case SYSMSG_REMOVE_PEER: {
  236. peers.erase(id);
  237. emit_signal(SNAME("peer_disconnected"), id);
  238. } break;
  239. }
  240. _destroy_unused(event.packet);
  241. } else {
  242. if (event.packet->dataLength < 8) {
  243. _destroy_unused(event.packet);
  244. ERR_FAIL_V_MSG(false, "Invalid packet size");
  245. }
  246. uint32_t source = decode_uint32(&event.packet->data[0]);
  247. Packet packet;
  248. packet.packet = event.packet;
  249. packet.from = source;
  250. packet.channel = event.channel_id;
  251. packet.packet->referenceCount++;
  252. incoming_packets.push_back(packet);
  253. // Destroy packet later
  254. }
  255. return false;
  256. }
  257. default:
  258. return true;
  259. }
  260. }
  261. bool ENetMultiplayerPeer::_poll_mesh() {
  262. for (const KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  263. if (!(E.value->is_active())) {
  264. emit_signal(SNAME("peer_disconnected"), E.key);
  265. peers.erase(E.key);
  266. if (hosts.has(E.key)) {
  267. hosts.erase(E.key);
  268. }
  269. }
  270. }
  271. bool should_stop = true;
  272. for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
  273. ENetConnection::Event event;
  274. ENetConnection::EventType ret = E.value->service(0, event);
  275. if (ret == ENetConnection::EVENT_ERROR) {
  276. if (peers.has(E.key)) {
  277. emit_signal(SNAME("peer_disconnected"), E.key);
  278. peers.erase(E.key);
  279. }
  280. hosts.erase(E.key);
  281. continue;
  282. }
  283. switch (ret) {
  284. case ENetConnection::EVENT_CONNECT:
  285. should_stop = false;
  286. event.peer->reset();
  287. break;
  288. case ENetConnection::EVENT_DISCONNECT:
  289. should_stop = false;
  290. if (peers.has(E.key)) {
  291. emit_signal(SNAME("peer_disconnected"), E.key);
  292. peers.erase(E.key);
  293. }
  294. hosts.erase(E.key);
  295. break;
  296. case ENetConnection::EVENT_RECEIVE: {
  297. should_stop = false;
  298. if (event.packet->dataLength < 8) {
  299. _destroy_unused(event.packet);
  300. ERR_CONTINUE_MSG(true, "Invalid packet size");
  301. }
  302. Packet packet;
  303. packet.packet = event.packet;
  304. packet.from = E.key;
  305. packet.channel = event.channel_id;
  306. packet.packet->referenceCount++;
  307. incoming_packets.push_back(packet);
  308. } break;
  309. default:
  310. break; // Nothing to do
  311. }
  312. }
  313. return should_stop;
  314. }
  315. void ENetMultiplayerPeer::poll() {
  316. ERR_FAIL_COND_MSG(!_is_active(), "The multiplayer instance isn't currently active.");
  317. _pop_current_packet();
  318. while (true) {
  319. switch (active_mode) {
  320. case MODE_CLIENT:
  321. if (_poll_client()) {
  322. return;
  323. }
  324. break;
  325. case MODE_SERVER:
  326. if (_poll_server()) {
  327. return;
  328. }
  329. break;
  330. case MODE_MESH:
  331. if (_poll_mesh()) {
  332. return;
  333. }
  334. break;
  335. default:
  336. return;
  337. }
  338. }
  339. }
  340. bool ENetMultiplayerPeer::is_server() const {
  341. return active_mode == MODE_SERVER;
  342. }
  343. void ENetMultiplayerPeer::close_connection(uint32_t wait_usec) {
  344. if (!_is_active()) {
  345. return;
  346. }
  347. _pop_current_packet();
  348. bool peers_disconnected = false;
  349. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  350. if (E.value.is_valid() && E.value->get_state() == ENetPacketPeer::STATE_CONNECTED) {
  351. E.value->peer_disconnect_now(unique_id);
  352. peers_disconnected = true;
  353. }
  354. }
  355. if (peers_disconnected) {
  356. for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
  357. E.value->flush();
  358. }
  359. if (wait_usec > 0) {
  360. OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send
  361. }
  362. }
  363. active_mode = MODE_NONE;
  364. incoming_packets.clear();
  365. peers.clear();
  366. hosts.clear();
  367. unique_id = 0;
  368. connection_status = CONNECTION_DISCONNECTED;
  369. set_refuse_new_connections(false);
  370. }
  371. int ENetMultiplayerPeer::get_available_packet_count() const {
  372. return incoming_packets.size();
  373. }
  374. Error ENetMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  375. ERR_FAIL_COND_V_MSG(incoming_packets.size() == 0, ERR_UNAVAILABLE, "No incoming packets available.");
  376. _pop_current_packet();
  377. current_packet = incoming_packets.front()->get();
  378. incoming_packets.pop_front();
  379. *r_buffer = (const uint8_t *)(&current_packet.packet->data[8]);
  380. r_buffer_size = current_packet.packet->dataLength - 8;
  381. return OK;
  382. }
  383. Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  384. ERR_FAIL_COND_V_MSG(!_is_active(), ERR_UNCONFIGURED, "The multiplayer instance isn't currently active.");
  385. ERR_FAIL_COND_V_MSG(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client.");
  386. ERR_FAIL_COND_V_MSG(target_peer != 0 && !peers.has(ABS(target_peer)), ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer));
  387. ERR_FAIL_COND_V(active_mode == MODE_CLIENT && !peers.has(1), ERR_BUG);
  388. int packet_flags = 0;
  389. int channel = SYSCH_RELIABLE;
  390. int transfer_channel = get_transfer_channel();
  391. if (transfer_channel > 0) {
  392. channel = SYSCH_MAX + transfer_channel - 1;
  393. } else {
  394. switch (get_transfer_mode()) {
  395. case Multiplayer::TRANSFER_MODE_UNRELIABLE: {
  396. packet_flags = ENET_PACKET_FLAG_UNSEQUENCED;
  397. channel = SYSCH_UNRELIABLE;
  398. } break;
  399. case Multiplayer::TRANSFER_MODE_UNRELIABLE_ORDERED: {
  400. packet_flags = 0;
  401. channel = SYSCH_UNRELIABLE;
  402. } break;
  403. case Multiplayer::TRANSFER_MODE_RELIABLE: {
  404. packet_flags = ENET_PACKET_FLAG_RELIABLE;
  405. channel = SYSCH_RELIABLE;
  406. } break;
  407. }
  408. }
  409. ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size + 8, packet_flags);
  410. encode_uint32(unique_id, &packet->data[0]); // Source ID
  411. encode_uint32(target_peer, &packet->data[4]); // Dest ID
  412. memcpy(&packet->data[8], p_buffer, p_buffer_size);
  413. if (is_server()) {
  414. if (target_peer == 0) {
  415. hosts[0]->broadcast(channel, packet);
  416. } else if (target_peer < 0) {
  417. // Send to all but one and make copies for sending.
  418. int exclude = -target_peer;
  419. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  420. if (E.key == exclude) {
  421. continue;
  422. }
  423. E.value->send(channel, packet);
  424. }
  425. _destroy_unused(packet);
  426. } else {
  427. peers[target_peer]->send(channel, packet);
  428. }
  429. ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG);
  430. hosts[0]->flush();
  431. } else if (active_mode == MODE_CLIENT) {
  432. peers[1]->send(channel, packet); // Send to server for broadcast.
  433. ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG);
  434. hosts[0]->flush();
  435. } else {
  436. if (target_peer <= 0) {
  437. int exclude = ABS(target_peer);
  438. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  439. if (E.key == exclude) {
  440. continue;
  441. }
  442. E.value->send(channel, packet);
  443. ERR_CONTINUE(!hosts.has(E.key));
  444. hosts[E.key]->flush();
  445. }
  446. _destroy_unused(packet);
  447. } else {
  448. peers[target_peer]->send(channel, packet);
  449. ERR_FAIL_COND_V(!hosts.has(target_peer), ERR_BUG);
  450. hosts[target_peer]->flush();
  451. }
  452. }
  453. return OK;
  454. }
  455. int ENetMultiplayerPeer::get_max_packet_size() const {
  456. return 1 << 24; // Anything is good
  457. }
  458. void ENetMultiplayerPeer::_pop_current_packet() {
  459. if (current_packet.packet) {
  460. current_packet.packet->referenceCount--;
  461. _destroy_unused(current_packet.packet);
  462. current_packet.packet = nullptr;
  463. current_packet.from = 0;
  464. current_packet.channel = -1;
  465. }
  466. }
  467. MultiplayerPeer::ConnectionStatus ENetMultiplayerPeer::get_connection_status() const {
  468. return connection_status;
  469. }
  470. int ENetMultiplayerPeer::get_unique_id() const {
  471. ERR_FAIL_COND_V_MSG(!_is_active(), 0, "The multiplayer instance isn't currently active.");
  472. return unique_id;
  473. }
  474. void ENetMultiplayerPeer::set_refuse_new_connections(bool p_enabled) {
  475. #ifdef GODOT_ENET
  476. if (_is_active()) {
  477. for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
  478. E.value->refuse_new_connections(p_enabled);
  479. }
  480. }
  481. #endif
  482. MultiplayerPeer::set_refuse_new_connections(p_enabled);
  483. }
  484. void ENetMultiplayerPeer::set_server_relay_enabled(bool p_enabled) {
  485. ERR_FAIL_COND_MSG(_is_active(), "Server relaying can't be toggled while the multiplayer instance is active.");
  486. server_relay = p_enabled;
  487. }
  488. bool ENetMultiplayerPeer::is_server_relay_enabled() const {
  489. return server_relay;
  490. }
  491. Ref<ENetConnection> ENetMultiplayerPeer::get_host() const {
  492. ERR_FAIL_COND_V(!_is_active(), nullptr);
  493. ERR_FAIL_COND_V(active_mode == MODE_MESH, nullptr);
  494. return hosts[0];
  495. }
  496. Ref<ENetPacketPeer> ENetMultiplayerPeer::get_peer(int p_id) const {
  497. ERR_FAIL_COND_V(!_is_active(), nullptr);
  498. ERR_FAIL_COND_V(!peers.has(p_id), nullptr);
  499. ERR_FAIL_COND_V(active_mode == MODE_CLIENT && p_id != 1, nullptr);
  500. return peers[p_id];
  501. }
  502. void ENetMultiplayerPeer::_destroy_unused(ENetPacket *p_packet) {
  503. if (p_packet->referenceCount == 0) {
  504. enet_packet_destroy(p_packet);
  505. }
  506. }
  507. void ENetMultiplayerPeer::_relay(int p_from, int p_to, enet_uint8 p_channel, ENetPacket *p_packet) {
  508. if (p_to == 0) {
  509. // Re-send to everyone but sender :|
  510. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  511. if (E.key == p_from) {
  512. continue;
  513. }
  514. E.value->send(p_channel, p_packet);
  515. }
  516. } else if (p_to < 0) {
  517. // Re-send to everyone but excluded and sender.
  518. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  519. if (E.key == p_from || E.key == -p_to) { // Do not resend to self, also do not send to excluded
  520. continue;
  521. }
  522. E.value->send(p_channel, p_packet);
  523. }
  524. } else {
  525. // To someone else, specifically
  526. ERR_FAIL_COND(!peers.has(p_to));
  527. ENetPacket *packet = enet_packet_create(p_packet->data, p_packet->dataLength, p_packet->flags);
  528. peers[p_to]->send(p_channel, packet);
  529. }
  530. }
  531. void ENetMultiplayerPeer::_notify_peers(int p_id, bool p_connected) {
  532. if (p_connected) {
  533. ERR_FAIL_COND(!peers.has(p_id));
  534. // Someone connected, notify all the peers available.
  535. Ref<ENetPacketPeer> peer = peers[p_id];
  536. ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
  537. encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
  538. encode_uint32(p_id, &packet->data[4]);
  539. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  540. if (E.key == p_id) {
  541. continue;
  542. }
  543. // Send new peer to existing peer.
  544. E.value->send(SYSCH_CONFIG, packet);
  545. // Send existing peer to new peer.
  546. // This packet will be automatically destroyed by ENet after send.
  547. ENetPacket *packet2 = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
  548. encode_uint32(SYSMSG_ADD_PEER, &packet2->data[0]);
  549. encode_uint32(E.key, &packet2->data[4]);
  550. peer->send(SYSCH_CONFIG, packet2);
  551. }
  552. _destroy_unused(packet);
  553. } else {
  554. // Server just received a client disconnect and is in relay mode, notify everyone else.
  555. ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
  556. encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
  557. encode_uint32(p_id, &packet->data[4]);
  558. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  559. if (E.key == p_id) {
  560. continue;
  561. }
  562. E.value->send(SYSCH_CONFIG, packet);
  563. }
  564. _destroy_unused(packet);
  565. }
  566. }
  567. void ENetMultiplayerPeer::_bind_methods() {
  568. ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetMultiplayerPeer::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0));
  569. ClassDB::bind_method(D_METHOD("create_client", "address", "port", "channel_count", "in_bandwidth", "out_bandwidth", "local_port"), &ENetMultiplayerPeer::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0), DEFVAL(0));
  570. ClassDB::bind_method(D_METHOD("create_mesh", "unique_id"), &ENetMultiplayerPeer::create_mesh);
  571. ClassDB::bind_method(D_METHOD("add_mesh_peer", "peer_id", "host"), &ENetMultiplayerPeer::add_mesh_peer);
  572. ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &ENetMultiplayerPeer::close_connection, DEFVAL(100));
  573. ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &ENetMultiplayerPeer::set_bind_ip);
  574. ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &ENetMultiplayerPeer::set_server_relay_enabled);
  575. ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &ENetMultiplayerPeer::is_server_relay_enabled);
  576. ClassDB::bind_method(D_METHOD("get_host"), &ENetMultiplayerPeer::get_host);
  577. ClassDB::bind_method(D_METHOD("get_peer", "id"), &ENetMultiplayerPeer::get_peer);
  578. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled");
  579. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "host", PROPERTY_HINT_RESOURCE_TYPE, "ENetConnection", PROPERTY_USAGE_NONE), "", "get_host");
  580. }
  581. ENetMultiplayerPeer::ENetMultiplayerPeer() {
  582. bind_ip = IPAddress("*");
  583. }
  584. ENetMultiplayerPeer::~ENetMultiplayerPeer() {
  585. if (_is_active()) {
  586. close_connection();
  587. }
  588. }
  589. // Sets IP for ENet to bind when using create_server or create_client
  590. // if no IP is set, then ENet bind to ENET_HOST_ANY
  591. void ENetMultiplayerPeer::set_bind_ip(const IPAddress &p_ip) {
  592. ERR_FAIL_COND_MSG(!p_ip.is_valid() && !p_ip.is_wildcard(), vformat("Invalid bind IP address: %s", String(p_ip)));
  593. bind_ip = p_ip;
  594. }