input.cpp 43 KB

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