input.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  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. if (action_state.cache.pressed && !was_pressed) {
  652. action_state.pressed_physics_frame = Engine::get_singleton()->get_physics_frames();
  653. action_state.pressed_process_frame = Engine::get_singleton()->get_process_frames();
  654. }
  655. if (!action_state.cache.pressed && was_pressed) {
  656. action_state.released_physics_frame = Engine::get_singleton()->get_physics_frames();
  657. action_state.released_process_frame = Engine::get_singleton()->get_process_frames();
  658. }
  659. }
  660. if (event_dispatch_function) {
  661. _THREAD_SAFE_UNLOCK_
  662. event_dispatch_function(p_event);
  663. _THREAD_SAFE_LOCK_
  664. }
  665. }
  666. void Input::set_joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  667. _THREAD_SAFE_METHOD_
  668. JoyAxis c = _combine_device(p_axis, p_device);
  669. _joy_axis[c] = p_value;
  670. }
  671. void Input::start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration) {
  672. _THREAD_SAFE_METHOD_
  673. if (p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  674. return;
  675. }
  676. VibrationInfo vibration;
  677. vibration.weak_magnitude = p_weak_magnitude;
  678. vibration.strong_magnitude = p_strong_magnitude;
  679. vibration.duration = p_duration;
  680. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  681. joy_vibration[p_device] = vibration;
  682. }
  683. void Input::stop_joy_vibration(int p_device) {
  684. _THREAD_SAFE_METHOD_
  685. VibrationInfo vibration;
  686. vibration.weak_magnitude = 0;
  687. vibration.strong_magnitude = 0;
  688. vibration.duration = 0;
  689. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  690. joy_vibration[p_device] = vibration;
  691. }
  692. void Input::vibrate_handheld(int p_duration_ms, float p_amplitude) {
  693. OS::get_singleton()->vibrate_handheld(p_duration_ms, p_amplitude);
  694. }
  695. void Input::set_gravity(const Vector3 &p_gravity) {
  696. _THREAD_SAFE_METHOD_
  697. gravity = p_gravity;
  698. }
  699. void Input::set_accelerometer(const Vector3 &p_accel) {
  700. _THREAD_SAFE_METHOD_
  701. accelerometer = p_accel;
  702. }
  703. void Input::set_magnetometer(const Vector3 &p_magnetometer) {
  704. _THREAD_SAFE_METHOD_
  705. magnetometer = p_magnetometer;
  706. }
  707. void Input::set_gyroscope(const Vector3 &p_gyroscope) {
  708. _THREAD_SAFE_METHOD_
  709. gyroscope = p_gyroscope;
  710. }
  711. void Input::set_mouse_position(const Point2 &p_posf) {
  712. mouse_pos = p_posf;
  713. }
  714. Point2 Input::get_mouse_position() const {
  715. return mouse_pos;
  716. }
  717. Point2 Input::get_last_mouse_velocity() {
  718. mouse_velocity_track.update(Vector2(), Vector2());
  719. return mouse_velocity_track.velocity;
  720. }
  721. Point2 Input::get_last_mouse_screen_velocity() {
  722. mouse_velocity_track.update(Vector2(), Vector2());
  723. return mouse_velocity_track.screen_velocity;
  724. }
  725. BitField<MouseButtonMask> Input::get_mouse_button_mask() const {
  726. return mouse_button_mask; // do not trust OS implementation, should remove it - OS::get_singleton()->get_mouse_button_state();
  727. }
  728. void Input::warp_mouse(const Vector2 &p_position) {
  729. warp_mouse_func(p_position);
  730. }
  731. Point2 Input::warp_mouse_motion(const Ref<InputEventMouseMotion> &p_motion, const Rect2 &p_rect) {
  732. // The relative distance reported for the next event after a warp is in the boundaries of the
  733. // size of the rect on that axis, but it may be greater, in which case there's no problem as fmod()
  734. // will warp it, but if the pointer has moved in the opposite direction between the pointer relocation
  735. // and the subsequent event, the reported relative distance will be less than the size of the rect
  736. // and thus fmod() will be disabled for handling the situation.
  737. // And due to this mouse warping mechanism being stateless, we need to apply some heuristics to
  738. // detect the warp: if the relative distance is greater than the half of the size of the relevant rect
  739. // (checked per each axis), it will be considered as the consequence of a former pointer warp.
  740. const Point2 rel_sign(p_motion->get_relative().x >= 0.0f ? 1 : -1, p_motion->get_relative().y >= 0.0 ? 1 : -1);
  741. const Size2 warp_margin = p_rect.size * 0.5f;
  742. const Point2 rel_warped(
  743. Math::fmod(p_motion->get_relative().x + rel_sign.x * warp_margin.x, p_rect.size.x) - rel_sign.x * warp_margin.x,
  744. Math::fmod(p_motion->get_relative().y + rel_sign.y * warp_margin.y, p_rect.size.y) - rel_sign.y * warp_margin.y);
  745. const Point2 pos_local = p_motion->get_global_position() - p_rect.position;
  746. const Point2 pos_warped(Math::fposmod(pos_local.x, p_rect.size.x), Math::fposmod(pos_local.y, p_rect.size.y));
  747. if (pos_warped != pos_local) {
  748. warp_mouse(pos_warped + p_rect.position);
  749. }
  750. return rel_warped;
  751. }
  752. void Input::action_press(const StringName &p_action, float p_strength) {
  753. ERR_FAIL_COND_MSG(!InputMap::get_singleton()->has_action(p_action), InputMap::get_singleton()->suggest_actions(p_action));
  754. // Create or retrieve existing action.
  755. ActionState &action_state = action_states[p_action];
  756. if (!action_state.cache.pressed) {
  757. action_state.pressed_physics_frame = Engine::get_singleton()->get_physics_frames();
  758. action_state.pressed_process_frame = Engine::get_singleton()->get_process_frames();
  759. }
  760. action_state.exact = true;
  761. action_state.api_pressed = true;
  762. action_state.api_strength = CLAMP(p_strength, 0.0f, 1.0f);
  763. _update_action_cache(p_action, action_state);
  764. }
  765. void Input::action_release(const StringName &p_action) {
  766. ERR_FAIL_COND_MSG(!InputMap::get_singleton()->has_action(p_action), InputMap::get_singleton()->suggest_actions(p_action));
  767. // Create or retrieve existing action.
  768. ActionState &action_state = action_states[p_action];
  769. action_state.cache.pressed = 0;
  770. action_state.cache.strength = 0.0;
  771. action_state.cache.raw_strength = 0.0;
  772. action_state.released_physics_frame = Engine::get_singleton()->get_physics_frames();
  773. action_state.released_process_frame = Engine::get_singleton()->get_process_frames();
  774. action_state.device_states.clear();
  775. action_state.exact = true;
  776. action_state.api_pressed = false;
  777. action_state.api_strength = 0.0;
  778. }
  779. void Input::set_emulate_touch_from_mouse(bool p_emulate) {
  780. emulate_touch_from_mouse = p_emulate;
  781. }
  782. bool Input::is_emulating_touch_from_mouse() const {
  783. return emulate_touch_from_mouse;
  784. }
  785. // Calling this whenever the game window is focused helps unsticking the "touch mouse"
  786. // if the OS or its abstraction class hasn't properly reported that touch pointers raised
  787. void Input::ensure_touch_mouse_raised() {
  788. _THREAD_SAFE_METHOD_
  789. if (mouse_from_touch_index != -1) {
  790. mouse_from_touch_index = -1;
  791. Ref<InputEventMouseButton> button_event;
  792. button_event.instantiate();
  793. button_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  794. button_event->set_position(mouse_pos);
  795. button_event->set_global_position(mouse_pos);
  796. button_event->set_pressed(false);
  797. button_event->set_button_index(MouseButton::LEFT);
  798. BitField<MouseButtonMask> ev_bm = mouse_button_mask;
  799. ev_bm.clear_flag(MouseButtonMask::LEFT);
  800. button_event->set_button_mask(ev_bm);
  801. _parse_input_event_impl(button_event, true);
  802. }
  803. }
  804. void Input::set_emulate_mouse_from_touch(bool p_emulate) {
  805. emulate_mouse_from_touch = p_emulate;
  806. }
  807. bool Input::is_emulating_mouse_from_touch() const {
  808. return emulate_mouse_from_touch;
  809. }
  810. Input::CursorShape Input::get_default_cursor_shape() const {
  811. return default_shape;
  812. }
  813. void Input::set_default_cursor_shape(CursorShape p_shape) {
  814. if (default_shape == p_shape) {
  815. return;
  816. }
  817. default_shape = p_shape;
  818. // The default shape is set in Viewport::_gui_input_event. To instantly
  819. // see the shape in the viewport we need to trigger a mouse motion event.
  820. Ref<InputEventMouseMotion> mm;
  821. mm.instantiate();
  822. mm->set_position(mouse_pos);
  823. mm->set_global_position(mouse_pos);
  824. mm->set_device(InputEvent::DEVICE_ID_INTERNAL);
  825. parse_input_event(mm);
  826. }
  827. Input::CursorShape Input::get_current_cursor_shape() const {
  828. return get_current_cursor_shape_func();
  829. }
  830. void Input::set_custom_mouse_cursor(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  831. if (Engine::get_singleton()->is_editor_hint()) {
  832. return;
  833. }
  834. ERR_FAIL_INDEX(p_shape, CursorShape::CURSOR_MAX);
  835. set_custom_mouse_cursor_func(p_cursor, p_shape, p_hotspot);
  836. }
  837. void Input::parse_input_event(const Ref<InputEvent> &p_event) {
  838. _THREAD_SAFE_METHOD_
  839. ERR_FAIL_COND(p_event.is_null());
  840. #ifdef DEBUG_ENABLED
  841. uint64_t curr_frame = Engine::get_singleton()->get_process_frames();
  842. if (curr_frame != last_parsed_frame) {
  843. frame_parsed_events.clear();
  844. last_parsed_frame = curr_frame;
  845. frame_parsed_events.insert(p_event);
  846. } else if (frame_parsed_events.has(p_event)) {
  847. // It would be technically safe to send the same event in cases such as:
  848. // - After an explicit flush.
  849. // - In platforms using buffering when agile flushing is enabled, after one of the mid-frame flushes.
  850. // - If platform doesn't use buffering and event accumulation is disabled.
  851. // - If platform doesn't use buffering and the event type is not accumulable.
  852. // However, it wouldn't be reasonable to ask users to remember the full ruleset and be aware at all times
  853. // of the possibilities of the target platform, project settings and engine internals, which may change
  854. // without prior notice.
  855. // Therefore, the guideline is, "don't send the same event object more than once per frame".
  856. WARN_PRINT_ONCE(
  857. "An input event object is being parsed more than once in the same frame, which is unsafe.\n"
  858. "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"
  859. "You can call duplicate() on the event to get a new instance with identical values.");
  860. } else {
  861. frame_parsed_events.insert(p_event);
  862. }
  863. #endif
  864. if (use_accumulated_input) {
  865. if (buffered_events.is_empty() || !buffered_events.back()->get()->accumulate(p_event)) {
  866. buffered_events.push_back(p_event);
  867. }
  868. } else if (use_input_buffering) {
  869. buffered_events.push_back(p_event);
  870. } else {
  871. _parse_input_event_impl(p_event, false);
  872. }
  873. }
  874. void Input::flush_buffered_events() {
  875. _THREAD_SAFE_METHOD_
  876. while (buffered_events.front()) {
  877. // The final delivery of the input event involves releasing the lock.
  878. // While the lock is released, another thread may lock it and add new events to the back.
  879. // Therefore, we get each event and pop it while we still have the lock,
  880. // to ensure the list is in a consistent state.
  881. List<Ref<InputEvent>>::Element *E = buffered_events.front();
  882. Ref<InputEvent> e = E->get();
  883. buffered_events.pop_front();
  884. _parse_input_event_impl(e, false);
  885. }
  886. }
  887. bool Input::is_using_input_buffering() {
  888. return use_input_buffering;
  889. }
  890. void Input::set_use_input_buffering(bool p_enable) {
  891. use_input_buffering = p_enable;
  892. }
  893. void Input::set_use_accumulated_input(bool p_enable) {
  894. use_accumulated_input = p_enable;
  895. }
  896. bool Input::is_using_accumulated_input() {
  897. return use_accumulated_input;
  898. }
  899. void Input::release_pressed_events() {
  900. flush_buffered_events(); // this is needed to release actions strengths
  901. keys_pressed.clear();
  902. physical_keys_pressed.clear();
  903. key_label_pressed.clear();
  904. joy_buttons_pressed.clear();
  905. _joy_axis.clear();
  906. for (KeyValue<StringName, Input::ActionState> &E : action_states) {
  907. if (E.value.cache.pressed) {
  908. action_release(E.key);
  909. }
  910. }
  911. }
  912. void Input::set_event_dispatch_function(EventDispatchFunc p_function) {
  913. event_dispatch_function = p_function;
  914. }
  915. void Input::joy_button(int p_device, JoyButton p_button, bool p_pressed) {
  916. _THREAD_SAFE_METHOD_;
  917. Joypad &joy = joy_names[p_device];
  918. ERR_FAIL_INDEX((int)p_button, (int)JoyButton::MAX);
  919. if (joy.last_buttons[(size_t)p_button] == p_pressed) {
  920. return;
  921. }
  922. joy.last_buttons[(size_t)p_button] = p_pressed;
  923. if (joy.mapping == -1) {
  924. _button_event(p_device, p_button, p_pressed);
  925. return;
  926. }
  927. JoyEvent map = _get_mapped_button_event(map_db[joy.mapping], p_button);
  928. if (map.type == TYPE_BUTTON) {
  929. _button_event(p_device, (JoyButton)map.index, p_pressed);
  930. return;
  931. }
  932. if (map.type == TYPE_AXIS) {
  933. _axis_event(p_device, (JoyAxis)map.index, p_pressed ? map.value : 0.0);
  934. }
  935. // no event?
  936. }
  937. void Input::joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  938. _THREAD_SAFE_METHOD_;
  939. ERR_FAIL_INDEX((int)p_axis, (int)JoyAxis::MAX);
  940. Joypad &joy = joy_names[p_device];
  941. if (joy.last_axis[(size_t)p_axis] == p_value) {
  942. return;
  943. }
  944. joy.last_axis[(size_t)p_axis] = p_value;
  945. if (joy.mapping == -1) {
  946. _axis_event(p_device, p_axis, p_value);
  947. return;
  948. }
  949. JoyAxisRange range;
  950. JoyEvent map = _get_mapped_axis_event(map_db[joy.mapping], p_axis, p_value, range);
  951. if (map.type == TYPE_BUTTON) {
  952. bool pressed = map.value > 0.5;
  953. if (pressed != joy_buttons_pressed.has(_combine_device((JoyButton)map.index, p_device))) {
  954. _button_event(p_device, (JoyButton)map.index, pressed);
  955. }
  956. // Ensure opposite D-Pad button is also released.
  957. switch ((JoyButton)map.index) {
  958. case JoyButton::DPAD_UP:
  959. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_DOWN, p_device))) {
  960. _button_event(p_device, JoyButton::DPAD_DOWN, false);
  961. }
  962. break;
  963. case JoyButton::DPAD_DOWN:
  964. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_UP, p_device))) {
  965. _button_event(p_device, JoyButton::DPAD_UP, false);
  966. }
  967. break;
  968. case JoyButton::DPAD_LEFT:
  969. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_RIGHT, p_device))) {
  970. _button_event(p_device, JoyButton::DPAD_RIGHT, false);
  971. }
  972. break;
  973. case JoyButton::DPAD_RIGHT:
  974. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_LEFT, p_device))) {
  975. _button_event(p_device, JoyButton::DPAD_LEFT, false);
  976. }
  977. break;
  978. default:
  979. // Nothing to do.
  980. break;
  981. }
  982. return;
  983. }
  984. if (map.type == TYPE_AXIS) {
  985. JoyAxis axis = JoyAxis(map.index);
  986. float value = map.value;
  987. if (range == FULL_AXIS && (axis == JoyAxis::TRIGGER_LEFT || axis == JoyAxis::TRIGGER_RIGHT)) {
  988. // Convert to a value between 0.0f and 1.0f.
  989. value = 0.5f + value / 2.0f;
  990. }
  991. _axis_event(p_device, axis, value);
  992. return;
  993. }
  994. }
  995. void Input::joy_hat(int p_device, BitField<HatMask> p_val) {
  996. _THREAD_SAFE_METHOD_;
  997. const Joypad &joy = joy_names[p_device];
  998. JoyEvent map[(size_t)HatDir::MAX];
  999. map[(size_t)HatDir::UP].type = TYPE_BUTTON;
  1000. map[(size_t)HatDir::UP].index = (int)JoyButton::DPAD_UP;
  1001. map[(size_t)HatDir::UP].value = 0;
  1002. map[(size_t)HatDir::RIGHT].type = TYPE_BUTTON;
  1003. map[(size_t)HatDir::RIGHT].index = (int)JoyButton::DPAD_RIGHT;
  1004. map[(size_t)HatDir::RIGHT].value = 0;
  1005. map[(size_t)HatDir::DOWN].type = TYPE_BUTTON;
  1006. map[(size_t)HatDir::DOWN].index = (int)JoyButton::DPAD_DOWN;
  1007. map[(size_t)HatDir::DOWN].value = 0;
  1008. map[(size_t)HatDir::LEFT].type = TYPE_BUTTON;
  1009. map[(size_t)HatDir::LEFT].index = (int)JoyButton::DPAD_LEFT;
  1010. map[(size_t)HatDir::LEFT].value = 0;
  1011. if (joy.mapping != -1) {
  1012. _get_mapped_hat_events(map_db[joy.mapping], (HatDir)0, map);
  1013. }
  1014. int cur_val = joy_names[p_device].hat_current;
  1015. for (int hat_direction = 0, hat_mask = 1; hat_direction < (int)HatDir::MAX; hat_direction++, hat_mask <<= 1) {
  1016. if (((int)p_val & hat_mask) != (cur_val & hat_mask)) {
  1017. if (map[hat_direction].type == TYPE_BUTTON) {
  1018. _button_event(p_device, (JoyButton)map[hat_direction].index, (int)p_val & hat_mask);
  1019. }
  1020. if (map[hat_direction].type == TYPE_AXIS) {
  1021. _axis_event(p_device, (JoyAxis)map[hat_direction].index, ((int)p_val & hat_mask) ? map[hat_direction].value : 0.0);
  1022. }
  1023. }
  1024. }
  1025. joy_names[p_device].hat_current = (int)p_val;
  1026. }
  1027. void Input::_button_event(int p_device, JoyButton p_index, bool p_pressed) {
  1028. Ref<InputEventJoypadButton> ievent;
  1029. ievent.instantiate();
  1030. ievent->set_device(p_device);
  1031. ievent->set_button_index(p_index);
  1032. ievent->set_pressed(p_pressed);
  1033. parse_input_event(ievent);
  1034. }
  1035. void Input::_axis_event(int p_device, JoyAxis p_axis, float p_value) {
  1036. Ref<InputEventJoypadMotion> ievent;
  1037. ievent.instantiate();
  1038. ievent->set_device(p_device);
  1039. ievent->set_axis(p_axis);
  1040. ievent->set_axis_value(p_value);
  1041. parse_input_event(ievent);
  1042. }
  1043. void Input::_update_action_cache(const StringName &p_action_name, ActionState &r_action_state) {
  1044. // Update the action cache, computed from the per-device and per-event states.
  1045. r_action_state.cache.pressed = false;
  1046. r_action_state.cache.strength = 0.0;
  1047. r_action_state.cache.raw_strength = 0.0;
  1048. int max_event = InputMap::get_singleton()->action_get_events(p_action_name)->size();
  1049. for (const KeyValue<int, ActionState::DeviceState> &kv : r_action_state.device_states) {
  1050. const ActionState::DeviceState &device_state = kv.value;
  1051. for (int i = 0; i < max_event; i++) {
  1052. r_action_state.cache.pressed = r_action_state.cache.pressed || device_state.pressed[i];
  1053. r_action_state.cache.strength = MAX(r_action_state.cache.strength, device_state.strength[i]);
  1054. r_action_state.cache.raw_strength = MAX(r_action_state.cache.raw_strength, device_state.raw_strength[i]);
  1055. }
  1056. }
  1057. if (r_action_state.api_pressed) {
  1058. r_action_state.cache.pressed = true;
  1059. r_action_state.cache.strength = MAX(r_action_state.cache.strength, r_action_state.api_strength);
  1060. 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.
  1061. }
  1062. }
  1063. Input::JoyEvent Input::_get_mapped_button_event(const JoyDeviceMapping &mapping, JoyButton p_button) {
  1064. JoyEvent event;
  1065. for (int i = 0; i < mapping.bindings.size(); i++) {
  1066. const JoyBinding binding = mapping.bindings[i];
  1067. if (binding.inputType == TYPE_BUTTON && binding.input.button == p_button) {
  1068. event.type = binding.outputType;
  1069. switch (binding.outputType) {
  1070. case TYPE_BUTTON:
  1071. event.index = (int)binding.output.button;
  1072. return event;
  1073. case TYPE_AXIS:
  1074. event.index = (int)binding.output.axis.axis;
  1075. switch (binding.output.axis.range) {
  1076. case POSITIVE_HALF_AXIS:
  1077. event.value = 1;
  1078. break;
  1079. case NEGATIVE_HALF_AXIS:
  1080. event.value = -1;
  1081. break;
  1082. case FULL_AXIS:
  1083. // It doesn't make sense for a button to map to a full axis,
  1084. // but keeping as a default for a trigger with a positive half-axis.
  1085. event.value = 1;
  1086. break;
  1087. }
  1088. return event;
  1089. default:
  1090. ERR_PRINT_ONCE("Joypad button mapping error.");
  1091. }
  1092. }
  1093. }
  1094. return event;
  1095. }
  1096. Input::JoyEvent Input::_get_mapped_axis_event(const JoyDeviceMapping &mapping, JoyAxis p_axis, float p_value, JoyAxisRange &r_range) {
  1097. JoyEvent event;
  1098. for (int i = 0; i < mapping.bindings.size(); i++) {
  1099. const JoyBinding binding = mapping.bindings[i];
  1100. if (binding.inputType == TYPE_AXIS && binding.input.axis.axis == p_axis) {
  1101. float value = p_value;
  1102. if (binding.input.axis.invert) {
  1103. value = -value;
  1104. }
  1105. if (binding.input.axis.range == FULL_AXIS ||
  1106. (binding.input.axis.range == POSITIVE_HALF_AXIS && value >= 0) ||
  1107. (binding.input.axis.range == NEGATIVE_HALF_AXIS && value < 0)) {
  1108. event.type = binding.outputType;
  1109. float shifted_positive_value = 0;
  1110. switch (binding.input.axis.range) {
  1111. case POSITIVE_HALF_AXIS:
  1112. shifted_positive_value = value;
  1113. break;
  1114. case NEGATIVE_HALF_AXIS:
  1115. shifted_positive_value = value + 1;
  1116. break;
  1117. case FULL_AXIS:
  1118. shifted_positive_value = (value + 1) / 2;
  1119. break;
  1120. }
  1121. switch (binding.outputType) {
  1122. case TYPE_BUTTON:
  1123. event.index = (int)binding.output.button;
  1124. switch (binding.input.axis.range) {
  1125. case POSITIVE_HALF_AXIS:
  1126. event.value = shifted_positive_value;
  1127. break;
  1128. case NEGATIVE_HALF_AXIS:
  1129. event.value = 1 - shifted_positive_value;
  1130. break;
  1131. case FULL_AXIS:
  1132. // It doesn't make sense for a full axis to map to a button,
  1133. // but keeping as a default for a trigger with a positive half-axis.
  1134. event.value = (shifted_positive_value * 2) - 1;
  1135. break;
  1136. }
  1137. return event;
  1138. case TYPE_AXIS:
  1139. event.index = (int)binding.output.axis.axis;
  1140. event.value = value;
  1141. r_range = binding.output.axis.range;
  1142. if (binding.output.axis.range != binding.input.axis.range) {
  1143. switch (binding.output.axis.range) {
  1144. case POSITIVE_HALF_AXIS:
  1145. event.value = shifted_positive_value;
  1146. break;
  1147. case NEGATIVE_HALF_AXIS:
  1148. event.value = shifted_positive_value - 1;
  1149. break;
  1150. case FULL_AXIS:
  1151. event.value = (shifted_positive_value * 2) - 1;
  1152. break;
  1153. }
  1154. }
  1155. return event;
  1156. default:
  1157. ERR_PRINT_ONCE("Joypad axis mapping error.");
  1158. }
  1159. }
  1160. }
  1161. }
  1162. return event;
  1163. }
  1164. void Input::_get_mapped_hat_events(const JoyDeviceMapping &mapping, HatDir p_hat, JoyEvent r_events[(size_t)HatDir::MAX]) {
  1165. for (int i = 0; i < mapping.bindings.size(); i++) {
  1166. const JoyBinding binding = mapping.bindings[i];
  1167. if (binding.inputType == TYPE_HAT && binding.input.hat.hat == p_hat) {
  1168. HatDir hat_direction;
  1169. switch (binding.input.hat.hat_mask) {
  1170. case HatMask::UP:
  1171. hat_direction = HatDir::UP;
  1172. break;
  1173. case HatMask::RIGHT:
  1174. hat_direction = HatDir::RIGHT;
  1175. break;
  1176. case HatMask::DOWN:
  1177. hat_direction = HatDir::DOWN;
  1178. break;
  1179. case HatMask::LEFT:
  1180. hat_direction = HatDir::LEFT;
  1181. break;
  1182. default:
  1183. ERR_PRINT_ONCE("Joypad button mapping error.");
  1184. continue;
  1185. }
  1186. r_events[(size_t)hat_direction].type = binding.outputType;
  1187. switch (binding.outputType) {
  1188. case TYPE_BUTTON:
  1189. r_events[(size_t)hat_direction].index = (int)binding.output.button;
  1190. break;
  1191. case TYPE_AXIS:
  1192. r_events[(size_t)hat_direction].index = (int)binding.output.axis.axis;
  1193. switch (binding.output.axis.range) {
  1194. case POSITIVE_HALF_AXIS:
  1195. r_events[(size_t)hat_direction].value = 1;
  1196. break;
  1197. case NEGATIVE_HALF_AXIS:
  1198. r_events[(size_t)hat_direction].value = -1;
  1199. break;
  1200. case FULL_AXIS:
  1201. // It doesn't make sense for a hat direction to map to a full axis,
  1202. // but keeping as a default for a trigger with a positive half-axis.
  1203. r_events[(size_t)hat_direction].value = 1;
  1204. break;
  1205. }
  1206. break;
  1207. default:
  1208. ERR_PRINT_ONCE("Joypad button mapping error.");
  1209. }
  1210. }
  1211. }
  1212. }
  1213. JoyButton Input::_get_output_button(const String &output) {
  1214. for (int i = 0; i < (int)JoyButton::SDL_MAX; i++) {
  1215. if (output == _joy_buttons[i]) {
  1216. return JoyButton(i);
  1217. }
  1218. }
  1219. return JoyButton::INVALID;
  1220. }
  1221. JoyAxis Input::_get_output_axis(const String &output) {
  1222. for (int i = 0; i < (int)JoyAxis::SDL_MAX; i++) {
  1223. if (output == _joy_axes[i]) {
  1224. return JoyAxis(i);
  1225. }
  1226. }
  1227. return JoyAxis::INVALID;
  1228. }
  1229. void Input::parse_mapping(const String &p_mapping) {
  1230. _THREAD_SAFE_METHOD_;
  1231. JoyDeviceMapping mapping;
  1232. Vector<String> entry = p_mapping.split(",");
  1233. if (entry.size() < 2) {
  1234. return;
  1235. }
  1236. CharString uid;
  1237. uid.resize(17);
  1238. mapping.uid = entry[0];
  1239. mapping.name = entry[1];
  1240. int idx = 1;
  1241. while (++idx < entry.size()) {
  1242. if (entry[idx].is_empty()) {
  1243. continue;
  1244. }
  1245. String output = entry[idx].get_slice(":", 0).replace(" ", "");
  1246. String input = entry[idx].get_slice(":", 1).replace(" ", "");
  1247. if (output.length() < 1 || input.length() < 2) {
  1248. continue;
  1249. }
  1250. if (output == "platform" || output == "hint") {
  1251. continue;
  1252. }
  1253. JoyAxisRange output_range = FULL_AXIS;
  1254. if (output[0] == '+' || output[0] == '-') {
  1255. ERR_CONTINUE_MSG(output.length() < 2,
  1256. vformat("Invalid output entry \"%s\" in mapping:\n%s", entry[idx], p_mapping));
  1257. if (output[0] == '+') {
  1258. output_range = POSITIVE_HALF_AXIS;
  1259. } else if (output[0] == '-') {
  1260. output_range = NEGATIVE_HALF_AXIS;
  1261. }
  1262. output = output.substr(1);
  1263. }
  1264. JoyAxisRange input_range = FULL_AXIS;
  1265. if (input[0] == '+') {
  1266. input_range = POSITIVE_HALF_AXIS;
  1267. input = input.substr(1);
  1268. } else if (input[0] == '-') {
  1269. input_range = NEGATIVE_HALF_AXIS;
  1270. input = input.substr(1);
  1271. }
  1272. bool invert_axis = false;
  1273. if (input[input.length() - 1] == '~') {
  1274. invert_axis = true;
  1275. input = input.left(input.length() - 1);
  1276. }
  1277. JoyButton output_button = _get_output_button(output);
  1278. JoyAxis output_axis = _get_output_axis(output);
  1279. if (output_button == JoyButton::INVALID && output_axis == JoyAxis::INVALID) {
  1280. print_verbose(vformat("Unrecognized output string \"%s\" in mapping:\n%s", output, p_mapping));
  1281. }
  1282. ERR_CONTINUE_MSG(output_button != JoyButton::INVALID && output_axis != JoyAxis::INVALID,
  1283. vformat("Output string \"%s\" matched both button and axis in mapping:\n%s", output, p_mapping));
  1284. JoyBinding binding;
  1285. if (output_button != JoyButton::INVALID) {
  1286. binding.outputType = TYPE_BUTTON;
  1287. binding.output.button = output_button;
  1288. } else if (output_axis != JoyAxis::INVALID) {
  1289. binding.outputType = TYPE_AXIS;
  1290. binding.output.axis.axis = output_axis;
  1291. binding.output.axis.range = output_range;
  1292. }
  1293. switch (input[0]) {
  1294. case 'b':
  1295. binding.inputType = TYPE_BUTTON;
  1296. binding.input.button = (JoyButton)input.substr(1).to_int();
  1297. break;
  1298. case 'a':
  1299. binding.inputType = TYPE_AXIS;
  1300. binding.input.axis.axis = (JoyAxis)input.substr(1).to_int();
  1301. binding.input.axis.range = input_range;
  1302. binding.input.axis.invert = invert_axis;
  1303. break;
  1304. case 'h':
  1305. ERR_CONTINUE_MSG(input.length() != 4 || input[2] != '.',
  1306. vformat("Invalid had input \"%s\" in mapping:\n%s", input, p_mapping));
  1307. binding.inputType = TYPE_HAT;
  1308. binding.input.hat.hat = (HatDir)input.substr(1, 1).to_int();
  1309. binding.input.hat.hat_mask = static_cast<HatMask>(input.substr(3).to_int());
  1310. break;
  1311. default:
  1312. ERR_CONTINUE_MSG(true, vformat("Unrecognized input string \"%s\" in mapping:\n%s", input, p_mapping));
  1313. }
  1314. mapping.bindings.push_back(binding);
  1315. }
  1316. map_db.push_back(mapping);
  1317. }
  1318. void Input::add_joy_mapping(const String &p_mapping, bool p_update_existing) {
  1319. parse_mapping(p_mapping);
  1320. if (p_update_existing) {
  1321. Vector<String> entry = p_mapping.split(",");
  1322. const String &uid = entry[0];
  1323. for (KeyValue<int, Joypad> &E : joy_names) {
  1324. Joypad &joy = E.value;
  1325. if (joy.uid == uid) {
  1326. joy.mapping = map_db.size() - 1;
  1327. }
  1328. }
  1329. }
  1330. }
  1331. void Input::remove_joy_mapping(const String &p_guid) {
  1332. for (int i = map_db.size() - 1; i >= 0; i--) {
  1333. if (p_guid == map_db[i].uid) {
  1334. map_db.remove_at(i);
  1335. }
  1336. }
  1337. for (KeyValue<int, Joypad> &E : joy_names) {
  1338. Joypad &joy = E.value;
  1339. if (joy.uid == p_guid) {
  1340. joy.mapping = -1;
  1341. }
  1342. }
  1343. }
  1344. void Input::set_fallback_mapping(const String &p_guid) {
  1345. for (int i = 0; i < map_db.size(); i++) {
  1346. if (map_db[i].uid == p_guid) {
  1347. fallback_mapping = i;
  1348. return;
  1349. }
  1350. }
  1351. }
  1352. //platforms that use the remapping system can override and call to these ones
  1353. bool Input::is_joy_known(int p_device) {
  1354. if (joy_names.has(p_device)) {
  1355. int mapping = joy_names[p_device].mapping;
  1356. if (mapping != -1 && mapping != fallback_mapping) {
  1357. return true;
  1358. }
  1359. }
  1360. return false;
  1361. }
  1362. String Input::get_joy_guid(int p_device) const {
  1363. ERR_FAIL_COND_V(!joy_names.has(p_device), "");
  1364. return joy_names[p_device].uid;
  1365. }
  1366. Dictionary Input::get_joy_info(int p_device) const {
  1367. ERR_FAIL_COND_V(!joy_names.has(p_device), Dictionary());
  1368. return joy_names[p_device].info;
  1369. }
  1370. bool Input::should_ignore_device(int p_vendor_id, int p_product_id) const {
  1371. uint32_t full_id = (((uint32_t)p_vendor_id) << 16) | ((uint16_t)p_product_id);
  1372. return ignored_device_ids.has(full_id);
  1373. }
  1374. TypedArray<int> Input::get_connected_joypads() {
  1375. TypedArray<int> ret;
  1376. HashMap<int, Joypad>::Iterator elem = joy_names.begin();
  1377. while (elem) {
  1378. if (elem->value.connected) {
  1379. ret.push_back(elem->key);
  1380. }
  1381. ++elem;
  1382. }
  1383. return ret;
  1384. }
  1385. int Input::get_unused_joy_id() {
  1386. for (int i = 0; i < JOYPADS_MAX; i++) {
  1387. if (!joy_names.has(i) || !joy_names[i].connected) {
  1388. return i;
  1389. }
  1390. }
  1391. return -1;
  1392. }
  1393. Input::Input() {
  1394. singleton = this;
  1395. // Parse default mappings.
  1396. {
  1397. int i = 0;
  1398. while (DefaultControllerMappings::mappings[i]) {
  1399. parse_mapping(DefaultControllerMappings::mappings[i++]);
  1400. }
  1401. }
  1402. // If defined, parse SDL_GAMECONTROLLERCONFIG for possible new mappings/overrides.
  1403. String env_mapping = OS::get_singleton()->get_environment("SDL_GAMECONTROLLERCONFIG");
  1404. if (!env_mapping.is_empty()) {
  1405. Vector<String> entries = env_mapping.split("\n");
  1406. for (int i = 0; i < entries.size(); i++) {
  1407. if (entries[i].is_empty()) {
  1408. continue;
  1409. }
  1410. parse_mapping(entries[i]);
  1411. }
  1412. }
  1413. String env_ignore_devices = OS::get_singleton()->get_environment("SDL_GAMECONTROLLER_IGNORE_DEVICES");
  1414. if (!env_ignore_devices.is_empty()) {
  1415. Vector<String> entries = env_ignore_devices.split(",");
  1416. for (int i = 0; i < entries.size(); i++) {
  1417. Vector<String> vid_pid = entries[i].split("/");
  1418. if (vid_pid.size() < 2) {
  1419. continue;
  1420. }
  1421. print_verbose(vformat("Device Ignored -- Vendor: %s Product: %s", vid_pid[0], vid_pid[1]));
  1422. const uint16_t vid_unswapped = vid_pid[0].hex_to_int();
  1423. const uint16_t pid_unswapped = vid_pid[1].hex_to_int();
  1424. const uint16_t vid = BSWAP16(vid_unswapped);
  1425. const uint16_t pid = BSWAP16(pid_unswapped);
  1426. uint32_t full_id = (((uint32_t)vid) << 16) | ((uint16_t)pid);
  1427. ignored_device_ids.insert(full_id);
  1428. }
  1429. }
  1430. legacy_just_pressed_behavior = GLOBAL_DEF("input_devices/compatibility/legacy_just_pressed_behavior", false);
  1431. if (Engine::get_singleton()->is_editor_hint()) {
  1432. // Always use standard behavior in the editor.
  1433. legacy_just_pressed_behavior = false;
  1434. }
  1435. }
  1436. Input::~Input() {
  1437. singleton = nullptr;
  1438. }
  1439. //////////////////////////////////////////////////////////