input.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. /**************************************************************************/
  2. /* input.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "input.compat.inc"
  32. #include "core/config/project_settings.h"
  33. #include "core/input/default_controller_mappings.h"
  34. #include "core/input/input_map.h"
  35. #include "core/os/os.h"
  36. #ifdef DEV_ENABLED
  37. #include "core/os/thread.h"
  38. #endif
  39. static const char *_joy_buttons[(size_t)JoyButton::SDL_MAX] = {
  40. "a",
  41. "b",
  42. "x",
  43. "y",
  44. "back",
  45. "guide",
  46. "start",
  47. "leftstick",
  48. "rightstick",
  49. "leftshoulder",
  50. "rightshoulder",
  51. "dpup",
  52. "dpdown",
  53. "dpleft",
  54. "dpright",
  55. "misc1",
  56. "paddle1",
  57. "paddle2",
  58. "paddle3",
  59. "paddle4",
  60. "touchpad",
  61. };
  62. static const char *_joy_axes[(size_t)JoyAxis::SDL_MAX] = {
  63. "leftx",
  64. "lefty",
  65. "rightx",
  66. "righty",
  67. "lefttrigger",
  68. "righttrigger",
  69. };
  70. Input *Input::singleton = nullptr;
  71. void (*Input::set_mouse_mode_func)(Input::MouseMode) = nullptr;
  72. Input::MouseMode (*Input::get_mouse_mode_func)() = nullptr;
  73. void (*Input::warp_mouse_func)(const Vector2 &p_position) = nullptr;
  74. Input::CursorShape (*Input::get_current_cursor_shape_func)() = nullptr;
  75. void (*Input::set_custom_mouse_cursor_func)(const Ref<Resource> &, Input::CursorShape, const Vector2 &) = nullptr;
  76. Input *Input::get_singleton() {
  77. return singleton;
  78. }
  79. void Input::set_mouse_mode(MouseMode p_mode) {
  80. ERR_FAIL_INDEX((int)p_mode, 5);
  81. set_mouse_mode_func(p_mode);
  82. }
  83. Input::MouseMode Input::get_mouse_mode() const {
  84. return get_mouse_mode_func();
  85. }
  86. void Input::_bind_methods() {
  87. ClassDB::bind_method(D_METHOD("is_anything_pressed"), &Input::is_anything_pressed);
  88. ClassDB::bind_method(D_METHOD("is_key_pressed", "keycode"), &Input::is_key_pressed);
  89. ClassDB::bind_method(D_METHOD("is_physical_key_pressed", "keycode"), &Input::is_physical_key_pressed);
  90. ClassDB::bind_method(D_METHOD("is_key_label_pressed", "keycode"), &Input::is_key_label_pressed);
  91. ClassDB::bind_method(D_METHOD("is_mouse_button_pressed", "button"), &Input::is_mouse_button_pressed);
  92. ClassDB::bind_method(D_METHOD("is_joy_button_pressed", "device", "button"), &Input::is_joy_button_pressed);
  93. ClassDB::bind_method(D_METHOD("is_action_pressed", "action", "exact_match"), &Input::is_action_pressed, DEFVAL(false));
  94. ClassDB::bind_method(D_METHOD("is_action_just_pressed", "action", "exact_match"), &Input::is_action_just_pressed, DEFVAL(false));
  95. ClassDB::bind_method(D_METHOD("is_action_just_released", "action", "exact_match"), &Input::is_action_just_released, DEFVAL(false));
  96. ClassDB::bind_method(D_METHOD("get_action_strength", "action", "exact_match"), &Input::get_action_strength, DEFVAL(false));
  97. ClassDB::bind_method(D_METHOD("get_action_raw_strength", "action", "exact_match"), &Input::get_action_raw_strength, DEFVAL(false));
  98. ClassDB::bind_method(D_METHOD("get_axis", "negative_action", "positive_action"), &Input::get_axis);
  99. ClassDB::bind_method(D_METHOD("get_vector", "negative_x", "positive_x", "negative_y", "positive_y", "deadzone"), &Input::get_vector, DEFVAL(-1.0f));
  100. ClassDB::bind_method(D_METHOD("add_joy_mapping", "mapping", "update_existing"), &Input::add_joy_mapping, DEFVAL(false));
  101. ClassDB::bind_method(D_METHOD("remove_joy_mapping", "guid"), &Input::remove_joy_mapping);
  102. ClassDB::bind_method(D_METHOD("is_joy_known", "device"), &Input::is_joy_known);
  103. ClassDB::bind_method(D_METHOD("get_joy_axis", "device", "axis"), &Input::get_joy_axis);
  104. ClassDB::bind_method(D_METHOD("get_joy_name", "device"), &Input::get_joy_name);
  105. ClassDB::bind_method(D_METHOD("get_joy_guid", "device"), &Input::get_joy_guid);
  106. ClassDB::bind_method(D_METHOD("get_joy_info", "device"), &Input::get_joy_info);
  107. ClassDB::bind_method(D_METHOD("should_ignore_device", "vendor_id", "product_id"), &Input::should_ignore_device);
  108. ClassDB::bind_method(D_METHOD("get_connected_joypads"), &Input::get_connected_joypads);
  109. ClassDB::bind_method(D_METHOD("get_joy_vibration_strength", "device"), &Input::get_joy_vibration_strength);
  110. ClassDB::bind_method(D_METHOD("get_joy_vibration_duration", "device"), &Input::get_joy_vibration_duration);
  111. ClassDB::bind_method(D_METHOD("start_joy_vibration", "device", "weak_magnitude", "strong_magnitude", "duration"), &Input::start_joy_vibration, DEFVAL(0));
  112. ClassDB::bind_method(D_METHOD("stop_joy_vibration", "device"), &Input::stop_joy_vibration);
  113. ClassDB::bind_method(D_METHOD("vibrate_handheld", "duration_ms", "amplitude"), &Input::vibrate_handheld, DEFVAL(500), DEFVAL(-1.0));
  114. ClassDB::bind_method(D_METHOD("get_gravity"), &Input::get_gravity);
  115. ClassDB::bind_method(D_METHOD("get_accelerometer"), &Input::get_accelerometer);
  116. ClassDB::bind_method(D_METHOD("get_magnetometer"), &Input::get_magnetometer);
  117. ClassDB::bind_method(D_METHOD("get_gyroscope"), &Input::get_gyroscope);
  118. ClassDB::bind_method(D_METHOD("set_gravity", "value"), &Input::set_gravity);
  119. ClassDB::bind_method(D_METHOD("set_accelerometer", "value"), &Input::set_accelerometer);
  120. ClassDB::bind_method(D_METHOD("set_magnetometer", "value"), &Input::set_magnetometer);
  121. ClassDB::bind_method(D_METHOD("set_gyroscope", "value"), &Input::set_gyroscope);
  122. ClassDB::bind_method(D_METHOD("get_last_mouse_velocity"), &Input::get_last_mouse_velocity);
  123. ClassDB::bind_method(D_METHOD("get_last_mouse_screen_velocity"), &Input::get_last_mouse_screen_velocity);
  124. ClassDB::bind_method(D_METHOD("get_mouse_button_mask"), &Input::get_mouse_button_mask);
  125. ClassDB::bind_method(D_METHOD("set_mouse_mode", "mode"), &Input::set_mouse_mode);
  126. ClassDB::bind_method(D_METHOD("get_mouse_mode"), &Input::get_mouse_mode);
  127. ClassDB::bind_method(D_METHOD("warp_mouse", "position"), &Input::warp_mouse);
  128. ClassDB::bind_method(D_METHOD("action_press", "action", "strength"), &Input::action_press, DEFVAL(1.f));
  129. ClassDB::bind_method(D_METHOD("action_release", "action"), &Input::action_release);
  130. ClassDB::bind_method(D_METHOD("set_default_cursor_shape", "shape"), &Input::set_default_cursor_shape, DEFVAL(CURSOR_ARROW));
  131. ClassDB::bind_method(D_METHOD("get_current_cursor_shape"), &Input::get_current_cursor_shape);
  132. ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor", "image", "shape", "hotspot"), &Input::set_custom_mouse_cursor, DEFVAL(CURSOR_ARROW), DEFVAL(Vector2()));
  133. ClassDB::bind_method(D_METHOD("parse_input_event", "event"), &Input::parse_input_event);
  134. ClassDB::bind_method(D_METHOD("set_use_accumulated_input", "enable"), &Input::set_use_accumulated_input);
  135. ClassDB::bind_method(D_METHOD("is_using_accumulated_input"), &Input::is_using_accumulated_input);
  136. ClassDB::bind_method(D_METHOD("flush_buffered_events"), &Input::flush_buffered_events);
  137. ClassDB::bind_method(D_METHOD("set_emulate_mouse_from_touch", "enable"), &Input::set_emulate_mouse_from_touch);
  138. ClassDB::bind_method(D_METHOD("is_emulating_mouse_from_touch"), &Input::is_emulating_mouse_from_touch);
  139. ClassDB::bind_method(D_METHOD("set_emulate_touch_from_mouse", "enable"), &Input::set_emulate_touch_from_mouse);
  140. ClassDB::bind_method(D_METHOD("is_emulating_touch_from_mouse"), &Input::is_emulating_touch_from_mouse);
  141. ADD_PROPERTY(PropertyInfo(Variant::INT, "mouse_mode"), "set_mouse_mode", "get_mouse_mode");
  142. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_accumulated_input"), "set_use_accumulated_input", "is_using_accumulated_input");
  143. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emulate_mouse_from_touch"), "set_emulate_mouse_from_touch", "is_emulating_mouse_from_touch");
  144. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emulate_touch_from_mouse"), "set_emulate_touch_from_mouse", "is_emulating_touch_from_mouse");
  145. BIND_ENUM_CONSTANT(MOUSE_MODE_VISIBLE);
  146. BIND_ENUM_CONSTANT(MOUSE_MODE_HIDDEN);
  147. BIND_ENUM_CONSTANT(MOUSE_MODE_CAPTURED);
  148. BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED);
  149. BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED_HIDDEN);
  150. BIND_ENUM_CONSTANT(CURSOR_ARROW);
  151. BIND_ENUM_CONSTANT(CURSOR_IBEAM);
  152. BIND_ENUM_CONSTANT(CURSOR_POINTING_HAND);
  153. BIND_ENUM_CONSTANT(CURSOR_CROSS);
  154. BIND_ENUM_CONSTANT(CURSOR_WAIT);
  155. BIND_ENUM_CONSTANT(CURSOR_BUSY);
  156. BIND_ENUM_CONSTANT(CURSOR_DRAG);
  157. BIND_ENUM_CONSTANT(CURSOR_CAN_DROP);
  158. BIND_ENUM_CONSTANT(CURSOR_FORBIDDEN);
  159. BIND_ENUM_CONSTANT(CURSOR_VSIZE);
  160. BIND_ENUM_CONSTANT(CURSOR_HSIZE);
  161. BIND_ENUM_CONSTANT(CURSOR_BDIAGSIZE);
  162. BIND_ENUM_CONSTANT(CURSOR_FDIAGSIZE);
  163. BIND_ENUM_CONSTANT(CURSOR_MOVE);
  164. BIND_ENUM_CONSTANT(CURSOR_VSPLIT);
  165. BIND_ENUM_CONSTANT(CURSOR_HSPLIT);
  166. BIND_ENUM_CONSTANT(CURSOR_HELP);
  167. ADD_SIGNAL(MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "device"), PropertyInfo(Variant::BOOL, "connected")));
  168. }
  169. #ifdef TOOLS_ENABLED
  170. void Input::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  171. const String pf = p_function;
  172. 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")) ||
  173. (p_idx < 2 && pf == "get_axis") ||
  174. (p_idx < 4 && pf == "get_vector")) {
  175. List<PropertyInfo> pinfo;
  176. ProjectSettings::get_singleton()->get_property_list(&pinfo);
  177. for (const PropertyInfo &pi : pinfo) {
  178. if (!pi.name.begins_with("input/")) {
  179. continue;
  180. }
  181. String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
  182. r_options->push_back(name.quote());
  183. }
  184. }
  185. Object::get_argument_options(p_function, p_idx, r_options);
  186. }
  187. #endif
  188. void Input::VelocityTrack::update(const Vector2 &p_delta_p, const Vector2 &p_screen_delta_p) {
  189. uint64_t tick = OS::get_singleton()->get_ticks_usec();
  190. uint32_t tdiff = tick - last_tick;
  191. float delta_t = tdiff / 1000000.0;
  192. last_tick = tick;
  193. if (delta_t > max_ref_frame) {
  194. // First movement in a long time, reset and start again.
  195. velocity = Vector2();
  196. screen_velocity = Vector2();
  197. accum = p_delta_p;
  198. screen_accum = p_screen_delta_p;
  199. accum_t = 0;
  200. return;
  201. }
  202. accum += p_delta_p;
  203. screen_accum += p_screen_delta_p;
  204. accum_t += delta_t;
  205. if (accum_t < min_ref_frame) {
  206. // Not enough time has passed to calculate speed precisely.
  207. return;
  208. }
  209. velocity = accum / accum_t;
  210. screen_velocity = screen_accum / accum_t;
  211. accum = Vector2();
  212. accum_t = 0;
  213. }
  214. void Input::VelocityTrack::reset() {
  215. last_tick = OS::get_singleton()->get_ticks_usec();
  216. velocity = Vector2();
  217. accum = Vector2();
  218. accum_t = 0;
  219. }
  220. Input::VelocityTrack::VelocityTrack() {
  221. min_ref_frame = 0.1;
  222. max_ref_frame = 3.0;
  223. reset();
  224. }
  225. bool Input::is_anything_pressed() const {
  226. _THREAD_SAFE_METHOD_
  227. if (!keys_pressed.is_empty() || !joy_buttons_pressed.is_empty() || !mouse_button_mask.is_empty()) {
  228. return true;
  229. }
  230. for (const KeyValue<StringName, Input::ActionState> &E : action_states) {
  231. if (E.value.cache.pressed) {
  232. return true;
  233. }
  234. }
  235. return false;
  236. }
  237. bool Input::is_key_pressed(Key p_keycode) const {
  238. _THREAD_SAFE_METHOD_
  239. return keys_pressed.has(p_keycode);
  240. }
  241. bool Input::is_physical_key_pressed(Key p_keycode) const {
  242. _THREAD_SAFE_METHOD_
  243. return physical_keys_pressed.has(p_keycode);
  244. }
  245. bool Input::is_key_label_pressed(Key p_keycode) const {
  246. _THREAD_SAFE_METHOD_
  247. return key_label_pressed.has(p_keycode);
  248. }
  249. bool Input::is_mouse_button_pressed(MouseButton p_button) const {
  250. _THREAD_SAFE_METHOD_
  251. return mouse_button_mask.has_flag(mouse_button_to_mask(p_button));
  252. }
  253. static JoyAxis _combine_device(JoyAxis p_value, int p_device) {
  254. return JoyAxis((int)p_value | (p_device << 20));
  255. }
  256. static JoyButton _combine_device(JoyButton p_value, int p_device) {
  257. return JoyButton((int)p_value | (p_device << 20));
  258. }
  259. bool Input::is_joy_button_pressed(int p_device, JoyButton p_button) const {
  260. _THREAD_SAFE_METHOD_
  261. return joy_buttons_pressed.has(_combine_device(p_button, p_device));
  262. }
  263. bool Input::is_action_pressed(const StringName &p_action, bool p_exact) const {
  264. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  265. HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
  266. if (!E) {
  267. return false;
  268. }
  269. return E->value.cache.pressed && (p_exact ? E->value.exact : true);
  270. }
  271. bool Input::is_action_just_pressed(const StringName &p_action, bool p_exact) const {
  272. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  273. HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
  274. if (!E) {
  275. return false;
  276. }
  277. if (p_exact && E->value.exact == false) {
  278. return false;
  279. }
  280. // Backward compatibility for legacy behavior, only return true if currently pressed.
  281. bool pressed_requirement = legacy_just_pressed_behavior ? E->value.cache.pressed : true;
  282. if (Engine::get_singleton()->is_in_physics_frame()) {
  283. return pressed_requirement && E->value.pressed_physics_frame == Engine::get_singleton()->get_physics_frames();
  284. } else {
  285. return pressed_requirement && E->value.pressed_process_frame == Engine::get_singleton()->get_process_frames();
  286. }
  287. }
  288. bool Input::is_action_just_released(const StringName &p_action, bool p_exact) const {
  289. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  290. HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
  291. if (!E) {
  292. return false;
  293. }
  294. if (p_exact && E->value.exact == false) {
  295. return false;
  296. }
  297. // Backward compatibility for legacy behavior, only return true if currently released.
  298. bool released_requirement = legacy_just_pressed_behavior ? !E->value.cache.pressed : true;
  299. if (Engine::get_singleton()->is_in_physics_frame()) {
  300. return released_requirement && E->value.released_physics_frame == Engine::get_singleton()->get_physics_frames();
  301. } else {
  302. return released_requirement && E->value.released_process_frame == Engine::get_singleton()->get_process_frames();
  303. }
  304. }
  305. float Input::get_action_strength(const StringName &p_action, bool p_exact) const {
  306. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
  307. HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
  308. if (!E) {
  309. return 0.0f;
  310. }
  311. if (p_exact && E->value.exact == false) {
  312. return 0.0f;
  313. }
  314. return E->value.cache.strength;
  315. }
  316. float Input::get_action_raw_strength(const StringName &p_action, bool p_exact) const {
  317. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
  318. HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
  319. if (!E) {
  320. return 0.0f;
  321. }
  322. if (p_exact && E->value.exact == false) {
  323. return 0.0f;
  324. }
  325. return E->value.cache.raw_strength;
  326. }
  327. float Input::get_axis(const StringName &p_negative_action, const StringName &p_positive_action) const {
  328. return get_action_strength(p_positive_action) - get_action_strength(p_negative_action);
  329. }
  330. 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 {
  331. Vector2 vector = Vector2(
  332. get_action_raw_strength(p_positive_x) - get_action_raw_strength(p_negative_x),
  333. get_action_raw_strength(p_positive_y) - get_action_raw_strength(p_negative_y));
  334. if (p_deadzone < 0.0f) {
  335. // If the deadzone isn't specified, get it from the average of the actions.
  336. p_deadzone = 0.25 *
  337. (InputMap::get_singleton()->action_get_deadzone(p_positive_x) +
  338. InputMap::get_singleton()->action_get_deadzone(p_negative_x) +
  339. InputMap::get_singleton()->action_get_deadzone(p_positive_y) +
  340. InputMap::get_singleton()->action_get_deadzone(p_negative_y));
  341. }
  342. // Circular length limiting and deadzone.
  343. float length = vector.length();
  344. if (length <= p_deadzone) {
  345. return Vector2();
  346. } else if (length > 1.0f) {
  347. return vector / length;
  348. } else {
  349. // Inverse lerp length to map (p_deadzone, 1) to (0, 1).
  350. return vector * (Math::inverse_lerp(p_deadzone, 1.0f, length) / length);
  351. }
  352. }
  353. float Input::get_joy_axis(int p_device, JoyAxis p_axis) const {
  354. _THREAD_SAFE_METHOD_
  355. JoyAxis c = _combine_device(p_axis, p_device);
  356. if (_joy_axis.has(c)) {
  357. return _joy_axis[c];
  358. } else {
  359. return 0;
  360. }
  361. }
  362. String Input::get_joy_name(int p_idx) {
  363. _THREAD_SAFE_METHOD_
  364. return joy_names[p_idx].name;
  365. }
  366. Vector2 Input::get_joy_vibration_strength(int p_device) {
  367. if (joy_vibration.has(p_device)) {
  368. return Vector2(joy_vibration[p_device].weak_magnitude, joy_vibration[p_device].strong_magnitude);
  369. } else {
  370. return Vector2(0, 0);
  371. }
  372. }
  373. uint64_t Input::get_joy_vibration_timestamp(int p_device) {
  374. if (joy_vibration.has(p_device)) {
  375. return joy_vibration[p_device].timestamp;
  376. } else {
  377. return 0;
  378. }
  379. }
  380. float Input::get_joy_vibration_duration(int p_device) {
  381. if (joy_vibration.has(p_device)) {
  382. return joy_vibration[p_device].duration;
  383. } else {
  384. return 0.f;
  385. }
  386. }
  387. static String _hex_str(uint8_t p_byte) {
  388. static const char *dict = "0123456789abcdef";
  389. char ret[3];
  390. ret[2] = 0;
  391. ret[0] = dict[p_byte >> 4];
  392. ret[1] = dict[p_byte & 0xf];
  393. return ret;
  394. }
  395. void Input::joy_connection_changed(int p_idx, bool p_connected, const String &p_name, const String &p_guid, const Dictionary &p_joypad_info) {
  396. _THREAD_SAFE_METHOD_
  397. // Clear the pressed status if a Joypad gets disconnected.
  398. if (!p_connected) {
  399. for (KeyValue<StringName, ActionState> &E : action_states) {
  400. HashMap<int, ActionState::DeviceState>::Iterator it = E.value.device_states.find(p_idx);
  401. if (it) {
  402. E.value.device_states.remove(it);
  403. _update_action_cache(E.key, E.value);
  404. }
  405. }
  406. }
  407. Joypad js;
  408. js.name = p_connected ? p_name : "";
  409. js.uid = p_connected ? p_guid : "";
  410. js.info = p_connected ? p_joypad_info : Dictionary();
  411. if (p_connected) {
  412. String uidname = p_guid;
  413. if (p_guid.is_empty()) {
  414. int uidlen = MIN(p_name.length(), 16);
  415. for (int i = 0; i < uidlen; i++) {
  416. uidname = uidname + _hex_str(p_name[i]);
  417. }
  418. }
  419. js.uid = uidname;
  420. js.connected = true;
  421. int mapping = fallback_mapping;
  422. for (int i = 0; i < map_db.size(); i++) {
  423. if (js.uid == map_db[i].uid) {
  424. mapping = i;
  425. js.name = map_db[i].name;
  426. }
  427. }
  428. js.mapping = mapping;
  429. } else {
  430. js.connected = false;
  431. for (int i = 0; i < (int)JoyButton::MAX; i++) {
  432. JoyButton c = _combine_device((JoyButton)i, p_idx);
  433. joy_buttons_pressed.erase(c);
  434. }
  435. for (int i = 0; i < (int)JoyAxis::MAX; i++) {
  436. set_joy_axis(p_idx, (JoyAxis)i, 0.0f);
  437. }
  438. }
  439. joy_names[p_idx] = js;
  440. // Ensure this signal is emitted on the main thread, as some platforms (e.g. Linux) call this from a different thread.
  441. call_deferred("emit_signal", SNAME("joy_connection_changed"), p_idx, p_connected);
  442. }
  443. Vector3 Input::get_gravity() const {
  444. _THREAD_SAFE_METHOD_
  445. return gravity;
  446. }
  447. Vector3 Input::get_accelerometer() const {
  448. _THREAD_SAFE_METHOD_
  449. return accelerometer;
  450. }
  451. Vector3 Input::get_magnetometer() const {
  452. _THREAD_SAFE_METHOD_
  453. return magnetometer;
  454. }
  455. Vector3 Input::get_gyroscope() const {
  456. _THREAD_SAFE_METHOD_
  457. return gyroscope;
  458. }
  459. void Input::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool p_is_emulated) {
  460. // This function does the final delivery of the input event to user land.
  461. // Regardless where the event came from originally, this has to happen on the main thread.
  462. DEV_ASSERT(Thread::get_caller_id() == Thread::get_main_id());
  463. // Notes on mouse-touch emulation:
  464. // - Emulated mouse events are parsed, that is, re-routed to this method, so they make the same effects
  465. // as true mouse events. The only difference is the situation is flagged as emulated so they are not
  466. // emulated back to touch events in an endless loop.
  467. // - Emulated touch events are handed right to the main loop (i.e., the SceneTree) because they don't
  468. // require additional handling by this class.
  469. Ref<InputEventKey> k = p_event;
  470. if (k.is_valid() && !k->is_echo() && k->get_keycode() != Key::NONE) {
  471. if (k->is_pressed()) {
  472. keys_pressed.insert(k->get_keycode());
  473. } else {
  474. keys_pressed.erase(k->get_keycode());
  475. }
  476. }
  477. if (k.is_valid() && !k->is_echo() && k->get_physical_keycode() != Key::NONE) {
  478. if (k->is_pressed()) {
  479. physical_keys_pressed.insert(k->get_physical_keycode());
  480. } else {
  481. physical_keys_pressed.erase(k->get_physical_keycode());
  482. }
  483. }
  484. if (k.is_valid() && !k->is_echo() && k->get_key_label() != Key::NONE) {
  485. if (k->is_pressed()) {
  486. key_label_pressed.insert(k->get_key_label());
  487. } else {
  488. key_label_pressed.erase(k->get_key_label());
  489. }
  490. }
  491. Ref<InputEventMouseButton> mb = p_event;
  492. if (mb.is_valid()) {
  493. if (mb->is_pressed()) {
  494. mouse_button_mask.set_flag(mouse_button_to_mask(mb->get_button_index()));
  495. } else {
  496. mouse_button_mask.clear_flag(mouse_button_to_mask(mb->get_button_index()));
  497. }
  498. Point2 pos = mb->get_global_position();
  499. if (mouse_pos != pos) {
  500. set_mouse_position(pos);
  501. }
  502. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mb->get_button_index() == MouseButton::LEFT) {
  503. Ref<InputEventScreenTouch> touch_event;
  504. touch_event.instantiate();
  505. touch_event->set_pressed(mb->is_pressed());
  506. touch_event->set_canceled(mb->is_canceled());
  507. touch_event->set_position(mb->get_position());
  508. touch_event->set_double_tap(mb->is_double_click());
  509. touch_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  510. _THREAD_SAFE_UNLOCK_
  511. event_dispatch_function(touch_event);
  512. _THREAD_SAFE_LOCK_
  513. }
  514. }
  515. Ref<InputEventMouseMotion> mm = p_event;
  516. if (mm.is_valid()) {
  517. Point2 position = mm->get_global_position();
  518. if (mouse_pos != position) {
  519. set_mouse_position(position);
  520. }
  521. Vector2 relative = mm->get_relative();
  522. Vector2 screen_relative = mm->get_relative_screen_position();
  523. mouse_velocity_track.update(relative, screen_relative);
  524. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mm->get_button_mask().has_flag(MouseButtonMask::LEFT)) {
  525. Ref<InputEventScreenDrag> drag_event;
  526. drag_event.instantiate();
  527. drag_event->set_position(position);
  528. drag_event->set_relative(relative);
  529. drag_event->set_relative_screen_position(screen_relative);
  530. drag_event->set_tilt(mm->get_tilt());
  531. drag_event->set_pen_inverted(mm->get_pen_inverted());
  532. drag_event->set_pressure(mm->get_pressure());
  533. drag_event->set_velocity(get_last_mouse_velocity());
  534. drag_event->set_screen_velocity(get_last_mouse_screen_velocity());
  535. drag_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  536. _THREAD_SAFE_UNLOCK_
  537. event_dispatch_function(drag_event);
  538. _THREAD_SAFE_LOCK_
  539. }
  540. }
  541. Ref<InputEventScreenTouch> st = p_event;
  542. if (st.is_valid()) {
  543. if (st->is_pressed()) {
  544. VelocityTrack &track = touch_velocity_track[st->get_index()];
  545. track.reset();
  546. } else {
  547. // Since a pointer index may not occur again (OSs may or may not reuse them),
  548. // imperatively remove it from the map to keep no fossil entries in it
  549. touch_velocity_track.erase(st->get_index());
  550. }
  551. if (emulate_mouse_from_touch) {
  552. bool translate = false;
  553. if (st->is_pressed()) {
  554. if (mouse_from_touch_index == -1) {
  555. translate = true;
  556. mouse_from_touch_index = st->get_index();
  557. }
  558. } else {
  559. if (st->get_index() == mouse_from_touch_index) {
  560. translate = true;
  561. mouse_from_touch_index = -1;
  562. }
  563. }
  564. if (translate) {
  565. Ref<InputEventMouseButton> button_event;
  566. button_event.instantiate();
  567. button_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  568. button_event->set_position(st->get_position());
  569. button_event->set_global_position(st->get_position());
  570. button_event->set_pressed(st->is_pressed());
  571. button_event->set_canceled(st->is_canceled());
  572. button_event->set_button_index(MouseButton::LEFT);
  573. button_event->set_double_click(st->is_double_tap());
  574. BitField<MouseButtonMask> ev_bm = mouse_button_mask;
  575. if (st->is_pressed()) {
  576. ev_bm.set_flag(MouseButtonMask::LEFT);
  577. } else {
  578. ev_bm.clear_flag(MouseButtonMask::LEFT);
  579. }
  580. button_event->set_button_mask(ev_bm);
  581. _parse_input_event_impl(button_event, true);
  582. }
  583. }
  584. }
  585. Ref<InputEventScreenDrag> sd = p_event;
  586. if (sd.is_valid()) {
  587. VelocityTrack &track = touch_velocity_track[sd->get_index()];
  588. track.update(sd->get_relative(), sd->get_relative_screen_position());
  589. sd->set_velocity(track.velocity);
  590. sd->set_screen_velocity(track.screen_velocity);
  591. if (emulate_mouse_from_touch && sd->get_index() == mouse_from_touch_index) {
  592. Ref<InputEventMouseMotion> motion_event;
  593. motion_event.instantiate();
  594. motion_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  595. motion_event->set_tilt(sd->get_tilt());
  596. motion_event->set_pen_inverted(sd->get_pen_inverted());
  597. motion_event->set_pressure(sd->get_pressure());
  598. motion_event->set_position(sd->get_position());
  599. motion_event->set_global_position(sd->get_position());
  600. motion_event->set_relative(sd->get_relative());
  601. motion_event->set_relative_screen_position(sd->get_relative_screen_position());
  602. motion_event->set_velocity(sd->get_velocity());
  603. motion_event->set_screen_velocity(sd->get_screen_velocity());
  604. motion_event->set_button_mask(mouse_button_mask);
  605. _parse_input_event_impl(motion_event, true);
  606. }
  607. }
  608. Ref<InputEventJoypadButton> jb = p_event;
  609. if (jb.is_valid()) {
  610. JoyButton c = _combine_device(jb->get_button_index(), jb->get_device());
  611. if (jb->is_pressed()) {
  612. joy_buttons_pressed.insert(c);
  613. } else {
  614. joy_buttons_pressed.erase(c);
  615. }
  616. }
  617. Ref<InputEventJoypadMotion> jm = p_event;
  618. if (jm.is_valid()) {
  619. set_joy_axis(jm->get_device(), jm->get_axis(), jm->get_axis_value());
  620. }
  621. Ref<InputEventGesture> ge = p_event;
  622. if (ge.is_valid()) {
  623. if (event_dispatch_function) {
  624. _THREAD_SAFE_UNLOCK_
  625. event_dispatch_function(ge);
  626. _THREAD_SAFE_LOCK_
  627. }
  628. }
  629. for (const KeyValue<StringName, InputMap::Action> &E : InputMap::get_singleton()->get_action_map()) {
  630. const int event_index = InputMap::get_singleton()->event_get_index(p_event, E.key);
  631. if (event_index == -1) {
  632. continue;
  633. }
  634. ERR_FAIL_COND_MSG(event_index >= (int)MAX_EVENT, vformat("Input singleton does not support more than %d events assigned to an action.", MAX_EVENT));
  635. int device_id = p_event->get_device();
  636. bool is_pressed = p_event->is_action_pressed(E.key, true);
  637. ActionState &action_state = action_states[E.key];
  638. // Update the action's per-device state.
  639. ActionState::DeviceState &device_state = action_state.device_states[device_id];
  640. device_state.pressed[event_index] = is_pressed;
  641. device_state.strength[event_index] = p_event->get_action_strength(E.key);
  642. device_state.raw_strength[event_index] = p_event->get_action_raw_strength(E.key);
  643. // Update the action's global state and cache.
  644. if (!is_pressed) {
  645. action_state.api_pressed = false; // Always release the event from action_press() method.
  646. action_state.api_strength = 0.0;
  647. }
  648. action_state.exact = InputMap::get_singleton()->event_is_action(p_event, E.key, true);
  649. bool was_pressed = action_state.cache.pressed;
  650. _update_action_cache(E.key, action_state);
  651. // As input may come in part way through a physics tick, the earliest we can react to it is the next physics tick.
  652. if (action_state.cache.pressed && !was_pressed) {
  653. action_state.pressed_physics_frame = Engine::get_singleton()->get_physics_frames() + 1;
  654. action_state.pressed_process_frame = Engine::get_singleton()->get_process_frames();
  655. }
  656. if (!action_state.cache.pressed && was_pressed) {
  657. action_state.released_physics_frame = Engine::get_singleton()->get_physics_frames() + 1;
  658. action_state.released_process_frame = Engine::get_singleton()->get_process_frames();
  659. }
  660. }
  661. if (event_dispatch_function) {
  662. _THREAD_SAFE_UNLOCK_
  663. event_dispatch_function(p_event);
  664. _THREAD_SAFE_LOCK_
  665. }
  666. }
  667. void Input::set_joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  668. _THREAD_SAFE_METHOD_
  669. JoyAxis c = _combine_device(p_axis, p_device);
  670. _joy_axis[c] = p_value;
  671. }
  672. void Input::start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration) {
  673. _THREAD_SAFE_METHOD_
  674. if (p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  675. return;
  676. }
  677. VibrationInfo vibration;
  678. vibration.weak_magnitude = p_weak_magnitude;
  679. vibration.strong_magnitude = p_strong_magnitude;
  680. vibration.duration = p_duration;
  681. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  682. joy_vibration[p_device] = vibration;
  683. }
  684. void Input::stop_joy_vibration(int p_device) {
  685. _THREAD_SAFE_METHOD_
  686. VibrationInfo vibration;
  687. vibration.weak_magnitude = 0;
  688. vibration.strong_magnitude = 0;
  689. vibration.duration = 0;
  690. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  691. joy_vibration[p_device] = vibration;
  692. }
  693. void Input::vibrate_handheld(int p_duration_ms, float p_amplitude) {
  694. OS::get_singleton()->vibrate_handheld(p_duration_ms, p_amplitude);
  695. }
  696. void Input::set_gravity(const Vector3 &p_gravity) {
  697. _THREAD_SAFE_METHOD_
  698. gravity = p_gravity;
  699. }
  700. void Input::set_accelerometer(const Vector3 &p_accel) {
  701. _THREAD_SAFE_METHOD_
  702. accelerometer = p_accel;
  703. }
  704. void Input::set_magnetometer(const Vector3 &p_magnetometer) {
  705. _THREAD_SAFE_METHOD_
  706. magnetometer = p_magnetometer;
  707. }
  708. void Input::set_gyroscope(const Vector3 &p_gyroscope) {
  709. _THREAD_SAFE_METHOD_
  710. gyroscope = p_gyroscope;
  711. }
  712. void Input::set_mouse_position(const Point2 &p_posf) {
  713. mouse_pos = p_posf;
  714. }
  715. Point2 Input::get_mouse_position() const {
  716. return mouse_pos;
  717. }
  718. Point2 Input::get_last_mouse_velocity() {
  719. mouse_velocity_track.update(Vector2(), Vector2());
  720. return mouse_velocity_track.velocity;
  721. }
  722. Point2 Input::get_last_mouse_screen_velocity() {
  723. mouse_velocity_track.update(Vector2(), Vector2());
  724. return mouse_velocity_track.screen_velocity;
  725. }
  726. BitField<MouseButtonMask> Input::get_mouse_button_mask() const {
  727. return mouse_button_mask; // do not trust OS implementation, should remove it - OS::get_singleton()->get_mouse_button_state();
  728. }
  729. void Input::warp_mouse(const Vector2 &p_position) {
  730. warp_mouse_func(p_position);
  731. }
  732. Point2 Input::warp_mouse_motion(const Ref<InputEventMouseMotion> &p_motion, const Rect2 &p_rect) {
  733. // The relative distance reported for the next event after a warp is in the boundaries of the
  734. // size of the rect on that axis, but it may be greater, in which case there's no problem as fmod()
  735. // will warp it, but if the pointer has moved in the opposite direction between the pointer relocation
  736. // and the subsequent event, the reported relative distance will be less than the size of the rect
  737. // and thus fmod() will be disabled for handling the situation.
  738. // And due to this mouse warping mechanism being stateless, we need to apply some heuristics to
  739. // detect the warp: if the relative distance is greater than the half of the size of the relevant rect
  740. // (checked per each axis), it will be considered as the consequence of a former pointer warp.
  741. const Point2 rel_sign(p_motion->get_relative().x >= 0.0f ? 1 : -1, p_motion->get_relative().y >= 0.0 ? 1 : -1);
  742. const Size2 warp_margin = p_rect.size * 0.5f;
  743. const Point2 rel_warped(
  744. Math::fmod(p_motion->get_relative().x + rel_sign.x * warp_margin.x, p_rect.size.x) - rel_sign.x * warp_margin.x,
  745. Math::fmod(p_motion->get_relative().y + rel_sign.y * warp_margin.y, p_rect.size.y) - rel_sign.y * warp_margin.y);
  746. const Point2 pos_local = p_motion->get_global_position() - p_rect.position;
  747. const Point2 pos_warped(Math::fposmod(pos_local.x, p_rect.size.x), Math::fposmod(pos_local.y, p_rect.size.y));
  748. if (pos_warped != pos_local) {
  749. warp_mouse(pos_warped + p_rect.position);
  750. }
  751. return rel_warped;
  752. }
  753. void Input::action_press(const StringName &p_action, float p_strength) {
  754. ERR_FAIL_COND_MSG(!InputMap::get_singleton()->has_action(p_action), InputMap::get_singleton()->suggest_actions(p_action));
  755. // Create or retrieve existing action.
  756. ActionState &action_state = action_states[p_action];
  757. // As input may come in part way through a physics tick, the earliest we can react to it is the next physics tick.
  758. if (!action_state.cache.pressed) {
  759. action_state.pressed_physics_frame = Engine::get_singleton()->get_physics_frames() + 1;
  760. action_state.pressed_process_frame = Engine::get_singleton()->get_process_frames();
  761. }
  762. action_state.exact = true;
  763. action_state.api_pressed = true;
  764. action_state.api_strength = CLAMP(p_strength, 0.0f, 1.0f);
  765. _update_action_cache(p_action, action_state);
  766. }
  767. void Input::action_release(const StringName &p_action) {
  768. ERR_FAIL_COND_MSG(!InputMap::get_singleton()->has_action(p_action), InputMap::get_singleton()->suggest_actions(p_action));
  769. // Create or retrieve existing action.
  770. ActionState &action_state = action_states[p_action];
  771. action_state.cache.pressed = 0;
  772. action_state.cache.strength = 0.0;
  773. action_state.cache.raw_strength = 0.0;
  774. // As input may come in part way through a physics tick, the earliest we can react to it is the next physics tick.
  775. action_state.released_physics_frame = Engine::get_singleton()->get_physics_frames() + 1;
  776. action_state.released_process_frame = Engine::get_singleton()->get_process_frames();
  777. action_state.device_states.clear();
  778. action_state.exact = true;
  779. action_state.api_pressed = false;
  780. action_state.api_strength = 0.0;
  781. }
  782. void Input::set_emulate_touch_from_mouse(bool p_emulate) {
  783. emulate_touch_from_mouse = p_emulate;
  784. }
  785. bool Input::is_emulating_touch_from_mouse() const {
  786. return emulate_touch_from_mouse;
  787. }
  788. // Calling this whenever the game window is focused helps unsticking the "touch mouse"
  789. // if the OS or its abstraction class hasn't properly reported that touch pointers raised
  790. void Input::ensure_touch_mouse_raised() {
  791. _THREAD_SAFE_METHOD_
  792. if (mouse_from_touch_index != -1) {
  793. mouse_from_touch_index = -1;
  794. Ref<InputEventMouseButton> button_event;
  795. button_event.instantiate();
  796. button_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  797. button_event->set_position(mouse_pos);
  798. button_event->set_global_position(mouse_pos);
  799. button_event->set_pressed(false);
  800. button_event->set_button_index(MouseButton::LEFT);
  801. BitField<MouseButtonMask> ev_bm = mouse_button_mask;
  802. ev_bm.clear_flag(MouseButtonMask::LEFT);
  803. button_event->set_button_mask(ev_bm);
  804. _parse_input_event_impl(button_event, true);
  805. }
  806. }
  807. void Input::set_emulate_mouse_from_touch(bool p_emulate) {
  808. emulate_mouse_from_touch = p_emulate;
  809. }
  810. bool Input::is_emulating_mouse_from_touch() const {
  811. return emulate_mouse_from_touch;
  812. }
  813. Input::CursorShape Input::get_default_cursor_shape() const {
  814. return default_shape;
  815. }
  816. void Input::set_default_cursor_shape(CursorShape p_shape) {
  817. if (default_shape == p_shape) {
  818. return;
  819. }
  820. default_shape = p_shape;
  821. // The default shape is set in Viewport::_gui_input_event. To instantly
  822. // see the shape in the viewport we need to trigger a mouse motion event.
  823. Ref<InputEventMouseMotion> mm;
  824. mm.instantiate();
  825. mm->set_position(mouse_pos);
  826. mm->set_global_position(mouse_pos);
  827. mm->set_device(InputEvent::DEVICE_ID_INTERNAL);
  828. parse_input_event(mm);
  829. }
  830. Input::CursorShape Input::get_current_cursor_shape() const {
  831. return get_current_cursor_shape_func();
  832. }
  833. void Input::set_custom_mouse_cursor(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  834. if (Engine::get_singleton()->is_editor_hint()) {
  835. return;
  836. }
  837. ERR_FAIL_INDEX(p_shape, CursorShape::CURSOR_MAX);
  838. set_custom_mouse_cursor_func(p_cursor, p_shape, p_hotspot);
  839. }
  840. void Input::parse_input_event(const Ref<InputEvent> &p_event) {
  841. _THREAD_SAFE_METHOD_
  842. ERR_FAIL_COND(p_event.is_null());
  843. #ifdef DEBUG_ENABLED
  844. uint64_t curr_frame = Engine::get_singleton()->get_process_frames();
  845. if (curr_frame != last_parsed_frame) {
  846. frame_parsed_events.clear();
  847. last_parsed_frame = curr_frame;
  848. frame_parsed_events.insert(p_event);
  849. } else if (frame_parsed_events.has(p_event)) {
  850. // It would be technically safe to send the same event in cases such as:
  851. // - After an explicit flush.
  852. // - In platforms using buffering when agile flushing is enabled, after one of the mid-frame flushes.
  853. // - If platform doesn't use buffering and event accumulation is disabled.
  854. // - If platform doesn't use buffering and the event type is not accumulable.
  855. // However, it wouldn't be reasonable to ask users to remember the full ruleset and be aware at all times
  856. // of the possibilities of the target platform, project settings and engine internals, which may change
  857. // without prior notice.
  858. // Therefore, the guideline is, "don't send the same event object more than once per frame".
  859. WARN_PRINT_ONCE(
  860. "An input event object is being parsed more than once in the same frame, which is unsafe.\n"
  861. "If you are generating events in a script, you have to instantiate a new event instead of sending the same one more than once, unless the original one was sent on an earlier frame.\n"
  862. "You can call duplicate() on the event to get a new instance with identical values.");
  863. } else {
  864. frame_parsed_events.insert(p_event);
  865. }
  866. #endif
  867. if (use_accumulated_input) {
  868. if (buffered_events.is_empty() || !buffered_events.back()->get()->accumulate(p_event)) {
  869. buffered_events.push_back(p_event);
  870. }
  871. } else if (agile_input_event_flushing) {
  872. buffered_events.push_back(p_event);
  873. } else {
  874. _parse_input_event_impl(p_event, false);
  875. }
  876. }
  877. #ifdef DEBUG_ENABLED
  878. void Input::flush_frame_parsed_events() {
  879. _THREAD_SAFE_METHOD_
  880. frame_parsed_events.clear();
  881. }
  882. #endif
  883. void Input::flush_buffered_events() {
  884. _THREAD_SAFE_METHOD_
  885. while (buffered_events.front()) {
  886. // The final delivery of the input event involves releasing the lock.
  887. // While the lock is released, another thread may lock it and add new events to the back.
  888. // Therefore, we get each event and pop it while we still have the lock,
  889. // to ensure the list is in a consistent state.
  890. List<Ref<InputEvent>>::Element *E = buffered_events.front();
  891. Ref<InputEvent> e = E->get();
  892. buffered_events.pop_front();
  893. _parse_input_event_impl(e, false);
  894. }
  895. }
  896. bool Input::is_agile_input_event_flushing() {
  897. return agile_input_event_flushing;
  898. }
  899. void Input::set_agile_input_event_flushing(bool p_enable) {
  900. agile_input_event_flushing = p_enable;
  901. }
  902. void Input::set_use_accumulated_input(bool p_enable) {
  903. use_accumulated_input = p_enable;
  904. }
  905. bool Input::is_using_accumulated_input() {
  906. return use_accumulated_input;
  907. }
  908. void Input::release_pressed_events() {
  909. flush_buffered_events(); // this is needed to release actions strengths
  910. keys_pressed.clear();
  911. physical_keys_pressed.clear();
  912. key_label_pressed.clear();
  913. joy_buttons_pressed.clear();
  914. _joy_axis.clear();
  915. for (KeyValue<StringName, Input::ActionState> &E : action_states) {
  916. if (E.value.cache.pressed) {
  917. action_release(E.key);
  918. }
  919. }
  920. }
  921. void Input::set_event_dispatch_function(EventDispatchFunc p_function) {
  922. event_dispatch_function = p_function;
  923. }
  924. void Input::joy_button(int p_device, JoyButton p_button, bool p_pressed) {
  925. _THREAD_SAFE_METHOD_;
  926. Joypad &joy = joy_names[p_device];
  927. ERR_FAIL_INDEX((int)p_button, (int)JoyButton::MAX);
  928. if (joy.last_buttons[(size_t)p_button] == p_pressed) {
  929. return;
  930. }
  931. joy.last_buttons[(size_t)p_button] = p_pressed;
  932. if (joy.mapping == -1) {
  933. _button_event(p_device, p_button, p_pressed);
  934. return;
  935. }
  936. JoyEvent map = _get_mapped_button_event(map_db[joy.mapping], p_button);
  937. if (map.type == TYPE_BUTTON) {
  938. _button_event(p_device, (JoyButton)map.index, p_pressed);
  939. return;
  940. }
  941. if (map.type == TYPE_AXIS) {
  942. _axis_event(p_device, (JoyAxis)map.index, p_pressed ? map.value : 0.0);
  943. }
  944. // no event?
  945. }
  946. void Input::joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  947. _THREAD_SAFE_METHOD_;
  948. ERR_FAIL_INDEX((int)p_axis, (int)JoyAxis::MAX);
  949. Joypad &joy = joy_names[p_device];
  950. if (joy.last_axis[(size_t)p_axis] == p_value) {
  951. return;
  952. }
  953. joy.last_axis[(size_t)p_axis] = p_value;
  954. if (joy.mapping == -1) {
  955. _axis_event(p_device, p_axis, p_value);
  956. return;
  957. }
  958. JoyAxisRange range;
  959. JoyEvent map = _get_mapped_axis_event(map_db[joy.mapping], p_axis, p_value, range);
  960. if (map.type == TYPE_BUTTON) {
  961. bool pressed = map.value > 0.5;
  962. if (pressed != joy_buttons_pressed.has(_combine_device((JoyButton)map.index, p_device))) {
  963. _button_event(p_device, (JoyButton)map.index, pressed);
  964. }
  965. // Ensure opposite D-Pad button is also released.
  966. switch ((JoyButton)map.index) {
  967. case JoyButton::DPAD_UP:
  968. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_DOWN, p_device))) {
  969. _button_event(p_device, JoyButton::DPAD_DOWN, false);
  970. }
  971. break;
  972. case JoyButton::DPAD_DOWN:
  973. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_UP, p_device))) {
  974. _button_event(p_device, JoyButton::DPAD_UP, false);
  975. }
  976. break;
  977. case JoyButton::DPAD_LEFT:
  978. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_RIGHT, p_device))) {
  979. _button_event(p_device, JoyButton::DPAD_RIGHT, false);
  980. }
  981. break;
  982. case JoyButton::DPAD_RIGHT:
  983. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_LEFT, p_device))) {
  984. _button_event(p_device, JoyButton::DPAD_LEFT, false);
  985. }
  986. break;
  987. default:
  988. // Nothing to do.
  989. break;
  990. }
  991. return;
  992. }
  993. if (map.type == TYPE_AXIS) {
  994. JoyAxis axis = JoyAxis(map.index);
  995. float value = map.value;
  996. if (range == FULL_AXIS && (axis == JoyAxis::TRIGGER_LEFT || axis == JoyAxis::TRIGGER_RIGHT)) {
  997. // Convert to a value between 0.0f and 1.0f.
  998. value = 0.5f + value / 2.0f;
  999. }
  1000. _axis_event(p_device, axis, value);
  1001. return;
  1002. }
  1003. }
  1004. void Input::joy_hat(int p_device, BitField<HatMask> p_val) {
  1005. _THREAD_SAFE_METHOD_;
  1006. const Joypad &joy = joy_names[p_device];
  1007. JoyEvent map[(size_t)HatDir::MAX];
  1008. map[(size_t)HatDir::UP].type = TYPE_BUTTON;
  1009. map[(size_t)HatDir::UP].index = (int)JoyButton::DPAD_UP;
  1010. map[(size_t)HatDir::UP].value = 0;
  1011. map[(size_t)HatDir::RIGHT].type = TYPE_BUTTON;
  1012. map[(size_t)HatDir::RIGHT].index = (int)JoyButton::DPAD_RIGHT;
  1013. map[(size_t)HatDir::RIGHT].value = 0;
  1014. map[(size_t)HatDir::DOWN].type = TYPE_BUTTON;
  1015. map[(size_t)HatDir::DOWN].index = (int)JoyButton::DPAD_DOWN;
  1016. map[(size_t)HatDir::DOWN].value = 0;
  1017. map[(size_t)HatDir::LEFT].type = TYPE_BUTTON;
  1018. map[(size_t)HatDir::LEFT].index = (int)JoyButton::DPAD_LEFT;
  1019. map[(size_t)HatDir::LEFT].value = 0;
  1020. if (joy.mapping != -1) {
  1021. _get_mapped_hat_events(map_db[joy.mapping], (HatDir)0, map);
  1022. }
  1023. int cur_val = joy_names[p_device].hat_current;
  1024. for (int hat_direction = 0, hat_mask = 1; hat_direction < (int)HatDir::MAX; hat_direction++, hat_mask <<= 1) {
  1025. if (((int)p_val & hat_mask) != (cur_val & hat_mask)) {
  1026. if (map[hat_direction].type == TYPE_BUTTON) {
  1027. _button_event(p_device, (JoyButton)map[hat_direction].index, (int)p_val & hat_mask);
  1028. }
  1029. if (map[hat_direction].type == TYPE_AXIS) {
  1030. _axis_event(p_device, (JoyAxis)map[hat_direction].index, ((int)p_val & hat_mask) ? map[hat_direction].value : 0.0);
  1031. }
  1032. }
  1033. }
  1034. joy_names[p_device].hat_current = (int)p_val;
  1035. }
  1036. void Input::_button_event(int p_device, JoyButton p_index, bool p_pressed) {
  1037. Ref<InputEventJoypadButton> ievent;
  1038. ievent.instantiate();
  1039. ievent->set_device(p_device);
  1040. ievent->set_button_index(p_index);
  1041. ievent->set_pressed(p_pressed);
  1042. parse_input_event(ievent);
  1043. }
  1044. void Input::_axis_event(int p_device, JoyAxis p_axis, float p_value) {
  1045. Ref<InputEventJoypadMotion> ievent;
  1046. ievent.instantiate();
  1047. ievent->set_device(p_device);
  1048. ievent->set_axis(p_axis);
  1049. ievent->set_axis_value(p_value);
  1050. parse_input_event(ievent);
  1051. }
  1052. void Input::_update_action_cache(const StringName &p_action_name, ActionState &r_action_state) {
  1053. // Update the action cache, computed from the per-device and per-event states.
  1054. r_action_state.cache.pressed = false;
  1055. r_action_state.cache.strength = 0.0;
  1056. r_action_state.cache.raw_strength = 0.0;
  1057. int max_event = InputMap::get_singleton()->action_get_events(p_action_name)->size() + 1; // +1 comes from InputEventAction.
  1058. for (const KeyValue<int, ActionState::DeviceState> &kv : r_action_state.device_states) {
  1059. const ActionState::DeviceState &device_state = kv.value;
  1060. for (int i = 0; i < max_event; i++) {
  1061. r_action_state.cache.pressed = r_action_state.cache.pressed || device_state.pressed[i];
  1062. r_action_state.cache.strength = MAX(r_action_state.cache.strength, device_state.strength[i]);
  1063. r_action_state.cache.raw_strength = MAX(r_action_state.cache.raw_strength, device_state.raw_strength[i]);
  1064. }
  1065. }
  1066. if (r_action_state.api_pressed) {
  1067. r_action_state.cache.pressed = true;
  1068. r_action_state.cache.strength = MAX(r_action_state.cache.strength, r_action_state.api_strength);
  1069. r_action_state.cache.raw_strength = MAX(r_action_state.cache.raw_strength, r_action_state.api_strength); // Use the strength as raw_strength for API-pressed states.
  1070. }
  1071. }
  1072. Input::JoyEvent Input::_get_mapped_button_event(const JoyDeviceMapping &mapping, JoyButton p_button) {
  1073. JoyEvent event;
  1074. for (int i = 0; i < mapping.bindings.size(); i++) {
  1075. const JoyBinding binding = mapping.bindings[i];
  1076. if (binding.inputType == TYPE_BUTTON && binding.input.button == p_button) {
  1077. event.type = binding.outputType;
  1078. switch (binding.outputType) {
  1079. case TYPE_BUTTON:
  1080. event.index = (int)binding.output.button;
  1081. return event;
  1082. case TYPE_AXIS:
  1083. event.index = (int)binding.output.axis.axis;
  1084. switch (binding.output.axis.range) {
  1085. case POSITIVE_HALF_AXIS:
  1086. event.value = 1;
  1087. break;
  1088. case NEGATIVE_HALF_AXIS:
  1089. event.value = -1;
  1090. break;
  1091. case FULL_AXIS:
  1092. // It doesn't make sense for a button to map to a full axis,
  1093. // but keeping as a default for a trigger with a positive half-axis.
  1094. event.value = 1;
  1095. break;
  1096. }
  1097. return event;
  1098. default:
  1099. ERR_PRINT_ONCE("Joypad button mapping error.");
  1100. }
  1101. }
  1102. }
  1103. return event;
  1104. }
  1105. Input::JoyEvent Input::_get_mapped_axis_event(const JoyDeviceMapping &mapping, JoyAxis p_axis, float p_value, JoyAxisRange &r_range) {
  1106. JoyEvent event;
  1107. for (int i = 0; i < mapping.bindings.size(); i++) {
  1108. const JoyBinding binding = mapping.bindings[i];
  1109. if (binding.inputType == TYPE_AXIS && binding.input.axis.axis == p_axis) {
  1110. float value = p_value;
  1111. if (binding.input.axis.invert) {
  1112. value = -value;
  1113. }
  1114. if (binding.input.axis.range == FULL_AXIS ||
  1115. (binding.input.axis.range == POSITIVE_HALF_AXIS && value >= 0) ||
  1116. (binding.input.axis.range == NEGATIVE_HALF_AXIS && value < 0)) {
  1117. event.type = binding.outputType;
  1118. float shifted_positive_value = 0;
  1119. switch (binding.input.axis.range) {
  1120. case POSITIVE_HALF_AXIS:
  1121. shifted_positive_value = value;
  1122. break;
  1123. case NEGATIVE_HALF_AXIS:
  1124. shifted_positive_value = value + 1;
  1125. break;
  1126. case FULL_AXIS:
  1127. shifted_positive_value = (value + 1) / 2;
  1128. break;
  1129. }
  1130. switch (binding.outputType) {
  1131. case TYPE_BUTTON:
  1132. event.index = (int)binding.output.button;
  1133. switch (binding.input.axis.range) {
  1134. case POSITIVE_HALF_AXIS:
  1135. event.value = shifted_positive_value;
  1136. break;
  1137. case NEGATIVE_HALF_AXIS:
  1138. event.value = 1 - shifted_positive_value;
  1139. break;
  1140. case FULL_AXIS:
  1141. // It doesn't make sense for a full axis to map to a button,
  1142. // but keeping as a default for a trigger with a positive half-axis.
  1143. event.value = (shifted_positive_value * 2) - 1;
  1144. break;
  1145. }
  1146. return event;
  1147. case TYPE_AXIS:
  1148. event.index = (int)binding.output.axis.axis;
  1149. event.value = value;
  1150. r_range = binding.output.axis.range;
  1151. if (binding.output.axis.range != binding.input.axis.range) {
  1152. switch (binding.output.axis.range) {
  1153. case POSITIVE_HALF_AXIS:
  1154. event.value = shifted_positive_value;
  1155. break;
  1156. case NEGATIVE_HALF_AXIS:
  1157. event.value = shifted_positive_value - 1;
  1158. break;
  1159. case FULL_AXIS:
  1160. event.value = (shifted_positive_value * 2) - 1;
  1161. break;
  1162. }
  1163. }
  1164. return event;
  1165. default:
  1166. ERR_PRINT_ONCE("Joypad axis mapping error.");
  1167. }
  1168. }
  1169. }
  1170. }
  1171. return event;
  1172. }
  1173. void Input::_get_mapped_hat_events(const JoyDeviceMapping &mapping, HatDir p_hat, JoyEvent r_events[(size_t)HatDir::MAX]) {
  1174. for (int i = 0; i < mapping.bindings.size(); i++) {
  1175. const JoyBinding binding = mapping.bindings[i];
  1176. if (binding.inputType == TYPE_HAT && binding.input.hat.hat == p_hat) {
  1177. HatDir hat_direction;
  1178. switch (binding.input.hat.hat_mask) {
  1179. case HatMask::UP:
  1180. hat_direction = HatDir::UP;
  1181. break;
  1182. case HatMask::RIGHT:
  1183. hat_direction = HatDir::RIGHT;
  1184. break;
  1185. case HatMask::DOWN:
  1186. hat_direction = HatDir::DOWN;
  1187. break;
  1188. case HatMask::LEFT:
  1189. hat_direction = HatDir::LEFT;
  1190. break;
  1191. default:
  1192. ERR_PRINT_ONCE("Joypad button mapping error.");
  1193. continue;
  1194. }
  1195. r_events[(size_t)hat_direction].type = binding.outputType;
  1196. switch (binding.outputType) {
  1197. case TYPE_BUTTON:
  1198. r_events[(size_t)hat_direction].index = (int)binding.output.button;
  1199. break;
  1200. case TYPE_AXIS:
  1201. r_events[(size_t)hat_direction].index = (int)binding.output.axis.axis;
  1202. switch (binding.output.axis.range) {
  1203. case POSITIVE_HALF_AXIS:
  1204. r_events[(size_t)hat_direction].value = 1;
  1205. break;
  1206. case NEGATIVE_HALF_AXIS:
  1207. r_events[(size_t)hat_direction].value = -1;
  1208. break;
  1209. case FULL_AXIS:
  1210. // It doesn't make sense for a hat direction to map to a full axis,
  1211. // but keeping as a default for a trigger with a positive half-axis.
  1212. r_events[(size_t)hat_direction].value = 1;
  1213. break;
  1214. }
  1215. break;
  1216. default:
  1217. ERR_PRINT_ONCE("Joypad button mapping error.");
  1218. }
  1219. }
  1220. }
  1221. }
  1222. JoyButton Input::_get_output_button(const String &output) {
  1223. for (int i = 0; i < (int)JoyButton::SDL_MAX; i++) {
  1224. if (output == _joy_buttons[i]) {
  1225. return JoyButton(i);
  1226. }
  1227. }
  1228. return JoyButton::INVALID;
  1229. }
  1230. JoyAxis Input::_get_output_axis(const String &output) {
  1231. for (int i = 0; i < (int)JoyAxis::SDL_MAX; i++) {
  1232. if (output == _joy_axes[i]) {
  1233. return JoyAxis(i);
  1234. }
  1235. }
  1236. return JoyAxis::INVALID;
  1237. }
  1238. void Input::parse_mapping(const String &p_mapping) {
  1239. _THREAD_SAFE_METHOD_;
  1240. JoyDeviceMapping mapping;
  1241. Vector<String> entry = p_mapping.split(",");
  1242. if (entry.size() < 2) {
  1243. return;
  1244. }
  1245. CharString uid;
  1246. uid.resize(17);
  1247. mapping.uid = entry[0];
  1248. mapping.name = entry[1];
  1249. int idx = 1;
  1250. while (++idx < entry.size()) {
  1251. if (entry[idx].is_empty()) {
  1252. continue;
  1253. }
  1254. String output = entry[idx].get_slice(":", 0).replace(" ", "");
  1255. String input = entry[idx].get_slice(":", 1).replace(" ", "");
  1256. if (output.length() < 1 || input.length() < 2) {
  1257. continue;
  1258. }
  1259. if (output == "platform" || output == "hint") {
  1260. continue;
  1261. }
  1262. JoyAxisRange output_range = FULL_AXIS;
  1263. if (output[0] == '+' || output[0] == '-') {
  1264. ERR_CONTINUE_MSG(output.length() < 2,
  1265. vformat("Invalid output entry \"%s\" in mapping:\n%s", entry[idx], p_mapping));
  1266. if (output[0] == '+') {
  1267. output_range = POSITIVE_HALF_AXIS;
  1268. } else if (output[0] == '-') {
  1269. output_range = NEGATIVE_HALF_AXIS;
  1270. }
  1271. output = output.substr(1);
  1272. }
  1273. JoyAxisRange input_range = FULL_AXIS;
  1274. if (input[0] == '+') {
  1275. input_range = POSITIVE_HALF_AXIS;
  1276. input = input.substr(1);
  1277. } else if (input[0] == '-') {
  1278. input_range = NEGATIVE_HALF_AXIS;
  1279. input = input.substr(1);
  1280. }
  1281. bool invert_axis = false;
  1282. if (input[input.length() - 1] == '~') {
  1283. invert_axis = true;
  1284. input = input.left(input.length() - 1);
  1285. }
  1286. JoyButton output_button = _get_output_button(output);
  1287. JoyAxis output_axis = _get_output_axis(output);
  1288. if (output_button == JoyButton::INVALID && output_axis == JoyAxis::INVALID) {
  1289. print_verbose(vformat("Unrecognized output string \"%s\" in mapping:\n%s", output, p_mapping));
  1290. continue;
  1291. }
  1292. ERR_CONTINUE_MSG(output_button != JoyButton::INVALID && output_axis != JoyAxis::INVALID,
  1293. vformat("Output string \"%s\" matched both button and axis in mapping:\n%s", output, p_mapping));
  1294. JoyBinding binding;
  1295. if (output_button != JoyButton::INVALID) {
  1296. binding.outputType = TYPE_BUTTON;
  1297. binding.output.button = output_button;
  1298. } else if (output_axis != JoyAxis::INVALID) {
  1299. binding.outputType = TYPE_AXIS;
  1300. binding.output.axis.axis = output_axis;
  1301. binding.output.axis.range = output_range;
  1302. }
  1303. switch (input[0]) {
  1304. case 'b':
  1305. binding.inputType = TYPE_BUTTON;
  1306. binding.input.button = (JoyButton)input.substr(1).to_int();
  1307. break;
  1308. case 'a':
  1309. binding.inputType = TYPE_AXIS;
  1310. binding.input.axis.axis = (JoyAxis)input.substr(1).to_int();
  1311. binding.input.axis.range = input_range;
  1312. binding.input.axis.invert = invert_axis;
  1313. break;
  1314. case 'h':
  1315. ERR_CONTINUE_MSG(input.length() != 4 || input[2] != '.',
  1316. vformat("Invalid had input \"%s\" in mapping:\n%s", input, p_mapping));
  1317. binding.inputType = TYPE_HAT;
  1318. binding.input.hat.hat = (HatDir)input.substr(1, 1).to_int();
  1319. binding.input.hat.hat_mask = static_cast<HatMask>(input.substr(3).to_int());
  1320. break;
  1321. default:
  1322. ERR_CONTINUE_MSG(true, vformat("Unrecognized input string \"%s\" in mapping:\n%s", input, p_mapping));
  1323. }
  1324. mapping.bindings.push_back(binding);
  1325. }
  1326. map_db.push_back(mapping);
  1327. }
  1328. void Input::add_joy_mapping(const String &p_mapping, bool p_update_existing) {
  1329. parse_mapping(p_mapping);
  1330. if (p_update_existing) {
  1331. Vector<String> entry = p_mapping.split(",");
  1332. const String &uid = entry[0];
  1333. for (KeyValue<int, Joypad> &E : joy_names) {
  1334. Joypad &joy = E.value;
  1335. if (joy.uid == uid) {
  1336. joy.mapping = map_db.size() - 1;
  1337. }
  1338. }
  1339. }
  1340. }
  1341. void Input::remove_joy_mapping(const String &p_guid) {
  1342. for (int i = map_db.size() - 1; i >= 0; i--) {
  1343. if (p_guid == map_db[i].uid) {
  1344. map_db.remove_at(i);
  1345. }
  1346. }
  1347. for (KeyValue<int, Joypad> &E : joy_names) {
  1348. Joypad &joy = E.value;
  1349. if (joy.uid == p_guid) {
  1350. joy.mapping = -1;
  1351. }
  1352. }
  1353. }
  1354. void Input::set_fallback_mapping(const String &p_guid) {
  1355. for (int i = 0; i < map_db.size(); i++) {
  1356. if (map_db[i].uid == p_guid) {
  1357. fallback_mapping = i;
  1358. return;
  1359. }
  1360. }
  1361. }
  1362. //platforms that use the remapping system can override and call to these ones
  1363. bool Input::is_joy_known(int p_device) {
  1364. if (joy_names.has(p_device)) {
  1365. int mapping = joy_names[p_device].mapping;
  1366. if (mapping != -1 && mapping != fallback_mapping) {
  1367. return true;
  1368. }
  1369. }
  1370. return false;
  1371. }
  1372. String Input::get_joy_guid(int p_device) const {
  1373. ERR_FAIL_COND_V(!joy_names.has(p_device), "");
  1374. return joy_names[p_device].uid;
  1375. }
  1376. Dictionary Input::get_joy_info(int p_device) const {
  1377. ERR_FAIL_COND_V(!joy_names.has(p_device), Dictionary());
  1378. return joy_names[p_device].info;
  1379. }
  1380. bool Input::should_ignore_device(int p_vendor_id, int p_product_id) const {
  1381. uint32_t full_id = (((uint32_t)p_vendor_id) << 16) | ((uint16_t)p_product_id);
  1382. return ignored_device_ids.has(full_id);
  1383. }
  1384. TypedArray<int> Input::get_connected_joypads() {
  1385. TypedArray<int> ret;
  1386. HashMap<int, Joypad>::Iterator elem = joy_names.begin();
  1387. while (elem) {
  1388. if (elem->value.connected) {
  1389. ret.push_back(elem->key);
  1390. }
  1391. ++elem;
  1392. }
  1393. return ret;
  1394. }
  1395. int Input::get_unused_joy_id() {
  1396. for (int i = 0; i < JOYPADS_MAX; i++) {
  1397. if (!joy_names.has(i) || !joy_names[i].connected) {
  1398. return i;
  1399. }
  1400. }
  1401. return -1;
  1402. }
  1403. Input::Input() {
  1404. singleton = this;
  1405. // Parse default mappings.
  1406. {
  1407. int i = 0;
  1408. while (DefaultControllerMappings::mappings[i]) {
  1409. parse_mapping(DefaultControllerMappings::mappings[i++]);
  1410. }
  1411. }
  1412. // If defined, parse SDL_GAMECONTROLLERCONFIG for possible new mappings/overrides.
  1413. String env_mapping = OS::get_singleton()->get_environment("SDL_GAMECONTROLLERCONFIG");
  1414. if (!env_mapping.is_empty()) {
  1415. Vector<String> entries = env_mapping.split("\n");
  1416. for (int i = 0; i < entries.size(); i++) {
  1417. if (entries[i].is_empty()) {
  1418. continue;
  1419. }
  1420. parse_mapping(entries[i]);
  1421. }
  1422. }
  1423. String env_ignore_devices = OS::get_singleton()->get_environment("SDL_GAMECONTROLLER_IGNORE_DEVICES");
  1424. if (!env_ignore_devices.is_empty()) {
  1425. Vector<String> entries = env_ignore_devices.split(",");
  1426. for (int i = 0; i < entries.size(); i++) {
  1427. Vector<String> vid_pid = entries[i].split("/");
  1428. if (vid_pid.size() < 2) {
  1429. continue;
  1430. }
  1431. print_verbose(vformat("Device Ignored -- Vendor: %s Product: %s", vid_pid[0], vid_pid[1]));
  1432. const uint16_t vid_unswapped = vid_pid[0].hex_to_int();
  1433. const uint16_t pid_unswapped = vid_pid[1].hex_to_int();
  1434. const uint16_t vid = BSWAP16(vid_unswapped);
  1435. const uint16_t pid = BSWAP16(pid_unswapped);
  1436. uint32_t full_id = (((uint32_t)vid) << 16) | ((uint16_t)pid);
  1437. ignored_device_ids.insert(full_id);
  1438. }
  1439. }
  1440. legacy_just_pressed_behavior = GLOBAL_DEF("input_devices/compatibility/legacy_just_pressed_behavior", false);
  1441. if (Engine::get_singleton()->is_editor_hint()) {
  1442. // Always use standard behavior in the editor.
  1443. legacy_just_pressed_behavior = false;
  1444. }
  1445. }
  1446. Input::~Input() {
  1447. singleton = nullptr;
  1448. }
  1449. //////////////////////////////////////////////////////////