2
0

input.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. /*************************************************************************/
  2. /* input.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. #include "input.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/input/default_controller_mappings.h"
  33. #include "core/input/input_map.h"
  34. #include "core/os/os.h"
  35. static const char *_joy_buttons[JOY_BUTTON_SDL_MAX] = {
  36. "a",
  37. "b",
  38. "x",
  39. "y",
  40. "back",
  41. "guide",
  42. "start",
  43. "leftstick",
  44. "rightstick",
  45. "leftshoulder",
  46. "rightshoulder",
  47. "dpup",
  48. "dpdown",
  49. "dpleft",
  50. "dpright",
  51. "misc1",
  52. "paddle1",
  53. "paddle2",
  54. "paddle3",
  55. "paddle4",
  56. "touchpad",
  57. };
  58. static const char *_joy_axes[JOY_AXIS_SDL_MAX] = {
  59. "leftx",
  60. "lefty",
  61. "rightx",
  62. "righty",
  63. "lefttrigger",
  64. "righttrigger",
  65. };
  66. Input *Input::singleton = nullptr;
  67. void (*Input::set_mouse_mode_func)(Input::MouseMode) = nullptr;
  68. Input::MouseMode (*Input::get_mouse_mode_func)() = nullptr;
  69. void (*Input::warp_mouse_func)(const Vector2 &p_to_pos) = nullptr;
  70. Input::CursorShape (*Input::get_current_cursor_shape_func)() = nullptr;
  71. void (*Input::set_custom_mouse_cursor_func)(const RES &, Input::CursorShape, const Vector2 &) = nullptr;
  72. Input *Input::get_singleton() {
  73. return singleton;
  74. }
  75. void Input::set_mouse_mode(MouseMode p_mode) {
  76. ERR_FAIL_INDEX((int)p_mode, 5);
  77. set_mouse_mode_func(p_mode);
  78. }
  79. Input::MouseMode Input::get_mouse_mode() const {
  80. return get_mouse_mode_func();
  81. }
  82. void Input::_bind_methods() {
  83. ClassDB::bind_method(D_METHOD("is_key_pressed", "keycode"), &Input::is_key_pressed);
  84. ClassDB::bind_method(D_METHOD("is_mouse_button_pressed", "button"), &Input::is_mouse_button_pressed);
  85. ClassDB::bind_method(D_METHOD("is_joy_button_pressed", "device", "button"), &Input::is_joy_button_pressed);
  86. ClassDB::bind_method(D_METHOD("is_action_pressed", "action", "exact_match"), &Input::is_action_pressed, DEFVAL(false));
  87. ClassDB::bind_method(D_METHOD("is_action_just_pressed", "action", "exact_match"), &Input::is_action_just_pressed, DEFVAL(false));
  88. ClassDB::bind_method(D_METHOD("is_action_just_released", "action", "exact_match"), &Input::is_action_just_released, DEFVAL(false));
  89. ClassDB::bind_method(D_METHOD("get_action_strength", "action", "exact_match"), &Input::get_action_strength, DEFVAL(false));
  90. ClassDB::bind_method(D_METHOD("get_action_raw_strength", "action", "exact_match"), &Input::get_action_raw_strength, DEFVAL(false));
  91. ClassDB::bind_method(D_METHOD("get_axis", "negative_action", "positive_action"), &Input::get_axis);
  92. ClassDB::bind_method(D_METHOD("get_vector", "negative_x", "positive_x", "negative_y", "positive_y", "deadzone"), &Input::get_vector, DEFVAL(-1.0f));
  93. ClassDB::bind_method(D_METHOD("add_joy_mapping", "mapping", "update_existing"), &Input::add_joy_mapping, DEFVAL(false));
  94. ClassDB::bind_method(D_METHOD("remove_joy_mapping", "guid"), &Input::remove_joy_mapping);
  95. ClassDB::bind_method(D_METHOD("joy_connection_changed", "device", "connected", "name", "guid"), &Input::joy_connection_changed);
  96. ClassDB::bind_method(D_METHOD("is_joy_known", "device"), &Input::is_joy_known);
  97. ClassDB::bind_method(D_METHOD("get_joy_axis", "device", "axis"), &Input::get_joy_axis);
  98. ClassDB::bind_method(D_METHOD("get_joy_name", "device"), &Input::get_joy_name);
  99. ClassDB::bind_method(D_METHOD("get_joy_guid", "device"), &Input::get_joy_guid);
  100. ClassDB::bind_method(D_METHOD("get_connected_joypads"), &Input::get_connected_joypads);
  101. ClassDB::bind_method(D_METHOD("get_joy_vibration_strength", "device"), &Input::get_joy_vibration_strength);
  102. ClassDB::bind_method(D_METHOD("get_joy_vibration_duration", "device"), &Input::get_joy_vibration_duration);
  103. ClassDB::bind_method(D_METHOD("start_joy_vibration", "device", "weak_magnitude", "strong_magnitude", "duration"), &Input::start_joy_vibration, DEFVAL(0));
  104. ClassDB::bind_method(D_METHOD("stop_joy_vibration", "device"), &Input::stop_joy_vibration);
  105. ClassDB::bind_method(D_METHOD("vibrate_handheld", "duration_ms"), &Input::vibrate_handheld, DEFVAL(500));
  106. ClassDB::bind_method(D_METHOD("get_gravity"), &Input::get_gravity);
  107. ClassDB::bind_method(D_METHOD("get_accelerometer"), &Input::get_accelerometer);
  108. ClassDB::bind_method(D_METHOD("get_magnetometer"), &Input::get_magnetometer);
  109. ClassDB::bind_method(D_METHOD("get_gyroscope"), &Input::get_gyroscope);
  110. ClassDB::bind_method(D_METHOD("set_gravity", "value"), &Input::set_gravity);
  111. ClassDB::bind_method(D_METHOD("set_accelerometer", "value"), &Input::set_accelerometer);
  112. ClassDB::bind_method(D_METHOD("set_magnetometer", "value"), &Input::set_magnetometer);
  113. ClassDB::bind_method(D_METHOD("set_gyroscope", "value"), &Input::set_gyroscope);
  114. ClassDB::bind_method(D_METHOD("get_last_mouse_speed"), &Input::get_last_mouse_speed);
  115. ClassDB::bind_method(D_METHOD("get_mouse_button_mask"), &Input::get_mouse_button_mask);
  116. ClassDB::bind_method(D_METHOD("set_mouse_mode", "mode"), &Input::set_mouse_mode);
  117. ClassDB::bind_method(D_METHOD("get_mouse_mode"), &Input::get_mouse_mode);
  118. ClassDB::bind_method(D_METHOD("warp_mouse_position", "to"), &Input::warp_mouse_position);
  119. ClassDB::bind_method(D_METHOD("action_press", "action", "strength"), &Input::action_press, DEFVAL(1.f));
  120. ClassDB::bind_method(D_METHOD("action_release", "action"), &Input::action_release);
  121. ClassDB::bind_method(D_METHOD("set_default_cursor_shape", "shape"), &Input::set_default_cursor_shape, DEFVAL(CURSOR_ARROW));
  122. ClassDB::bind_method(D_METHOD("get_current_cursor_shape"), &Input::get_current_cursor_shape);
  123. ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor", "image", "shape", "hotspot"), &Input::set_custom_mouse_cursor, DEFVAL(CURSOR_ARROW), DEFVAL(Vector2()));
  124. ClassDB::bind_method(D_METHOD("parse_input_event", "event"), &Input::parse_input_event);
  125. ClassDB::bind_method(D_METHOD("set_use_accumulated_input", "enable"), &Input::set_use_accumulated_input);
  126. ClassDB::bind_method(D_METHOD("flush_buffered_events"), &Input::flush_buffered_events);
  127. BIND_ENUM_CONSTANT(MOUSE_MODE_VISIBLE);
  128. BIND_ENUM_CONSTANT(MOUSE_MODE_HIDDEN);
  129. BIND_ENUM_CONSTANT(MOUSE_MODE_CAPTURED);
  130. BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED);
  131. BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED_HIDDEN);
  132. BIND_ENUM_CONSTANT(CURSOR_ARROW);
  133. BIND_ENUM_CONSTANT(CURSOR_IBEAM);
  134. BIND_ENUM_CONSTANT(CURSOR_POINTING_HAND);
  135. BIND_ENUM_CONSTANT(CURSOR_CROSS);
  136. BIND_ENUM_CONSTANT(CURSOR_WAIT);
  137. BIND_ENUM_CONSTANT(CURSOR_BUSY);
  138. BIND_ENUM_CONSTANT(CURSOR_DRAG);
  139. BIND_ENUM_CONSTANT(CURSOR_CAN_DROP);
  140. BIND_ENUM_CONSTANT(CURSOR_FORBIDDEN);
  141. BIND_ENUM_CONSTANT(CURSOR_VSIZE);
  142. BIND_ENUM_CONSTANT(CURSOR_HSIZE);
  143. BIND_ENUM_CONSTANT(CURSOR_BDIAGSIZE);
  144. BIND_ENUM_CONSTANT(CURSOR_FDIAGSIZE);
  145. BIND_ENUM_CONSTANT(CURSOR_MOVE);
  146. BIND_ENUM_CONSTANT(CURSOR_VSPLIT);
  147. BIND_ENUM_CONSTANT(CURSOR_HSPLIT);
  148. BIND_ENUM_CONSTANT(CURSOR_HELP);
  149. ADD_SIGNAL(MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "device"), PropertyInfo(Variant::BOOL, "connected")));
  150. }
  151. void Input::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  152. String pf = p_function;
  153. if (p_idx == 0 &&
  154. (pf == "is_action_pressed" || pf == "action_press" || pf == "action_release" ||
  155. pf == "is_action_just_pressed" || pf == "is_action_just_released" ||
  156. pf == "get_action_strength" || pf == "get_action_raw_strength" ||
  157. pf == "get_axis" || pf == "get_vector")) {
  158. List<PropertyInfo> pinfo;
  159. ProjectSettings::get_singleton()->get_property_list(&pinfo);
  160. for (const PropertyInfo &pi : pinfo) {
  161. if (!pi.name.begins_with("input/")) {
  162. continue;
  163. }
  164. String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
  165. r_options->push_back(name.quote());
  166. }
  167. }
  168. }
  169. void Input::SpeedTrack::update(const Vector2 &p_delta_p) {
  170. uint64_t tick = OS::get_singleton()->get_ticks_usec();
  171. uint32_t tdiff = tick - last_tick;
  172. float delta_t = tdiff / 1000000.0;
  173. last_tick = tick;
  174. accum += p_delta_p;
  175. accum_t += delta_t;
  176. if (accum_t > max_ref_frame * 10) {
  177. accum_t = max_ref_frame * 10;
  178. }
  179. while (accum_t >= min_ref_frame) {
  180. float slice_t = min_ref_frame / accum_t;
  181. Vector2 slice = accum * slice_t;
  182. accum = accum - slice;
  183. accum_t -= min_ref_frame;
  184. speed = (slice / min_ref_frame).lerp(speed, min_ref_frame / max_ref_frame);
  185. }
  186. }
  187. void Input::SpeedTrack::reset() {
  188. last_tick = OS::get_singleton()->get_ticks_usec();
  189. speed = Vector2();
  190. accum_t = 0;
  191. }
  192. Input::SpeedTrack::SpeedTrack() {
  193. min_ref_frame = 0.1;
  194. max_ref_frame = 0.3;
  195. reset();
  196. }
  197. bool Input::is_key_pressed(Key p_keycode) const {
  198. _THREAD_SAFE_METHOD_
  199. return keys_pressed.has(p_keycode);
  200. }
  201. bool Input::is_mouse_button_pressed(MouseButton p_button) const {
  202. _THREAD_SAFE_METHOD_
  203. return (mouse_button_mask & (1 << (p_button - 1))) != 0;
  204. }
  205. static int _combine_device(int p_value, int p_device) {
  206. return p_value | (p_device << 20);
  207. }
  208. bool Input::is_joy_button_pressed(int p_device, JoyButton p_button) const {
  209. _THREAD_SAFE_METHOD_
  210. return joy_buttons_pressed.has(_combine_device(p_button, p_device));
  211. }
  212. bool Input::is_action_pressed(const StringName &p_action, bool p_exact) const {
  213. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  214. return action_state.has(p_action) && action_state[p_action].pressed && (p_exact ? action_state[p_action].exact : true);
  215. }
  216. bool Input::is_action_just_pressed(const StringName &p_action, bool p_exact) const {
  217. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  218. const Map<StringName, Action>::Element *E = action_state.find(p_action);
  219. if (!E) {
  220. return false;
  221. }
  222. if (p_exact && E->get().exact == false) {
  223. return false;
  224. }
  225. if (Engine::get_singleton()->is_in_physics_frame()) {
  226. return E->get().pressed && E->get().physics_frame == Engine::get_singleton()->get_physics_frames();
  227. } else {
  228. return E->get().pressed && E->get().process_frame == Engine::get_singleton()->get_process_frames();
  229. }
  230. }
  231. bool Input::is_action_just_released(const StringName &p_action, bool p_exact) const {
  232. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  233. const Map<StringName, Action>::Element *E = action_state.find(p_action);
  234. if (!E) {
  235. return false;
  236. }
  237. if (p_exact && E->get().exact == false) {
  238. return false;
  239. }
  240. if (Engine::get_singleton()->is_in_physics_frame()) {
  241. return !E->get().pressed && E->get().physics_frame == Engine::get_singleton()->get_physics_frames();
  242. } else {
  243. return !E->get().pressed && E->get().process_frame == Engine::get_singleton()->get_process_frames();
  244. }
  245. }
  246. float Input::get_action_strength(const StringName &p_action, bool p_exact) const {
  247. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
  248. const Map<StringName, Action>::Element *E = action_state.find(p_action);
  249. if (!E) {
  250. return 0.0f;
  251. }
  252. if (p_exact && E->get().exact == false) {
  253. return 0.0f;
  254. }
  255. return E->get().strength;
  256. }
  257. float Input::get_action_raw_strength(const StringName &p_action, bool p_exact) const {
  258. const Map<StringName, Action>::Element *E = action_state.find(p_action);
  259. if (!E) {
  260. return 0.0f;
  261. }
  262. if (p_exact && E->get().exact == false) {
  263. return 0.0f;
  264. }
  265. return E->get().raw_strength;
  266. }
  267. float Input::get_axis(const StringName &p_negative_action, const StringName &p_positive_action) const {
  268. return get_action_strength(p_positive_action) - get_action_strength(p_negative_action);
  269. }
  270. Vector2 Input::get_vector(const StringName &p_negative_x, const StringName &p_positive_x, const StringName &p_negative_y, const StringName &p_positive_y, float p_deadzone) const {
  271. Vector2 vector = Vector2(
  272. get_action_raw_strength(p_positive_x) - get_action_raw_strength(p_negative_x),
  273. get_action_raw_strength(p_positive_y) - get_action_raw_strength(p_negative_y));
  274. if (p_deadzone < 0.0f) {
  275. // If the deadzone isn't specified, get it from the average of the actions.
  276. p_deadzone = 0.25 *
  277. (InputMap::get_singleton()->action_get_deadzone(p_positive_x) +
  278. InputMap::get_singleton()->action_get_deadzone(p_negative_x) +
  279. InputMap::get_singleton()->action_get_deadzone(p_positive_y) +
  280. InputMap::get_singleton()->action_get_deadzone(p_negative_y));
  281. }
  282. // Circular length limiting and deadzone.
  283. float length = vector.length();
  284. if (length <= p_deadzone) {
  285. return Vector2();
  286. } else if (length > 1.0f) {
  287. return vector / length;
  288. } else {
  289. // Inverse lerp length to map (p_deadzone, 1) to (0, 1).
  290. return vector * (Math::inverse_lerp(p_deadzone, 1.0f, length) / length);
  291. }
  292. return vector;
  293. }
  294. float Input::get_joy_axis(int p_device, JoyAxis p_axis) const {
  295. _THREAD_SAFE_METHOD_
  296. int c = _combine_device(p_axis, p_device);
  297. if (_joy_axis.has(c)) {
  298. return _joy_axis[c];
  299. } else {
  300. return 0;
  301. }
  302. }
  303. String Input::get_joy_name(int p_idx) {
  304. _THREAD_SAFE_METHOD_
  305. return joy_names[p_idx].name;
  306. }
  307. Vector2 Input::get_joy_vibration_strength(int p_device) {
  308. if (joy_vibration.has(p_device)) {
  309. return Vector2(joy_vibration[p_device].weak_magnitude, joy_vibration[p_device].strong_magnitude);
  310. } else {
  311. return Vector2(0, 0);
  312. }
  313. }
  314. uint64_t Input::get_joy_vibration_timestamp(int p_device) {
  315. if (joy_vibration.has(p_device)) {
  316. return joy_vibration[p_device].timestamp;
  317. } else {
  318. return 0;
  319. }
  320. }
  321. float Input::get_joy_vibration_duration(int p_device) {
  322. if (joy_vibration.has(p_device)) {
  323. return joy_vibration[p_device].duration;
  324. } else {
  325. return 0.f;
  326. }
  327. }
  328. static String _hex_str(uint8_t p_byte) {
  329. static const char *dict = "0123456789abcdef";
  330. char ret[3];
  331. ret[2] = 0;
  332. ret[0] = dict[p_byte >> 4];
  333. ret[1] = dict[p_byte & 0xf];
  334. return ret;
  335. }
  336. void Input::joy_connection_changed(int p_idx, bool p_connected, String p_name, String p_guid) {
  337. _THREAD_SAFE_METHOD_
  338. Joypad js;
  339. js.name = p_connected ? p_name : "";
  340. js.uid = p_connected ? p_guid : "";
  341. if (p_connected) {
  342. String uidname = p_guid;
  343. if (p_guid == "") {
  344. int uidlen = MIN(p_name.length(), 16);
  345. for (int i = 0; i < uidlen; i++) {
  346. uidname = uidname + _hex_str(p_name[i]);
  347. }
  348. }
  349. js.uid = uidname;
  350. js.connected = true;
  351. int mapping = fallback_mapping;
  352. for (int i = 0; i < map_db.size(); i++) {
  353. if (js.uid == map_db[i].uid) {
  354. mapping = i;
  355. js.name = map_db[i].name;
  356. }
  357. }
  358. js.mapping = mapping;
  359. } else {
  360. js.connected = false;
  361. for (int i = 0; i < JOY_BUTTON_MAX; i++) {
  362. int c = _combine_device(i, p_idx);
  363. joy_buttons_pressed.erase(c);
  364. }
  365. for (int i = 0; i < JOY_AXIS_MAX; i++) {
  366. set_joy_axis(p_idx, (JoyAxis)i, 0.0f);
  367. }
  368. }
  369. joy_names[p_idx] = js;
  370. emit_signal(SNAME("joy_connection_changed"), p_idx, p_connected);
  371. }
  372. Vector3 Input::get_gravity() const {
  373. _THREAD_SAFE_METHOD_
  374. return gravity;
  375. }
  376. Vector3 Input::get_accelerometer() const {
  377. _THREAD_SAFE_METHOD_
  378. return accelerometer;
  379. }
  380. Vector3 Input::get_magnetometer() const {
  381. _THREAD_SAFE_METHOD_
  382. return magnetometer;
  383. }
  384. Vector3 Input::get_gyroscope() const {
  385. _THREAD_SAFE_METHOD_
  386. return gyroscope;
  387. }
  388. void Input::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool p_is_emulated) {
  389. // Notes on mouse-touch emulation:
  390. // - Emulated mouse events are parsed, that is, re-routed to this method, so they make the same effects
  391. // as true mouse events. The only difference is the situation is flagged as emulated so they are not
  392. // emulated back to touch events in an endless loop.
  393. // - Emulated touch events are handed right to the main loop (i.e., the SceneTree) because they don't
  394. // require additional handling by this class.
  395. Ref<InputEventKey> k = p_event;
  396. if (k.is_valid() && !k->is_echo() && k->get_keycode() != 0) {
  397. if (k->is_pressed()) {
  398. keys_pressed.insert(k->get_keycode());
  399. } else {
  400. keys_pressed.erase(k->get_keycode());
  401. }
  402. }
  403. Ref<InputEventMouseButton> mb = p_event;
  404. if (mb.is_valid()) {
  405. if (mb->is_pressed()) {
  406. mouse_button_mask |= (MouseButton)(1 << (mb->get_button_index() - 1));
  407. } else {
  408. mouse_button_mask &= (MouseButton) ~(1 << (mb->get_button_index() - 1));
  409. }
  410. Point2 pos = mb->get_global_position();
  411. if (mouse_pos != pos) {
  412. set_mouse_position(pos);
  413. }
  414. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mb->get_button_index() == 1) {
  415. Ref<InputEventScreenTouch> touch_event;
  416. touch_event.instantiate();
  417. touch_event->set_pressed(mb->is_pressed());
  418. touch_event->set_position(mb->get_position());
  419. event_dispatch_function(touch_event);
  420. }
  421. }
  422. Ref<InputEventMouseMotion> mm = p_event;
  423. if (mm.is_valid()) {
  424. Point2 pos = mm->get_global_position();
  425. if (mouse_pos != pos) {
  426. set_mouse_position(pos);
  427. }
  428. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mm->get_button_mask() & 1) {
  429. Ref<InputEventScreenDrag> drag_event;
  430. drag_event.instantiate();
  431. drag_event->set_position(mm->get_position());
  432. drag_event->set_relative(mm->get_relative());
  433. drag_event->set_speed(mm->get_speed());
  434. event_dispatch_function(drag_event);
  435. }
  436. }
  437. Ref<InputEventScreenTouch> st = p_event;
  438. if (st.is_valid()) {
  439. if (st->is_pressed()) {
  440. SpeedTrack &track = touch_speed_track[st->get_index()];
  441. track.reset();
  442. } else {
  443. // Since a pointer index may not occur again (OSs may or may not reuse them),
  444. // imperatively remove it from the map to keep no fossil entries in it
  445. touch_speed_track.erase(st->get_index());
  446. }
  447. if (emulate_mouse_from_touch) {
  448. bool translate = false;
  449. if (st->is_pressed()) {
  450. if (mouse_from_touch_index == -1) {
  451. translate = true;
  452. mouse_from_touch_index = st->get_index();
  453. }
  454. } else {
  455. if (st->get_index() == mouse_from_touch_index) {
  456. translate = true;
  457. mouse_from_touch_index = -1;
  458. }
  459. }
  460. if (translate) {
  461. Ref<InputEventMouseButton> button_event;
  462. button_event.instantiate();
  463. button_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  464. button_event->set_position(st->get_position());
  465. button_event->set_global_position(st->get_position());
  466. button_event->set_pressed(st->is_pressed());
  467. button_event->set_button_index(MOUSE_BUTTON_LEFT);
  468. if (st->is_pressed()) {
  469. button_event->set_button_mask(MouseButton(mouse_button_mask | MOUSE_BUTTON_MASK_LEFT));
  470. } else {
  471. button_event->set_button_mask(MouseButton(mouse_button_mask & ~MOUSE_BUTTON_MASK_LEFT));
  472. }
  473. _parse_input_event_impl(button_event, true);
  474. }
  475. }
  476. }
  477. Ref<InputEventScreenDrag> sd = p_event;
  478. if (sd.is_valid()) {
  479. SpeedTrack &track = touch_speed_track[sd->get_index()];
  480. track.update(sd->get_relative());
  481. sd->set_speed(track.speed);
  482. if (emulate_mouse_from_touch && sd->get_index() == mouse_from_touch_index) {
  483. Ref<InputEventMouseMotion> motion_event;
  484. motion_event.instantiate();
  485. motion_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  486. motion_event->set_position(sd->get_position());
  487. motion_event->set_global_position(sd->get_position());
  488. motion_event->set_relative(sd->get_relative());
  489. motion_event->set_speed(sd->get_speed());
  490. motion_event->set_button_mask(mouse_button_mask);
  491. _parse_input_event_impl(motion_event, true);
  492. }
  493. }
  494. Ref<InputEventJoypadButton> jb = p_event;
  495. if (jb.is_valid()) {
  496. int c = _combine_device(jb->get_button_index(), jb->get_device());
  497. if (jb->is_pressed()) {
  498. joy_buttons_pressed.insert(c);
  499. } else {
  500. joy_buttons_pressed.erase(c);
  501. }
  502. }
  503. Ref<InputEventJoypadMotion> jm = p_event;
  504. if (jm.is_valid()) {
  505. set_joy_axis(jm->get_device(), jm->get_axis(), jm->get_axis_value());
  506. }
  507. Ref<InputEventGesture> ge = p_event;
  508. if (ge.is_valid()) {
  509. if (event_dispatch_function) {
  510. event_dispatch_function(ge);
  511. }
  512. }
  513. for (OrderedHashMap<StringName, InputMap::Action>::ConstElement E = InputMap::get_singleton()->get_action_map().front(); E; E = E.next()) {
  514. if (InputMap::get_singleton()->event_is_action(p_event, E.key())) {
  515. // If not echo and action pressed state has changed
  516. if (!p_event->is_echo() && is_action_pressed(E.key(), false) != p_event->is_action_pressed(E.key())) {
  517. Action action;
  518. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  519. action.process_frame = Engine::get_singleton()->get_process_frames();
  520. action.pressed = p_event->is_action_pressed(E.key());
  521. action.strength = 0.0f;
  522. action.raw_strength = 0.0f;
  523. action.exact = InputMap::get_singleton()->event_is_action(p_event, E.key(), true);
  524. action_state[E.key()] = action;
  525. }
  526. action_state[E.key()].strength = p_event->get_action_strength(E.key());
  527. action_state[E.key()].raw_strength = p_event->get_action_raw_strength(E.key());
  528. }
  529. }
  530. if (event_dispatch_function) {
  531. event_dispatch_function(p_event);
  532. }
  533. }
  534. void Input::set_joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  535. _THREAD_SAFE_METHOD_
  536. int c = _combine_device(p_axis, p_device);
  537. _joy_axis[c] = p_value;
  538. }
  539. void Input::start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration) {
  540. _THREAD_SAFE_METHOD_
  541. if (p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  542. return;
  543. }
  544. VibrationInfo vibration;
  545. vibration.weak_magnitude = p_weak_magnitude;
  546. vibration.strong_magnitude = p_strong_magnitude;
  547. vibration.duration = p_duration;
  548. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  549. joy_vibration[p_device] = vibration;
  550. }
  551. void Input::stop_joy_vibration(int p_device) {
  552. _THREAD_SAFE_METHOD_
  553. VibrationInfo vibration;
  554. vibration.weak_magnitude = 0;
  555. vibration.strong_magnitude = 0;
  556. vibration.duration = 0;
  557. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  558. joy_vibration[p_device] = vibration;
  559. }
  560. void Input::vibrate_handheld(int p_duration_ms) {
  561. OS::get_singleton()->vibrate_handheld(p_duration_ms);
  562. }
  563. void Input::set_gravity(const Vector3 &p_gravity) {
  564. _THREAD_SAFE_METHOD_
  565. gravity = p_gravity;
  566. }
  567. void Input::set_accelerometer(const Vector3 &p_accel) {
  568. _THREAD_SAFE_METHOD_
  569. accelerometer = p_accel;
  570. }
  571. void Input::set_magnetometer(const Vector3 &p_magnetometer) {
  572. _THREAD_SAFE_METHOD_
  573. magnetometer = p_magnetometer;
  574. }
  575. void Input::set_gyroscope(const Vector3 &p_gyroscope) {
  576. _THREAD_SAFE_METHOD_
  577. gyroscope = p_gyroscope;
  578. }
  579. void Input::set_mouse_position(const Point2 &p_posf) {
  580. mouse_speed_track.update(p_posf - mouse_pos);
  581. mouse_pos = p_posf;
  582. }
  583. Point2 Input::get_mouse_position() const {
  584. return mouse_pos;
  585. }
  586. Point2 Input::get_last_mouse_speed() const {
  587. return mouse_speed_track.speed;
  588. }
  589. int Input::get_mouse_button_mask() const {
  590. return mouse_button_mask; // do not trust OS implementation, should remove it - OS::get_singleton()->get_mouse_button_state();
  591. }
  592. void Input::warp_mouse_position(const Vector2 &p_to) {
  593. warp_mouse_func(p_to);
  594. }
  595. Point2i Input::warp_mouse_motion(const Ref<InputEventMouseMotion> &p_motion, const Rect2 &p_rect) {
  596. // The relative distance reported for the next event after a warp is in the boundaries of the
  597. // size of the rect on that axis, but it may be greater, in which case there's no problem as fmod()
  598. // will warp it, but if the pointer has moved in the opposite direction between the pointer relocation
  599. // and the subsequent event, the reported relative distance will be less than the size of the rect
  600. // and thus fmod() will be disabled for handling the situation.
  601. // And due to this mouse warping mechanism being stateless, we need to apply some heuristics to
  602. // detect the warp: if the relative distance is greater than the half of the size of the relevant rect
  603. // (checked per each axis), it will be considered as the consequence of a former pointer warp.
  604. const Point2i rel_sgn(p_motion->get_relative().x >= 0.0f ? 1 : -1, p_motion->get_relative().y >= 0.0 ? 1 : -1);
  605. const Size2i warp_margin = p_rect.size * 0.5f;
  606. const Point2i rel_warped(
  607. Math::fmod(p_motion->get_relative().x + rel_sgn.x * warp_margin.x, p_rect.size.x) - rel_sgn.x * warp_margin.x,
  608. Math::fmod(p_motion->get_relative().y + rel_sgn.y * warp_margin.y, p_rect.size.y) - rel_sgn.y * warp_margin.y);
  609. const Point2i pos_local = p_motion->get_global_position() - p_rect.position;
  610. const Point2i pos_warped(Math::fposmod(pos_local.x, p_rect.size.x), Math::fposmod(pos_local.y, p_rect.size.y));
  611. if (pos_warped != pos_local) {
  612. warp_mouse_position(pos_warped + p_rect.position);
  613. }
  614. return rel_warped;
  615. }
  616. void Input::iteration(float p_step) {
  617. }
  618. void Input::action_press(const StringName &p_action, float p_strength) {
  619. Action action;
  620. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  621. action.process_frame = Engine::get_singleton()->get_process_frames();
  622. action.pressed = true;
  623. action.strength = p_strength;
  624. action_state[p_action] = action;
  625. }
  626. void Input::action_release(const StringName &p_action) {
  627. Action action;
  628. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  629. action.process_frame = Engine::get_singleton()->get_process_frames();
  630. action.pressed = false;
  631. action.strength = 0.f;
  632. action_state[p_action] = action;
  633. }
  634. void Input::set_emulate_touch_from_mouse(bool p_emulate) {
  635. emulate_touch_from_mouse = p_emulate;
  636. }
  637. bool Input::is_emulating_touch_from_mouse() const {
  638. return emulate_touch_from_mouse;
  639. }
  640. // Calling this whenever the game window is focused helps unsticking the "touch mouse"
  641. // if the OS or its abstraction class hasn't properly reported that touch pointers raised
  642. void Input::ensure_touch_mouse_raised() {
  643. if (mouse_from_touch_index != -1) {
  644. mouse_from_touch_index = -1;
  645. Ref<InputEventMouseButton> button_event;
  646. button_event.instantiate();
  647. button_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  648. button_event->set_position(mouse_pos);
  649. button_event->set_global_position(mouse_pos);
  650. button_event->set_pressed(false);
  651. button_event->set_button_index(MOUSE_BUTTON_LEFT);
  652. button_event->set_button_mask(MouseButton(mouse_button_mask & ~MOUSE_BUTTON_MASK_LEFT));
  653. _parse_input_event_impl(button_event, true);
  654. }
  655. }
  656. void Input::set_emulate_mouse_from_touch(bool p_emulate) {
  657. emulate_mouse_from_touch = p_emulate;
  658. }
  659. bool Input::is_emulating_mouse_from_touch() const {
  660. return emulate_mouse_from_touch;
  661. }
  662. Input::CursorShape Input::get_default_cursor_shape() const {
  663. return default_shape;
  664. }
  665. void Input::set_default_cursor_shape(CursorShape p_shape) {
  666. if (default_shape == p_shape) {
  667. return;
  668. }
  669. default_shape = p_shape;
  670. // The default shape is set in Viewport::_gui_input_event. To instantly
  671. // see the shape in the viewport we need to trigger a mouse motion event.
  672. Ref<InputEventMouseMotion> mm;
  673. mm.instantiate();
  674. mm->set_position(mouse_pos);
  675. mm->set_global_position(mouse_pos);
  676. parse_input_event(mm);
  677. }
  678. Input::CursorShape Input::get_current_cursor_shape() const {
  679. return get_current_cursor_shape_func();
  680. }
  681. void Input::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  682. if (Engine::get_singleton()->is_editor_hint()) {
  683. return;
  684. }
  685. set_custom_mouse_cursor_func(p_cursor, p_shape, p_hotspot);
  686. }
  687. void Input::parse_input_event(const Ref<InputEvent> &p_event) {
  688. _THREAD_SAFE_METHOD_
  689. ERR_FAIL_COND(p_event.is_null());
  690. if (use_accumulated_input) {
  691. if (buffered_events.is_empty() || !buffered_events.back()->get()->accumulate(p_event)) {
  692. buffered_events.push_back(p_event);
  693. }
  694. } else if (use_input_buffering) {
  695. buffered_events.push_back(p_event);
  696. } else {
  697. _parse_input_event_impl(p_event, false);
  698. }
  699. }
  700. void Input::flush_buffered_events() {
  701. _THREAD_SAFE_METHOD_
  702. while (buffered_events.front()) {
  703. _parse_input_event_impl(buffered_events.front()->get(), false);
  704. buffered_events.pop_front();
  705. }
  706. }
  707. bool Input::is_using_input_buffering() {
  708. return use_input_buffering;
  709. }
  710. void Input::set_use_input_buffering(bool p_enable) {
  711. use_input_buffering = p_enable;
  712. }
  713. void Input::set_use_accumulated_input(bool p_enable) {
  714. use_accumulated_input = p_enable;
  715. }
  716. void Input::release_pressed_events() {
  717. flush_buffered_events(); // this is needed to release actions strengths
  718. keys_pressed.clear();
  719. joy_buttons_pressed.clear();
  720. _joy_axis.clear();
  721. for (const KeyValue<StringName, Input::Action> &E : action_state) {
  722. if (E.value.pressed) {
  723. action_release(E.key);
  724. }
  725. }
  726. }
  727. void Input::set_event_dispatch_function(EventDispatchFunc p_function) {
  728. event_dispatch_function = p_function;
  729. }
  730. void Input::joy_button(int p_device, JoyButton p_button, bool p_pressed) {
  731. _THREAD_SAFE_METHOD_;
  732. Joypad &joy = joy_names[p_device];
  733. //printf("got button %i, mapping is %i\n", p_button, joy.mapping);
  734. if (joy.last_buttons[p_button] == p_pressed) {
  735. return;
  736. }
  737. joy.last_buttons[p_button] = p_pressed;
  738. if (joy.mapping == -1) {
  739. _button_event(p_device, p_button, p_pressed);
  740. return;
  741. }
  742. JoyEvent map = _get_mapped_button_event(map_db[joy.mapping], p_button);
  743. if (map.type == TYPE_BUTTON) {
  744. _button_event(p_device, (JoyButton)map.index, p_pressed);
  745. return;
  746. }
  747. if (map.type == TYPE_AXIS) {
  748. _axis_event(p_device, (JoyAxis)map.index, p_pressed ? map.value : 0.0);
  749. }
  750. // no event?
  751. }
  752. void Input::joy_axis(int p_device, JoyAxis p_axis, const JoyAxisValue &p_value) {
  753. _THREAD_SAFE_METHOD_;
  754. ERR_FAIL_INDEX(p_axis, JOY_AXIS_MAX);
  755. Joypad &joy = joy_names[p_device];
  756. if (joy.last_axis[p_axis] == p_value.value) {
  757. return;
  758. }
  759. //when changing direction quickly, insert fake event to release pending inputmap actions
  760. float last = joy.last_axis[p_axis];
  761. if (p_value.min == 0 && (last < 0.25 || last > 0.75) && (last - 0.5) * (p_value.value - 0.5) < 0) {
  762. JoyAxisValue jx;
  763. jx.min = p_value.min;
  764. jx.value = p_value.value < 0.5 ? 0.6 : 0.4;
  765. joy_axis(p_device, p_axis, jx);
  766. } else if (ABS(last) > 0.5 && last * p_value.value <= 0) {
  767. JoyAxisValue jx;
  768. jx.min = p_value.min;
  769. jx.value = last > 0 ? 0.1 : -0.1;
  770. joy_axis(p_device, p_axis, jx);
  771. }
  772. joy.last_axis[p_axis] = p_value.value;
  773. float val = p_value.min == 0 ? -1.0f + 2.0f * p_value.value : p_value.value;
  774. if (joy.mapping == -1) {
  775. _axis_event(p_device, p_axis, val);
  776. return;
  777. }
  778. JoyEvent map = _get_mapped_axis_event(map_db[joy.mapping], p_axis, val);
  779. if (map.type == TYPE_BUTTON) {
  780. bool pressed = map.value > 0.5;
  781. if (pressed == joy_buttons_pressed.has(_combine_device(map.index, p_device))) {
  782. // Button already pressed or released; so ignore.
  783. return;
  784. }
  785. _button_event(p_device, (JoyButton)map.index, pressed);
  786. // Ensure opposite D-Pad button is also released.
  787. switch (map.index) {
  788. case JOY_BUTTON_DPAD_UP:
  789. if (joy_buttons_pressed.has(_combine_device(JOY_BUTTON_DPAD_DOWN, p_device))) {
  790. _button_event(p_device, JOY_BUTTON_DPAD_DOWN, false);
  791. }
  792. break;
  793. case JOY_BUTTON_DPAD_DOWN:
  794. if (joy_buttons_pressed.has(_combine_device(JOY_BUTTON_DPAD_UP, p_device))) {
  795. _button_event(p_device, JOY_BUTTON_DPAD_UP, false);
  796. }
  797. break;
  798. case JOY_BUTTON_DPAD_LEFT:
  799. if (joy_buttons_pressed.has(_combine_device(JOY_BUTTON_DPAD_RIGHT, p_device))) {
  800. _button_event(p_device, JOY_BUTTON_DPAD_RIGHT, false);
  801. }
  802. break;
  803. case JOY_BUTTON_DPAD_RIGHT:
  804. if (joy_buttons_pressed.has(_combine_device(JOY_BUTTON_DPAD_LEFT, p_device))) {
  805. _button_event(p_device, JOY_BUTTON_DPAD_LEFT, false);
  806. }
  807. break;
  808. default:
  809. // Nothing to do.
  810. break;
  811. }
  812. return;
  813. }
  814. if (map.type == TYPE_AXIS) {
  815. _axis_event(p_device, (JoyAxis)map.index, map.value);
  816. return;
  817. }
  818. //printf("invalid mapping\n");
  819. }
  820. void Input::joy_hat(int p_device, int p_val) {
  821. _THREAD_SAFE_METHOD_;
  822. const Joypad &joy = joy_names[p_device];
  823. JoyEvent map[HAT_MAX];
  824. map[HatDir::HAT_UP].type = TYPE_BUTTON;
  825. map[HatDir::HAT_UP].index = JOY_BUTTON_DPAD_UP;
  826. map[HatDir::HAT_UP].value = 0;
  827. map[HatDir::HAT_RIGHT].type = TYPE_BUTTON;
  828. map[HatDir::HAT_RIGHT].index = JOY_BUTTON_DPAD_RIGHT;
  829. map[HatDir::HAT_RIGHT].value = 0;
  830. map[HatDir::HAT_DOWN].type = TYPE_BUTTON;
  831. map[HatDir::HAT_DOWN].index = JOY_BUTTON_DPAD_DOWN;
  832. map[HatDir::HAT_DOWN].value = 0;
  833. map[HatDir::HAT_LEFT].type = TYPE_BUTTON;
  834. map[HatDir::HAT_LEFT].index = JOY_BUTTON_DPAD_LEFT;
  835. map[HatDir::HAT_LEFT].value = 0;
  836. if (joy.mapping != -1) {
  837. _get_mapped_hat_events(map_db[joy.mapping], (HatDir)0, map);
  838. }
  839. int cur_val = joy_names[p_device].hat_current;
  840. for (int hat_direction = 0, hat_mask = 1; hat_direction < HAT_MAX; hat_direction++, hat_mask <<= 1) {
  841. if ((p_val & hat_mask) != (cur_val & hat_mask)) {
  842. if (map[hat_direction].type == TYPE_BUTTON) {
  843. _button_event(p_device, (JoyButton)map[hat_direction].index, p_val & hat_mask);
  844. }
  845. if (map[hat_direction].type == TYPE_AXIS) {
  846. _axis_event(p_device, (JoyAxis)map[hat_direction].index, (p_val & hat_mask) ? map[hat_direction].value : 0.0);
  847. }
  848. }
  849. }
  850. joy_names[p_device].hat_current = p_val;
  851. }
  852. void Input::_button_event(int p_device, JoyButton p_index, bool p_pressed) {
  853. Ref<InputEventJoypadButton> ievent;
  854. ievent.instantiate();
  855. ievent->set_device(p_device);
  856. ievent->set_button_index(p_index);
  857. ievent->set_pressed(p_pressed);
  858. parse_input_event(ievent);
  859. }
  860. void Input::_axis_event(int p_device, JoyAxis p_axis, float p_value) {
  861. Ref<InputEventJoypadMotion> ievent;
  862. ievent.instantiate();
  863. ievent->set_device(p_device);
  864. ievent->set_axis(p_axis);
  865. ievent->set_axis_value(p_value);
  866. parse_input_event(ievent);
  867. }
  868. Input::JoyEvent Input::_get_mapped_button_event(const JoyDeviceMapping &mapping, JoyButton p_button) {
  869. JoyEvent event;
  870. event.type = TYPE_MAX;
  871. for (int i = 0; i < mapping.bindings.size(); i++) {
  872. const JoyBinding binding = mapping.bindings[i];
  873. if (binding.inputType == TYPE_BUTTON && binding.input.button == p_button) {
  874. event.type = binding.outputType;
  875. switch (binding.outputType) {
  876. case TYPE_BUTTON:
  877. event.index = binding.output.button;
  878. return event;
  879. case TYPE_AXIS:
  880. event.index = binding.output.axis.axis;
  881. switch (binding.output.axis.range) {
  882. case POSITIVE_HALF_AXIS:
  883. event.value = 1;
  884. break;
  885. case NEGATIVE_HALF_AXIS:
  886. event.value = -1;
  887. break;
  888. case FULL_AXIS:
  889. // It doesn't make sense for a button to map to a full axis,
  890. // but keeping as a default for a trigger with a positive half-axis.
  891. event.value = 1;
  892. break;
  893. }
  894. return event;
  895. default:
  896. ERR_PRINT_ONCE("Joypad button mapping error.");
  897. }
  898. }
  899. }
  900. return event;
  901. }
  902. Input::JoyEvent Input::_get_mapped_axis_event(const JoyDeviceMapping &mapping, JoyAxis p_axis, float p_value) {
  903. JoyEvent event;
  904. event.type = TYPE_MAX;
  905. for (int i = 0; i < mapping.bindings.size(); i++) {
  906. const JoyBinding binding = mapping.bindings[i];
  907. if (binding.inputType == TYPE_AXIS && binding.input.axis.axis == p_axis) {
  908. float value = p_value;
  909. if (binding.input.axis.invert) {
  910. value = -value;
  911. }
  912. if (binding.input.axis.range == FULL_AXIS ||
  913. (binding.input.axis.range == POSITIVE_HALF_AXIS && value > 0) ||
  914. (binding.input.axis.range == NEGATIVE_HALF_AXIS && value < 0)) {
  915. event.type = binding.outputType;
  916. float shifted_positive_value = 0;
  917. switch (binding.input.axis.range) {
  918. case POSITIVE_HALF_AXIS:
  919. shifted_positive_value = value;
  920. break;
  921. case NEGATIVE_HALF_AXIS:
  922. shifted_positive_value = value + 1;
  923. break;
  924. case FULL_AXIS:
  925. shifted_positive_value = (value + 1) / 2;
  926. break;
  927. }
  928. switch (binding.outputType) {
  929. case TYPE_BUTTON:
  930. event.index = binding.output.button;
  931. switch (binding.input.axis.range) {
  932. case POSITIVE_HALF_AXIS:
  933. event.value = shifted_positive_value;
  934. break;
  935. case NEGATIVE_HALF_AXIS:
  936. event.value = 1 - shifted_positive_value;
  937. break;
  938. case FULL_AXIS:
  939. // It doesn't make sense for a full axis to map to a button,
  940. // but keeping as a default for a trigger with a positive half-axis.
  941. event.value = (shifted_positive_value * 2) - 1;
  942. ;
  943. break;
  944. }
  945. return event;
  946. case TYPE_AXIS:
  947. event.index = binding.output.axis.axis;
  948. event.value = value;
  949. if (binding.output.axis.range != binding.input.axis.range) {
  950. switch (binding.output.axis.range) {
  951. case POSITIVE_HALF_AXIS:
  952. event.value = shifted_positive_value;
  953. break;
  954. case NEGATIVE_HALF_AXIS:
  955. event.value = shifted_positive_value - 1;
  956. break;
  957. case FULL_AXIS:
  958. event.value = (shifted_positive_value * 2) - 1;
  959. break;
  960. }
  961. }
  962. return event;
  963. default:
  964. ERR_PRINT_ONCE("Joypad axis mapping error.");
  965. }
  966. }
  967. }
  968. }
  969. return event;
  970. }
  971. void Input::_get_mapped_hat_events(const JoyDeviceMapping &mapping, HatDir p_hat, JoyEvent r_events[]) {
  972. for (int i = 0; i < mapping.bindings.size(); i++) {
  973. const JoyBinding binding = mapping.bindings[i];
  974. if (binding.inputType == TYPE_HAT && binding.input.hat.hat == p_hat) {
  975. int hat_direction;
  976. switch (binding.input.hat.hat_mask) {
  977. case HatMask::HAT_MASK_UP:
  978. hat_direction = HatDir::HAT_UP;
  979. break;
  980. case HatMask::HAT_MASK_RIGHT:
  981. hat_direction = HatDir::HAT_RIGHT;
  982. break;
  983. case HatMask::HAT_MASK_DOWN:
  984. hat_direction = HatDir::HAT_DOWN;
  985. break;
  986. case HatMask::HAT_MASK_LEFT:
  987. hat_direction = HatDir::HAT_LEFT;
  988. break;
  989. default:
  990. ERR_PRINT_ONCE("Joypad button mapping error.");
  991. continue;
  992. }
  993. r_events[hat_direction].type = binding.outputType;
  994. switch (binding.outputType) {
  995. case TYPE_BUTTON:
  996. r_events[hat_direction].index = binding.output.button;
  997. break;
  998. case TYPE_AXIS:
  999. r_events[hat_direction].index = binding.output.axis.axis;
  1000. switch (binding.output.axis.range) {
  1001. case POSITIVE_HALF_AXIS:
  1002. r_events[hat_direction].value = 1;
  1003. break;
  1004. case NEGATIVE_HALF_AXIS:
  1005. r_events[hat_direction].value = -1;
  1006. break;
  1007. case FULL_AXIS:
  1008. // It doesn't make sense for a hat direction to map to a full axis,
  1009. // but keeping as a default for a trigger with a positive half-axis.
  1010. r_events[hat_direction].value = 1;
  1011. break;
  1012. }
  1013. break;
  1014. default:
  1015. ERR_PRINT_ONCE("Joypad button mapping error.");
  1016. }
  1017. }
  1018. }
  1019. }
  1020. JoyButton Input::_get_output_button(String output) {
  1021. for (int i = 0; i < JOY_BUTTON_SDL_MAX; i++) {
  1022. if (output == _joy_buttons[i]) {
  1023. return JoyButton(i);
  1024. }
  1025. }
  1026. return JoyButton::JOY_BUTTON_INVALID;
  1027. }
  1028. JoyAxis Input::_get_output_axis(String output) {
  1029. for (int i = 0; i < JOY_AXIS_SDL_MAX; i++) {
  1030. if (output == _joy_axes[i]) {
  1031. return JoyAxis(i);
  1032. }
  1033. }
  1034. return JoyAxis::JOY_AXIS_INVALID;
  1035. }
  1036. void Input::parse_mapping(String p_mapping) {
  1037. _THREAD_SAFE_METHOD_;
  1038. JoyDeviceMapping mapping;
  1039. Vector<String> entry = p_mapping.split(",");
  1040. if (entry.size() < 2) {
  1041. return;
  1042. }
  1043. CharString uid;
  1044. uid.resize(17);
  1045. mapping.uid = entry[0];
  1046. mapping.name = entry[1];
  1047. int idx = 1;
  1048. while (++idx < entry.size()) {
  1049. if (entry[idx] == "") {
  1050. continue;
  1051. }
  1052. String output = entry[idx].get_slice(":", 0).replace(" ", "");
  1053. String input = entry[idx].get_slice(":", 1).replace(" ", "");
  1054. ERR_CONTINUE_MSG(output.length() < 1 || input.length() < 2,
  1055. vformat("Invalid device mapping entry \"%s\" in mapping:\n%s", entry[idx], p_mapping));
  1056. if (output == "platform" || output == "hint") {
  1057. continue;
  1058. }
  1059. JoyAxisRange output_range = FULL_AXIS;
  1060. if (output[0] == '+' || output[0] == '-') {
  1061. ERR_CONTINUE_MSG(output.length() < 2,
  1062. vformat("Invalid output entry \"%s\" in mapping:\n%s", entry[idx], p_mapping));
  1063. if (output[0] == '+') {
  1064. output_range = POSITIVE_HALF_AXIS;
  1065. } else if (output[0] == '-') {
  1066. output_range = NEGATIVE_HALF_AXIS;
  1067. }
  1068. output = output.substr(1);
  1069. }
  1070. JoyAxisRange input_range = FULL_AXIS;
  1071. if (input[0] == '+') {
  1072. input_range = POSITIVE_HALF_AXIS;
  1073. input = input.substr(1);
  1074. } else if (input[0] == '-') {
  1075. input_range = NEGATIVE_HALF_AXIS;
  1076. input = input.substr(1);
  1077. }
  1078. bool invert_axis = false;
  1079. if (input[input.length() - 1] == '~') {
  1080. invert_axis = true;
  1081. input = input.left(input.length() - 1);
  1082. }
  1083. JoyButton output_button = _get_output_button(output);
  1084. JoyAxis output_axis = _get_output_axis(output);
  1085. ERR_CONTINUE_MSG(output_button == JOY_BUTTON_INVALID && output_axis == JOY_AXIS_INVALID,
  1086. vformat("Unrecognised output string \"%s\" in mapping:\n%s", output, p_mapping));
  1087. ERR_CONTINUE_MSG(output_button != JOY_BUTTON_INVALID && output_axis != JOY_AXIS_INVALID,
  1088. vformat("Output string \"%s\" matched both button and axis in mapping:\n%s", output, p_mapping));
  1089. JoyBinding binding;
  1090. if (output_button != JOY_BUTTON_INVALID) {
  1091. binding.outputType = TYPE_BUTTON;
  1092. binding.output.button = output_button;
  1093. } else if (output_axis != JOY_AXIS_INVALID) {
  1094. binding.outputType = TYPE_AXIS;
  1095. binding.output.axis.axis = output_axis;
  1096. binding.output.axis.range = output_range;
  1097. }
  1098. switch (input[0]) {
  1099. case 'b':
  1100. binding.inputType = TYPE_BUTTON;
  1101. binding.input.button = (JoyButton)input.substr(1).to_int();
  1102. break;
  1103. case 'a':
  1104. binding.inputType = TYPE_AXIS;
  1105. binding.input.axis.axis = (JoyAxis)input.substr(1).to_int();
  1106. binding.input.axis.range = input_range;
  1107. binding.input.axis.invert = invert_axis;
  1108. break;
  1109. case 'h':
  1110. ERR_CONTINUE_MSG(input.length() != 4 || input[2] != '.',
  1111. vformat("Invalid had input \"%s\" in mapping:\n%s", input, p_mapping));
  1112. binding.inputType = TYPE_HAT;
  1113. binding.input.hat.hat = (HatDir)input.substr(1, 1).to_int();
  1114. binding.input.hat.hat_mask = static_cast<HatMask>(input.substr(3).to_int());
  1115. break;
  1116. default:
  1117. ERR_CONTINUE_MSG(true, vformat("Unrecognized input string \"%s\" in mapping:\n%s", input, p_mapping));
  1118. }
  1119. mapping.bindings.push_back(binding);
  1120. }
  1121. map_db.push_back(mapping);
  1122. }
  1123. void Input::add_joy_mapping(String p_mapping, bool p_update_existing) {
  1124. parse_mapping(p_mapping);
  1125. if (p_update_existing) {
  1126. Vector<String> entry = p_mapping.split(",");
  1127. String uid = entry[0];
  1128. for (KeyValue<int, Joypad> &E : joy_names) {
  1129. Joypad &joy = E.value;
  1130. if (joy.uid == uid) {
  1131. joy.mapping = map_db.size() - 1;
  1132. }
  1133. }
  1134. }
  1135. }
  1136. void Input::remove_joy_mapping(String p_guid) {
  1137. for (int i = map_db.size() - 1; i >= 0; i--) {
  1138. if (p_guid == map_db[i].uid) {
  1139. map_db.remove(i);
  1140. }
  1141. }
  1142. for (KeyValue<int, Joypad> &E : joy_names) {
  1143. Joypad &joy = E.value;
  1144. if (joy.uid == p_guid) {
  1145. joy.mapping = -1;
  1146. }
  1147. }
  1148. }
  1149. void Input::set_fallback_mapping(String p_guid) {
  1150. for (int i = 0; i < map_db.size(); i++) {
  1151. if (map_db[i].uid == p_guid) {
  1152. fallback_mapping = i;
  1153. return;
  1154. }
  1155. }
  1156. }
  1157. //platforms that use the remapping system can override and call to these ones
  1158. bool Input::is_joy_known(int p_device) {
  1159. if (joy_names.has(p_device)) {
  1160. int mapping = joy_names[p_device].mapping;
  1161. if (mapping != -1 && mapping != fallback_mapping) {
  1162. return true;
  1163. }
  1164. }
  1165. return false;
  1166. }
  1167. String Input::get_joy_guid(int p_device) const {
  1168. ERR_FAIL_COND_V(!joy_names.has(p_device), "");
  1169. return joy_names[p_device].uid;
  1170. }
  1171. Array Input::get_connected_joypads() {
  1172. Array ret;
  1173. Map<int, Joypad>::Element *elem = joy_names.front();
  1174. while (elem) {
  1175. if (elem->get().connected) {
  1176. ret.push_back(elem->key());
  1177. }
  1178. elem = elem->next();
  1179. }
  1180. return ret;
  1181. }
  1182. int Input::get_unused_joy_id() {
  1183. for (int i = 0; i < JOYPADS_MAX; i++) {
  1184. if (!joy_names.has(i) || !joy_names[i].connected) {
  1185. return i;
  1186. }
  1187. }
  1188. return -1;
  1189. }
  1190. Input::Input() {
  1191. singleton = this;
  1192. // Parse default mappings.
  1193. {
  1194. int i = 0;
  1195. while (DefaultControllerMappings::mappings[i]) {
  1196. parse_mapping(DefaultControllerMappings::mappings[i++]);
  1197. }
  1198. }
  1199. // If defined, parse SDL_GAMECONTROLLERCONFIG for possible new mappings/overrides.
  1200. String env_mapping = OS::get_singleton()->get_environment("SDL_GAMECONTROLLERCONFIG");
  1201. if (env_mapping != "") {
  1202. Vector<String> entries = env_mapping.split("\n");
  1203. for (int i = 0; i < entries.size(); i++) {
  1204. if (entries[i] == "") {
  1205. continue;
  1206. }
  1207. parse_mapping(entries[i]);
  1208. }
  1209. }
  1210. }
  1211. //////////////////////////////////////////////////////////