2
0

input.cpp 46 KB

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