joypad_linux.cpp 14 KB

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