enet.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. /**
  2. *
  3. * Copyright (C) 2014 by Leaf Corcoran
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. * THE SOFTWARE.
  22. */
  23. #ifdef _WIN32
  24. #define NOMINMAX
  25. #endif
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <math.h>
  29. #include <stdint.h>
  30. #include <cstdio>
  31. #include <cstddef>
  32. #include <algorithm>
  33. extern "C" {
  34. #define LUA_COMPAT_ALL
  35. #include "lua.h"
  36. #include "lualib.h"
  37. #include "lauxlib.h"
  38. #include <enet/enet.h>
  39. }
  40. #define check_host(l, idx)\
  41. *(ENetHost**)luaL_checkudata(l, idx, "enet_host")
  42. #define check_peer(l, idx)\
  43. *(ENetPeer**)luaL_checkudata(l, idx, "enet_peer")
  44. /**
  45. * Parse address string, eg:
  46. * *:5959
  47. * 127.0.0.1:*
  48. * website.com:8080
  49. */
  50. static void parse_address(lua_State *l, const char *addr_str, ENetAddress *address) {
  51. int host_i = 0, port_i = 0;
  52. char host_str[128] = {0};
  53. char port_str[32] = {0};
  54. int scanning_port = 0;
  55. char *c = (char *)addr_str;
  56. while (*c != 0) {
  57. if (host_i >= 128 || port_i >= 32 ) luaL_error(l, "Hostname too long");
  58. if (scanning_port) {
  59. port_str[port_i++] = *c;
  60. } else {
  61. if (*c == ':') {
  62. scanning_port = 1;
  63. } else {
  64. host_str[host_i++] = *c;
  65. }
  66. }
  67. c++;
  68. }
  69. host_str[host_i] = '\0';
  70. port_str[port_i] = '\0';
  71. if (host_i == 0) luaL_error(l, "Failed to parse address");
  72. if (port_i == 0) luaL_error(l, "Missing port in address");
  73. if (strcmp("*", host_str) == 0) {
  74. address->host = ENET_HOST_ANY;
  75. } else {
  76. if (enet_address_set_host(address, host_str) != 0) {
  77. luaL_error(l, "Failed to resolve host name");
  78. }
  79. }
  80. if (strcmp("*", port_str) == 0) {
  81. address->port = ENET_PORT_ANY;
  82. } else {
  83. address->port = atoi(port_str);
  84. }
  85. }
  86. /**
  87. * Find the index of a given peer for which we only have the pointer.
  88. */
  89. static size_t find_peer_index(lua_State *l, ENetHost *enet_host, ENetPeer *peer) {
  90. size_t peer_index;
  91. for (peer_index = 0; peer_index < enet_host->peerCount; peer_index++) {
  92. if (peer == &(enet_host->peers[peer_index]))
  93. return peer_index;
  94. }
  95. luaL_error (l, "enet: could not find peer id!");
  96. return peer_index;
  97. }
  98. // VS2013 doesn't support alignof
  99. #if defined(_MSC_VER) && _MSC_VER <= 1800
  100. #define ENET_ALIGNOF(x) __alignof(x)
  101. #else
  102. #define ENET_ALIGNOF(x) alignof(x)
  103. #endif
  104. static bool supports_full_lightuserdata(lua_State *L)
  105. {
  106. static bool checked = false;
  107. static bool supported = false;
  108. if (!checked)
  109. {
  110. lua_pushcclosure(L, [](lua_State* L) -> int
  111. {
  112. // Try to push pointer with all bits set.
  113. lua_pushlightuserdata(L, (void*)(~((size_t)0)));
  114. return 1;
  115. }, 0);
  116. supported = lua_pcall(L, 0, 1, 0) == 0;
  117. checked = true;
  118. lua_pop(L, 1);
  119. }
  120. return supported;
  121. }
  122. static uintptr_t compute_peer_key(lua_State *L, ENetPeer *peer)
  123. {
  124. // ENet peers are be allocated on the heap in an array. Lua numbers
  125. // (doubles) can store all possible integers up to 2^53. We can store
  126. // pointers that use more than 53 bits if their alignment is guaranteed to
  127. // be more than 1. For example an alignment requirement of 8 means we can
  128. // shift the pointer's bits by 3.
  129. // Please see these for the reason of this ternary operator:
  130. // * https://github.com/love2d/love/issues/1916
  131. // * https://github.com/love2d/love/commit/4ab9a1ce8c
  132. const size_t minalign = sizeof(void*) == 8 ? std::min(ENET_ALIGNOF(ENetPeer), ENET_ALIGNOF(std::max_align_t)) : 1;
  133. uintptr_t key = (uintptr_t) peer;
  134. if ((key & (minalign - 1)) != 0)
  135. {
  136. luaL_error(L, "Cannot push enet peer to Lua: unexpected alignment "
  137. "(pointer is %p but alignment should be %d)", peer, minalign);
  138. }
  139. static const size_t shift = (size_t) log2((double) minalign);
  140. return key >> shift;
  141. }
  142. static void push_peer_key(lua_State *L, uintptr_t key)
  143. {
  144. // If full 64-bit lightuserdata is supported, always use that. Otherwise,
  145. // if the key is smaller than 2^53 (which is integer precision for double
  146. // datatype), then push number. Otherwise, throw error.
  147. if (supports_full_lightuserdata(L))
  148. lua_pushlightuserdata(L, (void*) key);
  149. else if (key > 0x20000000000000ULL) // 2^53
  150. luaL_error(L, "Cannot push enet peer to Lua: pointer value %p is too large", key);
  151. else
  152. lua_pushnumber(L, (lua_Number) key);
  153. }
  154. static void push_peer(lua_State *l, ENetPeer *peer) {
  155. uintptr_t key = compute_peer_key(l, peer);
  156. // try to find in peer table
  157. lua_getfield(l, LUA_REGISTRYINDEX, "enet_peers");
  158. push_peer_key(l, key);
  159. lua_gettable(l, -2);
  160. if (lua_isnil(l, -1)) {
  161. // printf("creating new peer\n");
  162. lua_pop(l, 1);
  163. *(ENetPeer**)lua_newuserdata(l, sizeof(void*)) = peer;
  164. luaL_getmetatable(l, "enet_peer");
  165. lua_setmetatable(l, -2);
  166. push_peer_key(l, key);
  167. lua_pushvalue(l, -2);
  168. lua_settable(l, -4);
  169. }
  170. lua_remove(l, -2); // remove enet_peers
  171. }
  172. static void push_event(lua_State *l, ENetEvent *event) {
  173. lua_newtable(l); // event table
  174. if (event->peer) {
  175. push_peer(l, event->peer);
  176. lua_setfield(l, -2, "peer");
  177. }
  178. switch (event->type) {
  179. case ENET_EVENT_TYPE_CONNECT:
  180. lua_pushinteger(l, event->data);
  181. lua_setfield(l, -2, "data");
  182. lua_pushstring(l, "connect");
  183. break;
  184. case ENET_EVENT_TYPE_DISCONNECT:
  185. lua_pushinteger(l, event->data);
  186. lua_setfield(l, -2, "data");
  187. lua_pushstring(l, "disconnect");
  188. break;
  189. case ENET_EVENT_TYPE_RECEIVE:
  190. lua_pushlstring(l, (const char *)event->packet->data, event->packet->dataLength);
  191. lua_setfield(l, -2, "data");
  192. lua_pushinteger(l, event->channelID);
  193. lua_setfield(l, -2, "channel");
  194. lua_pushstring(l, "receive");
  195. enet_packet_destroy(event->packet);
  196. break;
  197. case ENET_EVENT_TYPE_NONE:
  198. lua_pushstring(l, "none");
  199. break;
  200. }
  201. lua_setfield(l, -2, "type");
  202. }
  203. /**
  204. * Read a packet off the stack as a string
  205. * idx is position of string
  206. */
  207. static ENetPacket *read_packet(lua_State *l, int idx, enet_uint8 *channel_id) {
  208. size_t size;
  209. int argc = lua_gettop(l);
  210. const void *data = luaL_checklstring(l, idx, &size);
  211. ENetPacket *packet;
  212. enet_uint32 flags = ENET_PACKET_FLAG_RELIABLE;
  213. *channel_id = 0;
  214. if (argc >= idx+2 && !lua_isnil(l, idx+2)) {
  215. const char *flag_str = luaL_checkstring(l, idx+2);
  216. if (strcmp("unsequenced", flag_str) == 0) {
  217. flags = ENET_PACKET_FLAG_UNSEQUENCED;
  218. } else if (strcmp("reliable", flag_str) == 0) {
  219. flags = ENET_PACKET_FLAG_RELIABLE;
  220. } else if (strcmp("unreliable", flag_str) == 0) {
  221. flags = 0;
  222. } else {
  223. luaL_error(l, "Unknown packet flag: %s", flag_str);
  224. }
  225. }
  226. if (argc >= idx+1 && !lua_isnil(l, idx+1)) {
  227. *channel_id = (int) luaL_checknumber(l, idx+1);
  228. }
  229. packet = enet_packet_create(data, size, flags);
  230. if (packet == NULL) {
  231. luaL_error(l, "Failed to create packet");
  232. }
  233. return packet;
  234. }
  235. /**
  236. * Create a new host
  237. * Args:
  238. * address (nil for client)
  239. * [peer_count = 64]
  240. * [channel_count = 1]
  241. * [in_bandwidth = 0]
  242. * [out_bandwidth = 0]
  243. */
  244. static int host_create(lua_State *l) {
  245. ENetHost *host;
  246. size_t peer_count = 64, channel_count = 1;
  247. enet_uint32 in_bandwidth = 0, out_bandwidth = 0;
  248. int have_address = 1;
  249. ENetAddress address;
  250. if (lua_gettop(l) == 0 || lua_isnil(l, 1)) {
  251. have_address = 0;
  252. } else {
  253. parse_address(l, luaL_checkstring(l, 1), &address);
  254. }
  255. switch (lua_gettop(l)) {
  256. case 5:
  257. if (!lua_isnil(l, 5)) out_bandwidth = (int) luaL_checknumber(l, 5);
  258. case 4:
  259. if (!lua_isnil(l, 4)) in_bandwidth = (int) luaL_checknumber(l, 4);
  260. case 3:
  261. if (!lua_isnil(l, 3)) channel_count = (int) luaL_checknumber(l, 3);
  262. case 2:
  263. if (!lua_isnil(l, 2)) peer_count = (int) luaL_checknumber(l, 2);
  264. }
  265. // printf("host create, peers=%d, channels=%d, in=%d, out=%d\n",
  266. // peer_count, channel_count, in_bandwidth, out_bandwidth);
  267. host = enet_host_create(have_address ? &address : NULL, peer_count,
  268. channel_count, in_bandwidth, out_bandwidth);
  269. if (host == NULL) {
  270. lua_pushnil (l);
  271. lua_pushstring(l, "enet: failed to create host (already listening?)");
  272. return 2;
  273. }
  274. *(ENetHost**)lua_newuserdata(l, sizeof(void*)) = host;
  275. luaL_getmetatable(l, "enet_host");
  276. lua_setmetatable(l, -2);
  277. return 1;
  278. }
  279. static int linked_version(lua_State *l) {
  280. lua_pushfstring(l, "%d.%d.%d",
  281. ENET_VERSION_GET_MAJOR(enet_linked_version()),
  282. ENET_VERSION_GET_MINOR(enet_linked_version()),
  283. ENET_VERSION_GET_PATCH(enet_linked_version()));
  284. return 1;
  285. }
  286. /**
  287. * Serice a host
  288. * Args:
  289. * timeout
  290. *
  291. * Return
  292. * nil on no event
  293. * an event table on event
  294. */
  295. static int host_service(lua_State *l) {
  296. ENetHost *host = check_host(l, 1);
  297. if (!host) {
  298. return luaL_error(l, "Tried to index a nil host!");
  299. }
  300. ENetEvent event;
  301. int timeout = 0, out;
  302. if (lua_gettop(l) > 1)
  303. timeout = (int) luaL_checknumber(l, 2);
  304. out = enet_host_service(host, &event, timeout);
  305. if (out == 0) return 0;
  306. if (out < 0) return luaL_error(l, "Error during service");
  307. push_event(l, &event);
  308. return 1;
  309. }
  310. /**
  311. * Dispatch a single event if available
  312. */
  313. static int host_check_events(lua_State *l) {
  314. ENetHost *host = check_host(l, 1);
  315. if (!host) {
  316. return luaL_error(l, "Tried to index a nil host!");
  317. }
  318. ENetEvent event;
  319. int out = enet_host_check_events(host, &event);
  320. if (out == 0) return 0;
  321. if (out < 0) return luaL_error(l, "Error checking event");
  322. push_event(l, &event);
  323. return 1;
  324. }
  325. /**
  326. * Enables an adaptive order-2 PPM range coder for the transmitted data of
  327. * all peers.
  328. */
  329. static int host_compress_with_range_coder(lua_State *l) {
  330. ENetHost *host = check_host(l, 1);
  331. if (!host) {
  332. return luaL_error(l, "Tried to index a nil host!");
  333. }
  334. int result = enet_host_compress_with_range_coder (host);
  335. if (result == 0) {
  336. lua_pushboolean (l, 1);
  337. } else {
  338. lua_pushboolean (l, 0);
  339. }
  340. return 1;
  341. }
  342. /**
  343. * Connect a host to an address
  344. * Args:
  345. * the address
  346. * [channel_count = 1]
  347. * [data = 0]
  348. */
  349. static int host_connect(lua_State *l) {
  350. ENetHost *host = check_host(l, 1);
  351. if (!host) {
  352. return luaL_error(l, "Tried to index a nil host!");
  353. }
  354. ENetAddress address;
  355. ENetPeer *peer;
  356. enet_uint32 data = 0;
  357. size_t channel_count = 1;
  358. parse_address(l, luaL_checkstring(l, 2), &address);
  359. switch (lua_gettop(l)) {
  360. case 4:
  361. if (!lua_isnil(l, 4)) data = (int) luaL_checknumber(l, 4);
  362. case 3:
  363. if (!lua_isnil(l, 3)) channel_count = (int) luaL_checknumber(l, 3);
  364. }
  365. // printf("host connect, channels=%d, data=%d\n", channel_count, data);
  366. peer = enet_host_connect(host, &address, channel_count, data);
  367. if (peer == NULL) {
  368. return luaL_error(l, "Failed to create peer");
  369. }
  370. push_peer(l, peer);
  371. return 1;
  372. }
  373. static int host_flush(lua_State *l) {
  374. ENetHost *host = check_host(l, 1);
  375. if (!host) {
  376. return luaL_error(l, "Tried to index a nil host!");
  377. }
  378. enet_host_flush(host);
  379. return 0;
  380. }
  381. static int host_broadcast(lua_State *l) {
  382. ENetHost *host = check_host(l, 1);
  383. if (!host) {
  384. return luaL_error(l, "Tried to index a nil host!");
  385. }
  386. enet_uint8 channel_id;
  387. ENetPacket *packet = read_packet(l, 2, &channel_id);
  388. enet_host_broadcast(host, channel_id, packet);
  389. return 0;
  390. }
  391. // Args: limit:number
  392. static int host_channel_limit(lua_State *l) {
  393. ENetHost *host = check_host(l, 1);
  394. if (!host) {
  395. return luaL_error(l, "Tried to index a nil host!");
  396. }
  397. int limit = (int) luaL_checknumber(l, 2);
  398. enet_host_channel_limit(host, limit);
  399. return 0;
  400. }
  401. static int host_bandwidth_limit(lua_State *l) {
  402. ENetHost *host = check_host(l, 1);
  403. if (!host) {
  404. return luaL_error(l, "Tried to index a nil host!");
  405. }
  406. enet_uint32 in_bandwidth = (int) luaL_checknumber(l, 2);
  407. enet_uint32 out_bandwidth = (int) luaL_checknumber(l, 2);
  408. enet_host_bandwidth_limit(host, in_bandwidth, out_bandwidth);
  409. return 0;
  410. }
  411. static int host_get_socket_address(lua_State *l) {
  412. ENetHost *host = check_host(l, 1);
  413. if (!host) {
  414. return luaL_error(l, "Tried to index a nil host!");
  415. }
  416. ENetAddress address;
  417. enet_socket_get_address (host->socket, &address);
  418. lua_pushfstring(l, "%d.%d.%d.%d:%d",
  419. ((address.host) & 0xFF),
  420. ((address.host >> 8) & 0xFF),
  421. ((address.host >> 16) & 0xFF),
  422. (address.host >> 24& 0xFF),
  423. address.port);
  424. return 1;
  425. }
  426. static int host_total_sent_data(lua_State *l) {
  427. ENetHost *host = check_host(l, 1);
  428. if (!host) {
  429. return luaL_error(l, "Tried to index a nil host!");
  430. }
  431. lua_pushinteger (l, host->totalSentData);
  432. return 1;
  433. }
  434. static int host_total_received_data(lua_State *l) {
  435. ENetHost *host = check_host(l, 1);
  436. if (!host) {
  437. return luaL_error(l, "Tried to index a nil host!");
  438. }
  439. lua_pushinteger (l, host->totalReceivedData);
  440. return 1;
  441. }
  442. static int host_service_time(lua_State *l) {
  443. ENetHost *host = check_host(l, 1);
  444. if (!host) {
  445. return luaL_error(l, "Tried to index a nil host!");
  446. }
  447. lua_pushinteger (l, host->serviceTime);
  448. return 1;
  449. }
  450. static int host_peer_count(lua_State *l) {
  451. ENetHost *host = check_host(l, 1);
  452. if (!host) {
  453. return luaL_error(l, "Tried to index a nil host!");
  454. }
  455. lua_pushinteger (l, host->peerCount);
  456. return 1;
  457. }
  458. static int host_get_peer(lua_State *l) {
  459. ENetHost *host = check_host(l, 1);
  460. if (!host) {
  461. return luaL_error(l, "Tried to index a nil host!");
  462. }
  463. int peer_index = (int) luaL_checknumber(l, 2) - 1;
  464. if (peer_index < 0 || ((size_t) peer_index) >= host->peerCount) {
  465. luaL_argerror (l, 2, "Invalid peer index");
  466. }
  467. ENetPeer *peer = &(host->peers[peer_index]);
  468. push_peer (l, peer);
  469. return 1;
  470. }
  471. static int host_gc(lua_State *l) {
  472. // We have to manually grab the userdata so that we can set it to NULL.
  473. ENetHost** host = (ENetHost**)luaL_checkudata(l, 1, "enet_host");
  474. // We don't want to crash by destroying a non-existant host.
  475. if (*host) {
  476. enet_host_destroy(*host);
  477. }
  478. *host = NULL;
  479. return 0;
  480. }
  481. static int peer_tostring(lua_State *l) {
  482. ENetPeer *peer = check_peer(l, 1);
  483. char host_str[128];
  484. enet_address_get_host_ip(&peer->address, host_str, 128);
  485. lua_pushstring(l, host_str);
  486. lua_pushstring(l, ":");
  487. lua_pushinteger(l, peer->address.port);
  488. lua_concat(l, 3);
  489. return 1;
  490. }
  491. static int peer_ping(lua_State *l) {
  492. ENetPeer *peer = check_peer(l, 1);
  493. enet_peer_ping(peer);
  494. return 0;
  495. }
  496. static int peer_throttle_configure(lua_State *l) {
  497. ENetPeer *peer = check_peer(l, 1);
  498. enet_uint32 interval = (int) luaL_checknumber(l, 2);
  499. enet_uint32 acceleration = (int) luaL_checknumber(l, 3);
  500. enet_uint32 deceleration = (int) luaL_checknumber(l, 4);
  501. enet_peer_throttle_configure(peer, interval, acceleration, deceleration);
  502. return 0;
  503. }
  504. static int peer_round_trip_time(lua_State *l) {
  505. ENetPeer *peer = check_peer(l, 1);
  506. if (lua_gettop(l) > 1) {
  507. enet_uint32 round_trip_time = (int) luaL_checknumber(l, 2);
  508. peer->roundTripTime = round_trip_time;
  509. }
  510. lua_pushinteger (l, peer->roundTripTime);
  511. return 1;
  512. }
  513. static int peer_last_round_trip_time(lua_State *l) {
  514. ENetPeer *peer = check_peer(l, 1);
  515. if (lua_gettop(l) > 1) {
  516. enet_uint32 round_trip_time = (int) luaL_checknumber(l, 2);
  517. peer->lastRoundTripTime = round_trip_time;
  518. }
  519. lua_pushinteger (l, peer->lastRoundTripTime);
  520. return 1;
  521. }
  522. static int peer_ping_interval(lua_State *l) {
  523. ENetPeer *peer = check_peer(l, 1);
  524. if (lua_gettop(l) > 1) {
  525. enet_uint32 interval = (int) luaL_checknumber(l, 2);
  526. enet_peer_ping_interval (peer, interval);
  527. }
  528. lua_pushinteger (l, peer->pingInterval);
  529. return 1;
  530. }
  531. static int peer_timeout(lua_State *l) {
  532. ENetPeer *peer = check_peer(l, 1);
  533. enet_uint32 timeout_limit = 0;
  534. enet_uint32 timeout_minimum = 0;
  535. enet_uint32 timeout_maximum = 0;
  536. switch (lua_gettop(l)) {
  537. case 4:
  538. if (!lua_isnil(l, 4)) timeout_maximum = (int) luaL_checknumber(l, 4);
  539. case 3:
  540. if (!lua_isnil(l, 3)) timeout_minimum = (int) luaL_checknumber(l, 3);
  541. case 2:
  542. if (!lua_isnil(l, 2)) timeout_limit = (int) luaL_checknumber(l, 2);
  543. }
  544. enet_peer_timeout (peer, timeout_limit, timeout_minimum, timeout_maximum);
  545. lua_pushinteger (l, peer->timeoutLimit);
  546. lua_pushinteger (l, peer->timeoutMinimum);
  547. lua_pushinteger (l, peer->timeoutMaximum);
  548. return 3;
  549. }
  550. static int peer_disconnect(lua_State *l) {
  551. ENetPeer *peer = check_peer(l, 1);
  552. enet_uint32 data = lua_gettop(l) > 1 ? (int) luaL_checknumber(l, 2) : 0;
  553. enet_peer_disconnect(peer, data);
  554. return 0;
  555. }
  556. static int peer_disconnect_now(lua_State *l) {
  557. ENetPeer *peer = check_peer(l, 1);
  558. enet_uint32 data = lua_gettop(l) > 1 ? (int) luaL_checknumber(l, 2) : 0;
  559. enet_peer_disconnect_now(peer, data);
  560. return 0;
  561. }
  562. static int peer_disconnect_later(lua_State *l) {
  563. ENetPeer *peer = check_peer(l, 1);
  564. enet_uint32 data = lua_gettop(l) > 1 ? (int) luaL_checknumber(l, 2) : 0;
  565. enet_peer_disconnect_later(peer, data);
  566. return 0;
  567. }
  568. static int peer_index(lua_State *l) {
  569. ENetPeer *peer = check_peer(l, 1);
  570. size_t peer_index = find_peer_index (l, peer->host, peer);
  571. lua_pushinteger (l, peer_index + 1);
  572. return 1;
  573. }
  574. static int peer_state(lua_State *l) {
  575. ENetPeer *peer = check_peer(l, 1);
  576. switch (peer->state) {
  577. case (ENET_PEER_STATE_DISCONNECTED):
  578. lua_pushstring (l, "disconnected");
  579. break;
  580. case (ENET_PEER_STATE_CONNECTING):
  581. lua_pushstring (l, "connecting");
  582. break;
  583. case (ENET_PEER_STATE_ACKNOWLEDGING_CONNECT):
  584. lua_pushstring (l, "acknowledging_connect");
  585. break;
  586. case (ENET_PEER_STATE_CONNECTION_PENDING):
  587. lua_pushstring (l, "connection_pending");
  588. break;
  589. case (ENET_PEER_STATE_CONNECTION_SUCCEEDED):
  590. lua_pushstring (l, "connection_succeeded");
  591. break;
  592. case (ENET_PEER_STATE_CONNECTED):
  593. lua_pushstring (l, "connected");
  594. break;
  595. case (ENET_PEER_STATE_DISCONNECT_LATER):
  596. lua_pushstring (l, "disconnect_later");
  597. break;
  598. case (ENET_PEER_STATE_DISCONNECTING):
  599. lua_pushstring (l, "disconnecting");
  600. break;
  601. case (ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT):
  602. lua_pushstring (l, "acknowledging_disconnect");
  603. break;
  604. case (ENET_PEER_STATE_ZOMBIE):
  605. lua_pushstring (l, "zombie");
  606. break;
  607. default:
  608. lua_pushstring (l, "unknown");
  609. }
  610. return 1;
  611. }
  612. static int peer_connect_id(lua_State *l) {
  613. ENetPeer *peer = check_peer(l, 1);
  614. lua_pushinteger (l, peer->connectID);
  615. return 1;
  616. }
  617. static int peer_reset(lua_State *l) {
  618. ENetPeer *peer = check_peer(l, 1);
  619. enet_peer_reset(peer);
  620. return 0;
  621. }
  622. static int peer_receive(lua_State *l) {
  623. ENetPeer *peer = check_peer(l, 1);
  624. ENetPacket *packet;
  625. enet_uint8 channel_id = 0;
  626. if (lua_gettop(l) > 1) {
  627. channel_id = (int) luaL_checknumber(l, 2);
  628. }
  629. packet = enet_peer_receive(peer, &channel_id);
  630. if (packet == NULL) return 0;
  631. lua_pushlstring(l, (const char *)packet->data, packet->dataLength);
  632. lua_pushinteger(l, channel_id);
  633. enet_packet_destroy(packet);
  634. return 2;
  635. }
  636. /**
  637. * Send a lua string to a peer
  638. * Args:
  639. * packet data, string
  640. * channel id
  641. * flags ["reliable", nil]
  642. *
  643. */
  644. static int peer_send(lua_State *l) {
  645. ENetPeer *peer = check_peer(l, 1);
  646. enet_uint8 channel_id;
  647. ENetPacket *packet = read_packet(l, 2, &channel_id);
  648. // printf("sending, channel_id=%d\n", channel_id);
  649. int ret = enet_peer_send(peer, channel_id, packet);
  650. if (ret < 0) {
  651. enet_packet_destroy(packet);
  652. }
  653. lua_pushinteger(l, ret);
  654. return 1;
  655. }
  656. static const struct luaL_Reg enet_funcs [] = {
  657. {"host_create", host_create},
  658. {"linked_version", linked_version},
  659. {NULL, NULL}
  660. };
  661. static const struct luaL_Reg enet_host_funcs [] = {
  662. {"service", host_service},
  663. {"check_events", host_check_events},
  664. {"compress_with_range_coder", host_compress_with_range_coder},
  665. {"connect", host_connect},
  666. {"flush", host_flush},
  667. {"broadcast", host_broadcast},
  668. {"channel_limit", host_channel_limit},
  669. {"bandwidth_limit", host_bandwidth_limit},
  670. // Since ENetSocket isn't part of enet-lua, we should try to keep
  671. // naming conventions the same as the rest of the lib.
  672. {"get_socket_address", host_get_socket_address},
  673. // We need this function to free up our ports when needed!
  674. {"destroy", host_gc},
  675. // additional convenience functions (mostly accessors)
  676. {"total_sent_data", host_total_sent_data},
  677. {"total_received_data", host_total_received_data},
  678. {"service_time", host_service_time},
  679. {"peer_count", host_peer_count},
  680. {"get_peer", host_get_peer},
  681. {NULL, NULL}
  682. };
  683. static const struct luaL_Reg enet_peer_funcs [] = {
  684. {"disconnect", peer_disconnect},
  685. {"disconnect_now", peer_disconnect_now},
  686. {"disconnect_later", peer_disconnect_later},
  687. {"reset", peer_reset},
  688. {"ping", peer_ping},
  689. {"receive", peer_receive},
  690. {"send", peer_send},
  691. {"throttle_configure", peer_throttle_configure},
  692. {"ping_interval", peer_ping_interval},
  693. {"timeout", peer_timeout},
  694. // additional convenience functions to member variables
  695. {"index", peer_index},
  696. {"state", peer_state},
  697. {"connect_id", peer_connect_id},
  698. {"round_trip_time", peer_round_trip_time},
  699. {"last_round_trip_time", peer_last_round_trip_time},
  700. {NULL, NULL}
  701. };
  702. extern "C" {
  703. void luax_register(lua_State *L, const char *name, const luaL_Reg *l);
  704. }
  705. int luaopen_enet(lua_State *l) {
  706. enet_initialize();
  707. atexit(enet_deinitialize);
  708. // create metatables
  709. luaL_newmetatable(l, "enet_host");
  710. lua_newtable(l); // index
  711. luax_register(l, NULL, enet_host_funcs);
  712. lua_setfield(l, -2, "__index");
  713. lua_pushcfunction(l, host_gc);
  714. lua_setfield(l, -2, "__gc");
  715. luaL_newmetatable(l, "enet_peer");
  716. lua_newtable(l);
  717. luax_register(l, NULL, enet_peer_funcs);
  718. lua_setfield(l, -2, "__index");
  719. lua_pushcfunction(l, peer_tostring);
  720. lua_setfield(l, -2, "__tostring");
  721. // set up peer table
  722. lua_newtable(l);
  723. lua_newtable(l); // metatable
  724. lua_pushstring(l, "v");
  725. lua_setfield(l, -2, "__mode");
  726. lua_setmetatable(l, -2);
  727. lua_setfield(l, LUA_REGISTRYINDEX, "enet_peers");
  728. luax_register(l, nullptr, enet_funcs);
  729. // return the enet table created with luaL_register
  730. return 1;
  731. }