joypad_linux.cpp 14 KB

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