input.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  1. /*************************************************************************/
  2. /* input.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "input.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/input/default_controller_mappings.h"
  33. #include "core/input/input_map.h"
  34. #include "core/os/os.h"
  35. static const char *_joy_buttons[(size_t)JoyButton::SDL_MAX] = {
  36. "a",
  37. "b",
  38. "x",
  39. "y",
  40. "back",
  41. "guide",
  42. "start",
  43. "leftstick",
  44. "rightstick",
  45. "leftshoulder",
  46. "rightshoulder",
  47. "dpup",
  48. "dpdown",
  49. "dpleft",
  50. "dpright",
  51. "misc1",
  52. "paddle1",
  53. "paddle2",
  54. "paddle3",
  55. "paddle4",
  56. "touchpad",
  57. };
  58. static const char *_joy_axes[(size_t)JoyAxis::SDL_MAX] = {
  59. "leftx",
  60. "lefty",
  61. "rightx",
  62. "righty",
  63. "lefttrigger",
  64. "righttrigger",
  65. };
  66. Input *Input::singleton = nullptr;
  67. void (*Input::set_mouse_mode_func)(Input::MouseMode) = nullptr;
  68. Input::MouseMode (*Input::get_mouse_mode_func)() = nullptr;
  69. void (*Input::warp_mouse_func)(const Vector2 &p_position) = nullptr;
  70. Input::CursorShape (*Input::get_current_cursor_shape_func)() = nullptr;
  71. void (*Input::set_custom_mouse_cursor_func)(const Ref<Resource> &, Input::CursorShape, const Vector2 &) = nullptr;
  72. Input *Input::get_singleton() {
  73. return singleton;
  74. }
  75. void Input::set_mouse_mode(MouseMode p_mode) {
  76. ERR_FAIL_INDEX((int)p_mode, 5);
  77. set_mouse_mode_func(p_mode);
  78. }
  79. Input::MouseMode Input::get_mouse_mode() const {
  80. return get_mouse_mode_func();
  81. }
  82. void Input::_bind_methods() {
  83. ClassDB::bind_method(D_METHOD("is_anything_pressed"), &Input::is_anything_pressed);
  84. ClassDB::bind_method(D_METHOD("is_key_pressed", "keycode"), &Input::is_key_pressed);
  85. ClassDB::bind_method(D_METHOD("is_physical_key_pressed", "keycode"), &Input::is_physical_key_pressed);
  86. ClassDB::bind_method(D_METHOD("is_mouse_button_pressed", "button"), &Input::is_mouse_button_pressed);
  87. ClassDB::bind_method(D_METHOD("is_joy_button_pressed", "device", "button"), &Input::is_joy_button_pressed);
  88. ClassDB::bind_method(D_METHOD("is_action_pressed", "action", "exact_match"), &Input::is_action_pressed, DEFVAL(false));
  89. ClassDB::bind_method(D_METHOD("is_action_just_pressed", "action", "exact_match"), &Input::is_action_just_pressed, DEFVAL(false));
  90. ClassDB::bind_method(D_METHOD("is_action_just_released", "action", "exact_match"), &Input::is_action_just_released, DEFVAL(false));
  91. ClassDB::bind_method(D_METHOD("get_action_strength", "action", "exact_match"), &Input::get_action_strength, DEFVAL(false));
  92. ClassDB::bind_method(D_METHOD("get_action_raw_strength", "action", "exact_match"), &Input::get_action_raw_strength, DEFVAL(false));
  93. ClassDB::bind_method(D_METHOD("get_axis", "negative_action", "positive_action"), &Input::get_axis);
  94. ClassDB::bind_method(D_METHOD("get_vector", "negative_x", "positive_x", "negative_y", "positive_y", "deadzone"), &Input::get_vector, DEFVAL(-1.0f));
  95. ClassDB::bind_method(D_METHOD("add_joy_mapping", "mapping", "update_existing"), &Input::add_joy_mapping, DEFVAL(false));
  96. ClassDB::bind_method(D_METHOD("remove_joy_mapping", "guid"), &Input::remove_joy_mapping);
  97. ClassDB::bind_method(D_METHOD("is_joy_known", "device"), &Input::is_joy_known);
  98. ClassDB::bind_method(D_METHOD("get_joy_axis", "device", "axis"), &Input::get_joy_axis);
  99. ClassDB::bind_method(D_METHOD("get_joy_name", "device"), &Input::get_joy_name);
  100. ClassDB::bind_method(D_METHOD("get_joy_guid", "device"), &Input::get_joy_guid);
  101. ClassDB::bind_method(D_METHOD("get_connected_joypads"), &Input::get_connected_joypads);
  102. ClassDB::bind_method(D_METHOD("get_joy_vibration_strength", "device"), &Input::get_joy_vibration_strength);
  103. ClassDB::bind_method(D_METHOD("get_joy_vibration_duration", "device"), &Input::get_joy_vibration_duration);
  104. ClassDB::bind_method(D_METHOD("start_joy_vibration", "device", "weak_magnitude", "strong_magnitude", "duration"), &Input::start_joy_vibration, DEFVAL(0));
  105. ClassDB::bind_method(D_METHOD("stop_joy_vibration", "device"), &Input::stop_joy_vibration);
  106. ClassDB::bind_method(D_METHOD("vibrate_handheld", "duration_ms"), &Input::vibrate_handheld, DEFVAL(500));
  107. ClassDB::bind_method(D_METHOD("get_gravity"), &Input::get_gravity);
  108. ClassDB::bind_method(D_METHOD("get_accelerometer"), &Input::get_accelerometer);
  109. ClassDB::bind_method(D_METHOD("get_magnetometer"), &Input::get_magnetometer);
  110. ClassDB::bind_method(D_METHOD("get_gyroscope"), &Input::get_gyroscope);
  111. ClassDB::bind_method(D_METHOD("set_gravity", "value"), &Input::set_gravity);
  112. ClassDB::bind_method(D_METHOD("set_accelerometer", "value"), &Input::set_accelerometer);
  113. ClassDB::bind_method(D_METHOD("set_magnetometer", "value"), &Input::set_magnetometer);
  114. ClassDB::bind_method(D_METHOD("set_gyroscope", "value"), &Input::set_gyroscope);
  115. ClassDB::bind_method(D_METHOD("get_last_mouse_velocity"), &Input::get_last_mouse_velocity);
  116. ClassDB::bind_method(D_METHOD("get_mouse_button_mask"), &Input::get_mouse_button_mask);
  117. ClassDB::bind_method(D_METHOD("set_mouse_mode", "mode"), &Input::set_mouse_mode);
  118. ClassDB::bind_method(D_METHOD("get_mouse_mode"), &Input::get_mouse_mode);
  119. ClassDB::bind_method(D_METHOD("warp_mouse", "position"), &Input::warp_mouse);
  120. ClassDB::bind_method(D_METHOD("action_press", "action", "strength"), &Input::action_press, DEFVAL(1.f));
  121. ClassDB::bind_method(D_METHOD("action_release", "action"), &Input::action_release);
  122. ClassDB::bind_method(D_METHOD("set_default_cursor_shape", "shape"), &Input::set_default_cursor_shape, DEFVAL(CURSOR_ARROW));
  123. ClassDB::bind_method(D_METHOD("get_current_cursor_shape"), &Input::get_current_cursor_shape);
  124. ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor", "image", "shape", "hotspot"), &Input::set_custom_mouse_cursor, DEFVAL(CURSOR_ARROW), DEFVAL(Vector2()));
  125. ClassDB::bind_method(D_METHOD("parse_input_event", "event"), &Input::parse_input_event);
  126. ClassDB::bind_method(D_METHOD("set_use_accumulated_input", "enable"), &Input::set_use_accumulated_input);
  127. ClassDB::bind_method(D_METHOD("is_using_accumulated_input"), &Input::is_using_accumulated_input);
  128. ClassDB::bind_method(D_METHOD("flush_buffered_events"), &Input::flush_buffered_events);
  129. ADD_PROPERTY(PropertyInfo(Variant::INT, "mouse_mode"), "set_mouse_mode", "get_mouse_mode");
  130. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_accumulated_input"), "set_use_accumulated_input", "is_using_accumulated_input");
  131. BIND_ENUM_CONSTANT(MOUSE_MODE_VISIBLE);
  132. BIND_ENUM_CONSTANT(MOUSE_MODE_HIDDEN);
  133. BIND_ENUM_CONSTANT(MOUSE_MODE_CAPTURED);
  134. BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED);
  135. BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED_HIDDEN);
  136. BIND_ENUM_CONSTANT(CURSOR_ARROW);
  137. BIND_ENUM_CONSTANT(CURSOR_IBEAM);
  138. BIND_ENUM_CONSTANT(CURSOR_POINTING_HAND);
  139. BIND_ENUM_CONSTANT(CURSOR_CROSS);
  140. BIND_ENUM_CONSTANT(CURSOR_WAIT);
  141. BIND_ENUM_CONSTANT(CURSOR_BUSY);
  142. BIND_ENUM_CONSTANT(CURSOR_DRAG);
  143. BIND_ENUM_CONSTANT(CURSOR_CAN_DROP);
  144. BIND_ENUM_CONSTANT(CURSOR_FORBIDDEN);
  145. BIND_ENUM_CONSTANT(CURSOR_VSIZE);
  146. BIND_ENUM_CONSTANT(CURSOR_HSIZE);
  147. BIND_ENUM_CONSTANT(CURSOR_BDIAGSIZE);
  148. BIND_ENUM_CONSTANT(CURSOR_FDIAGSIZE);
  149. BIND_ENUM_CONSTANT(CURSOR_MOVE);
  150. BIND_ENUM_CONSTANT(CURSOR_VSPLIT);
  151. BIND_ENUM_CONSTANT(CURSOR_HSPLIT);
  152. BIND_ENUM_CONSTANT(CURSOR_HELP);
  153. ADD_SIGNAL(MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "device"), PropertyInfo(Variant::BOOL, "connected")));
  154. }
  155. void Input::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  156. String pf = p_function;
  157. if ((p_idx == 0 && (pf == "is_action_pressed" || pf == "action_press" || pf == "action_release" || pf == "is_action_just_pressed" || pf == "is_action_just_released" || pf == "get_action_strength" || pf == "get_action_raw_strength")) ||
  158. (p_idx < 2 && pf == "get_axis") ||
  159. (p_idx < 4 && pf == "get_vector")) {
  160. List<PropertyInfo> pinfo;
  161. ProjectSettings::get_singleton()->get_property_list(&pinfo);
  162. for (const PropertyInfo &pi : pinfo) {
  163. if (!pi.name.begins_with("input/")) {
  164. continue;
  165. }
  166. String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
  167. r_options->push_back(name.quote());
  168. }
  169. }
  170. }
  171. void Input::VelocityTrack::update(const Vector2 &p_delta_p) {
  172. uint64_t tick = OS::get_singleton()->get_ticks_usec();
  173. uint32_t tdiff = tick - last_tick;
  174. float delta_t = tdiff / 1000000.0;
  175. last_tick = tick;
  176. if (delta_t > max_ref_frame) {
  177. // First movement in a long time, reset and start again.
  178. velocity = Vector2();
  179. accum = p_delta_p;
  180. accum_t = 0;
  181. return;
  182. }
  183. accum += p_delta_p;
  184. accum_t += delta_t;
  185. if (accum_t < min_ref_frame) {
  186. // Not enough time has passed to calculate speed precisely.
  187. return;
  188. }
  189. velocity = accum / accum_t;
  190. accum = Vector2();
  191. accum_t = 0;
  192. }
  193. void Input::VelocityTrack::reset() {
  194. last_tick = OS::get_singleton()->get_ticks_usec();
  195. velocity = Vector2();
  196. accum = Vector2();
  197. accum_t = 0;
  198. }
  199. Input::VelocityTrack::VelocityTrack() {
  200. min_ref_frame = 0.1;
  201. max_ref_frame = 3.0;
  202. reset();
  203. }
  204. bool Input::is_anything_pressed() const {
  205. _THREAD_SAFE_METHOD_
  206. for (const KeyValue<StringName, Input::Action> &E : action_state) {
  207. if (E.value.pressed) {
  208. return true;
  209. }
  210. }
  211. return !keys_pressed.is_empty() ||
  212. !joy_buttons_pressed.is_empty() ||
  213. mouse_button_mask > MouseButton::NONE;
  214. }
  215. bool Input::is_key_pressed(Key p_keycode) const {
  216. _THREAD_SAFE_METHOD_
  217. return keys_pressed.has(p_keycode);
  218. }
  219. bool Input::is_physical_key_pressed(Key p_keycode) const {
  220. _THREAD_SAFE_METHOD_
  221. return physical_keys_pressed.has(p_keycode);
  222. }
  223. bool Input::is_mouse_button_pressed(MouseButton p_button) const {
  224. _THREAD_SAFE_METHOD_
  225. return (mouse_button_mask & mouse_button_to_mask(p_button)) != MouseButton::NONE;
  226. }
  227. static JoyAxis _combine_device(JoyAxis p_value, int p_device) {
  228. return JoyAxis((int)p_value | (p_device << 20));
  229. }
  230. static JoyButton _combine_device(JoyButton p_value, int p_device) {
  231. return JoyButton((int)p_value | (p_device << 20));
  232. }
  233. bool Input::is_joy_button_pressed(int p_device, JoyButton p_button) const {
  234. _THREAD_SAFE_METHOD_
  235. return joy_buttons_pressed.has(_combine_device(p_button, p_device));
  236. }
  237. bool Input::is_action_pressed(const StringName &p_action, bool p_exact) const {
  238. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  239. return action_state.has(p_action) && action_state[p_action].pressed && (p_exact ? action_state[p_action].exact : true);
  240. }
  241. bool Input::is_action_just_pressed(const StringName &p_action, bool p_exact) const {
  242. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  243. HashMap<StringName, Action>::ConstIterator E = action_state.find(p_action);
  244. if (!E) {
  245. return false;
  246. }
  247. if (p_exact && E->value.exact == false) {
  248. return false;
  249. }
  250. if (Engine::get_singleton()->is_in_physics_frame()) {
  251. return E->value.pressed && E->value.physics_frame == Engine::get_singleton()->get_physics_frames();
  252. } else {
  253. return E->value.pressed && E->value.process_frame == Engine::get_singleton()->get_process_frames();
  254. }
  255. }
  256. bool Input::is_action_just_released(const StringName &p_action, bool p_exact) const {
  257. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  258. HashMap<StringName, Action>::ConstIterator E = action_state.find(p_action);
  259. if (!E) {
  260. return false;
  261. }
  262. if (p_exact && E->value.exact == false) {
  263. return false;
  264. }
  265. if (Engine::get_singleton()->is_in_physics_frame()) {
  266. return !E->value.pressed && E->value.physics_frame == Engine::get_singleton()->get_physics_frames();
  267. } else {
  268. return !E->value.pressed && E->value.process_frame == Engine::get_singleton()->get_process_frames();
  269. }
  270. }
  271. float Input::get_action_strength(const StringName &p_action, bool p_exact) const {
  272. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
  273. HashMap<StringName, Action>::ConstIterator E = action_state.find(p_action);
  274. if (!E) {
  275. return 0.0f;
  276. }
  277. if (p_exact && E->value.exact == false) {
  278. return 0.0f;
  279. }
  280. return E->value.strength;
  281. }
  282. float Input::get_action_raw_strength(const StringName &p_action, bool p_exact) const {
  283. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
  284. HashMap<StringName, Action>::ConstIterator E = action_state.find(p_action);
  285. if (!E) {
  286. return 0.0f;
  287. }
  288. if (p_exact && E->value.exact == false) {
  289. return 0.0f;
  290. }
  291. return E->value.raw_strength;
  292. }
  293. float Input::get_axis(const StringName &p_negative_action, const StringName &p_positive_action) const {
  294. return get_action_strength(p_positive_action) - get_action_strength(p_negative_action);
  295. }
  296. Vector2 Input::get_vector(const StringName &p_negative_x, const StringName &p_positive_x, const StringName &p_negative_y, const StringName &p_positive_y, float p_deadzone) const {
  297. Vector2 vector = Vector2(
  298. get_action_raw_strength(p_positive_x) - get_action_raw_strength(p_negative_x),
  299. get_action_raw_strength(p_positive_y) - get_action_raw_strength(p_negative_y));
  300. if (p_deadzone < 0.0f) {
  301. // If the deadzone isn't specified, get it from the average of the actions.
  302. p_deadzone = 0.25 *
  303. (InputMap::get_singleton()->action_get_deadzone(p_positive_x) +
  304. InputMap::get_singleton()->action_get_deadzone(p_negative_x) +
  305. InputMap::get_singleton()->action_get_deadzone(p_positive_y) +
  306. InputMap::get_singleton()->action_get_deadzone(p_negative_y));
  307. }
  308. // Circular length limiting and deadzone.
  309. float length = vector.length();
  310. if (length <= p_deadzone) {
  311. return Vector2();
  312. } else if (length > 1.0f) {
  313. return vector / length;
  314. } else {
  315. // Inverse lerp length to map (p_deadzone, 1) to (0, 1).
  316. return vector * (Math::inverse_lerp(p_deadzone, 1.0f, length) / length);
  317. }
  318. }
  319. float Input::get_joy_axis(int p_device, JoyAxis p_axis) const {
  320. _THREAD_SAFE_METHOD_
  321. JoyAxis c = _combine_device(p_axis, p_device);
  322. if (_joy_axis.has(c)) {
  323. return _joy_axis[c];
  324. } else {
  325. return 0;
  326. }
  327. }
  328. String Input::get_joy_name(int p_idx) {
  329. _THREAD_SAFE_METHOD_
  330. return joy_names[p_idx].name;
  331. }
  332. Vector2 Input::get_joy_vibration_strength(int p_device) {
  333. if (joy_vibration.has(p_device)) {
  334. return Vector2(joy_vibration[p_device].weak_magnitude, joy_vibration[p_device].strong_magnitude);
  335. } else {
  336. return Vector2(0, 0);
  337. }
  338. }
  339. uint64_t Input::get_joy_vibration_timestamp(int p_device) {
  340. if (joy_vibration.has(p_device)) {
  341. return joy_vibration[p_device].timestamp;
  342. } else {
  343. return 0;
  344. }
  345. }
  346. float Input::get_joy_vibration_duration(int p_device) {
  347. if (joy_vibration.has(p_device)) {
  348. return joy_vibration[p_device].duration;
  349. } else {
  350. return 0.f;
  351. }
  352. }
  353. static String _hex_str(uint8_t p_byte) {
  354. static const char *dict = "0123456789abcdef";
  355. char ret[3];
  356. ret[2] = 0;
  357. ret[0] = dict[p_byte >> 4];
  358. ret[1] = dict[p_byte & 0xf];
  359. return ret;
  360. }
  361. void Input::joy_connection_changed(int p_idx, bool p_connected, String p_name, String p_guid) {
  362. _THREAD_SAFE_METHOD_
  363. Joypad js;
  364. js.name = p_connected ? p_name : "";
  365. js.uid = p_connected ? p_guid : "";
  366. if (p_connected) {
  367. String uidname = p_guid;
  368. if (p_guid.is_empty()) {
  369. int uidlen = MIN(p_name.length(), 16);
  370. for (int i = 0; i < uidlen; i++) {
  371. uidname = uidname + _hex_str(p_name[i]);
  372. }
  373. }
  374. js.uid = uidname;
  375. js.connected = true;
  376. int mapping = fallback_mapping;
  377. for (int i = 0; i < map_db.size(); i++) {
  378. if (js.uid == map_db[i].uid) {
  379. mapping = i;
  380. js.name = map_db[i].name;
  381. }
  382. }
  383. js.mapping = mapping;
  384. } else {
  385. js.connected = false;
  386. for (int i = 0; i < (int)JoyButton::MAX; i++) {
  387. JoyButton c = _combine_device((JoyButton)i, p_idx);
  388. joy_buttons_pressed.erase(c);
  389. }
  390. for (int i = 0; i < (int)JoyAxis::MAX; i++) {
  391. set_joy_axis(p_idx, (JoyAxis)i, 0.0f);
  392. }
  393. }
  394. joy_names[p_idx] = js;
  395. emit_signal(SNAME("joy_connection_changed"), p_idx, p_connected);
  396. }
  397. Vector3 Input::get_gravity() const {
  398. _THREAD_SAFE_METHOD_
  399. return gravity;
  400. }
  401. Vector3 Input::get_accelerometer() const {
  402. _THREAD_SAFE_METHOD_
  403. return accelerometer;
  404. }
  405. Vector3 Input::get_magnetometer() const {
  406. _THREAD_SAFE_METHOD_
  407. return magnetometer;
  408. }
  409. Vector3 Input::get_gyroscope() const {
  410. _THREAD_SAFE_METHOD_
  411. return gyroscope;
  412. }
  413. void Input::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool p_is_emulated) {
  414. // Notes on mouse-touch emulation:
  415. // - Emulated mouse events are parsed, that is, re-routed to this method, so they make the same effects
  416. // as true mouse events. The only difference is the situation is flagged as emulated so they are not
  417. // emulated back to touch events in an endless loop.
  418. // - Emulated touch events are handed right to the main loop (i.e., the SceneTree) because they don't
  419. // require additional handling by this class.
  420. Ref<InputEventKey> k = p_event;
  421. if (k.is_valid() && !k->is_echo() && k->get_keycode() != Key::NONE) {
  422. if (k->is_pressed()) {
  423. keys_pressed.insert(k->get_keycode());
  424. } else {
  425. keys_pressed.erase(k->get_keycode());
  426. }
  427. }
  428. if (k.is_valid() && !k->is_echo() && k->get_physical_keycode() != Key::NONE) {
  429. if (k->is_pressed()) {
  430. physical_keys_pressed.insert(k->get_physical_keycode());
  431. } else {
  432. physical_keys_pressed.erase(k->get_physical_keycode());
  433. }
  434. }
  435. Ref<InputEventMouseButton> mb = p_event;
  436. if (mb.is_valid()) {
  437. if (mb->is_pressed()) {
  438. mouse_button_mask |= mouse_button_to_mask(mb->get_button_index());
  439. } else {
  440. mouse_button_mask &= ~mouse_button_to_mask(mb->get_button_index());
  441. }
  442. Point2 pos = mb->get_global_position();
  443. if (mouse_pos != pos) {
  444. set_mouse_position(pos);
  445. }
  446. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mb->get_button_index() == MouseButton::LEFT) {
  447. Ref<InputEventScreenTouch> touch_event;
  448. touch_event.instantiate();
  449. touch_event->set_pressed(mb->is_pressed());
  450. touch_event->set_position(mb->get_position());
  451. event_dispatch_function(touch_event);
  452. }
  453. }
  454. Ref<InputEventMouseMotion> mm = p_event;
  455. if (mm.is_valid()) {
  456. Point2 position = mm->get_global_position();
  457. if (mouse_pos != position) {
  458. set_mouse_position(position);
  459. }
  460. Vector2 relative = mm->get_relative();
  461. mouse_velocity_track.update(relative);
  462. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && (mm->get_button_mask() & MouseButton::LEFT) != MouseButton::NONE) {
  463. Ref<InputEventScreenDrag> drag_event;
  464. drag_event.instantiate();
  465. drag_event->set_position(position);
  466. drag_event->set_relative(relative);
  467. drag_event->set_velocity(get_last_mouse_velocity());
  468. event_dispatch_function(drag_event);
  469. }
  470. }
  471. Ref<InputEventScreenTouch> st = p_event;
  472. if (st.is_valid()) {
  473. if (st->is_pressed()) {
  474. VelocityTrack &track = touch_velocity_track[st->get_index()];
  475. track.reset();
  476. } else {
  477. // Since a pointer index may not occur again (OSs may or may not reuse them),
  478. // imperatively remove it from the map to keep no fossil entries in it
  479. touch_velocity_track.erase(st->get_index());
  480. }
  481. if (emulate_mouse_from_touch) {
  482. bool translate = false;
  483. if (st->is_pressed()) {
  484. if (mouse_from_touch_index == -1) {
  485. translate = true;
  486. mouse_from_touch_index = st->get_index();
  487. }
  488. } else {
  489. if (st->get_index() == mouse_from_touch_index) {
  490. translate = true;
  491. mouse_from_touch_index = -1;
  492. }
  493. }
  494. if (translate) {
  495. Ref<InputEventMouseButton> button_event;
  496. button_event.instantiate();
  497. button_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  498. button_event->set_position(st->get_position());
  499. button_event->set_global_position(st->get_position());
  500. button_event->set_pressed(st->is_pressed());
  501. button_event->set_button_index(MouseButton::LEFT);
  502. if (st->is_pressed()) {
  503. button_event->set_button_mask(MouseButton(mouse_button_mask | MouseButton::MASK_LEFT));
  504. } else {
  505. button_event->set_button_mask(MouseButton(mouse_button_mask & ~MouseButton::MASK_LEFT));
  506. }
  507. _parse_input_event_impl(button_event, true);
  508. }
  509. }
  510. }
  511. Ref<InputEventScreenDrag> sd = p_event;
  512. if (sd.is_valid()) {
  513. VelocityTrack &track = touch_velocity_track[sd->get_index()];
  514. track.update(sd->get_relative());
  515. sd->set_velocity(track.velocity);
  516. if (emulate_mouse_from_touch && sd->get_index() == mouse_from_touch_index) {
  517. Ref<InputEventMouseMotion> motion_event;
  518. motion_event.instantiate();
  519. motion_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  520. motion_event->set_position(sd->get_position());
  521. motion_event->set_global_position(sd->get_position());
  522. motion_event->set_relative(sd->get_relative());
  523. motion_event->set_velocity(sd->get_velocity());
  524. motion_event->set_button_mask(mouse_button_mask);
  525. _parse_input_event_impl(motion_event, true);
  526. }
  527. }
  528. Ref<InputEventJoypadButton> jb = p_event;
  529. if (jb.is_valid()) {
  530. JoyButton c = _combine_device(jb->get_button_index(), jb->get_device());
  531. if (jb->is_pressed()) {
  532. joy_buttons_pressed.insert(c);
  533. } else {
  534. joy_buttons_pressed.erase(c);
  535. }
  536. }
  537. Ref<InputEventJoypadMotion> jm = p_event;
  538. if (jm.is_valid()) {
  539. set_joy_axis(jm->get_device(), jm->get_axis(), jm->get_axis_value());
  540. }
  541. Ref<InputEventGesture> ge = p_event;
  542. if (ge.is_valid()) {
  543. if (event_dispatch_function) {
  544. event_dispatch_function(ge);
  545. }
  546. }
  547. for (const KeyValue<StringName, InputMap::Action> &E : InputMap::get_singleton()->get_action_map()) {
  548. if (InputMap::get_singleton()->event_is_action(p_event, E.key)) {
  549. // If not echo and action pressed state has changed
  550. if (!p_event->is_echo() && is_action_pressed(E.key, false) != p_event->is_action_pressed(E.key)) {
  551. Action action;
  552. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  553. action.process_frame = Engine::get_singleton()->get_process_frames();
  554. action.pressed = p_event->is_action_pressed(E.key);
  555. action.strength = 0.0f;
  556. action.raw_strength = 0.0f;
  557. action.exact = InputMap::get_singleton()->event_is_action(p_event, E.key, true);
  558. action_state[E.key] = action;
  559. }
  560. action_state[E.key].strength = p_event->get_action_strength(E.key);
  561. action_state[E.key].raw_strength = p_event->get_action_raw_strength(E.key);
  562. }
  563. }
  564. if (event_dispatch_function) {
  565. event_dispatch_function(p_event);
  566. }
  567. }
  568. void Input::set_joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  569. _THREAD_SAFE_METHOD_
  570. JoyAxis c = _combine_device(p_axis, p_device);
  571. _joy_axis[c] = p_value;
  572. }
  573. void Input::start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration) {
  574. _THREAD_SAFE_METHOD_
  575. if (p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  576. return;
  577. }
  578. VibrationInfo vibration;
  579. vibration.weak_magnitude = p_weak_magnitude;
  580. vibration.strong_magnitude = p_strong_magnitude;
  581. vibration.duration = p_duration;
  582. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  583. joy_vibration[p_device] = vibration;
  584. }
  585. void Input::stop_joy_vibration(int p_device) {
  586. _THREAD_SAFE_METHOD_
  587. VibrationInfo vibration;
  588. vibration.weak_magnitude = 0;
  589. vibration.strong_magnitude = 0;
  590. vibration.duration = 0;
  591. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  592. joy_vibration[p_device] = vibration;
  593. }
  594. void Input::vibrate_handheld(int p_duration_ms) {
  595. OS::get_singleton()->vibrate_handheld(p_duration_ms);
  596. }
  597. void Input::set_gravity(const Vector3 &p_gravity) {
  598. _THREAD_SAFE_METHOD_
  599. gravity = p_gravity;
  600. }
  601. void Input::set_accelerometer(const Vector3 &p_accel) {
  602. _THREAD_SAFE_METHOD_
  603. accelerometer = p_accel;
  604. }
  605. void Input::set_magnetometer(const Vector3 &p_magnetometer) {
  606. _THREAD_SAFE_METHOD_
  607. magnetometer = p_magnetometer;
  608. }
  609. void Input::set_gyroscope(const Vector3 &p_gyroscope) {
  610. _THREAD_SAFE_METHOD_
  611. gyroscope = p_gyroscope;
  612. }
  613. void Input::set_mouse_position(const Point2 &p_posf) {
  614. mouse_pos = p_posf;
  615. }
  616. Point2 Input::get_mouse_position() const {
  617. return mouse_pos;
  618. }
  619. Point2 Input::get_last_mouse_velocity() {
  620. mouse_velocity_track.update(Vector2());
  621. return mouse_velocity_track.velocity;
  622. }
  623. MouseButton Input::get_mouse_button_mask() const {
  624. return mouse_button_mask; // do not trust OS implementation, should remove it - OS::get_singleton()->get_mouse_button_state();
  625. }
  626. void Input::warp_mouse(const Vector2 &p_position) {
  627. warp_mouse_func(p_position);
  628. }
  629. Point2i Input::warp_mouse_motion(const Ref<InputEventMouseMotion> &p_motion, const Rect2 &p_rect) {
  630. // The relative distance reported for the next event after a warp is in the boundaries of the
  631. // size of the rect on that axis, but it may be greater, in which case there's no problem as fmod()
  632. // will warp it, but if the pointer has moved in the opposite direction between the pointer relocation
  633. // and the subsequent event, the reported relative distance will be less than the size of the rect
  634. // and thus fmod() will be disabled for handling the situation.
  635. // And due to this mouse warping mechanism being stateless, we need to apply some heuristics to
  636. // detect the warp: if the relative distance is greater than the half of the size of the relevant rect
  637. // (checked per each axis), it will be considered as the consequence of a former pointer warp.
  638. const Point2i rel_sign(p_motion->get_relative().x >= 0.0f ? 1 : -1, p_motion->get_relative().y >= 0.0 ? 1 : -1);
  639. const Size2i warp_margin = p_rect.size * 0.5f;
  640. const Point2i rel_warped(
  641. Math::fmod(p_motion->get_relative().x + rel_sign.x * warp_margin.x, p_rect.size.x) - rel_sign.x * warp_margin.x,
  642. Math::fmod(p_motion->get_relative().y + rel_sign.y * warp_margin.y, p_rect.size.y) - rel_sign.y * warp_margin.y);
  643. const Point2i pos_local = p_motion->get_global_position() - p_rect.position;
  644. const Point2i pos_warped(Math::fposmod(pos_local.x, p_rect.size.x), Math::fposmod(pos_local.y, p_rect.size.y));
  645. if (pos_warped != pos_local) {
  646. warp_mouse(pos_warped + p_rect.position);
  647. }
  648. return rel_warped;
  649. }
  650. void Input::action_press(const StringName &p_action, float p_strength) {
  651. Action action;
  652. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  653. action.process_frame = Engine::get_singleton()->get_process_frames();
  654. action.pressed = true;
  655. action.strength = p_strength;
  656. action.raw_strength = p_strength;
  657. action.exact = true;
  658. action_state[p_action] = action;
  659. }
  660. void Input::action_release(const StringName &p_action) {
  661. Action action;
  662. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  663. action.process_frame = Engine::get_singleton()->get_process_frames();
  664. action.pressed = false;
  665. action.strength = 0.f;
  666. action.raw_strength = 0.f;
  667. action.exact = true;
  668. action_state[p_action] = action;
  669. }
  670. void Input::set_emulate_touch_from_mouse(bool p_emulate) {
  671. emulate_touch_from_mouse = p_emulate;
  672. }
  673. bool Input::is_emulating_touch_from_mouse() const {
  674. return emulate_touch_from_mouse;
  675. }
  676. // Calling this whenever the game window is focused helps unsticking the "touch mouse"
  677. // if the OS or its abstraction class hasn't properly reported that touch pointers raised
  678. void Input::ensure_touch_mouse_raised() {
  679. if (mouse_from_touch_index != -1) {
  680. mouse_from_touch_index = -1;
  681. Ref<InputEventMouseButton> button_event;
  682. button_event.instantiate();
  683. button_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  684. button_event->set_position(mouse_pos);
  685. button_event->set_global_position(mouse_pos);
  686. button_event->set_pressed(false);
  687. button_event->set_button_index(MouseButton::LEFT);
  688. button_event->set_button_mask(MouseButton(mouse_button_mask & ~MouseButton::MASK_LEFT));
  689. _parse_input_event_impl(button_event, true);
  690. }
  691. }
  692. void Input::set_emulate_mouse_from_touch(bool p_emulate) {
  693. emulate_mouse_from_touch = p_emulate;
  694. }
  695. bool Input::is_emulating_mouse_from_touch() const {
  696. return emulate_mouse_from_touch;
  697. }
  698. Input::CursorShape Input::get_default_cursor_shape() const {
  699. return default_shape;
  700. }
  701. void Input::set_default_cursor_shape(CursorShape p_shape) {
  702. if (default_shape == p_shape) {
  703. return;
  704. }
  705. default_shape = p_shape;
  706. // The default shape is set in Viewport::_gui_input_event. To instantly
  707. // see the shape in the viewport we need to trigger a mouse motion event.
  708. Ref<InputEventMouseMotion> mm;
  709. mm.instantiate();
  710. mm->set_position(mouse_pos);
  711. mm->set_global_position(mouse_pos);
  712. parse_input_event(mm);
  713. }
  714. Input::CursorShape Input::get_current_cursor_shape() const {
  715. return get_current_cursor_shape_func();
  716. }
  717. void Input::set_custom_mouse_cursor(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  718. if (Engine::get_singleton()->is_editor_hint()) {
  719. return;
  720. }
  721. ERR_FAIL_INDEX(p_shape, CursorShape::CURSOR_MAX);
  722. set_custom_mouse_cursor_func(p_cursor, p_shape, p_hotspot);
  723. }
  724. void Input::parse_input_event(const Ref<InputEvent> &p_event) {
  725. _THREAD_SAFE_METHOD_
  726. ERR_FAIL_COND(p_event.is_null());
  727. if (use_accumulated_input) {
  728. if (buffered_events.is_empty() || !buffered_events.back()->get()->accumulate(p_event)) {
  729. buffered_events.push_back(p_event);
  730. }
  731. } else if (use_input_buffering) {
  732. buffered_events.push_back(p_event);
  733. } else {
  734. _parse_input_event_impl(p_event, false);
  735. }
  736. }
  737. void Input::flush_buffered_events() {
  738. _THREAD_SAFE_METHOD_
  739. while (buffered_events.front()) {
  740. _parse_input_event_impl(buffered_events.front()->get(), false);
  741. buffered_events.pop_front();
  742. }
  743. }
  744. bool Input::is_using_input_buffering() {
  745. return use_input_buffering;
  746. }
  747. void Input::set_use_input_buffering(bool p_enable) {
  748. use_input_buffering = p_enable;
  749. }
  750. void Input::set_use_accumulated_input(bool p_enable) {
  751. use_accumulated_input = p_enable;
  752. }
  753. bool Input::is_using_accumulated_input() {
  754. return use_accumulated_input;
  755. }
  756. void Input::release_pressed_events() {
  757. flush_buffered_events(); // this is needed to release actions strengths
  758. keys_pressed.clear();
  759. physical_keys_pressed.clear();
  760. joy_buttons_pressed.clear();
  761. _joy_axis.clear();
  762. for (const KeyValue<StringName, Input::Action> &E : action_state) {
  763. if (E.value.pressed) {
  764. action_release(E.key);
  765. }
  766. }
  767. }
  768. void Input::set_event_dispatch_function(EventDispatchFunc p_function) {
  769. event_dispatch_function = p_function;
  770. }
  771. void Input::joy_button(int p_device, JoyButton p_button, bool p_pressed) {
  772. _THREAD_SAFE_METHOD_;
  773. Joypad &joy = joy_names[p_device];
  774. ERR_FAIL_INDEX((int)p_button, (int)JoyButton::MAX);
  775. if (joy.last_buttons[(size_t)p_button] == p_pressed) {
  776. return;
  777. }
  778. joy.last_buttons[(size_t)p_button] = p_pressed;
  779. if (joy.mapping == -1) {
  780. _button_event(p_device, p_button, p_pressed);
  781. return;
  782. }
  783. JoyEvent map = _get_mapped_button_event(map_db[joy.mapping], p_button);
  784. if (map.type == TYPE_BUTTON) {
  785. _button_event(p_device, (JoyButton)map.index, p_pressed);
  786. return;
  787. }
  788. if (map.type == TYPE_AXIS) {
  789. _axis_event(p_device, (JoyAxis)map.index, p_pressed ? map.value : 0.0);
  790. }
  791. // no event?
  792. }
  793. void Input::joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  794. _THREAD_SAFE_METHOD_;
  795. ERR_FAIL_INDEX((int)p_axis, (int)JoyAxis::MAX);
  796. Joypad &joy = joy_names[p_device];
  797. if (joy.last_axis[(size_t)p_axis] == p_value) {
  798. return;
  799. }
  800. joy.last_axis[(size_t)p_axis] = p_value;
  801. if (joy.mapping == -1) {
  802. _axis_event(p_device, p_axis, p_value);
  803. return;
  804. }
  805. JoyEvent map = _get_mapped_axis_event(map_db[joy.mapping], p_axis, p_value);
  806. if (map.type == TYPE_BUTTON) {
  807. bool pressed = map.value > 0.5;
  808. if (pressed != joy_buttons_pressed.has(_combine_device((JoyButton)map.index, p_device))) {
  809. _button_event(p_device, (JoyButton)map.index, pressed);
  810. }
  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[(size_t)HatDir::MAX]) {
  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. TypedArray<int> Input::get_connected_joypads() {
  1199. TypedArray<int> ret;
  1200. HashMap<int, Joypad>::Iterator elem = joy_names.begin();
  1201. while (elem) {
  1202. if (elem->value.connected) {
  1203. ret.push_back(elem->key);
  1204. }
  1205. ++elem;
  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. //////////////////////////////////////////////////////////