joypad_linux.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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 = Thread::create(joy_thread_func, this);
  68. }
  69. JoypadLinux::~JoypadLinux() {
  70. exit_udev = true;
  71. Thread::wait_to_finish(joy_thread);
  72. memdelete(joy_thread);
  73. close_joypad();
  74. }
  75. void JoypadLinux::joy_thread_func(void *p_user) {
  76. if (p_user) {
  77. JoypadLinux *joy = (JoypadLinux *)p_user;
  78. joy->run_joypad_thread();
  79. }
  80. }
  81. void JoypadLinux::run_joypad_thread() {
  82. #ifdef UDEV_ENABLED
  83. udev *_udev = udev_new();
  84. ERR_FAIL_COND(!_udev);
  85. enumerate_joypads(_udev);
  86. monitor_joypads(_udev);
  87. udev_unref(_udev);
  88. #else
  89. monitor_joypads();
  90. #endif
  91. }
  92. #ifdef UDEV_ENABLED
  93. void JoypadLinux::enumerate_joypads(udev *p_udev) {
  94. udev_enumerate *enumerate;
  95. udev_list_entry *devices, *dev_list_entry;
  96. udev_device *dev;
  97. enumerate = udev_enumerate_new(p_udev);
  98. udev_enumerate_add_match_subsystem(enumerate, "input");
  99. udev_enumerate_scan_devices(enumerate);
  100. devices = udev_enumerate_get_list_entry(enumerate);
  101. udev_list_entry_foreach(dev_list_entry, devices) {
  102. const char *path = udev_list_entry_get_name(dev_list_entry);
  103. dev = udev_device_new_from_syspath(p_udev, path);
  104. const char *devnode = udev_device_get_devnode(dev);
  105. if (devnode) {
  106. String devnode_str = devnode;
  107. if (devnode_str.find(ignore_str) == -1) {
  108. MutexLock lock(joy_mutex);
  109. open_joypad(devnode);
  110. }
  111. }
  112. udev_device_unref(dev);
  113. }
  114. udev_enumerate_unref(enumerate);
  115. }
  116. void JoypadLinux::monitor_joypads(udev *p_udev) {
  117. udev_device *dev = nullptr;
  118. udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev");
  119. udev_monitor_filter_add_match_subsystem_devtype(mon, "input", nullptr);
  120. udev_monitor_enable_receiving(mon);
  121. int fd = udev_monitor_get_fd(mon);
  122. while (!exit_udev) {
  123. fd_set fds;
  124. struct timeval tv;
  125. int ret;
  126. FD_ZERO(&fds);
  127. FD_SET(fd, &fds);
  128. tv.tv_sec = 0;
  129. tv.tv_usec = 0;
  130. ret = select(fd + 1, &fds, nullptr, nullptr, &tv);
  131. /* Check if our file descriptor has received data. */
  132. if (ret > 0 && FD_ISSET(fd, &fds)) {
  133. /* Make the call to receive the device.
  134. select() ensured that this will not block. */
  135. dev = udev_monitor_receive_device(mon);
  136. if (dev && udev_device_get_devnode(dev) != 0) {
  137. MutexLock lock(joy_mutex);
  138. String action = udev_device_get_action(dev);
  139. const char *devnode = udev_device_get_devnode(dev);
  140. if (devnode) {
  141. String devnode_str = devnode;
  142. if (devnode_str.find(ignore_str) == -1) {
  143. if (action == "add")
  144. open_joypad(devnode);
  145. else if (String(action) == "remove")
  146. close_joypad(get_joy_from_path(devnode));
  147. }
  148. }
  149. udev_device_unref(dev);
  150. }
  151. }
  152. usleep(50000);
  153. }
  154. udev_monitor_unref(mon);
  155. }
  156. #endif
  157. void JoypadLinux::monitor_joypads() {
  158. while (!exit_udev) {
  159. {
  160. MutexLock lock(joy_mutex);
  161. DIR *input_directory;
  162. input_directory = opendir("/dev/input");
  163. if (input_directory) {
  164. struct dirent *current;
  165. char fname[64];
  166. while ((current = readdir(input_directory)) != NULL) {
  167. if (strncmp(current->d_name, "event", 5) != 0) {
  168. continue;
  169. }
  170. sprintf(fname, "/dev/input/%.*s", 16, current->d_name);
  171. if (attached_devices.find(fname) == -1) {
  172. open_joypad(fname);
  173. }
  174. }
  175. }
  176. closedir(input_directory);
  177. }
  178. usleep(1000000); // 1s
  179. }
  180. }
  181. int JoypadLinux::get_joy_from_path(String p_path) const {
  182. for (int i = 0; i < JOYPADS_MAX; i++) {
  183. if (joypads[i].devpath == p_path) {
  184. return i;
  185. }
  186. }
  187. return -2;
  188. }
  189. void JoypadLinux::close_joypad(int p_id) {
  190. if (p_id == -1) {
  191. for (int i = 0; i < JOYPADS_MAX; i++) {
  192. close_joypad(i);
  193. };
  194. return;
  195. } else if (p_id < 0) {
  196. return;
  197. }
  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] = nullptr;
  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
  274. if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) &&
  275. test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit))) {
  276. close(fd);
  277. return;
  278. }
  279. char uid[128];
  280. char namebuf[128];
  281. String name = "";
  282. input_id inpid;
  283. if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) >= 0) {
  284. name = namebuf;
  285. }
  286. if (ioctl(fd, EVIOCGID, &inpid) < 0) {
  287. close(fd);
  288. return;
  289. }
  290. joypads[joy_num].reset();
  291. Joypad &joy = joypads[joy_num];
  292. joy.fd = fd;
  293. joy.devpath = String(p_path);
  294. setup_joypad_properties(joy_num);
  295. sprintf(uid, "%04x%04x", BSWAP16(inpid.bustype), 0);
  296. if (inpid.vendor && inpid.product && inpid.version) {
  297. uint16_t vendor = BSWAP16(inpid.vendor);
  298. uint16_t product = BSWAP16(inpid.product);
  299. uint16_t version = BSWAP16(inpid.version);
  300. sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor, 0, product, 0, version, 0);
  301. input->joy_connection_changed(joy_num, true, name, uid);
  302. } else {
  303. String uidname = uid;
  304. int uidlen = MIN(name.length(), 11);
  305. for (int i = 0; i < uidlen; i++) {
  306. uidname = uidname + _hex_str(name[i]);
  307. }
  308. uidname += "00";
  309. input->joy_connection_changed(joy_num, true, name, uidname);
  310. }
  311. }
  312. }
  313. void JoypadLinux::joypad_vibration_start(int p_id, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) {
  314. Joypad &joy = joypads[p_id];
  315. 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) {
  316. return;
  317. }
  318. if (joy.ff_effect_id != -1) {
  319. joypad_vibration_stop(p_id, p_timestamp);
  320. }
  321. struct ff_effect effect;
  322. effect.type = FF_RUMBLE;
  323. effect.id = -1;
  324. effect.u.rumble.weak_magnitude = floor(p_weak_magnitude * (float)0xffff);
  325. effect.u.rumble.strong_magnitude = floor(p_strong_magnitude * (float)0xffff);
  326. effect.replay.length = floor(p_duration * 1000);
  327. effect.replay.delay = 0;
  328. if (ioctl(joy.fd, EVIOCSFF, &effect) < 0) {
  329. return;
  330. }
  331. struct input_event play;
  332. play.type = EV_FF;
  333. play.code = effect.id;
  334. play.value = 1;
  335. if (write(joy.fd, (const void *)&play, sizeof(play)) == -1) {
  336. print_verbose("Couldn't write to Joypad device.");
  337. }
  338. joy.ff_effect_id = effect.id;
  339. joy.ff_effect_timestamp = p_timestamp;
  340. }
  341. void JoypadLinux::joypad_vibration_stop(int p_id, uint64_t p_timestamp) {
  342. Joypad &joy = joypads[p_id];
  343. if (!joy.force_feedback || joy.fd == -1 || joy.ff_effect_id == -1) {
  344. return;
  345. }
  346. if (ioctl(joy.fd, EVIOCRMFF, joy.ff_effect_id) < 0) {
  347. return;
  348. }
  349. joy.ff_effect_id = -1;
  350. joy.ff_effect_timestamp = p_timestamp;
  351. }
  352. Input::JoyAxis JoypadLinux::axis_correct(const input_absinfo *p_abs, int p_value) const {
  353. int min = p_abs->minimum;
  354. int max = p_abs->maximum;
  355. Input::JoyAxis jx;
  356. if (min < 0) {
  357. jx.min = -1;
  358. if (p_value < 0) {
  359. jx.value = (float)-p_value / min;
  360. } else {
  361. jx.value = (float)p_value / max;
  362. }
  363. } else if (min == 0) {
  364. jx.min = 0;
  365. jx.value = 0.0f + (float)p_value / max;
  366. }
  367. return jx;
  368. }
  369. void JoypadLinux::process_joypads() {
  370. if (joy_mutex.try_lock() != OK) {
  371. return;
  372. }
  373. for (int i = 0; i < JOYPADS_MAX; i++) {
  374. if (joypads[i].fd == -1) {
  375. continue;
  376. }
  377. input_event events[32];
  378. Joypad *joy = &joypads[i];
  379. int len;
  380. while ((len = read(joy->fd, events, (sizeof events))) > 0) {
  381. len /= sizeof(events[0]);
  382. for (int j = 0; j < len; j++) {
  383. input_event &ev = events[j];
  384. // ev may be tainted and out of MAX_KEY range, which will cause
  385. // joy->key_map[ev.code] to crash
  386. if (ev.code >= MAX_KEY) {
  387. return;
  388. }
  389. switch (ev.type) {
  390. case EV_KEY:
  391. input->joy_button(i, joy->key_map[ev.code], ev.value);
  392. break;
  393. case EV_ABS:
  394. switch (ev.code) {
  395. case ABS_HAT0X:
  396. if (ev.value != 0) {
  397. if (ev.value < 0) {
  398. joy->dpad = (joy->dpad | Input::HAT_MASK_LEFT) & ~Input::HAT_MASK_RIGHT;
  399. } else {
  400. joy->dpad = (joy->dpad | Input::HAT_MASK_RIGHT) & ~Input::HAT_MASK_LEFT;
  401. }
  402. } else {
  403. joy->dpad &= ~(Input::HAT_MASK_LEFT | Input::HAT_MASK_RIGHT);
  404. }
  405. input->joy_hat(i, joy->dpad);
  406. break;
  407. case ABS_HAT0Y:
  408. if (ev.value != 0) {
  409. if (ev.value < 0) {
  410. joy->dpad = (joy->dpad | Input::HAT_MASK_UP) & ~Input::HAT_MASK_DOWN;
  411. } else {
  412. joy->dpad = (joy->dpad | Input::HAT_MASK_DOWN) & ~Input::HAT_MASK_UP;
  413. }
  414. } else {
  415. joy->dpad &= ~(Input::HAT_MASK_UP | Input::HAT_MASK_DOWN);
  416. }
  417. input->joy_hat(i, joy->dpad);
  418. break;
  419. default:
  420. if (ev.code >= MAX_ABS) {
  421. return;
  422. }
  423. if (joy->abs_map[ev.code] != -1 && joy->abs_info[ev.code]) {
  424. Input::JoyAxis value = axis_correct(joy->abs_info[ev.code], ev.value);
  425. joy->curr_axis[joy->abs_map[ev.code]] = value;
  426. }
  427. break;
  428. }
  429. break;
  430. }
  431. }
  432. }
  433. for (int j = 0; j < MAX_ABS; j++) {
  434. int index = joy->abs_map[j];
  435. if (index != -1) {
  436. input->joy_axis(i, index, joy->curr_axis[index]);
  437. }
  438. }
  439. if (len == 0 || (len < 0 && errno != EAGAIN)) {
  440. close_joypad(i);
  441. };
  442. if (joy->force_feedback) {
  443. uint64_t timestamp = input->get_joy_vibration_timestamp(i);
  444. if (timestamp > joy->ff_effect_timestamp) {
  445. Vector2 strength = input->get_joy_vibration_strength(i);
  446. float duration = input->get_joy_vibration_duration(i);
  447. if (strength.x == 0 && strength.y == 0) {
  448. joypad_vibration_stop(i, timestamp);
  449. } else {
  450. joypad_vibration_start(i, strength.x, strength.y, duration, timestamp);
  451. }
  452. }
  453. }
  454. }
  455. joy_mutex.unlock();
  456. }
  457. #endif