2
0

joypad_linux.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /*************************************************************************/
  2. /* joypad_linux.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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. #ifdef JOYDEV_ENABLED
  31. #include "joypad_linux.h"
  32. #include <errno.h>
  33. #include <fcntl.h>
  34. #include <linux/input.h>
  35. #include <unistd.h>
  36. #ifdef UDEV_ENABLED
  37. #include <libudev.h>
  38. #endif
  39. #define LONG_BITS (sizeof(long) * 8)
  40. #define test_bit(nr, addr) (((1UL << ((nr) % LONG_BITS)) & ((addr)[(nr) / LONG_BITS])) != 0)
  41. #define NBITS(x) ((((x)-1) / LONG_BITS) + 1)
  42. #ifdef UDEV_ENABLED
  43. static const char *ignore_str = "/dev/input/js";
  44. #endif
  45. JoypadLinux::Joypad::Joypad() {
  46. fd = -1;
  47. dpad = 0;
  48. devpath = "";
  49. for (int i = 0; i < MAX_ABS; i++) {
  50. abs_info[i] = NULL;
  51. }
  52. }
  53. JoypadLinux::Joypad::~Joypad() {
  54. for (int i = 0; i < MAX_ABS; i++) {
  55. if (abs_info[i]) {
  56. memdelete(abs_info[i]);
  57. }
  58. }
  59. }
  60. void JoypadLinux::Joypad::reset() {
  61. dpad = 0;
  62. fd = -1;
  63. InputDefault::JoyAxis jx;
  64. jx.min = -1;
  65. jx.value = 0.0f;
  66. for (int i = 0; i < MAX_ABS; i++) {
  67. abs_map[i] = -1;
  68. curr_axis[i] = jx;
  69. }
  70. }
  71. JoypadLinux::JoypadLinux(InputDefault *in) {
  72. exit_udev = false;
  73. input = in;
  74. joy_mutex = Mutex::create();
  75. joy_thread = Thread::create(joy_thread_func, this);
  76. }
  77. JoypadLinux::~JoypadLinux() {
  78. exit_udev = true;
  79. Thread::wait_to_finish(joy_thread);
  80. memdelete(joy_thread);
  81. memdelete(joy_mutex);
  82. close_joypad();
  83. }
  84. void JoypadLinux::joy_thread_func(void *p_user) {
  85. if (p_user) {
  86. JoypadLinux *joy = (JoypadLinux *)p_user;
  87. joy->run_joypad_thread();
  88. }
  89. }
  90. void JoypadLinux::run_joypad_thread() {
  91. #ifdef UDEV_ENABLED
  92. udev *_udev = udev_new();
  93. ERR_FAIL_COND(!_udev);
  94. enumerate_joypads(_udev);
  95. monitor_joypads(_udev);
  96. udev_unref(_udev);
  97. #else
  98. monitor_joypads();
  99. #endif
  100. }
  101. #ifdef UDEV_ENABLED
  102. void JoypadLinux::enumerate_joypads(udev *p_udev) {
  103. udev_enumerate *enumerate;
  104. udev_list_entry *devices, *dev_list_entry;
  105. udev_device *dev;
  106. enumerate = udev_enumerate_new(p_udev);
  107. udev_enumerate_add_match_subsystem(enumerate, "input");
  108. udev_enumerate_scan_devices(enumerate);
  109. devices = udev_enumerate_get_list_entry(enumerate);
  110. udev_list_entry_foreach(dev_list_entry, devices) {
  111. const char *path = udev_list_entry_get_name(dev_list_entry);
  112. dev = udev_device_new_from_syspath(p_udev, path);
  113. const char *devnode = udev_device_get_devnode(dev);
  114. if (devnode) {
  115. String devnode_str = devnode;
  116. if (devnode_str.find(ignore_str) == -1) {
  117. joy_mutex->lock();
  118. open_joypad(devnode);
  119. joy_mutex->unlock();
  120. }
  121. }
  122. udev_device_unref(dev);
  123. }
  124. udev_enumerate_unref(enumerate);
  125. }
  126. void JoypadLinux::monitor_joypads(udev *p_udev) {
  127. udev_device *dev = NULL;
  128. udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev");
  129. udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL);
  130. udev_monitor_enable_receiving(mon);
  131. int fd = udev_monitor_get_fd(mon);
  132. while (!exit_udev) {
  133. fd_set fds;
  134. struct timeval tv;
  135. int ret;
  136. FD_ZERO(&fds);
  137. FD_SET(fd, &fds);
  138. tv.tv_sec = 0;
  139. tv.tv_usec = 0;
  140. ret = select(fd + 1, &fds, NULL, NULL, &tv);
  141. /* Check if our file descriptor has received data. */
  142. if (ret > 0 && FD_ISSET(fd, &fds)) {
  143. /* Make the call to receive the device.
  144. select() ensured that this will not block. */
  145. dev = udev_monitor_receive_device(mon);
  146. if (dev && udev_device_get_devnode(dev) != 0) {
  147. joy_mutex->lock();
  148. String action = udev_device_get_action(dev);
  149. const char *devnode = udev_device_get_devnode(dev);
  150. if (devnode) {
  151. String devnode_str = devnode;
  152. if (devnode_str.find(ignore_str) == -1) {
  153. if (action == "add")
  154. open_joypad(devnode);
  155. else if (String(action) == "remove")
  156. close_joypad(get_joy_from_path(devnode));
  157. }
  158. }
  159. udev_device_unref(dev);
  160. joy_mutex->unlock();
  161. }
  162. }
  163. usleep(50000);
  164. }
  165. udev_monitor_unref(mon);
  166. }
  167. #endif
  168. void JoypadLinux::monitor_joypads() {
  169. while (!exit_udev) {
  170. joy_mutex->lock();
  171. for (int i = 0; i < 32; i++) {
  172. char fname[64];
  173. sprintf(fname, "/dev/input/event%d", i);
  174. if (attached_devices.find(fname) == -1) {
  175. open_joypad(fname);
  176. }
  177. }
  178. joy_mutex->unlock();
  179. usleep(1000000); // 1s
  180. }
  181. }
  182. int JoypadLinux::get_joy_from_path(String p_path) const {
  183. for (int i = 0; i < JOYPADS_MAX; i++) {
  184. if (joypads[i].devpath == p_path) {
  185. return i;
  186. }
  187. }
  188. return -2;
  189. }
  190. void JoypadLinux::close_joypad(int p_id) {
  191. if (p_id == -1) {
  192. for (int i = 0; i < JOYPADS_MAX; i++) {
  193. close_joypad(i);
  194. };
  195. return;
  196. } else if (p_id < 0)
  197. return;
  198. Joypad &joy = joypads[p_id];
  199. if (joy.fd != -1) {
  200. close(joy.fd);
  201. joy.fd = -1;
  202. attached_devices.remove(attached_devices.find(joy.devpath));
  203. input->joy_connection_changed(p_id, false, "");
  204. };
  205. }
  206. static String _hex_str(uint8_t p_byte) {
  207. static const char *dict = "0123456789abcdef";
  208. char ret[3];
  209. ret[2] = 0;
  210. ret[0] = dict[p_byte >> 4];
  211. ret[1] = dict[p_byte & 0xF];
  212. return ret;
  213. }
  214. void JoypadLinux::setup_joypad_properties(int p_id) {
  215. Joypad *joy = &joypads[p_id];
  216. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  217. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  218. int num_buttons = 0;
  219. int num_axes = 0;
  220. if ((ioctl(joy->fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  221. (ioctl(joy->fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  222. return;
  223. }
  224. for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
  225. if (test_bit(i, keybit)) {
  226. joy->key_map[i] = num_buttons++;
  227. }
  228. }
  229. for (int i = BTN_MISC; i < BTN_JOYSTICK; ++i) {
  230. if (test_bit(i, keybit)) {
  231. joy->key_map[i] = num_buttons++;
  232. }
  233. }
  234. for (int i = 0; i < ABS_MISC; ++i) {
  235. /* Skip hats */
  236. if (i == ABS_HAT0X) {
  237. i = ABS_HAT3Y;
  238. continue;
  239. }
  240. if (test_bit(i, absbit)) {
  241. joy->abs_map[i] = num_axes++;
  242. joy->abs_info[i] = memnew(input_absinfo);
  243. if (ioctl(joy->fd, EVIOCGABS(i), joy->abs_info[i]) < 0) {
  244. memdelete(joy->abs_info[i]);
  245. joy->abs_info[i] = NULL;
  246. }
  247. }
  248. }
  249. joy->force_feedback = false;
  250. joy->ff_effect_timestamp = 0;
  251. unsigned long ffbit[NBITS(FF_CNT)];
  252. if (ioctl(joy->fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) != -1) {
  253. if (test_bit(FF_RUMBLE, ffbit)) {
  254. joy->force_feedback = true;
  255. }
  256. }
  257. }
  258. void JoypadLinux::open_joypad(const char *p_path) {
  259. int joy_num = input->get_unused_joy_id();
  260. int fd = open(p_path, O_RDWR | O_NONBLOCK);
  261. if (fd != -1 && joy_num != -1) {
  262. unsigned long evbit[NBITS(EV_MAX)] = { 0 };
  263. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  264. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  265. // add to attached devices so we don't try to open it again
  266. attached_devices.push_back(String(p_path));
  267. if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
  268. (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  269. (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  270. close(fd);
  271. return;
  272. }
  273. //check if the device supports basic gamepad events, prevents certain keyboards from
  274. //being detected as joypads
  275. if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) &&
  276. (test_bit(ABS_X, absbit) || test_bit(ABS_Y, absbit) || test_bit(ABS_HAT0X, absbit) ||
  277. test_bit(ABS_GAS, absbit) || test_bit(ABS_RUDDER, absbit)) &&
  278. (test_bit(BTN_A, keybit) || test_bit(BTN_THUMBL, keybit) ||
  279. test_bit(BTN_TRIGGER, keybit) || test_bit(BTN_1, keybit))) &&
  280. !(test_bit(EV_ABS, evbit) &&
  281. test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit) &&
  282. test_bit(ABS_RX, absbit) && test_bit(ABS_RY, absbit))) {
  283. close(fd);
  284. return;
  285. }
  286. char uid[128];
  287. char namebuf[128];
  288. String name = "";
  289. input_id inpid;
  290. if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) >= 0) {
  291. name = namebuf;
  292. }
  293. if (ioctl(fd, EVIOCGID, &inpid) < 0) {
  294. close(fd);
  295. return;
  296. }
  297. joypads[joy_num].reset();
  298. Joypad &joy = joypads[joy_num];
  299. joy.fd = fd;
  300. joy.devpath = String(p_path);
  301. setup_joypad_properties(joy_num);
  302. sprintf(uid, "%04x%04x", BSWAP16(inpid.bustype), 0);
  303. if (inpid.vendor && inpid.product && inpid.version) {
  304. uint16_t vendor = BSWAP16(inpid.vendor);
  305. uint16_t product = BSWAP16(inpid.product);
  306. uint16_t version = BSWAP16(inpid.version);
  307. sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor, 0, product, 0, version, 0);
  308. input->joy_connection_changed(joy_num, true, name, uid);
  309. } else {
  310. String uidname = uid;
  311. int uidlen = MIN(name.length(), 11);
  312. for (int i = 0; i < uidlen; i++) {
  313. uidname = uidname + _hex_str(name[i]);
  314. }
  315. uidname += "00";
  316. input->joy_connection_changed(joy_num, true, name, uidname);
  317. }
  318. }
  319. }
  320. void JoypadLinux::joypad_vibration_start(int p_id, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) {
  321. Joypad &joy = joypads[p_id];
  322. if (!joy.force_feedback || joy.fd == -1 || p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  323. return;
  324. }
  325. if (joy.ff_effect_id != -1) {
  326. joypad_vibration_stop(p_id, p_timestamp);
  327. }
  328. struct ff_effect effect;
  329. effect.type = FF_RUMBLE;
  330. effect.id = -1;
  331. effect.u.rumble.weak_magnitude = floor(p_weak_magnitude * (float)0xffff);
  332. effect.u.rumble.strong_magnitude = floor(p_strong_magnitude * (float)0xffff);
  333. effect.replay.length = floor(p_duration * 1000);
  334. effect.replay.delay = 0;
  335. if (ioctl(joy.fd, EVIOCSFF, &effect) < 0) {
  336. return;
  337. }
  338. struct input_event play;
  339. play.type = EV_FF;
  340. play.code = effect.id;
  341. play.value = 1;
  342. if (write(joy.fd, (const void *)&play, sizeof(play)) == -1) {
  343. print_verbose("Couldn't write to Joypad device.");
  344. }
  345. joy.ff_effect_id = effect.id;
  346. joy.ff_effect_timestamp = p_timestamp;
  347. }
  348. void JoypadLinux::joypad_vibration_stop(int p_id, uint64_t p_timestamp) {
  349. Joypad &joy = joypads[p_id];
  350. if (!joy.force_feedback || joy.fd == -1 || joy.ff_effect_id == -1) {
  351. return;
  352. }
  353. if (ioctl(joy.fd, EVIOCRMFF, joy.ff_effect_id) < 0) {
  354. return;
  355. }
  356. joy.ff_effect_id = -1;
  357. joy.ff_effect_timestamp = p_timestamp;
  358. }
  359. InputDefault::JoyAxis JoypadLinux::axis_correct(const input_absinfo *p_abs, int p_value) const {
  360. int min = p_abs->minimum;
  361. int max = p_abs->maximum;
  362. InputDefault::JoyAxis jx;
  363. if (min < 0) {
  364. jx.min = -1;
  365. if (p_value < 0) {
  366. jx.value = (float)-p_value / min;
  367. } else {
  368. jx.value = (float)p_value / max;
  369. }
  370. } else if (min == 0) {
  371. jx.min = 0;
  372. jx.value = 0.0f + (float)p_value / max;
  373. }
  374. return jx;
  375. }
  376. void JoypadLinux::process_joypads() {
  377. if (joy_mutex->try_lock() != OK) {
  378. return;
  379. }
  380. for (int i = 0; i < JOYPADS_MAX; i++) {
  381. if (joypads[i].fd == -1) continue;
  382. input_event events[32];
  383. Joypad *joy = &joypads[i];
  384. int len;
  385. while ((len = read(joy->fd, events, (sizeof events))) > 0) {
  386. len /= sizeof(events[0]);
  387. for (int j = 0; j < len; j++) {
  388. input_event &ev = events[j];
  389. // ev may be tainted and out of MAX_KEY range, which will cause
  390. // joy->key_map[ev.code] to crash
  391. if (ev.code >= MAX_KEY)
  392. return;
  393. switch (ev.type) {
  394. case EV_KEY:
  395. input->joy_button(i, joy->key_map[ev.code], ev.value);
  396. break;
  397. case EV_ABS:
  398. switch (ev.code) {
  399. case ABS_HAT0X:
  400. if (ev.value != 0) {
  401. if (ev.value < 0)
  402. joy->dpad |= InputDefault::HAT_MASK_LEFT;
  403. else
  404. joy->dpad |= InputDefault::HAT_MASK_RIGHT;
  405. } else
  406. joy->dpad &= ~(InputDefault::HAT_MASK_LEFT | InputDefault::HAT_MASK_RIGHT);
  407. input->joy_hat(i, joy->dpad);
  408. break;
  409. case ABS_HAT0Y:
  410. if (ev.value != 0) {
  411. if (ev.value < 0)
  412. joy->dpad |= InputDefault::HAT_MASK_UP;
  413. else
  414. joy->dpad |= InputDefault::HAT_MASK_DOWN;
  415. } else
  416. joy->dpad &= ~(InputDefault::HAT_MASK_UP | InputDefault::HAT_MASK_DOWN);
  417. input->joy_hat(i, joy->dpad);
  418. break;
  419. default:
  420. if (ev.code >= MAX_ABS)
  421. return;
  422. if (joy->abs_map[ev.code] != -1 && joy->abs_info[ev.code]) {
  423. InputDefault::JoyAxis value = axis_correct(joy->abs_info[ev.code], ev.value);
  424. joy->curr_axis[joy->abs_map[ev.code]] = value;
  425. }
  426. break;
  427. }
  428. break;
  429. }
  430. }
  431. }
  432. for (int j = 0; j < MAX_ABS; j++) {
  433. int index = joy->abs_map[j];
  434. if (index != -1) {
  435. input->joy_axis(i, index, joy->curr_axis[index]);
  436. }
  437. }
  438. if (len == 0 || (len < 0 && errno != EAGAIN)) {
  439. close_joypad(i);
  440. };
  441. if (joy->force_feedback) {
  442. uint64_t timestamp = input->get_joy_vibration_timestamp(i);
  443. if (timestamp > joy->ff_effect_timestamp) {
  444. Vector2 strength = input->get_joy_vibration_strength(i);
  445. float duration = input->get_joy_vibration_duration(i);
  446. if (strength.x == 0 && strength.y == 0) {
  447. joypad_vibration_stop(i, timestamp);
  448. } else {
  449. joypad_vibration_start(i, strength.x, strength.y, duration, timestamp);
  450. }
  451. }
  452. }
  453. }
  454. joy_mutex->unlock();
  455. }
  456. #endif