joypad_linux.cpp 16 KB

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