input.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  1. /**************************************************************************/
  2. /* input.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "input.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/input/default_controller_mappings.h"
  33. #include "core/input/input_map.h"
  34. #include "core/os/os.h"
  35. 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. touch_event->set_double_tap(mb->is_double_click());
  452. event_dispatch_function(touch_event);
  453. }
  454. }
  455. Ref<InputEventMouseMotion> mm = p_event;
  456. if (mm.is_valid()) {
  457. Point2 position = mm->get_global_position();
  458. if (mouse_pos != position) {
  459. set_mouse_position(position);
  460. }
  461. Vector2 relative = mm->get_relative();
  462. mouse_velocity_track.update(relative);
  463. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && (mm->get_button_mask() & MouseButton::LEFT) != MouseButton::NONE) {
  464. Ref<InputEventScreenDrag> drag_event;
  465. drag_event.instantiate();
  466. drag_event->set_position(position);
  467. drag_event->set_relative(relative);
  468. drag_event->set_tilt(mm->get_tilt());
  469. drag_event->set_pen_inverted(mm->get_pen_inverted());
  470. drag_event->set_pressure(mm->get_pressure());
  471. drag_event->set_velocity(get_last_mouse_velocity());
  472. event_dispatch_function(drag_event);
  473. }
  474. }
  475. Ref<InputEventScreenTouch> st = p_event;
  476. if (st.is_valid()) {
  477. if (st->is_pressed()) {
  478. VelocityTrack &track = touch_velocity_track[st->get_index()];
  479. track.reset();
  480. } else {
  481. // Since a pointer index may not occur again (OSs may or may not reuse them),
  482. // imperatively remove it from the map to keep no fossil entries in it
  483. touch_velocity_track.erase(st->get_index());
  484. }
  485. if (emulate_mouse_from_touch) {
  486. bool translate = false;
  487. if (st->is_pressed()) {
  488. if (mouse_from_touch_index == -1) {
  489. translate = true;
  490. mouse_from_touch_index = st->get_index();
  491. }
  492. } else {
  493. if (st->get_index() == mouse_from_touch_index) {
  494. translate = true;
  495. mouse_from_touch_index = -1;
  496. }
  497. }
  498. if (translate) {
  499. Ref<InputEventMouseButton> button_event;
  500. button_event.instantiate();
  501. button_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  502. button_event->set_position(st->get_position());
  503. button_event->set_global_position(st->get_position());
  504. button_event->set_pressed(st->is_pressed());
  505. button_event->set_button_index(MouseButton::LEFT);
  506. button_event->set_double_click(st->is_double_tap());
  507. if (st->is_pressed()) {
  508. button_event->set_button_mask(MouseButton(mouse_button_mask | MouseButton::MASK_LEFT));
  509. } else {
  510. button_event->set_button_mask(MouseButton(mouse_button_mask & ~MouseButton::MASK_LEFT));
  511. }
  512. _parse_input_event_impl(button_event, true);
  513. }
  514. }
  515. }
  516. Ref<InputEventScreenDrag> sd = p_event;
  517. if (sd.is_valid()) {
  518. VelocityTrack &track = touch_velocity_track[sd->get_index()];
  519. track.update(sd->get_relative());
  520. sd->set_velocity(track.velocity);
  521. if (emulate_mouse_from_touch && sd->get_index() == mouse_from_touch_index) {
  522. Ref<InputEventMouseMotion> motion_event;
  523. motion_event.instantiate();
  524. motion_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  525. motion_event->set_tilt(sd->get_tilt());
  526. motion_event->set_pen_inverted(sd->get_pen_inverted());
  527. motion_event->set_pressure(sd->get_pressure());
  528. motion_event->set_position(sd->get_position());
  529. motion_event->set_global_position(sd->get_position());
  530. motion_event->set_relative(sd->get_relative());
  531. motion_event->set_velocity(sd->get_velocity());
  532. motion_event->set_button_mask(mouse_button_mask);
  533. _parse_input_event_impl(motion_event, true);
  534. }
  535. }
  536. Ref<InputEventJoypadButton> jb = p_event;
  537. if (jb.is_valid()) {
  538. JoyButton c = _combine_device(jb->get_button_index(), jb->get_device());
  539. if (jb->is_pressed()) {
  540. joy_buttons_pressed.insert(c);
  541. } else {
  542. joy_buttons_pressed.erase(c);
  543. }
  544. }
  545. Ref<InputEventJoypadMotion> jm = p_event;
  546. if (jm.is_valid()) {
  547. set_joy_axis(jm->get_device(), jm->get_axis(), jm->get_axis_value());
  548. }
  549. Ref<InputEventGesture> ge = p_event;
  550. if (ge.is_valid()) {
  551. if (event_dispatch_function) {
  552. event_dispatch_function(ge);
  553. }
  554. }
  555. for (const KeyValue<StringName, InputMap::Action> &E : InputMap::get_singleton()->get_action_map()) {
  556. if (InputMap::get_singleton()->event_is_action(p_event, E.key)) {
  557. // If not echo and action pressed state has changed
  558. if (!p_event->is_echo() && is_action_pressed(E.key, false) != p_event->is_action_pressed(E.key)) {
  559. Action action;
  560. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  561. action.process_frame = Engine::get_singleton()->get_process_frames();
  562. action.pressed = p_event->is_action_pressed(E.key);
  563. action.strength = 0.0f;
  564. action.raw_strength = 0.0f;
  565. action.exact = InputMap::get_singleton()->event_is_action(p_event, E.key, true);
  566. action_state[E.key] = action;
  567. }
  568. action_state[E.key].strength = p_event->get_action_strength(E.key);
  569. action_state[E.key].raw_strength = p_event->get_action_raw_strength(E.key);
  570. }
  571. }
  572. if (event_dispatch_function) {
  573. event_dispatch_function(p_event);
  574. }
  575. }
  576. void Input::set_joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  577. _THREAD_SAFE_METHOD_
  578. JoyAxis c = _combine_device(p_axis, p_device);
  579. _joy_axis[c] = p_value;
  580. }
  581. void Input::start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration) {
  582. _THREAD_SAFE_METHOD_
  583. if (p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  584. return;
  585. }
  586. VibrationInfo vibration;
  587. vibration.weak_magnitude = p_weak_magnitude;
  588. vibration.strong_magnitude = p_strong_magnitude;
  589. vibration.duration = p_duration;
  590. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  591. joy_vibration[p_device] = vibration;
  592. }
  593. void Input::stop_joy_vibration(int p_device) {
  594. _THREAD_SAFE_METHOD_
  595. VibrationInfo vibration;
  596. vibration.weak_magnitude = 0;
  597. vibration.strong_magnitude = 0;
  598. vibration.duration = 0;
  599. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  600. joy_vibration[p_device] = vibration;
  601. }
  602. void Input::vibrate_handheld(int p_duration_ms) {
  603. OS::get_singleton()->vibrate_handheld(p_duration_ms);
  604. }
  605. void Input::set_gravity(const Vector3 &p_gravity) {
  606. _THREAD_SAFE_METHOD_
  607. gravity = p_gravity;
  608. }
  609. void Input::set_accelerometer(const Vector3 &p_accel) {
  610. _THREAD_SAFE_METHOD_
  611. accelerometer = p_accel;
  612. }
  613. void Input::set_magnetometer(const Vector3 &p_magnetometer) {
  614. _THREAD_SAFE_METHOD_
  615. magnetometer = p_magnetometer;
  616. }
  617. void Input::set_gyroscope(const Vector3 &p_gyroscope) {
  618. _THREAD_SAFE_METHOD_
  619. gyroscope = p_gyroscope;
  620. }
  621. void Input::set_mouse_position(const Point2 &p_posf) {
  622. mouse_pos = p_posf;
  623. }
  624. Point2 Input::get_mouse_position() const {
  625. return mouse_pos;
  626. }
  627. Point2 Input::get_last_mouse_velocity() {
  628. mouse_velocity_track.update(Vector2());
  629. return mouse_velocity_track.velocity;
  630. }
  631. MouseButton Input::get_mouse_button_mask() const {
  632. return mouse_button_mask; // do not trust OS implementation, should remove it - OS::get_singleton()->get_mouse_button_state();
  633. }
  634. void Input::warp_mouse(const Vector2 &p_position) {
  635. warp_mouse_func(p_position);
  636. }
  637. Point2i Input::warp_mouse_motion(const Ref<InputEventMouseMotion> &p_motion, const Rect2 &p_rect) {
  638. // The relative distance reported for the next event after a warp is in the boundaries of the
  639. // size of the rect on that axis, but it may be greater, in which case there's no problem as fmod()
  640. // will warp it, but if the pointer has moved in the opposite direction between the pointer relocation
  641. // and the subsequent event, the reported relative distance will be less than the size of the rect
  642. // and thus fmod() will be disabled for handling the situation.
  643. // And due to this mouse warping mechanism being stateless, we need to apply some heuristics to
  644. // detect the warp: if the relative distance is greater than the half of the size of the relevant rect
  645. // (checked per each axis), it will be considered as the consequence of a former pointer warp.
  646. const Point2i rel_sign(p_motion->get_relative().x >= 0.0f ? 1 : -1, p_motion->get_relative().y >= 0.0 ? 1 : -1);
  647. const Size2i warp_margin = p_rect.size * 0.5f;
  648. const Point2i rel_warped(
  649. Math::fmod(p_motion->get_relative().x + rel_sign.x * warp_margin.x, p_rect.size.x) - rel_sign.x * warp_margin.x,
  650. Math::fmod(p_motion->get_relative().y + rel_sign.y * warp_margin.y, p_rect.size.y) - rel_sign.y * warp_margin.y);
  651. const Point2i pos_local = p_motion->get_global_position() - p_rect.position;
  652. const Point2i pos_warped(Math::fposmod(pos_local.x, p_rect.size.x), Math::fposmod(pos_local.y, p_rect.size.y));
  653. if (pos_warped != pos_local) {
  654. warp_mouse(pos_warped + p_rect.position);
  655. }
  656. return rel_warped;
  657. }
  658. void Input::action_press(const StringName &p_action, float p_strength) {
  659. Action action;
  660. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  661. action.process_frame = Engine::get_singleton()->get_process_frames();
  662. action.pressed = true;
  663. action.strength = p_strength;
  664. action.raw_strength = p_strength;
  665. action.exact = true;
  666. action_state[p_action] = action;
  667. }
  668. void Input::action_release(const StringName &p_action) {
  669. Action action;
  670. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  671. action.process_frame = Engine::get_singleton()->get_process_frames();
  672. action.pressed = false;
  673. action.strength = 0.f;
  674. action.raw_strength = 0.f;
  675. action.exact = true;
  676. action_state[p_action] = action;
  677. }
  678. void Input::set_emulate_touch_from_mouse(bool p_emulate) {
  679. emulate_touch_from_mouse = p_emulate;
  680. }
  681. bool Input::is_emulating_touch_from_mouse() const {
  682. return emulate_touch_from_mouse;
  683. }
  684. // Calling this whenever the game window is focused helps unsticking the "touch mouse"
  685. // if the OS or its abstraction class hasn't properly reported that touch pointers raised
  686. void Input::ensure_touch_mouse_raised() {
  687. if (mouse_from_touch_index != -1) {
  688. mouse_from_touch_index = -1;
  689. Ref<InputEventMouseButton> button_event;
  690. button_event.instantiate();
  691. button_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  692. button_event->set_position(mouse_pos);
  693. button_event->set_global_position(mouse_pos);
  694. button_event->set_pressed(false);
  695. button_event->set_button_index(MouseButton::LEFT);
  696. button_event->set_button_mask(MouseButton(mouse_button_mask & ~MouseButton::MASK_LEFT));
  697. _parse_input_event_impl(button_event, true);
  698. }
  699. }
  700. void Input::set_emulate_mouse_from_touch(bool p_emulate) {
  701. emulate_mouse_from_touch = p_emulate;
  702. }
  703. bool Input::is_emulating_mouse_from_touch() const {
  704. return emulate_mouse_from_touch;
  705. }
  706. Input::CursorShape Input::get_default_cursor_shape() const {
  707. return default_shape;
  708. }
  709. void Input::set_default_cursor_shape(CursorShape p_shape) {
  710. if (default_shape == p_shape) {
  711. return;
  712. }
  713. default_shape = p_shape;
  714. // The default shape is set in Viewport::_gui_input_event. To instantly
  715. // see the shape in the viewport we need to trigger a mouse motion event.
  716. Ref<InputEventMouseMotion> mm;
  717. mm.instantiate();
  718. mm->set_position(mouse_pos);
  719. mm->set_global_position(mouse_pos);
  720. parse_input_event(mm);
  721. }
  722. Input::CursorShape Input::get_current_cursor_shape() const {
  723. return get_current_cursor_shape_func();
  724. }
  725. void Input::set_custom_mouse_cursor(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  726. if (Engine::get_singleton()->is_editor_hint()) {
  727. return;
  728. }
  729. ERR_FAIL_INDEX(p_shape, CursorShape::CURSOR_MAX);
  730. set_custom_mouse_cursor_func(p_cursor, p_shape, p_hotspot);
  731. }
  732. void Input::parse_input_event(const Ref<InputEvent> &p_event) {
  733. _THREAD_SAFE_METHOD_
  734. ERR_FAIL_COND(p_event.is_null());
  735. if (use_accumulated_input) {
  736. if (buffered_events.is_empty() || !buffered_events.back()->get()->accumulate(p_event)) {
  737. buffered_events.push_back(p_event);
  738. }
  739. } else if (use_input_buffering) {
  740. buffered_events.push_back(p_event);
  741. } else {
  742. _parse_input_event_impl(p_event, false);
  743. }
  744. }
  745. void Input::flush_buffered_events() {
  746. _THREAD_SAFE_METHOD_
  747. while (buffered_events.front()) {
  748. _parse_input_event_impl(buffered_events.front()->get(), false);
  749. buffered_events.pop_front();
  750. }
  751. }
  752. bool Input::is_using_input_buffering() {
  753. return use_input_buffering;
  754. }
  755. void Input::set_use_input_buffering(bool p_enable) {
  756. use_input_buffering = p_enable;
  757. }
  758. void Input::set_use_accumulated_input(bool p_enable) {
  759. use_accumulated_input = p_enable;
  760. }
  761. bool Input::is_using_accumulated_input() {
  762. return use_accumulated_input;
  763. }
  764. void Input::release_pressed_events() {
  765. flush_buffered_events(); // this is needed to release actions strengths
  766. keys_pressed.clear();
  767. physical_keys_pressed.clear();
  768. joy_buttons_pressed.clear();
  769. _joy_axis.clear();
  770. for (const KeyValue<StringName, Input::Action> &E : action_state) {
  771. if (E.value.pressed) {
  772. action_release(E.key);
  773. }
  774. }
  775. }
  776. void Input::set_event_dispatch_function(EventDispatchFunc p_function) {
  777. event_dispatch_function = p_function;
  778. }
  779. void Input::joy_button(int p_device, JoyButton p_button, bool p_pressed) {
  780. _THREAD_SAFE_METHOD_;
  781. Joypad &joy = joy_names[p_device];
  782. ERR_FAIL_INDEX((int)p_button, (int)JoyButton::MAX);
  783. if (joy.last_buttons[(size_t)p_button] == p_pressed) {
  784. return;
  785. }
  786. joy.last_buttons[(size_t)p_button] = p_pressed;
  787. if (joy.mapping == -1) {
  788. _button_event(p_device, p_button, p_pressed);
  789. return;
  790. }
  791. JoyEvent map = _get_mapped_button_event(map_db[joy.mapping], p_button);
  792. if (map.type == TYPE_BUTTON) {
  793. _button_event(p_device, (JoyButton)map.index, p_pressed);
  794. return;
  795. }
  796. if (map.type == TYPE_AXIS) {
  797. _axis_event(p_device, (JoyAxis)map.index, p_pressed ? map.value : 0.0);
  798. }
  799. // no event?
  800. }
  801. void Input::joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  802. _THREAD_SAFE_METHOD_;
  803. ERR_FAIL_INDEX((int)p_axis, (int)JoyAxis::MAX);
  804. Joypad &joy = joy_names[p_device];
  805. if (joy.last_axis[(size_t)p_axis] == p_value) {
  806. return;
  807. }
  808. joy.last_axis[(size_t)p_axis] = p_value;
  809. if (joy.mapping == -1) {
  810. _axis_event(p_device, p_axis, p_value);
  811. return;
  812. }
  813. JoyEvent map = _get_mapped_axis_event(map_db[joy.mapping], p_axis, p_value);
  814. if (map.type == TYPE_BUTTON) {
  815. bool pressed = map.value > 0.5;
  816. if (pressed != joy_buttons_pressed.has(_combine_device((JoyButton)map.index, p_device))) {
  817. _button_event(p_device, (JoyButton)map.index, pressed);
  818. }
  819. // Ensure opposite D-Pad button is also released.
  820. switch ((JoyButton)map.index) {
  821. case JoyButton::DPAD_UP:
  822. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_DOWN, p_device))) {
  823. _button_event(p_device, JoyButton::DPAD_DOWN, false);
  824. }
  825. break;
  826. case JoyButton::DPAD_DOWN:
  827. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_UP, p_device))) {
  828. _button_event(p_device, JoyButton::DPAD_UP, false);
  829. }
  830. break;
  831. case JoyButton::DPAD_LEFT:
  832. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_RIGHT, p_device))) {
  833. _button_event(p_device, JoyButton::DPAD_RIGHT, false);
  834. }
  835. break;
  836. case JoyButton::DPAD_RIGHT:
  837. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_LEFT, p_device))) {
  838. _button_event(p_device, JoyButton::DPAD_LEFT, false);
  839. }
  840. break;
  841. default:
  842. // Nothing to do.
  843. break;
  844. }
  845. return;
  846. }
  847. if (map.type == TYPE_AXIS) {
  848. JoyAxis axis = JoyAxis(map.index);
  849. float value = map.value;
  850. if (axis == JoyAxis::TRIGGER_LEFT || axis == JoyAxis::TRIGGER_RIGHT) {
  851. // Convert to a value between 0.0f and 1.0f.
  852. value = 0.5f + value / 2.0f;
  853. }
  854. _axis_event(p_device, axis, value);
  855. return;
  856. }
  857. }
  858. void Input::joy_hat(int p_device, HatMask p_val) {
  859. _THREAD_SAFE_METHOD_;
  860. const Joypad &joy = joy_names[p_device];
  861. JoyEvent map[(size_t)HatDir::MAX];
  862. map[(size_t)HatDir::UP].type = TYPE_BUTTON;
  863. map[(size_t)HatDir::UP].index = (int)JoyButton::DPAD_UP;
  864. map[(size_t)HatDir::UP].value = 0;
  865. map[(size_t)HatDir::RIGHT].type = TYPE_BUTTON;
  866. map[(size_t)HatDir::RIGHT].index = (int)JoyButton::DPAD_RIGHT;
  867. map[(size_t)HatDir::RIGHT].value = 0;
  868. map[(size_t)HatDir::DOWN].type = TYPE_BUTTON;
  869. map[(size_t)HatDir::DOWN].index = (int)JoyButton::DPAD_DOWN;
  870. map[(size_t)HatDir::DOWN].value = 0;
  871. map[(size_t)HatDir::LEFT].type = TYPE_BUTTON;
  872. map[(size_t)HatDir::LEFT].index = (int)JoyButton::DPAD_LEFT;
  873. map[(size_t)HatDir::LEFT].value = 0;
  874. if (joy.mapping != -1) {
  875. _get_mapped_hat_events(map_db[joy.mapping], (HatDir)0, map);
  876. }
  877. int cur_val = joy_names[p_device].hat_current;
  878. for (int hat_direction = 0, hat_mask = 1; hat_direction < (int)HatDir::MAX; hat_direction++, hat_mask <<= 1) {
  879. if (((int)p_val & hat_mask) != (cur_val & hat_mask)) {
  880. if (map[hat_direction].type == TYPE_BUTTON) {
  881. _button_event(p_device, (JoyButton)map[hat_direction].index, (int)p_val & hat_mask);
  882. }
  883. if (map[hat_direction].type == TYPE_AXIS) {
  884. _axis_event(p_device, (JoyAxis)map[hat_direction].index, ((int)p_val & hat_mask) ? map[hat_direction].value : 0.0);
  885. }
  886. }
  887. }
  888. joy_names[p_device].hat_current = (int)p_val;
  889. }
  890. void Input::_button_event(int p_device, JoyButton p_index, bool p_pressed) {
  891. Ref<InputEventJoypadButton> ievent;
  892. ievent.instantiate();
  893. ievent->set_device(p_device);
  894. ievent->set_button_index(p_index);
  895. ievent->set_pressed(p_pressed);
  896. parse_input_event(ievent);
  897. }
  898. void Input::_axis_event(int p_device, JoyAxis p_axis, float p_value) {
  899. Ref<InputEventJoypadMotion> ievent;
  900. ievent.instantiate();
  901. ievent->set_device(p_device);
  902. ievent->set_axis(p_axis);
  903. ievent->set_axis_value(p_value);
  904. parse_input_event(ievent);
  905. }
  906. Input::JoyEvent Input::_get_mapped_button_event(const JoyDeviceMapping &mapping, JoyButton p_button) {
  907. JoyEvent event;
  908. for (int i = 0; i < mapping.bindings.size(); i++) {
  909. const JoyBinding binding = mapping.bindings[i];
  910. if (binding.inputType == TYPE_BUTTON && binding.input.button == p_button) {
  911. event.type = binding.outputType;
  912. switch (binding.outputType) {
  913. case TYPE_BUTTON:
  914. event.index = (int)binding.output.button;
  915. return event;
  916. case TYPE_AXIS:
  917. event.index = (int)binding.output.axis.axis;
  918. switch (binding.output.axis.range) {
  919. case POSITIVE_HALF_AXIS:
  920. event.value = 1;
  921. break;
  922. case NEGATIVE_HALF_AXIS:
  923. event.value = -1;
  924. break;
  925. case FULL_AXIS:
  926. // It doesn't make sense for a button to map to a full axis,
  927. // but keeping as a default for a trigger with a positive half-axis.
  928. event.value = 1;
  929. break;
  930. }
  931. return event;
  932. default:
  933. ERR_PRINT_ONCE("Joypad button mapping error.");
  934. }
  935. }
  936. }
  937. return event;
  938. }
  939. Input::JoyEvent Input::_get_mapped_axis_event(const JoyDeviceMapping &mapping, JoyAxis p_axis, float p_value) {
  940. JoyEvent event;
  941. for (int i = 0; i < mapping.bindings.size(); i++) {
  942. const JoyBinding binding = mapping.bindings[i];
  943. if (binding.inputType == TYPE_AXIS && binding.input.axis.axis == p_axis) {
  944. float value = p_value;
  945. if (binding.input.axis.invert) {
  946. value = -value;
  947. }
  948. if (binding.input.axis.range == FULL_AXIS ||
  949. (binding.input.axis.range == POSITIVE_HALF_AXIS && value >= 0) ||
  950. (binding.input.axis.range == NEGATIVE_HALF_AXIS && value < 0)) {
  951. event.type = binding.outputType;
  952. float shifted_positive_value = 0;
  953. switch (binding.input.axis.range) {
  954. case POSITIVE_HALF_AXIS:
  955. shifted_positive_value = value;
  956. break;
  957. case NEGATIVE_HALF_AXIS:
  958. shifted_positive_value = value + 1;
  959. break;
  960. case FULL_AXIS:
  961. shifted_positive_value = (value + 1) / 2;
  962. break;
  963. }
  964. switch (binding.outputType) {
  965. case TYPE_BUTTON:
  966. event.index = (int)binding.output.button;
  967. switch (binding.input.axis.range) {
  968. case POSITIVE_HALF_AXIS:
  969. event.value = shifted_positive_value;
  970. break;
  971. case NEGATIVE_HALF_AXIS:
  972. event.value = 1 - shifted_positive_value;
  973. break;
  974. case FULL_AXIS:
  975. // It doesn't make sense for a full axis to map to a button,
  976. // but keeping as a default for a trigger with a positive half-axis.
  977. event.value = (shifted_positive_value * 2) - 1;
  978. break;
  979. }
  980. return event;
  981. case TYPE_AXIS:
  982. event.index = (int)binding.output.axis.axis;
  983. event.value = value;
  984. if (binding.output.axis.range != binding.input.axis.range) {
  985. switch (binding.output.axis.range) {
  986. case POSITIVE_HALF_AXIS:
  987. event.value = shifted_positive_value;
  988. break;
  989. case NEGATIVE_HALF_AXIS:
  990. event.value = shifted_positive_value - 1;
  991. break;
  992. case FULL_AXIS:
  993. event.value = (shifted_positive_value * 2) - 1;
  994. break;
  995. }
  996. }
  997. return event;
  998. default:
  999. ERR_PRINT_ONCE("Joypad axis mapping error.");
  1000. }
  1001. }
  1002. }
  1003. }
  1004. return event;
  1005. }
  1006. void Input::_get_mapped_hat_events(const JoyDeviceMapping &mapping, HatDir p_hat, JoyEvent r_events[(size_t)HatDir::MAX]) {
  1007. for (int i = 0; i < mapping.bindings.size(); i++) {
  1008. const JoyBinding binding = mapping.bindings[i];
  1009. if (binding.inputType == TYPE_HAT && binding.input.hat.hat == p_hat) {
  1010. HatDir hat_direction;
  1011. switch (binding.input.hat.hat_mask) {
  1012. case HatMask::UP:
  1013. hat_direction = HatDir::UP;
  1014. break;
  1015. case HatMask::RIGHT:
  1016. hat_direction = HatDir::RIGHT;
  1017. break;
  1018. case HatMask::DOWN:
  1019. hat_direction = HatDir::DOWN;
  1020. break;
  1021. case HatMask::LEFT:
  1022. hat_direction = HatDir::LEFT;
  1023. break;
  1024. default:
  1025. ERR_PRINT_ONCE("Joypad button mapping error.");
  1026. continue;
  1027. }
  1028. r_events[(size_t)hat_direction].type = binding.outputType;
  1029. switch (binding.outputType) {
  1030. case TYPE_BUTTON:
  1031. r_events[(size_t)hat_direction].index = (int)binding.output.button;
  1032. break;
  1033. case TYPE_AXIS:
  1034. r_events[(size_t)hat_direction].index = (int)binding.output.axis.axis;
  1035. switch (binding.output.axis.range) {
  1036. case POSITIVE_HALF_AXIS:
  1037. r_events[(size_t)hat_direction].value = 1;
  1038. break;
  1039. case NEGATIVE_HALF_AXIS:
  1040. r_events[(size_t)hat_direction].value = -1;
  1041. break;
  1042. case FULL_AXIS:
  1043. // It doesn't make sense for a hat direction to map to a full axis,
  1044. // but keeping as a default for a trigger with a positive half-axis.
  1045. r_events[(size_t)hat_direction].value = 1;
  1046. break;
  1047. }
  1048. break;
  1049. default:
  1050. ERR_PRINT_ONCE("Joypad button mapping error.");
  1051. }
  1052. }
  1053. }
  1054. }
  1055. JoyButton Input::_get_output_button(String output) {
  1056. for (int i = 0; i < (int)JoyButton::SDL_MAX; i++) {
  1057. if (output == _joy_buttons[i]) {
  1058. return JoyButton(i);
  1059. }
  1060. }
  1061. return JoyButton::INVALID;
  1062. }
  1063. JoyAxis Input::_get_output_axis(String output) {
  1064. for (int i = 0; i < (int)JoyAxis::SDL_MAX; i++) {
  1065. if (output == _joy_axes[i]) {
  1066. return JoyAxis(i);
  1067. }
  1068. }
  1069. return JoyAxis::INVALID;
  1070. }
  1071. void Input::parse_mapping(String p_mapping) {
  1072. _THREAD_SAFE_METHOD_;
  1073. JoyDeviceMapping mapping;
  1074. Vector<String> entry = p_mapping.split(",");
  1075. if (entry.size() < 2) {
  1076. return;
  1077. }
  1078. CharString uid;
  1079. uid.resize(17);
  1080. mapping.uid = entry[0];
  1081. mapping.name = entry[1];
  1082. int idx = 1;
  1083. while (++idx < entry.size()) {
  1084. if (entry[idx].is_empty()) {
  1085. continue;
  1086. }
  1087. String output = entry[idx].get_slice(":", 0).replace(" ", "");
  1088. String input = entry[idx].get_slice(":", 1).replace(" ", "");
  1089. ERR_CONTINUE_MSG(output.length() < 1 || input.length() < 2,
  1090. vformat("Invalid device mapping entry \"%s\" in mapping:\n%s", entry[idx], p_mapping));
  1091. if (output == "platform" || output == "hint") {
  1092. continue;
  1093. }
  1094. JoyAxisRange output_range = FULL_AXIS;
  1095. if (output[0] == '+' || output[0] == '-') {
  1096. ERR_CONTINUE_MSG(output.length() < 2,
  1097. vformat("Invalid output entry \"%s\" in mapping:\n%s", entry[idx], p_mapping));
  1098. if (output[0] == '+') {
  1099. output_range = POSITIVE_HALF_AXIS;
  1100. } else if (output[0] == '-') {
  1101. output_range = NEGATIVE_HALF_AXIS;
  1102. }
  1103. output = output.substr(1);
  1104. }
  1105. JoyAxisRange input_range = FULL_AXIS;
  1106. if (input[0] == '+') {
  1107. input_range = POSITIVE_HALF_AXIS;
  1108. input = input.substr(1);
  1109. } else if (input[0] == '-') {
  1110. input_range = NEGATIVE_HALF_AXIS;
  1111. input = input.substr(1);
  1112. }
  1113. bool invert_axis = false;
  1114. if (input[input.length() - 1] == '~') {
  1115. invert_axis = true;
  1116. input = input.left(input.length() - 1);
  1117. }
  1118. JoyButton output_button = _get_output_button(output);
  1119. JoyAxis output_axis = _get_output_axis(output);
  1120. ERR_CONTINUE_MSG(output_button == JoyButton::INVALID && output_axis == JoyAxis::INVALID,
  1121. vformat("Unrecognized output string \"%s\" in mapping:\n%s", output, p_mapping));
  1122. ERR_CONTINUE_MSG(output_button != JoyButton::INVALID && output_axis != JoyAxis::INVALID,
  1123. vformat("Output string \"%s\" matched both button and axis in mapping:\n%s", output, p_mapping));
  1124. JoyBinding binding;
  1125. if (output_button != JoyButton::INVALID) {
  1126. binding.outputType = TYPE_BUTTON;
  1127. binding.output.button = output_button;
  1128. } else if (output_axis != JoyAxis::INVALID) {
  1129. binding.outputType = TYPE_AXIS;
  1130. binding.output.axis.axis = output_axis;
  1131. binding.output.axis.range = output_range;
  1132. }
  1133. switch (input[0]) {
  1134. case 'b':
  1135. binding.inputType = TYPE_BUTTON;
  1136. binding.input.button = (JoyButton)input.substr(1).to_int();
  1137. break;
  1138. case 'a':
  1139. binding.inputType = TYPE_AXIS;
  1140. binding.input.axis.axis = (JoyAxis)input.substr(1).to_int();
  1141. binding.input.axis.range = input_range;
  1142. binding.input.axis.invert = invert_axis;
  1143. break;
  1144. case 'h':
  1145. ERR_CONTINUE_MSG(input.length() != 4 || input[2] != '.',
  1146. vformat("Invalid had input \"%s\" in mapping:\n%s", input, p_mapping));
  1147. binding.inputType = TYPE_HAT;
  1148. binding.input.hat.hat = (HatDir)input.substr(1, 1).to_int();
  1149. binding.input.hat.hat_mask = static_cast<HatMask>(input.substr(3).to_int());
  1150. break;
  1151. default:
  1152. ERR_CONTINUE_MSG(true, vformat("Unrecognized input string \"%s\" in mapping:\n%s", input, p_mapping));
  1153. }
  1154. mapping.bindings.push_back(binding);
  1155. }
  1156. map_db.push_back(mapping);
  1157. }
  1158. void Input::add_joy_mapping(String p_mapping, bool p_update_existing) {
  1159. parse_mapping(p_mapping);
  1160. if (p_update_existing) {
  1161. Vector<String> entry = p_mapping.split(",");
  1162. String uid = entry[0];
  1163. for (KeyValue<int, Joypad> &E : joy_names) {
  1164. Joypad &joy = E.value;
  1165. if (joy.uid == uid) {
  1166. joy.mapping = map_db.size() - 1;
  1167. }
  1168. }
  1169. }
  1170. }
  1171. void Input::remove_joy_mapping(String p_guid) {
  1172. for (int i = map_db.size() - 1; i >= 0; i--) {
  1173. if (p_guid == map_db[i].uid) {
  1174. map_db.remove_at(i);
  1175. }
  1176. }
  1177. for (KeyValue<int, Joypad> &E : joy_names) {
  1178. Joypad &joy = E.value;
  1179. if (joy.uid == p_guid) {
  1180. joy.mapping = -1;
  1181. }
  1182. }
  1183. }
  1184. void Input::set_fallback_mapping(String p_guid) {
  1185. for (int i = 0; i < map_db.size(); i++) {
  1186. if (map_db[i].uid == p_guid) {
  1187. fallback_mapping = i;
  1188. return;
  1189. }
  1190. }
  1191. }
  1192. //platforms that use the remapping system can override and call to these ones
  1193. bool Input::is_joy_known(int p_device) {
  1194. if (joy_names.has(p_device)) {
  1195. int mapping = joy_names[p_device].mapping;
  1196. if (mapping != -1 && mapping != fallback_mapping) {
  1197. return true;
  1198. }
  1199. }
  1200. return false;
  1201. }
  1202. String Input::get_joy_guid(int p_device) const {
  1203. ERR_FAIL_COND_V(!joy_names.has(p_device), "");
  1204. return joy_names[p_device].uid;
  1205. }
  1206. TypedArray<int> Input::get_connected_joypads() {
  1207. TypedArray<int> ret;
  1208. HashMap<int, Joypad>::Iterator elem = joy_names.begin();
  1209. while (elem) {
  1210. if (elem->value.connected) {
  1211. ret.push_back(elem->key);
  1212. }
  1213. ++elem;
  1214. }
  1215. return ret;
  1216. }
  1217. int Input::get_unused_joy_id() {
  1218. for (int i = 0; i < JOYPADS_MAX; i++) {
  1219. if (!joy_names.has(i) || !joy_names[i].connected) {
  1220. return i;
  1221. }
  1222. }
  1223. return -1;
  1224. }
  1225. Input::Input() {
  1226. singleton = this;
  1227. // Parse default mappings.
  1228. {
  1229. int i = 0;
  1230. while (DefaultControllerMappings::mappings[i]) {
  1231. parse_mapping(DefaultControllerMappings::mappings[i++]);
  1232. }
  1233. }
  1234. // If defined, parse SDL_GAMECONTROLLERCONFIG for possible new mappings/overrides.
  1235. String env_mapping = OS::get_singleton()->get_environment("SDL_GAMECONTROLLERCONFIG");
  1236. if (!env_mapping.is_empty()) {
  1237. Vector<String> entries = env_mapping.split("\n");
  1238. for (int i = 0; i < entries.size(); i++) {
  1239. if (entries[i].is_empty()) {
  1240. continue;
  1241. }
  1242. parse_mapping(entries[i]);
  1243. }
  1244. }
  1245. }
  1246. Input::~Input() {
  1247. singleton = nullptr;
  1248. }
  1249. //////////////////////////////////////////////////////////