Debian Codegraph @

core/input/input.cpp

raw symbols SCIP
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
31 #include "input.h"
32 #include "input.compat.inc"
33
34 #include "core/config/project_settings.h"
35 #include "core/input/default_controller_mappings.h"
36 #include "core/input/input_map.h"
37 #include "core/os/os.h"
38
39 #ifdef DEV_ENABLED
40 #include "core/os/thread.h"
41 #endif
42
43 static const char *_joy_buttons[(size_t)JoyButton::SDL_MAX] = {
44 "a",
45 "b",
46 "x",
47 "y",
48 "back",
49 "guide",
50 "start",
51 "leftstick",
52 "rightstick",
53 "leftshoulder",
54 "rightshoulder",
55 "dpup",
56 "dpdown",
57 "dpleft",
58 "dpright",
59 "misc1",
60 "paddle1",
61 "paddle2",
62 "paddle3",
63 "paddle4",
64 "touchpad",
65 };
66
67 static const char *_joy_axes[(size_t)JoyAxis::SDL_MAX] = {
68 "leftx",
69 "lefty",
70 "rightx",
71 "righty",
72 "lefttrigger",
73 "righttrigger",
74 };
75
76 void (*Input::set_mouse_mode_func)(Input::MouseMode) = nullptr;
77 Input::MouseMode (*Input::get_mouse_mode_func)() = nullptr;
78 void (*Input::set_mouse_mode_override_func)(Input::MouseMode) = nullptr;
79 Input::MouseMode (*Input::get_mouse_mode_override_func)() = nullptr;
80 void (*Input::set_mouse_mode_override_enabled_func)(bool) = nullptr;
81 bool (*Input::is_mouse_mode_override_enabled_func)() = nullptr;
82 void (*Input::warp_mouse_func)(const Vector2 &p_position) = nullptr;
83 Input::CursorShape (*Input::get_current_cursor_shape_func)() = nullptr;
84 void (*Input::set_custom_mouse_cursor_func)(const Ref<Resource> &, Input::CursorShape, const Vector2 &) = nullptr;
85
86 Input *Input::get_singleton() {
87 return singleton;
88 }
89
90 void Input::set_mouse_mode(MouseMode p_mode) {
91 ERR_FAIL_INDEX(p_mode, MouseMode::MOUSE_MODE_MAX);
92 set_mouse_mode_func(p_mode);
93 }
94
95 Input::MouseMode Input::get_mouse_mode() const {
96 return get_mouse_mode_func();
97 }
98
99 void Input::set_mouse_mode_override(MouseMode p_mode) {
100 ERR_FAIL_INDEX(p_mode, MouseMode::MOUSE_MODE_MAX);
101 set_mouse_mode_override_func(p_mode);
102 }
103
104 Input::MouseMode Input::get_mouse_mode_override() const {
105 return get_mouse_mode_override_func();
106 }
107
108 void Input::set_mouse_mode_override_enabled(bool p_override_enabled) {
109 set_mouse_mode_override_enabled_func(p_override_enabled);
110 }
111
112 bool Input::is_mouse_mode_override_enabled() {
113 return is_mouse_mode_override_enabled_func();
114 }
115
116 void Input::_bind_methods() {
117 ClassDB::bind_method(D_METHOD("is_anything_pressed"), &Input::is_anything_pressed);
118 ClassDB::bind_method(D_METHOD("is_key_pressed", "keycode"), &Input::is_key_pressed);
119 ClassDB::bind_method(D_METHOD("is_physical_key_pressed", "keycode"), &Input::is_physical_key_pressed);
120 ClassDB::bind_method(D_METHOD("is_key_label_pressed", "keycode"), &Input::is_key_label_pressed);
121 ClassDB::bind_method(D_METHOD("is_mouse_button_pressed", "button"), &Input::is_mouse_button_pressed);
122 ClassDB::bind_method(D_METHOD("is_joy_button_pressed", "device", "button"), &Input::is_joy_button_pressed);
123 ClassDB::bind_method(D_METHOD("is_action_pressed", "action", "exact_match"), &Input::is_action_pressed, DEFVAL(false));
124 ClassDB::bind_method(D_METHOD("is_action_just_pressed", "action", "exact_match"), &Input::is_action_just_pressed, DEFVAL(false));
125 ClassDB::bind_method(D_METHOD("is_action_just_released", "action", "exact_match"), &Input::is_action_just_released, DEFVAL(false));
126 ClassDB::bind_method(D_METHOD("is_action_just_pressed_by_event", "action", "event", "exact_match"), &Input::is_action_just_pressed_by_event, DEFVAL(false));
127 ClassDB::bind_method(D_METHOD("is_action_just_released_by_event", "action", "event", "exact_match"), &Input::is_action_just_released_by_event, DEFVAL(false));
128 ClassDB::bind_method(D_METHOD("get_action_strength", "action", "exact_match"), &Input::get_action_strength, DEFVAL(false));
129 ClassDB::bind_method(D_METHOD("get_action_raw_strength", "action", "exact_match"), &Input::get_action_raw_strength, DEFVAL(false));
130 ClassDB::bind_method(D_METHOD("get_axis", "negative_action", "positive_action"), &Input::get_axis);
131 ClassDB::bind_method(D_METHOD("get_vector", "negative_x", "positive_x", "negative_y", "positive_y", "deadzone"), &Input::get_vector, DEFVAL(-1.0f));
132 ClassDB::bind_method(D_METHOD("add_joy_mapping", "mapping", "update_existing"), &Input::add_joy_mapping, DEFVAL(false));
133 ClassDB::bind_method(D_METHOD("remove_joy_mapping", "guid"), &Input::remove_joy_mapping);
134 ClassDB::bind_method(D_METHOD("is_joy_known", "device"), &Input::is_joy_known);
135 ClassDB::bind_method(D_METHOD("get_joy_axis", "device", "axis"), &Input::get_joy_axis);
136 ClassDB::bind_method(D_METHOD("get_joy_name", "device"), &Input::get_joy_name);
137 ClassDB::bind_method(D_METHOD("get_joy_guid", "device"), &Input::get_joy_guid);
138 ClassDB::bind_method(D_METHOD("get_joy_info", "device"), &Input::get_joy_info);
139 ClassDB::bind_method(D_METHOD("should_ignore_device", "vendor_id", "product_id"), &Input::should_ignore_device);
140 ClassDB::bind_method(D_METHOD("get_connected_joypads"), &Input::get_connected_joypads);
141 ClassDB::bind_method(D_METHOD("get_joy_vibration_strength", "device"), &Input::get_joy_vibration_strength);
142 ClassDB::bind_method(D_METHOD("get_joy_vibration_duration", "device"), &Input::get_joy_vibration_duration);
143 ClassDB::bind_method(D_METHOD("start_joy_vibration", "device", "weak_magnitude", "strong_magnitude", "duration"), &Input::start_joy_vibration, DEFVAL(0));
144 ClassDB::bind_method(D_METHOD("stop_joy_vibration", "device"), &Input::stop_joy_vibration);
145 ClassDB::bind_method(D_METHOD("vibrate_handheld", "duration_ms", "amplitude"), &Input::vibrate_handheld, DEFVAL(500), DEFVAL(-1.0));
146 ClassDB::bind_method(D_METHOD("get_gravity"), &Input::get_gravity);
147 ClassDB::bind_method(D_METHOD("get_accelerometer"), &Input::get_accelerometer);
148 ClassDB::bind_method(D_METHOD("get_magnetometer"), &Input::get_magnetometer);
149 ClassDB::bind_method(D_METHOD("get_gyroscope"), &Input::get_gyroscope);
150 ClassDB::bind_method(D_METHOD("set_gravity", "value"), &Input::set_gravity);
151 ClassDB::bind_method(D_METHOD("set_accelerometer", "value"), &Input::set_accelerometer);
152 ClassDB::bind_method(D_METHOD("set_magnetometer", "value"), &Input::set_magnetometer);
153 ClassDB::bind_method(D_METHOD("set_gyroscope", "value"), &Input::set_gyroscope);
154 ClassDB::bind_method(D_METHOD("set_joy_light", "device", "color"), &Input::set_joy_light);
155 ClassDB::bind_method(D_METHOD("has_joy_light", "device"), &Input::has_joy_light);
156 ClassDB::bind_method(D_METHOD("get_last_mouse_velocity"), &Input::get_last_mouse_velocity);
157 ClassDB::bind_method(D_METHOD("get_last_mouse_screen_velocity"), &Input::get_last_mouse_screen_velocity);
158 ClassDB::bind_method(D_METHOD("get_mouse_button_mask"), &Input::get_mouse_button_mask);
159 ClassDB::bind_method(D_METHOD("set_mouse_mode", "mode"), &Input::set_mouse_mode);
160 ClassDB::bind_method(D_METHOD("get_mouse_mode"), &Input::get_mouse_mode);
161 ClassDB::bind_method(D_METHOD("warp_mouse", "position"), &Input::warp_mouse);
162 ClassDB::bind_method(D_METHOD("action_press", "action", "strength"), &Input::action_press, DEFVAL(1.f));
163 ClassDB::bind_method(D_METHOD("action_release", "action"), &Input::action_release);
164 ClassDB::bind_method(D_METHOD("set_default_cursor_shape", "shape"), &Input::set_default_cursor_shape, DEFVAL(CURSOR_ARROW));
165 ClassDB::bind_method(D_METHOD("get_current_cursor_shape"), &Input::get_current_cursor_shape);
166 ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor", "image", "shape", "hotspot"), &Input::set_custom_mouse_cursor, DEFVAL(CURSOR_ARROW), DEFVAL(Vector2()));
167 ClassDB::bind_method(D_METHOD("parse_input_event", "event"), &Input::parse_input_event);
168 ClassDB::bind_method(D_METHOD("set_use_accumulated_input", "enable"), &Input::set_use_accumulated_input);
169 ClassDB::bind_method(D_METHOD("is_using_accumulated_input"), &Input::is_using_accumulated_input);
170 ClassDB::bind_method(D_METHOD("flush_buffered_events"), &Input::flush_buffered_events);
171 ClassDB::bind_method(D_METHOD("set_emulate_mouse_from_touch", "enable"), &Input::set_emulate_mouse_from_touch);
172 ClassDB::bind_method(D_METHOD("is_emulating_mouse_from_touch"), &Input::is_emulating_mouse_from_touch);
173 ClassDB::bind_method(D_METHOD("set_emulate_touch_from_mouse", "enable"), &Input::set_emulate_touch_from_mouse);
174 ClassDB::bind_method(D_METHOD("is_emulating_touch_from_mouse"), &Input::is_emulating_touch_from_mouse);
175
176 ADD_PROPERTY(PropertyInfo(Variant::INT, "mouse_mode"), "set_mouse_mode", "get_mouse_mode");
177 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_accumulated_input"), "set_use_accumulated_input", "is_using_accumulated_input");
178 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emulate_mouse_from_touch"), "set_emulate_mouse_from_touch", "is_emulating_mouse_from_touch");
179 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emulate_touch_from_mouse"), "set_emulate_touch_from_mouse", "is_emulating_touch_from_mouse");
180
181 BIND_ENUM_CONSTANT(MOUSE_MODE_VISIBLE);
182 BIND_ENUM_CONSTANT(MOUSE_MODE_HIDDEN);
183 BIND_ENUM_CONSTANT(MOUSE_MODE_CAPTURED);
184 BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED);
185 BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED_HIDDEN);
186 BIND_ENUM_CONSTANT(MOUSE_MODE_MAX);
187
188 BIND_ENUM_CONSTANT(CURSOR_ARROW);
189 BIND_ENUM_CONSTANT(CURSOR_IBEAM);
190 BIND_ENUM_CONSTANT(CURSOR_POINTING_HAND);
191 BIND_ENUM_CONSTANT(CURSOR_CROSS);
192 BIND_ENUM_CONSTANT(CURSOR_WAIT);
193 BIND_ENUM_CONSTANT(CURSOR_BUSY);
194 BIND_ENUM_CONSTANT(CURSOR_DRAG);
195 BIND_ENUM_CONSTANT(CURSOR_CAN_DROP);
196 BIND_ENUM_CONSTANT(CURSOR_FORBIDDEN);
197 BIND_ENUM_CONSTANT(CURSOR_VSIZE);
198 BIND_ENUM_CONSTANT(CURSOR_HSIZE);
199 BIND_ENUM_CONSTANT(CURSOR_BDIAGSIZE);
200 BIND_ENUM_CONSTANT(CURSOR_FDIAGSIZE);
201 BIND_ENUM_CONSTANT(CURSOR_MOVE);
202 BIND_ENUM_CONSTANT(CURSOR_VSPLIT);
203 BIND_ENUM_CONSTANT(CURSOR_HSPLIT);
204 BIND_ENUM_CONSTANT(CURSOR_HELP);
205
206 ADD_SIGNAL(MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "device"), PropertyInfo(Variant::BOOL, "connected")));
207 }
208
209 #ifdef TOOLS_ENABLED
210 void Input::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
211 const String pf = p_function;
212
213 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")) ||
214 (p_idx < 2 && pf == "get_axis") ||
215 (p_idx < 4 && pf == "get_vector")) {
216 List<PropertyInfo> pinfo;
217 ProjectSettings::get_singleton()->get_property_list(&pinfo);
218
219 for (const PropertyInfo &pi : pinfo) {
220 if (!pi.name.begins_with("input/")) {
221 continue;
222 }
223
224 String name = pi.name.substr(pi.name.find_char('/') + 1);
225 r_options->push_back(name.quote());
226 }
227 }
228 Object::get_argument_options(p_function, p_idx, r_options);
229 }
230 #endif
231
232 void Input::VelocityTrack::update(const Vector2 &p_delta_p, const Vector2 &p_screen_delta_p) {
233 uint64_t tick = OS::get_singleton()->get_ticks_usec();
234 uint32_t tdiff = tick - last_tick;
235 float delta_t = tdiff / 1000000.0;
236 last_tick = tick;
237
238 if (delta_t > max_ref_frame) {
239 // First movement in a long time, reset and start again.
240 velocity = Vector2();
241 screen_velocity = Vector2();
242 accum = p_delta_p;
243 screen_accum = p_screen_delta_p;
244 accum_t = 0;
245 return;
246 }
247
248 accum += p_delta_p;
249 screen_accum += p_screen_delta_p;
250 accum_t += delta_t;
251
252 if (accum_t < min_ref_frame) {
253 // Not enough time has passed to calculate speed precisely.
254 return;
255 }
256
257 velocity = accum / accum_t;
258 screen_velocity = screen_accum / accum_t;
259 accum = Vector2();
260 screen_accum = Vector2();
261 accum_t = 0;
262 }
263
264 void Input::VelocityTrack::reset() {
265 last_tick = OS::get_singleton()->get_ticks_usec();
266 velocity = Vector2();
267 screen_velocity = Vector2();
268 accum = Vector2();
269 screen_accum = Vector2();
270 accum_t = 0;
271 }
272
273 Input::VelocityTrack::VelocityTrack() {
274 min_ref_frame = 0.1;
275 max_ref_frame = 3.0;
276 reset();
277 }
278
279 bool Input::is_anything_pressed() const {
280 _THREAD_SAFE_METHOD_
281
282 if (disable_input) {
283 return false;
284 }
285
286 if (!keys_pressed.is_empty() || !joy_buttons_pressed.is_empty() || !mouse_button_mask.is_empty()) {
287 return true;
288 }
289
290 for (const KeyValue<StringName, Input::ActionState> &E : action_states) {
291 if (E.value.cache.pressed) {
292 return true;
293 }
294 }
295
296 return false;
297 }
298
299 bool Input::is_anything_pressed_except_mouse() const {
300 _THREAD_SAFE_METHOD_
301
302 if (disable_input) {
303 return false;
304 }
305
306 if (!keys_pressed.is_empty() || !joy_buttons_pressed.is_empty()) {
307 return true;
308 }
309
310 for (const KeyValue<StringName, Input::ActionState> &E : action_states) {
311 if (E.value.cache.pressed) {
312 return true;
313 }
314 }
315
316 return false;
317 }
318
319 bool Input::is_key_pressed(Key p_keycode) const {
320 _THREAD_SAFE_METHOD_
321
322 if (disable_input) {
323 return false;
324 }
325
326 return keys_pressed.has(p_keycode);
327 }
328
329 bool Input::is_physical_key_pressed(Key p_keycode) const {
330 _THREAD_SAFE_METHOD_
331
332 if (disable_input) {
333 return false;
334 }
335
336 return physical_keys_pressed.has(p_keycode);
337 }
338
339 bool Input::is_key_label_pressed(Key p_keycode) const {
340 _THREAD_SAFE_METHOD_
341
342 if (disable_input) {
343 return false;
344 }
345
346 return key_label_pressed.has(p_keycode);
347 }
348
349 bool Input::is_mouse_button_pressed(MouseButton p_button) const {
350 _THREAD_SAFE_METHOD_
351
352 if (disable_input) {
353 return false;
354 }
355
356 return mouse_button_mask.has_flag(mouse_button_to_mask(p_button));
357 }
358
359 static JoyAxis _combine_device(JoyAxis p_value, int p_device) {
360 return JoyAxis((int)p_value | (p_device << 20));
361 }
362
363 static JoyButton _combine_device(JoyButton p_value, int p_device) {
364 return JoyButton((int)p_value | (p_device << 20));
365 }
366
367 bool Input::is_joy_button_pressed(int p_device, JoyButton p_button) const {
368 _THREAD_SAFE_METHOD_
369
370 if (disable_input) {
371 return false;
372 }
373
374 return joy_buttons_pressed.has(_combine_device(p_button, p_device));
375 }
376
377 bool Input::is_action_pressed(const StringName &p_action, bool p_exact) const {
378 ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
379
380 if (disable_input) {
381 return false;
382 }
383
384 HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
385 if (!E) {
386 return false;
387 }
388
389 return E->value.cache.pressed && (p_exact ? E->value.exact : true);
390 }
391
392 bool Input::is_action_just_pressed(const StringName &p_action, bool p_exact) const {
393 ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
394
395 if (disable_input) {
396 return false;
397 }
398
399 HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
400 if (!E) {
401 return false;
402 }
403
404 if (p_exact && E->value.exact == false) {
405 return false;
406 }
407
408 // Backward compatibility for legacy behavior, only return true if currently pressed.
409 bool pressed_requirement = legacy_just_pressed_behavior ? E->value.cache.pressed : true;
410
411 if (Engine::get_singleton()->is_in_physics_frame()) {
412 return pressed_requirement && E->value.pressed_physics_frame == Engine::get_singleton()->get_physics_frames();
413 } else {
414 return pressed_requirement && E->value.pressed_process_frame == Engine::get_singleton()->get_process_frames();
415 }
416 }
417
418 bool Input::is_action_just_pressed_by_event(const StringName &p_action, RequiredParam<InputEvent> rp_event, bool p_exact) const {
419 ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
420 EXTRACT_PARAM_OR_FAIL_V(p_event, rp_event, false);
421
422 if (disable_input) {
423 return false;
424 }
425
426 HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
427 if (!E) {
428 return false;
429 }
430
431 if (p_exact && E->value.exact == false) {
432 return false;
433 }
434
435 if (E->value.pressed_event_id != p_event->get_instance_id()) {
436 return false;
437 }
438
439 // Backward compatibility for legacy behavior, only return true if currently pressed.
440 bool pressed_requirement = legacy_just_pressed_behavior ? E->value.cache.pressed : true;
441
442 if (Engine::get_singleton()->is_in_physics_frame()) {
443 return pressed_requirement && E->value.pressed_physics_frame == Engine::get_singleton()->get_physics_frames();
444 } else {
445 return pressed_requirement && E->value.pressed_process_frame == Engine::get_singleton()->get_process_frames();
446 }
447 }
448
449 bool Input::is_action_just_released(const StringName &p_action, bool p_exact) const {
450 ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
451
452 if (disable_input) {
453 return false;
454 }
455
456 HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
457 if (!E) {
458 return false;
459 }
460
461 if (p_exact && E->value.exact == false) {
462 return false;
463 }
464
465 // Backward compatibility for legacy behavior, only return true if currently released.
466 bool released_requirement = legacy_just_pressed_behavior ? !E->value.cache.pressed : true;
467
468 if (Engine::get_singleton()->is_in_physics_frame()) {
469 return released_requirement && E->value.released_physics_frame == Engine::get_singleton()->get_physics_frames();
470 } else {
471 return released_requirement && E->value.released_process_frame == Engine::get_singleton()->get_process_frames();
472 }
473 }
474
475 bool Input::is_action_just_released_by_event(const StringName &p_action, RequiredParam<InputEvent> rp_event, bool p_exact) const {
476 ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
477 EXTRACT_PARAM_OR_FAIL_V(p_event, rp_event, false);
478
479 if (disable_input) {
480 return false;
481 }
482
483 HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
484 if (!E) {
485 return false;
486 }
487
488 if (p_exact && E->value.exact == false) {
489 return false;
490 }
491
492 if (E->value.released_event_id != p_event->get_instance_id()) {
493 return false;
494 }
495
496 // Backward compatibility for legacy behavior, only return true if currently released.
497 bool released_requirement = legacy_just_pressed_behavior ? !E->value.cache.pressed : true;
498
499 if (Engine::get_singleton()->is_in_physics_frame()) {
500 return released_requirement && E->value.released_physics_frame == Engine::get_singleton()->get_physics_frames();
501 } else {
502 return released_requirement && E->value.released_process_frame == Engine::get_singleton()->get_process_frames();
503 }
504 }
505
506 float Input::get_action_strength(const StringName &p_action, bool p_exact) const {
507 ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
508
509 if (disable_input) {
510 return 0.0f;
511 }
512
513 HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
514 if (!E) {
515 return 0.0f;
516 }
517
518 if (p_exact && E->value.exact == false) {
519 return 0.0f;
520 }
521
522 return E->value.cache.strength;
523 }
524
525 float Input::get_action_raw_strength(const StringName &p_action, bool p_exact) const {
526 ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
527
528 if (disable_input) {
529 return 0.0f;
530 }
531
532 HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
533 if (!E) {
534 return 0.0f;
535 }
536
537 if (p_exact && E->value.exact == false) {
538 return 0.0f;
539 }
540
541 return E->value.cache.raw_strength;
542 }
543
544 float Input::get_axis(const StringName &p_negative_action, const StringName &p_positive_action) const {
545 return get_action_strength(p_positive_action) - get_action_strength(p_negative_action);
546 }
547
548 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 {
549 Vector2 vector = Vector2(
550 get_action_raw_strength(p_positive_x) - get_action_raw_strength(p_negative_x),
551 get_action_raw_strength(p_positive_y) - get_action_raw_strength(p_negative_y));
552
553 if (p_deadzone < 0.0f) {
554 // If the deadzone isn't specified, get it from the average of the actions.
555 p_deadzone = 0.25 *
556 (InputMap::get_singleton()->action_get_deadzone(p_positive_x) +
557 InputMap::get_singleton()->action_get_deadzone(p_negative_x) +
558 InputMap::get_singleton()->action_get_deadzone(p_positive_y) +
559 InputMap::get_singleton()->action_get_deadzone(p_negative_y));
560 }
561
562 // Circular length limiting and deadzone.
563 float length = vector.length();
564 if (length <= p_deadzone) {
565 return Vector2();
566 } else if (length > 1.0f) {
567 return vector / length;
568 } else {
569 // Inverse lerp length to map (p_deadzone, 1) to (0, 1).
570 return vector * (Math::inverse_lerp(p_deadzone, 1.0f, length) / length);
571 }
572 }
573
574 float Input::get_joy_axis(int p_device, JoyAxis p_axis) const {
575 _THREAD_SAFE_METHOD_
576
577 if (disable_input) {
578 return 0;
579 }
580
581 JoyAxis c = _combine_device(p_axis, p_device);
582 if (_joy_axis.has(c)) {
583 return _joy_axis[c];
584 } else {
585 return 0;
586 }
587 }
588
589 String Input::get_joy_name(int p_idx) {
590 _THREAD_SAFE_METHOD_
591 return joy_names[p_idx].name;
592 }
593
594 Vector2 Input::get_joy_vibration_strength(int p_device) {
595 if (joy_vibration.has(p_device)) {
596 return Vector2(joy_vibration[p_device].weak_magnitude, joy_vibration[p_device].strong_magnitude);
597 } else {
598 return Vector2(0, 0);
599 }
600 }
601
602 uint64_t Input::get_joy_vibration_timestamp(int p_device) {
603 if (joy_vibration.has(p_device)) {
604 return joy_vibration[p_device].timestamp;
605 } else {
606 return 0;
607 }
608 }
609
610 float Input::get_joy_vibration_duration(int p_device) {
611 if (joy_vibration.has(p_device)) {
612 return joy_vibration[p_device].duration;
613 } else {
614 return 0.f;
615 }
616 }
617
618 static String _hex_str(uint8_t p_byte) {
619 static const char *dict = "0123456789abcdef";
620 char ret[3];
621 ret[2] = 0;
622
623 ret[0] = dict[p_byte >> 4];
624 ret[1] = dict[p_byte & 0xf];
625
626 return ret;
627 }
628
629 void Input::joy_connection_changed(int p_idx, bool p_connected, const String &p_name, const String &p_guid, const Dictionary &p_joypad_info) {
630 _THREAD_SAFE_METHOD_
631
632 // Clear the pressed status if a Joypad gets disconnected.
633 if (!p_connected) {
634 for (KeyValue<StringName, ActionState> &E : action_states) {
635 HashMap<int, ActionState::DeviceState>::Iterator it = E.value.device_states.find(p_idx);
636 if (it) {
637 E.value.device_states.remove(it);
638 _update_action_cache(E.key, E.value);
639 }
640 }
641 }
642
643 Joypad js;
644 js.name = p_connected ? p_name : "";
645 js.uid = p_connected ? p_guid : "";
646 js.info = p_connected ? p_joypad_info : Dictionary();
647
648 if (p_connected) {
649 String uidname = p_guid;
650 if (p_guid.is_empty()) {
651 int uidlen = MIN(p_name.length(), 16);
652 for (int i = 0; i < uidlen; i++) {
653 uidname = uidname + _hex_str(p_name[i]);
654 }
655 }
656 js.uid = uidname;
657 js.connected = true;
658 int mapping = fallback_mapping;
659 // Bypass the mapping system if the joypad's mapping is already handled by its driver
660 // (for example, the SDL joypad driver).
661 if (p_joypad_info.get("mapping_handled", false)) {
662 js.is_known = true;
663 } else {
664 for (int i = 0; i < map_db.size(); i++) {
665 if (js.uid == map_db[i].uid) {
666 mapping = i;
667 if (mapping != fallback_mapping) {
668 js.is_known = true;
669 }
670 break;
671 }
672 }
673 }
674 // We don't want this setting to be exposed to the user, because it's not very useful outside of this method.
675 js.info.erase("mapping_handled");
676
677 _set_joypad_mapping(js, mapping);
678 } else {
679 js.connected = false;
680 for (int i = 0; i < (int)JoyButton::MAX; i++) {
681 JoyButton c = _combine_device((JoyButton)i, p_idx);
682 joy_buttons_pressed.erase(c);
683 }
684 for (int i = 0; i < (int)JoyAxis::MAX; i++) {
685 set_joy_axis(p_idx, (JoyAxis)i, 0.0f);
686 }
687 }
688 joy_names[p_idx] = js;
689
690 // Ensure this signal is emitted on the main thread, as some platforms (e.g. Linux) call this from a different thread.
691 call_deferred("emit_signal", SNAME("joy_connection_changed"), p_idx, p_connected);
692 }
693
694 Vector3 Input::get_gravity() const {
695 _THREAD_SAFE_METHOD_
696
697 #if defined(DEBUG_ENABLED) && defined(ANDROID_ENABLED)
698 if (!gravity_enabled) {
699 WARN_PRINT_ONCE("`input_devices/sensors/enable_gravity` is not enabled in project settings.");
700 }
701 #endif
702
703 return gravity;
704 }
705
706 Vector3 Input::get_accelerometer() const {
707 _THREAD_SAFE_METHOD_
708
709 #if defined(DEBUG_ENABLED) && defined(ANDROID_ENABLED)
710 if (!accelerometer_enabled) {
711 WARN_PRINT_ONCE("`input_devices/sensors/enable_accelerometer` is not enabled in project settings.");
712 }
713 #endif
714
715 return accelerometer;
716 }
717
718 Vector3 Input::get_magnetometer() const {
719 _THREAD_SAFE_METHOD_
720
721 #if defined(DEBUG_ENABLED) && defined(ANDROID_ENABLED)
722 if (!magnetometer_enabled) {
723 WARN_PRINT_ONCE("`input_devices/sensors/enable_magnetometer` is not enabled in project settings.");
724 }
725 #endif
726
727 return magnetometer;
728 }
729
730 Vector3 Input::get_gyroscope() const {
731 _THREAD_SAFE_METHOD_
732
733 #if defined(DEBUG_ENABLED) && defined(ANDROID_ENABLED)
734 if (!gyroscope_enabled) {
735 WARN_PRINT_ONCE("`input_devices/sensors/enable_gyroscope` is not enabled in project settings.");
736 }
737 #endif
738
739 return gyroscope;
740 }
741
742 void Input::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool p_is_emulated) {
743 // This function does the final delivery of the input event to user land.
744 // Regardless where the event came from originally, this has to happen on the main thread.
745 DEV_ASSERT(Thread::get_caller_id() == Thread::get_main_id());
746
747 // Notes on mouse-touch emulation:
748 // - Emulated mouse events are parsed, that is, re-routed to this method, so they make the same effects
749 // as true mouse events. The only difference is the situation is flagged as emulated so they are not
750 // emulated back to touch events in an endless loop.
751 // - Emulated touch events are handed right to the main loop (i.e., the SceneTree) because they don't
752 // require additional handling by this class.
753
754 Ref<InputEventKey> k = p_event;
755 if (k.is_valid() && !k->is_echo() && k->get_keycode() != Key::NONE) {
756 if (k->is_pressed()) {
757 keys_pressed.insert(k->get_keycode());
758 } else {
759 keys_pressed.erase(k->get_keycode());
760 }
761 }
762 if (k.is_valid() && !k->is_echo() && k->get_physical_keycode() != Key::NONE) {
763 if (k->is_pressed()) {
764 physical_keys_pressed.insert(k->get_physical_keycode());
765 } else {
766 physical_keys_pressed.erase(k->get_physical_keycode());
767 }
768 }
769 if (k.is_valid() && !k->is_echo() && k->get_key_label() != Key::NONE) {
770 if (k->is_pressed()) {
771 key_label_pressed.insert(k->get_key_label());
772 } else {
773 key_label_pressed.erase(k->get_key_label());
774 }
775 }
776
777 Ref<InputEventMouseButton> mb = p_event;
778
779 if (mb.is_valid()) {
780 if (mb->is_pressed()) {
781 mouse_button_mask.set_flag(mouse_button_to_mask(mb->get_button_index()));
782 } else {
783 mouse_button_mask.clear_flag(mouse_button_to_mask(mb->get_button_index()));
784 }
785
786 Point2 pos = mb->get_global_position();
787 if (mouse_pos != pos) {
788 set_mouse_position(pos);
789 }
790
791 if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mb->get_button_index() == MouseButton::LEFT) {
792 Ref<InputEventScreenTouch> touch_event;
793 touch_event.instantiate();
794 touch_event->set_pressed(mb->is_pressed());
795 touch_event->set_canceled(mb->is_canceled());
796 touch_event->set_position(mb->get_position());
797 touch_event->set_double_tap(mb->is_double_click());
798 touch_event->set_window_id(mb->get_window_id());
799 touch_event->set_device(InputEvent::DEVICE_ID_EMULATION);
800 _THREAD_SAFE_UNLOCK_
801 event_dispatch_function(touch_event);
802 _THREAD_SAFE_LOCK_
803 }
804 }
805
806 Ref<InputEventMouseMotion> mm = p_event;
807
808 if (mm.is_valid()) {
809 Point2 position = mm->get_global_position();
810 if (mouse_pos != position) {
811 set_mouse_position(position);
812 }
813 Vector2 relative = mm->get_relative();
814 Vector2 screen_relative = mm->get_relative_screen_position();
815 mouse_velocity_track.update(relative, screen_relative);
816
817 if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mm->get_button_mask().has_flag(MouseButtonMask::LEFT)) {
818 Ref<InputEventScreenDrag> drag_event;
819 drag_event.instantiate();
820
821 drag_event->set_position(position);
822 drag_event->set_relative(relative);
823 drag_event->set_relative_screen_position(screen_relative);
824 drag_event->set_tilt(mm->get_tilt());
825 drag_event->set_pen_inverted(mm->get_pen_inverted());
826 drag_event->set_pressure(mm->get_pressure());
827 drag_event->set_velocity(get_last_mouse_velocity());
828 drag_event->set_screen_velocity(get_last_mouse_screen_velocity());
829 drag_event->set_device(InputEvent::DEVICE_ID_EMULATION);
830
831 _THREAD_SAFE_UNLOCK_
832 event_dispatch_function(drag_event);
833 _THREAD_SAFE_LOCK_
834 }
835 }
836
837 Ref<InputEventScreenTouch> st = p_event;
838
839 if (st.is_valid()) {
840 if (st->is_pressed()) {
841 VelocityTrack &track = touch_velocity_track[st->get_index()];
842 track.reset();
843 } else {
844 // Since a pointer index may not occur again (OSs may or may not reuse them),
845 // imperatively remove it from the map to keep no fossil entries in it
846 touch_velocity_track.erase(st->get_index());
847 }
848
849 if (emulate_mouse_from_touch) {
850 bool translate = false;
851 if (st->is_pressed()) {
852 if (mouse_from_touch_index == -1) {
853 translate = true;
854 mouse_from_touch_index = st->get_index();
855 }
856 } else {
857 if (st->get_index() == mouse_from_touch_index) {
858 translate = true;
859 mouse_from_touch_index = -1;
860 }
861 }
862
863 if (translate) {
864 Ref<InputEventMouseButton> button_event;
865 button_event.instantiate();
866
867 button_event->set_device(InputEvent::DEVICE_ID_EMULATION);
868 button_event->set_position(st->get_position());
869 button_event->set_global_position(st->get_position());
870 button_event->set_pressed(st->is_pressed());
871 button_event->set_canceled(st->is_canceled());
872 button_event->set_button_index(MouseButton::LEFT);
873 button_event->set_double_click(st->is_double_tap());
874 button_event->set_window_id(st->get_window_id());
875
876 BitField<MouseButtonMask> ev_bm = mouse_button_mask;
877 if (st->is_pressed()) {
878 ev_bm.set_flag(MouseButtonMask::LEFT);
879 } else {
880 ev_bm.clear_flag(MouseButtonMask::LEFT);
881 }
882 button_event->set_button_mask(ev_bm);
883
884 _parse_input_event_impl(button_event, true);
885 }
886 }
887 }
888
889 Ref<InputEventScreenDrag> sd = p_event;
890
891 if (sd.is_valid()) {
892 VelocityTrack &track = touch_velocity_track[sd->get_index()];
893 track.update(sd->get_relative(), sd->get_relative_screen_position());
894 sd->set_velocity(track.velocity);
895 sd->set_screen_velocity(track.screen_velocity);
896
897 if (emulate_mouse_from_touch && sd->get_index() == mouse_from_touch_index) {
898 Ref<InputEventMouseMotion> motion_event;
899 motion_event.instantiate();
900
901 motion_event->set_device(InputEvent::DEVICE_ID_EMULATION);
902 motion_event->set_tilt(sd->get_tilt());
903 motion_event->set_pen_inverted(sd->get_pen_inverted());
904 motion_event->set_pressure(sd->get_pressure());
905 motion_event->set_position(sd->get_position());
906 motion_event->set_global_position(sd->get_position());
907 motion_event->set_relative(sd->get_relative());
908 motion_event->set_relative_screen_position(sd->get_relative_screen_position());
909 motion_event->set_velocity(sd->get_velocity());
910 motion_event->set_screen_velocity(sd->get_screen_velocity());
911 motion_event->set_button_mask(mouse_button_mask);
912 motion_event->set_window_id(sd->get_window_id());
913
914 _parse_input_event_impl(motion_event, true);
915 }
916 }
917
918 Ref<InputEventJoypadButton> jb = p_event;
919
920 if (jb.is_valid()) {
921 JoyButton c = _combine_device(jb->get_button_index(), jb->get_device());
922
923 if (jb->is_pressed()) {
924 joy_buttons_pressed.insert(c);
925 } else {
926 joy_buttons_pressed.erase(c);
927 }
928 }
929
930 Ref<InputEventJoypadMotion> jm = p_event;
931
932 if (jm.is_valid()) {
933 set_joy_axis(jm->get_device(), jm->get_axis(), jm->get_axis_value());
934 }
935
936 Ref<InputEventGesture> ge = p_event;
937
938 if (ge.is_valid()) {
939 if (event_dispatch_function) {
940 _THREAD_SAFE_UNLOCK_
941 event_dispatch_function(ge);
942 _THREAD_SAFE_LOCK_
943 }
944 }
945
946 for (const KeyValue<StringName, InputMap::Action> &E : InputMap::get_singleton()->get_action_map()) {
947 const int event_index = InputMap::get_singleton()->event_get_index(p_event, E.key);
948 if (event_index == -1) {
949 continue;
950 }
951 ERR_FAIL_COND_MSG(event_index >= (int)MAX_EVENT, vformat("Input singleton does not support more than %d events assigned to an action.", MAX_EVENT));
952
953 int device_id = p_event->get_device();
954 bool is_pressed = p_event->is_action_pressed(E.key, true);
955 ActionState &action_state = action_states[E.key];
956
957 // Update the action's per-device state.
958 ActionState::DeviceState &device_state = action_state.device_states[device_id];
959 device_state.pressed[event_index] = is_pressed;
960 device_state.strength[event_index] = p_event->get_action_strength(E.key);
961 device_state.raw_strength[event_index] = p_event->get_action_raw_strength(E.key);
962
963 // Update the action's global state and cache.
964 if (!is_pressed) {
965 action_state.api_pressed = false; // Always release the event from action_press() method.
966 action_state.api_strength = 0.0;
967 }
968 action_state.exact = InputMap::get_singleton()->event_is_action(p_event, E.key, true);
969
970 bool was_pressed = action_state.cache.pressed;
971 _update_action_cache(E.key, action_state);
972 // As input may come in part way through a physics tick, the earliest we can react to it is the next physics tick.
973 if (action_state.cache.pressed && !was_pressed) {
974 action_state.pressed_event_id = p_event->get_instance_id();
975 action_state.pressed_physics_frame = Engine::get_singleton()->get_physics_frames() + 1;
976 action_state.pressed_process_frame = Engine::get_singleton()->get_process_frames();
977 }
978 if (!action_state.cache.pressed && was_pressed) {
979 action_state.released_event_id = p_event->get_instance_id();
980 action_state.released_physics_frame = Engine::get_singleton()->get_physics_frames() + 1;
981 action_state.released_process_frame = Engine::get_singleton()->get_process_frames();
982 }
983 }
984
985 if (event_dispatch_function) {
986 _THREAD_SAFE_UNLOCK_
987 event_dispatch_function(p_event);
988 _THREAD_SAFE_LOCK_
989 }
990 }
991
992 void Input::set_joy_axis(int p_device, JoyAxis p_axis, float p_value) {
993 _THREAD_SAFE_METHOD_
994 JoyAxis c = _combine_device(p_axis, p_device);
995 _joy_axis[c] = p_value;
996 }
997
998 void Input::set_joy_features(int p_device, JoypadFeatures *p_features) {
999 Joypad *joypad = joy_names.getptr(p_device);
1000 if (!joypad) {
1001 return;
1002 }
1003 joypad->features = p_features;
1004 _update_joypad_features(p_device);
1005 }
1006
1007 void Input::set_joy_light(int p_device, const Color &p_color) {
1008 Joypad *joypad = joy_names.getptr(p_device);
1009 if (!joypad || !joypad->has_light || joypad->features == nullptr) {
1010 return;
1011 }
1012 Color linear = p_color.srgb_to_linear();
1013 joypad->features->set_joy_light(linear);
1014 }
1015
1016 bool Input::has_joy_light(int p_device) const {
1017 const Joypad *joypad = joy_names.getptr(p_device);
1018 return joypad && joypad->has_light;
1019 }
1020
1021 void Input::start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration) {
1022 _THREAD_SAFE_METHOD_
1023 if (p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
1024 return;
1025 }
1026 VibrationInfo vibration;
1027 vibration.weak_magnitude = p_weak_magnitude;
1028 vibration.strong_magnitude = p_strong_magnitude;
1029 vibration.duration = p_duration;
1030 vibration.timestamp = OS::get_singleton()->get_ticks_usec();
1031 joy_vibration[p_device] = vibration;
1032 }
1033
1034 void Input::stop_joy_vibration(int p_device) {
1035 _THREAD_SAFE_METHOD_
1036 VibrationInfo vibration;
1037 vibration.weak_magnitude = 0;
1038 vibration.strong_magnitude = 0;
1039 vibration.duration = 0;
1040 vibration.timestamp = OS::get_singleton()->get_ticks_usec();
1041 joy_vibration[p_device] = vibration;
1042 }
1043
1044 void Input::vibrate_handheld(int p_duration_ms, float p_amplitude) {
1045 OS::get_singleton()->vibrate_handheld(p_duration_ms, p_amplitude);
1046 }
1047
1048 void Input::set_gravity(const Vector3 &p_gravity) {
1049 _THREAD_SAFE_METHOD_
1050
1051 gravity = p_gravity;
1052 }
1053
1054 void Input::set_accelerometer(const Vector3 &p_accel) {
1055 _THREAD_SAFE_METHOD_
1056
1057 accelerometer = p_accel;
1058 }
1059
1060 void Input::set_magnetometer(const Vector3 &p_magnetometer) {
1061 _THREAD_SAFE_METHOD_
1062
1063 magnetometer = p_magnetometer;
1064 }
1065
1066 void Input::set_gyroscope(const Vector3 &p_gyroscope) {
1067 _THREAD_SAFE_METHOD_
1068
1069 gyroscope = p_gyroscope;
1070 }
1071
1072 void Input::set_mouse_position(const Point2 &p_posf) {
1073 mouse_pos = p_posf;
1074 }
1075
1076 Point2 Input::get_mouse_position() const {
1077 return mouse_pos;
1078 }
1079
1080 Point2 Input::get_last_mouse_velocity() {
1081 mouse_velocity_track.update(Vector2(), Vector2());
1082 return mouse_velocity_track.velocity;
1083 }
1084
1085 Point2 Input::get_last_mouse_screen_velocity() {
1086 mouse_velocity_track.update(Vector2(), Vector2());
1087 return mouse_velocity_track.screen_velocity;
1088 }
1089
1090 BitField<MouseButtonMask> Input::get_mouse_button_mask() const {
1091 return mouse_button_mask; // do not trust OS implementation, should remove it - OS::get_singleton()->get_mouse_button_state();
1092 }
1093
1094 void Input::warp_mouse(const Vector2 &p_position) {
1095 warp_mouse_func(p_position);
1096 }
1097
1098 Point2 Input::warp_mouse_motion(const Ref<InputEventMouseMotion> &p_motion, const Rect2 &p_rect) {
1099 // The relative distance reported for the next event after a warp is in the boundaries of the
1100 // size of the rect on that axis, but it may be greater, in which case there's no problem as fmod()
1101 // will warp it, but if the pointer has moved in the opposite direction between the pointer relocation
1102 // and the subsequent event, the reported relative distance will be less than the size of the rect
1103 // and thus fmod() will be disabled for handling the situation.
1104 // And due to this mouse warping mechanism being stateless, we need to apply some heuristics to
1105 // detect the warp: if the relative distance is greater than the half of the size of the relevant rect
1106 // (checked per each axis), it will be considered as the consequence of a former pointer warp.
1107
1108 const Point2 rel_sign(p_motion->get_relative().x >= 0.0f ? 1 : -1, p_motion->get_relative().y >= 0.0 ? 1 : -1);
1109 const Size2 warp_margin = p_rect.size * 0.5f;
1110 const Point2 rel_warped(
1111 Math::fmod(p_motion->get_relative().x + rel_sign.x * warp_margin.x, p_rect.size.x) - rel_sign.x * warp_margin.x,
1112 Math::fmod(p_motion->get_relative().y + rel_sign.y * warp_margin.y, p_rect.size.y) - rel_sign.y * warp_margin.y);
1113
1114 const Point2 pos_local = p_motion->get_global_position() - p_rect.position;
1115 const Point2 pos_warped(Math::fposmod(pos_local.x, p_rect.size.x), Math::fposmod(pos_local.y, p_rect.size.y));
1116 if (pos_warped != pos_local) {
1117 warp_mouse(pos_warped + p_rect.position);
1118 }
1119
1120 return rel_warped;
1121 }
1122
1123 void Input::action_press(const StringName &p_action, float p_strength) {
1124 ERR_FAIL_COND_MSG(!InputMap::get_singleton()->has_action(p_action), InputMap::get_singleton()->suggest_actions(p_action));
1125
1126 // Create or retrieve existing action.
1127 ActionState &action_state = action_states[p_action];
1128
1129 // As input may come in part way through a physics tick, the earliest we can react to it is the next physics tick.
1130 if (!action_state.cache.pressed) {
1131 action_state.pressed_event_id = ObjectID();
1132 action_state.pressed_physics_frame = Engine::get_singleton()->get_physics_frames() + 1;
1133 action_state.pressed_process_frame = Engine::get_singleton()->get_process_frames();
1134 }
1135 action_state.exact = true;
1136 action_state.api_pressed = true;
1137 action_state.api_strength = CLAMP(p_strength, 0.0f, 1.0f);
1138 _update_action_cache(p_action, action_state);
1139 }
1140
1141 void Input::action_release(const StringName &p_action) {
1142 ERR_FAIL_COND_MSG(!InputMap::get_singleton()->has_action(p_action), InputMap::get_singleton()->suggest_actions(p_action));
1143
1144 // Create or retrieve existing action.
1145 ActionState &action_state = action_states[p_action];
1146 action_state.cache.pressed = false;
1147 action_state.cache.strength = 0.0;
1148 action_state.cache.raw_strength = 0.0;
1149 // As input may come in part way through a physics tick, the earliest we can react to it is the next physics tick.
1150 action_state.released_event_id = ObjectID();
1151 action_state.released_physics_frame = Engine::get_singleton()->get_physics_frames() + 1;
1152 action_state.released_process_frame = Engine::get_singleton()->get_process_frames();
1153 action_state.device_states.clear();
1154 action_state.exact = true;
1155 action_state.api_pressed = false;
1156 action_state.api_strength = 0.0;
1157 }
1158
1159 void Input::set_emulate_touch_from_mouse(bool p_emulate) {
1160 emulate_touch_from_mouse = p_emulate;
1161 }
1162
1163 bool Input::is_emulating_touch_from_mouse() const {
1164 return emulate_touch_from_mouse;
1165 }
1166
1167 // Calling this whenever the game window is focused helps unsticking the "touch mouse"
1168 // if the OS or its abstraction class hasn't properly reported that touch pointers raised
1169 void Input::ensure_touch_mouse_raised() {
1170 _THREAD_SAFE_METHOD_
1171 if (mouse_from_touch_index != -1) {
1172 mouse_from_touch_index = -1;
1173
1174 Ref<InputEventMouseButton> button_event;
1175 button_event.instantiate();
1176
1177 button_event->set_device(InputEvent::DEVICE_ID_EMULATION);
1178 button_event->set_position(mouse_pos);
1179 button_event->set_global_position(mouse_pos);
1180 button_event->set_pressed(false);
1181 button_event->set_button_index(MouseButton::LEFT);
1182 BitField<MouseButtonMask> ev_bm = mouse_button_mask;
1183 ev_bm.clear_flag(MouseButtonMask::LEFT);
1184 button_event->set_button_mask(ev_bm);
1185
1186 _parse_input_event_impl(button_event, true);
1187 }
1188 }
1189
1190 void Input::set_emulate_mouse_from_touch(bool p_emulate) {
1191 emulate_mouse_from_touch = p_emulate;
1192 }
1193
1194 bool Input::is_emulating_mouse_from_touch() const {
1195 return emulate_mouse_from_touch;
1196 }
1197
1198 Input::CursorShape Input::get_default_cursor_shape() const {
1199 return default_shape;
1200 }
1201
1202 void Input::set_default_cursor_shape(CursorShape p_shape) {
1203 if (default_shape == p_shape) {
1204 return;
1205 }
1206
1207 default_shape = p_shape;
1208 // The default shape is set in Viewport::_gui_input_event. To instantly
1209 // see the shape in the viewport we need to trigger a mouse motion event.
1210 Ref<InputEventMouseMotion> mm;
1211 mm.instantiate();
1212 mm->set_position(mouse_pos);
1213 mm->set_global_position(mouse_pos);
1214 mm->set_device(InputEvent::DEVICE_ID_INTERNAL);
1215 parse_input_event(mm);
1216 }
1217
1218 Input::CursorShape Input::get_current_cursor_shape() const {
1219 return get_current_cursor_shape_func();
1220 }
1221
1222 void Input::set_custom_mouse_cursor(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
1223 if (Engine::get_singleton()->is_editor_hint()) {
1224 return;
1225 }
1226
1227 ERR_FAIL_INDEX(p_shape, CursorShape::CURSOR_MAX);
1228
1229 set_custom_mouse_cursor_func(p_cursor, p_shape, p_hotspot);
1230 }
1231
1232 void Input::parse_input_event(RequiredParam<InputEvent> rp_event) {
1233 _THREAD_SAFE_METHOD_
1234
1235 EXTRACT_PARAM_OR_FAIL(p_event, rp_event);
1236
1237 #ifdef DEBUG_ENABLED
1238 uint64_t curr_frame = Engine::get_singleton()->get_process_frames();
1239 if (curr_frame != last_parsed_frame) {
1240 frame_parsed_events.clear();
1241 last_parsed_frame = curr_frame;
1242 frame_parsed_events.insert(p_event);
1243 } else if (frame_parsed_events.has(p_event)) {
1244 // It would be technically safe to send the same event in cases such as:
1245 // - After an explicit flush.
1246 // - In platforms using buffering when agile flushing is enabled, after one of the mid-frame flushes.
1247 // - If platform doesn't use buffering and event accumulation is disabled.
1248 // - If platform doesn't use buffering and the event type is not accumulable.
1249 // However, it wouldn't be reasonable to ask users to remember the full ruleset and be aware at all times
1250 // of the possibilities of the target platform, project settings and engine internals, which may change
1251 // without prior notice.
1252 // Therefore, the guideline is, "don't send the same event object more than once per frame".
1253 WARN_PRINT_ONCE(
1254 "An input event object is being parsed more than once in the same frame, which is unsafe.\n"
1255 "If you are generating events in a script, you have to instantiate a new event instead of sending the same one more than once, unless the original one was sent on an earlier frame.\n"
1256 "You can call duplicate() on the event to get a new instance with identical values.");
1257 } else {
1258 frame_parsed_events.insert(p_event);
1259 }
1260 #endif
1261
1262 if (use_accumulated_input) {
1263 if (buffered_events.is_empty() || !buffered_events.back()->get()->accumulate(p_event)) {
1264 buffered_events.push_back(p_event);
1265 }
1266 } else if (agile_input_event_flushing) {
1267 buffered_events.push_back(p_event);
1268 } else {
1269 _parse_input_event_impl(p_event, false);
1270 }
1271 }
1272
1273 #ifdef DEBUG_ENABLED
1274 void Input::flush_frame_parsed_events() {
1275 _THREAD_SAFE_METHOD_
1276
1277 frame_parsed_events.clear();
1278 }
1279 #endif
1280
1281 void Input::flush_buffered_events() {
1282 _THREAD_SAFE_METHOD_
1283
1284 while (buffered_events.front()) {
1285 // The final delivery of the input event involves releasing the lock.
1286 // While the lock is released, another thread may lock it and add new events to the back.
1287 // Therefore, we get each event and pop it while we still have the lock,
1288 // to ensure the list is in a consistent state.
1289 List<Ref<InputEvent>>::Element *E = buffered_events.front();
1290 Ref<InputEvent> e = E->get();
1291 buffered_events.pop_front();
1292
1293 _parse_input_event_impl(e, false);
1294 }
1295 }
1296
1297 bool Input::is_agile_input_event_flushing() {
1298 return agile_input_event_flushing;
1299 }
1300
1301 void Input::set_agile_input_event_flushing(bool p_enable) {
1302 agile_input_event_flushing = p_enable;
1303 }
1304
1305 void Input::set_use_accumulated_input(bool p_enable) {
1306 use_accumulated_input = p_enable;
1307 }
1308
1309 bool Input::is_using_accumulated_input() {
1310 return use_accumulated_input;
1311 }
1312
1313 void Input::release_pressed_events() {
1314 flush_buffered_events(); // this is needed to release actions strengths
1315
1316 keys_pressed.clear();
1317 physical_keys_pressed.clear();
1318 key_label_pressed.clear();
1319 joy_buttons_pressed.clear();
1320 _joy_axis.clear();
1321
1322 for (KeyValue<StringName, Input::ActionState> &E : action_states) {
1323 if (E.value.cache.pressed) {
1324 action_release(E.key);
1325 }
1326 }
1327 }
1328
1329 void Input::set_event_dispatch_function(EventDispatchFunc p_function) {
1330 event_dispatch_function = p_function;
1331 }
1332
1333 void Input::joy_button(int p_device, JoyButton p_button, bool p_pressed) {
1334 _THREAD_SAFE_METHOD_;
1335 Joypad &joy = joy_names[p_device];
1336 ERR_FAIL_INDEX((int)p_button, (int)JoyButton::MAX);
1337
1338 if (joy.last_buttons[(size_t)p_button] == p_pressed) {
1339 return;
1340 }
1341 joy.last_buttons[(size_t)p_button] = p_pressed;
1342 if (joy.mapping == -1) {
1343 _button_event(p_device, p_button, p_pressed);
1344 return;
1345 }
1346
1347 JoyEvent map = _get_mapped_button_event(map_db[joy.mapping], p_button);
1348
1349 if (map.type == TYPE_BUTTON) {
1350 _button_event(p_device, (JoyButton)map.index, p_pressed);
1351 return;
1352 }
1353
1354 if (map.type == TYPE_AXIS) {
1355 _axis_event(p_device, (JoyAxis)map.index, p_pressed ? map.value : 0.0);
1356 }
1357 // no event?
1358 }
1359
1360 void Input::joy_axis(int p_device, JoyAxis p_axis, float p_value) {
1361 _THREAD_SAFE_METHOD_;
1362
1363 ERR_FAIL_INDEX((int)p_axis, (int)JoyAxis::MAX);
1364
1365 Joypad &joy = joy_names[p_device];
1366
1367 if (joy.last_axis[(size_t)p_axis] == p_value) {
1368 return;
1369 }
1370
1371 joy.last_axis[(size_t)p_axis] = p_value;
1372
1373 if (joy.mapping == -1) {
1374 _axis_event(p_device, p_axis, p_value);
1375 return;
1376 }
1377
1378 JoyAxisRange range;
1379 JoyEvent map = _get_mapped_axis_event(map_db[joy.mapping], p_axis, p_value, range);
1380
1381 if (map.type == TYPE_BUTTON) {
1382 bool pressed = map.value > 0.5;
1383 if (pressed != joy_buttons_pressed.has(_combine_device((JoyButton)map.index, p_device))) {
1384 _button_event(p_device, (JoyButton)map.index, pressed);
1385 }
1386
1387 // Ensure opposite D-Pad button is also released.
1388 switch ((JoyButton)map.index) {
1389 case JoyButton::DPAD_UP:
1390 if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_DOWN, p_device))) {
1391 _button_event(p_device, JoyButton::DPAD_DOWN, false);
1392 }
1393 break;
1394 case JoyButton::DPAD_DOWN:
1395 if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_UP, p_device))) {
1396 _button_event(p_device, JoyButton::DPAD_UP, false);
1397 }
1398 break;
1399 case JoyButton::DPAD_LEFT:
1400 if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_RIGHT, p_device))) {
1401 _button_event(p_device, JoyButton::DPAD_RIGHT, false);
1402 }
1403 break;
1404 case JoyButton::DPAD_RIGHT:
1405 if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_LEFT, p_device))) {
1406 _button_event(p_device, JoyButton::DPAD_LEFT, false);
1407 }
1408 break;
1409 default:
1410 // Nothing to do.
1411 break;
1412 }
1413 return;
1414 }
1415
1416 if (map.type == TYPE_AXIS) {
1417 JoyAxis axis = JoyAxis(map.index);
1418 float value = map.value;
1419 #ifndef ANDROID_ENABLED // Android trigger values are already between 0.0f and 1.0f.
1420 if (range == FULL_AXIS && (axis == JoyAxis::TRIGGER_LEFT || axis == JoyAxis::TRIGGER_RIGHT)) {
1421 // Convert to a value between 0.0f and 1.0f.
1422 value = 0.5f + value / 2.0f;
1423 }
1424 #endif
1425 _axis_event(p_device, axis, value);
1426 return;
1427 }
1428 }
1429
1430 void Input::joy_hat(int p_device, BitField<HatMask> p_val) {
1431 _THREAD_SAFE_METHOD_;
1432 const Joypad &joy = joy_names[p_device];
1433
1434 JoyEvent map[(size_t)HatDir::MAX];
1435
1436 map[(size_t)HatDir::UP].type = TYPE_BUTTON;
1437 map[(size_t)HatDir::UP].index = (int)JoyButton::DPAD_UP;
1438 map[(size_t)HatDir::UP].value = 0;
1439
1440 map[(size_t)HatDir::RIGHT].type = TYPE_BUTTON;
1441 map[(size_t)HatDir::RIGHT].index = (int)JoyButton::DPAD_RIGHT;
1442 map[(size_t)HatDir::RIGHT].value = 0;
1443
1444 map[(size_t)HatDir::DOWN].type = TYPE_BUTTON;
1445 map[(size_t)HatDir::DOWN].index = (int)JoyButton::DPAD_DOWN;
1446 map[(size_t)HatDir::DOWN].value = 0;
1447
1448 map[(size_t)HatDir::LEFT].type = TYPE_BUTTON;
1449 map[(size_t)HatDir::LEFT].index = (int)JoyButton::DPAD_LEFT;
1450 map[(size_t)HatDir::LEFT].value = 0;
1451
1452 if (joy.mapping != -1) {
1453 _get_mapped_hat_events(map_db[joy.mapping], (HatDir)0, map);
1454 }
1455
1456 int cur_val = joy_names[p_device].hat_current;
1457
1458 for (int hat_direction = 0, hat_mask = 1; hat_direction < (int)HatDir::MAX; hat_direction++, hat_mask <<= 1) {
1459 if (((int)p_val & hat_mask) != (cur_val & hat_mask)) {
1460 if (map[hat_direction].type == TYPE_BUTTON) {
1461 _button_event(p_device, (JoyButton)map[hat_direction].index, (int)p_val & hat_mask);
1462 }
1463 if (map[hat_direction].type == TYPE_AXIS) {
1464 _axis_event(p_device, (JoyAxis)map[hat_direction].index, ((int)p_val & hat_mask) ? map[hat_direction].value : 0.0);
1465 }
1466 }
1467 }
1468
1469 joy_names[p_device].hat_current = (int)p_val;
1470 }
1471
1472 void Input::_button_event(int p_device, JoyButton p_index, bool p_pressed) {
1473 Ref<InputEventJoypadButton> ievent;
1474 ievent.instantiate();
1475 ievent->set_device(p_device);
1476 ievent->set_button_index(p_index);
1477 ievent->set_pressed(p_pressed);
1478
1479 parse_input_event(ievent);
1480 }
1481
1482 void Input::_axis_event(int p_device, JoyAxis p_axis, float p_value) {
1483 Ref<InputEventJoypadMotion> ievent;
1484 ievent.instantiate();
1485 ievent->set_device(p_device);
1486 ievent->set_axis(p_axis);
1487 ievent->set_axis_value(p_value);
1488
1489 parse_input_event(ievent);
1490 }
1491
1492 void Input::_update_action_cache(const StringName &p_action_name, ActionState &r_action_state) {
1493 // Update the action cache, computed from the per-device and per-event states.
1494 r_action_state.cache.pressed = false;
1495 r_action_state.cache.strength = 0.0;
1496 r_action_state.cache.raw_strength = 0.0;
1497
1498 int max_event = InputMap::get_singleton()->action_get_events(p_action_name)->size() + 1; // +1 comes from InputEventAction.
1499 for (const KeyValue<int, ActionState::DeviceState> &kv : r_action_state.device_states) {
1500 const ActionState::DeviceState &device_state = kv.value;
1501 for (int i = 0; i < max_event; i++) {
1502 r_action_state.cache.pressed = r_action_state.cache.pressed || device_state.pressed[i];
1503 r_action_state.cache.strength = MAX(r_action_state.cache.strength, device_state.strength[i]);
1504 r_action_state.cache.raw_strength = MAX(r_action_state.cache.raw_strength, device_state.raw_strength[i]);
1505 }
1506 }
1507
1508 if (r_action_state.api_pressed) {
1509 r_action_state.cache.pressed = true;
1510 r_action_state.cache.strength = MAX(r_action_state.cache.strength, r_action_state.api_strength);
1511 r_action_state.cache.raw_strength = MAX(r_action_state.cache.raw_strength, r_action_state.api_strength); // Use the strength as raw_strength for API-pressed states.
1512 }
1513 }
1514
1515 void Input::_update_joypad_features(int p_device) {
1516 Joypad *joypad = joy_names.getptr(p_device);
1517 if (!joypad || joypad->features == nullptr) {
1518 return;
1519 }
1520 if (joypad->features->has_joy_light()) {
1521 joypad->has_light = true;
1522 }
1523 }
1524
1525 Input::JoyEvent Input::_get_mapped_button_event(const JoyDeviceMapping &mapping, JoyButton p_button) {
1526 JoyEvent event;
1527
1528 for (int i = 0; i < mapping.bindings.size(); i++) {
1529 const JoyBinding binding = mapping.bindings[i];
1530 if (binding.inputType == TYPE_BUTTON && binding.input.button == p_button) {
1531 event.type = binding.outputType;
1532 switch (binding.outputType) {
1533 case TYPE_BUTTON:
1534 event.index = (int)binding.output.button;
1535 return event;
1536 case TYPE_AXIS:
1537 event.index = (int)binding.output.axis.axis;
1538 switch (binding.output.axis.range) {
1539 case POSITIVE_HALF_AXIS:
1540 event.value = 1;
1541 break;
1542 case NEGATIVE_HALF_AXIS:
1543 event.value = -1;
1544 break;
1545 case FULL_AXIS:
1546 // It doesn't make sense for a button to map to a full axis,
1547 // but keeping as a default for a trigger with a positive half-axis.
1548 event.value = 1;
1549 break;
1550 }
1551 return event;
1552 default:
1553 ERR_PRINT_ONCE("Joypad button mapping error.");
1554 }
1555 }
1556 }
1557 return event;
1558 }
1559
1560 Input::JoyEvent Input::_get_mapped_axis_event(const JoyDeviceMapping &mapping, JoyAxis p_axis, float p_value, JoyAxisRange &r_range) {
1561 JoyEvent event;
1562
1563 for (int i = 0; i < mapping.bindings.size(); i++) {
1564 const JoyBinding binding = mapping.bindings[i];
1565 if (binding.inputType == TYPE_AXIS && binding.input.axis.axis == p_axis) {
1566 float value = p_value;
1567 if (binding.input.axis.invert) {
1568 value = -value;
1569 }
1570 if (binding.input.axis.range == FULL_AXIS ||
1571 (binding.input.axis.range == POSITIVE_HALF_AXIS && value >= 0) ||
1572 (binding.input.axis.range == NEGATIVE_HALF_AXIS && value < 0)) {
1573 event.type = binding.outputType;
1574 float shifted_positive_value = 0;
1575 switch (binding.input.axis.range) {
1576 case POSITIVE_HALF_AXIS:
1577 shifted_positive_value = value;
1578 break;
1579 case NEGATIVE_HALF_AXIS:
1580 shifted_positive_value = value + 1;
1581 break;
1582 case FULL_AXIS:
1583 shifted_positive_value = (value + 1) / 2;
1584 break;
1585 }
1586 switch (binding.outputType) {
1587 case TYPE_BUTTON:
1588 event.index = (int)binding.output.button;
1589 switch (binding.input.axis.range) {
1590 case POSITIVE_HALF_AXIS:
1591 event.value = shifted_positive_value;
1592 break;
1593 case NEGATIVE_HALF_AXIS:
1594 event.value = 1 - shifted_positive_value;
1595 break;
1596 case FULL_AXIS:
1597 // It doesn't make sense for a full axis to map to a button,
1598 // but keeping as a default for a trigger with a positive half-axis.
1599 event.value = (shifted_positive_value * 2) - 1;
1600 break;
1601 }
1602 return event;
1603 case TYPE_AXIS:
1604 event.index = (int)binding.output.axis.axis;
1605 event.value = value;
1606 r_range = binding.output.axis.range;
1607 if (binding.output.axis.range != binding.input.axis.range) {
1608 switch (binding.output.axis.range) {
1609 case POSITIVE_HALF_AXIS:
1610 event.value = shifted_positive_value;
1611 break;
1612 case NEGATIVE_HALF_AXIS:
1613 event.value = shifted_positive_value - 1;
1614 break;
1615 case FULL_AXIS:
1616 event.value = (shifted_positive_value * 2) - 1;
1617 break;
1618 }
1619 }
1620 return event;
1621 default:
1622 ERR_PRINT_ONCE("Joypad axis mapping error.");
1623 }
1624 }
1625 }
1626 }
1627 return event;
1628 }
1629
1630 void Input::_get_mapped_hat_events(const JoyDeviceMapping &mapping, HatDir p_hat, JoyEvent r_events[(size_t)HatDir::MAX]) {
1631 for (int i = 0; i < mapping.bindings.size(); i++) {
1632 const JoyBinding binding = mapping.bindings[i];
1633 if (binding.inputType == TYPE_HAT && binding.input.hat.hat == p_hat) {
1634 HatDir hat_direction;
1635 switch (binding.input.hat.hat_mask) {
1636 case HatMask::UP:
1637 hat_direction = HatDir::UP;
1638 break;
1639 case HatMask::RIGHT:
1640 hat_direction = HatDir::RIGHT;
1641 break;
1642 case HatMask::DOWN:
1643 hat_direction = HatDir::DOWN;
1644 break;
1645 case HatMask::LEFT:
1646 hat_direction = HatDir::LEFT;
1647 break;
1648 default:
1649 ERR_PRINT_ONCE("Joypad button mapping error.");
1650 continue;
1651 }
1652
1653 r_events[(size_t)hat_direction].type = binding.outputType;
1654 switch (binding.outputType) {
1655 case TYPE_BUTTON:
1656 r_events[(size_t)hat_direction].index = (int)binding.output.button;
1657 break;
1658 case TYPE_AXIS:
1659 r_events[(size_t)hat_direction].index = (int)binding.output.axis.axis;
1660 switch (binding.output.axis.range) {
1661 case POSITIVE_HALF_AXIS:
1662 r_events[(size_t)hat_direction].value = 1;
1663 break;
1664 case NEGATIVE_HALF_AXIS:
1665 r_events[(size_t)hat_direction].value = -1;
1666 break;
1667 case FULL_AXIS:
1668 // It doesn't make sense for a hat direction to map to a full axis,
1669 // but keeping as a default for a trigger with a positive half-axis.
1670 r_events[(size_t)hat_direction].value = 1;
1671 break;
1672 }
1673 break;
1674 default:
1675 ERR_PRINT_ONCE("Joypad button mapping error.");
1676 }
1677 }
1678 }
1679 }
1680
1681 JoyButton Input::_get_output_button(const String &output) {
1682 for (int i = 0; i < (int)JoyButton::SDL_MAX; i++) {
1683 if (output == _joy_buttons[i]) {
1684 return JoyButton(i);
1685 }
1686 }
1687 return JoyButton::INVALID;
1688 }
1689
1690 JoyAxis Input::_get_output_axis(const String &output) {
1691 for (int i = 0; i < (int)JoyAxis::SDL_MAX; i++) {
1692 if (output == _joy_axes[i]) {
1693 return JoyAxis(i);
1694 }
1695 }
1696 return JoyAxis::INVALID;
1697 }
1698
1699 void Input::parse_mapping(const String &p_mapping) {
1700 _THREAD_SAFE_METHOD_;
1701 JoyDeviceMapping mapping;
1702
1703 Vector<String> entry = p_mapping.split(",");
1704 if (entry.size() < 2) {
1705 return;
1706 }
1707
1708 mapping.uid = entry[0];
1709 mapping.name = entry[1];
1710
1711 int idx = 1;
1712 while (++idx < entry.size()) {
1713 if (entry[idx].is_empty()) {
1714 continue;
1715 }
1716
1717 String output = entry[idx].get_slicec(':', 0).remove_char(' ');
1718 String input = entry[idx].get_slicec(':', 1).remove_char(' ');
1719 if (output.length() < 1 || input.length() < 2) {
1720 continue;
1721 }
1722
1723 if (output == "platform" || output == "hint") {
1724 continue;
1725 }
1726
1727 JoyAxisRange output_range = FULL_AXIS;
1728 if (output[0] == '+' || output[0] == '-') {
1729 ERR_CONTINUE_MSG(output.length() < 2,
1730 vformat("Invalid output entry \"%s\" in mapping:\n%s", entry[idx], p_mapping));
1731 if (output[0] == '+') {
1732 output_range = POSITIVE_HALF_AXIS;
1733 } else if (output[0] == '-') {
1734 output_range = NEGATIVE_HALF_AXIS;
1735 }
1736 output = output.substr(1);
1737 }
1738
1739 JoyAxisRange input_range = FULL_AXIS;
1740 if (input[0] == '+') {
1741 input_range = POSITIVE_HALF_AXIS;
1742 input = input.substr(1);
1743 } else if (input[0] == '-') {
1744 input_range = NEGATIVE_HALF_AXIS;
1745 input = input.substr(1);
1746 }
1747 bool invert_axis = false;
1748 if (input[input.length() - 1] == '~') {
1749 invert_axis = true;
1750 input = input.left(input.length() - 1);
1751 }
1752
1753 JoyButton output_button = _get_output_button(output);
1754 JoyAxis output_axis = _get_output_axis(output);
1755 if (output_button == JoyButton::INVALID && output_axis == JoyAxis::INVALID) {
1756 print_verbose(vformat("Unrecognized output string \"%s\" in mapping:\n%s", output, p_mapping));
1757 continue;
1758 }
1759 ERR_CONTINUE_MSG(output_button != JoyButton::INVALID && output_axis != JoyAxis::INVALID,
1760 vformat("Output string \"%s\" matched both button and axis in mapping:\n%s", output, p_mapping));
1761
1762 JoyBinding binding;
1763 if (output_button != JoyButton::INVALID) {
1764 binding.outputType = TYPE_BUTTON;
1765 binding.output.button = output_button;
1766 } else if (output_axis != JoyAxis::INVALID) {
1767 binding.outputType = TYPE_AXIS;
1768 binding.output.axis.axis = output_axis;
1769 binding.output.axis.range = output_range;
1770 }
1771
1772 switch (input[0]) {
1773 case 'b':
1774 binding.inputType = TYPE_BUTTON;
1775 binding.input.button = (JoyButton)input.substr(1).to_int();
1776 break;
1777 case 'a':
1778 binding.inputType = TYPE_AXIS;
1779 binding.input.axis.axis = (JoyAxis)input.substr(1).to_int();
1780 binding.input.axis.range = input_range;
1781 binding.input.axis.invert = invert_axis;
1782 break;
1783 case 'h':
1784 ERR_CONTINUE_MSG(input.length() != 4 || input[2] != '.',
1785 vformat("Invalid had input \"%s\" in mapping:\n%s", input, p_mapping));
1786 binding.inputType = TYPE_HAT;
1787 binding.input.hat.hat = (HatDir)input.substr(1, 1).to_int();
1788 binding.input.hat.hat_mask = static_cast<HatMask>(input.substr(3).to_int());
1789 break;
1790 default:
1791 ERR_CONTINUE_MSG(true, vformat("Unrecognized input string \"%s\" in mapping:\n%s", input, p_mapping));
1792 }
1793
1794 mapping.bindings.push_back(binding);
1795 }
1796
1797 map_db.push_back(mapping);
1798 }
1799
1800 void Input::add_joy_mapping(const String &p_mapping, bool p_update_existing) {
1801 parse_mapping(p_mapping);
1802 if (p_update_existing) {
1803 const String uid = p_mapping.get_slicec(',', 0);
1804 for (KeyValue<int, Joypad> &E : joy_names) {
1805 Joypad &joy = E.value;
1806 if (joy.uid == uid) {
1807 _set_joypad_mapping(joy, map_db.size() - 1);
1808 }
1809 }
1810 }
1811 }
1812
1813 void Input::remove_joy_mapping(const String &p_guid) {
1814 // One GUID can exist multiple times in `map_db`, and
1815 // `add_joy_mapping` can choose not to update the existing mapping,
1816 // so the indices can be all over the place. Therefore we need to remember them.
1817 Vector<int> removed_idx;
1818 int min_removed_idx = -1;
1819 int max_removed_idx = -1;
1820 int fallback_mapping_offset = 0;
1821
1822 for (int i = map_db.size() - 1; i >= 0; i--) {
1823 if (p_guid == map_db[i].uid) {
1824 map_db.remove_at(i);
1825
1826 if (max_removed_idx == -1) {
1827 max_removed_idx = i;
1828 }
1829 min_removed_idx = i;
1830 removed_idx.push_back(i);
1831
1832 if (i < fallback_mapping) {
1833 fallback_mapping_offset++;
1834 } else if (i == fallback_mapping) {
1835 fallback_mapping = -1;
1836 WARN_PRINT_ONCE(vformat("Removed fallback joypad input mapping \"%s\". This could lead to joypads not working as intended.", p_guid));
1837 }
1838 }
1839 }
1840
1841 if (min_removed_idx == -1) {
1842 return; // Nothing removed.
1843 }
1844
1845 if (fallback_mapping > 0) {
1846 // Fix the shifted index.
1847 fallback_mapping -= fallback_mapping_offset;
1848 }
1849
1850 int removed_idx_size = removed_idx.size();
1851
1852 // Update joypad mapping references: some
1853 // * should use the fallback_mapping (if set; if not, they get unmapped), or
1854 // * need their mapping reference fixed, because the deletion(s) offset them.
1855 for (KeyValue<int, Joypad> &E : joy_names) {
1856 Joypad &joy = E.value;
1857 if (joy.mapping < min_removed_idx) {
1858 continue; // Not affected.
1859 }
1860
1861 if (joy.mapping > max_removed_idx) {
1862 _set_joypad_mapping(joy, joy.mapping - removed_idx_size);
1863 continue; // Simple offset fix.
1864 }
1865
1866 // removed_idx is in reverse order (ie. high to low), because the first loop is in reverse order.
1867 for (int i = 0; i < removed_idx.size(); i++) {
1868 if (removed_idx[i] == joy.mapping) {
1869 // Set to fallback_mapping, if defined, else unmap the joypad.
1870 // Currently, the fallback_mapping is only set internally, and only for Android.
1871 _set_joypad_mapping(joy, fallback_mapping);
1872 break;
1873 }
1874 if (removed_idx[i] < joy.mapping) {
1875 // Complex offset fix:
1876 // This mapping was shifted by `(removed_idx_size - i)` deletions.
1877 _set_joypad_mapping(joy, joy.mapping - (removed_idx_size - i));
1878 break;
1879 }
1880 }
1881 }
1882 }
1883
1884 void Input::_set_joypad_mapping(Joypad &p_js, int p_map_index) {
1885 if (p_map_index != fallback_mapping && p_map_index >= 0 && p_map_index < map_db.size() && p_js.uid != "__XINPUT_DEVICE__") {
1886 // Prefer the joypad name defined in the mapping.
1887 // Exceptions:
1888 // * On Windows for XInput devices the mapping would change the joypad's name to a collective name.
1889 // * A fallback mapping is not allowed to override the joypad's name.
1890 p_js.name = map_db[p_map_index].name;
1891 }
1892 p_js.mapping = p_map_index;
1893 }
1894
1895 void Input::set_fallback_mapping(const String &p_guid) {
1896 for (int i = 0; i < map_db.size(); i++) {
1897 if (map_db[i].uid == p_guid) {
1898 fallback_mapping = i;
1899 return;
1900 }
1901 }
1902 }
1903
1904 //platforms that use the remapping system can override and call to these ones
1905 bool Input::is_joy_known(int p_device) {
1906 return joy_names.has(p_device) && joy_names[p_device].is_known;
1907 }
1908
1909 String Input::get_joy_guid(int p_device) const {
1910 ERR_FAIL_COND_V(!joy_names.has(p_device), "");
1911 return joy_names[p_device].uid;
1912 }
1913
1914 Dictionary Input::get_joy_info(int p_device) const {
1915 ERR_FAIL_COND_V(!joy_names.has(p_device), Dictionary());
1916 return joy_names[p_device].info;
1917 }
1918
1919 bool Input::should_ignore_device(int p_vendor_id, int p_product_id) const {
1920 uint32_t full_id = (((uint32_t)p_vendor_id) << 16) | ((uint16_t)p_product_id);
1921 return ignored_device_ids.has(full_id);
1922 }
1923
1924 TypedArray<int> Input::get_connected_joypads() {
1925 TypedArray<int> ret;
1926 HashMap<int, Joypad>::Iterator elem = joy_names.begin();
1927 while (elem) {
1928 if (elem->value.connected) {
1929 ret.push_back(elem->key);
1930 }
1931 ++elem;
1932 }
1933 return ret;
1934 }
1935
1936 int Input::get_unused_joy_id() {
1937 for (int i = 0; i < JOYPADS_MAX; i++) {
1938 if (!joy_names.has(i) || !joy_names[i].connected) {
1939 return i;
1940 }
1941 }
1942 return -1;
1943 }
1944
1945 void Input::set_disable_input(bool p_disable) {
1946 disable_input = p_disable;
1947 }
1948
1949 bool Input::is_input_disabled() const {
1950 return disable_input;
1951 }
1952
1953 Input::Input() {
1954 singleton = this;
1955
1956 // Parse default mappings.
1957 {
1958 int i = 0;
1959 while (DefaultControllerMappings::mappings[i]) {
1960 parse_mapping(DefaultControllerMappings::mappings[i++]);
1961 }
1962 }
1963
1964 // If defined, parse SDL_GAMECONTROLLERCONFIG for possible new mappings/overrides.
1965 String env_mapping = OS::get_singleton()->get_environment("SDL_GAMECONTROLLERCONFIG");
1966 if (!env_mapping.is_empty()) {
1967 Vector<String> entries = env_mapping.split("\n");
1968 for (int i = 0; i < entries.size(); i++) {
1969 if (entries[i].is_empty()) {
1970 continue;
1971 }
1972 parse_mapping(entries[i]);
1973 }
1974 }
1975
1976 String env_ignore_devices = OS::get_singleton()->get_environment("SDL_GAMECONTROLLER_IGNORE_DEVICES");
1977 if (!env_ignore_devices.is_empty()) {
1978 Vector<String> entries = env_ignore_devices.split(",");
1979 for (int i = 0; i < entries.size(); i++) {
1980 Vector<String> vid_pid = entries[i].split("/");
1981
1982 if (vid_pid.size() < 2) {
1983 continue;
1984 }
1985
1986 print_verbose(vformat("Device Ignored -- Vendor: %s Product: %s", vid_pid[0], vid_pid[1]));
1987 const uint16_t vid_unswapped = vid_pid[0].hex_to_int();
1988 const uint16_t pid_unswapped = vid_pid[1].hex_to_int();
1989 const uint16_t vid = BSWAP16(vid_unswapped);
1990 const uint16_t pid = BSWAP16(pid_unswapped);
1991
1992 uint32_t full_id = (((uint32_t)vid) << 16) | ((uint16_t)pid);
1993 ignored_device_ids.insert(full_id);
1994 }
1995 }
1996
1997 legacy_just_pressed_behavior = GLOBAL_DEF("input_devices/compatibility/legacy_just_pressed_behavior", false);
1998 if (Engine::get_singleton()->is_editor_hint()) {
1999 // Always use standard behavior in the editor.
2000 legacy_just_pressed_behavior = false;
2001 }
2002
2003 accelerometer_enabled = GLOBAL_DEF_RST_BASIC("input_devices/sensors/enable_accelerometer", false);
2004 gravity_enabled = GLOBAL_DEF_RST_BASIC("input_devices/sensors/enable_gravity", false);
2005 gyroscope_enabled = GLOBAL_DEF_RST_BASIC("input_devices/sensors/enable_gyroscope", false);
2006 magnetometer_enabled = GLOBAL_DEF_RST_BASIC("input_devices/sensors/enable_magnetometer", false);
2007 }
2008
2009 Input::~Input() {
2010 singleton = nullptr;
2011 }
2012
2013 //////////////////////////////////////////////////////////