input.cpp 46 KB

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