input.cpp 50 KB

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