From 0b3496fb4f2acd8896d7db5becd4ba95694d0472 Mon Sep 17 00:00:00 2001 From: Nintorch <92302738+Nintorch@users.noreply.github.com> Date: Wed, 28 May 2025 14:22:20 +0500 Subject: [PATCH] Add support for SDL3 joystick input driver MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Made possible by EIREXE, xsellier and the SDL team. This commit includes statically linked SDL3 for Windows, Linux and macOS. The vendored copy of SDL3 was setup to only build the required subsystems for gamepad/joystick support, with some patches to be able to make it as minimal as possible and reduce the impact on binary size and code size. Co-authored-by: Álex Román Núñez Co-authored-by: Xavier Sellier Co-authored-by: Rémi Verschelde --- COPYRIGHT.txt | 10 + SConstruct | 10 +- core/input/input.cpp | 10 +- drivers/SCsub | 5 + drivers/sdl/SCsub | 209 + drivers/sdl/SDL_build_config_private.h | 130 + drivers/sdl/joypad_sdl.cpp | 273 + drivers/sdl/joypad_sdl.h | 69 + platform/linuxbsd/SCsub | 1 - platform/linuxbsd/detect.py | 12 + platform/linuxbsd/joypad_linux.cpp | 613 -- platform/linuxbsd/joypad_linux.h | 136 - platform/linuxbsd/os_linuxbsd.cpp | 24 +- platform/linuxbsd/os_linuxbsd.h | 7 +- platform/linuxbsd/x11/display_server_x11.h | 2 - platform/macos/detect.py | 4 + platform/macos/os_macos.h | 7 +- platform/macos/os_macos.mm | 25 +- platform/windows/SCsub | 1 - platform/windows/detect.py | 6 + platform/windows/display_server_windows.cpp | 30 +- platform/windows/display_server_windows.h | 7 +- platform/windows/drop_target_windows.cpp | 1 + platform/windows/joypad_windows.cpp | 625 -- platform/windows/joypad_windows.h | 149 - platform/windows/os_windows.cpp | 1 - platform/windows/os_windows.h | 10 +- thirdparty/README.md | 33 + thirdparty/sdl/CREDITS.md | 38 + thirdparty/sdl/LICENSE.txt | 18 + thirdparty/sdl/SDL.c | 841 +++ thirdparty/sdl/SDL_assert.c | 443 ++ thirdparty/sdl/SDL_assert_c.h | 28 + thirdparty/sdl/SDL_error.c | 112 + thirdparty/sdl/SDL_error_c.h | 61 + thirdparty/sdl/SDL_guid.c | 88 + thirdparty/sdl/SDL_hashtable.c | 543 ++ thirdparty/sdl/SDL_hashtable.h | 633 ++ thirdparty/sdl/SDL_hints.c | 403 + thirdparty/sdl/SDL_hints_c.h | 33 + thirdparty/sdl/SDL_internal.h | 289 + thirdparty/sdl/SDL_list.c | 86 + thirdparty/sdl/SDL_list.h | 36 + thirdparty/sdl/SDL_log.c | 805 ++ thirdparty/sdl/SDL_log_c.h | 31 + thirdparty/sdl/SDL_properties.c | 824 +++ thirdparty/sdl/SDL_properties_c.h | 26 + thirdparty/sdl/SDL_utils.c | 554 ++ thirdparty/sdl/SDL_utils_c.h | 78 + thirdparty/sdl/atomic/SDL_atomic.c | 382 + thirdparty/sdl/atomic/SDL_spinlock.c | 203 + thirdparty/sdl/core/linux/SDL_dbus.c | 641 ++ thirdparty/sdl/core/linux/SDL_dbus.h | 114 + thirdparty/sdl/core/linux/SDL_evdev.c | 1037 +++ thirdparty/sdl/core/linux/SDL_evdev.h | 41 + .../sdl/core/linux/SDL_evdev_capabilities.c | 168 + .../sdl/core/linux/SDL_evdev_capabilities.h | 76 + thirdparty/sdl/core/linux/SDL_evdev_kbd.c | 997 +++ thirdparty/sdl/core/linux/SDL_evdev_kbd.h | 35 + .../linux/SDL_evdev_kbd_default_accents.h | 282 + .../core/linux/SDL_evdev_kbd_default_keymap.h | 4765 ++++++++++++ thirdparty/sdl/core/linux/SDL_fcitx.c | 414 ++ thirdparty/sdl/core/linux/SDL_fcitx.h | 35 + thirdparty/sdl/core/linux/SDL_ibus.c | 694 ++ thirdparty/sdl/core/linux/SDL_ibus.h | 55 + thirdparty/sdl/core/linux/SDL_ime.c | 150 + thirdparty/sdl/core/linux/SDL_ime.h | 35 + thirdparty/sdl/core/linux/SDL_system_theme.c | 156 + thirdparty/sdl/core/linux/SDL_system_theme.h | 30 + thirdparty/sdl/core/linux/SDL_threadprio.c | 345 + thirdparty/sdl/core/linux/SDL_udev.c | 596 ++ thirdparty/sdl/core/linux/SDL_udev.h | 113 + thirdparty/sdl/core/unix/SDL_appid.c | 75 + thirdparty/sdl/core/unix/SDL_appid.h | 30 + thirdparty/sdl/core/unix/SDL_poll.c | 95 + thirdparty/sdl/core/unix/SDL_poll.h | 33 + thirdparty/sdl/core/windows/SDL_directx.h | 112 + thirdparty/sdl/core/windows/SDL_gameinput.c | 98 + thirdparty/sdl/core/windows/SDL_gameinput.h | 36 + thirdparty/sdl/core/windows/SDL_hid.c | 254 + thirdparty/sdl/core/windows/SDL_hid.h | 215 + thirdparty/sdl/core/windows/SDL_immdevice.c | 434 ++ thirdparty/sdl/core/windows/SDL_immdevice.h | 45 + thirdparty/sdl/core/windows/SDL_windows.c | 375 + thirdparty/sdl/core/windows/SDL_windows.h | 172 + thirdparty/sdl/core/windows/SDL_xinput.c | 140 + thirdparty/sdl/core/windows/SDL_xinput.h | 276 + thirdparty/sdl/core/windows/pch.c | 21 + thirdparty/sdl/core/windows/pch_cpp.cpp | 21 + thirdparty/sdl/events/SDL_events.c | 1833 +++++ thirdparty/sdl/events/SDL_events_c.h | 59 + thirdparty/sdl/events/SDL_eventwatch.c | 143 + thirdparty/sdl/events/SDL_eventwatch_c.h | 45 + thirdparty/sdl/events/SDL_mouse_c.h | 215 + thirdparty/sdl/haptic/SDL_haptic.c | 788 ++ thirdparty/sdl/haptic/SDL_haptic_c.h | 28 + thirdparty/sdl/haptic/SDL_syshaptic.h | 194 + thirdparty/sdl/haptic/darwin/SDL_syshaptic.c | 1373 ++++ .../sdl/haptic/darwin/SDL_syshaptic_c.h | 29 + thirdparty/sdl/haptic/linux/SDL_syshaptic.c | 1134 +++ .../sdl/haptic/windows/SDL_dinputhaptic.c | 1244 ++++ .../sdl/haptic/windows/SDL_dinputhaptic_c.h | 53 + .../sdl/haptic/windows/SDL_windowshaptic.c | 369 + .../sdl/haptic/windows/SDL_windowshaptic_c.h | 87 + thirdparty/sdl/hidapi/AUTHORS.txt | 18 + thirdparty/sdl/hidapi/LICENSE-bsd.txt | 26 + thirdparty/sdl/hidapi/LICENSE.txt | 13 + thirdparty/sdl/hidapi/SDL_hidapi.c | 1752 +++++ thirdparty/sdl/hidapi/SDL_hidapi_android.h | 26 + thirdparty/sdl/hidapi/SDL_hidapi_c.h | 35 + thirdparty/sdl/hidapi/SDL_hidapi_ios.h | 26 + thirdparty/sdl/hidapi/SDL_hidapi_libusb.h | 134 + thirdparty/sdl/hidapi/SDL_hidapi_linux.h | 47 + thirdparty/sdl/hidapi/SDL_hidapi_mac.h | 25 + thirdparty/sdl/hidapi/SDL_hidapi_netbsd.h | 25 + thirdparty/sdl/hidapi/SDL_hidapi_steamxbox.h | 23 + thirdparty/sdl/hidapi/SDL_hidapi_windows.h | 86 + thirdparty/sdl/hidapi/VERSION | 1 + thirdparty/sdl/hidapi/hidapi/hidapi.h | 634 ++ thirdparty/sdl/hidapi/linux/hid.c | 1492 ++++ thirdparty/sdl/hidapi/mac/hid.c | 1594 ++++ thirdparty/sdl/hidapi/mac/hidapi_darwin.h | 98 + thirdparty/sdl/hidapi/windows/hid.c | 1728 +++++ .../sdl/hidapi/windows/hidapi_cfgmgr32.h | 86 + .../windows/hidapi_descriptor_reconstruct.c | 990 +++ .../windows/hidapi_descriptor_reconstruct.h | 254 + .../sdl/hidapi/windows/hidapi_hidclass.h | 40 + thirdparty/sdl/hidapi/windows/hidapi_hidpi.h | 72 + thirdparty/sdl/hidapi/windows/hidapi_hidsdi.h | 59 + thirdparty/sdl/hidapi/windows/hidapi_winapi.h | 74 + thirdparty/sdl/include/SDL3/SDL.h | 90 + thirdparty/sdl/include/SDL3/SDL_assert.h | 662 ++ thirdparty/sdl/include/SDL3/SDL_asyncio.h | 546 ++ thirdparty/sdl/include/SDL3/SDL_atomic.h | 664 ++ thirdparty/sdl/include/SDL3/SDL_audio.h | 2200 ++++++ thirdparty/sdl/include/SDL3/SDL_begin_code.h | 486 ++ thirdparty/sdl/include/SDL3/SDL_bits.h | 147 + thirdparty/sdl/include/SDL3/SDL_blendmode.h | 202 + thirdparty/sdl/include/SDL3/SDL_camera.h | 519 ++ thirdparty/sdl/include/SDL3/SDL_clipboard.h | 331 + thirdparty/sdl/include/SDL3/SDL_close_code.h | 41 + thirdparty/sdl/include/SDL3/SDL_copying.h | 22 + thirdparty/sdl/include/SDL3/SDL_cpuinfo.h | 353 + thirdparty/sdl/include/SDL3/SDL_dialog.h | 341 + thirdparty/sdl/include/SDL3/SDL_endian.h | 645 ++ thirdparty/sdl/include/SDL3/SDL_error.h | 226 + thirdparty/sdl/include/SDL3/SDL_events.h | 1576 ++++ thirdparty/sdl/include/SDL3/SDL_filesystem.h | 503 ++ thirdparty/sdl/include/SDL3/SDL_gamepad.h | 1509 ++++ thirdparty/sdl/include/SDL3/SDL_guid.h | 106 + thirdparty/sdl/include/SDL3/SDL_haptic.h | 1441 ++++ thirdparty/sdl/include/SDL3/SDL_hidapi.h | 552 ++ thirdparty/sdl/include/SDL3/SDL_hints.h | 4486 ++++++++++++ thirdparty/sdl/include/SDL3/SDL_init.h | 497 ++ thirdparty/sdl/include/SDL3/SDL_intrin.h | 407 ++ thirdparty/sdl/include/SDL3/SDL_iostream.h | 1354 ++++ thirdparty/sdl/include/SDL3/SDL_joystick.h | 1202 +++ thirdparty/sdl/include/SDL3/SDL_keyboard.h | 609 ++ thirdparty/sdl/include/SDL3/SDL_keycode.h | 343 + thirdparty/sdl/include/SDL3/SDL_loadso.h | 145 + thirdparty/sdl/include/SDL3/SDL_locale.h | 117 + thirdparty/sdl/include/SDL3/SDL_log.h | 538 ++ thirdparty/sdl/include/SDL3/SDL_main.h | 675 ++ thirdparty/sdl/include/SDL3/SDL_main_impl.h | 151 + thirdparty/sdl/include/SDL3/SDL_messagebox.h | 226 + thirdparty/sdl/include/SDL3/SDL_metal.h | 107 + thirdparty/sdl/include/SDL3/SDL_misc.h | 78 + thirdparty/sdl/include/SDL3/SDL_mouse.h | 689 ++ thirdparty/sdl/include/SDL3/SDL_mutex.h | 1073 +++ thirdparty/sdl/include/SDL3/SDL_pen.h | 127 + thirdparty/sdl/include/SDL3/SDL_pixels.h | 1441 ++++ thirdparty/sdl/include/SDL3/SDL_platform.h | 64 + .../sdl/include/SDL3/SDL_platform_defines.h | 476 ++ thirdparty/sdl/include/SDL3/SDL_power.h | 106 + thirdparty/sdl/include/SDL3/SDL_process.h | 430 ++ thirdparty/sdl/include/SDL3/SDL_properties.h | 543 ++ thirdparty/sdl/include/SDL3/SDL_rect.h | 507 ++ thirdparty/sdl/include/SDL3/SDL_render.h | 2645 +++++++ thirdparty/sdl/include/SDL3/SDL_revision.h | 56 + thirdparty/sdl/include/SDL3/SDL_scancode.h | 429 ++ thirdparty/sdl/include/SDL3/SDL_sensor.h | 320 + thirdparty/sdl/include/SDL3/SDL_stdinc.h | 6137 ++++++++++++++++ thirdparty/sdl/include/SDL3/SDL_storage.h | 682 ++ thirdparty/sdl/include/SDL3/SDL_surface.h | 1563 ++++ thirdparty/sdl/include/SDL3/SDL_system.h | 818 +++ thirdparty/sdl/include/SDL3/SDL_thread.h | 578 ++ thirdparty/sdl/include/SDL3/SDL_time.h | 231 + thirdparty/sdl/include/SDL3/SDL_timer.h | 450 ++ thirdparty/sdl/include/SDL3/SDL_touch.h | 184 + thirdparty/sdl/include/SDL3/SDL_tray.h | 544 ++ thirdparty/sdl/include/SDL3/SDL_version.h | 183 + thirdparty/sdl/include/SDL3/SDL_video.h | 3298 +++++++++ .../include/build_config/SDL_build_config.h | 57 + thirdparty/sdl/io/SDL_iostream.c | 1657 +++++ thirdparty/sdl/io/SDL_iostream_c.h | 35 + thirdparty/sdl/joystick/SDL_gamepad.c | 3915 ++++++++++ thirdparty/sdl/joystick/SDL_gamepad_c.h | 50 + thirdparty/sdl/joystick/SDL_gamepad_db.h | 913 +++ thirdparty/sdl/joystick/SDL_joystick.c | 3797 ++++++++++ thirdparty/sdl/joystick/SDL_joystick_c.h | 270 + .../sdl/joystick/SDL_steam_virtual_gamepad.c | 254 + .../sdl/joystick/SDL_steam_virtual_gamepad.h | 36 + thirdparty/sdl/joystick/SDL_sysjoystick.h | 272 + .../sdl/joystick/apple/SDL_mfijoystick.m | 1946 +++++ .../sdl/joystick/apple/SDL_mfijoystick_c.h | 73 + thirdparty/sdl/joystick/controller_list.h | 609 ++ thirdparty/sdl/joystick/controller_type.c | 140 + thirdparty/sdl/joystick/controller_type.h | 78 + .../sdl/joystick/darwin/SDL_iokitjoystick.c | 1089 +++ .../sdl/joystick/darwin/SDL_iokitjoystick_c.h | 80 + .../sdl/joystick/hidapi/SDL_hidapi_combined.c | 236 + .../sdl/joystick/hidapi/SDL_hidapi_gamecube.c | 534 ++ .../sdl/joystick/hidapi/SDL_hidapi_luna.c | 421 ++ .../sdl/joystick/hidapi/SDL_hidapi_nintendo.h | 49 + .../sdl/joystick/hidapi/SDL_hidapi_ps3.c | 1446 ++++ .../sdl/joystick/hidapi/SDL_hidapi_ps4.c | 1390 ++++ .../sdl/joystick/hidapi/SDL_hidapi_ps5.c | 1624 ++++ .../sdl/joystick/hidapi/SDL_hidapi_rumble.c | 285 + .../sdl/joystick/hidapi/SDL_hidapi_rumble.h | 42 + .../sdl/joystick/hidapi/SDL_hidapi_shield.c | 578 ++ .../sdl/joystick/hidapi/SDL_hidapi_stadia.c | 324 + .../sdl/joystick/hidapi/SDL_hidapi_steam.c | 1534 ++++ .../joystick/hidapi/SDL_hidapi_steam_hori.c | 415 ++ .../joystick/hidapi/SDL_hidapi_steamdeck.c | 451 ++ .../sdl/joystick/hidapi/SDL_hidapi_switch.c | 2859 ++++++++ .../sdl/joystick/hidapi/SDL_hidapi_wii.c | 1617 ++++ .../sdl/joystick/hidapi/SDL_hidapi_xbox360.c | 379 + .../sdl/joystick/hidapi/SDL_hidapi_xbox360w.c | 388 + .../sdl/joystick/hidapi/SDL_hidapi_xboxone.c | 1675 +++++ .../sdl/joystick/hidapi/SDL_hidapijoystick.c | 1734 +++++ .../joystick/hidapi/SDL_hidapijoystick_c.h | 195 + .../hidapi/steam/controller_constants.h | 582 ++ .../hidapi/steam/controller_structs.h | 463 ++ .../sdl/joystick/linux/SDL_sysjoystick.c | 2730 +++++++ .../sdl/joystick/linux/SDL_sysjoystick_c.h | 117 + thirdparty/sdl/joystick/usb_ids.h | 195 + .../sdl/joystick/windows/SDL_dinputjoystick.c | 1207 +++ .../joystick/windows/SDL_dinputjoystick_c.h | 40 + .../joystick/windows/SDL_rawinputjoystick.c | 2242 ++++++ .../joystick/windows/SDL_rawinputjoystick_c.h | 32 + .../windows/SDL_windows_gaming_input.c | 1039 +++ .../joystick/windows/SDL_windowsjoystick.c | 693 ++ .../joystick/windows/SDL_windowsjoystick_c.h | 103 + .../sdl/joystick/windows/SDL_xinputjoystick.c | 473 ++ .../joystick/windows/SDL_xinputjoystick_c.h | 44 + thirdparty/sdl/libm/e_atan2.c | 135 + thirdparty/sdl/libm/e_exp.c | 201 + thirdparty/sdl/libm/e_fmod.c | 145 + thirdparty/sdl/libm/e_log.c | 153 + thirdparty/sdl/libm/e_log10.c | 107 + thirdparty/sdl/libm/e_pow.c | 348 + thirdparty/sdl/libm/e_rem_pio2.c | 162 + thirdparty/sdl/libm/e_sqrt.c | 458 ++ thirdparty/sdl/libm/k_cos.c | 83 + thirdparty/sdl/libm/k_rem_pio2.c | 315 + thirdparty/sdl/libm/k_sin.c | 66 + thirdparty/sdl/libm/k_tan.c | 119 + thirdparty/sdl/libm/math_libm.h | 50 + thirdparty/sdl/libm/math_private.h | 234 + thirdparty/sdl/libm/s_atan.c | 119 + thirdparty/sdl/libm/s_copysign.c | 30 + thirdparty/sdl/libm/s_cos.c | 74 + thirdparty/sdl/libm/s_fabs.c | 30 + thirdparty/sdl/libm/s_floor.c | 76 + thirdparty/sdl/libm/s_isinf.c | 24 + thirdparty/sdl/libm/s_isinff.c | 24 + thirdparty/sdl/libm/s_isnan.c | 31 + thirdparty/sdl/libm/s_isnanf.c | 33 + thirdparty/sdl/libm/s_modf.c | 68 + thirdparty/sdl/libm/s_scalbn.c | 74 + thirdparty/sdl/libm/s_sin.c | 74 + thirdparty/sdl/libm/s_tan.c | 68 + thirdparty/sdl/loadso/dlopen/SDL_sysloadso.c | 82 + .../0001-remove-unnecessary-subsystems.patch | 917 +++ .../0002-msvc-constants-fpstrict.patch | 41 + thirdparty/sdl/sensor/SDL_sensor.c | 622 ++ thirdparty/sdl/sensor/SDL_sensor_c.h | 59 + thirdparty/sdl/sensor/SDL_syssensor.h | 110 + thirdparty/sdl/sensor/dummy/SDL_dummysensor.c | 93 + thirdparty/sdl/sensor/dummy/SDL_dummysensor.h | 21 + thirdparty/sdl/stdlib/SDL_casefolding.h | 2769 +++++++ thirdparty/sdl/stdlib/SDL_crc16.c | 52 + thirdparty/sdl/stdlib/SDL_crc32.c | 50 + thirdparty/sdl/stdlib/SDL_getenv.c | 601 ++ thirdparty/sdl/stdlib/SDL_getenv_c.h | 24 + thirdparty/sdl/stdlib/SDL_iconv.c | 860 +++ thirdparty/sdl/stdlib/SDL_malloc.c | 6507 +++++++++++++++++ thirdparty/sdl/stdlib/SDL_memcpy.c | 101 + thirdparty/sdl/stdlib/SDL_memmove.c | 73 + thirdparty/sdl/stdlib/SDL_memset.c | 139 + thirdparty/sdl/stdlib/SDL_mslibc.c | 746 ++ thirdparty/sdl/stdlib/SDL_murmur3.c | 87 + thirdparty/sdl/stdlib/SDL_qsort.c | 574 ++ thirdparty/sdl/stdlib/SDL_random.c | 115 + thirdparty/sdl/stdlib/SDL_stdlib.c | 573 ++ thirdparty/sdl/stdlib/SDL_string.c | 2511 +++++++ thirdparty/sdl/stdlib/SDL_strtokr.c | 95 + thirdparty/sdl/stdlib/SDL_sysstdlib.h | 32 + thirdparty/sdl/stdlib/SDL_vacopy.h | 30 + thirdparty/sdl/thread/SDL_systhread.h | 77 + thirdparty/sdl/thread/SDL_thread.c | 584 ++ thirdparty/sdl/thread/SDL_thread_c.h | 92 + thirdparty/sdl/thread/generic/SDL_syscond.c | 216 + thirdparty/sdl/thread/generic/SDL_syscond_c.h | 36 + thirdparty/sdl/thread/generic/SDL_sysrwlock.c | 194 + .../sdl/thread/generic/SDL_sysrwlock_c.h | 38 + thirdparty/sdl/thread/generic/SDL_syssem.c | 183 + thirdparty/sdl/thread/generic/SDL_systhread.c | 57 + .../sdl/thread/generic/SDL_systhread_c.h | 24 + thirdparty/sdl/thread/pthread/SDL_syscond.c | 128 + thirdparty/sdl/thread/pthread/SDL_sysmutex.c | 154 + .../sdl/thread/pthread/SDL_sysmutex_c.h | 40 + thirdparty/sdl/thread/pthread/SDL_sysrwlock.c | 113 + thirdparty/sdl/thread/pthread/SDL_syssem.c | 160 + thirdparty/sdl/thread/pthread/SDL_systhread.c | 293 + .../sdl/thread/pthread/SDL_systhread_c.h | 25 + thirdparty/sdl/thread/pthread/SDL_systls.c | 78 + .../sdl/thread/windows/SDL_syscond_cv.c | 226 + thirdparty/sdl/thread/windows/SDL_sysmutex.c | 238 + .../sdl/thread/windows/SDL_sysmutex_c.h | 73 + .../sdl/thread/windows/SDL_sysrwlock_srw.c | 231 + thirdparty/sdl/thread/windows/SDL_syssem.c | 351 + thirdparty/sdl/thread/windows/SDL_systhread.c | 197 + .../sdl/thread/windows/SDL_systhread_c.h | 30 + thirdparty/sdl/thread/windows/SDL_systls.c | 81 + thirdparty/sdl/timer/SDL_timer.c | 734 ++ thirdparty/sdl/timer/SDL_timer_c.h | 39 + thirdparty/sdl/timer/unix/SDL_systimer.c | 188 + thirdparty/sdl/timer/windows/SDL_systimer.c | 133 + thirdparty/sdl/update-sdl.sh | 87 + 330 files changed, 154930 insertions(+), 1561 deletions(-) create mode 100644 drivers/sdl/SCsub create mode 100644 drivers/sdl/SDL_build_config_private.h create mode 100644 drivers/sdl/joypad_sdl.cpp create mode 100644 drivers/sdl/joypad_sdl.h delete mode 100644 platform/linuxbsd/joypad_linux.cpp delete mode 100644 platform/linuxbsd/joypad_linux.h delete mode 100644 platform/windows/joypad_windows.cpp delete mode 100644 platform/windows/joypad_windows.h create mode 100644 thirdparty/sdl/CREDITS.md create mode 100644 thirdparty/sdl/LICENSE.txt create mode 100644 thirdparty/sdl/SDL.c create mode 100644 thirdparty/sdl/SDL_assert.c create mode 100644 thirdparty/sdl/SDL_assert_c.h create mode 100644 thirdparty/sdl/SDL_error.c create mode 100644 thirdparty/sdl/SDL_error_c.h create mode 100644 thirdparty/sdl/SDL_guid.c create mode 100644 thirdparty/sdl/SDL_hashtable.c create mode 100644 thirdparty/sdl/SDL_hashtable.h create mode 100644 thirdparty/sdl/SDL_hints.c create mode 100644 thirdparty/sdl/SDL_hints_c.h create mode 100644 thirdparty/sdl/SDL_internal.h create mode 100644 thirdparty/sdl/SDL_list.c create mode 100644 thirdparty/sdl/SDL_list.h create mode 100644 thirdparty/sdl/SDL_log.c create mode 100644 thirdparty/sdl/SDL_log_c.h create mode 100644 thirdparty/sdl/SDL_properties.c create mode 100644 thirdparty/sdl/SDL_properties_c.h create mode 100644 thirdparty/sdl/SDL_utils.c create mode 100644 thirdparty/sdl/SDL_utils_c.h create mode 100644 thirdparty/sdl/atomic/SDL_atomic.c create mode 100644 thirdparty/sdl/atomic/SDL_spinlock.c create mode 100644 thirdparty/sdl/core/linux/SDL_dbus.c create mode 100644 thirdparty/sdl/core/linux/SDL_dbus.h create mode 100644 thirdparty/sdl/core/linux/SDL_evdev.c create mode 100644 thirdparty/sdl/core/linux/SDL_evdev.h create mode 100644 thirdparty/sdl/core/linux/SDL_evdev_capabilities.c create mode 100644 thirdparty/sdl/core/linux/SDL_evdev_capabilities.h create mode 100644 thirdparty/sdl/core/linux/SDL_evdev_kbd.c create mode 100644 thirdparty/sdl/core/linux/SDL_evdev_kbd.h create mode 100644 thirdparty/sdl/core/linux/SDL_evdev_kbd_default_accents.h create mode 100644 thirdparty/sdl/core/linux/SDL_evdev_kbd_default_keymap.h create mode 100644 thirdparty/sdl/core/linux/SDL_fcitx.c create mode 100644 thirdparty/sdl/core/linux/SDL_fcitx.h create mode 100644 thirdparty/sdl/core/linux/SDL_ibus.c create mode 100644 thirdparty/sdl/core/linux/SDL_ibus.h create mode 100644 thirdparty/sdl/core/linux/SDL_ime.c create mode 100644 thirdparty/sdl/core/linux/SDL_ime.h create mode 100644 thirdparty/sdl/core/linux/SDL_system_theme.c create mode 100644 thirdparty/sdl/core/linux/SDL_system_theme.h create mode 100644 thirdparty/sdl/core/linux/SDL_threadprio.c create mode 100644 thirdparty/sdl/core/linux/SDL_udev.c create mode 100644 thirdparty/sdl/core/linux/SDL_udev.h create mode 100644 thirdparty/sdl/core/unix/SDL_appid.c create mode 100644 thirdparty/sdl/core/unix/SDL_appid.h create mode 100644 thirdparty/sdl/core/unix/SDL_poll.c create mode 100644 thirdparty/sdl/core/unix/SDL_poll.h create mode 100644 thirdparty/sdl/core/windows/SDL_directx.h create mode 100644 thirdparty/sdl/core/windows/SDL_gameinput.c create mode 100644 thirdparty/sdl/core/windows/SDL_gameinput.h create mode 100644 thirdparty/sdl/core/windows/SDL_hid.c create mode 100644 thirdparty/sdl/core/windows/SDL_hid.h create mode 100644 thirdparty/sdl/core/windows/SDL_immdevice.c create mode 100644 thirdparty/sdl/core/windows/SDL_immdevice.h create mode 100644 thirdparty/sdl/core/windows/SDL_windows.c create mode 100644 thirdparty/sdl/core/windows/SDL_windows.h create mode 100644 thirdparty/sdl/core/windows/SDL_xinput.c create mode 100644 thirdparty/sdl/core/windows/SDL_xinput.h create mode 100644 thirdparty/sdl/core/windows/pch.c create mode 100644 thirdparty/sdl/core/windows/pch_cpp.cpp create mode 100644 thirdparty/sdl/events/SDL_events.c create mode 100644 thirdparty/sdl/events/SDL_events_c.h create mode 100644 thirdparty/sdl/events/SDL_eventwatch.c create mode 100644 thirdparty/sdl/events/SDL_eventwatch_c.h create mode 100644 thirdparty/sdl/events/SDL_mouse_c.h create mode 100644 thirdparty/sdl/haptic/SDL_haptic.c create mode 100644 thirdparty/sdl/haptic/SDL_haptic_c.h create mode 100644 thirdparty/sdl/haptic/SDL_syshaptic.h create mode 100644 thirdparty/sdl/haptic/darwin/SDL_syshaptic.c create mode 100644 thirdparty/sdl/haptic/darwin/SDL_syshaptic_c.h create mode 100644 thirdparty/sdl/haptic/linux/SDL_syshaptic.c create mode 100644 thirdparty/sdl/haptic/windows/SDL_dinputhaptic.c create mode 100644 thirdparty/sdl/haptic/windows/SDL_dinputhaptic_c.h create mode 100644 thirdparty/sdl/haptic/windows/SDL_windowshaptic.c create mode 100644 thirdparty/sdl/haptic/windows/SDL_windowshaptic_c.h create mode 100644 thirdparty/sdl/hidapi/AUTHORS.txt create mode 100644 thirdparty/sdl/hidapi/LICENSE-bsd.txt create mode 100644 thirdparty/sdl/hidapi/LICENSE.txt create mode 100644 thirdparty/sdl/hidapi/SDL_hidapi.c create mode 100644 thirdparty/sdl/hidapi/SDL_hidapi_android.h create mode 100644 thirdparty/sdl/hidapi/SDL_hidapi_c.h create mode 100644 thirdparty/sdl/hidapi/SDL_hidapi_ios.h create mode 100644 thirdparty/sdl/hidapi/SDL_hidapi_libusb.h create mode 100644 thirdparty/sdl/hidapi/SDL_hidapi_linux.h create mode 100644 thirdparty/sdl/hidapi/SDL_hidapi_mac.h create mode 100644 thirdparty/sdl/hidapi/SDL_hidapi_netbsd.h create mode 100644 thirdparty/sdl/hidapi/SDL_hidapi_steamxbox.h create mode 100644 thirdparty/sdl/hidapi/SDL_hidapi_windows.h create mode 100644 thirdparty/sdl/hidapi/VERSION create mode 100644 thirdparty/sdl/hidapi/hidapi/hidapi.h create mode 100644 thirdparty/sdl/hidapi/linux/hid.c create mode 100644 thirdparty/sdl/hidapi/mac/hid.c create mode 100644 thirdparty/sdl/hidapi/mac/hidapi_darwin.h create mode 100644 thirdparty/sdl/hidapi/windows/hid.c create mode 100644 thirdparty/sdl/hidapi/windows/hidapi_cfgmgr32.h create mode 100644 thirdparty/sdl/hidapi/windows/hidapi_descriptor_reconstruct.c create mode 100644 thirdparty/sdl/hidapi/windows/hidapi_descriptor_reconstruct.h create mode 100644 thirdparty/sdl/hidapi/windows/hidapi_hidclass.h create mode 100644 thirdparty/sdl/hidapi/windows/hidapi_hidpi.h create mode 100644 thirdparty/sdl/hidapi/windows/hidapi_hidsdi.h create mode 100644 thirdparty/sdl/hidapi/windows/hidapi_winapi.h create mode 100644 thirdparty/sdl/include/SDL3/SDL.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_assert.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_asyncio.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_atomic.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_audio.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_begin_code.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_bits.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_blendmode.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_camera.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_clipboard.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_close_code.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_copying.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_cpuinfo.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_dialog.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_endian.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_error.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_events.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_filesystem.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_gamepad.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_guid.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_haptic.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_hidapi.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_hints.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_init.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_intrin.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_iostream.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_joystick.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_keyboard.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_keycode.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_loadso.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_locale.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_log.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_main.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_main_impl.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_messagebox.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_metal.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_misc.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_mouse.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_mutex.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_pen.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_pixels.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_platform.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_platform_defines.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_power.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_process.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_properties.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_rect.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_render.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_revision.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_scancode.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_sensor.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_stdinc.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_storage.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_surface.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_system.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_thread.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_time.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_timer.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_touch.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_tray.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_version.h create mode 100644 thirdparty/sdl/include/SDL3/SDL_video.h create mode 100644 thirdparty/sdl/include/build_config/SDL_build_config.h create mode 100644 thirdparty/sdl/io/SDL_iostream.c create mode 100644 thirdparty/sdl/io/SDL_iostream_c.h create mode 100644 thirdparty/sdl/joystick/SDL_gamepad.c create mode 100644 thirdparty/sdl/joystick/SDL_gamepad_c.h create mode 100644 thirdparty/sdl/joystick/SDL_gamepad_db.h create mode 100644 thirdparty/sdl/joystick/SDL_joystick.c create mode 100644 thirdparty/sdl/joystick/SDL_joystick_c.h create mode 100644 thirdparty/sdl/joystick/SDL_steam_virtual_gamepad.c create mode 100644 thirdparty/sdl/joystick/SDL_steam_virtual_gamepad.h create mode 100644 thirdparty/sdl/joystick/SDL_sysjoystick.h create mode 100644 thirdparty/sdl/joystick/apple/SDL_mfijoystick.m create mode 100644 thirdparty/sdl/joystick/apple/SDL_mfijoystick_c.h create mode 100644 thirdparty/sdl/joystick/controller_list.h create mode 100644 thirdparty/sdl/joystick/controller_type.c create mode 100644 thirdparty/sdl/joystick/controller_type.h create mode 100644 thirdparty/sdl/joystick/darwin/SDL_iokitjoystick.c create mode 100644 thirdparty/sdl/joystick/darwin/SDL_iokitjoystick_c.h create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_combined.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_gamecube.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_luna.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_nintendo.h create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps3.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps4.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps5.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_rumble.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_rumble.h create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_shield.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_stadia.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_steam.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_steam_hori.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_steamdeck.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_switch.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_wii.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_xbox360.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_xbox360w.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapi_xboxone.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapijoystick.c create mode 100644 thirdparty/sdl/joystick/hidapi/SDL_hidapijoystick_c.h create mode 100644 thirdparty/sdl/joystick/hidapi/steam/controller_constants.h create mode 100644 thirdparty/sdl/joystick/hidapi/steam/controller_structs.h create mode 100644 thirdparty/sdl/joystick/linux/SDL_sysjoystick.c create mode 100644 thirdparty/sdl/joystick/linux/SDL_sysjoystick_c.h create mode 100644 thirdparty/sdl/joystick/usb_ids.h create mode 100644 thirdparty/sdl/joystick/windows/SDL_dinputjoystick.c create mode 100644 thirdparty/sdl/joystick/windows/SDL_dinputjoystick_c.h create mode 100644 thirdparty/sdl/joystick/windows/SDL_rawinputjoystick.c create mode 100644 thirdparty/sdl/joystick/windows/SDL_rawinputjoystick_c.h create mode 100644 thirdparty/sdl/joystick/windows/SDL_windows_gaming_input.c create mode 100644 thirdparty/sdl/joystick/windows/SDL_windowsjoystick.c create mode 100644 thirdparty/sdl/joystick/windows/SDL_windowsjoystick_c.h create mode 100644 thirdparty/sdl/joystick/windows/SDL_xinputjoystick.c create mode 100644 thirdparty/sdl/joystick/windows/SDL_xinputjoystick_c.h create mode 100644 thirdparty/sdl/libm/e_atan2.c create mode 100644 thirdparty/sdl/libm/e_exp.c create mode 100644 thirdparty/sdl/libm/e_fmod.c create mode 100644 thirdparty/sdl/libm/e_log.c create mode 100644 thirdparty/sdl/libm/e_log10.c create mode 100644 thirdparty/sdl/libm/e_pow.c create mode 100644 thirdparty/sdl/libm/e_rem_pio2.c create mode 100644 thirdparty/sdl/libm/e_sqrt.c create mode 100644 thirdparty/sdl/libm/k_cos.c create mode 100644 thirdparty/sdl/libm/k_rem_pio2.c create mode 100644 thirdparty/sdl/libm/k_sin.c create mode 100644 thirdparty/sdl/libm/k_tan.c create mode 100644 thirdparty/sdl/libm/math_libm.h create mode 100644 thirdparty/sdl/libm/math_private.h create mode 100644 thirdparty/sdl/libm/s_atan.c create mode 100644 thirdparty/sdl/libm/s_copysign.c create mode 100644 thirdparty/sdl/libm/s_cos.c create mode 100644 thirdparty/sdl/libm/s_fabs.c create mode 100644 thirdparty/sdl/libm/s_floor.c create mode 100644 thirdparty/sdl/libm/s_isinf.c create mode 100644 thirdparty/sdl/libm/s_isinff.c create mode 100644 thirdparty/sdl/libm/s_isnan.c create mode 100644 thirdparty/sdl/libm/s_isnanf.c create mode 100644 thirdparty/sdl/libm/s_modf.c create mode 100644 thirdparty/sdl/libm/s_scalbn.c create mode 100644 thirdparty/sdl/libm/s_sin.c create mode 100644 thirdparty/sdl/libm/s_tan.c create mode 100644 thirdparty/sdl/loadso/dlopen/SDL_sysloadso.c create mode 100644 thirdparty/sdl/patches/0001-remove-unnecessary-subsystems.patch create mode 100644 thirdparty/sdl/patches/0002-msvc-constants-fpstrict.patch create mode 100644 thirdparty/sdl/sensor/SDL_sensor.c create mode 100644 thirdparty/sdl/sensor/SDL_sensor_c.h create mode 100644 thirdparty/sdl/sensor/SDL_syssensor.h create mode 100644 thirdparty/sdl/sensor/dummy/SDL_dummysensor.c create mode 100644 thirdparty/sdl/sensor/dummy/SDL_dummysensor.h create mode 100644 thirdparty/sdl/stdlib/SDL_casefolding.h create mode 100644 thirdparty/sdl/stdlib/SDL_crc16.c create mode 100644 thirdparty/sdl/stdlib/SDL_crc32.c create mode 100644 thirdparty/sdl/stdlib/SDL_getenv.c create mode 100644 thirdparty/sdl/stdlib/SDL_getenv_c.h create mode 100644 thirdparty/sdl/stdlib/SDL_iconv.c create mode 100644 thirdparty/sdl/stdlib/SDL_malloc.c create mode 100644 thirdparty/sdl/stdlib/SDL_memcpy.c create mode 100644 thirdparty/sdl/stdlib/SDL_memmove.c create mode 100644 thirdparty/sdl/stdlib/SDL_memset.c create mode 100644 thirdparty/sdl/stdlib/SDL_mslibc.c create mode 100644 thirdparty/sdl/stdlib/SDL_murmur3.c create mode 100644 thirdparty/sdl/stdlib/SDL_qsort.c create mode 100644 thirdparty/sdl/stdlib/SDL_random.c create mode 100644 thirdparty/sdl/stdlib/SDL_stdlib.c create mode 100644 thirdparty/sdl/stdlib/SDL_string.c create mode 100644 thirdparty/sdl/stdlib/SDL_strtokr.c create mode 100644 thirdparty/sdl/stdlib/SDL_sysstdlib.h create mode 100644 thirdparty/sdl/stdlib/SDL_vacopy.h create mode 100644 thirdparty/sdl/thread/SDL_systhread.h create mode 100644 thirdparty/sdl/thread/SDL_thread.c create mode 100644 thirdparty/sdl/thread/SDL_thread_c.h create mode 100644 thirdparty/sdl/thread/generic/SDL_syscond.c create mode 100644 thirdparty/sdl/thread/generic/SDL_syscond_c.h create mode 100644 thirdparty/sdl/thread/generic/SDL_sysrwlock.c create mode 100644 thirdparty/sdl/thread/generic/SDL_sysrwlock_c.h create mode 100644 thirdparty/sdl/thread/generic/SDL_syssem.c create mode 100644 thirdparty/sdl/thread/generic/SDL_systhread.c create mode 100644 thirdparty/sdl/thread/generic/SDL_systhread_c.h create mode 100644 thirdparty/sdl/thread/pthread/SDL_syscond.c create mode 100644 thirdparty/sdl/thread/pthread/SDL_sysmutex.c create mode 100644 thirdparty/sdl/thread/pthread/SDL_sysmutex_c.h create mode 100644 thirdparty/sdl/thread/pthread/SDL_sysrwlock.c create mode 100644 thirdparty/sdl/thread/pthread/SDL_syssem.c create mode 100644 thirdparty/sdl/thread/pthread/SDL_systhread.c create mode 100644 thirdparty/sdl/thread/pthread/SDL_systhread_c.h create mode 100644 thirdparty/sdl/thread/pthread/SDL_systls.c create mode 100644 thirdparty/sdl/thread/windows/SDL_syscond_cv.c create mode 100644 thirdparty/sdl/thread/windows/SDL_sysmutex.c create mode 100644 thirdparty/sdl/thread/windows/SDL_sysmutex_c.h create mode 100644 thirdparty/sdl/thread/windows/SDL_sysrwlock_srw.c create mode 100644 thirdparty/sdl/thread/windows/SDL_syssem.c create mode 100644 thirdparty/sdl/thread/windows/SDL_systhread.c create mode 100644 thirdparty/sdl/thread/windows/SDL_systhread_c.h create mode 100644 thirdparty/sdl/thread/windows/SDL_systls.c create mode 100644 thirdparty/sdl/timer/SDL_timer.c create mode 100644 thirdparty/sdl/timer/SDL_timer_c.h create mode 100644 thirdparty/sdl/timer/unix/SDL_systimer.c create mode 100644 thirdparty/sdl/timer/windows/SDL_systimer.c create mode 100755 thirdparty/sdl/update-sdl.sh diff --git a/COPYRIGHT.txt b/COPYRIGHT.txt index f12dc91911f..8aaf6e46232 100644 --- a/COPYRIGHT.txt +++ b/COPYRIGHT.txt @@ -541,6 +541,16 @@ Comment: RVO2 Copyright: 2016, University of North Carolina at Chapel Hill License: Apache-2.0 +Files: thirdparty/sdl/* +Comment: SDL +Copyright: 1997-2025, Sam Lantinga +License: Zlib + +Files: thirdparty/sdl/hidapi/* +Comment: hidapi +Copyright: 2010, Alan Ott, Signal 11 Software +License: BSD-3-Clause + Files: thirdparty/spirv-cross/* Comment: SPIRV-Cross Copyright: 2015-2021, Arm Limited diff --git a/SConstruct b/SConstruct index fb6a7e6ffb2..24c9ffdb96c 100644 --- a/SConstruct +++ b/SConstruct @@ -194,16 +194,14 @@ opts.Add( opts.Add(BoolVariable("minizip", "Enable ZIP archive support using minizip", True)) opts.Add(BoolVariable("brotli", "Enable Brotli for decompression and WOFF2 fonts support", True)) opts.Add(BoolVariable("xaudio2", "Enable the XAudio2 audio driver on supported platforms", False)) -opts.Add(BoolVariable("vulkan", "Enable the vulkan rendering driver", True)) +opts.Add(BoolVariable("vulkan", "Enable the Vulkan rendering driver", True)) opts.Add(BoolVariable("opengl3", "Enable the OpenGL/GLES3 rendering driver", True)) opts.Add(BoolVariable("d3d12", "Enable the Direct3D 12 rendering driver on supported platforms", False)) opts.Add(BoolVariable("metal", "Enable the Metal rendering driver on supported platforms (Apple arm64 only)", False)) opts.Add(BoolVariable("use_volk", "Use the volk library to load the Vulkan loader dynamically", True)) -opts.Add(BoolVariable("disable_exceptions", "Force disabling exception handling code", True)) -opts.Add("custom_modules", "A list of comma-separated directory paths containing custom modules to build.", "") -opts.Add(BoolVariable("custom_modules_recursive", "Detect custom modules recursively for each specified path.", True)) opts.Add(BoolVariable("accesskit", "Use AccessKit C SDK", True)) opts.Add(("accesskit_sdk_path", "Path to the AccessKit C SDK", "")) +opts.Add(BoolVariable("sdl", "Enable the SDL3 input driver", True)) # Advanced options opts.Add( @@ -233,6 +231,7 @@ opts.Add("object_prefix", "Custom prefix added to the base filename of all gener opts.Add(BoolVariable("vsproj", "Generate a Visual Studio solution", False)) opts.Add("vsproj_name", "Name of the Visual Studio solution", "godot") opts.Add("import_env_vars", "A comma-separated list of environment variables to copy from the outer environment.", "") +opts.Add(BoolVariable("disable_exceptions", "Force disabling exception handling code", True)) opts.Add(BoolVariable("disable_3d", "Disable 3D nodes for a smaller executable", False)) opts.Add(BoolVariable("disable_advanced_gui", "Disable advanced GUI nodes and behaviors", False)) opts.Add(BoolVariable("disable_physics_2d", "Disable 2D physics nodes and server", False)) @@ -241,6 +240,8 @@ opts.Add(BoolVariable("disable_navigation_2d", "Disable 2D navigation features", opts.Add(BoolVariable("disable_navigation_3d", "Disable 3D navigation features", False)) opts.Add(BoolVariable("disable_xr", "Disable XR nodes and server", False)) opts.Add("build_profile", "Path to a file containing a feature build profile", "") +opts.Add("custom_modules", "A list of comma-separated directory paths containing custom modules to build.", "") +opts.Add(BoolVariable("custom_modules_recursive", "Detect custom modules recursively for each specified path.", True)) opts.Add(BoolVariable("modules_enabled_by_default", "If no, disable all modules except ones explicitly enabled", True)) opts.Add(BoolVariable("no_editor_splash", "Don't use the custom splash screen for the editor", True)) opts.Add( @@ -275,6 +276,7 @@ opts.Add(BoolVariable("builtin_msdfgen", "Use the built-in MSDFgen library", Tru opts.Add(BoolVariable("builtin_glslang", "Use the built-in glslang library", True)) opts.Add(BoolVariable("builtin_graphite", "Use the built-in Graphite library", True)) opts.Add(BoolVariable("builtin_harfbuzz", "Use the built-in HarfBuzz library", True)) +opts.Add(BoolVariable("builtin_sdl", "Use the built-in SDL library", True)) opts.Add(BoolVariable("builtin_icu4c", "Use the built-in ICU library", True)) opts.Add(BoolVariable("builtin_libjpeg_turbo", "Use the built-in libjpeg-turbo library", True)) opts.Add(BoolVariable("builtin_libogg", "Use the built-in libogg library", True)) diff --git a/core/input/input.cpp b/core/input/input.cpp index 1ee99764d21..9225d82245a 100644 --- a/core/input/input.cpp +++ b/core/input/input.cpp @@ -587,9 +587,13 @@ void Input::joy_connection_changed(int p_idx, bool p_connected, const String &p_ js.uid = uidname; js.connected = true; int mapping = fallback_mapping; - for (int i = 0; i < map_db.size(); i++) { - if (js.uid == map_db[i].uid) { - mapping = i; + // Bypass the mapping system if the joypad's mapping is already handled by its driver + // (for example, the SDL joypad driver). + if (!p_joypad_info.get("mapping_handled", false)) { + for (int i = 0; i < map_db.size(); i++) { + if (js.uid == map_db[i].uid) { + mapping = i; + } } } _set_joypad_mapping(js, mapping); diff --git a/drivers/SCsub b/drivers/SCsub index 5b891631ce8..a5a5e6d8de6 100644 --- a/drivers/SCsub +++ b/drivers/SCsub @@ -60,6 +60,11 @@ if env["metal"]: Exit(255) SConscript("metal/SCsub") +# Input drivers +if env["sdl"] and env["platform"] in ["linuxbsd", "macos", "windows"]: + # TODO: Evaluate support for Android, iOS, and Web. + SConscript("sdl/SCsub") + # Core dependencies SConscript("png/SCsub") diff --git a/drivers/sdl/SCsub b/drivers/sdl/SCsub new file mode 100644 index 00000000000..b6bd1a53793 --- /dev/null +++ b/drivers/sdl/SCsub @@ -0,0 +1,209 @@ +#!/usr/bin/env python +from misc.utility.scons_hints import * + +Import("env") + +env_sdl = env.Clone() + +# Thirdparty source files + +thirdparty_obj = [] + +if env["builtin_sdl"]: + thirdparty_dir = "#thirdparty/sdl/" + + # Use our own SDL_build_config_private.h. + env_sdl.Prepend(CPPDEFINES=["SDL_PLATFORM_PRIVATE"]) + + # Common sources. + + env_sdl.Prepend( + CPPPATH=[ + thirdparty_dir, + thirdparty_dir + "include", + thirdparty_dir + "include/build_config", + ".", # SDL_build_config_private.h + ] + ) + + thirdparty_sources = [ + "SDL.c", + "SDL_assert.c", + "SDL_error.c", + "SDL_guid.c", + "SDL_hashtable.c", + "SDL_hints.c", + "SDL_list.c", + "SDL_log.c", + "SDL_properties.c", + "SDL_utils.c", + "atomic/SDL_atomic.c", + "atomic/SDL_spinlock.c", + "events/SDL_events.c", + "events/SDL_eventwatch.c", + "haptic/SDL_haptic.c", + "io/SDL_iostream.c", + "joystick/SDL_gamepad.c", + "joystick/SDL_joystick.c", + "joystick/SDL_steam_virtual_gamepad.c", + "joystick/controller_type.c", + "libm/e_atan2.c", + "libm/e_exp.c", + "libm/e_fmod.c", + "libm/e_log.c", + "libm/e_log10.c", + "libm/e_pow.c", + "libm/e_rem_pio2.c", + "libm/e_sqrt.c", + "libm/k_cos.c", + "libm/k_rem_pio2.c", + "libm/k_sin.c", + "libm/k_tan.c", + "libm/s_atan.c", + "libm/s_copysign.c", + "libm/s_cos.c", + "libm/s_fabs.c", + "libm/s_floor.c", + "libm/s_isinf.c", + "libm/s_isinff.c", + "libm/s_isnan.c", + "libm/s_isnanf.c", + "libm/s_modf.c", + "libm/s_scalbn.c", + "libm/s_sin.c", + "libm/s_tan.c", + "sensor/SDL_sensor.c", + "sensor/dummy/SDL_dummysensor.c", + "stdlib/SDL_crc16.c", + "stdlib/SDL_crc32.c", + "stdlib/SDL_getenv.c", + "stdlib/SDL_iconv.c", + "stdlib/SDL_malloc.c", + "stdlib/SDL_memcpy.c", + "stdlib/SDL_memmove.c", + "stdlib/SDL_memset.c", + "stdlib/SDL_mslibc.c", + "stdlib/SDL_murmur3.c", + "stdlib/SDL_qsort.c", + "stdlib/SDL_random.c", + "stdlib/SDL_stdlib.c", + "stdlib/SDL_string.c", + "stdlib/SDL_strtokr.c", + "thread/SDL_thread.c", + "thread/generic/SDL_syscond.c", + "thread/generic/SDL_sysrwlock.c", + "thread/generic/SDL_systhread.c", + "timer/SDL_timer.c", + ] + + # HIDAPI + thirdparty_sources += [ + "hidapi/SDL_hidapi.c", + "joystick/hidapi/SDL_hidapi_combined.c", + "joystick/hidapi/SDL_hidapi_gamecube.c", + "joystick/hidapi/SDL_hidapijoystick.c", + "joystick/hidapi/SDL_hidapi_luna.c", + "joystick/hidapi/SDL_hidapi_ps3.c", + "joystick/hidapi/SDL_hidapi_ps4.c", + "joystick/hidapi/SDL_hidapi_ps5.c", + "joystick/hidapi/SDL_hidapi_rumble.c", + "joystick/hidapi/SDL_hidapi_shield.c", + "joystick/hidapi/SDL_hidapi_stadia.c", + "joystick/hidapi/SDL_hidapi_steam.c", + "joystick/hidapi/SDL_hidapi_steamdeck.c", + "joystick/hidapi/SDL_hidapi_steam_hori.c", + "joystick/hidapi/SDL_hidapi_switch.c", + "joystick/hidapi/SDL_hidapi_wii.c", + "joystick/hidapi/SDL_hidapi_xbox360.c", + "joystick/hidapi/SDL_hidapi_xbox360w.c", + "joystick/hidapi/SDL_hidapi_xboxone.c", + ] + + # Platform specific sources. + + if env["platform"] == "linuxbsd": + # TODO: Check support for BSD systems. + env_sdl.Append(CPPDEFINES=["SDL_PLATFORM_LINUX"]) + thirdparty_sources += [ + "core/linux/SDL_dbus.c", + "core/linux/SDL_evdev.c", + "core/linux/SDL_evdev_capabilities.c", + "core/linux/SDL_evdev_kbd.c", + "core/linux/SDL_fcitx.c", + "core/linux/SDL_ibus.c", + "core/linux/SDL_ime.c", + "core/linux/SDL_system_theme.c", + "core/linux/SDL_threadprio.c", + "core/linux/SDL_udev.c", + "core/unix/SDL_appid.c", + "core/unix/SDL_poll.c", + "haptic/linux/SDL_syshaptic.c", + "joystick/linux/SDL_sysjoystick.c", + "loadso/dlopen/SDL_sysloadso.c", + "thread/pthread/SDL_syscond.c", + "thread/pthread/SDL_sysmutex.c", + "thread/pthread/SDL_sysrwlock.c", + "thread/pthread/SDL_syssem.c", + "thread/pthread/SDL_systhread.c", + "thread/pthread/SDL_systls.c", + "timer/unix/SDL_systimer.c", + ] + + elif env["platform"] == "macos": + env_sdl.Append(CPPDEFINES=["SDL_PLATFORM_MACOS"]) + thirdparty_sources += [ + "core/unix/SDL_appid.c", + "core/unix/SDL_poll.c", + "haptic/darwin/SDL_syshaptic.c", + "joystick/darwin/SDL_iokitjoystick.c", + "joystick/apple/SDL_mfijoystick.m", + "thread/pthread/SDL_syscond.c", + "thread/pthread/SDL_sysmutex.c", + "thread/pthread/SDL_sysrwlock.c", + "thread/pthread/SDL_syssem.c", + "thread/pthread/SDL_systhread.c", + "thread/pthread/SDL_systls.c", + "timer/unix/SDL_systimer.c", + ] + + elif env["platform"] == "windows": + env_sdl.Append(CPPDEFINES=["SDL_PLATFORM_WINDOWS"]) + thirdparty_sources += [ + "core/windows/SDL_gameinput.c", + "core/windows/SDL_hid.c", + "core/windows/SDL_immdevice.c", + "core/windows/SDL_windows.c", + "core/windows/SDL_xinput.c", + "core/windows/pch.c", + "haptic/windows/SDL_dinputhaptic.c", + "haptic/windows/SDL_windowshaptic.c", + "joystick/windows/SDL_dinputjoystick.c", + "joystick/windows/SDL_rawinputjoystick.c", + "joystick/windows/SDL_windows_gaming_input.c", + "joystick/windows/SDL_windowsjoystick.c", + "joystick/windows/SDL_xinputjoystick.c", + "thread/windows/SDL_syscond_cv.c", + "thread/windows/SDL_sysmutex.c", + "thread/windows/SDL_sysrwlock_srw.c", + "thread/windows/SDL_syssem.c", + "thread/windows/SDL_systhread.c", + "thread/windows/SDL_systls.c", + "timer/windows/SDL_systimer.c", + ] + + thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] + + env_thirdparty = env_sdl.Clone() + env_thirdparty.disable_warnings() + env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources) + env.drivers_sources += thirdparty_obj + +# Godot source files + +driver_obj = [] + +env_sdl.add_source_files(driver_obj, "*.cpp") +env.drivers_sources += driver_obj + +# Needed to force rebuilding the driver files when the thirdparty library is updated. +env.Depends(driver_obj, thirdparty_obj) diff --git a/drivers/sdl/SDL_build_config_private.h b/drivers/sdl/SDL_build_config_private.h new file mode 100644 index 00000000000..1282b1434d5 --- /dev/null +++ b/drivers/sdl/SDL_build_config_private.h @@ -0,0 +1,130 @@ +/**************************************************************************/ +/* SDL_build_config_private.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#pragma once + +#define SDL_build_config_h_ + +#include + +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 + +// Here we disable SDL subsystems that are not going to be used +#define SDL_CPUINFO_DISABLED 1 +#define SDL_AUDIO_DISABLED 1 +#define SDL_PROCESS_DUMMY 1 +#define SDL_LOADSO_DUMMY 1 +#define SDL_VIDEO_DISABLED 1 +#define SDL_CAMERA_DISABLED 1 +#define SDL_DIALOG_DISABLED 1 +#define SDL_FILESYSTEM_DUMMY 1 +#define SDL_FSOPS_DUMMY 1 +#define SDL_SENSOR_DISABLED 1 +#define SDL_GPU_DISABLED 1 +#define SDL_RENDER_DISABLED 1 +#define SDL_POWER_DISABLED 1 +#define SDL_LEAN_AND_MEAN 1 + +// Windows defines +#if defined(SDL_PLATFORM_WINDOWS) + +#define SDL_PLATFORM_PRIVATE_NAME "Windows" +#define HAVE_LIBC 1 +#define HAVE_DINPUT_H 1 +#define HAVE_XINPUT_H 1 +#if defined(_WIN32_MAXVER) && _WIN32_MAXVER >= 0x0A00 /* Windows 10 SDK */ +#define HAVE_WINDOWS_GAMING_INPUT_H 1 +#define SDL_JOYSTICK_WGI 1 +#endif +#define SDL_JOYSTICK_DINPUT 1 +#define SDL_JOYSTICK_HIDAPI 1 +#define SDL_JOYSTICK_RAWINPUT 1 +#define SDL_JOYSTICK_XINPUT 1 +#define SDL_HAPTIC_DINPUT 1 +#define SDL_THREAD_GENERIC_COND_SUFFIX 1 +#define SDL_THREAD_GENERIC_RWLOCK_SUFFIX 1 +#define SDL_THREAD_WINDOWS 1 +#define SDL_TIMER_WINDOWS 1 + +// Linux defines +#elif defined(SDL_PLATFORM_LINUX) + +#define SDL_PLATFORM_PRIVATE_NAME "Linux" +#define SDL_PLATFORM_UNIX 1 + +#define HAVE_STDIO_H 1 +#define HAVE_LINUX_INPUT_H 1 +#define HAVE_POLL 1 + +// TODO: handle dynamic loading with SOWRAP_ENABLED + +// (even though DBus can also be loaded with SOWRAP_ENABLED, we load it +// statically regardless of SOWRAP_ENABLED, because otherwise SDL won't compile) +#ifdef DBUS_ENABLED +#define HAVE_DBUS_DBUS_H 1 +#endif + +#if defined(UDEV_ENABLED) && !defined(SOWRAP_ENABLED) +#define HAVE_LIBUDEV_H 1 +#endif + +#define SDL_LOADSO_DLOPEN 1 +#define SDL_HAPTIC_LINUX 1 +#define SDL_TIMER_UNIX 1 +#define SDL_JOYSTICK_LINUX 1 +#define SDL_INPUT_LINUXEV 1 +#define SDL_THREAD_PTHREAD 1 + +// MacOS defines +#elif defined(SDL_PLATFORM_MACOS) + +#define SDL_PLATFORM_PRIVATE_NAME "macOS" +#define SDL_PLATFORM_UNIX 1 +#define HAVE_STDIO_H 1 +#define HAVE_LIBC 1 +#define SDL_HAPTIC_IOKIT 1 +#define SDL_JOYSTICK_IOKIT 1 +#define SDL_JOYSTICK_MFI 1 +#define SDL_TIMER_UNIX 1 +#define SDL_THREAD_PTHREAD 1 + +// Other platforms are not supported (for now) +#else +#error "No SDL build config was found for this platform. Setup one before compiling the engine." +#endif + +#if !defined(HAVE_STDINT_H) && !defined(_STDINT_H_) +#define HAVE_STDINT_H 1 +#endif /* !_STDINT_H_ && !HAVE_STDINT_H */ + +#ifdef __GNUC__ +#define HAVE_GCC_SYNC_LOCK_TEST_AND_SET 1 +#endif diff --git a/drivers/sdl/joypad_sdl.cpp b/drivers/sdl/joypad_sdl.cpp new file mode 100644 index 00000000000..693b4a21694 --- /dev/null +++ b/drivers/sdl/joypad_sdl.cpp @@ -0,0 +1,273 @@ +/**************************************************************************/ +/* joypad_sdl.cpp */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#include "joypad_sdl.h" + +#ifdef SDL_ENABLED + +#include "core/input/default_controller_mappings.h" +#include "core/os/time.h" +#include "core/variant/dictionary.h" + +#include + +#include +#include +#include +#include +#include +#include + +JoypadSDL *JoypadSDL::singleton = nullptr; + +// Macro to skip the SDL joystick event handling if the device is an SDL gamepad, because +// there are separate events for SDL gamepads +#define SKIP_EVENT_FOR_GAMEPAD \ + if (SDL_IsGamepad(sdl_event.jdevice.which)) { \ + continue; \ + } + +JoypadSDL::JoypadSDL() { + singleton = this; +} + +JoypadSDL::~JoypadSDL() { + // Process any remaining input events + process_events(); + for (int i = 0; i < Input::JOYPADS_MAX; i++) { + if (joypads[i].attached) { + close_joypad(i); + } + } + SDL_Quit(); + singleton = nullptr; +} + +JoypadSDL *JoypadSDL::get_singleton() { + return singleton; +} + +Error JoypadSDL::initialize() { + SDL_SetHint(SDL_HINT_JOYSTICK_THREAD, "1"); + SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1"); + ERR_FAIL_COND_V_MSG(!SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_GAMEPAD), FAILED, SDL_GetError()); + + // Add Godot's mapping database from memory + int i = 0; + while (DefaultControllerMappings::mappings[i]) { + String mapping_string = DefaultControllerMappings::mappings[i++]; + CharString data = mapping_string.utf8(); + SDL_IOStream *rw = SDL_IOFromMem((void *)data.ptr(), data.size()); + SDL_AddGamepadMappingsFromIO(rw, 1); + } + + print_verbose("SDL: Init OK!"); + return OK; +} + +void JoypadSDL::process_events() { + // Update rumble first for it to be applied when we handle SDL events + for (int i = 0; i < Input::JOYPADS_MAX; i++) { + Joypad &joy = joypads[i]; + if (joy.attached && joy.supports_force_feedback) { + uint64_t timestamp = Input::get_singleton()->get_joy_vibration_timestamp(i); + + // Update the joypad rumble only if there was a new vibration request + if (timestamp > joy.ff_effect_timestamp) { + joy.ff_effect_timestamp = timestamp; + + SDL_Joystick *sdl_joy = SDL_GetJoystickFromID(joypads[i].sdl_instance_idx); + Vector2 strength = Input::get_singleton()->get_joy_vibration_strength(i); + + // If the vibration was requested to start, SDL_RumbleJoystick will start it. + // If the vibration was requested to stop, strength and duration will be 0, so SDL will stop the rumble. + SDL_RumbleJoystick( + sdl_joy, + // Rumble strength goes from 0 to 0xFFFF + strength.x * UINT16_MAX, + strength.y * UINT16_MAX, + Input::get_singleton()->get_joy_vibration_duration(i) * 1000); + } + } + } + + SDL_Event sdl_event; + while (SDL_PollEvent(&sdl_event)) { + // A new joypad was attached + if (sdl_event.type == SDL_EVENT_JOYSTICK_ADDED) { + int joy_id = Input::get_singleton()->get_unused_joy_id(); + if (joy_id == -1) { + // There is no space for more joypads... + print_error("A new joypad was attached but couldn't allocate a new id for it because joypad limit was reached."); + } else { + SDL_Joystick *joy = nullptr; + String device_name; + + // Gamepads must be opened with SDL_OpenGamepad to get their special remapped events + if (SDL_IsGamepad(sdl_event.jdevice.which)) { + SDL_Gamepad *gamepad = SDL_OpenGamepad(sdl_event.jdevice.which); + + ERR_CONTINUE_MSG(!gamepad, + vformat("Error opening gamepad at index %d: %s", sdl_event.jdevice.which, SDL_GetError())); + + device_name = SDL_GetGamepadName(gamepad); + joy = SDL_GetGamepadJoystick(gamepad); + + print_verbose(vformat("SDL: Gamepad %s connected", SDL_GetGamepadName(gamepad))); + } else { + joy = SDL_OpenJoystick(sdl_event.jdevice.which); + ERR_CONTINUE_MSG(!joy, + vformat("Error opening joystick at index %d: %s", sdl_event.jdevice.which, SDL_GetError())); + + device_name = SDL_GetJoystickName(joy); + + print_verbose(vformat("SDL: Joystick %s connected", SDL_GetJoystickName(joy))); + } + + const int MAX_GUID_SIZE = 64; + char guid[MAX_GUID_SIZE] = {}; + + SDL_GUIDToString(SDL_GetJoystickGUID(joy), guid, MAX_GUID_SIZE); + SDL_PropertiesID propertiesID = SDL_GetJoystickProperties(joy); + + joypads[joy_id].attached = true; + joypads[joy_id].sdl_instance_idx = sdl_event.jdevice.which; + joypads[joy_id].supports_force_feedback = SDL_GetBooleanProperty(propertiesID, SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, false); + joypads[joy_id].guid = StringName(String(guid)); + + sdl_instance_id_to_joypad_id.insert(sdl_event.jdevice.which, joy_id); + + // Skip Godot's mapping system because SDL already handles the joypad's mapping + Dictionary joypad_info; + joypad_info["mapping_handled"] = true; + + Input::get_singleton()->joy_connection_changed( + joy_id, + true, + device_name, + joypads[joy_id].guid, + joypad_info); + } + // An event for an attached joypad + } else if (sdl_event.type >= SDL_EVENT_JOYSTICK_AXIS_MOTION && sdl_event.type < SDL_EVENT_FINGER_DOWN && sdl_instance_id_to_joypad_id.has(sdl_event.jdevice.which)) { + int joy_id = sdl_instance_id_to_joypad_id.get(sdl_event.jdevice.which); + + switch (sdl_event.type) { + case SDL_EVENT_JOYSTICK_REMOVED: + Input::get_singleton()->joy_connection_changed(joy_id, false, ""); + close_joypad(joy_id); + break; + + case SDL_EVENT_JOYSTICK_AXIS_MOTION: + SKIP_EVENT_FOR_GAMEPAD; + + Input::get_singleton()->joy_axis( + joy_id, + static_cast(sdl_event.jaxis.axis), // Godot joy axis constants are already intentionally the same as SDL's + ((sdl_event.jaxis.value - SDL_JOYSTICK_AXIS_MIN) / (float)(SDL_JOYSTICK_AXIS_MAX - SDL_JOYSTICK_AXIS_MIN) - 0.5f) * 2.0f); + break; + + case SDL_EVENT_JOYSTICK_BUTTON_UP: + case SDL_EVENT_JOYSTICK_BUTTON_DOWN: + SKIP_EVENT_FOR_GAMEPAD; + + Input::get_singleton()->joy_button( + joy_id, + static_cast(sdl_event.jbutton.button), // Godot button constants are intentionally the same as SDL's, so we can just straight up use them + sdl_event.jbutton.down); + break; + + case SDL_EVENT_JOYSTICK_HAT_MOTION: + SKIP_EVENT_FOR_GAMEPAD; + + Input::get_singleton()->joy_hat( + joy_id, + (HatMask)sdl_event.jhat.value // Godot hat masks are identical to SDL hat masks, so we can just use them as-is. + ); + break; + + case SDL_EVENT_GAMEPAD_AXIS_MOTION: { + float axis_value; + + if (sdl_event.gaxis.axis == SDL_GAMEPAD_AXIS_LEFT_TRIGGER || sdl_event.gaxis.axis == SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) { + // Gamepad triggers go from 0 to SDL_JOYSTICK_AXIS_MAX + axis_value = sdl_event.gaxis.value / (float)SDL_JOYSTICK_AXIS_MAX; + } else { + // Other axis go from SDL_JOYSTICK_AXIS_MIN to SDL_JOYSTICK_AXIS_MAX + axis_value = + ((sdl_event.gaxis.value - SDL_JOYSTICK_AXIS_MIN) / (float)(SDL_JOYSTICK_AXIS_MAX - SDL_JOYSTICK_AXIS_MIN) - 0.5f) * 2.0f; + } + + Input::get_singleton()->joy_axis( + joy_id, + static_cast(sdl_event.gaxis.axis), // Godot joy axis constants are already intentionally the same as SDL's + axis_value); + } break; + + // Do note SDL gamepads do not have separate events for the dpad + case SDL_EVENT_GAMEPAD_BUTTON_UP: + case SDL_EVENT_GAMEPAD_BUTTON_DOWN: + Input::get_singleton()->joy_button( + joy_id, + static_cast(sdl_event.gbutton.button), // Godot button constants are intentionally the same as SDL's, so we can just straight up use them + sdl_event.gbutton.down); + break; + } + } + } +} + +#ifdef WINDOWS_ENABLED +extern "C" { +HWND SDL_HelperWindow; +} + +// Required for DInput joypads to work +void JoypadSDL::setup_sdl_helper_window(HWND p_hwnd) { + SDL_HelperWindow = p_hwnd; +} +#endif + +void JoypadSDL::close_joypad(int p_pad_idx) { + int sdl_instance_idx = joypads[p_pad_idx].sdl_instance_idx; + + joypads[p_pad_idx].attached = false; + sdl_instance_id_to_joypad_id.erase(sdl_instance_idx); + + if (SDL_IsGamepad(sdl_instance_idx)) { + SDL_Gamepad *gamepad = SDL_GetGamepadFromID(sdl_instance_idx); + SDL_CloseGamepad(gamepad); + } else { + SDL_Joystick *joy = SDL_GetJoystickFromID(sdl_instance_idx); + SDL_CloseJoystick(joy); + } +} + +#endif // SDL_ENABLED diff --git a/drivers/sdl/joypad_sdl.h b/drivers/sdl/joypad_sdl.h new file mode 100644 index 00000000000..fb242a36354 --- /dev/null +++ b/drivers/sdl/joypad_sdl.h @@ -0,0 +1,69 @@ +/**************************************************************************/ +/* joypad_sdl.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#pragma once + +#include "core/input/input.h" +#include "core/os/thread.h" + +typedef uint32_t SDL_JoystickID; +typedef struct HWND__ *HWND; + +class JoypadSDL { +public: + JoypadSDL(); + ~JoypadSDL(); + + static JoypadSDL *get_singleton(); + + Error initialize(); + void process_events(); +#ifdef WINDOWS_ENABLED + void setup_sdl_helper_window(HWND p_hwnd); +#endif + +private: + struct Joypad { + bool attached = false; + StringName guid; + + SDL_JoystickID sdl_instance_idx; + + bool supports_force_feedback = false; + uint64_t ff_effect_timestamp = 0; + }; + + static JoypadSDL *singleton; + + Joypad joypads[Input::JOYPADS_MAX]; + HashMap sdl_instance_id_to_joypad_id; + + void close_joypad(int p_pad_idx); +}; diff --git a/platform/linuxbsd/SCsub b/platform/linuxbsd/SCsub index 678fc78015a..88e0efa0770 100644 --- a/platform/linuxbsd/SCsub +++ b/platform/linuxbsd/SCsub @@ -8,7 +8,6 @@ import platform_linuxbsd_builders common_linuxbsd = [ "crash_handler_linuxbsd.cpp", "os_linuxbsd.cpp", - "joypad_linux.cpp", "freedesktop_portal_desktop.cpp", "freedesktop_screensaver.cpp", "freedesktop_at_spi_monitor.cpp", diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py index 1d9f416cf08..b649c2f1b2d 100644 --- a/platform/linuxbsd/detect.py +++ b/platform/linuxbsd/detect.py @@ -394,6 +394,18 @@ def configure(env: "SConsEnvironment"): else: env["udev"] = False # Linux specific + if env["sdl"]: + if env["builtin_sdl"]: + env.Append(CPPDEFINES=["SDL_ENABLED"]) + elif os.system("pkg-config --exists fontconfig") == 0: # 0 means found + env.ParseConfig("pkg-config sdl3 --cflags --libs") + env.Append(CPPDEFINES=["SDL_ENABLED"]) + else: + print_warning( + "SDL3 development libraries not found, and `builtin_sdl` was explicitly disabled. Disabling SDL input driver support." + ) + env["sdl"] = False + # Linkflags below this line should typically stay the last ones if not env["builtin_zlib"]: env.ParseConfig("pkg-config zlib --cflags --libs") diff --git a/platform/linuxbsd/joypad_linux.cpp b/platform/linuxbsd/joypad_linux.cpp deleted file mode 100644 index 9cd19d441c4..00000000000 --- a/platform/linuxbsd/joypad_linux.cpp +++ /dev/null @@ -1,613 +0,0 @@ -/**************************************************************************/ -/* joypad_linux.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#ifdef JOYDEV_ENABLED - -#include "joypad_linux.h" - -#include "core/os/os.h" - -#include -#include -#include -#include -#include - -#ifdef UDEV_ENABLED -#ifdef SOWRAP_ENABLED -#include "libudev-so_wrap.h" -#else -#include -#endif -#endif - -#define LONG_BITS (sizeof(long) * 8) -#define test_bit(nr, addr) (((1UL << ((nr) % LONG_BITS)) & ((addr)[(nr) / LONG_BITS])) != 0) -#define NBITS(x) ((((x) - 1) / LONG_BITS) + 1) - -#ifdef UDEV_ENABLED -static const char *ignore_str = "/dev/input/js"; -#endif - -// On Linux with Steam Input Xbox 360 devices have an index appended to their device name, this index is -// the Steam Input gamepad index -#define VALVE_GAMEPAD_NAME_PREFIX "Microsoft X-Box 360 pad " -// IDs used by Steam Input virtual controllers. -// See https://partner.steamgames.com/doc/features/steam_controller/steam_input_gamepad_emulation_bestpractices -#define VALVE_GAMEPAD_VID 0x28DE -#define VALVE_GAMEPAD_PID 0x11FF - -JoypadLinux::Joypad::~Joypad() { - for (int i = 0; i < MAX_ABS; i++) { - if (abs_info[i]) { - memdelete(abs_info[i]); - } - } -} - -void JoypadLinux::Joypad::reset() { - dpad.clear(); - fd = -1; - for (int i = 0; i < MAX_ABS; i++) { - abs_map[i] = -1; - curr_axis[i] = 0; - } - events.clear(); -} - -JoypadLinux::JoypadLinux(Input *in) { -#ifdef UDEV_ENABLED - if (OS::get_singleton()->is_sandboxed()) { - // Linux binaries in sandboxes / containers need special handling because - // libudev doesn't work there. So we need to fallback to manual parsing - // of /dev/input in such case. - use_udev = false; - print_verbose("JoypadLinux: udev enabled, but detected incompatible sandboxed mode. Falling back to /dev/input to detect joypads."); - } -#ifdef SOWRAP_ENABLED - else { -#ifdef DEBUG_ENABLED - int dylibloader_verbose = 1; -#else - int dylibloader_verbose = 0; -#endif - use_udev = initialize_libudev(dylibloader_verbose) == 0; - if (use_udev) { - if (!udev_new || !udev_unref || !udev_enumerate_new || !udev_enumerate_add_match_subsystem || !udev_enumerate_scan_devices || !udev_enumerate_get_list_entry || !udev_list_entry_get_next || !udev_list_entry_get_name || !udev_device_new_from_syspath || !udev_device_get_devnode || !udev_device_get_action || !udev_device_unref || !udev_enumerate_unref || !udev_monitor_new_from_netlink || !udev_monitor_filter_add_match_subsystem_devtype || !udev_monitor_enable_receiving || !udev_monitor_get_fd || !udev_monitor_receive_device || !udev_monitor_unref) { - // There's no API to check version, check if functions are available instead. - use_udev = false; - print_verbose("JoypadLinux: Unsupported udev library version!"); - } else { - print_verbose("JoypadLinux: udev enabled and loaded successfully."); - } - } else { - print_verbose("JoypadLinux: udev enabled, but couldn't be loaded. Falling back to /dev/input to detect joypads."); - } - } -#endif // SOWRAP_ENABLED -#else - print_verbose("JoypadLinux: udev disabled, parsing /dev/input to detect joypads."); -#endif // UDEV_ENABLED - - input = in; - monitor_joypads_thread.start(monitor_joypads_thread_func, this); - joypad_events_thread.start(joypad_events_thread_func, this); -} - -JoypadLinux::~JoypadLinux() { - monitor_joypads_exit.set(); - joypad_events_exit.set(); - monitor_joypads_thread.wait_to_finish(); - joypad_events_thread.wait_to_finish(); - close_joypads(); -} - -void JoypadLinux::monitor_joypads_thread_func(void *p_user) { - if (p_user) { - JoypadLinux *joy = static_cast(p_user); - joy->monitor_joypads_thread_run(); - } -} - -void JoypadLinux::monitor_joypads_thread_run() { -#ifdef UDEV_ENABLED - if (use_udev) { - udev *_udev = udev_new(); - if (!_udev) { - use_udev = false; - ERR_PRINT("Failed getting an udev context, falling back to parsing /dev/input."); - monitor_joypads(); - } else { - enumerate_joypads(_udev); - monitor_joypads(_udev); - udev_unref(_udev); - } - } else { - monitor_joypads(); - } -#else - monitor_joypads(); -#endif -} - -#ifdef UDEV_ENABLED -void JoypadLinux::enumerate_joypads(udev *p_udev) { - udev_enumerate *enumerate; - udev_list_entry *devices, *dev_list_entry; - udev_device *dev; - - enumerate = udev_enumerate_new(p_udev); - udev_enumerate_add_match_subsystem(enumerate, "input"); - - udev_enumerate_scan_devices(enumerate); - devices = udev_enumerate_get_list_entry(enumerate); - udev_list_entry_foreach(dev_list_entry, devices) { - const char *path = udev_list_entry_get_name(dev_list_entry); - dev = udev_device_new_from_syspath(p_udev, path); - const char *devnode = udev_device_get_devnode(dev); - - if (devnode) { - String devnode_str = devnode; - if (!devnode_str.contains(ignore_str)) { - open_joypad(devnode); - } - } - udev_device_unref(dev); - } - udev_enumerate_unref(enumerate); -} - -void JoypadLinux::monitor_joypads(udev *p_udev) { - udev_device *dev = nullptr; - udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev"); - udev_monitor_filter_add_match_subsystem_devtype(mon, "input", nullptr); - udev_monitor_enable_receiving(mon); - int fd = udev_monitor_get_fd(mon); - - while (!monitor_joypads_exit.is_set()) { - fd_set fds; - struct timeval tv; - int ret; - - FD_ZERO(&fds); - FD_SET(fd, &fds); - tv.tv_sec = 0; - tv.tv_usec = 0; - - ret = select(fd + 1, &fds, nullptr, nullptr, &tv); - - /* Check if our file descriptor has received data. */ - if (ret > 0 && FD_ISSET(fd, &fds)) { - /* Make the call to receive the device. - select() ensured that this will not block. */ - dev = udev_monitor_receive_device(mon); - - if (dev && udev_device_get_devnode(dev) != nullptr) { - String action = udev_device_get_action(dev); - const char *devnode = udev_device_get_devnode(dev); - if (devnode) { - String devnode_str = devnode; - if (!devnode_str.contains(ignore_str)) { - if (action == "add") { - open_joypad(devnode); - } else if (String(action) == "remove") { - close_joypad(devnode); - } - } - } - udev_device_unref(dev); - } - } - OS::get_singleton()->delay_usec(50'000); - } - udev_monitor_unref(mon); -} -#endif - -void JoypadLinux::monitor_joypads() { - while (!monitor_joypads_exit.is_set()) { - DIR *input_directory; - input_directory = opendir("/dev/input"); - if (input_directory) { - struct dirent *current; - char fname[64]; - - while ((current = readdir(input_directory)) != nullptr) { - if (strncmp(current->d_name, "event", 5) != 0) { - continue; - } - sprintf(fname, "/dev/input/%.*s", 16, current->d_name); - if (!attached_devices.has(fname)) { - open_joypad(fname); - } - } - } - closedir(input_directory); - OS::get_singleton()->delay_usec(1'000'000); - } -} - -void JoypadLinux::close_joypads() { - for (int i = 0; i < JOYPADS_MAX; i++) { - MutexLock lock(joypads_mutex[i]); - Joypad &joypad = joypads[i]; - close_joypad(joypad, i); - } -} - -void JoypadLinux::close_joypad(const char *p_devpath) { - for (int i = 0; i < JOYPADS_MAX; i++) { - MutexLock lock(joypads_mutex[i]); - Joypad &joypad = joypads[i]; - if (joypads[i].devpath == p_devpath) { - close_joypad(joypad, i); - } - } -} - -void JoypadLinux::close_joypad(Joypad &p_joypad, int p_id) { - if (p_joypad.fd != -1) { - close(p_joypad.fd); - p_joypad.fd = -1; - attached_devices.erase(p_joypad.devpath); - input->joy_connection_changed(p_id, false, ""); - } - p_joypad.events.clear(); -} - -static String _hex_str(uint8_t p_byte) { - static const char *dict = "0123456789abcdef"; - char ret[3]; - ret[2] = 0; - - ret[0] = dict[p_byte >> 4]; - ret[1] = dict[p_byte & 0xF]; - - return ret; -} - -void JoypadLinux::setup_joypad_properties(Joypad &p_joypad) { - unsigned long keybit[NBITS(KEY_MAX)] = { 0 }; - unsigned long absbit[NBITS(ABS_MAX)] = { 0 }; - - int num_buttons = 0; - int num_axes = 0; - - if ((ioctl(p_joypad.fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) || - (ioctl(p_joypad.fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) { - return; - } - for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) { - if (test_bit(i, keybit)) { - p_joypad.key_map[i] = num_buttons++; - } - } - for (int i = BTN_MISC; i < BTN_JOYSTICK; ++i) { - if (test_bit(i, keybit)) { - p_joypad.key_map[i] = num_buttons++; - } - } - for (int i = 0; i < ABS_MISC; ++i) { - /* Skip hats */ - if (i == ABS_HAT0X) { - i = ABS_HAT3Y; - continue; - } - if (test_bit(i, absbit)) { - p_joypad.abs_map[i] = num_axes++; - p_joypad.abs_info[i] = memnew(input_absinfo); - if (ioctl(p_joypad.fd, EVIOCGABS(i), p_joypad.abs_info[i]) < 0) { - memdelete(p_joypad.abs_info[i]); - p_joypad.abs_info[i] = nullptr; - } - } - } - - p_joypad.force_feedback = false; - p_joypad.ff_effect_timestamp = 0; - unsigned long ffbit[NBITS(FF_CNT)]; - if (ioctl(p_joypad.fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) != -1) { - if (test_bit(FF_RUMBLE, ffbit)) { - p_joypad.force_feedback = true; - } - } -} - -void JoypadLinux::open_joypad(const char *p_path) { - int joy_num = input->get_unused_joy_id(); - int fd = open(p_path, O_RDWR | O_NONBLOCK); - if (fd != -1 && joy_num != -1) { - unsigned long evbit[NBITS(EV_MAX)] = { 0 }; - unsigned long keybit[NBITS(KEY_MAX)] = { 0 }; - unsigned long absbit[NBITS(ABS_MAX)] = { 0 }; - - // add to attached devices so we don't try to open it again - attached_devices.push_back(String(p_path)); - - if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) || - (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) || - (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) { - close(fd); - return; - } - - // Check if the device supports basic gamepad events - bool has_abs_left = (test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit)); - bool has_abs_right = (test_bit(ABS_RX, absbit) && test_bit(ABS_RY, absbit)); - if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) && (has_abs_left || has_abs_right))) { - close(fd); - return; - } - - char uid[128]; - char namebuf[128]; - String name = ""; - input_id inpid; - if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) >= 0) { - name = namebuf; - } - - for (const String &word : name.to_lower().split(" ")) { - if (banned_words.has(word)) { - return; - } - } - - if (ioctl(fd, EVIOCGID, &inpid) < 0) { - close(fd); - return; - } - - uint16_t vendor = BSWAP16(inpid.vendor); - uint16_t product = BSWAP16(inpid.product); - uint16_t version = BSWAP16(inpid.version); - - if (input->should_ignore_device(vendor, product)) { - // This can be true in cases where Steam is passing information into the game to ignore - // original gamepads when using virtual rebindings (See SteamInput). - return; - } - - MutexLock lock(joypads_mutex[joy_num]); - Joypad &joypad = joypads[joy_num]; - joypad.reset(); - joypad.fd = fd; - joypad.devpath = String(p_path); - setup_joypad_properties(joypad); - sprintf(uid, "%04x%04x", BSWAP16(inpid.bustype), 0); - if (inpid.vendor && inpid.product && inpid.version) { - Dictionary joypad_info; - joypad_info["vendor_id"] = inpid.vendor; - joypad_info["product_id"] = inpid.product; - joypad_info["raw_name"] = name; - - sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor, 0, product, 0, version, 0); - - if (inpid.vendor == VALVE_GAMEPAD_VID && inpid.product == VALVE_GAMEPAD_PID) { - if (name.begins_with(VALVE_GAMEPAD_NAME_PREFIX)) { - String idx_str = name.substr(strlen(VALVE_GAMEPAD_NAME_PREFIX)); - if (idx_str.is_valid_int()) { - joypad_info["steam_input_index"] = idx_str.to_int(); - } - } - } - - input->joy_connection_changed(joy_num, true, name, uid, joypad_info); - } else { - String uidname = uid; - int uidlen = MIN(name.length(), 11); - for (int i = 0; i < uidlen; i++) { - uidname = uidname + _hex_str(name[i]); - } - uidname += "00"; - input->joy_connection_changed(joy_num, true, name, uidname); - } - } -} - -void JoypadLinux::joypad_vibration_start(Joypad &p_joypad, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) { - if (!p_joypad.force_feedback || p_joypad.fd == -1 || p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) { - return; - } - if (p_joypad.ff_effect_id != -1) { - joypad_vibration_stop(p_joypad, p_timestamp); - } - - struct ff_effect effect; - effect.type = FF_RUMBLE; - effect.id = -1; - effect.u.rumble.weak_magnitude = std::floor(p_weak_magnitude * (float)0xffff); - effect.u.rumble.strong_magnitude = std::floor(p_strong_magnitude * (float)0xffff); - effect.replay.length = std::floor(p_duration * 1000); - effect.replay.delay = 0; - - if (ioctl(p_joypad.fd, EVIOCSFF, &effect) < 0) { - return; - } - - struct input_event play; - play.type = EV_FF; - play.code = effect.id; - play.value = 1; - if (write(p_joypad.fd, (const void *)&play, sizeof(play)) == -1) { - print_verbose("Couldn't write to Joypad device."); - } - - p_joypad.ff_effect_id = effect.id; - p_joypad.ff_effect_timestamp = p_timestamp; -} - -void JoypadLinux::joypad_vibration_stop(Joypad &p_joypad, uint64_t p_timestamp) { - if (!p_joypad.force_feedback || p_joypad.fd == -1 || p_joypad.ff_effect_id == -1) { - return; - } - - if (ioctl(p_joypad.fd, EVIOCRMFF, p_joypad.ff_effect_id) < 0) { - return; - } - - p_joypad.ff_effect_id = -1; - p_joypad.ff_effect_timestamp = p_timestamp; -} - -float JoypadLinux::axis_correct(const input_absinfo *p_abs, int p_value) const { - int min = p_abs->minimum; - int max = p_abs->maximum; - // Convert to a value between -1.0f and 1.0f. - return 2.0f * (p_value - min) / (max - min) - 1.0f; -} - -void JoypadLinux::joypad_events_thread_func(void *p_user) { - if (p_user) { - JoypadLinux *joy = (JoypadLinux *)p_user; - joy->joypad_events_thread_run(); - } -} - -void JoypadLinux::joypad_events_thread_run() { - while (!joypad_events_exit.is_set()) { - bool no_events = true; - for (int i = 0; i < JOYPADS_MAX; i++) { - MutexLock lock(joypads_mutex[i]); - Joypad &joypad = joypads[i]; - if (joypad.fd == -1) { - continue; - } - input_event event; - while (read(joypad.fd, &event, sizeof(event)) > 0) { - no_events = false; - JoypadEvent joypad_event; - joypad_event.type = event.type; - joypad_event.code = event.code; - joypad_event.value = event.value; - joypad.events.push_back(joypad_event); - } - if (errno != EAGAIN) { - close_joypad(joypad, i); - } - } - if (no_events) { - OS::get_singleton()->delay_usec(10'000); - } - } -} - -void JoypadLinux::process_joypads() { - for (int i = 0; i < JOYPADS_MAX; i++) { - MutexLock lock(joypads_mutex[i]); - Joypad &joypad = joypads[i]; - if (joypad.fd == -1) { - continue; - } - for (uint32_t j = 0; j < joypad.events.size(); j++) { - const JoypadEvent &joypad_event = joypad.events[j]; - // joypad_event may be tainted and out of MAX_KEY range, which will cause - // joypad.key_map[joypad_event.code] to crash - if (joypad_event.code >= MAX_KEY) { - return; - } - - switch (joypad_event.type) { - case EV_KEY: - input->joy_button(i, (JoyButton)joypad.key_map[joypad_event.code], joypad_event.value); - break; - - case EV_ABS: - switch (joypad_event.code) { - case ABS_HAT0X: - if (joypad_event.value != 0) { - if (joypad_event.value < 0) { - joypad.dpad.set_flag(HatMask::LEFT); - joypad.dpad.clear_flag(HatMask::RIGHT); - } else { - joypad.dpad.set_flag(HatMask::RIGHT); - joypad.dpad.clear_flag(HatMask::LEFT); - } - } else { - joypad.dpad.clear_flag(HatMask::LEFT); - joypad.dpad.clear_flag(HatMask::RIGHT); - } - input->joy_hat(i, joypad.dpad); - break; - - case ABS_HAT0Y: - if (joypad_event.value != 0) { - if (joypad_event.value < 0) { - joypad.dpad.set_flag(HatMask::UP); - joypad.dpad.clear_flag(HatMask::DOWN); - } else { - joypad.dpad.set_flag(HatMask::DOWN); - joypad.dpad.clear_flag(HatMask::UP); - } - } else { - joypad.dpad.clear_flag(HatMask::UP); - joypad.dpad.clear_flag(HatMask::DOWN); - } - input->joy_hat(i, joypad.dpad); - break; - - default: - if (joypad_event.code >= MAX_ABS) { - return; - } - if (joypad.abs_map[joypad_event.code] != -1 && joypad.abs_info[joypad_event.code]) { - float value = axis_correct(joypad.abs_info[joypad_event.code], joypad_event.value); - joypad.curr_axis[joypad.abs_map[joypad_event.code]] = value; - } - break; - } - break; - } - } - joypad.events.clear(); - - for (int j = 0; j < MAX_ABS; j++) { - int index = joypad.abs_map[j]; - if (index != -1) { - input->joy_axis(i, (JoyAxis)index, joypad.curr_axis[index]); - } - } - - if (joypad.force_feedback) { - uint64_t timestamp = input->get_joy_vibration_timestamp(i); - if (timestamp > joypad.ff_effect_timestamp) { - Vector2 strength = input->get_joy_vibration_strength(i); - float duration = input->get_joy_vibration_duration(i); - if (strength.x == 0 && strength.y == 0) { - joypad_vibration_stop(joypad, timestamp); - } else { - joypad_vibration_start(joypad, strength.x, strength.y, duration, timestamp); - } - } - } - } -} - -#endif // JOYDEV_ENABLED diff --git a/platform/linuxbsd/joypad_linux.h b/platform/linuxbsd/joypad_linux.h deleted file mode 100644 index 5f9f3d9e248..00000000000 --- a/platform/linuxbsd/joypad_linux.h +++ /dev/null @@ -1,136 +0,0 @@ -/**************************************************************************/ -/* joypad_linux.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#pragma once - -#ifdef JOYDEV_ENABLED - -#include "core/input/input.h" -#include "core/os/mutex.h" -#include "core/os/thread.h" -#include "core/templates/local_vector.h" - -struct input_absinfo; - -class JoypadLinux { -public: - JoypadLinux(Input *in); - ~JoypadLinux(); - void process_joypads(); - -private: - enum { - JOYPADS_MAX = 16, - MAX_ABS = 63, - MAX_KEY = 767, // Hack because can't be included here - }; - - struct JoypadEvent { - uint16_t type; - uint16_t code; - int32_t value; - }; - - struct Joypad { - float curr_axis[MAX_ABS]; - int key_map[MAX_KEY]; - int abs_map[MAX_ABS]; - BitField dpad = HatMask::CENTER; - int fd = -1; - - String devpath; - input_absinfo *abs_info[MAX_ABS] = {}; - - bool force_feedback = false; - int ff_effect_id = 0; - uint64_t ff_effect_timestamp = 0; - - LocalVector events; - - ~Joypad(); - void reset(); - }; - -#ifdef UDEV_ENABLED - bool use_udev = false; -#endif - Input *input = nullptr; - - SafeFlag monitor_joypads_exit; - SafeFlag joypad_events_exit; - Thread monitor_joypads_thread; - Thread joypad_events_thread; - - Joypad joypads[JOYPADS_MAX]; - Mutex joypads_mutex[JOYPADS_MAX]; - - Vector attached_devices; - - // List of lowercase words that will prevent the controller from being recognized if its name matches. - // This is done to prevent trackpads, graphics tablets and motherboard LED controllers from being - // recognized as controllers (and taking up controller ID slots as a result). - // Only whole words are matched within the controller name string. The match is case-insensitive. - const Vector banned_words = { - "touchpad", // Matches e.g. "SynPS/2 Synaptics TouchPad", "Sony Interactive Entertainment DualSense Wireless Controller Touchpad" - "trackpad", - "clickpad", - "keyboard", // Matches e.g. "PG-90215 Keyboard", "Usb Keyboard Usb Keyboard Consumer Control" - "mouse", // Matches e.g. "Mouse passthrough" - "pen", // Matches e.g. "Wacom One by Wacom S Pen" - "finger", // Matches e.g. "Wacom HID 495F Finger" - "led", // Matches e.g. "ASRock LED Controller" - }; - - static void monitor_joypads_thread_func(void *p_user); - void monitor_joypads_thread_run(); - - void open_joypad(const char *p_path); - void setup_joypad_properties(Joypad &p_joypad); - - void close_joypads(); - void close_joypad(const char *p_devpath); - void close_joypad(Joypad &p_joypad, int p_id); - -#ifdef UDEV_ENABLED - void enumerate_joypads(struct udev *p_udev); - void monitor_joypads(struct udev *p_udev); -#endif - void monitor_joypads(); - - void joypad_vibration_start(Joypad &p_joypad, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp); - void joypad_vibration_stop(Joypad &p_joypad, uint64_t p_timestamp); - - static void joypad_events_thread_func(void *p_user); - void joypad_events_thread_run(); - - float axis_correct(const input_absinfo *p_abs, int p_value) const; -}; - -#endif // JOYDEV_ENABLED diff --git a/platform/linuxbsd/os_linuxbsd.cpp b/platform/linuxbsd/os_linuxbsd.cpp index 91958cb7633..e99e513ca96 100644 --- a/platform/linuxbsd/os_linuxbsd.cpp +++ b/platform/linuxbsd/os_linuxbsd.cpp @@ -32,6 +32,9 @@ #include "core/io/certs_compressed.gen.h" #include "core/io/dir_access.h" +#ifdef SDL_ENABLED +#include "drivers/sdl/joypad_sdl.h" +#endif #include "main/main.h" #include "servers/display_server.h" #include "servers/rendering_server.h" @@ -158,8 +161,13 @@ void OS_LinuxBSD::initialize() { } void OS_LinuxBSD::initialize_joypads() { -#ifdef JOYDEV_ENABLED - joypad = memnew(JoypadLinux(Input::get_singleton())); +#ifdef SDL_ENABLED + joypad_sdl = memnew(JoypadSDL()); + if (joypad_sdl->initialize() != OK) { + ERR_PRINT("Couldn't initialize SDL joypad input driver."); + memdelete(joypad_sdl); + joypad_sdl = nullptr; + } #endif } @@ -241,9 +249,9 @@ void OS_LinuxBSD::finalize() { driver_alsamidi.close(); #endif -#ifdef JOYDEV_ENABLED - if (joypad) { - memdelete(joypad); +#ifdef SDL_ENABLED + if (joypad_sdl) { + memdelete(joypad_sdl); } #endif } @@ -973,8 +981,10 @@ void OS_LinuxBSD::run() { while (true) { DisplayServer::get_singleton()->process_events(); // get rid of pending events -#ifdef JOYDEV_ENABLED - joypad->process_joypads(); +#ifdef SDL_ENABLED + if (joypad_sdl) { + joypad_sdl->process_events(); + } #endif if (Main::iteration()) { break; diff --git a/platform/linuxbsd/os_linuxbsd.h b/platform/linuxbsd/os_linuxbsd.h index 50bc0910283..fc309607c42 100644 --- a/platform/linuxbsd/os_linuxbsd.h +++ b/platform/linuxbsd/os_linuxbsd.h @@ -31,7 +31,6 @@ #pragma once #include "crash_handler_linuxbsd.h" -#include "joypad_linux.h" #include "core/input/input.h" #include "drivers/alsa/audio_driver_alsa.h" @@ -48,6 +47,8 @@ #endif #endif +class JoypadSDL; + class OS_LinuxBSD : public OS_Unix { virtual void delete_main_loop() override; @@ -60,8 +61,8 @@ class OS_LinuxBSD : public OS_Unix { int _stretch_to_fc(int p_stretch) const; #endif -#ifdef JOYDEV_ENABLED - JoypadLinux *joypad = nullptr; +#ifdef SDL_ENABLED + JoypadSDL *joypad_sdl = nullptr; #endif #ifdef ALSA_ENABLED diff --git a/platform/linuxbsd/x11/display_server_x11.h b/platform/linuxbsd/x11/display_server_x11.h index a2ccc47c390..e155248a3da 100644 --- a/platform/linuxbsd/x11/display_server_x11.h +++ b/platform/linuxbsd/x11/display_server_x11.h @@ -32,8 +32,6 @@ #ifdef X11_ENABLED -#include "joypad_linux.h" - #include "core/input/input.h" #include "core/os/mutex.h" #include "core/os/thread.h" diff --git a/platform/macos/detect.py b/platform/macos/detect.py index 62f92719990..15c92b9798c 100644 --- a/platform/macos/detect.py +++ b/platform/macos/detect.py @@ -197,6 +197,10 @@ def configure(env: "SConsEnvironment"): if env["builtin_libtheora"] and env["arch"] == "x86_64": env["x86_libtheora_opt_gcc"] = True + if env["sdl"]: + env.Append(CPPDEFINES=["SDL_ENABLED"]) + env.Append(LINKFLAGS=["-framework", "ForceFeedback"]) + ## Flags env.Prepend(CPPPATH=["#platform/macos"]) diff --git a/platform/macos/os_macos.h b/platform/macos/os_macos.h index caaeb72fa4e..73294c0fec7 100644 --- a/platform/macos/os_macos.h +++ b/platform/macos/os_macos.h @@ -33,12 +33,13 @@ #include "crash_handler_macos.h" #include "core/input/input.h" -#import "drivers/apple/joypad_apple.h" #import "drivers/coreaudio/audio_driver_coreaudio.h" #import "drivers/coremidi/midi_driver_coremidi.h" #include "drivers/unix/os_unix.h" #include "servers/audio_server.h" +class JoypadSDL; + class OS_MacOS : public OS_Unix { #ifdef COREAUDIO_ENABLED AudioDriverCoreAudio audio_driver; @@ -62,7 +63,9 @@ protected: int argc = 0; char **argv = nullptr; - JoypadApple *joypad_apple = nullptr; +#ifdef SDL_ENABLED + JoypadSDL *joypad_sdl = nullptr; +#endif MainLoop *main_loop = nullptr; CFRunLoopTimerRef wait_timer = nil; diff --git a/platform/macos/os_macos.mm b/platform/macos/os_macos.mm index 09a538bfa0d..f70a24a3c53 100644 --- a/platform/macos/os_macos.mm +++ b/platform/macos/os_macos.mm @@ -43,6 +43,10 @@ #include "drivers/apple/os_log_logger.h" #include "main/main.h" +#ifdef SDL_ENABLED +#include "drivers/sdl/joypad_sdl.h" +#endif + #include #include #import @@ -230,13 +234,22 @@ void OS_MacOS::finalize() { delete_main_loop(); - if (joypad_apple) { - memdelete(joypad_apple); +#ifdef SDL_ENABLED + if (joypad_sdl) { + memdelete(joypad_sdl); } +#endif } void OS_MacOS::initialize_joypads() { - joypad_apple = memnew(JoypadApple()); +#ifdef SDL_ENABLED + joypad_sdl = memnew(JoypadSDL()); + if (joypad_sdl->initialize() != OK) { + ERR_PRINT("Couldn't initialize SDL joypad input driver."); + memdelete(joypad_sdl); + joypad_sdl = nullptr; + } +#endif } void OS_MacOS::set_main_loop(MainLoop *p_main_loop) { @@ -1078,7 +1091,11 @@ void OS_MacOS_NSApp::start_main() { } else if (ds) { ds->process_events(); } - joypad_apple->process_joypads(); +#ifdef SDL_ENABLED + if (joypad_sdl) { + joypad_sdl->process_events(); + } +#endif if (Main::iteration() || sig_received) { terminate(); diff --git a/platform/windows/SCsub b/platform/windows/SCsub index 6ba989903f9..338b6f4d1d7 100644 --- a/platform/windows/SCsub +++ b/platform/windows/SCsub @@ -17,7 +17,6 @@ common_win = [ "os_windows.cpp", "display_server_windows.cpp", "key_mapping_windows.cpp", - "joypad_windows.cpp", "tts_windows.cpp", "windows_terminal_logger.cpp", "windows_utils.cpp", diff --git a/platform/windows/detect.py b/platform/windows/detect.py index 9a5ee8e4679..8bad796db6b 100644 --- a/platform/windows/detect.py +++ b/platform/windows/detect.py @@ -480,6 +480,9 @@ def configure_msvc(env: "SConsEnvironment"): if not env["use_volk"]: LIBS += ["vulkan"] + if env["sdl"]: + env.Append(CPPDEFINES=["SDL_ENABLED"]) + if env["d3d12"]: check_d3d12_installed(env, env["arch"] + "-msvc") @@ -867,6 +870,9 @@ def configure_mingw(env: "SConsEnvironment"): if not env["use_volk"]: env.Append(LIBS=["vulkan"]) + if env["sdl"]: + env.Append(CPPDEFINES=["SDL_ENABLED"]) + if env["d3d12"]: if env["use_llvm"]: check_d3d12_installed(env, env["arch"] + "-llvm") diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp index 805eb970b19..e035ea5bfba 100644 --- a/platform/windows/display_server_windows.cpp +++ b/platform/windows/display_server_windows.cpp @@ -43,6 +43,10 @@ #include "main/main.h" #include "scene/resources/texture.h" +#ifdef SDL_ENABLED +#include "drivers/sdl/joypad_sdl.h" +#endif + #include "servers/rendering/dummy/rasterizer_dummy.h" #if defined(VULKAN_ENABLED) @@ -3771,7 +3775,11 @@ void DisplayServerWindows::process_events() { ERR_FAIL_COND(!Thread::is_main_thread()); if (!drop_events) { - joypad->process_joypads(); +#ifdef SDL_ENABLED + if (joypad_sdl) { + joypad_sdl->process_events(); + } +#endif } _THREAD_SAFE_LOCK_ @@ -5962,9 +5970,6 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA } } break; - case WM_DEVICECHANGE: { - joypad->probe_joypads(); - } break; case WM_DESTROY: { #ifdef ACCESSKIT_ENABLED if (accessibility_driver) { @@ -7155,7 +7160,16 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win ERR_FAIL_MSG("Failed to create main window."); } - joypad = new JoypadWindows(&windows[MAIN_WINDOW_ID].hWnd); +#ifdef SDL_ENABLED + joypad_sdl = memnew(JoypadSDL()); + if (joypad_sdl->initialize() == OK) { + joypad_sdl->setup_sdl_helper_window(windows[MAIN_WINDOW_ID].hWnd); + } else { + ERR_PRINT("Couldn't initialize SDL joypad input driver."); + memdelete(joypad_sdl); + joypad_sdl = nullptr; + } +#endif for (int i = 0; i < WINDOW_FLAG_MAX; i++) { if (p_flags & (1 << i)) { @@ -7309,7 +7323,11 @@ DisplayServerWindows::~DisplayServerWindows() { E->erase(); } - delete joypad; +#ifdef SDL_ENABLED + if (joypad_sdl) { + memdelete(joypad_sdl); + } +#endif touch_state.clear(); cursors_cache.clear(); diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h index f7d588b7458..4c920e66f35 100644 --- a/platform/windows/display_server_windows.h +++ b/platform/windows/display_server_windows.h @@ -31,7 +31,6 @@ #pragma once #include "crash_handler_windows.h" -#include "joypad_windows.h" #include "key_mapping_windows.h" #include "tts_windows.h" @@ -196,6 +195,8 @@ class DropTargetWindows; #define WDA_EXCLUDEFROMCAPTURE 0x00000011 #endif +class JoypadSDL; + class DisplayServerWindows : public DisplayServer { GDSOFTCLASS(DisplayServerWindows, DisplayServer); @@ -375,7 +376,9 @@ class DisplayServerWindows : public DisplayServer { HWND parent_hwnd = 0; }; - JoypadWindows *joypad = nullptr; +#ifdef SDL_ENABLED + JoypadSDL *joypad_sdl = nullptr; +#endif HHOOK mouse_monitor = nullptr; List popup_list; uint64_t time_since_popup = 0; diff --git a/platform/windows/drop_target_windows.cpp b/platform/windows/drop_target_windows.cpp index 5bf62253b5a..842c2016fcb 100644 --- a/platform/windows/drop_target_windows.cpp +++ b/platform/windows/drop_target_windows.cpp @@ -35,6 +35,7 @@ #include "core/os/time.h" #include +#include // Helpers diff --git a/platform/windows/joypad_windows.cpp b/platform/windows/joypad_windows.cpp deleted file mode 100644 index 5628c616999..00000000000 --- a/platform/windows/joypad_windows.cpp +++ /dev/null @@ -1,625 +0,0 @@ -/**************************************************************************/ -/* joypad_windows.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#include "joypad_windows.h" - -#include -#include - -DWORD WINAPI _xinput_get_state(DWORD dwUserIndex, XINPUT_STATE *pState) { - return ERROR_DEVICE_NOT_CONNECTED; -} - -DWORD WINAPI _xinput_set_state(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration) { - return ERROR_DEVICE_NOT_CONNECTED; -} - -MMRESULT WINAPI _winmm_get_joycaps(UINT uJoyID, LPJOYCAPSW pjc, UINT cbjc) { - return MMSYSERR_NODRIVER; -} - -JoypadWindows::JoypadWindows() { -} - -JoypadWindows::JoypadWindows(HWND *hwnd) { - input = Input::get_singleton(); - hWnd = hwnd; - x_joypad_probe_count = 0; - d_joypad_count = 0; - dinput = nullptr; - xinput_dll = nullptr; - xinput_get_state = nullptr; - xinput_set_state = nullptr; - winmm_get_joycaps = nullptr; - - load_xinput(); - - for (int i = 0; i < JOYPADS_MAX; i++) { - attached_joypads[i] = false; - } - - HRESULT result = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&dinput, nullptr); - if (result == DI_OK) { - probe_joypads(); - } else { - ERR_PRINT("Couldn't initialize DirectInput. Error: " + itos(result)); - if (result == DIERR_OUTOFMEMORY) { - ERR_PRINT("The Windows DirectInput subsystem could not allocate sufficient memory."); - ERR_PRINT("Rebooting your PC may solve this issue."); - } - // Ensure dinput is still a nullptr. - dinput = nullptr; - } -} - -JoypadWindows::~JoypadWindows() { - close_d_joypad(); - if (dinput) { - dinput->Release(); - } - unload_winmm(); - unload_xinput(); -} - -bool JoypadWindows::is_d_joypad_known(const GUID &p_guid) { - for (int i = 0; i < JOYPADS_MAX; i++) { - if (d_joypads[i].guid == p_guid) { - d_joypads[i].confirmed = true; - return true; - } - } - return false; -} - -// adapted from SDL2, works a lot better than the MSDN version -bool JoypadWindows::is_xinput_joypad(const GUID *p_guid) { - static GUID IID_ValveStreamingGamepad = { MAKELONG(0x28DE, 0x11FF), 0x28DE, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_X360WiredGamepad = { MAKELONG(0x045E, 0x02A1), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_X360WirelessGamepad = { MAKELONG(0x045E, 0x028E), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_XSWirelessGamepad = { MAKELONG(0x045E, 0x0B13), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_XEliteWirelessGamepad = { MAKELONG(0x045E, 0x0B05), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_XOneWiredGamepad = { MAKELONG(0x045E, 0x02FF), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_XOneWirelessGamepad = { MAKELONG(0x045E, 0x02DD), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_XOneNewWirelessGamepad = { MAKELONG(0x045E, 0x02D1), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_XOneSWirelessGamepad = { MAKELONG(0x045E, 0x02EA), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_XOneSBluetoothGamepad = { MAKELONG(0x045E, 0x02E0), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_XOneEliteWirelessGamepad = { MAKELONG(0x045E, 0x02E3), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - static GUID IID_XOneElite2WirelessGamepad = { MAKELONG(0x045E, 0x0B22), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; - - if (memcmp(p_guid, &IID_ValveStreamingGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_X360WiredGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_X360WirelessGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_XSWirelessGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_XEliteWirelessGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_XOneWiredGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_XOneWirelessGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_XOneNewWirelessGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_XOneSWirelessGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_XOneSBluetoothGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_XOneEliteWirelessGamepad, sizeof(*p_guid)) == 0 || - memcmp(p_guid, &IID_XOneElite2WirelessGamepad, sizeof(*p_guid)) == 0) { - return true; - } - - PRAWINPUTDEVICELIST dev_list = nullptr; - unsigned int dev_list_count = 0; - - if (GetRawInputDeviceList(nullptr, &dev_list_count, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) { - return false; - } - dev_list = (PRAWINPUTDEVICELIST)memalloc(sizeof(RAWINPUTDEVICELIST) * dev_list_count); - ERR_FAIL_NULL_V_MSG(dev_list, false, "Out of memory."); - - if (GetRawInputDeviceList(dev_list, &dev_list_count, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) { - memfree(dev_list); - return false; - } - for (unsigned int i = 0; i < dev_list_count; i++) { - RID_DEVICE_INFO rdi; - char dev_name[128]; - UINT rdiSize = sizeof(rdi); - UINT nameSize = sizeof(dev_name); - - rdi.cbSize = rdiSize; - if ((dev_list[i].dwType == RIM_TYPEHID) && - (GetRawInputDeviceInfoA(dev_list[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) != (UINT)-1) && - (MAKELONG(rdi.hid.dwVendorId, rdi.hid.dwProductId) == (LONG)p_guid->Data1) && - (GetRawInputDeviceInfoA(dev_list[i].hDevice, RIDI_DEVICENAME, &dev_name, &nameSize) != (UINT)-1) && - (strstr(dev_name, "IG_") != nullptr)) { - memfree(dev_list); - return true; - } - } - memfree(dev_list); - return false; -} - -void JoypadWindows::probe_xinput_joypad(const String &name) { - if (x_joypad_probe_count >= XUSER_MAX_COUNT) { - return; - } - int i = x_joypad_probe_count; - x_joypad_probe_count++; - - ZeroMemory(&x_joypads[i].state, sizeof(XINPUT_STATE)); - - DWORD dwResult = xinput_get_state(i, &x_joypads[i].state); - if (dwResult == ERROR_SUCCESS) { - int id = input->get_unused_joy_id(); - if (id != -1 && !x_joypads[i].attached) { - x_joypads[i].attached = true; - x_joypads[i].id = id; - x_joypads[i].ff_timestamp = 0; - x_joypads[i].ff_end_timestamp = 0; - x_joypads[i].vibrating = false; - attached_joypads[id] = true; - Dictionary joypad_info; - String joypad_name; - - joypad_info["xinput_index"] = (int)i; - - JOYCAPSW jc; - memset(&jc, 0, sizeof(JOYCAPSW)); - MMRESULT jcResult = winmm_get_joycaps((UINT)id, &jc, sizeof(JOYCAPSW)); - if (jcResult == JOYERR_NOERROR) { - joypad_info["vendor_id"] = itos(jc.wMid); - joypad_info["product_id"] = itos(jc.wPid); - if (!name.is_empty()) { - joypad_name = name.trim_prefix("Controller (").trim_suffix(")"); - } - } - - input->joy_connection_changed(id, true, joypad_name, "__XINPUT_DEVICE__", joypad_info); - } - } else if (x_joypads[i].attached) { - x_joypads[i].attached = false; - attached_joypads[x_joypads[i].id] = false; - input->joy_connection_changed(x_joypads[i].id, false, ""); - } -} - -bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE *instance) { - ERR_FAIL_NULL_V_MSG(dinput, false, "DirectInput not initialized. Rebooting your PC may solve this issue."); - HRESULT hr; - int num = input->get_unused_joy_id(); - - if (is_d_joypad_known(instance->guidInstance) || num == -1) { - return false; - } - - d_joypads[num] = dinput_gamepad(); - dinput_gamepad *joy = &d_joypads[num]; - - const DWORD devtype = (instance->dwDevType & 0xFF); - - if ((devtype != DI8DEVTYPE_JOYSTICK) && (devtype != DI8DEVTYPE_GAMEPAD) && (devtype != DI8DEVTYPE_1STPERSON) && (devtype != DI8DEVTYPE_DRIVING)) { - return false; - } - - hr = dinput->CreateDevice(instance->guidInstance, &joy->di_joy, nullptr); - - if (FAILED(hr)) { - return false; - } - - const GUID &guid = instance->guidProduct; - char uid[128]; - - ERR_FAIL_COND_V_MSG(memcmp(&guid.Data4[2], "PIDVID", 6), false, "DirectInput device not recognized."); - WORD type = BSWAP16(0x03); - WORD vendor = BSWAP16(LOWORD(guid.Data1)); - WORD product = BSWAP16(HIWORD(guid.Data1)); - WORD version = 0; - sprintf_s(uid, "%04x%04x%04x%04x%04x%04x%04x%04x", type, 0, vendor, 0, product, 0, version, 0); - - Dictionary joypad_info; - joypad_info["vendor_id"] = itos(vendor); - joypad_info["product_id"] = itos(product); - - id_to_change = num; - slider_count = 0; - - joy->di_joy->SetDataFormat(&c_dfDIJoystick2); - joy->di_joy->SetCooperativeLevel(*hWnd, DISCL_FOREGROUND); - joy->di_joy->EnumObjects(objectsCallback, this, 0); - joy->joy_axis.sort(); - - joy->guid = instance->guidInstance; - const String &name = String(instance->tszProductName).trim_prefix("Controller (").trim_suffix(")"); - input->joy_connection_changed(num, true, name, uid, joypad_info); - joy->attached = true; - joy->id = num; - attached_joypads[num] = true; - joy->confirmed = true; - d_joypad_count++; - return true; -} - -void JoypadWindows::setup_d_joypad_object(const DIDEVICEOBJECTINSTANCE *ob, int p_joy_id) { - if (ob->dwType & DIDFT_AXIS) { - HRESULT res; - DIPROPRANGE prop_range; - DIPROPDWORD dilong; - LONG ofs; - if (ob->guidType == GUID_XAxis) { - ofs = DIJOFS_X; - } else if (ob->guidType == GUID_YAxis) { - ofs = DIJOFS_Y; - } else if (ob->guidType == GUID_ZAxis) { - ofs = DIJOFS_Z; - } else if (ob->guidType == GUID_RxAxis) { - ofs = DIJOFS_RX; - } else if (ob->guidType == GUID_RyAxis) { - ofs = DIJOFS_RY; - } else if (ob->guidType == GUID_RzAxis) { - ofs = DIJOFS_RZ; - } else if (ob->guidType == GUID_Slider) { - if (slider_count < 2) { - ofs = DIJOFS_SLIDER(slider_count); - slider_count++; - } else { - return; - } - } else { - return; - } - prop_range.diph.dwSize = sizeof(DIPROPRANGE); - prop_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); - prop_range.diph.dwObj = ob->dwType; - prop_range.diph.dwHow = DIPH_BYID; - prop_range.lMin = -MAX_JOY_AXIS; - prop_range.lMax = +MAX_JOY_AXIS; - - dinput_gamepad &joy = d_joypads[p_joy_id]; - - res = IDirectInputDevice8_SetProperty(joy.di_joy, DIPROP_RANGE, &prop_range.diph); - if (FAILED(res)) { - return; - } - - dilong.diph.dwSize = sizeof(dilong); - dilong.diph.dwHeaderSize = sizeof(dilong.diph); - dilong.diph.dwObj = ob->dwType; - dilong.diph.dwHow = DIPH_BYID; - dilong.dwData = 0; - - res = IDirectInputDevice8_SetProperty(joy.di_joy, DIPROP_DEADZONE, &dilong.diph); - if (FAILED(res)) { - return; - } - - joy.joy_axis.push_back(ofs); - } -} - -BOOL CALLBACK JoypadWindows::enumCallback(const DIDEVICEINSTANCE *p_instance, void *p_context) { - JoypadWindows *self = static_cast(p_context); - if (self->is_xinput_joypad(&p_instance->guidProduct)) { - self->probe_xinput_joypad(p_instance->tszProductName); - return DIENUM_CONTINUE; - } - self->setup_dinput_joypad(p_instance); - return DIENUM_CONTINUE; -} - -BOOL CALLBACK JoypadWindows::objectsCallback(const DIDEVICEOBJECTINSTANCE *p_instance, void *p_context) { - JoypadWindows *self = static_cast(p_context); - self->setup_d_joypad_object(p_instance, self->id_to_change); - - return DIENUM_CONTINUE; -} - -void JoypadWindows::close_d_joypad(int id) { - if (id == -1) { - for (int i = 0; i < JOYPADS_MAX; i++) { - close_d_joypad(i); - } - return; - } - - if (!d_joypads[id].attached) { - return; - } - - d_joypads[id].di_joy->Unacquire(); - d_joypads[id].di_joy->Release(); - d_joypads[id].attached = false; - attached_joypads[d_joypads[id].id] = false; - d_joypads[id].guid.Data1 = d_joypads[id].guid.Data2 = d_joypads[id].guid.Data3 = 0; - input->joy_connection_changed(d_joypads[id].id, false, ""); - d_joypad_count--; -} - -void JoypadWindows::probe_joypads() { - ERR_FAIL_NULL_MSG(dinput, "DirectInput not initialized. Rebooting your PC may solve this issue."); - - for (int i = 0; i < d_joypad_count; i++) { - d_joypads[i].confirmed = false; // Flag DirectInput devices for re-checking their availability. - } - - x_joypad_probe_count = 0; - // Probe _all attached_ joypad devices. - dinput->EnumDevices(DI8DEVCLASS_GAMECTRL, enumCallback, this, DIEDFL_ATTACHEDONLY); - - for (int i = x_joypad_probe_count; i < XUSER_MAX_COUNT; i++) { - // Handle disconnect of XInput devices. - // And act as a fallback, just in case DirectInput could not find the device. - probe_xinput_joypad(); - } - - for (int i = 0; i < d_joypad_count; i++) { - if (!d_joypads[i].confirmed) { - close_d_joypad(i); // Any DirectInput device not found during probing is considered as disconnected. - } - } -} - -void JoypadWindows::process_joypads() { - HRESULT hr; - - // Handle XInput joypads. - for (int i = 0; i < XUSER_MAX_COUNT; i++) { - xinput_gamepad &joy = x_joypads[i]; - if (!joy.attached) { - continue; - } - ZeroMemory(&joy.state, sizeof(XINPUT_STATE)); - - xinput_get_state(i, &joy.state); - if (joy.state.dwPacketNumber != joy.last_packet) { - int button_mask = XINPUT_GAMEPAD_DPAD_UP; - for (int j = 0; j <= 16; j++) { - input->joy_button(joy.id, (JoyButton)j, joy.state.Gamepad.wButtons & button_mask); - button_mask = button_mask * 2; - } - - input->joy_axis(joy.id, JoyAxis::LEFT_X, axis_correct(joy.state.Gamepad.sThumbLX, true)); - input->joy_axis(joy.id, JoyAxis::LEFT_Y, axis_correct(joy.state.Gamepad.sThumbLY, true, false, true)); - input->joy_axis(joy.id, JoyAxis::RIGHT_X, axis_correct(joy.state.Gamepad.sThumbRX, true)); - input->joy_axis(joy.id, JoyAxis::RIGHT_Y, axis_correct(joy.state.Gamepad.sThumbRY, true, false, true)); - input->joy_axis(joy.id, JoyAxis::TRIGGER_LEFT, axis_correct(joy.state.Gamepad.bLeftTrigger, true, true)); - input->joy_axis(joy.id, JoyAxis::TRIGGER_RIGHT, axis_correct(joy.state.Gamepad.bRightTrigger, true, true)); - joy.last_packet = joy.state.dwPacketNumber; - } - uint64_t timestamp = input->get_joy_vibration_timestamp(joy.id); - if (timestamp > joy.ff_timestamp) { - Vector2 strength = input->get_joy_vibration_strength(joy.id); - float duration = input->get_joy_vibration_duration(joy.id); - if (strength.x == 0 && strength.y == 0) { - joypad_vibration_stop_xinput(i, timestamp); - } else { - joypad_vibration_start_xinput(i, strength.x, strength.y, duration, timestamp); - } - } else if (joy.vibrating && joy.ff_end_timestamp != 0) { - uint64_t current_time = OS::get_singleton()->get_ticks_usec(); - if (current_time >= joy.ff_end_timestamp) { - joypad_vibration_stop_xinput(i, current_time); - } - } - } - - // Handle DirectIndput joypads. - for (int i = 0; i < JOYPADS_MAX; i++) { - dinput_gamepad *joy = &d_joypads[i]; - - if (!joy->attached) { - continue; - } - - DIJOYSTATE2 js; - hr = joy->di_joy->Poll(); - if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED) { - IDirectInputDevice8_Acquire(joy->di_joy); - joy->di_joy->Poll(); - } - - hr = joy->di_joy->GetDeviceState(sizeof(DIJOYSTATE2), &js); - if (FAILED(hr)) { - continue; - } - - post_hat(joy->id, js.rgdwPOV[0]); - - for (int j = 0; j < 128; j++) { - if (js.rgbButtons[j] & 0x80) { - if (!joy->last_buttons[j]) { - input->joy_button(joy->id, (JoyButton)j, true); - joy->last_buttons[j] = true; - } - } else { - if (joy->last_buttons[j]) { - input->joy_button(joy->id, (JoyButton)j, false); - joy->last_buttons[j] = false; - } - } - } - - // on mingw, these constants are not constants - int count = 8; - const LONG axes[] = { DIJOFS_X, DIJOFS_Y, DIJOFS_Z, DIJOFS_RX, DIJOFS_RY, DIJOFS_RZ, (LONG)DIJOFS_SLIDER(0), (LONG)DIJOFS_SLIDER(1) }; - int values[] = { js.lX, js.lY, js.lZ, js.lRx, js.lRy, js.lRz, js.rglSlider[0], js.rglSlider[1] }; - - for (uint32_t j = 0; j < joy->joy_axis.size(); j++) { - for (int k = 0; k < count; k++) { - if (joy->joy_axis[j] == axes[k]) { - input->joy_axis(joy->id, (JoyAxis)j, axis_correct(values[k])); - break; - } - } - } - } - return; -} - -void JoypadWindows::post_hat(int p_device, DWORD p_dpad) { - BitField dpad_val = HatMask::CENTER; - - // Should be -1 when centered, but according to docs: - // "Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows: - // BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);" - // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ee416628(v%3Dvs.85)#remarks - if (LOWORD(p_dpad) == 0xFFFF) { - // Do nothing. - // dpad_val.set_flag(HatMask::CENTER); - } - if (p_dpad == 0) { - dpad_val.set_flag(HatMask::UP); - - } else if (p_dpad == 4500) { - dpad_val.set_flag(HatMask::UP); - dpad_val.set_flag(HatMask::RIGHT); - - } else if (p_dpad == 9000) { - dpad_val.set_flag(HatMask::RIGHT); - - } else if (p_dpad == 13500) { - dpad_val.set_flag(HatMask::RIGHT); - dpad_val.set_flag(HatMask::DOWN); - - } else if (p_dpad == 18000) { - dpad_val.set_flag(HatMask::DOWN); - - } else if (p_dpad == 22500) { - dpad_val.set_flag(HatMask::DOWN); - dpad_val.set_flag(HatMask::LEFT); - - } else if (p_dpad == 27000) { - dpad_val.set_flag(HatMask::LEFT); - - } else if (p_dpad == 31500) { - dpad_val.set_flag(HatMask::LEFT); - dpad_val.set_flag(HatMask::UP); - } - input->joy_hat(p_device, dpad_val); -} - -float JoypadWindows::axis_correct(int p_val, bool p_xinput, bool p_trigger, bool p_negate) const { - if (Math::abs(p_val) < MIN_JOY_AXIS) { - return p_trigger ? -1.0f : 0.0f; - } - if (!p_xinput) { - return p_val / (float)MAX_JOY_AXIS; - } - if (p_trigger) { - // Convert to a value between -1.0f and 1.0f. - return 2.0f * p_val / (float)MAX_TRIGGER - 1.0f; - } - float value; - if (p_val < 0) { - value = p_val / (float)MAX_JOY_AXIS; - } else { - value = p_val / (float)(MAX_JOY_AXIS - 1); - } - if (p_negate) { - value = -value; - } - return value; -} - -void JoypadWindows::joypad_vibration_start_xinput(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) { - xinput_gamepad &joy = x_joypads[p_device]; - if (joy.attached) { - XINPUT_VIBRATION effect; - effect.wLeftMotorSpeed = (65535 * p_strong_magnitude); - effect.wRightMotorSpeed = (65535 * p_weak_magnitude); - if (xinput_set_state(p_device, &effect) == ERROR_SUCCESS) { - joy.ff_timestamp = p_timestamp; - joy.ff_end_timestamp = p_duration == 0 ? 0 : p_timestamp + (uint64_t)(p_duration * 1000000.0); - joy.vibrating = true; - } - } -} - -void JoypadWindows::joypad_vibration_stop_xinput(int p_device, uint64_t p_timestamp) { - xinput_gamepad &joy = x_joypads[p_device]; - if (joy.attached) { - XINPUT_VIBRATION effect; - effect.wLeftMotorSpeed = 0; - effect.wRightMotorSpeed = 0; - if (xinput_set_state(p_device, &effect) == ERROR_SUCCESS) { - joy.ff_timestamp = p_timestamp; - joy.vibrating = false; - } - } -} - -void JoypadWindows::load_xinput() { - xinput_get_state = &_xinput_get_state; - xinput_set_state = &_xinput_set_state; - winmm_get_joycaps = &_winmm_get_joycaps; - bool legacy_xinput = false; - - xinput_dll = LoadLibrary("XInput1_4.dll"); - if (!xinput_dll) { - xinput_dll = LoadLibrary("XInput1_3.dll"); - if (!xinput_dll) { - xinput_dll = LoadLibrary("XInput9_1_0.dll"); - legacy_xinput = true; - } - } - - if (!xinput_dll) { - print_verbose("Could not find XInput, using DirectInput only"); - return; - } - - // (LPCSTR)100 is the magic number to get XInputGetStateEx, which also provides the state for the guide button - LPCSTR get_state_func_name = legacy_xinput ? "XInputGetState" : (LPCSTR)100; - XInputGetState_t func = (XInputGetState_t)(void *)GetProcAddress((HMODULE)xinput_dll, get_state_func_name); - XInputSetState_t set_func = (XInputSetState_t)(void *)GetProcAddress((HMODULE)xinput_dll, "XInputSetState"); - if (!func || !set_func) { - unload_xinput(); - return; - } - xinput_get_state = func; - xinput_set_state = set_func; - - winmm_dll = LoadLibrary("Winmm.dll"); - if (winmm_dll) { - joyGetDevCaps_t caps_func = (joyGetDevCaps_t)(void *)GetProcAddress((HMODULE)winmm_dll, "joyGetDevCapsW"); - if (caps_func) { - winmm_get_joycaps = caps_func; - } else { - unload_winmm(); - } - } -} - -void JoypadWindows::unload_xinput() { - if (xinput_dll) { - FreeLibrary((HMODULE)xinput_dll); - } -} - -void JoypadWindows::unload_winmm() { - if (winmm_dll) { - FreeLibrary((HMODULE)winmm_dll); - } -} diff --git a/platform/windows/joypad_windows.h b/platform/windows/joypad_windows.h deleted file mode 100644 index de0db6d5d30..00000000000 --- a/platform/windows/joypad_windows.h +++ /dev/null @@ -1,149 +0,0 @@ -/**************************************************************************/ -/* joypad_windows.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#pragma once - -#include "os_windows.h" - -#define DIRECTINPUT_VERSION 0x0800 -#include -#include - -#include - -#ifndef SAFE_RELEASE // when Windows Media Device M? is not present -#define SAFE_RELEASE(x) \ - if (x != nullptr) { \ - x->Release(); \ - x = nullptr; \ - } -#endif - -#ifndef XUSER_MAX_COUNT -#define XUSER_MAX_COUNT 4 -#endif - -class JoypadWindows { -public: - JoypadWindows(); - JoypadWindows(HWND *hwnd); - ~JoypadWindows(); - - void probe_joypads(); - void process_joypads(); - -private: - enum { - JOYPADS_MAX = 16, - JOY_AXIS_COUNT = 6, - MIN_JOY_AXIS = 10, - MAX_JOY_AXIS = 32768, - MAX_JOY_BUTTONS = 128, - KEY_EVENT_BUFFER_SIZE = 512, - MAX_TRIGGER = 255 - }; - - struct dinput_gamepad { - int id; - bool attached; - bool confirmed; - bool last_buttons[MAX_JOY_BUTTONS]; - DWORD last_pad; - - LPDIRECTINPUTDEVICE8 di_joy; - LocalVector joy_axis; - GUID guid; - - dinput_gamepad() { - id = -1; - last_pad = -1; - attached = false; - confirmed = false; - di_joy = nullptr; - guid = {}; - - for (int i = 0; i < MAX_JOY_BUTTONS; i++) { - last_buttons[i] = false; - } - } - }; - - struct xinput_gamepad { - int id = 0; - bool attached = false; - bool vibrating = false; - DWORD last_packet = 0; - XINPUT_STATE state; - uint64_t ff_timestamp = 0; - uint64_t ff_end_timestamp = 0; - }; - - typedef DWORD(WINAPI *XInputGetState_t)(DWORD dwUserIndex, XINPUT_STATE *pState); - typedef DWORD(WINAPI *XInputSetState_t)(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration); - - typedef MMRESULT(WINAPI *joyGetDevCaps_t)(UINT uJoyID, LPJOYCAPSW pjc, UINT cbjc); - - HWND *hWnd = nullptr; - HANDLE xinput_dll; - HANDLE winmm_dll; - LPDIRECTINPUT8 dinput; - Input *input = nullptr; - - int id_to_change; - int slider_count; - int x_joypad_probe_count; // XInput equivalent to dinput_gamepad.confirmed. - int d_joypad_count; - bool attached_joypads[JOYPADS_MAX]; - dinput_gamepad d_joypads[JOYPADS_MAX]; - xinput_gamepad x_joypads[XUSER_MAX_COUNT]; - - static BOOL CALLBACK enumCallback(const DIDEVICEINSTANCE *p_instance, void *p_context); - static BOOL CALLBACK objectsCallback(const DIDEVICEOBJECTINSTANCE *instance, void *context); - - void setup_d_joypad_object(const DIDEVICEOBJECTINSTANCE *ob, int p_joy_id); - void close_d_joypad(int id = -1); - void load_xinput(); - void unload_xinput(); - void unload_winmm(); - - void post_hat(int p_device, DWORD p_dpad); - - bool is_d_joypad_known(const GUID &p_guid); - bool is_xinput_joypad(const GUID *p_guid); - bool setup_dinput_joypad(const DIDEVICEINSTANCE *instance); - void probe_xinput_joypad(const String &name = ""); // Handles connect, disconnect & re-connect for XInput joypads. - void joypad_vibration_start_xinput(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp); - void joypad_vibration_stop_xinput(int p_device, uint64_t p_timestamp); - - float axis_correct(int p_val, bool p_xinput = false, bool p_trigger = false, bool p_negate = false) const; - XInputGetState_t xinput_get_state; - XInputSetState_t xinput_set_state; - joyGetDevCaps_t winmm_get_joycaps; // Only for reading info on XInput joypads. -}; diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp index e4b9bf33205..c7b0bfd1d7d 100644 --- a/platform/windows/os_windows.cpp +++ b/platform/windows/os_windows.cpp @@ -31,7 +31,6 @@ #include "os_windows.h" #include "display_server_windows.h" -#include "joypad_windows.h" #include "lang_table.h" #include "windows_terminal_logger.h" #include "windows_utils.h" diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h index 11f86999292..aeb64472725 100644 --- a/platform/windows/os_windows.h +++ b/platform/windows/os_windows.h @@ -67,6 +67,14 @@ #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4 #endif +#ifndef SAFE_RELEASE // when Windows Media Device M? is not present +#define SAFE_RELEASE(x) \ + if (x != nullptr) { \ + x->Release(); \ + x = nullptr; \ + } +#endif + template class ComAutoreleaseRef { public: @@ -90,8 +98,6 @@ public: } }; -class JoypadWindows; - class OS_Windows : public OS { uint64_t target_ticks = 0; uint64_t ticks_start = 0; diff --git a/thirdparty/README.md b/thirdparty/README.md index 904b7c7e195..f6b2abb6dcf 100644 --- a/thirdparty/README.md +++ b/thirdparty/README.md @@ -447,6 +447,20 @@ Files extracted from upstream source: - Except `main.cc`, `harfbuzz*.cc`, `failing-alloc.c`, `test*.cc`, `hb-wasm*.*`, `wasm/*` +## hidapi + +- Upstream: https://github.com/libsdl-org/SDL/tree/main/src/hidapi +- Version: 0.14.0 (8d604353a53853fa56d1bdce0363535605ca868f, 2025) +- License: BSD-3-Clause + +Files extracted from upstream source: + +- See `thirdparty/sdl/update-sdl.sh` + +The source code of this library is being bundled with SDL's source code files. +The files of hidapi are stored in `thirdparty/sdl/hidapi/` folder. + + ## icu4c - Upstream: https://github.com/unicode-org/icu @@ -942,6 +956,25 @@ Files extracted from upstream source: - Textures generated using the Python scripts in the `Scripts` folder +## sdl + +- Upstream: https://github.com/libsdl-org/SDL +- Version: 3.2.14 (8d604353a53853fa56d1bdce0363535605ca868f, 2025) +- License: Zlib + +Files extracted from upstream source: + +- See `thirdparty/sdl/update-sdl.sh` + +Patches: + +- `0001-remove-unnecessary-subsystems.patch` (GH-106218) +- `0002-msvc-constants-fpstrict.patch` (GH-106218) + +The SDL source code folder includes `hidapi` library inside of folder `thirdparty/sdl/hidapi/`. +Its version and license is described in this file under `hidapi`. + + ## spirv-cross - Upstream: https://github.com/KhronosGroup/SPIRV-Cross diff --git a/thirdparty/sdl/CREDITS.md b/thirdparty/sdl/CREDITS.md new file mode 100644 index 00000000000..55105a88e5d --- /dev/null +++ b/thirdparty/sdl/CREDITS.md @@ -0,0 +1,38 @@ +# Simple DirectMedia Layer CREDITS + +Thanks to everyone who made this possible, including: + +- Cliff Matthews, for giving me a reason to start this project. :) -- Executor rocks! *grin* +- Ryan Gordon for helping everybody out and keeping the dream alive. :) +- Frank Praznik for his Wayland support and general windowing development. +- Ozkan Sezer for sanity checks and make sure the i's are dotted and t's are crossed. +- Anonymous Maarten for CMake support and build system development. +- Evan Hemsley, Caleb Cornett, and Ethan Lee for SDL GPU development. +- Gabriel Jacobo for his work on the Android port and generally helping out all around. +- Philipp Wiesemann for his attention to detail reviewing the entire SDL code base and proposes patches. +- Andreas Schiffler for his dedication to unit tests, Visual Studio projects, and managing the Google Summer of Code. +- Mike Sartain for incorporating SDL into Team Fortress 2 and cheering me on at Valve. +- Alfred Reynolds for the game controller API and general (in)sanity +- Jørgen Tjernø¸ for numerous magical macOS fixes. +- Pierre-Loup Griffais for his deep knowledge of OpenGL drivers. +- Julian Winter for the SDL 2.0 website. +- Sheena Smith for many months of great work on the SDL wiki creating the API documentation and style guides. +- Paul Hunkin for his port of SDL to Android during the Google Summer of Code 2010. +- Eli Gottlieb for his work on shaped windows during the Google Summer of Code 2010. +- Jim Grandpre for his work on multi-touch and gesture recognition during + the Google Summer of Code 2010. +- Edgar "bobbens" Simo for his force feedback API development during the + Google Summer of Code 2008. +- Aaron Wishnick for his work on audio resampling and pitch shifting during + the Google Summer of Code 2008. +- Holmes Futrell for his port of SDL to the iPhone and iPod Touch during the + Google Summer of Code 2008. +- Jon Atkins for SDL_image, SDL_mixer and SDL_net documentation. +- Everybody at Loki Software, Inc. and Valve Corporation for their great contributions! + + And a big hand to everyone else who has contributed over the years. + +THANKS! :) + + -- Sam Lantinga + diff --git a/thirdparty/sdl/LICENSE.txt b/thirdparty/sdl/LICENSE.txt new file mode 100644 index 00000000000..23abb73f2b6 --- /dev/null +++ b/thirdparty/sdl/LICENSE.txt @@ -0,0 +1,18 @@ +Copyright (C) 1997-2025 Sam Lantinga + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + diff --git a/thirdparty/sdl/SDL.c b/thirdparty/sdl/SDL.c new file mode 100644 index 00000000000..dd0b823634a --- /dev/null +++ b/thirdparty/sdl/SDL.c @@ -0,0 +1,841 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" +#include "SDL3/SDL_revision.h" + +#if defined(SDL_PLATFORM_WINDOWS) +#include "core/windows/SDL_windows.h" +#else +#include // _exit(), etc. +#endif + +// this checks for HAVE_DBUS_DBUS_H internally. +#include "core/linux/SDL_dbus.h" + +#ifdef SDL_PLATFORM_EMSCRIPTEN +#include +#endif + +// Initialization code for SDL + +#include "SDL_assert_c.h" +#include "SDL_hints_c.h" +#include "SDL_log_c.h" +#include "SDL_properties_c.h" +//#include "audio/SDL_sysaudio.h" +#include "events/SDL_events_c.h" +#include "haptic/SDL_haptic_c.h" +#include "joystick/SDL_gamepad_c.h" +#include "joystick/SDL_joystick_c.h" +#include "sensor/SDL_sensor_c.h" +#include "stdlib/SDL_getenv_c.h" +#include "thread/SDL_thread_c.h" +#ifdef SDL_PLATFORM_ANDROID +#include "core/android/SDL_android.h" +#endif + +#define SDL_INIT_EVERYTHING ~0U + +// Initialization/Cleanup routines +#include "timer/SDL_timer_c.h" +#ifdef SDL_VIDEO_DRIVER_WINDOWS +extern bool SDL_HelperWindowCreate(void); +extern void SDL_HelperWindowDestroy(void); +#endif + +#ifdef SDL_BUILD_MAJOR_VERSION +SDL_COMPILE_TIME_ASSERT(SDL_BUILD_MAJOR_VERSION, + SDL_MAJOR_VERSION == SDL_BUILD_MAJOR_VERSION); +SDL_COMPILE_TIME_ASSERT(SDL_BUILD_MINOR_VERSION, + SDL_MINOR_VERSION == SDL_BUILD_MINOR_VERSION); +SDL_COMPILE_TIME_ASSERT(SDL_BUILD_MICRO_VERSION, + SDL_MICRO_VERSION == SDL_BUILD_MICRO_VERSION); +#endif + +// Limited by its encoding in SDL_VERSIONNUM +SDL_COMPILE_TIME_ASSERT(SDL_MAJOR_VERSION_min, SDL_MAJOR_VERSION >= 0); +SDL_COMPILE_TIME_ASSERT(SDL_MAJOR_VERSION_max, SDL_MAJOR_VERSION <= 10); +SDL_COMPILE_TIME_ASSERT(SDL_MINOR_VERSION_min, SDL_MINOR_VERSION >= 0); +SDL_COMPILE_TIME_ASSERT(SDL_MINOR_VERSION_max, SDL_MINOR_VERSION <= 999); +SDL_COMPILE_TIME_ASSERT(SDL_MICRO_VERSION_min, SDL_MICRO_VERSION >= 0); +SDL_COMPILE_TIME_ASSERT(SDL_MICRO_VERSION_max, SDL_MICRO_VERSION <= 999); + +/* This is not declared in any header, although it is shared between some + parts of SDL, because we don't want anything calling it without an + extremely good reason. */ +extern SDL_NORETURN void SDL_ExitProcess(int exitcode); +SDL_NORETURN void SDL_ExitProcess(int exitcode) +{ +#if defined(SDL_PLATFORM_WINDOWS) + /* "if you do not know the state of all threads in your process, it is + better to call TerminateProcess than ExitProcess" + https://msdn.microsoft.com/en-us/library/windows/desktop/ms682658(v=vs.85).aspx */ + TerminateProcess(GetCurrentProcess(), exitcode); + /* MingW doesn't have TerminateProcess marked as noreturn, so add an + ExitProcess here that will never be reached but make MingW happy. */ + ExitProcess(exitcode); +#elif defined(SDL_PLATFORM_EMSCRIPTEN) + emscripten_cancel_main_loop(); // this should "kill" the app. + emscripten_force_exit(exitcode); // this should "kill" the app. + exit(exitcode); +#elif defined(SDL_PLATFORM_HAIKU) // Haiku has _Exit, but it's not marked noreturn. + _exit(exitcode); +#elif defined(HAVE__EXIT) // Upper case _Exit() + _Exit(exitcode); +#else + _exit(exitcode); +#endif +} + +// App metadata + +bool SDL_SetAppMetadata(const char *appname, const char *appversion, const char *appidentifier) +{ + SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_NAME_STRING, appname); + SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_VERSION_STRING, appversion); + SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_IDENTIFIER_STRING, appidentifier); + return true; +} + +static bool SDL_ValidMetadataProperty(const char *name) +{ + if (!name || !*name) { + return false; + } + + if (SDL_strcmp(name, SDL_PROP_APP_METADATA_NAME_STRING) == 0 || + SDL_strcmp(name, SDL_PROP_APP_METADATA_VERSION_STRING) == 0 || + SDL_strcmp(name, SDL_PROP_APP_METADATA_IDENTIFIER_STRING) == 0 || + SDL_strcmp(name, SDL_PROP_APP_METADATA_CREATOR_STRING) == 0 || + SDL_strcmp(name, SDL_PROP_APP_METADATA_COPYRIGHT_STRING) == 0 || + SDL_strcmp(name, SDL_PROP_APP_METADATA_URL_STRING) == 0 || + SDL_strcmp(name, SDL_PROP_APP_METADATA_TYPE_STRING) == 0) { + return true; + } + return false; +} + +bool SDL_SetAppMetadataProperty(const char *name, const char *value) +{ + if (!SDL_ValidMetadataProperty(name)) { + return SDL_InvalidParamError("name"); + } + + return SDL_SetStringProperty(SDL_GetGlobalProperties(), name, value); +} + +const char *SDL_GetAppMetadataProperty(const char *name) +{ + if (!SDL_ValidMetadataProperty(name)) { + SDL_InvalidParamError("name"); + return NULL; + } + + const char *value = NULL; + if (SDL_strcmp(name, SDL_PROP_APP_METADATA_NAME_STRING) == 0) { + value = SDL_GetHint(SDL_HINT_APP_NAME); + } else if (SDL_strcmp(name, SDL_PROP_APP_METADATA_IDENTIFIER_STRING) == 0) { + value = SDL_GetHint(SDL_HINT_APP_ID); + } + if (!value || !*value) { + value = SDL_GetStringProperty(SDL_GetGlobalProperties(), name, NULL); + } + if (!value || !*value) { + if (SDL_strcmp(name, SDL_PROP_APP_METADATA_NAME_STRING) == 0) { + value = "SDL Application"; + } else if (SDL_strcmp(name, SDL_PROP_APP_METADATA_TYPE_STRING) == 0) { + value = "application"; + } + } + return value; +} + + +// The initialized subsystems +#ifdef SDL_MAIN_NEEDED +static bool SDL_MainIsReady = false; +#else +static bool SDL_MainIsReady = true; +#endif +static SDL_ThreadID SDL_MainThreadID = 0; +static bool SDL_bInMainQuit = false; +static Uint8 SDL_SubsystemRefCount[32]; + +// Private helper to increment a subsystem's ref counter. +static void SDL_IncrementSubsystemRefCount(Uint32 subsystem) +{ + const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); + SDL_assert((subsystem_index < 0) || (SDL_SubsystemRefCount[subsystem_index] < 255)); + if (subsystem_index >= 0) { + ++SDL_SubsystemRefCount[subsystem_index]; + } +} + +// Private helper to decrement a subsystem's ref counter. +static void SDL_DecrementSubsystemRefCount(Uint32 subsystem) +{ + const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); + if ((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] > 0)) { + if (SDL_bInMainQuit) { + SDL_SubsystemRefCount[subsystem_index] = 0; + } else { + --SDL_SubsystemRefCount[subsystem_index]; + } + } +} + +// Private helper to check if a system needs init. +static bool SDL_ShouldInitSubsystem(Uint32 subsystem) +{ + const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); + SDL_assert((subsystem_index < 0) || (SDL_SubsystemRefCount[subsystem_index] < 255)); + return ((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] == 0)); +} + +// Private helper to check if a system needs to be quit. +static bool SDL_ShouldQuitSubsystem(Uint32 subsystem) +{ + const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); + if ((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] == 0)) { + return false; + } + + /* If we're in SDL_Quit, we shut down every subsystem, even if refcount + * isn't zero. + */ + return (((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] == 1)) || SDL_bInMainQuit); +} + +/* Private helper to either increment's existing ref counter, + * or fully init a new subsystem. */ +static bool SDL_InitOrIncrementSubsystem(Uint32 subsystem) +{ + int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); + SDL_assert((subsystem_index < 0) || (SDL_SubsystemRefCount[subsystem_index] < 255)); + if (subsystem_index < 0) { + return false; + } + if (SDL_SubsystemRefCount[subsystem_index] > 0) { + ++SDL_SubsystemRefCount[subsystem_index]; + return true; + } + return SDL_InitSubSystem(subsystem); +} + +void SDL_SetMainReady(void) +{ + SDL_MainIsReady = true; + + if (SDL_MainThreadID == 0) { + SDL_MainThreadID = SDL_GetCurrentThreadID(); + } +} + +bool SDL_IsMainThread(void) +{ + if (SDL_MainThreadID == 0) { + // Not initialized yet? + return true; + } + if (SDL_MainThreadID == SDL_GetCurrentThreadID()) { + return true; + } + return false; +} + +// Initialize all the subsystems that require initialization before threads start +void SDL_InitMainThread(void) +{ + static bool done_info = false; + + SDL_InitTLSData(); + SDL_InitEnvironment(); + SDL_InitTicks(); + //SDL_InitFilesystem(); + + if (!done_info) { + const char *value; + + value = SDL_GetAppMetadataProperty(SDL_PROP_APP_METADATA_NAME_STRING); + SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "App name: %s", value ? value : ""); + value = SDL_GetAppMetadataProperty(SDL_PROP_APP_METADATA_VERSION_STRING); + SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "App version: %s", value ? value : ""); + value = SDL_GetAppMetadataProperty(SDL_PROP_APP_METADATA_IDENTIFIER_STRING); + SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "App ID: %s", value ? value : ""); + SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "SDL revision: %s", SDL_REVISION); + + done_info = true; + } +} + +static void SDL_QuitMainThread(void) +{ + //SDL_QuitFilesystem(); + SDL_QuitTicks(); + SDL_QuitEnvironment(); + SDL_QuitTLSData(); +} + +bool SDL_InitSubSystem(SDL_InitFlags flags) +{ + Uint32 flags_initialized = 0; + + if (!SDL_MainIsReady) { + return SDL_SetError("Application didn't initialize properly, did you include SDL_main.h in the file containing your main() function?"); + } + + SDL_InitMainThread(); + +#ifdef SDL_USE_LIBDBUS + SDL_DBus_Init(); +#endif + +#ifdef SDL_VIDEO_DRIVER_WINDOWS + if (flags & (SDL_INIT_HAPTIC | SDL_INIT_JOYSTICK)) { + if (!SDL_HelperWindowCreate()) { + goto quit_and_error; + } + } +#endif + + // Initialize the event subsystem + if (flags & SDL_INIT_EVENTS) { + if (SDL_ShouldInitSubsystem(SDL_INIT_EVENTS)) { + SDL_IncrementSubsystemRefCount(SDL_INIT_EVENTS); + if (!SDL_InitEvents()) { + SDL_DecrementSubsystemRefCount(SDL_INIT_EVENTS); + goto quit_and_error; + } + } else { + SDL_IncrementSubsystemRefCount(SDL_INIT_EVENTS); + } + flags_initialized |= SDL_INIT_EVENTS; + } + + // Initialize the video subsystem + if (flags & SDL_INIT_VIDEO) { +#ifndef SDL_VIDEO_DISABLED + if (SDL_ShouldInitSubsystem(SDL_INIT_VIDEO)) { + // video implies events + if (!SDL_InitOrIncrementSubsystem(SDL_INIT_EVENTS)) { + goto quit_and_error; + } + + // We initialize video on the main thread + // On Apple platforms this is a requirement. + // On other platforms, this is the definition. + SDL_MainThreadID = SDL_GetCurrentThreadID(); + + SDL_IncrementSubsystemRefCount(SDL_INIT_VIDEO); + if (!SDL_VideoInit(NULL)) { + SDL_DecrementSubsystemRefCount(SDL_INIT_VIDEO); + SDL_PushError(); + SDL_QuitSubSystem(SDL_INIT_EVENTS); + SDL_PopError(); + goto quit_and_error; + } + } else { + SDL_IncrementSubsystemRefCount(SDL_INIT_VIDEO); + } + flags_initialized |= SDL_INIT_VIDEO; +#else + SDL_SetError("SDL not built with video support"); + goto quit_and_error; +#endif + } + + // Initialize the audio subsystem + if (flags & SDL_INIT_AUDIO) { +#ifndef SDL_AUDIO_DISABLED + if (SDL_ShouldInitSubsystem(SDL_INIT_AUDIO)) { + // audio implies events + if (!SDL_InitOrIncrementSubsystem(SDL_INIT_EVENTS)) { + goto quit_and_error; + } + + SDL_IncrementSubsystemRefCount(SDL_INIT_AUDIO); + if (!SDL_InitAudio(NULL)) { + SDL_DecrementSubsystemRefCount(SDL_INIT_AUDIO); + SDL_PushError(); + SDL_QuitSubSystem(SDL_INIT_EVENTS); + SDL_PopError(); + goto quit_and_error; + } + } else { + SDL_IncrementSubsystemRefCount(SDL_INIT_AUDIO); + } + flags_initialized |= SDL_INIT_AUDIO; +#else + SDL_SetError("SDL not built with audio support"); + goto quit_and_error; +#endif + } + + // Initialize the joystick subsystem + if (flags & SDL_INIT_JOYSTICK) { +#ifndef SDL_JOYSTICK_DISABLED + if (SDL_ShouldInitSubsystem(SDL_INIT_JOYSTICK)) { + // joystick implies events + if (!SDL_InitOrIncrementSubsystem(SDL_INIT_EVENTS)) { + goto quit_and_error; + } + + SDL_IncrementSubsystemRefCount(SDL_INIT_JOYSTICK); + if (!SDL_InitJoysticks()) { + SDL_DecrementSubsystemRefCount(SDL_INIT_JOYSTICK); + SDL_PushError(); + SDL_QuitSubSystem(SDL_INIT_EVENTS); + SDL_PopError(); + goto quit_and_error; + } + } else { + SDL_IncrementSubsystemRefCount(SDL_INIT_JOYSTICK); + } + flags_initialized |= SDL_INIT_JOYSTICK; +#else + SDL_SetError("SDL not built with joystick support"); + goto quit_and_error; +#endif + } + + if (flags & SDL_INIT_GAMEPAD) { +#ifndef SDL_JOYSTICK_DISABLED + if (SDL_ShouldInitSubsystem(SDL_INIT_GAMEPAD)) { + // game controller implies joystick + if (!SDL_InitOrIncrementSubsystem(SDL_INIT_JOYSTICK)) { + goto quit_and_error; + } + + SDL_IncrementSubsystemRefCount(SDL_INIT_GAMEPAD); + if (!SDL_InitGamepads()) { + SDL_DecrementSubsystemRefCount(SDL_INIT_GAMEPAD); + SDL_PushError(); + SDL_QuitSubSystem(SDL_INIT_JOYSTICK); + SDL_PopError(); + goto quit_and_error; + } + } else { + SDL_IncrementSubsystemRefCount(SDL_INIT_GAMEPAD); + } + flags_initialized |= SDL_INIT_GAMEPAD; +#else + SDL_SetError("SDL not built with joystick support"); + goto quit_and_error; +#endif + } + + // Initialize the haptic subsystem + if (flags & SDL_INIT_HAPTIC) { +#ifndef SDL_HAPTIC_DISABLED + if (SDL_ShouldInitSubsystem(SDL_INIT_HAPTIC)) { + SDL_IncrementSubsystemRefCount(SDL_INIT_HAPTIC); + if (!SDL_InitHaptics()) { + SDL_DecrementSubsystemRefCount(SDL_INIT_HAPTIC); + goto quit_and_error; + } + } else { + SDL_IncrementSubsystemRefCount(SDL_INIT_HAPTIC); + } + flags_initialized |= SDL_INIT_HAPTIC; +#else + SDL_SetError("SDL not built with haptic (force feedback) support"); + goto quit_and_error; +#endif + } + + // Initialize the sensor subsystem + if (flags & SDL_INIT_SENSOR) { +#ifndef SDL_SENSOR_DISABLED + if (SDL_ShouldInitSubsystem(SDL_INIT_SENSOR)) { + SDL_IncrementSubsystemRefCount(SDL_INIT_SENSOR); + if (!SDL_InitSensors()) { + SDL_DecrementSubsystemRefCount(SDL_INIT_SENSOR); + goto quit_and_error; + } + } else { + SDL_IncrementSubsystemRefCount(SDL_INIT_SENSOR); + } + flags_initialized |= SDL_INIT_SENSOR; +#else + SDL_SetError("SDL not built with sensor support"); + goto quit_and_error; +#endif + } + + // Initialize the camera subsystem + if (flags & SDL_INIT_CAMERA) { +#ifndef SDL_CAMERA_DISABLED + if (SDL_ShouldInitSubsystem(SDL_INIT_CAMERA)) { + // camera implies events + if (!SDL_InitOrIncrementSubsystem(SDL_INIT_EVENTS)) { + goto quit_and_error; + } + + SDL_IncrementSubsystemRefCount(SDL_INIT_CAMERA); + if (!SDL_CameraInit(NULL)) { + SDL_DecrementSubsystemRefCount(SDL_INIT_CAMERA); + SDL_PushError(); + SDL_QuitSubSystem(SDL_INIT_EVENTS); + SDL_PopError(); + goto quit_and_error; + } + } else { + SDL_IncrementSubsystemRefCount(SDL_INIT_CAMERA); + } + flags_initialized |= SDL_INIT_CAMERA; +#else + SDL_SetError("SDL not built with camera support"); + goto quit_and_error; +#endif + } + + (void)flags_initialized; // make static analysis happy, since this only gets used in error cases. + + return SDL_ClearError(); + +quit_and_error: + { + SDL_PushError(); + SDL_QuitSubSystem(flags_initialized); + SDL_PopError(); + } + return false; +} + +bool SDL_Init(SDL_InitFlags flags) +{ + return SDL_InitSubSystem(flags); +} + +void SDL_QuitSubSystem(SDL_InitFlags flags) +{ + // Shut down requested initialized subsystems + +#ifndef SDL_CAMERA_DISABLED + if (flags & SDL_INIT_CAMERA) { + if (SDL_ShouldQuitSubsystem(SDL_INIT_CAMERA)) { + SDL_QuitCamera(); + // camera implies events + SDL_QuitSubSystem(SDL_INIT_EVENTS); + } + SDL_DecrementSubsystemRefCount(SDL_INIT_CAMERA); + } +#endif + +#ifndef SDL_SENSOR_DISABLED + if (flags & SDL_INIT_SENSOR) { + if (SDL_ShouldQuitSubsystem(SDL_INIT_SENSOR)) { + SDL_QuitSensors(); + } + SDL_DecrementSubsystemRefCount(SDL_INIT_SENSOR); + } +#endif + +#ifndef SDL_JOYSTICK_DISABLED + if (flags & SDL_INIT_GAMEPAD) { + if (SDL_ShouldQuitSubsystem(SDL_INIT_GAMEPAD)) { + SDL_QuitGamepads(); + // game controller implies joystick + SDL_QuitSubSystem(SDL_INIT_JOYSTICK); + } + SDL_DecrementSubsystemRefCount(SDL_INIT_GAMEPAD); + } + + if (flags & SDL_INIT_JOYSTICK) { + if (SDL_ShouldQuitSubsystem(SDL_INIT_JOYSTICK)) { + SDL_QuitJoysticks(); + // joystick implies events + SDL_QuitSubSystem(SDL_INIT_EVENTS); + } + SDL_DecrementSubsystemRefCount(SDL_INIT_JOYSTICK); + } +#endif + +#ifndef SDL_HAPTIC_DISABLED + if (flags & SDL_INIT_HAPTIC) { + if (SDL_ShouldQuitSubsystem(SDL_INIT_HAPTIC)) { + SDL_QuitHaptics(); + } + SDL_DecrementSubsystemRefCount(SDL_INIT_HAPTIC); + } +#endif + +#ifndef SDL_AUDIO_DISABLED + if (flags & SDL_INIT_AUDIO) { + if (SDL_ShouldQuitSubsystem(SDL_INIT_AUDIO)) { + SDL_QuitAudio(); + // audio implies events + SDL_QuitSubSystem(SDL_INIT_EVENTS); + } + SDL_DecrementSubsystemRefCount(SDL_INIT_AUDIO); + } +#endif + +#ifndef SDL_VIDEO_DISABLED + if (flags & SDL_INIT_VIDEO) { + if (SDL_ShouldQuitSubsystem(SDL_INIT_VIDEO)) { + SDL_QuitRender(); + SDL_VideoQuit(); + // video implies events + SDL_QuitSubSystem(SDL_INIT_EVENTS); + } + SDL_DecrementSubsystemRefCount(SDL_INIT_VIDEO); + } +#endif + + if (flags & SDL_INIT_EVENTS) { + if (SDL_ShouldQuitSubsystem(SDL_INIT_EVENTS)) { + SDL_QuitEvents(); + } + SDL_DecrementSubsystemRefCount(SDL_INIT_EVENTS); + } +} + +Uint32 SDL_WasInit(SDL_InitFlags flags) +{ + int i; + int num_subsystems = SDL_arraysize(SDL_SubsystemRefCount); + Uint32 initialized = 0; + + // Fast path for checking one flag + if (SDL_HasExactlyOneBitSet32(flags)) { + int subsystem_index = SDL_MostSignificantBitIndex32(flags); + return SDL_SubsystemRefCount[subsystem_index] ? flags : 0; + } + + if (!flags) { + flags = SDL_INIT_EVERYTHING; + } + + num_subsystems = SDL_min(num_subsystems, SDL_MostSignificantBitIndex32(flags) + 1); + + // Iterate over each bit in flags, and check the matching subsystem. + for (i = 0; i < num_subsystems; ++i) { + if ((flags & 1) && SDL_SubsystemRefCount[i] > 0) { + initialized |= (1 << i); + } + + flags >>= 1; + } + + return initialized; +} + +void SDL_Quit(void) +{ + SDL_bInMainQuit = true; + + // Quit all subsystems +#ifdef SDL_VIDEO_DRIVER_WINDOWS + SDL_HelperWindowDestroy(); +#endif + SDL_QuitSubSystem(SDL_INIT_EVERYTHING); + //SDL_CleanupTrays(); + +#ifdef SDL_USE_LIBDBUS + SDL_DBus_Quit(); +#endif + + SDL_QuitTimers(); + //SDL_QuitAsyncIO(); + + SDL_SetObjectsInvalid(); + SDL_AssertionsQuit(); + + //SDL_QuitPixelFormatDetails(); + + //SDL_QuitCPUInfo(); + + /* Now that every subsystem has been quit, we reset the subsystem refcount + * and the list of initialized subsystems. + */ + SDL_memset(SDL_SubsystemRefCount, 0x0, sizeof(SDL_SubsystemRefCount)); + + SDL_QuitLog(); + SDL_QuitHints(); + SDL_QuitProperties(); + + SDL_QuitMainThread(); + + SDL_bInMainQuit = false; +} + +// Get the library version number +int SDL_GetVersion(void) +{ + return SDL_VERSION; +} + +// Get the library source revision +const char *SDL_GetRevision(void) +{ + return SDL_REVISION; +} + +// Get the name of the platform +const char *SDL_GetPlatform(void) +{ +#if defined(SDL_PLATFORM_PRIVATE) + return SDL_PLATFORM_PRIVATE_NAME; +#elif defined(SDL_PLATFORM_AIX) + return "AIX"; +#elif defined(SDL_PLATFORM_ANDROID) + return "Android"; +#elif defined(SDL_PLATFORM_BSDI) + return "BSDI"; +#elif defined(SDL_PLATFORM_EMSCRIPTEN) + return "Emscripten"; +#elif defined(SDL_PLATFORM_FREEBSD) + return "FreeBSD"; +#elif defined(SDL_PLATFORM_HAIKU) + return "Haiku"; +#elif defined(SDL_PLATFORM_HPUX) + return "HP-UX"; +#elif defined(SDL_PLATFORM_IRIX) + return "Irix"; +#elif defined(SDL_PLATFORM_LINUX) + return "Linux"; +#elif defined(__MINT__) + return "Atari MiNT"; +#elif defined(SDL_PLATFORM_MACOS) + return "macOS"; +#elif defined(SDL_PLATFORM_NETBSD) + return "NetBSD"; +#elif defined(SDL_PLATFORM_OPENBSD) + return "OpenBSD"; +#elif defined(SDL_PLATFORM_OS2) + return "OS/2"; +#elif defined(SDL_PLATFORM_OSF) + return "OSF/1"; +#elif defined(SDL_PLATFORM_QNXNTO) + return "QNX Neutrino"; +#elif defined(SDL_PLATFORM_RISCOS) + return "RISC OS"; +#elif defined(SDL_PLATFORM_SOLARIS) + return "Solaris"; +#elif defined(SDL_PLATFORM_WIN32) + return "Windows"; +#elif defined(SDL_PLATFORM_WINGDK) + return "WinGDK"; +#elif defined(SDL_PLATFORM_XBOXONE) + return "Xbox One"; +#elif defined(SDL_PLATFORM_XBOXSERIES) + return "Xbox Series X|S"; +#elif defined(SDL_PLATFORM_IOS) + return "iOS"; +#elif defined(SDL_PLATFORM_TVOS) + return "tvOS"; +#elif defined(SDL_PLATFORM_PS2) + return "PlayStation 2"; +#elif defined(SDL_PLATFORM_PSP) + return "PlayStation Portable"; +#elif defined(SDL_PLATFORM_VITA) + return "PlayStation Vita"; +#elif defined(SDL_PLATFORM_3DS) + return "Nintendo 3DS"; +#elif defined(__managarm__) + return "Managarm"; +#else + return "Unknown (see SDL_platform.h)"; +#endif +} + +bool SDL_IsTablet(void) +{ +#ifdef SDL_PLATFORM_ANDROID + return SDL_IsAndroidTablet(); +#elif defined(SDL_PLATFORM_IOS) + extern bool SDL_IsIPad(void); + return SDL_IsIPad(); +#else + return false; +#endif +} + +bool SDL_IsTV(void) +{ +#ifdef SDL_PLATFORM_ANDROID + return SDL_IsAndroidTV(); +#elif defined(SDL_PLATFORM_IOS) + extern bool SDL_IsAppleTV(void); + return SDL_IsAppleTV(); +#else + return false; +#endif +} + +static SDL_Sandbox SDL_DetectSandbox(void) +{ +#if defined(SDL_PLATFORM_LINUX) + if (access("/.flatpak-info", F_OK) == 0) { + return SDL_SANDBOX_FLATPAK; + } + + /* For Snap, we check multiple variables because they might be set for + * unrelated reasons. This is the same thing WebKitGTK does. */ + if (SDL_getenv("SNAP") && SDL_getenv("SNAP_NAME") && SDL_getenv("SNAP_REVISION")) { + return SDL_SANDBOX_SNAP; + } + + if (access("/run/host/container-manager", F_OK) == 0) { + return SDL_SANDBOX_UNKNOWN_CONTAINER; + } + +#elif defined(SDL_PLATFORM_MACOS) + if (SDL_getenv("APP_SANDBOX_CONTAINER_ID")) { + return SDL_SANDBOX_MACOS; + } +#endif + + return SDL_SANDBOX_NONE; +} + +SDL_Sandbox SDL_GetSandbox(void) +{ + static SDL_Sandbox sandbox; + static bool sandbox_initialized; + + if (!sandbox_initialized) { + sandbox = SDL_DetectSandbox(); + sandbox_initialized = true; + } + return sandbox; +} + +#ifdef SDL_PLATFORM_WIN32 + +#if (!defined(HAVE_LIBC) || defined(__WATCOMC__)) && !defined(SDL_STATIC_LIB) +// FIXME: Still need to include DllMain() on Watcom C ? + +BOOL APIENTRY MINGW32_FORCEALIGN _DllMainCRTStartup(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) +{ + switch (ul_reason_for_call) { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} +#endif // Building DLL + +#endif // defined(SDL_PLATFORM_WIN32) diff --git a/thirdparty/sdl/SDL_assert.c b/thirdparty/sdl/SDL_assert.c new file mode 100644 index 00000000000..af904039a49 --- /dev/null +++ b/thirdparty/sdl/SDL_assert.c @@ -0,0 +1,443 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(SDL_PLATFORM_WINDOWS) +#include "core/windows/SDL_windows.h" +#endif + +#include "SDL_assert_c.h" +//#include "video/SDL_sysvideo.h" + +#if defined(SDL_PLATFORM_WINDOWS) +#ifndef WS_OVERLAPPEDWINDOW +#define WS_OVERLAPPEDWINDOW 0 +#endif +#endif + +#ifdef SDL_PLATFORM_EMSCRIPTEN +#include +#endif + +// The size of the stack buffer to use for rendering assert messages. +#define SDL_MAX_ASSERT_MESSAGE_STACK 256 + +static SDL_AssertState SDLCALL SDL_PromptAssertion(const SDL_AssertData *data, void *userdata); + +/* + * We keep all triggered assertions in a singly-linked list so we can + * generate a report later. + */ +static SDL_AssertData *triggered_assertions = NULL; + +#ifndef SDL_THREADS_DISABLED +static SDL_Mutex *assertion_mutex = NULL; +#endif + +static SDL_AssertionHandler assertion_handler = SDL_PromptAssertion; +static void *assertion_userdata = NULL; + +#ifdef __GNUC__ +static void debug_print(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +#endif + +static void debug_print(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + SDL_LogMessageV(SDL_LOG_CATEGORY_ASSERT, SDL_LOG_PRIORITY_WARN, fmt, ap); + va_end(ap); +} + +static void SDL_AddAssertionToReport(SDL_AssertData *data) +{ + /* (data) is always a static struct defined with the assert macros, so + we don't have to worry about copying or allocating them. */ + data->trigger_count++; + if (data->trigger_count == 1) { // not yet added? + data->next = triggered_assertions; + triggered_assertions = data; + } +} + +#if defined(SDL_PLATFORM_WINDOWS) +#define ENDLINE "\r\n" +#else +#define ENDLINE "\n" +#endif + +static int SDL_RenderAssertMessage(char *buf, size_t buf_len, const SDL_AssertData *data) +{ + return SDL_snprintf(buf, buf_len, + "Assertion failure at %s (%s:%d), triggered %u %s:" ENDLINE " '%s'", + data->function, data->filename, data->linenum, + data->trigger_count, (data->trigger_count == 1) ? "time" : "times", + data->condition); +} + +static void SDL_GenerateAssertionReport(void) +{ + const SDL_AssertData *item = triggered_assertions; + + // only do this if the app hasn't assigned an assertion handler. + if ((item) && (assertion_handler != SDL_PromptAssertion)) { + debug_print("\n\nSDL assertion report.\n"); + debug_print("All SDL assertions between last init/quit:\n\n"); + + while (item) { + debug_print( + "'%s'\n" + " * %s (%s:%d)\n" + " * triggered %u time%s.\n" + " * always ignore: %s.\n", + item->condition, item->function, item->filename, + item->linenum, item->trigger_count, + (item->trigger_count == 1) ? "" : "s", + item->always_ignore ? "yes" : "no"); + item = item->next; + } + debug_print("\n"); + + SDL_ResetAssertionReport(); + } +} + +/* This is not declared in any header, although it is shared between some + parts of SDL, because we don't want anything calling it without an + extremely good reason. */ +#ifdef __WATCOMC__ +extern void SDL_ExitProcess(int exitcode); +#pragma aux SDL_ExitProcess aborts; +#endif +extern SDL_NORETURN void SDL_ExitProcess(int exitcode); + +#ifdef __WATCOMC__ +static void SDL_AbortAssertion(void); +#pragma aux SDL_AbortAssertion aborts; +#endif +static SDL_NORETURN void SDL_AbortAssertion(void) +{ + SDL_Quit(); + SDL_ExitProcess(42); +} + +static SDL_AssertState SDLCALL SDL_PromptAssertion(const SDL_AssertData *data, void *userdata) +{ + SDL_AssertState state = SDL_ASSERTION_ABORT; + SDL_Window *window; + SDL_MessageBoxData messagebox; + SDL_MessageBoxButtonData buttons[] = { + { 0, SDL_ASSERTION_RETRY, "Retry" }, + { 0, SDL_ASSERTION_BREAK, "Break" }, + { 0, SDL_ASSERTION_ABORT, "Abort" }, + { SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, + SDL_ASSERTION_IGNORE, "Ignore" }, + { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, + SDL_ASSERTION_ALWAYS_IGNORE, "Always Ignore" } + }; + int selected; + + char stack_buf[SDL_MAX_ASSERT_MESSAGE_STACK]; + char *message = stack_buf; + size_t buf_len = sizeof(stack_buf); + int len; + + (void)userdata; // unused in default handler. + + // Assume the output will fit... + len = SDL_RenderAssertMessage(message, buf_len, data); + + // .. and if it didn't, try to allocate as much room as we actually need. + if (len >= (int)buf_len) { + if (SDL_size_add_check_overflow(len, 1, &buf_len)) { + message = (char *)SDL_malloc(buf_len); + if (message) { + len = SDL_RenderAssertMessage(message, buf_len, data); + } else { + message = stack_buf; + } + } + } + + // Something went very wrong + if (len < 0) { + if (message != stack_buf) { + SDL_free(message); + } + return SDL_ASSERTION_ABORT; + } + + debug_print("\n\n%s\n\n", message); + + // let env. variable override, so unit tests won't block in a GUI. + const char *hint = SDL_GetHint(SDL_HINT_ASSERT); + if (hint) { + if (message != stack_buf) { + SDL_free(message); + } + + if (SDL_strcmp(hint, "abort") == 0) { + return SDL_ASSERTION_ABORT; + } else if (SDL_strcmp(hint, "break") == 0) { + return SDL_ASSERTION_BREAK; + } else if (SDL_strcmp(hint, "retry") == 0) { + return SDL_ASSERTION_RETRY; + } else if (SDL_strcmp(hint, "ignore") == 0) { + return SDL_ASSERTION_IGNORE; + } else if (SDL_strcmp(hint, "always_ignore") == 0) { + return SDL_ASSERTION_ALWAYS_IGNORE; + } else { + return SDL_ASSERTION_ABORT; // oh well. + } + } + + // Show a messagebox if we can, otherwise fall back to stdio + SDL_zero(messagebox); + messagebox.flags = SDL_MESSAGEBOX_WARNING; + messagebox.window = window; + messagebox.title = "Assertion Failed"; + messagebox.message = message; + messagebox.numbuttons = SDL_arraysize(buttons); + messagebox.buttons = buttons; + + //if (SDL_ShowMessageBox(&messagebox, &selected)) { + if (false) { + if (selected == -1) { + state = SDL_ASSERTION_IGNORE; + } else { + state = (SDL_AssertState)selected; + } + } else { +#ifdef SDL_PLATFORM_PRIVATE_ASSERT + SDL_PRIVATE_PROMPTASSERTION(); +#elif defined(SDL_PLATFORM_EMSCRIPTEN) + // This is nasty, but we can't block on a custom UI. + for (;;) { + bool okay = true; + /* *INDENT-OFF* */ // clang-format off + int reply = MAIN_THREAD_EM_ASM_INT({ + var str = + UTF8ToString($0) + '\n\n' + + 'Abort/Retry/Ignore/AlwaysIgnore? [ariA] :'; + var reply = window.prompt(str, "i"); + if (reply === null) { + reply = "i"; + } + return reply.length === 1 ? reply.charCodeAt(0) : -1; + }, message); + /* *INDENT-ON* */ // clang-format on + + switch (reply) { + case 'a': + state = SDL_ASSERTION_ABORT; + break; +#if 0 // (currently) no break functionality on Emscripten + case 'b': + state = SDL_ASSERTION_BREAK; + break; +#endif + case 'r': + state = SDL_ASSERTION_RETRY; + break; + case 'i': + state = SDL_ASSERTION_IGNORE; + break; + case 'A': + state = SDL_ASSERTION_ALWAYS_IGNORE; + break; + default: + okay = false; + break; + } + + if (okay) { + break; + } + } +#elif defined(HAVE_STDIO_H) && !defined(SDL_PLATFORM_3DS) + // this is a little hacky. + for (;;) { + char buf[32]; + (void)fprintf(stderr, "Abort/Break/Retry/Ignore/AlwaysIgnore? [abriA] : "); + (void)fflush(stderr); + if (fgets(buf, sizeof(buf), stdin) == NULL) { + break; + } + + if (SDL_strncmp(buf, "a", 1) == 0) { + state = SDL_ASSERTION_ABORT; + break; + } else if (SDL_strncmp(buf, "b", 1) == 0) { + state = SDL_ASSERTION_BREAK; + break; + } else if (SDL_strncmp(buf, "r", 1) == 0) { + state = SDL_ASSERTION_RETRY; + break; + } else if (SDL_strncmp(buf, "i", 1) == 0) { + state = SDL_ASSERTION_IGNORE; + break; + } else if (SDL_strncmp(buf, "A", 1) == 0) { + state = SDL_ASSERTION_ALWAYS_IGNORE; + break; + } + } +#else + //SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Assertion Failed", message, window); +#endif // HAVE_STDIO_H + } + + // Re-enter fullscreen mode + if (window) { + //SDL_RestoreWindow(window); + } + + if (message != stack_buf) { + SDL_free(message); + } + + return state; +} + +SDL_AssertState SDL_ReportAssertion(SDL_AssertData *data, const char *func, const char *file, int line) +{ + SDL_AssertState state = SDL_ASSERTION_IGNORE; + static int assertion_running = 0; + +#ifndef SDL_THREADS_DISABLED + static SDL_SpinLock spinlock = 0; + SDL_LockSpinlock(&spinlock); + if (!assertion_mutex) { // never called SDL_Init()? + assertion_mutex = SDL_CreateMutex(); + if (!assertion_mutex) { + SDL_UnlockSpinlock(&spinlock); + return SDL_ASSERTION_IGNORE; // oh well, I guess. + } + } + SDL_UnlockSpinlock(&spinlock); + + SDL_LockMutex(assertion_mutex); +#endif // !SDL_THREADS_DISABLED + + // doing this because Visual C is upset over assigning in the macro. + if (data->trigger_count == 0) { + data->function = func; + data->filename = file; + data->linenum = line; + } + + SDL_AddAssertionToReport(data); + + assertion_running++; + if (assertion_running > 1) { // assert during assert! Abort. + if (assertion_running == 2) { + SDL_AbortAssertion(); + } else if (assertion_running == 3) { // Abort asserted! + SDL_ExitProcess(42); + } else { + while (1) { // do nothing but spin; what else can you do?! + } + } + } + + if (!data->always_ignore) { + state = assertion_handler(data, assertion_userdata); + } + + switch (state) { + case SDL_ASSERTION_ALWAYS_IGNORE: + state = SDL_ASSERTION_IGNORE; + data->always_ignore = true; + break; + + case SDL_ASSERTION_IGNORE: + case SDL_ASSERTION_RETRY: + case SDL_ASSERTION_BREAK: + break; // macro handles these. + + case SDL_ASSERTION_ABORT: + SDL_AbortAssertion(); + // break; ...shouldn't return, but oh well. + } + + assertion_running--; + +#ifndef SDL_THREADS_DISABLED + SDL_UnlockMutex(assertion_mutex); +#endif + + return state; +} + +void SDL_AssertionsQuit(void) +{ +#if SDL_ASSERT_LEVEL > 0 + SDL_GenerateAssertionReport(); +#ifndef SDL_THREADS_DISABLED + if (assertion_mutex) { + SDL_DestroyMutex(assertion_mutex); + assertion_mutex = NULL; + } +#endif +#endif // SDL_ASSERT_LEVEL > 0 +} + +void SDL_SetAssertionHandler(SDL_AssertionHandler handler, void *userdata) +{ + if (handler != NULL) { + assertion_handler = handler; + assertion_userdata = userdata; + } else { + assertion_handler = SDL_PromptAssertion; + assertion_userdata = NULL; + } +} + +const SDL_AssertData *SDL_GetAssertionReport(void) +{ + return triggered_assertions; +} + +void SDL_ResetAssertionReport(void) +{ + SDL_AssertData *next = NULL; + SDL_AssertData *item; + for (item = triggered_assertions; item; item = next) { + next = (SDL_AssertData *)item->next; + item->always_ignore = false; + item->trigger_count = 0; + item->next = NULL; + } + + triggered_assertions = NULL; +} + +SDL_AssertionHandler SDL_GetDefaultAssertionHandler(void) +{ + return SDL_PromptAssertion; +} + +SDL_AssertionHandler SDL_GetAssertionHandler(void **userdata) +{ + if (userdata) { + *userdata = assertion_userdata; + } + return assertion_handler; +} diff --git a/thirdparty/sdl/SDL_assert_c.h b/thirdparty/sdl/SDL_assert_c.h new file mode 100644 index 00000000000..d892dbef8ae --- /dev/null +++ b/thirdparty/sdl/SDL_assert_c.h @@ -0,0 +1,28 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_assert_c_h_ +#define SDL_assert_c_h_ + +extern void SDL_AssertionsQuit(void); + +#endif // SDL_assert_c_h_ diff --git a/thirdparty/sdl/SDL_error.c b/thirdparty/sdl/SDL_error.c new file mode 100644 index 00000000000..3c62c8aff48 --- /dev/null +++ b/thirdparty/sdl/SDL_error.c @@ -0,0 +1,112 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// Simple error handling in SDL + +#include "SDL_error_c.h" + +bool SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + bool result; + + va_start(ap, fmt); + result = SDL_SetErrorV(fmt, ap); + va_end(ap); + return result; +} + +bool SDL_SetErrorV(SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) +{ + // Ignore call if invalid format pointer was passed + if (fmt) { + int result; + SDL_error *error = SDL_GetErrBuf(true); + va_list ap2; + + error->error = SDL_ErrorCodeGeneric; + + va_copy(ap2, ap); + result = SDL_vsnprintf(error->str, error->len, fmt, ap2); + va_end(ap2); + + if (result >= 0 && (size_t)result >= error->len && error->realloc_func) { + size_t len = (size_t)result + 1; + char *str = (char *)error->realloc_func(error->str, len); + if (str) { + error->str = str; + error->len = len; + va_copy(ap2, ap); + (void)SDL_vsnprintf(error->str, error->len, fmt, ap2); + va_end(ap2); + } + } + +// Enable this if you want to see all errors printed as they occur. +// Note that there are many recoverable errors that may happen internally and +// can be safely ignored if the public API doesn't return an error code. +#if 0 + SDL_LogError(SDL_LOG_CATEGORY_ERROR, "%s", error->str); +#endif + } + + return false; +} + +const char *SDL_GetError(void) +{ + const SDL_error *error = SDL_GetErrBuf(false); + + if (!error) { + return ""; + } + + switch (error->error) { + case SDL_ErrorCodeGeneric: + return error->str; + case SDL_ErrorCodeOutOfMemory: + return "Out of memory"; + default: + return ""; + } +} + +bool SDL_ClearError(void) +{ + SDL_error *error = SDL_GetErrBuf(false); + + if (error) { + error->error = SDL_ErrorCodeNone; + } + return true; +} + +bool SDL_OutOfMemory(void) +{ + SDL_error *error = SDL_GetErrBuf(true); + + if (error) { + error->error = SDL_ErrorCodeOutOfMemory; + } + return false; +} + diff --git a/thirdparty/sdl/SDL_error_c.h b/thirdparty/sdl/SDL_error_c.h new file mode 100644 index 00000000000..ba4550ed029 --- /dev/null +++ b/thirdparty/sdl/SDL_error_c.h @@ -0,0 +1,61 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +/* This file defines a structure that carries language-independent + error messages +*/ + +#ifndef SDL_error_c_h_ +#define SDL_error_c_h_ + +typedef enum +{ + SDL_ErrorCodeNone, + SDL_ErrorCodeGeneric, + SDL_ErrorCodeOutOfMemory, +} SDL_ErrorCode; + +typedef struct SDL_error +{ + SDL_ErrorCode error; + char *str; + size_t len; + SDL_realloc_func realloc_func; + SDL_free_func free_func; +} SDL_error; + +// Defined in SDL_thread.c +extern SDL_error *SDL_GetErrBuf(bool create); + +// Macros to save and restore error values +#define SDL_PushError() \ + char *saved_error = SDL_strdup(SDL_GetError()) + +#define SDL_PopError() \ + do { \ + if (saved_error) { \ + SDL_SetError("%s", saved_error); \ + SDL_free(saved_error); \ + } \ + } while (0) + +#endif // SDL_error_c_h_ diff --git a/thirdparty/sdl/SDL_guid.c b/thirdparty/sdl/SDL_guid.c new file mode 100644 index 00000000000..6c355d8dd90 --- /dev/null +++ b/thirdparty/sdl/SDL_guid.c @@ -0,0 +1,88 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// convert the guid to a printable string +void SDL_GUIDToString(SDL_GUID guid, char *pszGUID, int cbGUID) +{ + static const char k_rgchHexToASCII[] = "0123456789abcdef"; + int i; + + if ((!pszGUID) || (cbGUID <= 0)) { + return; + } + + for (i = 0; i < sizeof(guid.data) && i < (cbGUID - 1) / 2; i++) { + // each input byte writes 2 ascii chars, and might write a null byte. + // If we don't have room for next input byte, stop + unsigned char c = guid.data[i]; + + *pszGUID++ = k_rgchHexToASCII[c >> 4]; + *pszGUID++ = k_rgchHexToASCII[c & 0x0F]; + } + *pszGUID = '\0'; +} + +/*----------------------------------------------------------------------------- + * Purpose: Returns the 4 bit nibble for a hex character + * Input : c - + * Output : unsigned char + *-----------------------------------------------------------------------------*/ +static unsigned char nibble(unsigned char c) +{ + if ((c >= '0') && (c <= '9')) { + return c - '0'; + } + + if ((c >= 'A') && (c <= 'F')) { + return c - 'A' + 0x0a; + } + + if ((c >= 'a') && (c <= 'f')) { + return c - 'a' + 0x0a; + } + + // received an invalid character, and no real way to return an error + // AssertMsg1(false, "Q_nibble invalid hex character '%c' ", c); + return 0; +} + +// convert the string version of a guid to the struct +SDL_GUID SDL_StringToGUID(const char *pchGUID) +{ + SDL_GUID guid; + int maxoutputbytes = sizeof(guid); + size_t len = SDL_strlen(pchGUID); + Uint8 *p; + size_t i; + + // Make sure it's even + len = (len) & ~0x1; + + SDL_memset(&guid, 0x00, sizeof(guid)); + + p = (Uint8 *)&guid; + for (i = 0; (i < len) && ((p - (Uint8 *)&guid) < maxoutputbytes); i += 2, p++) { + *p = (nibble((unsigned char)pchGUID[i]) << 4) | nibble((unsigned char)pchGUID[i + 1]); + } + + return guid; +} diff --git a/thirdparty/sdl/SDL_hashtable.c b/thirdparty/sdl/SDL_hashtable.c new file mode 100644 index 00000000000..3124b41a8a9 --- /dev/null +++ b/thirdparty/sdl/SDL_hashtable.c @@ -0,0 +1,543 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +typedef struct SDL_HashItem +{ + // TODO: Splitting off values into a separate array might be more cache-friendly + const void *key; + const void *value; + Uint32 hash; + Uint32 probe_len : 31; + Uint32 live : 1; +} SDL_HashItem; + +// Must be a power of 2 >= sizeof(SDL_HashItem) +#define MAX_HASHITEM_SIZEOF 32u +SDL_COMPILE_TIME_ASSERT(sizeof_SDL_HashItem, sizeof(SDL_HashItem) <= MAX_HASHITEM_SIZEOF); + +// Anything larger than this will cause integer overflows +#define MAX_HASHTABLE_SIZE (0x80000000u / (MAX_HASHITEM_SIZEOF)) + +struct SDL_HashTable +{ + SDL_RWLock *lock; // NULL if not created threadsafe + SDL_HashItem *table; + SDL_HashCallback hash; + SDL_HashKeyMatchCallback keymatch; + SDL_HashDestroyCallback destroy; + void *userdata; + Uint32 hash_mask; + Uint32 max_probe_len; + Uint32 num_occupied_slots; +}; + + +static Uint32 CalculateHashBucketsFromEstimate(int estimated_capacity) +{ + if (estimated_capacity <= 0) { + return 4; // start small, grow as necessary. + } + + const Uint32 estimated32 = (Uint32) estimated_capacity; + Uint32 buckets = ((Uint32) 1) << SDL_MostSignificantBitIndex32(estimated32); + if (!SDL_HasExactlyOneBitSet32(estimated32)) { + buckets <<= 1; // need next power of two up to fit overflow capacity bits. + } + + return SDL_min(buckets, MAX_HASHTABLE_SIZE); +} + +SDL_HashTable *SDL_CreateHashTable(int estimated_capacity, bool threadsafe, SDL_HashCallback hash, + SDL_HashKeyMatchCallback keymatch, + SDL_HashDestroyCallback destroy, void *userdata) +{ + const Uint32 num_buckets = CalculateHashBucketsFromEstimate(estimated_capacity); + SDL_HashTable *table = (SDL_HashTable *)SDL_calloc(1, sizeof(SDL_HashTable)); + if (!table) { + return NULL; + } + + if (threadsafe) { + table->lock = SDL_CreateRWLock(); + if (!table->lock) { + SDL_DestroyHashTable(table); + return NULL; + } + } + + table->table = (SDL_HashItem *)SDL_calloc(num_buckets, sizeof(SDL_HashItem)); + if (!table->table) { + SDL_DestroyHashTable(table); + return NULL; + } + + table->hash_mask = num_buckets - 1; + table->userdata = userdata; + table->hash = hash; + table->keymatch = keymatch; + table->destroy = destroy; + return table; +} + +static SDL_INLINE Uint32 calc_hash(const SDL_HashTable *table, const void *key) +{ + const Uint32 BitMixer = 0x9E3779B1u; + return table->hash(table->userdata, key) * BitMixer; +} + +static SDL_INLINE Uint32 get_probe_length(Uint32 zero_idx, Uint32 actual_idx, Uint32 num_buckets) +{ + // returns the probe sequence length from zero_idx to actual_idx + if (actual_idx < zero_idx) { + return num_buckets - zero_idx + actual_idx; + } + + return actual_idx - zero_idx; +} + +static SDL_HashItem *find_item(const SDL_HashTable *ht, const void *key, Uint32 hash, Uint32 *i, Uint32 *probe_len) +{ + Uint32 hash_mask = ht->hash_mask; + Uint32 max_probe_len = ht->max_probe_len; + + SDL_HashItem *table = ht->table; + + while (true) { + SDL_HashItem *item = table + *i; + Uint32 item_hash = item->hash; + + if (!item->live) { + return NULL; + } + + if (item_hash == hash && ht->keymatch(ht->userdata, item->key, key)) { + return item; + } + + Uint32 item_probe_len = item->probe_len; + SDL_assert(item_probe_len == get_probe_length(item_hash & hash_mask, (Uint32)(item - table), hash_mask + 1)); + + if (*probe_len > item_probe_len) { + return NULL; + } + + if (++*probe_len > max_probe_len) { + return NULL; + } + + *i = (*i + 1) & hash_mask; + } +} + +static SDL_HashItem *find_first_item(const SDL_HashTable *ht, const void *key, Uint32 hash) +{ + Uint32 i = hash & ht->hash_mask; + Uint32 probe_len = 0; + return find_item(ht, key, hash, &i, &probe_len); +} + +static SDL_HashItem *insert_item(SDL_HashItem *item_to_insert, SDL_HashItem *table, Uint32 hash_mask, Uint32 *max_probe_len_ptr) +{ + const Uint32 num_buckets = hash_mask + 1; + Uint32 idx = item_to_insert->hash & hash_mask; + SDL_HashItem *target = NULL; + SDL_HashItem temp_item; + + while (true) { + SDL_HashItem *candidate = table + idx; + + if (!candidate->live) { + // Found an empty slot. Put it here and we're done. + *candidate = *item_to_insert; + + if (target == NULL) { + target = candidate; + } + + const Uint32 probe_len = get_probe_length(candidate->hash & hash_mask, idx, num_buckets); + candidate->probe_len = probe_len; + + if (*max_probe_len_ptr < probe_len) { + *max_probe_len_ptr = probe_len; + } + + break; + } + + const Uint32 candidate_probe_len = candidate->probe_len; + SDL_assert(candidate_probe_len == get_probe_length(candidate->hash & hash_mask, idx, num_buckets)); + const Uint32 new_probe_len = get_probe_length(item_to_insert->hash & hash_mask, idx, num_buckets); + + if (candidate_probe_len < new_probe_len) { + // Robin Hood hashing: the item at idx has a better probe length than our item would at this position. + // Evict it and put our item in its place, then continue looking for a new spot for the displaced item. + // This algorithm significantly reduces clustering in the table, making lookups take very few probes. + + temp_item = *candidate; + *candidate = *item_to_insert; + + if (target == NULL) { + target = candidate; + } + + *item_to_insert = temp_item; + + SDL_assert(new_probe_len == get_probe_length(candidate->hash & hash_mask, idx, num_buckets)); + candidate->probe_len = new_probe_len; + + if (*max_probe_len_ptr < new_probe_len) { + *max_probe_len_ptr = new_probe_len; + } + } + + idx = (idx + 1) & hash_mask; + } + + return target; +} + +static void delete_item(SDL_HashTable *ht, SDL_HashItem *item) +{ + const Uint32 hash_mask = ht->hash_mask; + SDL_HashItem *table = ht->table; + + if (ht->destroy) { + ht->destroy(ht->userdata, item->key, item->value); + } + + SDL_assert(ht->num_occupied_slots > 0); + ht->num_occupied_slots--; + + Uint32 idx = (Uint32)(item - ht->table); + + while (true) { + idx = (idx + 1) & hash_mask; + SDL_HashItem *next_item = table + idx; + + if (next_item->probe_len < 1) { + SDL_zerop(item); + return; + } + + *item = *next_item; + item->probe_len -= 1; + SDL_assert(item->probe_len < ht->max_probe_len); + item = next_item; + } +} + +static bool resize(SDL_HashTable *ht, Uint32 new_size) +{ + const Uint32 new_hash_mask = new_size - 1; + SDL_HashItem *new_table = SDL_calloc(new_size, sizeof(*new_table)); + + if (!new_table) { + return false; + } + + SDL_HashItem *old_table = ht->table; + const Uint32 old_size = ht->hash_mask + 1; + + ht->max_probe_len = 0; + ht->hash_mask = new_hash_mask; + ht->table = new_table; + + for (Uint32 i = 0; i < old_size; ++i) { + SDL_HashItem *item = old_table + i; + if (item->live) { + insert_item(item, new_table, new_hash_mask, &ht->max_probe_len); + } + } + + SDL_free(old_table); + return true; +} + +static bool maybe_resize(SDL_HashTable *ht) +{ + const Uint32 capacity = ht->hash_mask + 1; + + if (capacity >= MAX_HASHTABLE_SIZE) { + return false; + } + + const Uint32 max_load_factor = 217; // range: 0-255; 217 is roughly 85% + const Uint32 resize_threshold = (Uint32)((max_load_factor * (Uint64)capacity) >> 8); + + if (ht->num_occupied_slots > resize_threshold) { + return resize(ht, capacity * 2); + } + + return true; +} + +bool SDL_InsertIntoHashTable(SDL_HashTable *table, const void *key, const void *value, bool replace) +{ + if (!table) { + return SDL_InvalidParamError("table"); + } + + bool result = false; + + SDL_LockRWLockForWriting(table->lock); + + const Uint32 hash = calc_hash(table, key); + SDL_HashItem *item = find_first_item(table, key, hash); + bool do_insert = true; + + if (item) { + if (replace) { + delete_item(table, item); + } else { + SDL_SetError("key already exists and replace is disabled"); + do_insert = false; + } + } + + if (do_insert) { + SDL_HashItem new_item; + new_item.key = key; + new_item.value = value; + new_item.hash = hash; + new_item.live = true; + new_item.probe_len = 0; + + table->num_occupied_slots++; + + if (!maybe_resize(table)) { + table->num_occupied_slots--; + } else { + // This never returns NULL + insert_item(&new_item, table->table, table->hash_mask, &table->max_probe_len); + result = true; + } + } + + SDL_UnlockRWLock(table->lock); + return result; +} + +bool SDL_FindInHashTable(const SDL_HashTable *table, const void *key, const void **value) +{ + if (!table) { + if (value) { + *value = NULL; + } + return SDL_InvalidParamError("table"); + } + + SDL_LockRWLockForReading(table->lock); + + bool result = false; + const Uint32 hash = calc_hash(table, key); + SDL_HashItem *i = find_first_item(table, key, hash); + if (i) { + if (value) { + *value = i->value; + } + result = true; + } + + SDL_UnlockRWLock(table->lock); + + return result; +} + +bool SDL_RemoveFromHashTable(SDL_HashTable *table, const void *key) +{ + if (!table) { + return SDL_InvalidParamError("table"); + } + + SDL_LockRWLockForWriting(table->lock); + + bool result = false; + const Uint32 hash = calc_hash(table, key); + SDL_HashItem *item = find_first_item(table, key, hash); + if (item) { + delete_item(table, item); + result = true; + } + + SDL_UnlockRWLock(table->lock); + return result; +} + +bool SDL_IterateHashTable(const SDL_HashTable *table, SDL_HashTableIterateCallback callback, void *userdata) +{ + if (!table) { + return SDL_InvalidParamError("table"); + } else if (!callback) { + return SDL_InvalidParamError("callback"); + } + + SDL_LockRWLockForReading(table->lock); + SDL_HashItem *end = table->table + (table->hash_mask + 1); + Uint32 num_iterated = 0; + + for (SDL_HashItem *item = table->table; item < end; item++) { + if (item->live) { + if (!callback(userdata, table, item->key, item->value)) { + break; // callback requested iteration stop. + } else if (++num_iterated >= table->num_occupied_slots) { + break; // we can drop out early because we've seen all the live items. + } + } + } + + SDL_UnlockRWLock(table->lock); + return true; +} + +bool SDL_HashTableEmpty(SDL_HashTable *table) +{ + if (!table) { + return SDL_InvalidParamError("table"); + } + + SDL_LockRWLockForReading(table->lock); + const bool retval = (table->num_occupied_slots == 0); + SDL_UnlockRWLock(table->lock); + return retval; +} + + +static void destroy_all(SDL_HashTable *table) +{ + SDL_HashDestroyCallback destroy = table->destroy; + if (destroy) { + void *userdata = table->userdata; + SDL_HashItem *end = table->table + (table->hash_mask + 1); + for (SDL_HashItem *i = table->table; i < end; ++i) { + if (i->live) { + i->live = false; + destroy(userdata, i->key, i->value); + } + } + } +} + +void SDL_ClearHashTable(SDL_HashTable *table) +{ + if (table) { + SDL_LockRWLockForWriting(table->lock); + { + destroy_all(table); + SDL_memset(table->table, 0, sizeof(*table->table) * (table->hash_mask + 1)); + table->num_occupied_slots = 0; + } + SDL_UnlockRWLock(table->lock); + } +} + +void SDL_DestroyHashTable(SDL_HashTable *table) +{ + if (table) { + destroy_all(table); + if (table->lock) { + SDL_DestroyRWLock(table->lock); + } + SDL_free(table->table); + SDL_free(table); + } +} + +// this is djb's xor hashing function. +static SDL_INLINE Uint32 hash_string_djbxor(const char *str, size_t len) +{ + Uint32 hash = 5381; + while (len--) { + hash = ((hash << 5) + hash) ^ *(str++); + } + return hash; +} + +Uint32 SDL_HashPointer(void *unused, const void *key) +{ + (void)unused; + return SDL_murmur3_32(&key, sizeof(key), 0); +} + +bool SDL_KeyMatchPointer(void *unused, const void *a, const void *b) +{ + (void)unused; + return (a == b); +} + +Uint32 SDL_HashString(void *unused, const void *key) +{ + (void)unused; + const char *str = (const char *)key; + return hash_string_djbxor(str, SDL_strlen(str)); +} + +bool SDL_KeyMatchString(void *unused, const void *a, const void *b) +{ + const char *a_string = (const char *)a; + const char *b_string = (const char *)b; + + (void)unused; + if (a == b) { + return true; // same pointer, must match. + } else if (!a || !b) { + return false; // one pointer is NULL (and first test shows they aren't the same pointer), must not match. + } else if (a_string[0] != b_string[0]) { + return false; // we know they don't match + } + return (SDL_strcmp(a_string, b_string) == 0); // Check against actual string contents. +} + +// We assume we can fit the ID in the key directly +SDL_COMPILE_TIME_ASSERT(SDL_HashID_KeySize, sizeof(Uint32) <= sizeof(const void *)); + +Uint32 SDL_HashID(void *unused, const void *key) +{ + (void)unused; + return (Uint32)(uintptr_t)key; +} + +bool SDL_KeyMatchID(void *unused, const void *a, const void *b) +{ + (void)unused; + return (a == b); +} + +void SDL_DestroyHashKeyAndValue(void *unused, const void *key, const void *value) +{ + (void)unused; + SDL_free((void *)key); + SDL_free((void *)value); +} + +void SDL_DestroyHashKey(void *unused, const void *key, const void *value) +{ + (void)value; + (void)unused; + SDL_free((void *)key); +} + +void SDL_DestroyHashValue(void *unused, const void *key, const void *value) +{ + (void)key; + (void)unused; + SDL_free((void *)value); +} diff --git a/thirdparty/sdl/SDL_hashtable.h b/thirdparty/sdl/SDL_hashtable.h new file mode 100644 index 00000000000..598a6d6be13 --- /dev/null +++ b/thirdparty/sdl/SDL_hashtable.h @@ -0,0 +1,633 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* this is over-documented because it was almost a public API. Leaving the + full docs here in case it _does_ become public some day. */ + +/* WIKI CATEGORY: HashTable */ + +/** + * # CategoryHashTable + * + * SDL offers a hash table implementation, as a convenience for C code that + * needs efficient organization and access of arbitrary data. + * + * Hash tables are a popular data structure, designed to make it quick to + * store and look up arbitrary data. Data is stored with an associated "key." + * While one would look up an element of an array with an index, a hash table + * uses a unique key to find an element later. + * + * A key can be anything, as long as its unique and in a format that the table + * understands. For example, it's popular to use strings as keys: the key + * might be a username, and it is used to lookup account information for that + * user, etc. + * + * Hash tables are named because they "hash" their keys down into simple + * integers that can be used to efficiently organize and access the associated + * data. + * + * As this is a C API, there is one generic interface that is intended to work + * with different data types. This can be a little awkward to set up, but is + * easy to use after that. + * + * Hashtables are generated by a call to SDL_CreateHashTable(). This function + * requires several callbacks to be provided (for hashing keys, comparing + * entries, and cleaning up entries when removed). These are necessary to + * allow the hash to manage any arbitrary data type. + * + * Once a hash table is created, the common tasks are inserting data into the + * table, (SDL_InsertIntoHashTable), looking up previously inserted data + * (SDL_FindInHashTable), and removing data (SDL_RemoveFromHashTable and + * SDL_ClearHashTable). Less common but still useful is the ability to + * iterate through all the items in the table (SDL_IterateHashTable). + * + * The underlying hash table implementation is always subject to change, but + * at the time of writing, it uses open addressing and Robin Hood hashing. + * The technical details are explained [here](https://github.com/libsdl-org/SDL/pull/10897). + * + * Hashtables keep an SDL_RWLock internally, so multiple threads can perform + * hash lookups in parallel, while changes to the table will safely serialize + * access between threads. + * + * SDL provides a layer on top of this hash table implementation that might be + * more pleasant to use. SDL_PropertiesID maps a string to arbitrary data of + * various types in the same table, which could be both easier to use and more + * flexible. Refer to [CategoryProperties](CategoryProperties) for details. + */ + +#ifndef SDL_hashtable_h_ +#define SDL_hashtable_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The opaque type that represents a hash table. + * + * This is hidden behind an opaque pointer because not only does the table + * need to store arbitrary data types, but the hash table implementation may + * change in the future. + * + * \since This struct is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +typedef struct SDL_HashTable SDL_HashTable; + +/** + * A function pointer representing a hash table hashing callback. + * + * This is called by SDL_HashTable when it needs to look up a key in + * its dataset. It generates a hash value from that key, and then uses that + * value as a basis for an index into an internal array. + * + * There are no rules on what hashing algorithm is used, so long as it + * can produce a reliable 32-bit value from `key`, and ideally distributes + * those values well across the 32-bit value space. The quality of a + * hashing algorithm is directly related to how well a hash table performs. + * + * Hashing can be a complicated subject, and often times what works best + * for one dataset will be suboptimal for another. There is a good discussion + * of the field [on Wikipedia](https://en.wikipedia.org/wiki/Hash_function). + * + * Also: do you _need_ to write a hashing function? SDL provides generic + * functions for strings (SDL_HashString), generic integer IDs (SDL_HashID), + * and generic pointers (SDL_HashPointer). Often you should use one of these + * before writing your own. + * + * \param userdata what was passed as `userdata` to SDL_CreateHashTable(). + * \param key the key to be hashed. + * \returns a 32-bit value that represents a hash of `key`. + * + * \threadsafety This function must be thread safe if the hash table is used + * from multiple threads at the same time. + * + * \since This datatype is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + * \sa SDL_HashString + * \sa SDL_HashID + * \sa SDL_HashPointer + */ +typedef Uint32 (SDLCALL *SDL_HashCallback)(void *userdata, const void *key); + + +/** + * A function pointer representing a hash table matching callback. + * + * This is called by SDL_HashTable when it needs to look up a key in its + * dataset. After hashing the key, it looks for items stored in relation to + * that hash value. Since there can be more than one item found through the + * same hash value, this function verifies a specific value is actually + * correct before choosing it. + * + * So this function needs to compare the keys at `a` and `b` and decide if + * they are actually the same. + * + * For example, if the keys are C strings, this function might just be: + * + * ```c + * return (SDL_strcmp((const char *) a, const char *b) == 0);` + * ``` + * + * Also: do you _need_ to write a matching function? SDL provides generic + * functions for strings (SDL_KeyMatchString), generic integer IDs + * (SDL_KeyMatchID), and generic pointers (SDL_KeyMatchPointer). Often you + * should use one of these before writing your own. + * + * \param userdata what was passed as `userdata` to SDL_CreateHashTable(). + * \param a the first key to be compared. + * \param b the second key to be compared. + * \returns true if two keys are identical, false otherwise. + * + * \threadsafety This function must be thread safe if the hash table is used + * from multiple threads at the same time. + * + * \since This datatype is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +typedef bool (SDLCALL *SDL_HashKeyMatchCallback)(void *userdata, const void *a, const void *b); + + +/** + * A function pointer representing a hash table cleanup callback. + * + * This is called by SDL_HashTable when removing items from the hash, or + * destroying the hash table. It is used to optionally deallocate the + * key/value pairs. + * + * This is not required to do anything, if all the data in the table is + * static or POD data, but it can also do more than a simple free: for + * example, if the hash table is storing open files, it can close them here. + * It can also free only the key or only the value; it depends on what the + * hash table contains. + * + * \param userdata what was passed as `userdata` to SDL_CreateHashTable(). + * \param key the key to deallocate. + * \param value the value to deallocate. + * + * \threadsafety This function must be thread safe if the hash table is used + * from multiple threads at the same time. + * + * \since This datatype is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +typedef void (SDLCALL *SDL_HashDestroyCallback)(void *userdata, const void *key, const void *value); + + +/** + * A function pointer representing a hash table iterator callback. + * + * This function is called once for each key/value pair to be considered + * when iterating a hash table. + * + * Iteration continues as long as there are more items to examine and this + * callback continues to return true. + * + * Do not attempt to modify the hash table during this callback, as it will + * cause incorrect behavior and possibly crashes. + * + * \param userdata what was passed as `userdata` to an iterator function. + * \param table the hash table being iterated. + * \param key the current key being iterated. + * \param value the current value being iterated. + * \returns true to keep iterating, false to stop iteration. + * + * \threadsafety A read lock is held during iteration, so other threads can + * still access the the hash table, but threads attempting to + * make changes will be blocked until iteration completes. If + * this is a concern, do as little in the callback as possible + * and finish iteration quickly. + * + * \since This datatype is available since SDL 3.4.0. + * + * \sa SDL_IterateHashTable + */ +typedef bool (SDLCALL *SDL_HashTableIterateCallback)(void *userdata, const SDL_HashTable *table, const void *key, const void *value); + + +/** + * Create a new hash table. + * + * To deal with different datatypes and needs of the caller, hash tables + * require several callbacks that deal with some specifics: how to hash a key, + * how to compare a key for equality, and how to clean up keys and values. + * SDL provides a few generic functions that can be used for these callbacks: + * + * - SDL_HashString and SDL_KeyMatchString for C strings. + * - SDL_HashPointer and SDL_KeyMatchPointer for generic pointers. + * - SDL_HashID and SDL_KeyMatchID for generic (possibly small) integers. + * + * Oftentimes, these are all you need for any hash table, but depending on + * your dataset, custom implementations might make more sense. + * + * You can specify an estimate of the number of items expected to be stored + * in the table, which can help make the table run more efficiently. The table + * will preallocate resources to accomodate this number of items, which is + * most useful if you intend to fill the table with a lot of data right after + * creating it. Otherwise, it might make more sense to specify the _minimum_ + * you expect the table to hold and let it grow as necessary from there. This + * number is only a hint, and the table will be able to handle any amount of + * data--as long as the system doesn't run out of resources--so a perfect + * answer is not required. A value of 0 signifies no guess at all, and the + * table will start small and reallocate as necessary; often this is the + * correct thing to do. + * + * !!! FIXME: add note about `threadsafe` here. And update `threadsafety` tags. + * !!! FIXME: note that `threadsafe` tables can't be recursively locked, so + * !!! FIXME: you can't use `destroy` callbacks that might end up relocking. + * + * Note that SDL provides a higher-level option built on its hash tables: + * SDL_PropertiesID lets you map strings to various datatypes, and this + * might be easier to use. It only allows strings for keys, however. Those are + * created with SDL_CreateProperties(). + * + * The returned hash table should be destroyed with SDL_DestroyHashTable() + * when no longer needed. + * + * \param estimated_capacity the approximate maximum number of items to be held + * in the hash table, or 0 for no estimate. + * \param threadsafe true to create an internal rwlock for this table. + * \param hash the function to use to hash keys. + * \param keymatch the function to use to compare keys. + * \param destroy the function to use to clean up keys and values, may be NULL. + * \param userdata a pointer that is passed to the callbacks. + * \returns a newly-created hash table, or NULL if there was an error; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_DestroyHashTable + */ +extern SDL_HashTable * SDL_CreateHashTable(int estimated_capacity, + bool threadsafe, + SDL_HashCallback hash, + SDL_HashKeyMatchCallback keymatch, + SDL_HashDestroyCallback destroy, + void *userdata); + + +/** + * Destroy a hash table. + * + * This will call the hash table's SDL_HashDestroyCallback for each item in + * the table, removing all inserted items, before deallocating the table + * itself. + * + * The table becomes invalid once this function is called, and no other thread + * should be accessing this table once this function has started. + * + * \param table the hash table to destroy. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + */ +extern void SDL_DestroyHashTable(SDL_HashTable *table); + +/** + * Add an item to a hash table. + * + * All keys in the table must be unique. If attempting to insert a key that + * already exists in the hash table, what will be done depends on the + * `replace` value: + * + * - If `replace` is false, this function will return false without modifying + * the table. + * - If `replace` is true, SDL will remove the previous item first, so the new + * value is the only one associated with that key. This will call the hash + * table's SDL_HashDestroyCallback for the previous item. + * + * \param table the hash table to insert into. + * \param key the key of the new item to insert. + * \param value the value of the new item to insert. + * \param replace true if a duplicate key should replace the previous value. + * \returns true if the new item was inserted, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + */ +extern bool SDL_InsertIntoHashTable(SDL_HashTable *table, const void *key, const void *value, bool replace); + +/** + * Look up an item in a hash table. + * + * On return, the value associated with `key` is stored to `*value`. + * If the key does not exist in the table, `*value` will be set to NULL. + * + * It is legal for `value` to be NULL, to not retrieve the key's value. In + * this case, the return value is still useful for reporting if the key exists + * in the table at all. + * + * \param table the hash table to search. + * \param key the key to search for in the table. + * \param value the found value will be stored here. Can be NULL. + * \returns true if key exists in the table, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_InsertIntoHashTable + */ +extern bool SDL_FindInHashTable(const SDL_HashTable *table, const void *key, const void **value); + +/** + * Remove an item from a hash table. + * + * If there is an item that matches `key`, it is removed from the table. This + * will call the hash table's SDL_HashDestroyCallback for the item to be + * removed. + * + * \param table the hash table to remove from. + * \param key the key of the item to remove from the table. + * \returns true if a key was removed, false if the key was not found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + */ +extern bool SDL_RemoveFromHashTable(SDL_HashTable *table, const void *key); + +/** + * Remove all items in a hash table. + * + * This will call the hash table's SDL_HashDestroyCallback for each item in + * the table, removing all inserted items. + * + * When this function returns, the hash table will be empty. + * + * \param table the hash table to clear. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + */ +extern void SDL_ClearHashTable(SDL_HashTable *table); + +/** + * Check if any items are currently stored in a hash table. + * + * If there are no items stored (the table is completely empty), this will + * return true. + * + * \param table the hash table to check. + * \returns true if the table is completely empty, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_ClearHashTable + */ +extern bool SDL_HashTableEmpty(SDL_HashTable *table); + +/** + * Iterate all key/value pairs in a hash table. + * + * This function will call `callback` once for each key/value pair in the + * table, until either all pairs have been presented to the callback, or the + * callback has returned false to signal it is done. + * + * There is no guarantee what order results will be returned in. + * + * \param table the hash table to iterate. + * \param callback the function pointer to call for each value. + * \param userdata a pointer that is passed to `callback`. + * \returns true if iteration happened, false if not (bogus parameter, etc). + * + * \since This function is available since SDL 3.4.0. + */ +extern bool SDL_IterateHashTable(const SDL_HashTable *table, SDL_HashTableIterateCallback callback, void *userdata); + + +/* Helper functions for SDL_CreateHashTable callbacks... */ + +/** + * Generate a hash from a generic pointer. + * + * The key is intended to be a unique pointer to any datatype. + * + * This is intended to be used as one of the callbacks to SDL_CreateHashTable, + * if this is useful to the type of keys to be used with the hash table. + * + * Note that the implementation may change in the future; do not expect + * the results to be stable vs future SDL releases. Use this in a hash table + * in the current process and don't store them to disk for the future. + * + * \param unused this parameter is ignored. + * \param key the key to hash as a generic pointer. + * \returns a 32-bit hash of the key. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +extern Uint32 SDL_HashPointer(void *unused, const void *key); + +/** + * Compare two generic pointers as hash table keys. + * + * This is intended to be used as one of the callbacks to SDL_CreateHashTable, + * if this is useful to the type of keys to be used with the hash table. + * + * \param unused this parameter is ignored. + * \param a the first generic pointer to compare. + * \param b the second generic pointer to compare. + * \returns true if the pointers are the same, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +extern bool SDL_KeyMatchPointer(void *unused, const void *a, const void *b); + +/** + * Generate a hash from a C string. + * + * The key is intended to be a NULL-terminated string, in UTF-8 format. + * + * This is intended to be used as one of the callbacks to SDL_CreateHashTable, + * if this is useful to the type of keys to be used with the hash table. + * + * Note that the implementation may change in the future; do not expect + * the results to be stable vs future SDL releases. Use this in a hash table + * in the current process and don't store them to disk for the future. + * + * \param unused this parameter is ignored. + * \param key the key to hash as a generic pointer. + * \returns a 32-bit hash of the key. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +extern Uint32 SDL_HashString(void *unused, const void *key); + +/** + * Compare two C strings as hash table keys. + * + * Strings will be compared in a case-sensitive manner. More specifically, + * they'll be compared as NULL-terminated arrays of bytes. + * + * This is intended to be used as one of the callbacks to SDL_CreateHashTable, + * if this is useful to the type of keys to be used with the hash table. + * + * \param unused this parameter is ignored. + * \param a the first string to compare. + * \param b the second string to compare. + * \returns true if the strings are the same, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +extern bool SDL_KeyMatchString(void *unused, const void *a, const void *b); + +/** + * Generate a hash from an integer ID. + * + * The key is intended to a unique integer, possibly within a small range. + * + * This is intended to be used as one of the callbacks to SDL_CreateHashTable, + * if this is useful to the type of keys to be used with the hash table. + * + * Note that the implementation may change in the future; do not expect + * the results to be stable vs future SDL releases. Use this in a hash table + * in the current process and don't store them to disk for the future. + * + * \param unused this parameter is ignored. + * \param key the key to hash as a generic pointer. + * \returns a 32-bit hash of the key. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +extern Uint32 SDL_HashID(void *unused, const void *key); + +/** + * Compare two integer IDs as hash table keys. + * + * This is intended to be used as one of the callbacks to SDL_CreateHashTable, + * if this is useful to the type of keys to be used with the hash table. + * + * \param unused this parameter is ignored. + * \param a the first ID to compare. + * \param b the second ID to compare. + * \returns true if the IDs are the same, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +extern bool SDL_KeyMatchID(void *unused, const void *a, const void *b); + +/** + * Free both the key and value pointers of a hash table item. + * + * This is intended to be used as one of the callbacks to SDL_CreateHashTable, + * if this is useful to the type of data to be used with the hash table. + * + * This literally calls `SDL_free(key);` and `SDL_free(value);`. + * + * \param unused this parameter is ignored. + * \param key the key to be destroyed. + * \param value the value to be destroyed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +extern void SDL_DestroyHashKeyAndValue(void *unused, const void *key, const void *value); + +/** + * Free just the value pointer of a hash table item. + * + * This is intended to be used as one of the callbacks to SDL_CreateHashTable, + * if this is useful to the type of data to be used with the hash table. + * + * This literally calls `SDL_free(key);` and leaves `value` alone. + * + * \param unused this parameter is ignored. + * \param key the key to be destroyed. + * \param value the value to be destroyed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +extern void SDL_DestroyHashKey(void *unused, const void *key, const void *value); + +/** + * Free just the value pointer of a hash table item. + * + * This is intended to be used as one of the callbacks to SDL_CreateHashTable, + * if this is useful to the type of data to be used with the hash table. + * + * This literally calls `SDL_free(value);` and leaves `key` alone. + * + * \param unused this parameter is ignored. + * \param key the key to be destroyed. + * \param value the value to be destroyed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_CreateHashTable + */ +extern void SDL_DestroyHashValue(void *unused, const void *key, const void *value); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_hashtable_h_ */ diff --git a/thirdparty/sdl/SDL_hints.c b/thirdparty/sdl/SDL_hints.c new file mode 100644 index 00000000000..a10598f0ffe --- /dev/null +++ b/thirdparty/sdl/SDL_hints.c @@ -0,0 +1,403 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_hints_c.h" + +#ifdef SDL_PLATFORM_ANDROID +#include "core/android/SDL_android.h" +#endif + +typedef struct SDL_HintWatch +{ + SDL_HintCallback callback; + void *userdata; + struct SDL_HintWatch *next; +} SDL_HintWatch; + +typedef struct SDL_Hint +{ + char *value; + SDL_HintPriority priority; + SDL_HintWatch *callbacks; +} SDL_Hint; + +static SDL_AtomicU32 SDL_hint_props; + + +void SDL_InitHints(void) +{ +} + +void SDL_QuitHints(void) +{ + SDL_PropertiesID props; + do { + props = SDL_GetAtomicU32(&SDL_hint_props); + } while (!SDL_CompareAndSwapAtomicU32(&SDL_hint_props, props, 0)); + + if (props) { + SDL_DestroyProperties(props); + } +} + +static SDL_PropertiesID GetHintProperties(bool create) +{ + SDL_PropertiesID props = SDL_GetAtomicU32(&SDL_hint_props); + if (!props && create) { + props = SDL_CreateProperties(); + if (!SDL_CompareAndSwapAtomicU32(&SDL_hint_props, 0, props)) { + // Somebody else created hint properties before us, just use those + SDL_DestroyProperties(props); + props = SDL_GetAtomicU32(&SDL_hint_props); + } + } + return props; +} + +static void SDLCALL CleanupHintProperty(void *userdata, void *value) +{ + SDL_Hint *hint = (SDL_Hint *) value; + SDL_free(hint->value); + + SDL_HintWatch *entry = hint->callbacks; + while (entry) { + SDL_HintWatch *freeable = entry; + entry = entry->next; + SDL_free(freeable); + } + SDL_free(hint); +} + +static const char* GetHintEnvironmentVariable(const char *name) +{ + const char *result = SDL_getenv(name); + if (!result && name && *name) { + // fall back to old (SDL2) names of environment variables that + // are important to users (e.g. many use SDL_VIDEODRIVER=wayland) + if (SDL_strcmp(name, SDL_HINT_VIDEO_DRIVER) == 0) { + result = SDL_getenv("SDL_VIDEODRIVER"); + } else if (SDL_strcmp(name, SDL_HINT_AUDIO_DRIVER) == 0) { + result = SDL_getenv("SDL_AUDIODRIVER"); + } + } + return result; +} + +bool SDL_SetHintWithPriority(const char *name, const char *value, SDL_HintPriority priority) +{ + if (!name || !*name) { + return SDL_InvalidParamError("name"); + } + + const char *env = GetHintEnvironmentVariable(name); + if (env && (priority < SDL_HINT_OVERRIDE)) { + return SDL_SetError("An environment variable is taking priority"); + } + + const SDL_PropertiesID hints = GetHintProperties(true); + if (!hints) { + return false; + } + + bool result = false; + + SDL_LockProperties(hints); + + SDL_Hint *hint = (SDL_Hint *)SDL_GetPointerProperty(hints, name, NULL); + if (hint) { + if (priority >= hint->priority) { + if (hint->value != value && (!value || !hint->value || SDL_strcmp(hint->value, value) != 0)) { + char *old_value = hint->value; + + hint->value = value ? SDL_strdup(value) : NULL; + SDL_HintWatch *entry = hint->callbacks; + while (entry) { + // Save the next entry in case this one is deleted + SDL_HintWatch *next = entry->next; + entry->callback(entry->userdata, name, old_value, value); + entry = next; + } + SDL_free(old_value); + } + hint->priority = priority; + result = true; + } + } else { // Couldn't find the hint? Add a new one. + hint = (SDL_Hint *)SDL_malloc(sizeof(*hint)); + if (hint) { + hint->value = value ? SDL_strdup(value) : NULL; + hint->priority = priority; + hint->callbacks = NULL; + result = SDL_SetPointerPropertyWithCleanup(hints, name, hint, CleanupHintProperty, NULL); + } + } + +#ifdef SDL_PLATFORM_ANDROID + if (SDL_strcmp(name, SDL_HINT_ANDROID_ALLOW_RECREATE_ACTIVITY) == 0) { + // Special handling for this hint, which needs to persist outside the normal application flow + Android_SetAllowRecreateActivity(SDL_GetStringBoolean(value, false)); + } +#endif // SDL_PLATFORM_ANDROID + + SDL_UnlockProperties(hints); + + return result; +} + +bool SDL_ResetHint(const char *name) +{ + if (!name || !*name) { + return SDL_InvalidParamError("name"); + } + + const char *env = GetHintEnvironmentVariable(name); + + const SDL_PropertiesID hints = GetHintProperties(false); + if (!hints) { + return false; + } + + bool result = false; + + SDL_LockProperties(hints); + + SDL_Hint *hint = (SDL_Hint *)SDL_GetPointerProperty(hints, name, NULL); + if (hint) { + if ((!env && hint->value) || (env && !hint->value) || (env && SDL_strcmp(env, hint->value) != 0)) { + for (SDL_HintWatch *entry = hint->callbacks; entry;) { + // Save the next entry in case this one is deleted + SDL_HintWatch *next = entry->next; + entry->callback(entry->userdata, name, hint->value, env); + entry = next; + } + } + SDL_free(hint->value); + hint->value = NULL; + hint->priority = SDL_HINT_DEFAULT; + result = true; + } + +#ifdef SDL_PLATFORM_ANDROID + if (SDL_strcmp(name, SDL_HINT_ANDROID_ALLOW_RECREATE_ACTIVITY) == 0) { + // Special handling for this hint, which needs to persist outside the normal application flow + if (env) { + Android_SetAllowRecreateActivity(SDL_GetStringBoolean(env, false)); + } else { + Android_SetAllowRecreateActivity(false); + } + } +#endif // SDL_PLATFORM_ANDROID + + SDL_UnlockProperties(hints); + + return result; +} + +static void SDLCALL ResetHintsCallback(void *userdata, SDL_PropertiesID hints, const char *name) +{ + SDL_Hint *hint = (SDL_Hint *)SDL_GetPointerProperty(hints, name, NULL); + if (!hint) { + return; // uh...okay. + } + + const char *env = GetHintEnvironmentVariable(name); + if ((!env && hint->value) || (env && !hint->value) || (env && SDL_strcmp(env, hint->value) != 0)) { + SDL_HintWatch *entry = hint->callbacks; + while (entry) { + // Save the next entry in case this one is deleted + SDL_HintWatch *next = entry->next; + entry->callback(entry->userdata, name, hint->value, env); + entry = next; + } + } + SDL_free(hint->value); + hint->value = NULL; + hint->priority = SDL_HINT_DEFAULT; + +#ifdef SDL_PLATFORM_ANDROID + if (SDL_strcmp(name, SDL_HINT_ANDROID_ALLOW_RECREATE_ACTIVITY) == 0) { + // Special handling for this hint, which needs to persist outside the normal application flow + if (env) { + Android_SetAllowRecreateActivity(SDL_GetStringBoolean(env, false)); + } else { + Android_SetAllowRecreateActivity(false); + } + } +#endif // SDL_PLATFORM_ANDROID +} + +void SDL_ResetHints(void) +{ + SDL_EnumerateProperties(GetHintProperties(false), ResetHintsCallback, NULL); +} + +bool SDL_SetHint(const char *name, const char *value) +{ + return SDL_SetHintWithPriority(name, value, SDL_HINT_NORMAL); +} + +const char *SDL_GetHint(const char *name) +{ + if (!name) { + return NULL; + } + + const char *result = GetHintEnvironmentVariable(name); + + const SDL_PropertiesID hints = GetHintProperties(false); + if (hints) { + SDL_LockProperties(hints); + + SDL_Hint *hint = (SDL_Hint *)SDL_GetPointerProperty(hints, name, NULL); + if (hint) { + if (!result || hint->priority == SDL_HINT_OVERRIDE) { + result = SDL_GetPersistentString(hint->value); + } + } + + SDL_UnlockProperties(hints); + } + + return result; +} + +int SDL_GetStringInteger(const char *value, int default_value) +{ + if (!value || !*value) { + return default_value; + } + if (SDL_strcasecmp(value, "false") == 0) { + return 0; + } + if (SDL_strcasecmp(value, "true") == 0) { + return 1; + } + if (*value == '-' || SDL_isdigit(*value)) { + return SDL_atoi(value); + } + return default_value; +} + +bool SDL_GetStringBoolean(const char *value, bool default_value) +{ + if (!value || !*value) { + return default_value; + } + if (*value == '0' || SDL_strcasecmp(value, "false") == 0) { + return false; + } + return true; +} + +bool SDL_GetHintBoolean(const char *name, bool default_value) +{ + const char *hint = SDL_GetHint(name); + return SDL_GetStringBoolean(hint, default_value); +} + +bool SDL_AddHintCallback(const char *name, SDL_HintCallback callback, void *userdata) +{ + if (!name || !*name) { + return SDL_InvalidParamError("name"); + } else if (!callback) { + return SDL_InvalidParamError("callback"); + } + + const SDL_PropertiesID hints = GetHintProperties(true); + if (!hints) { + return false; + } + + SDL_HintWatch *entry = (SDL_HintWatch *)SDL_malloc(sizeof(*entry)); + if (!entry) { + return false; + } + entry->callback = callback; + entry->userdata = userdata; + + bool result = false; + + SDL_LockProperties(hints); + + SDL_RemoveHintCallback(name, callback, userdata); + + SDL_Hint *hint = (SDL_Hint *)SDL_GetPointerProperty(hints, name, NULL); + if (hint) { + result = true; + } else { // Need to add a hint entry for this watcher + hint = (SDL_Hint *)SDL_malloc(sizeof(*hint)); + if (!hint) { + SDL_free(entry); + SDL_UnlockProperties(hints); + return false; + } else { + hint->value = NULL; + hint->priority = SDL_HINT_DEFAULT; + hint->callbacks = NULL; + result = SDL_SetPointerPropertyWithCleanup(hints, name, hint, CleanupHintProperty, NULL); + } + } + + // Add it to the callbacks for this hint + entry->next = hint->callbacks; + hint->callbacks = entry; + + // Now call it with the current value + const char *value = SDL_GetHint(name); + callback(userdata, name, value, value); + + SDL_UnlockProperties(hints); + + return result; +} + +void SDL_RemoveHintCallback(const char *name, SDL_HintCallback callback, void *userdata) +{ + if (!name || !*name) { + return; + } + + const SDL_PropertiesID hints = GetHintProperties(false); + if (!hints) { + return; + } + + SDL_LockProperties(hints); + SDL_Hint *hint = (SDL_Hint *)SDL_GetPointerProperty(hints, name, NULL); + if (hint) { + SDL_HintWatch *prev = NULL; + for (SDL_HintWatch *entry = hint->callbacks; entry; entry = entry->next) { + if ((callback == entry->callback) && (userdata == entry->userdata)) { + if (prev) { + prev->next = entry->next; + } else { + hint->callbacks = entry->next; + } + SDL_free(entry); + break; + } + prev = entry; + } + } + SDL_UnlockProperties(hints); +} + diff --git a/thirdparty/sdl/SDL_hints_c.h b/thirdparty/sdl/SDL_hints_c.h new file mode 100644 index 00000000000..dd54cba6709 --- /dev/null +++ b/thirdparty/sdl/SDL_hints_c.h @@ -0,0 +1,33 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This file defines useful function for working with SDL hints + +#ifndef SDL_hints_c_h_ +#define SDL_hints_c_h_ + +extern void SDL_InitHints(void); +extern bool SDL_GetStringBoolean(const char *value, bool default_value); +extern int SDL_GetStringInteger(const char *value, int default_value); +extern void SDL_QuitHints(void); + +#endif // SDL_hints_c_h_ diff --git a/thirdparty/sdl/SDL_internal.h b/thirdparty/sdl/SDL_internal.h new file mode 100644 index 00000000000..20ec0fcb913 --- /dev/null +++ b/thirdparty/sdl/SDL_internal.h @@ -0,0 +1,289 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#ifndef SDL_internal_h_ +#define SDL_internal_h_ + +// Many of SDL's features require _GNU_SOURCE on various platforms +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + +// Need this so Linux systems define fseek64o, ftell64o and off64_t +#ifndef _LARGEFILE64_SOURCE +#define _LARGEFILE64_SOURCE 1 +#endif + +/* This is for a variable-length array at the end of a struct: + struct x { int y; char z[SDL_VARIABLE_LENGTH_ARRAY]; }; + Use this because GCC 2 needs different magic than other compilers. */ +#if (defined(__GNUC__) && (__GNUC__ <= 2)) || defined(__CC_ARM) || defined(__cplusplus) +#define SDL_VARIABLE_LENGTH_ARRAY 1 +#else +#define SDL_VARIABLE_LENGTH_ARRAY +#endif + +#if (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) || defined(__clang__) +#define HAVE_GCC_DIAGNOSTIC_PRAGMA 1 +#endif + +#ifdef _MSC_VER // We use constant comparison for generated code +#pragma warning(disable : 6326) +#endif + +#ifdef _MSC_VER // SDL_MAX_SMALL_ALLOC_STACKSIZE is smaller than _ALLOCA_S_THRESHOLD and should be generally safe +#pragma warning(disable : 6255) +#endif +#define SDL_MAX_SMALL_ALLOC_STACKSIZE 128 +#define SDL_small_alloc(type, count, pisstack) ((*(pisstack) = ((sizeof(type) * (count)) < SDL_MAX_SMALL_ALLOC_STACKSIZE)), (*(pisstack) ? SDL_stack_alloc(type, count) : (type *)SDL_malloc(sizeof(type) * (count)))) +#define SDL_small_free(ptr, isstack) \ + if ((isstack)) { \ + SDL_stack_free(ptr); \ + } else { \ + SDL_free(ptr); \ + } + +#include "SDL_build_config.h" + +//#include "dynapi/SDL_dynapi.h" + +#if SDL_DYNAMIC_API +#include "dynapi/SDL_dynapi_overrides.h" +/* force SDL_DECLSPEC off...it's all internal symbols now. + These will have actual #defines during SDL_dynapi.c only */ +#ifdef SDL_DECLSPEC +#undef SDL_DECLSPEC +#endif +#define SDL_DECLSPEC +#endif + +#ifdef SDL_PLATFORM_APPLE +#ifndef _DARWIN_C_SOURCE +#define _DARWIN_C_SOURCE 1 // for memset_pattern4() +#endif +#include + +#ifndef __IPHONE_OS_VERSION_MAX_ALLOWED +#define __IPHONE_OS_VERSION_MAX_ALLOWED 0 +#endif +#ifndef __APPLETV_OS_VERSION_MAX_ALLOWED +#define __APPLETV_OS_VERSION_MAX_ALLOWED 0 +#endif +#ifndef __MAC_OS_X_VERSION_MAX_ALLOWED +#define __MAC_OS_X_VERSION_MAX_ALLOWED 0 +#endif +#endif // SDL_PLATFORM_APPLE + +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_STDIO_H +#include +#endif +#ifdef HAVE_STDLIB_H +#include +#elif defined(HAVE_MALLOC_H) +#include +#endif +#ifdef HAVE_STDDEF_H +#include +#endif +#ifdef HAVE_STDARG_H +#include +#endif +#ifdef HAVE_STRING_H +#ifdef HAVE_MEMORY_H +#include +#endif +#include +#endif +#ifdef HAVE_STRINGS_H +#include +#endif +#ifdef HAVE_WCHAR_H +#include +#endif +#ifdef HAVE_INTTYPES_H +#include +#elif defined(HAVE_STDINT_H) +#include +#endif +#ifdef HAVE_MATH_H +#include +#endif +#ifdef HAVE_FLOAT_H +#include +#endif + +// If you run into a warning that O_CLOEXEC is redefined, update the SDL configuration header for your platform to add HAVE_O_CLOEXEC +#ifndef HAVE_O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +/* A few #defines to reduce SDL footprint. + Only effective when library is statically linked. */ + +/* Optimized functions from 'SDL_blit_0.c' + - blit with source bits_per_pixel < 8, palette */ +#if !defined(SDL_HAVE_BLIT_0) && !defined(SDL_LEAN_AND_MEAN) +#define SDL_HAVE_BLIT_0 1 +#endif + +/* Optimized functions from 'SDL_blit_1.c' + - blit with source bytes_per_pixel == 1, palette */ +#if !defined(SDL_HAVE_BLIT_1) && !defined(SDL_LEAN_AND_MEAN) +#define SDL_HAVE_BLIT_1 1 +#endif + +/* Optimized functions from 'SDL_blit_A.c' + - blit with 'SDL_BLENDMODE_BLEND' blending mode */ +#if !defined(SDL_HAVE_BLIT_A) && !defined(SDL_LEAN_AND_MEAN) +#define SDL_HAVE_BLIT_A 1 +#endif + +/* Optimized functions from 'SDL_blit_N.c' + - blit with COLORKEY mode, or nothing */ +#if !defined(SDL_HAVE_BLIT_N) && !defined(SDL_LEAN_AND_MEAN) +#define SDL_HAVE_BLIT_N 1 +#endif + +/* Optimized functions from 'SDL_blit_N.c' + - RGB565 conversion with Lookup tables */ +#if !defined(SDL_HAVE_BLIT_N_RGB565) && !defined(SDL_LEAN_AND_MEAN) +#define SDL_HAVE_BLIT_N_RGB565 1 +#endif + +/* Optimized functions from 'SDL_blit_AUTO.c' + - blit with modulate color, modulate alpha, any blending mode + - scaling or not */ +#if !defined(SDL_HAVE_BLIT_AUTO) && !defined(SDL_LEAN_AND_MEAN) +#define SDL_HAVE_BLIT_AUTO 1 +#endif + +/* Run-Length-Encoding + - SDL_SetSurfaceColorKey() called with SDL_RLEACCEL flag */ +#if !defined(SDL_HAVE_RLE) && !defined(SDL_LEAN_AND_MEAN) +#define SDL_HAVE_RLE 1 +#endif + +/* Software SDL_Renderer + - creation of software renderer + - *not* general blitting functions + - {blend,draw}{fillrect,line,point} internal functions */ +#if !defined(SDL_VIDEO_RENDER_SW) && !defined(SDL_LEAN_AND_MEAN) +#define SDL_VIDEO_RENDER_SW 1 +#endif + +/* STB image conversion */ +#if !defined(SDL_HAVE_STB) && !defined(SDL_LEAN_AND_MEAN) +#define SDL_HAVE_STB 1 +#endif + +/* YUV formats + - handling of YUV surfaces + - blitting and conversion functions */ +#if !defined(SDL_HAVE_YUV) && !defined(SDL_LEAN_AND_MEAN) +#define SDL_HAVE_YUV 1 +#endif + +#ifdef SDL_CAMERA_DISABLED +#undef SDL_CAMERA_DRIVER_ANDROID +#undef SDL_CAMERA_DRIVER_COREMEDIA +#undef SDL_CAMERA_DRIVER_DUMMY +#undef SDL_CAMERA_DRIVER_EMSCRIPTEN +#undef SDL_CAMERA_DRIVER_MEDIAFOUNDATION +#undef SDL_CAMERA_DRIVER_PIPEWIRE +#undef SDL_CAMERA_DRIVER_V4L2 +#undef SDL_CAMERA_DRIVER_VITA +#endif + +#ifdef SDL_RENDER_DISABLED +#undef SDL_VIDEO_RENDER_SW +#undef SDL_VIDEO_RENDER_D3D +#undef SDL_VIDEO_RENDER_D3D11 +#undef SDL_VIDEO_RENDER_D3D12 +#undef SDL_VIDEO_RENDER_GPU +#undef SDL_VIDEO_RENDER_METAL +#undef SDL_VIDEO_RENDER_OGL +#undef SDL_VIDEO_RENDER_OGL_ES2 +#undef SDL_VIDEO_RENDER_PS2 +#undef SDL_VIDEO_RENDER_PSP +#undef SDL_VIDEO_RENDER_VITA_GXM +#undef SDL_VIDEO_RENDER_VULKAN +#endif // SDL_RENDER_DISABLED + +#ifdef SDL_GPU_DISABLED +#undef SDL_GPU_D3D12 +#undef SDL_GPU_METAL +#undef SDL_GPU_VULKAN +#undef SDL_VIDEO_RENDER_GPU +#endif // SDL_GPU_DISABLED + +#if !defined(HAVE_LIBC) +// If not using _any_ C runtime, these have to be defined before SDL_thread.h +// gets included, so internal SDL_CreateThread calls will not try to reference +// the (unavailable and unneeded) _beginthreadex/_endthreadex functions. +#define SDL_BeginThreadFunction NULL +#define SDL_EndThreadFunction NULL +#endif + +#ifdef SDL_NOLONGLONG +#error We cannot build a valid SDL3 library without long long support +#endif + +/* Enable internal definitions in SDL API headers */ +#define SDL_INTERNAL + +#include +#include + +#define SDL_MAIN_NOIMPL // don't drag in header-only implementation of SDL_main +#include + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +#include "SDL_utils_c.h" +#include "SDL_hashtable.h" + +#define PUSH_SDL_ERROR() \ + { char *_error = SDL_strdup(SDL_GetError()); + +#define POP_SDL_ERROR() \ + SDL_SetError("%s", _error); SDL_free(_error); } + +// Do any initialization that needs to happen before threads are started +extern void SDL_InitMainThread(void); + +/* The internal implementations of these functions have up to nanosecond precision. + We can expose these functions as part of the API if we want to later. +*/ +extern bool SDLCALL SDL_WaitSemaphoreTimeoutNS(SDL_Semaphore *sem, Sint64 timeoutNS); +extern bool SDLCALL SDL_WaitConditionTimeoutNS(SDL_Condition *cond, SDL_Mutex *mutex, Sint64 timeoutNS); +extern bool SDLCALL SDL_WaitEventTimeoutNS(SDL_Event *event, Sint64 timeoutNS); + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif + +#endif // SDL_internal_h_ diff --git a/thirdparty/sdl/SDL_list.c b/thirdparty/sdl/SDL_list.c new file mode 100644 index 00000000000..04cc0825b44 --- /dev/null +++ b/thirdparty/sdl/SDL_list.c @@ -0,0 +1,86 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "./SDL_list.h" + +// Push +bool SDL_ListAdd(SDL_ListNode **head, void *ent) +{ + SDL_ListNode *node = (SDL_ListNode *)SDL_malloc(sizeof(*node)); + + if (!node) { + return false; + } + + node->entry = ent; + node->next = *head; + *head = node; + return true; +} + +// Pop from end as a FIFO (if add with SDL_ListAdd) +void SDL_ListPop(SDL_ListNode **head, void **ent) +{ + SDL_ListNode **ptr = head; + + // Invalid or empty + if (!head || !*head) { + return; + } + + while ((*ptr)->next) { + ptr = &(*ptr)->next; + } + + if (ent) { + *ent = (*ptr)->entry; + } + + SDL_free(*ptr); + *ptr = NULL; +} + +void SDL_ListRemove(SDL_ListNode **head, void *ent) +{ + SDL_ListNode **ptr = head; + + while (*ptr) { + if ((*ptr)->entry == ent) { + SDL_ListNode *tmp = *ptr; + *ptr = (*ptr)->next; + SDL_free(tmp); + return; + } + ptr = &(*ptr)->next; + } +} + +void SDL_ListClear(SDL_ListNode **head) +{ + SDL_ListNode *l = *head; + *head = NULL; + while (l) { + SDL_ListNode *tmp = l; + l = l->next; + SDL_free(tmp); + } +} diff --git a/thirdparty/sdl/SDL_list.h b/thirdparty/sdl/SDL_list.h new file mode 100644 index 00000000000..83ec844b018 --- /dev/null +++ b/thirdparty/sdl/SDL_list.h @@ -0,0 +1,36 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_list_h_ +#define SDL_list_h_ + +typedef struct SDL_ListNode +{ + void *entry; + struct SDL_ListNode *next; +} SDL_ListNode; + +bool SDL_ListAdd(SDL_ListNode **head, void *ent); +void SDL_ListPop(SDL_ListNode **head, void **ent); +void SDL_ListRemove(SDL_ListNode **head, void *ent); +void SDL_ListClear(SDL_ListNode **head); + +#endif // SDL_list_h_ diff --git a/thirdparty/sdl/SDL_log.c b/thirdparty/sdl/SDL_log.c new file mode 100644 index 00000000000..10a814ff1b2 --- /dev/null +++ b/thirdparty/sdl/SDL_log.c @@ -0,0 +1,805 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(SDL_PLATFORM_WINDOWS) +#include "core/windows/SDL_windows.h" +#endif + +// Simple log messages in SDL + +#include "SDL_log_c.h" + +#ifdef HAVE_STDIO_H +#include +#endif + +#ifdef SDL_PLATFORM_ANDROID +#include +#endif + +#include "stdlib/SDL_vacopy.h" + +// The size of the stack buffer to use for rendering log messages. +#define SDL_MAX_LOG_MESSAGE_STACK 256 + +#define DEFAULT_CATEGORY -1 + +typedef struct SDL_LogLevel +{ + int category; + SDL_LogPriority priority; + struct SDL_LogLevel *next; +} SDL_LogLevel; + + +// The default log output function +static void SDLCALL SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority, const char *message); + +static void CleanupLogPriorities(void); +static void CleanupLogPrefixes(void); + +static SDL_InitState SDL_log_init; +static SDL_Mutex *SDL_log_lock; +static SDL_Mutex *SDL_log_function_lock; +static SDL_LogLevel *SDL_loglevels SDL_GUARDED_BY(SDL_log_lock); +static SDL_LogPriority SDL_log_priorities[SDL_LOG_CATEGORY_CUSTOM] SDL_GUARDED_BY(SDL_log_lock); +static SDL_LogPriority SDL_log_default_priority SDL_GUARDED_BY(SDL_log_lock); +static SDL_LogOutputFunction SDL_log_function SDL_GUARDED_BY(SDL_log_function_lock) = SDL_LogOutput; +static void *SDL_log_userdata SDL_GUARDED_BY(SDL_log_function_lock) = NULL; + +#ifdef HAVE_GCC_DIAGNOSTIC_PRAGMA +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-variable" +#endif + +// If this list changes, update the documentation for SDL_HINT_LOGGING +static const char * const SDL_priority_names[] = { + NULL, + "TRACE", + "VERBOSE", + "DEBUG", + "INFO", + "WARN", + "ERROR", + "CRITICAL" +}; +SDL_COMPILE_TIME_ASSERT(priority_names, SDL_arraysize(SDL_priority_names) == SDL_LOG_PRIORITY_COUNT); + +// This is guarded by SDL_log_function_lock because it's the logging function that calls GetLogPriorityPrefix() +static char *SDL_priority_prefixes[SDL_LOG_PRIORITY_COUNT] SDL_GUARDED_BY(SDL_log_function_lock); + +// If this list changes, update the documentation for SDL_HINT_LOGGING +static const char * const SDL_category_names[] = { + "APP", + "ERROR", + "ASSERT", + "SYSTEM", + "AUDIO", + "VIDEO", + "RENDER", + "INPUT", + "TEST", + "GPU" +}; +SDL_COMPILE_TIME_ASSERT(category_names, SDL_arraysize(SDL_category_names) == SDL_LOG_CATEGORY_RESERVED2); + +#ifdef HAVE_GCC_DIAGNOSTIC_PRAGMA +#pragma GCC diagnostic pop +#endif + +#ifdef SDL_PLATFORM_ANDROID +static int SDL_android_priority[] = { + ANDROID_LOG_UNKNOWN, + ANDROID_LOG_VERBOSE, + ANDROID_LOG_VERBOSE, + ANDROID_LOG_DEBUG, + ANDROID_LOG_INFO, + ANDROID_LOG_WARN, + ANDROID_LOG_ERROR, + ANDROID_LOG_FATAL +}; +SDL_COMPILE_TIME_ASSERT(android_priority, SDL_arraysize(SDL_android_priority) == SDL_LOG_PRIORITY_COUNT); +#endif // SDL_PLATFORM_ANDROID + +static void SDLCALL SDL_LoggingChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_ResetLogPriorities(); +} + +void SDL_InitLog(void) +{ + if (!SDL_ShouldInit(&SDL_log_init)) { + return; + } + + // If these fail we'll continue without them. + SDL_log_lock = SDL_CreateMutex(); + SDL_log_function_lock = SDL_CreateMutex(); + + SDL_AddHintCallback(SDL_HINT_LOGGING, SDL_LoggingChanged, NULL); + + SDL_SetInitialized(&SDL_log_init, true); +} + +void SDL_QuitLog(void) +{ + if (!SDL_ShouldQuit(&SDL_log_init)) { + return; + } + + SDL_RemoveHintCallback(SDL_HINT_LOGGING, SDL_LoggingChanged, NULL); + + CleanupLogPriorities(); + CleanupLogPrefixes(); + + if (SDL_log_lock) { + SDL_DestroyMutex(SDL_log_lock); + SDL_log_lock = NULL; + } + if (SDL_log_function_lock) { + SDL_DestroyMutex(SDL_log_function_lock); + SDL_log_function_lock = NULL; + } + + SDL_SetInitialized(&SDL_log_init, false); +} + +static void SDL_CheckInitLog(void) +{ + int status = SDL_GetAtomicInt(&SDL_log_init.status); + if (status == SDL_INIT_STATUS_INITIALIZED || + (status == SDL_INIT_STATUS_INITIALIZING && SDL_log_init.thread == SDL_GetCurrentThreadID())) { + return; + } + + SDL_InitLog(); +} + +static void CleanupLogPriorities(void) +{ + while (SDL_loglevels) { + SDL_LogLevel *entry = SDL_loglevels; + SDL_loglevels = entry->next; + SDL_free(entry); + } +} + +void SDL_SetLogPriorities(SDL_LogPriority priority) +{ + SDL_CheckInitLog(); + + SDL_LockMutex(SDL_log_lock); + { + CleanupLogPriorities(); + + SDL_log_default_priority = priority; + for (int i = 0; i < SDL_arraysize(SDL_log_priorities); ++i) { + SDL_log_priorities[i] = priority; + } + } + SDL_UnlockMutex(SDL_log_lock); +} + +void SDL_SetLogPriority(int category, SDL_LogPriority priority) +{ + SDL_LogLevel *entry; + + SDL_CheckInitLog(); + + SDL_LockMutex(SDL_log_lock); + { + if (category >= 0 && category < SDL_arraysize(SDL_log_priorities)) { + SDL_log_priorities[category] = priority; + } else { + for (entry = SDL_loglevels; entry; entry = entry->next) { + if (entry->category == category) { + entry->priority = priority; + break; + } + } + + if (!entry) { + entry = (SDL_LogLevel *)SDL_malloc(sizeof(*entry)); + if (entry) { + entry->category = category; + entry->priority = priority; + entry->next = SDL_loglevels; + SDL_loglevels = entry; + } + } + } + } + SDL_UnlockMutex(SDL_log_lock); +} + +SDL_LogPriority SDL_GetLogPriority(int category) +{ + SDL_LogLevel *entry; + SDL_LogPriority priority = SDL_LOG_PRIORITY_INVALID; + + SDL_CheckInitLog(); + + // Bypass the lock for known categories + // Technically if the priority was set on a different CPU the value might not + // be visible on this CPU for a while, but in practice it's fast enough that + // this performance improvement is worthwhile. + if (category >= 0 && category < SDL_arraysize(SDL_log_priorities)) { + return SDL_log_priorities[category]; + } + + SDL_LockMutex(SDL_log_lock); + { + if (category >= 0 && category < SDL_arraysize(SDL_log_priorities)) { + priority = SDL_log_priorities[category]; + } else { + for (entry = SDL_loglevels; entry; entry = entry->next) { + if (entry->category == category) { + priority = entry->priority; + break; + } + } + if (priority == SDL_LOG_PRIORITY_INVALID) { + priority = SDL_log_default_priority; + } + } + } + SDL_UnlockMutex(SDL_log_lock); + + return priority; +} + +static bool ParseLogCategory(const char *string, size_t length, int *category) +{ + int i; + + if (SDL_isdigit(*string)) { + *category = SDL_atoi(string); + return true; + } + + if (*string == '*') { + *category = DEFAULT_CATEGORY; + return true; + } + + for (i = 0; i < SDL_arraysize(SDL_category_names); ++i) { + if (SDL_strncasecmp(string, SDL_category_names[i], length) == 0) { + *category = i; + return true; + } + } + return false; +} + +static bool ParseLogPriority(const char *string, size_t length, SDL_LogPriority *priority) +{ + int i; + + if (SDL_isdigit(*string)) { + i = SDL_atoi(string); + if (i == 0) { + // 0 has a special meaning of "disable this category" + *priority = SDL_LOG_PRIORITY_COUNT; + return true; + } + if (i > SDL_LOG_PRIORITY_INVALID && i < SDL_LOG_PRIORITY_COUNT) { + *priority = (SDL_LogPriority)i; + return true; + } + return false; + } + + if (SDL_strncasecmp(string, "quiet", length) == 0) { + *priority = SDL_LOG_PRIORITY_COUNT; + return true; + } + + for (i = SDL_LOG_PRIORITY_INVALID + 1; i < SDL_LOG_PRIORITY_COUNT; ++i) { + if (SDL_strncasecmp(string, SDL_priority_names[i], length) == 0) { + *priority = (SDL_LogPriority)i; + return true; + } + } + return false; +} + +static void ParseLogPriorities(const char *hint) +{ + const char *name, *next; + int category = DEFAULT_CATEGORY; + SDL_LogPriority priority = SDL_LOG_PRIORITY_INVALID; + + if (SDL_strchr(hint, '=') == NULL) { + if (ParseLogPriority(hint, SDL_strlen(hint), &priority)) { + SDL_SetLogPriorities(priority); + } + return; + } + + for (name = hint; name; name = next) { + const char *sep = SDL_strchr(name, '='); + if (!sep) { + break; + } + next = SDL_strchr(sep, ','); + if (next) { + ++next; + } + + if (ParseLogCategory(name, (sep - name), &category)) { + const char *value = sep + 1; + size_t len; + if (next) { + len = (next - value - 1); + } else { + len = SDL_strlen(value); + } + if (ParseLogPriority(value, len, &priority)) { + if (category == DEFAULT_CATEGORY) { + for (int i = 0; i < SDL_arraysize(SDL_log_priorities); ++i) { + if (SDL_log_priorities[i] == SDL_LOG_PRIORITY_INVALID) { + SDL_log_priorities[i] = priority; + } + } + SDL_log_default_priority = priority; + } else { + SDL_SetLogPriority(category, priority); + } + } + } + } +} + +void SDL_ResetLogPriorities(void) +{ + SDL_CheckInitLog(); + + SDL_LockMutex(SDL_log_lock); + { + CleanupLogPriorities(); + + SDL_log_default_priority = SDL_LOG_PRIORITY_INVALID; + for (int i = 0; i < SDL_arraysize(SDL_log_priorities); ++i) { + SDL_log_priorities[i] = SDL_LOG_PRIORITY_INVALID; + } + + const char *hint = SDL_GetHint(SDL_HINT_LOGGING); + if (hint) { + ParseLogPriorities(hint); + } + + if (SDL_log_default_priority == SDL_LOG_PRIORITY_INVALID) { + SDL_log_default_priority = SDL_LOG_PRIORITY_ERROR; + } + for (int i = 0; i < SDL_arraysize(SDL_log_priorities); ++i) { + if (SDL_log_priorities[i] != SDL_LOG_PRIORITY_INVALID) { + continue; + } + + switch (i) { + case SDL_LOG_CATEGORY_APPLICATION: + SDL_log_priorities[i] = SDL_LOG_PRIORITY_INFO; + break; + case SDL_LOG_CATEGORY_ASSERT: + SDL_log_priorities[i] = SDL_LOG_PRIORITY_WARN; + break; + case SDL_LOG_CATEGORY_TEST: + SDL_log_priorities[i] = SDL_LOG_PRIORITY_VERBOSE; + break; + default: + SDL_log_priorities[i] = SDL_LOG_PRIORITY_ERROR; + break; + } + } + } + SDL_UnlockMutex(SDL_log_lock); +} + +static void CleanupLogPrefixes(void) +{ + for (int i = 0; i < SDL_arraysize(SDL_priority_prefixes); ++i) { + if (SDL_priority_prefixes[i]) { + SDL_free(SDL_priority_prefixes[i]); + SDL_priority_prefixes[i] = NULL; + } + } +} + +static const char *GetLogPriorityPrefix(SDL_LogPriority priority) +{ + if (priority <= SDL_LOG_PRIORITY_INVALID || priority >= SDL_LOG_PRIORITY_COUNT) { + return ""; + } + + if (SDL_priority_prefixes[priority]) { + return SDL_priority_prefixes[priority]; + } + + switch (priority) { + case SDL_LOG_PRIORITY_WARN: + return "WARNING: "; + case SDL_LOG_PRIORITY_ERROR: + return "ERROR: "; + case SDL_LOG_PRIORITY_CRITICAL: + return "ERROR: "; + default: + return ""; + } +} + +bool SDL_SetLogPriorityPrefix(SDL_LogPriority priority, const char *prefix) +{ + char *prefix_copy; + + if (priority <= SDL_LOG_PRIORITY_INVALID || priority >= SDL_LOG_PRIORITY_COUNT) { + return SDL_InvalidParamError("priority"); + } + + if (!prefix || !*prefix) { + prefix_copy = SDL_strdup(""); + } else { + prefix_copy = SDL_strdup(prefix); + } + if (!prefix_copy) { + return false; + } + + SDL_LockMutex(SDL_log_function_lock); + { + if (SDL_priority_prefixes[priority]) { + SDL_free(SDL_priority_prefixes[priority]); + } + SDL_priority_prefixes[priority] = prefix_copy; + } + SDL_UnlockMutex(SDL_log_function_lock); + + return true; +} + +void SDL_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap); + va_end(ap); +} + +void SDL_LogTrace(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_TRACE, fmt, ap); + va_end(ap); +} + +void SDL_LogVerbose(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_VERBOSE, fmt, ap); + va_end(ap); +} + +void SDL_LogDebug(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_DEBUG, fmt, ap); + va_end(ap); +} + +void SDL_LogInfo(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_INFO, fmt, ap); + va_end(ap); +} + +void SDL_LogWarn(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_WARN, fmt, ap); + va_end(ap); +} + +void SDL_LogError(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_ERROR, fmt, ap); + va_end(ap); +} + +void SDL_LogCritical(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_CRITICAL, fmt, ap); + va_end(ap); +} + +void SDL_LogMessage(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, priority, fmt, ap); + va_end(ap); +} + +#ifdef SDL_PLATFORM_ANDROID +static const char *GetCategoryPrefix(int category) +{ + if (category < SDL_LOG_CATEGORY_RESERVED2) { + return SDL_category_names[category]; + } + if (category < SDL_LOG_CATEGORY_CUSTOM) { + return "RESERVED"; + } + return "CUSTOM"; +} +#endif // SDL_PLATFORM_ANDROID + +void SDL_LogMessageV(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) +{ + char *message = NULL; + char stack_buf[SDL_MAX_LOG_MESSAGE_STACK]; + size_t len_plus_term; + int len; + va_list aq; + + // Nothing to do if we don't have an output function + if (!SDL_log_function) { + return; + } + + // See if we want to do anything with this message + if (priority < SDL_GetLogPriority(category)) { + return; + } + + // Render into stack buffer + va_copy(aq, ap); + len = SDL_vsnprintf(stack_buf, sizeof(stack_buf), fmt, aq); + va_end(aq); + + if (len < 0) { + return; + } + + // If message truncated, allocate and re-render + if (len >= sizeof(stack_buf) && SDL_size_add_check_overflow(len, 1, &len_plus_term)) { + // Allocate exactly what we need, including the zero-terminator + message = (char *)SDL_malloc(len_plus_term); + if (!message) { + return; + } + va_copy(aq, ap); + len = SDL_vsnprintf(message, len_plus_term, fmt, aq); + va_end(aq); + } else { + message = stack_buf; + } + + // Chop off final endline. + if ((len > 0) && (message[len - 1] == '\n')) { + message[--len] = '\0'; + if ((len > 0) && (message[len - 1] == '\r')) { // catch "\r\n", too. + message[--len] = '\0'; + } + } + + SDL_LockMutex(SDL_log_function_lock); + { + SDL_log_function(SDL_log_userdata, category, priority, message); + } + SDL_UnlockMutex(SDL_log_function_lock); + + // Free only if dynamically allocated + if (message != stack_buf) { + SDL_free(message); + } +} + +#if defined(SDL_PLATFORM_WIN32) && !defined(SDL_PLATFORM_GDK) +enum { + CONSOLE_UNATTACHED = 0, + CONSOLE_ATTACHED_CONSOLE = 1, + CONSOLE_ATTACHED_FILE = 2, + CONSOLE_ATTACHED_ERROR = -1, +} consoleAttached = CONSOLE_UNATTACHED; + +// Handle to stderr output of console. +static HANDLE stderrHandle = NULL; +#endif + +static void SDLCALL SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority, + const char *message) +{ +#if defined(SDL_PLATFORM_WINDOWS) + // Way too many allocations here, urgh + // Note: One can't call SDL_SetError here, since that function itself logs. + { + char *output; + size_t length; + LPTSTR tstr; + bool isstack; + +#if !defined(SDL_PLATFORM_GDK) + BOOL attachResult; + DWORD attachError; + DWORD consoleMode; + DWORD charsWritten; + + // Maybe attach console and get stderr handle + if (consoleAttached == CONSOLE_UNATTACHED) { + attachResult = AttachConsole(ATTACH_PARENT_PROCESS); + if (!attachResult) { + attachError = GetLastError(); + if (attachError == ERROR_INVALID_HANDLE) { + // This is expected when running from Visual Studio + // OutputDebugString(TEXT("Parent process has no console\r\n")); + consoleAttached = CONSOLE_ATTACHED_ERROR; + } else if (attachError == ERROR_GEN_FAILURE) { + OutputDebugString(TEXT("Could not attach to console of parent process\r\n")); + consoleAttached = CONSOLE_ATTACHED_ERROR; + } else if (attachError == ERROR_ACCESS_DENIED) { + // Already attached + consoleAttached = CONSOLE_ATTACHED_CONSOLE; + } else { + OutputDebugString(TEXT("Error attaching console\r\n")); + consoleAttached = CONSOLE_ATTACHED_ERROR; + } + } else { + // Newly attached + consoleAttached = CONSOLE_ATTACHED_CONSOLE; + } + + if (consoleAttached == CONSOLE_ATTACHED_CONSOLE) { + stderrHandle = GetStdHandle(STD_ERROR_HANDLE); + + if (GetConsoleMode(stderrHandle, &consoleMode) == 0) { + // WriteConsole fails if the output is redirected to a file. Must use WriteFile instead. + consoleAttached = CONSOLE_ATTACHED_FILE; + } + } + } +#endif // !defined(SDL_PLATFORM_GDK) + length = SDL_strlen(GetLogPriorityPrefix(priority)) + SDL_strlen(message) + 1 + 1 + 1; + output = SDL_small_alloc(char, length, &isstack); + if (!output) { + return; + } + (void)SDL_snprintf(output, length, "%s%s\r\n", GetLogPriorityPrefix(priority), message); + tstr = WIN_UTF8ToString(output); + + // Output to debugger + OutputDebugString(tstr); + +#if !defined(SDL_PLATFORM_GDK) + // Screen output to stderr, if console was attached. + if (consoleAttached == CONSOLE_ATTACHED_CONSOLE) { + if (!WriteConsole(stderrHandle, tstr, (DWORD)SDL_tcslen(tstr), &charsWritten, NULL)) { + OutputDebugString(TEXT("Error calling WriteConsole\r\n")); + if (GetLastError() == ERROR_NOT_ENOUGH_MEMORY) { + OutputDebugString(TEXT("Insufficient heap memory to write message\r\n")); + } + } + + } else if (consoleAttached == CONSOLE_ATTACHED_FILE) { + if (!WriteFile(stderrHandle, output, (DWORD)SDL_strlen(output), &charsWritten, NULL)) { + OutputDebugString(TEXT("Error calling WriteFile\r\n")); + } + } +#endif // !defined(SDL_PLATFORM_GDK) + + SDL_free(tstr); + SDL_small_free(output, isstack); + } +#elif defined(SDL_PLATFORM_ANDROID) + { + char tag[32]; + + SDL_snprintf(tag, SDL_arraysize(tag), "SDL/%s", GetCategoryPrefix(category)); + __android_log_write(SDL_android_priority[priority], tag, message); + } +#elif defined(SDL_PLATFORM_APPLE) && (defined(SDL_VIDEO_DRIVER_COCOA) || defined(SDL_VIDEO_DRIVER_UIKIT)) + /* Technically we don't need Cocoa/UIKit, but that's where this function is defined for now. + */ + extern void SDL_NSLog(const char *prefix, const char *text); + { + SDL_NSLog(GetLogPriorityPrefix(priority), message); + return; + } +#elif defined(SDL_PLATFORM_PSP) || defined(SDL_PLATFORM_PS2) + { + FILE *pFile; + pFile = fopen("SDL_Log.txt", "a"); + if (pFile) { + (void)fprintf(pFile, "%s%s\n", GetLogPriorityPrefix(priority), message); + (void)fclose(pFile); + } + } +#elif defined(SDL_PLATFORM_VITA) + { + FILE *pFile; + pFile = fopen("ux0:/data/SDL_Log.txt", "a"); + if (pFile) { + (void)fprintf(pFile, "%s%s\n", GetLogPriorityPrefix(priority), message); + (void)fclose(pFile); + } + } +#elif defined(SDL_PLATFORM_3DS) + { + FILE *pFile; + pFile = fopen("sdmc:/3ds/SDL_Log.txt", "a"); + if (pFile) { + (void)fprintf(pFile, "%s%s\n", GetLogPriorityPrefix(priority), message); + (void)fclose(pFile); + } + } +#endif +#if defined(HAVE_STDIO_H) && \ + !(defined(SDL_PLATFORM_APPLE) && (defined(SDL_VIDEO_DRIVER_COCOA) || defined(SDL_VIDEO_DRIVER_UIKIT))) && \ + !(defined(SDL_PLATFORM_WIN32)) + (void)fprintf(stderr, "%s%s\n", GetLogPriorityPrefix(priority), message); +#endif +} + +SDL_LogOutputFunction SDL_GetDefaultLogOutputFunction(void) +{ + return SDL_LogOutput; +} + +void SDL_GetLogOutputFunction(SDL_LogOutputFunction *callback, void **userdata) +{ + SDL_LockMutex(SDL_log_function_lock); + { + if (callback) { + *callback = SDL_log_function; + } + if (userdata) { + *userdata = SDL_log_userdata; + } + } + SDL_UnlockMutex(SDL_log_function_lock); +} + +void SDL_SetLogOutputFunction(SDL_LogOutputFunction callback, void *userdata) +{ + SDL_LockMutex(SDL_log_function_lock); + { + SDL_log_function = callback; + SDL_log_userdata = userdata; + } + SDL_UnlockMutex(SDL_log_function_lock); +} diff --git a/thirdparty/sdl/SDL_log_c.h b/thirdparty/sdl/SDL_log_c.h new file mode 100644 index 00000000000..887a3253806 --- /dev/null +++ b/thirdparty/sdl/SDL_log_c.h @@ -0,0 +1,31 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This file defines useful function for working with SDL logging + +#ifndef SDL_log_c_h_ +#define SDL_log_c_h_ + +extern void SDL_InitLog(void); +extern void SDL_QuitLog(void); + +#endif // SDL_log_c_h_ diff --git a/thirdparty/sdl/SDL_properties.c b/thirdparty/sdl/SDL_properties.c new file mode 100644 index 00000000000..42d48454580 --- /dev/null +++ b/thirdparty/sdl/SDL_properties.c @@ -0,0 +1,824 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_hints_c.h" +#include "SDL_properties_c.h" + + +typedef struct +{ + SDL_PropertyType type; + + union { + void *pointer_value; + char *string_value; + Sint64 number_value; + float float_value; + bool boolean_value; + } value; + + char *string_storage; + + SDL_CleanupPropertyCallback cleanup; + void *userdata; +} SDL_Property; + +typedef struct +{ + SDL_HashTable *props; + SDL_Mutex *lock; +} SDL_Properties; + +static SDL_InitState SDL_properties_init; +static SDL_HashTable *SDL_properties; +static SDL_AtomicU32 SDL_last_properties_id; +static SDL_AtomicU32 SDL_global_properties; + + +static void SDL_FreePropertyWithCleanup(const void *key, const void *value, void *data, bool cleanup) +{ + SDL_Property *property = (SDL_Property *)value; + if (property) { + switch (property->type) { + case SDL_PROPERTY_TYPE_POINTER: + if (property->cleanup && cleanup) { + property->cleanup(property->userdata, property->value.pointer_value); + } + break; + case SDL_PROPERTY_TYPE_STRING: + SDL_free(property->value.string_value); + break; + default: + break; + } + SDL_free(property->string_storage); + } + SDL_free((void *)key); + SDL_free((void *)value); +} + +static void SDLCALL SDL_FreeProperty(void *data, const void *key, const void *value) +{ + SDL_FreePropertyWithCleanup(key, value, data, true); +} + +static void SDL_FreeProperties(SDL_Properties *properties) +{ + if (properties) { + SDL_DestroyHashTable(properties->props); + SDL_DestroyMutex(properties->lock); + SDL_free(properties); + } +} + +bool SDL_InitProperties(void) +{ + if (!SDL_ShouldInit(&SDL_properties_init)) { + return true; + } + + SDL_properties = SDL_CreateHashTable(0, true, SDL_HashID, SDL_KeyMatchID, NULL, NULL); + const bool initialized = (SDL_properties != NULL); + SDL_SetInitialized(&SDL_properties_init, initialized); + return initialized; +} + +static bool SDLCALL FreeOneProperties(void *userdata, const SDL_HashTable *table, const void *key, const void *value) +{ + SDL_FreeProperties((SDL_Properties *)value); + return true; // keep iterating. +} + +void SDL_QuitProperties(void) +{ + if (!SDL_ShouldQuit(&SDL_properties_init)) { + return; + } + + SDL_PropertiesID props; + do { + props = SDL_GetAtomicU32(&SDL_global_properties); + } while (!SDL_CompareAndSwapAtomicU32(&SDL_global_properties, props, 0)); + + if (props) { + SDL_DestroyProperties(props); + } + + // this can't just DestroyHashTable with SDL_FreeProperties as the destructor, because + // other destructors under this might cause use to attempt a recursive lock on SDL_properties, + // which isn't allowed with rwlocks. So manually iterate and free everything. + SDL_HashTable *properties = SDL_properties; + SDL_properties = NULL; + SDL_IterateHashTable(properties, FreeOneProperties, NULL); + SDL_DestroyHashTable(properties); + + SDL_SetInitialized(&SDL_properties_init, false); +} + +static bool SDL_CheckInitProperties(void) +{ + return SDL_InitProperties(); +} + +SDL_PropertiesID SDL_GetGlobalProperties(void) +{ + SDL_PropertiesID props = SDL_GetAtomicU32(&SDL_global_properties); + if (!props) { + props = SDL_CreateProperties(); + if (!SDL_CompareAndSwapAtomicU32(&SDL_global_properties, 0, props)) { + // Somebody else created global properties before us, just use those + SDL_DestroyProperties(props); + props = SDL_GetAtomicU32(&SDL_global_properties); + } + } + return props; +} + +SDL_PropertiesID SDL_CreateProperties(void) +{ + if (!SDL_CheckInitProperties()) { + return 0; + } + + SDL_Properties *properties = (SDL_Properties *)SDL_calloc(1, sizeof(*properties)); + if (!properties) { + return 0; + } + + properties->lock = SDL_CreateMutex(); + if (!properties->lock) { + SDL_free(properties); + return 0; + } + + properties->props = SDL_CreateHashTable(0, false, SDL_HashString, SDL_KeyMatchString, SDL_FreeProperty, NULL); + if (!properties->props) { + SDL_DestroyMutex(properties->lock); + SDL_free(properties); + return 0; + } + + SDL_PropertiesID props = 0; + while (true) { + props = (SDL_GetAtomicU32(&SDL_last_properties_id) + 1); + if (props == 0) { + continue; + } else if (SDL_CompareAndSwapAtomicU32(&SDL_last_properties_id, props - 1, props)) { + break; + } + } + + SDL_assert(!SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, NULL)); // should NOT be in the hash table already. + + if (!SDL_InsertIntoHashTable(SDL_properties, (const void *)(uintptr_t)props, properties, false)) { + SDL_FreeProperties(properties); + return 0; + } + + return props; // All done! +} + +typedef struct CopyOnePropertyData +{ + SDL_Properties *dst_properties; + bool result; +} CopyOnePropertyData; + +static bool SDLCALL CopyOneProperty(void *userdata, const SDL_HashTable *table, const void *key, const void *value) +{ + const SDL_Property *src_property = (const SDL_Property *)value; + if (src_property->cleanup) { + // Can't copy properties with cleanup functions, we don't know how to duplicate the data + return true; // keep iterating. + } + + CopyOnePropertyData *data = (CopyOnePropertyData *) userdata; + SDL_Properties *dst_properties = data->dst_properties; + const char *src_name = (const char *)key; + SDL_Property *dst_property; + + char *dst_name = SDL_strdup(src_name); + if (!dst_name) { + data->result = false; + return true; // keep iterating (I guess...?) + } + + dst_property = (SDL_Property *)SDL_malloc(sizeof(*dst_property)); + if (!dst_property) { + SDL_free(dst_name); + data->result = false; + return true; // keep iterating (I guess...?) + } + + SDL_copyp(dst_property, src_property); + if (src_property->type == SDL_PROPERTY_TYPE_STRING) { + dst_property->value.string_value = SDL_strdup(src_property->value.string_value); + if (!dst_property->value.string_value) { + SDL_free(dst_name); + SDL_free(dst_property); + data->result = false; + return true; // keep iterating (I guess...?) + } + } + + if (!SDL_InsertIntoHashTable(dst_properties->props, dst_name, dst_property, true)) { + SDL_FreePropertyWithCleanup(dst_name, dst_property, NULL, false); + data->result = false; + } + + return true; // keep iterating. +} + +bool SDL_CopyProperties(SDL_PropertiesID src, SDL_PropertiesID dst) +{ + if (!src) { + return SDL_InvalidParamError("src"); + } + if (!dst) { + return SDL_InvalidParamError("dst"); + } + + SDL_Properties *src_properties = NULL; + SDL_Properties *dst_properties = NULL; + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)src, (const void **)&src_properties); + if (!src_properties) { + return SDL_InvalidParamError("src"); + } + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)dst, (const void **)&dst_properties); + if (!dst_properties) { + return SDL_InvalidParamError("dst"); + } + + bool result = true; + SDL_LockMutex(src_properties->lock); + SDL_LockMutex(dst_properties->lock); + { + CopyOnePropertyData data = { dst_properties, true }; + SDL_IterateHashTable(src_properties->props, CopyOneProperty, &data); + result = data.result; + } + SDL_UnlockMutex(dst_properties->lock); + SDL_UnlockMutex(src_properties->lock); + + return result; +} + +bool SDL_LockProperties(SDL_PropertiesID props) +{ + SDL_Properties *properties = NULL; + + if (!props) { + return SDL_InvalidParamError("props"); + } + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties); + if (!properties) { + return SDL_InvalidParamError("props"); + } + + SDL_LockMutex(properties->lock); + return true; +} + +void SDL_UnlockProperties(SDL_PropertiesID props) +{ + SDL_Properties *properties = NULL; + + if (!props) { + return; + } + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties); + if (!properties) { + return; + } + + SDL_UnlockMutex(properties->lock); +} + +static bool SDL_PrivateSetProperty(SDL_PropertiesID props, const char *name, SDL_Property *property) +{ + SDL_Properties *properties = NULL; + bool result = true; + + if (!props) { + SDL_FreePropertyWithCleanup(NULL, property, NULL, true); + return SDL_InvalidParamError("props"); + } + if (!name || !*name) { + SDL_FreePropertyWithCleanup(NULL, property, NULL, true); + return SDL_InvalidParamError("name"); + } + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties); + if (!properties) { + SDL_FreePropertyWithCleanup(NULL, property, NULL, true); + return SDL_InvalidParamError("props"); + } + + SDL_LockMutex(properties->lock); + { + SDL_RemoveFromHashTable(properties->props, name); + if (property) { + char *key = SDL_strdup(name); + if (!key || !SDL_InsertIntoHashTable(properties->props, key, property, false)) { + SDL_FreePropertyWithCleanup(key, property, NULL, true); + result = false; + } + } + } + SDL_UnlockMutex(properties->lock); + + return result; +} + +bool SDL_SetPointerPropertyWithCleanup(SDL_PropertiesID props, const char *name, void *value, SDL_CleanupPropertyCallback cleanup, void *userdata) +{ + SDL_Property *property; + + if (!value) { + if (cleanup) { + cleanup(userdata, value); + } + return SDL_ClearProperty(props, name); + } + + property = (SDL_Property *)SDL_calloc(1, sizeof(*property)); + if (!property) { + if (cleanup) { + cleanup(userdata, value); + } + SDL_FreePropertyWithCleanup(NULL, property, NULL, false); + return false; + } + property->type = SDL_PROPERTY_TYPE_POINTER; + property->value.pointer_value = value; + property->cleanup = cleanup; + property->userdata = userdata; + return SDL_PrivateSetProperty(props, name, property); +} + +bool SDL_SetPointerProperty(SDL_PropertiesID props, const char *name, void *value) +{ + SDL_Property *property; + + if (!value) { + return SDL_ClearProperty(props, name); + } + + property = (SDL_Property *)SDL_calloc(1, sizeof(*property)); + if (!property) { + return false; + } + property->type = SDL_PROPERTY_TYPE_POINTER; + property->value.pointer_value = value; + return SDL_PrivateSetProperty(props, name, property); +} + +static void SDLCALL CleanupFreeableProperty(void *userdata, void *value) +{ + SDL_free(value); +} + +bool SDL_SetFreeableProperty(SDL_PropertiesID props, const char *name, void *value) +{ + return SDL_SetPointerPropertyWithCleanup(props, name, value, CleanupFreeableProperty, NULL); +} + +static void SDLCALL CleanupSurface(void *userdata, void *value) +{ + SDL_Surface *surface = (SDL_Surface *)value; + + //SDL_DestroySurface(surface); +} + +bool SDL_SetSurfaceProperty(SDL_PropertiesID props, const char *name, SDL_Surface *surface) +{ + return SDL_SetPointerPropertyWithCleanup(props, name, surface, CleanupSurface, NULL); +} + +bool SDL_SetStringProperty(SDL_PropertiesID props, const char *name, const char *value) +{ + SDL_Property *property; + + if (!value) { + return SDL_ClearProperty(props, name); + } + + property = (SDL_Property *)SDL_calloc(1, sizeof(*property)); + if (!property) { + return false; + } + property->type = SDL_PROPERTY_TYPE_STRING; + property->value.string_value = SDL_strdup(value); + if (!property->value.string_value) { + SDL_free(property); + return false; + } + return SDL_PrivateSetProperty(props, name, property); +} + +bool SDL_SetNumberProperty(SDL_PropertiesID props, const char *name, Sint64 value) +{ + SDL_Property *property = (SDL_Property *)SDL_calloc(1, sizeof(*property)); + if (!property) { + return false; + } + property->type = SDL_PROPERTY_TYPE_NUMBER; + property->value.number_value = value; + return SDL_PrivateSetProperty(props, name, property); +} + +bool SDL_SetFloatProperty(SDL_PropertiesID props, const char *name, float value) +{ + SDL_Property *property = (SDL_Property *)SDL_calloc(1, sizeof(*property)); + if (!property) { + return false; + } + property->type = SDL_PROPERTY_TYPE_FLOAT; + property->value.float_value = value; + return SDL_PrivateSetProperty(props, name, property); +} + +bool SDL_SetBooleanProperty(SDL_PropertiesID props, const char *name, bool value) +{ + SDL_Property *property = (SDL_Property *)SDL_calloc(1, sizeof(*property)); + if (!property) { + return false; + } + property->type = SDL_PROPERTY_TYPE_BOOLEAN; + property->value.boolean_value = value ? true : false; + return SDL_PrivateSetProperty(props, name, property); +} + +bool SDL_HasProperty(SDL_PropertiesID props, const char *name) +{ + return (SDL_GetPropertyType(props, name) != SDL_PROPERTY_TYPE_INVALID); +} + +SDL_PropertyType SDL_GetPropertyType(SDL_PropertiesID props, const char *name) +{ + SDL_Properties *properties = NULL; + SDL_PropertyType type = SDL_PROPERTY_TYPE_INVALID; + + if (!props) { + return SDL_PROPERTY_TYPE_INVALID; + } + if (!name || !*name) { + return SDL_PROPERTY_TYPE_INVALID; + } + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties); + if (!properties) { + return SDL_PROPERTY_TYPE_INVALID; + } + + SDL_LockMutex(properties->lock); + { + SDL_Property *property = NULL; + if (SDL_FindInHashTable(properties->props, name, (const void **)&property)) { + type = property->type; + } + } + SDL_UnlockMutex(properties->lock); + + return type; +} + +void *SDL_GetPointerProperty(SDL_PropertiesID props, const char *name, void *default_value) +{ + SDL_Properties *properties = NULL; + void *value = default_value; + + if (!props) { + return value; + } + if (!name || !*name) { + return value; + } + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties); + if (!properties) { + return value; + } + + // Note that taking the lock here only guarantees that we won't read the + // hashtable while it's being modified. The value itself can easily be + // freed from another thread after it is returned here. + SDL_LockMutex(properties->lock); + { + SDL_Property *property = NULL; + if (SDL_FindInHashTable(properties->props, name, (const void **)&property)) { + if (property->type == SDL_PROPERTY_TYPE_POINTER) { + value = property->value.pointer_value; + } + } + } + SDL_UnlockMutex(properties->lock); + + return value; +} + +const char *SDL_GetStringProperty(SDL_PropertiesID props, const char *name, const char *default_value) +{ + SDL_Properties *properties = NULL; + const char *value = default_value; + + if (!props) { + return value; + } + if (!name || !*name) { + return value; + } + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties); + if (!properties) { + return value; + } + + SDL_LockMutex(properties->lock); + { + SDL_Property *property = NULL; + if (SDL_FindInHashTable(properties->props, name, (const void **)&property)) { + switch (property->type) { + case SDL_PROPERTY_TYPE_STRING: + value = property->value.string_value; + break; + case SDL_PROPERTY_TYPE_NUMBER: + if (property->string_storage) { + value = property->string_storage; + } else { + SDL_asprintf(&property->string_storage, "%" SDL_PRIs64, property->value.number_value); + if (property->string_storage) { + value = property->string_storage; + } + } + break; + case SDL_PROPERTY_TYPE_FLOAT: + if (property->string_storage) { + value = property->string_storage; + } else { + SDL_asprintf(&property->string_storage, "%f", property->value.float_value); + if (property->string_storage) { + value = property->string_storage; + } + } + break; + case SDL_PROPERTY_TYPE_BOOLEAN: + value = property->value.boolean_value ? "true" : "false"; + break; + default: + break; + } + } + } + SDL_UnlockMutex(properties->lock); + + return value; +} + +Sint64 SDL_GetNumberProperty(SDL_PropertiesID props, const char *name, Sint64 default_value) +{ + SDL_Properties *properties = NULL; + Sint64 value = default_value; + + if (!props) { + return value; + } + if (!name || !*name) { + return value; + } + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties); + if (!properties) { + return value; + } + + SDL_LockMutex(properties->lock); + { + SDL_Property *property = NULL; + if (SDL_FindInHashTable(properties->props, name, (const void **)&property)) { + switch (property->type) { + case SDL_PROPERTY_TYPE_STRING: + value = (Sint64)SDL_strtoll(property->value.string_value, NULL, 0); + break; + case SDL_PROPERTY_TYPE_NUMBER: + value = property->value.number_value; + break; + case SDL_PROPERTY_TYPE_FLOAT: + value = (Sint64)SDL_round((double)property->value.float_value); + break; + case SDL_PROPERTY_TYPE_BOOLEAN: + value = property->value.boolean_value; + break; + default: + break; + } + } + } + SDL_UnlockMutex(properties->lock); + + return value; +} + +float SDL_GetFloatProperty(SDL_PropertiesID props, const char *name, float default_value) +{ + SDL_Properties *properties = NULL; + float value = default_value; + + if (!props) { + return value; + } + if (!name || !*name) { + return value; + } + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties); + if (!properties) { + return value; + } + + SDL_LockMutex(properties->lock); + { + SDL_Property *property = NULL; + if (SDL_FindInHashTable(properties->props, name, (const void **)&property)) { + switch (property->type) { + case SDL_PROPERTY_TYPE_STRING: + value = (float)SDL_atof(property->value.string_value); + break; + case SDL_PROPERTY_TYPE_NUMBER: + value = (float)property->value.number_value; + break; + case SDL_PROPERTY_TYPE_FLOAT: + value = property->value.float_value; + break; + case SDL_PROPERTY_TYPE_BOOLEAN: + value = (float)property->value.boolean_value; + break; + default: + break; + } + } + } + SDL_UnlockMutex(properties->lock); + + return value; +} + +bool SDL_GetBooleanProperty(SDL_PropertiesID props, const char *name, bool default_value) +{ + SDL_Properties *properties = NULL; + bool value = default_value ? true : false; + + if (!props) { + return value; + } + if (!name || !*name) { + return value; + } + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties); + if (!properties) { + return value; + } + + SDL_LockMutex(properties->lock); + { + SDL_Property *property = NULL; + if (SDL_FindInHashTable(properties->props, name, (const void **)&property)) { + switch (property->type) { + case SDL_PROPERTY_TYPE_STRING: + value = SDL_GetStringBoolean(property->value.string_value, default_value); + break; + case SDL_PROPERTY_TYPE_NUMBER: + value = (property->value.number_value != 0); + break; + case SDL_PROPERTY_TYPE_FLOAT: + value = (property->value.float_value != 0.0f); + break; + case SDL_PROPERTY_TYPE_BOOLEAN: + value = property->value.boolean_value; + break; + default: + break; + } + } + } + SDL_UnlockMutex(properties->lock); + + return value; +} + +bool SDL_ClearProperty(SDL_PropertiesID props, const char *name) +{ + return SDL_PrivateSetProperty(props, name, NULL); +} + +typedef struct EnumerateOnePropertyData +{ + SDL_EnumeratePropertiesCallback callback; + void *userdata; + SDL_PropertiesID props; +} EnumerateOnePropertyData; + + +static bool SDLCALL EnumerateOneProperty(void *userdata, const SDL_HashTable *table, const void *key, const void *value) +{ + (void) table; + (void) value; + const EnumerateOnePropertyData *data = (const EnumerateOnePropertyData *) userdata; + data->callback(data->userdata, data->props, (const char *)key); + return true; // keep iterating. +} + +bool SDL_EnumerateProperties(SDL_PropertiesID props, SDL_EnumeratePropertiesCallback callback, void *userdata) +{ + SDL_Properties *properties = NULL; + + if (!props) { + return SDL_InvalidParamError("props"); + } + if (!callback) { + return SDL_InvalidParamError("callback"); + } + + SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties); + if (!properties) { + return SDL_InvalidParamError("props"); + } + + SDL_LockMutex(properties->lock); + { + EnumerateOnePropertyData data = { callback, userdata, props }; + SDL_IterateHashTable(properties->props, EnumerateOneProperty, &data); + } + SDL_UnlockMutex(properties->lock); + + return true; +} + +static void SDLCALL SDL_DumpPropertiesCallback(void *userdata, SDL_PropertiesID props, const char *name) +{ + switch (SDL_GetPropertyType(props, name)) { + case SDL_PROPERTY_TYPE_POINTER: + SDL_Log("%s: %p", name, SDL_GetPointerProperty(props, name, NULL)); + break; + case SDL_PROPERTY_TYPE_STRING: + SDL_Log("%s: \"%s\"", name, SDL_GetStringProperty(props, name, "")); + break; + case SDL_PROPERTY_TYPE_NUMBER: + { + Sint64 value = SDL_GetNumberProperty(props, name, 0); + SDL_Log("%s: %" SDL_PRIs64 " (%" SDL_PRIx64 ")", name, value, value); + } + break; + case SDL_PROPERTY_TYPE_FLOAT: + SDL_Log("%s: %g", name, SDL_GetFloatProperty(props, name, 0.0f)); + break; + case SDL_PROPERTY_TYPE_BOOLEAN: + SDL_Log("%s: %s", name, SDL_GetBooleanProperty(props, name, false) ? "true" : "false"); + break; + default: + SDL_Log("%s UNKNOWN TYPE", name); + break; + } +} + +bool SDL_DumpProperties(SDL_PropertiesID props) +{ + return SDL_EnumerateProperties(props, SDL_DumpPropertiesCallback, NULL); +} + +void SDL_DestroyProperties(SDL_PropertiesID props) +{ + if (props) { + // this can't just use RemoveFromHashTable with SDL_FreeProperties as the destructor, because + // other destructors under this might cause use to attempt a recursive lock on SDL_properties, + // which isn't allowed with rwlocks. So manually look it up and remove/free it. + SDL_Properties *properties = NULL; + if (SDL_FindInHashTable(SDL_properties, (const void *)(uintptr_t)props, (const void **)&properties)) { + SDL_FreeProperties(properties); + SDL_RemoveFromHashTable(SDL_properties, (const void *)(uintptr_t)props); + } + } +} diff --git a/thirdparty/sdl/SDL_properties_c.h b/thirdparty/sdl/SDL_properties_c.h new file mode 100644 index 00000000000..8d1d39daea3 --- /dev/null +++ b/thirdparty/sdl/SDL_properties_c.h @@ -0,0 +1,26 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +extern bool SDL_InitProperties(void); +extern bool SDL_SetFreeableProperty(SDL_PropertiesID props, const char *name, void *value); +extern bool SDL_SetSurfaceProperty(SDL_PropertiesID props, const char *name, SDL_Surface *surface); +extern bool SDL_DumpProperties(SDL_PropertiesID props); +extern void SDL_QuitProperties(void); diff --git a/thirdparty/sdl/SDL_utils.c b/thirdparty/sdl/SDL_utils.c new file mode 100644 index 00000000000..f2090747a8d --- /dev/null +++ b/thirdparty/sdl/SDL_utils.c @@ -0,0 +1,554 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(HAVE_GETHOSTNAME) && !defined(SDL_PLATFORM_WINDOWS) +#include +#endif + +#include "joystick/SDL_joystick_c.h" // For SDL_GetGamepadTypeFromVIDPID() + + +// Common utility functions that aren't in the public API + +int SDL_powerof2(int x) +{ + int value; + + if (x <= 0) { + // Return some sane value - we shouldn't hit this in our use cases + return 1; + } + + // This trick works for 32-bit values + { + SDL_COMPILE_TIME_ASSERT(SDL_powerof2, sizeof(x) == sizeof(Uint32)); + } + value = x; + value -= 1; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + value += 1; + + return value; +} + +Uint32 SDL_CalculateGCD(Uint32 a, Uint32 b) +{ + if (b == 0) { + return a; + } + return SDL_CalculateGCD(b, (a % b)); +} + +// Algorithm adapted with thanks from John Cook's blog post: +// http://www.johndcook.com/blog/2010/10/20/best-rational-approximation +void SDL_CalculateFraction(float x, int *numerator, int *denominator) +{ + const int N = 1000; + int a = 0, b = 1; + int c = 1, d = 0; + + while (b <= N && d <= N) { + float mediant = (float)(a + c) / (b + d); + if (x == mediant) { + if (b + d <= N) { + *numerator = a + c; + *denominator = b + d; + } else if (d > b) { + *numerator = c; + *denominator = d; + } else { + *numerator = a; + *denominator = b; + } + return; + } else if (x > mediant) { + a = a + c; + b = b + d; + } else { + c = a + c; + d = b + d; + } + } + if (b > N) { + *numerator = c; + *denominator = d; + } else { + *numerator = a; + *denominator = b; + } +} + +bool SDL_startswith(const char *string, const char *prefix) +{ + if (SDL_strncmp(string, prefix, SDL_strlen(prefix)) == 0) { + return true; + } + return false; +} + +bool SDL_endswith(const char *string, const char *suffix) +{ + size_t string_length = string ? SDL_strlen(string) : 0; + size_t suffix_length = suffix ? SDL_strlen(suffix) : 0; + + if (suffix_length > 0 && suffix_length <= string_length) { + if (SDL_memcmp(string + string_length - suffix_length, suffix, suffix_length) == 0) { + return true; + } + } + return false; +} + +SDL_COMPILE_TIME_ASSERT(sizeof_object_id, sizeof(int) == sizeof(Uint32)); + +Uint32 SDL_GetNextObjectID(void) +{ + static SDL_AtomicInt last_id; + + Uint32 id = (Uint32)SDL_AtomicIncRef(&last_id) + 1; + if (id == 0) { + id = (Uint32)SDL_AtomicIncRef(&last_id) + 1; + } + return id; +} + +static SDL_InitState SDL_objects_init; +static SDL_HashTable *SDL_objects; + +static Uint32 SDLCALL SDL_HashObject(void *unused, const void *key) +{ + return (Uint32)(uintptr_t)key; +} + +static bool SDL_KeyMatchObject(void *unused, const void *a, const void *b) +{ + return (a == b); +} + +void SDL_SetObjectValid(void *object, SDL_ObjectType type, bool valid) +{ + SDL_assert(object != NULL); + + if (SDL_ShouldInit(&SDL_objects_init)) { + SDL_objects = SDL_CreateHashTable(0, true, SDL_HashObject, SDL_KeyMatchObject, NULL, NULL); + const bool initialized = (SDL_objects != NULL); + SDL_SetInitialized(&SDL_objects_init, initialized); + if (!initialized) { + return; + } + } + + if (valid) { + SDL_InsertIntoHashTable(SDL_objects, object, (void *)(uintptr_t)type, true); + } else { + SDL_RemoveFromHashTable(SDL_objects, object); + } +} + +bool SDL_ObjectValid(void *object, SDL_ObjectType type) +{ + if (!object) { + return false; + } + + const void *object_type; + if (!SDL_FindInHashTable(SDL_objects, object, &object_type)) { + return false; + } + + return (((SDL_ObjectType)(uintptr_t)object_type) == type); +} + +typedef struct GetOneObjectData +{ + const SDL_ObjectType type; + void **objects; + const int count; + int num_objects; +} GetOneObjectData; + +static bool SDLCALL GetOneObject(void *userdata, const SDL_HashTable *table, const void *object, const void *object_type) +{ + GetOneObjectData *data = (GetOneObjectData *) userdata; + if ((SDL_ObjectType)(uintptr_t)object_type == data->type) { + if (data->num_objects < data->count) { + data->objects[data->num_objects] = (void *)object; + } + ++data->num_objects; + } + return true; // keep iterating. +} + + +int SDL_GetObjects(SDL_ObjectType type, void **objects, int count) +{ + GetOneObjectData data = { type, objects, count, 0 }; + SDL_IterateHashTable(SDL_objects, GetOneObject, &data); + return data.num_objects; +} + +static bool SDLCALL LogOneLeakedObject(void *userdata, const SDL_HashTable *table, const void *object, const void *object_type) +{ + const char *type = "unknown object"; + switch ((SDL_ObjectType)(uintptr_t)object_type) { + #define SDLOBJTYPECASE(typ, name) case SDL_OBJECT_TYPE_##typ: type = name; break + SDLOBJTYPECASE(WINDOW, "SDL_Window"); + SDLOBJTYPECASE(RENDERER, "SDL_Renderer"); + SDLOBJTYPECASE(TEXTURE, "SDL_Texture"); + SDLOBJTYPECASE(JOYSTICK, "SDL_Joystick"); + SDLOBJTYPECASE(GAMEPAD, "SDL_Gamepad"); + SDLOBJTYPECASE(HAPTIC, "SDL_Haptic"); + SDLOBJTYPECASE(SENSOR, "SDL_Sensor"); + SDLOBJTYPECASE(HIDAPI_DEVICE, "hidapi device"); + SDLOBJTYPECASE(HIDAPI_JOYSTICK, "hidapi joystick"); + SDLOBJTYPECASE(THREAD, "thread"); + SDLOBJTYPECASE(TRAY, "SDL_Tray"); + #undef SDLOBJTYPECASE + default: break; + } + SDL_Log("Leaked %s (%p)", type, object); + return true; // keep iterating. +} + +void SDL_SetObjectsInvalid(void) +{ + if (SDL_ShouldQuit(&SDL_objects_init)) { + // Log any leaked objects + SDL_IterateHashTable(SDL_objects, LogOneLeakedObject, NULL); + SDL_assert(SDL_HashTableEmpty(SDL_objects)); + SDL_DestroyHashTable(SDL_objects); + SDL_objects = NULL; + SDL_SetInitialized(&SDL_objects_init, false); + } +} + +static int SDL_URIDecode(const char *src, char *dst, int len) +{ + int ri, wi, di; + char decode = '\0'; + if (!src || !dst || len < 0) { + return -1; + } + if (len == 0) { + len = (int)SDL_strlen(src); + } + for (ri = 0, wi = 0, di = 0; ri < len && wi < len; ri += 1) { + if (di == 0) { + // start decoding + if (src[ri] == '%') { + decode = '\0'; + di += 1; + continue; + } + // normal write + dst[wi] = src[ri]; + wi += 1; + } else if (di == 1 || di == 2) { + char off = '\0'; + char isa = src[ri] >= 'a' && src[ri] <= 'f'; + char isA = src[ri] >= 'A' && src[ri] <= 'F'; + char isn = src[ri] >= '0' && src[ri] <= '9'; + if (!(isa || isA || isn)) { + // not a hexadecimal + int sri; + for (sri = ri - di; sri <= ri; sri += 1) { + dst[wi] = src[sri]; + wi += 1; + } + di = 0; + continue; + } + // itsy bitsy magicsy + if (isn) { + off = 0 - '0'; + } else if (isa) { + off = 10 - 'a'; + } else if (isA) { + off = 10 - 'A'; + } + decode |= (src[ri] + off) << (2 - di) * 4; + if (di == 2) { + dst[wi] = decode; + wi += 1; + di = 0; + } else { + di += 1; + } + } + } + dst[wi] = '\0'; + return wi; +} + +int SDL_URIToLocal(const char *src, char *dst) +{ + if (SDL_memcmp(src, "file:/", 6) == 0) { + src += 6; // local file? + } else if (SDL_strstr(src, ":/") != NULL) { + return -1; // wrong scheme + } + + bool local = src[0] != '/' || (src[0] != '\0' && src[1] == '/'); + + // Check the hostname, if present. RFC 3986 states that the hostname component of a URI is not case-sensitive. + if (!local && src[0] == '/' && src[2] != '/') { + char *hostname_end = SDL_strchr(src + 1, '/'); + if (hostname_end) { + const size_t src_len = hostname_end - (src + 1); + size_t hostname_len; + +#if defined(HAVE_GETHOSTNAME) && !defined(SDL_PLATFORM_WINDOWS) + char hostname[257]; + if (gethostname(hostname, 255) == 0) { + hostname[256] = '\0'; + hostname_len = SDL_strlen(hostname); + if (hostname_len == src_len && SDL_strncasecmp(src + 1, hostname, src_len) == 0) { + src = hostname_end + 1; + local = true; + } + } +#endif + + if (!local) { + static const char *localhost = "localhost"; + hostname_len = SDL_strlen(localhost); + if (hostname_len == src_len && SDL_strncasecmp(src + 1, localhost, src_len) == 0) { + src = hostname_end + 1; + local = true; + } + } + } + } + + if (local) { + // Convert URI escape sequences to real characters + if (src[0] == '/') { + src++; + } else { + src--; + } + return SDL_URIDecode(src, dst, 0); + } + return -1; +} + +// This is a set of per-thread persistent strings that we can return from the SDL API. +// This is used for short strings that might persist past the lifetime of the object +// they are related to. + +static SDL_TLSID SDL_string_storage; + +static void SDL_FreePersistentStrings( void *value ) +{ + SDL_HashTable *strings = (SDL_HashTable *)value; + SDL_DestroyHashTable(strings); +} + +const char *SDL_GetPersistentString(const char *string) +{ + if (!string) { + return NULL; + } + if (!*string) { + return ""; + } + + SDL_HashTable *strings = (SDL_HashTable *)SDL_GetTLS(&SDL_string_storage); + if (!strings) { + strings = SDL_CreateHashTable(0, false, SDL_HashString, SDL_KeyMatchString, SDL_DestroyHashValue, NULL); + if (!strings) { + return NULL; + } + + SDL_SetTLS(&SDL_string_storage, strings, SDL_FreePersistentStrings); + } + + const char *result; + if (!SDL_FindInHashTable(strings, string, (const void **)&result)) { + char *new_string = SDL_strdup(string); + if (!new_string) { + return NULL; + } + + // If the hash table insert fails, at least we can return the string we allocated + SDL_InsertIntoHashTable(strings, new_string, new_string, false); + result = new_string; + } + return result; +} + +static int PrefixMatch(const char *a, const char *b) +{ + int matchlen = 0; + // Fixes the "HORI HORl Taiko No Tatsujin Drum Controller" + if (SDL_strncmp(a, "HORI ", 5) == 0 && SDL_strncmp(b, "HORl ", 5) == 0) { + return 5; + } + while (*a && *b) { + if (SDL_tolower((unsigned char)*a++) == SDL_tolower((unsigned char)*b++)) { + ++matchlen; + } else { + break; + } + } + return matchlen; +} + +char *SDL_CreateDeviceName(Uint16 vendor, Uint16 product, const char *vendor_name, const char *product_name, const char *default_name) +{ + static struct + { + const char *prefix; + const char *replacement; + } replacements[] = { + { "8BitDo Tech Ltd", "8BitDo" }, + { "ASTRO Gaming", "ASTRO" }, + { "Bensussen Deutsch & Associates,Inc.(BDA)", "BDA" }, + { "Guangzhou Chicken Run Network Technology Co., Ltd.", "GameSir" }, + { "HORI CO.,LTD.", "HORI" }, + { "HORI CO.,LTD", "HORI" }, + { "Mad Catz Inc.", "Mad Catz" }, + { "Nintendo Co., Ltd.", "Nintendo" }, + { "NVIDIA Corporation ", "" }, + { "Performance Designed Products", "PDP" }, + { "QANBA USA, LLC", "Qanba" }, + { "QANBA USA,LLC", "Qanba" }, + { "Unknown ", "" }, + }; + char *name = NULL; + size_t i, len; + + if (!vendor_name) { + vendor_name = ""; + } + if (!product_name) { + product_name = ""; + } + + while (*vendor_name == ' ') { + ++vendor_name; + } + while (*product_name == ' ') { + ++product_name; + } + + if (*vendor_name && *product_name) { + len = (SDL_strlen(vendor_name) + 1 + SDL_strlen(product_name) + 1); + name = (char *)SDL_malloc(len); + if (name) { + (void)SDL_snprintf(name, len, "%s %s", vendor_name, product_name); + } + } else if (*product_name) { + name = SDL_strdup(product_name); + } else if (vendor || product) { + // Couldn't find a controller name, try to give it one based on device type + switch (SDL_GetGamepadTypeFromVIDPID(vendor, product, NULL, true)) { + case SDL_GAMEPAD_TYPE_XBOX360: + name = SDL_strdup("Xbox 360 Controller"); + break; + case SDL_GAMEPAD_TYPE_XBOXONE: + name = SDL_strdup("Xbox One Controller"); + break; + case SDL_GAMEPAD_TYPE_PS3: + name = SDL_strdup("PS3 Controller"); + break; + case SDL_GAMEPAD_TYPE_PS4: + name = SDL_strdup("PS4 Controller"); + break; + case SDL_GAMEPAD_TYPE_PS5: + name = SDL_strdup("DualSense Wireless Controller"); + break; + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO: + name = SDL_strdup("Nintendo Switch Pro Controller"); + break; + default: + len = (6 + 1 + 6 + 1); + name = (char *)SDL_malloc(len); + if (name) { + (void)SDL_snprintf(name, len, "0x%.4x/0x%.4x", vendor, product); + } + break; + } + } else if (default_name) { + name = SDL_strdup(default_name); + } + + if (!name) { + return NULL; + } + + // Trim trailing whitespace + for (len = SDL_strlen(name); (len > 0 && name[len - 1] == ' '); --len) { + // continue + } + name[len] = '\0'; + + // Compress duplicate spaces + for (i = 0; i < (len - 1);) { + if (name[i] == ' ' && name[i + 1] == ' ') { + SDL_memmove(&name[i], &name[i + 1], (len - i)); + --len; + } else { + ++i; + } + } + + // Perform any manufacturer replacements + for (i = 0; i < SDL_arraysize(replacements); ++i) { + size_t prefixlen = SDL_strlen(replacements[i].prefix); + if (SDL_strncasecmp(name, replacements[i].prefix, prefixlen) == 0) { + size_t replacementlen = SDL_strlen(replacements[i].replacement); + if (replacementlen <= prefixlen) { + SDL_memcpy(name, replacements[i].replacement, replacementlen); + SDL_memmove(name + replacementlen, name + prefixlen, (len - prefixlen) + 1); + len -= (prefixlen - replacementlen); + } else { + // FIXME: Need to handle the expand case by reallocating the string + } + break; + } + } + + /* Remove duplicate manufacturer or product in the name + * e.g. Razer Razer Raiju Tournament Edition Wired + */ + for (i = 1; i < (len - 1); ++i) { + int matchlen = PrefixMatch(name, &name[i]); + while (matchlen > 0) { + if (name[matchlen] == ' ' || name[matchlen] == '-') { + SDL_memmove(name, name + matchlen + 1, len - matchlen); + break; + } + --matchlen; + } + if (matchlen > 0) { + // We matched the manufacturer's name and removed it + break; + } + } + + return name; +} diff --git a/thirdparty/sdl/SDL_utils_c.h b/thirdparty/sdl/SDL_utils_c.h new file mode 100644 index 00000000000..5e0e8f519eb --- /dev/null +++ b/thirdparty/sdl/SDL_utils_c.h @@ -0,0 +1,78 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +// This is included in SDL_internal.h +//#include "SDL_internal.h" + +#ifndef SDL_utils_h_ +#define SDL_utils_h_ + +// Common utility functions that aren't in the public API + +// Return the smallest power of 2 greater than or equal to 'x' +extern int SDL_powerof2(int x); + +extern Uint32 SDL_CalculateGCD(Uint32 a, Uint32 b); +extern void SDL_CalculateFraction(float x, int *numerator, int *denominator); + +extern bool SDL_startswith(const char *string, const char *prefix); +extern bool SDL_endswith(const char *string, const char *suffix); + +/** Convert URI to a local filename, stripping the "file://" + * preamble and hostname if present, and writes the result + * to the dst buffer. Since URI-encoded characters take + * three times the space of normal characters, src and dst + * can safely point to the same buffer for in situ conversion. + * + * Returns the number of decoded bytes that wound up in + * the destination buffer, excluding the terminating NULL byte. + * + * On error, -1 is returned. + */ +extern int SDL_URIToLocal(const char *src, char *dst); + +typedef enum +{ + SDL_OBJECT_TYPE_UNKNOWN, + SDL_OBJECT_TYPE_WINDOW, + SDL_OBJECT_TYPE_RENDERER, + SDL_OBJECT_TYPE_TEXTURE, + SDL_OBJECT_TYPE_JOYSTICK, + SDL_OBJECT_TYPE_GAMEPAD, + SDL_OBJECT_TYPE_HAPTIC, + SDL_OBJECT_TYPE_SENSOR, + SDL_OBJECT_TYPE_HIDAPI_DEVICE, + SDL_OBJECT_TYPE_HIDAPI_JOYSTICK, + SDL_OBJECT_TYPE_THREAD, + SDL_OBJECT_TYPE_TRAY, + +} SDL_ObjectType; + +extern Uint32 SDL_GetNextObjectID(void); +extern void SDL_SetObjectValid(void *object, SDL_ObjectType type, bool valid); +extern bool SDL_ObjectValid(void *object, SDL_ObjectType type); +extern int SDL_GetObjects(SDL_ObjectType type, void **objects, int count); +extern void SDL_SetObjectsInvalid(void); + +extern const char *SDL_GetPersistentString(const char *string); + +extern char *SDL_CreateDeviceName(Uint16 vendor, Uint16 product, const char *vendor_name, const char *product_name, const char *default_name); + +#endif // SDL_utils_h_ diff --git a/thirdparty/sdl/atomic/SDL_atomic.c b/thirdparty/sdl/atomic/SDL_atomic.c new file mode 100644 index 00000000000..5e7774da853 --- /dev/null +++ b/thirdparty/sdl/atomic/SDL_atomic.c @@ -0,0 +1,382 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(_MSC_VER) && (_MSC_VER >= 1900) +#include +#define HAVE_MSC_ATOMICS 1 +#endif + +#ifdef SDL_PLATFORM_MACOS // !!! FIXME: should we favor gcc atomics? +#include +#endif + +#if !defined(HAVE_GCC_ATOMICS) && defined(SDL_PLATFORM_SOLARIS) +#include +#endif + +// The __atomic_load_n() intrinsic showed up in different times for different compilers. +#ifdef __clang__ +#if __has_builtin(__atomic_load_n) || defined(HAVE_GCC_ATOMICS) +/* !!! FIXME: this advertises as available in the NDK but uses an external symbol we don't have. + It might be in a later NDK or we might need an extra library? --ryan. */ +#ifndef SDL_PLATFORM_ANDROID +#define HAVE_ATOMIC_LOAD_N 1 +#endif +#endif +#elif defined(__GNUC__) +#if (__GNUC__ >= 5) +#define HAVE_ATOMIC_LOAD_N 1 +#endif +#endif + +/* *INDENT-OFF* */ // clang-format off +#if defined(__WATCOMC__) && defined(__386__) +SDL_COMPILE_TIME_ASSERT(intsize, 4==sizeof(int)); +#define HAVE_WATCOM_ATOMICS +extern __inline int _SDL_xchg_watcom(volatile int *a, int v); +#pragma aux _SDL_xchg_watcom = \ + "lock xchg [ecx], eax" \ + parm [ecx] [eax] \ + value [eax] \ + modify exact [eax]; + +extern __inline unsigned char _SDL_cmpxchg_watcom(volatile int *a, int newval, int oldval); +#pragma aux _SDL_cmpxchg_watcom = \ + "lock cmpxchg [edx], ecx" \ + "setz al" \ + parm [edx] [ecx] [eax] \ + value [al] \ + modify exact [eax]; + +extern __inline int _SDL_xadd_watcom(volatile int *a, int v); +#pragma aux _SDL_xadd_watcom = \ + "lock xadd [ecx], eax" \ + parm [ecx] [eax] \ + value [eax] \ + modify exact [eax]; + +#endif // __WATCOMC__ && __386__ +/* *INDENT-ON* */ // clang-format on + +/* + If any of the operations are not provided then we must emulate some + of them. That means we need a nice implementation of spin locks + that avoids the "one big lock" problem. We use a vector of spin + locks and pick which one to use based on the address of the operand + of the function. + + To generate the index of the lock we first shift by 3 bits to get + rid on the zero bits that result from 32 and 64 bit alignment of + data. We then mask off all but 5 bits and use those 5 bits as an + index into the table. + + Picking the lock this way insures that accesses to the same data at + the same time will go to the same lock. OTOH, accesses to different + data have only a 1/32 chance of hitting the same lock. That should + pretty much eliminate the chances of several atomic operations on + different data from waiting on the same "big lock". If it isn't + then the table of locks can be expanded to a new size so long as + the new size is a power of two. + + Contributed by Bob Pendleton, bob@pendleton.com +*/ + +#if !defined(HAVE_MSC_ATOMICS) && !defined(HAVE_GCC_ATOMICS) && !defined(SDL_PLATFORM_MACOS) && !defined(SDL_PLATFORM_SOLARIS) && !defined(HAVE_WATCOM_ATOMICS) +#define EMULATE_CAS 1 +#endif + +#ifdef EMULATE_CAS +static SDL_SpinLock locks[32]; + +static SDL_INLINE void enterLock(void *a) +{ + uintptr_t index = ((((uintptr_t)a) >> 3) & 0x1f); + + SDL_LockSpinlock(&locks[index]); +} + +static SDL_INLINE void leaveLock(void *a) +{ + uintptr_t index = ((((uintptr_t)a) >> 3) & 0x1f); + + SDL_UnlockSpinlock(&locks[index]); +} +#endif + +bool SDL_CompareAndSwapAtomicInt(SDL_AtomicInt *a, int oldval, int newval) +{ +#ifdef HAVE_MSC_ATOMICS + SDL_COMPILE_TIME_ASSERT(atomic_cas, sizeof(long) == sizeof(a->value)); + return _InterlockedCompareExchange((long *)&a->value, (long)newval, (long)oldval) == (long)oldval; +#elif defined(HAVE_WATCOM_ATOMICS) + return _SDL_cmpxchg_watcom((volatile int *)&a->value, newval, oldval); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_bool_compare_and_swap(&a->value, oldval, newval); +#elif defined(SDL_PLATFORM_MACOS) // this is deprecated in 10.12 sdk; favor gcc atomics. + return OSAtomicCompareAndSwap32Barrier(oldval, newval, &a->value); +#elif defined(SDL_PLATFORM_SOLARIS) + SDL_COMPILE_TIME_ASSERT(atomic_cas, sizeof(uint_t) == sizeof(a->value)); + return ((int)atomic_cas_uint((volatile uint_t *)&a->value, (uint_t)oldval, (uint_t)newval) == oldval); +#elif defined(EMULATE_CAS) + bool result = false; + + enterLock(a); + if (a->value == oldval) { + a->value = newval; + result = true; + } + leaveLock(a); + + return result; +#else +#error Please define your platform. +#endif +} + +bool SDL_CompareAndSwapAtomicU32(SDL_AtomicU32 *a, Uint32 oldval, Uint32 newval) +{ +#ifdef HAVE_MSC_ATOMICS + SDL_COMPILE_TIME_ASSERT(atomic_cas, sizeof(long) == sizeof(a->value)); + return _InterlockedCompareExchange((long *)&a->value, (long)newval, (long)oldval) == (long)oldval; +#elif defined(HAVE_WATCOM_ATOMICS) + SDL_COMPILE_TIME_ASSERT(atomic_cas, sizeof(int) == sizeof(a->value)); + return _SDL_cmpxchg_watcom((volatile int *)&a->value, (int)newval, (int)oldval); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_bool_compare_and_swap(&a->value, oldval, newval); +#elif defined(SDL_PLATFORM_MACOS) // this is deprecated in 10.12 sdk; favor gcc atomics. + return OSAtomicCompareAndSwap32Barrier((int32_t)oldval, (int32_t)newval, (int32_t*)&a->value); +#elif defined(SDL_PLATFORM_SOLARIS) + SDL_COMPILE_TIME_ASSERT(atomic_cas, sizeof(uint_t) == sizeof(a->value)); + return ((Uint32)atomic_cas_uint((volatile uint_t *)&a->value, (uint_t)oldval, (uint_t)newval) == oldval); +#elif defined(EMULATE_CAS) + bool result = false; + + enterLock(a); + if (a->value == oldval) { + a->value = newval; + result = true; + } + leaveLock(a); + + return result; +#else +#error Please define your platform. +#endif +} + +bool SDL_CompareAndSwapAtomicPointer(void **a, void *oldval, void *newval) +{ +#ifdef HAVE_MSC_ATOMICS + return _InterlockedCompareExchangePointer(a, newval, oldval) == oldval; +#elif defined(HAVE_WATCOM_ATOMICS) + return _SDL_cmpxchg_watcom((int *)a, (long)newval, (long)oldval); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_bool_compare_and_swap(a, oldval, newval); +#elif defined(SDL_PLATFORM_MACOS) && defined(__LP64__) // this is deprecated in 10.12 sdk; favor gcc atomics. + return OSAtomicCompareAndSwap64Barrier((int64_t)oldval, (int64_t)newval, (int64_t *)a); +#elif defined(SDL_PLATFORM_MACOS) && !defined(__LP64__) // this is deprecated in 10.12 sdk; favor gcc atomics. + return OSAtomicCompareAndSwap32Barrier((int32_t)oldval, (int32_t)newval, (int32_t *)a); +#elif defined(SDL_PLATFORM_SOLARIS) + return (atomic_cas_ptr(a, oldval, newval) == oldval); +#elif defined(EMULATE_CAS) + bool result = false; + + enterLock(a); + if (*a == oldval) { + *a = newval; + result = true; + } + leaveLock(a); + + return result; +#else +#error Please define your platform. +#endif +} + +int SDL_SetAtomicInt(SDL_AtomicInt *a, int v) +{ +#ifdef HAVE_MSC_ATOMICS + SDL_COMPILE_TIME_ASSERT(atomic_set, sizeof(long) == sizeof(a->value)); + return _InterlockedExchange((long *)&a->value, v); +#elif defined(HAVE_WATCOM_ATOMICS) + return _SDL_xchg_watcom(&a->value, v); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_lock_test_and_set(&a->value, v); +#elif defined(SDL_PLATFORM_SOLARIS) + SDL_COMPILE_TIME_ASSERT(atomic_set, sizeof(uint_t) == sizeof(a->value)); + return (int)atomic_swap_uint((volatile uint_t *)&a->value, v); +#else + int value; + do { + value = a->value; + } while (!SDL_CompareAndSwapAtomicInt(a, value, v)); + return value; +#endif +} + +Uint32 SDL_SetAtomicU32(SDL_AtomicU32 *a, Uint32 v) +{ +#ifdef HAVE_MSC_ATOMICS + SDL_COMPILE_TIME_ASSERT(atomic_set, sizeof(long) == sizeof(a->value)); + return _InterlockedExchange((long *)&a->value, v); +#elif defined(HAVE_WATCOM_ATOMICS) + return _SDL_xchg_watcom(&a->value, v); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_lock_test_and_set(&a->value, v); +#elif defined(SDL_PLATFORM_SOLARIS) + SDL_COMPILE_TIME_ASSERT(atomic_set, sizeof(uint_t) == sizeof(a->value)); + return (Uint32)atomic_swap_uint((volatile uint_t *)&a->value, v); +#else + Uint32 value; + do { + value = a->value; + } while (!SDL_CompareAndSwapAtomicU32(a, value, v)); + return value; +#endif +} + +void *SDL_SetAtomicPointer(void **a, void *v) +{ +#ifdef HAVE_MSC_ATOMICS + return _InterlockedExchangePointer(a, v); +#elif defined(HAVE_WATCOM_ATOMICS) + return (void *)_SDL_xchg_watcom((int *)a, (long)v); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_lock_test_and_set(a, v); +#elif defined(SDL_PLATFORM_SOLARIS) + return atomic_swap_ptr(a, v); +#else + void *value; + do { + value = *a; + } while (!SDL_CompareAndSwapAtomicPointer(a, value, v)); + return value; +#endif +} + +int SDL_AddAtomicInt(SDL_AtomicInt *a, int v) +{ +#ifdef HAVE_MSC_ATOMICS + SDL_COMPILE_TIME_ASSERT(atomic_add, sizeof(long) == sizeof(a->value)); + return _InterlockedExchangeAdd((long *)&a->value, v); +#elif defined(HAVE_WATCOM_ATOMICS) + SDL_COMPILE_TIME_ASSERT(atomic_add, sizeof(int) == sizeof(a->value)); + return _SDL_xadd_watcom((volatile int *)&a->value, v); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_fetch_and_add(&a->value, v); +#elif defined(SDL_PLATFORM_SOLARIS) + int pv = a->value; + membar_consumer(); + atomic_add_int((volatile uint_t *)&a->value, v); + return pv; +#else + int value; + do { + value = a->value; + } while (!SDL_CompareAndSwapAtomicInt(a, value, (value + v))); + return value; +#endif +} + +int SDL_GetAtomicInt(SDL_AtomicInt *a) +{ +#ifdef HAVE_ATOMIC_LOAD_N + return __atomic_load_n(&a->value, __ATOMIC_SEQ_CST); +#elif defined(HAVE_MSC_ATOMICS) + SDL_COMPILE_TIME_ASSERT(atomic_get, sizeof(long) == sizeof(a->value)); + return _InterlockedOr((long *)&a->value, 0); +#elif defined(HAVE_WATCOM_ATOMICS) + return _SDL_xadd_watcom(&a->value, 0); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_or_and_fetch(&a->value, 0); +#elif defined(SDL_PLATFORM_MACOS) // this is deprecated in 10.12 sdk; favor gcc atomics. + return sizeof(a->value) == sizeof(uint32_t) ? OSAtomicOr32Barrier(0, (volatile uint32_t *)&a->value) : OSAtomicAdd64Barrier(0, (volatile int64_t *)&a->value); +#elif defined(SDL_PLATFORM_SOLARIS) + return atomic_or_uint_nv((volatile uint_t *)&a->value, 0); +#else + int value; + do { + value = a->value; + } while (!SDL_CompareAndSwapAtomicInt(a, value, value)); + return value; +#endif +} + +Uint32 SDL_GetAtomicU32(SDL_AtomicU32 *a) +{ +#ifdef HAVE_ATOMIC_LOAD_N + return __atomic_load_n(&a->value, __ATOMIC_SEQ_CST); +#elif defined(HAVE_MSC_ATOMICS) + SDL_COMPILE_TIME_ASSERT(atomic_get, sizeof(long) == sizeof(a->value)); + return (Uint32)_InterlockedOr((long *)&a->value, 0); +#elif defined(HAVE_WATCOM_ATOMICS) + SDL_COMPILE_TIME_ASSERT(atomic_get, sizeof(int) == sizeof(a->value)); + return (Uint32)_SDL_xadd_watcom((volatile int *)&a->value, 0); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_or_and_fetch(&a->value, 0); +#elif defined(SDL_PLATFORM_MACOS) // this is deprecated in 10.12 sdk; favor gcc atomics. + return OSAtomicOr32Barrier(0, (volatile uint32_t *)&a->value); +#elif defined(SDL_PLATFORM_SOLARIS) + SDL_COMPILE_TIME_ASSERT(atomic_get, sizeof(uint_t) == sizeof(a->value)); + return (Uint32)atomic_or_uint_nv((volatile uint_t *)&a->value, 0); +#else + Uint32 value; + do { + value = a->value; + } while (!SDL_CompareAndSwapAtomicU32(a, value, value)); + return value; +#endif +} + +void *SDL_GetAtomicPointer(void **a) +{ +#ifdef HAVE_ATOMIC_LOAD_N + return __atomic_load_n(a, __ATOMIC_SEQ_CST); +#elif defined(HAVE_MSC_ATOMICS) + return _InterlockedCompareExchangePointer(a, NULL, NULL); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_val_compare_and_swap(a, (void *)0, (void *)0); +#elif defined(SDL_PLATFORM_SOLARIS) + return atomic_cas_ptr(a, (void *)0, (void *)0); +#else + void *value; + do { + value = *a; + } while (!SDL_CompareAndSwapAtomicPointer(a, value, value)); + return value; +#endif +} + +#ifdef SDL_MEMORY_BARRIER_USES_FUNCTION +#error This file should be built in arm mode so the mcr instruction is available for memory barriers +#endif + +void SDL_MemoryBarrierReleaseFunction(void) +{ + SDL_MemoryBarrierRelease(); +} + +void SDL_MemoryBarrierAcquireFunction(void) +{ + SDL_MemoryBarrierAcquire(); +} diff --git a/thirdparty/sdl/atomic/SDL_spinlock.c b/thirdparty/sdl/atomic/SDL_spinlock.c new file mode 100644 index 00000000000..8e35c8a74b0 --- /dev/null +++ b/thirdparty/sdl/atomic/SDL_spinlock.c @@ -0,0 +1,203 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(SDL_PLATFORM_WINDOWS) +#include "../core/windows/SDL_windows.h" +#endif + +#if !defined(HAVE_GCC_ATOMICS) && defined(SDL_PLATFORM_SOLARIS) +#include +#endif + +#if !defined(HAVE_GCC_ATOMICS) && defined(SDL_PLATFORM_RISCOS) +#include +#endif + +#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) +#include +#endif + +#ifdef PS2 +#include +#endif + +#if !defined(HAVE_GCC_ATOMICS) && defined(SDL_PLATFORM_MACOS) +#include +#endif + +/* *INDENT-OFF* */ // clang-format off +#if defined(__WATCOMC__) && defined(__386__) +SDL_COMPILE_TIME_ASSERT(locksize, 4==sizeof(SDL_SpinLock)); +extern __inline int _SDL_xchg_watcom(volatile int *a, int v); +#pragma aux _SDL_xchg_watcom = \ + "lock xchg [ecx], eax" \ + parm [ecx] [eax] \ + value [eax] \ + modify exact [eax]; +#endif // __WATCOMC__ && __386__ +/* *INDENT-ON* */ // clang-format on + +// This function is where all the magic happens... +bool SDL_TryLockSpinlock(SDL_SpinLock *lock) +{ +#if defined(HAVE_GCC_ATOMICS) || defined(HAVE_GCC_SYNC_LOCK_TEST_AND_SET) + return __sync_lock_test_and_set(lock, 1) == 0; + +#elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) + return _InterlockedExchange_acq(lock, 1) == 0; + +#elif defined(_MSC_VER) + SDL_COMPILE_TIME_ASSERT(locksize, sizeof(*lock) == sizeof(long)); + return InterlockedExchange((long *)lock, 1) == 0; + +#elif defined(__WATCOMC__) && defined(__386__) + return _SDL_xchg_watcom(lock, 1) == 0; + +#elif defined(__GNUC__) && defined(__arm__) && \ + (defined(__ARM_ARCH_3__) || defined(__ARM_ARCH_3M__) || \ + defined(__ARM_ARCH_4__) || defined(__ARM_ARCH_4T__) || \ + defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5TE__) || \ + defined(__ARM_ARCH_5TEJ__)) + int result; + +#ifdef SDL_PLATFORM_RISCOS + if (__cpucap_have_rex()) { + __asm__ __volatile__( + "ldrex %0, [%2]\nteq %0, #0\nstrexeq %0, %1, [%2]" + : "=&r"(result) + : "r"(1), "r"(lock) + : "cc", "memory"); + return result == 0; + } +#endif + + __asm__ __volatile__( + "swp %0, %1, [%2]\n" + : "=&r,&r"(result) + : "r,0"(1), "r,r"(lock) + : "memory"); + return result == 0; + +#elif defined(__GNUC__) && defined(__arm__) + int result; + __asm__ __volatile__( + "ldrex %0, [%2]\nteq %0, #0\nstrexeq %0, %1, [%2]" + : "=&r"(result) + : "r"(1), "r"(lock) + : "cc", "memory"); + return result == 0; + +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) + int result; + __asm__ __volatile__( + "lock ; xchgl %0, (%1)\n" + : "=r"(result) + : "r"(lock), "0"(1) + : "cc", "memory"); + return result == 0; + +#elif defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS) || defined(SDL_PLATFORM_TVOS) + // Maybe used for PowerPC, but the Intel asm or gcc atomics are favored. + return OSAtomicCompareAndSwap32Barrier(0, 1, lock); + +#elif defined(SDL_PLATFORM_SOLARIS) && defined(_LP64) + // Used for Solaris with non-gcc compilers. + return ((int)atomic_cas_64((volatile uint64_t *)lock, 0, 1) == 0); + +#elif defined(SDL_PLATFORM_SOLARIS) && !defined(_LP64) + // Used for Solaris with non-gcc compilers. + return ((int)atomic_cas_32((volatile uint32_t *)lock, 0, 1) == 0); +#elif defined(PS2) + uint32_t oldintr; + bool res = false; + // disable interruption + oldintr = DIntr(); + + if (*lock == 0) { + *lock = 1; + res = true; + } + // enable interruption + if (oldintr) { + EIntr(); + } + return res; +#else + // Terrible terrible damage + static SDL_Mutex *_spinlock_mutex; + + if (!_spinlock_mutex) { + // Race condition on first lock... + _spinlock_mutex = SDL_CreateMutex(); + } + SDL_LockMutex(_spinlock_mutex); + if (*lock == 0) { + *lock = 1; + SDL_UnlockMutex(_spinlock_mutex); + return true; + } else { + SDL_UnlockMutex(_spinlock_mutex); + return false; + } +#endif +} + +void SDL_LockSpinlock(SDL_SpinLock *lock) +{ + int iterations = 0; + // FIXME: Should we have an eventual timeout? + while (!SDL_TryLockSpinlock(lock)) { + if (iterations < 32) { + iterations++; + SDL_CPUPauseInstruction(); + } else { + // !!! FIXME: this doesn't definitely give up the current timeslice, it does different things on various platforms. + SDL_Delay(0); + } + } +} + +void SDL_UnlockSpinlock(SDL_SpinLock *lock) +{ +#if defined(HAVE_GCC_ATOMICS) || defined(HAVE_GCC_SYNC_LOCK_TEST_AND_SET) + __sync_lock_release(lock); + +#elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) + _InterlockedExchange_rel(lock, 0); + +#elif defined(_MSC_VER) + _ReadWriteBarrier(); + *lock = 0; + +#elif defined(__WATCOMC__) && defined(__386__) + SDL_CompilerBarrier(); + *lock = 0; + +#elif defined(SDL_PLATFORM_SOLARIS) + // Used for Solaris when not using gcc. + *lock = 0; + membar_producer(); + +#else + *lock = 0; +#endif +} diff --git a/thirdparty/sdl/core/linux/SDL_dbus.c b/thirdparty/sdl/core/linux/SDL_dbus.c new file mode 100644 index 00000000000..9a2fc1ea531 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_dbus.c @@ -0,0 +1,641 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" +#include "SDL_dbus.h" +#include "../../stdlib/SDL_vacopy.h" + +#ifdef SDL_USE_LIBDBUS +// we never link directly to libdbus. +static const char *dbus_library = "libdbus-1.so.3"; +static SDL_SharedObject *dbus_handle = NULL; +static char *inhibit_handle = NULL; +static unsigned int screensaver_cookie = 0; +static SDL_DBusContext dbus; + +static bool LoadDBUSSyms(void) +{ +#define SDL_DBUS_SYM2_OPTIONAL(TYPE, x, y) \ + dbus.x = (TYPE)SDL_LoadFunction(dbus_handle, #y) + +#define SDL_DBUS_SYM2(TYPE, x, y) \ + if (!(dbus.x = (TYPE)SDL_LoadFunction(dbus_handle, #y))) \ + return false + +#define SDL_DBUS_SYM_OPTIONAL(TYPE, x) \ + SDL_DBUS_SYM2_OPTIONAL(TYPE, x, dbus_##x) + +#define SDL_DBUS_SYM(TYPE, x) \ + SDL_DBUS_SYM2(TYPE, x, dbus_##x) + + SDL_DBUS_SYM(DBusConnection *(*)(DBusBusType, DBusError *), bus_get_private); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, DBusError *), bus_register); + SDL_DBUS_SYM(void (*)(DBusConnection *, const char *, DBusError *), bus_add_match); + SDL_DBUS_SYM(DBusConnection *(*)(const char *, DBusError *), connection_open_private); + SDL_DBUS_SYM(void (*)(DBusConnection *, dbus_bool_t), connection_set_exit_on_disconnect); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *), connection_get_is_connected); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, DBusHandleMessageFunction, void *, DBusFreeFunction), connection_add_filter); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, DBusHandleMessageFunction, void *), connection_remove_filter); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, const char *, const DBusObjectPathVTable *, void *, DBusError *), connection_try_register_object_path); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, DBusMessage *, dbus_uint32_t *), connection_send); + SDL_DBUS_SYM(DBusMessage *(*)(DBusConnection *, DBusMessage *, int, DBusError *), connection_send_with_reply_and_block); + SDL_DBUS_SYM(void (*)(DBusConnection *), connection_close); + SDL_DBUS_SYM(void (*)(DBusConnection *), connection_ref); + SDL_DBUS_SYM(void (*)(DBusConnection *), connection_unref); + SDL_DBUS_SYM(void (*)(DBusConnection *), connection_flush); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, int), connection_read_write); + SDL_DBUS_SYM(DBusDispatchStatus (*)(DBusConnection *), connection_dispatch); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, const char *, const char *), message_is_signal); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, const char *), message_has_path); + SDL_DBUS_SYM(DBusMessage *(*)(const char *, const char *, const char *, const char *), message_new_method_call); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, int, ...), message_append_args); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, int, va_list), message_append_args_valist); + SDL_DBUS_SYM(void (*)(DBusMessage *, DBusMessageIter *), message_iter_init_append); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessageIter *, int, const char *, DBusMessageIter *), message_iter_open_container); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessageIter *, int, const void *), message_iter_append_basic); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessageIter *, DBusMessageIter *), message_iter_close_container); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, DBusError *, int, ...), message_get_args); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, DBusError *, int, va_list), message_get_args_valist); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, DBusMessageIter *), message_iter_init); + SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessageIter *), message_iter_next); + SDL_DBUS_SYM(void (*)(DBusMessageIter *, void *), message_iter_get_basic); + SDL_DBUS_SYM(int (*)(DBusMessageIter *), message_iter_get_arg_type); + SDL_DBUS_SYM(void (*)(DBusMessageIter *, DBusMessageIter *), message_iter_recurse); + SDL_DBUS_SYM(void (*)(DBusMessage *), message_unref); + SDL_DBUS_SYM(dbus_bool_t (*)(void), threads_init_default); + SDL_DBUS_SYM(void (*)(DBusError *), error_init); + SDL_DBUS_SYM(dbus_bool_t (*)(const DBusError *), error_is_set); + SDL_DBUS_SYM(void (*)(DBusError *), error_free); + SDL_DBUS_SYM(char *(*)(void), get_local_machine_id); + SDL_DBUS_SYM_OPTIONAL(char *(*)(DBusError *), try_get_local_machine_id); + SDL_DBUS_SYM(void (*)(void *), free); + SDL_DBUS_SYM(void (*)(char **), free_string_array); + SDL_DBUS_SYM(void (*)(void), shutdown); + +#undef SDL_DBUS_SYM +#undef SDL_DBUS_SYM2 + + return true; +} + +static void UnloadDBUSLibrary(void) +{ + if (dbus_handle) { + SDL_UnloadObject(dbus_handle); + dbus_handle = NULL; + } +} + +static bool LoadDBUSLibrary(void) +{ + bool result = true; + if (!dbus_handle) { + dbus_handle = SDL_LoadObject(dbus_library); + if (!dbus_handle) { + result = false; + // Don't call SDL_SetError(): SDL_LoadObject already did. + } else { + result = LoadDBUSSyms(); + if (!result) { + UnloadDBUSLibrary(); + } + } + } + return result; +} + +static SDL_InitState dbus_init; + +void SDL_DBus_Init(void) +{ + static bool is_dbus_available = true; + + if (!is_dbus_available) { + return; // don't keep trying if this fails. + } + + if (!SDL_ShouldInit(&dbus_init)) { + return; + } + + if (!LoadDBUSLibrary()) { + goto error; + } + + if (!dbus.threads_init_default()) { + goto error; + } + + DBusError err; + dbus.error_init(&err); + // session bus is required + + dbus.session_conn = dbus.bus_get_private(DBUS_BUS_SESSION, &err); + if (dbus.error_is_set(&err)) { + dbus.error_free(&err); + goto error; + } + dbus.connection_set_exit_on_disconnect(dbus.session_conn, 0); + + // system bus is optional + dbus.system_conn = dbus.bus_get_private(DBUS_BUS_SYSTEM, &err); + if (!dbus.error_is_set(&err)) { + dbus.connection_set_exit_on_disconnect(dbus.system_conn, 0); + } + + dbus.error_free(&err); + SDL_SetInitialized(&dbus_init, true); + return; + +error: + is_dbus_available = false; + SDL_SetInitialized(&dbus_init, true); + SDL_DBus_Quit(); +} + +void SDL_DBus_Quit(void) +{ + if (!SDL_ShouldQuit(&dbus_init)) { + return; + } + + if (dbus.system_conn) { + dbus.connection_close(dbus.system_conn); + dbus.connection_unref(dbus.system_conn); + } + if (dbus.session_conn) { + dbus.connection_close(dbus.session_conn); + dbus.connection_unref(dbus.session_conn); + } + + if (SDL_GetHintBoolean(SDL_HINT_SHUTDOWN_DBUS_ON_QUIT, false)) { + if (dbus.shutdown) { + dbus.shutdown(); + } + + UnloadDBUSLibrary(); + } else { + /* Leaving libdbus loaded when skipping dbus_shutdown() avoids + * spurious leak warnings from LeakSanitizer on internal D-Bus + * allocations that would be freed by dbus_shutdown(). */ + dbus_handle = NULL; + } + + SDL_zero(dbus); + if (inhibit_handle) { + SDL_free(inhibit_handle); + inhibit_handle = NULL; + } + + SDL_SetInitialized(&dbus_init, false); +} + +SDL_DBusContext *SDL_DBus_GetContext(void) +{ + if (!dbus_handle || !dbus.session_conn) { + SDL_DBus_Init(); + } + + return (dbus_handle && dbus.session_conn) ? &dbus : NULL; +} + +static bool SDL_DBus_CallMethodInternal(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, va_list ap) +{ + bool result = false; + + if (conn) { + DBusMessage *msg = dbus.message_new_method_call(node, path, interface, method); + if (msg) { + int firstarg; + va_list ap_reply; + va_copy(ap_reply, ap); // copy the arg list so we don't compete with D-Bus for it + firstarg = va_arg(ap, int); + if ((firstarg == DBUS_TYPE_INVALID) || dbus.message_append_args_valist(msg, firstarg, ap)) { + DBusMessage *reply = dbus.connection_send_with_reply_and_block(conn, msg, 300, NULL); + if (reply) { + // skip any input args, get to output args. + while ((firstarg = va_arg(ap_reply, int)) != DBUS_TYPE_INVALID) { + // we assume D-Bus already validated all this. + { + void *dumpptr = va_arg(ap_reply, void *); + (void)dumpptr; + } + if (firstarg == DBUS_TYPE_ARRAY) { + { + const int dumpint = va_arg(ap_reply, int); + (void)dumpint; + } + } + } + firstarg = va_arg(ap_reply, int); + if ((firstarg == DBUS_TYPE_INVALID) || dbus.message_get_args_valist(reply, NULL, firstarg, ap_reply)) { + result = true; + } + dbus.message_unref(reply); + } + } + va_end(ap_reply); + dbus.message_unref(msg); + } + } + + return result; +} + +bool SDL_DBus_CallMethodOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, ...) +{ + bool result; + va_list ap; + va_start(ap, method); + result = SDL_DBus_CallMethodInternal(conn, node, path, interface, method, ap); + va_end(ap); + return result; +} + +bool SDL_DBus_CallMethod(const char *node, const char *path, const char *interface, const char *method, ...) +{ + bool result; + va_list ap; + va_start(ap, method); + result = SDL_DBus_CallMethodInternal(dbus.session_conn, node, path, interface, method, ap); + va_end(ap); + return result; +} + +static bool SDL_DBus_CallVoidMethodInternal(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, va_list ap) +{ + bool result = false; + + if (conn) { + DBusMessage *msg = dbus.message_new_method_call(node, path, interface, method); + if (msg) { + int firstarg = va_arg(ap, int); + if ((firstarg == DBUS_TYPE_INVALID) || dbus.message_append_args_valist(msg, firstarg, ap)) { + if (dbus.connection_send(conn, msg, NULL)) { + dbus.connection_flush(conn); + result = true; + } + } + + dbus.message_unref(msg); + } + } + + return result; +} + +static bool SDL_DBus_CallWithBasicReply(DBusConnection *conn, DBusMessage *msg, const int expectedtype, void *result) +{ + bool retval = false; + + DBusMessage *reply = dbus.connection_send_with_reply_and_block(conn, msg, 300, NULL); + if (reply) { + DBusMessageIter iter, actual_iter; + dbus.message_iter_init(reply, &iter); + if (dbus.message_iter_get_arg_type(&iter) == DBUS_TYPE_VARIANT) { + dbus.message_iter_recurse(&iter, &actual_iter); + } else { + actual_iter = iter; + } + + if (dbus.message_iter_get_arg_type(&actual_iter) == expectedtype) { + dbus.message_iter_get_basic(&actual_iter, result); + retval = true; + } + + dbus.message_unref(reply); + } + + return retval; +} + +bool SDL_DBus_CallVoidMethodOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, ...) +{ + bool result; + va_list ap; + va_start(ap, method); + result = SDL_DBus_CallVoidMethodInternal(conn, node, path, interface, method, ap); + va_end(ap); + return result; +} + +bool SDL_DBus_CallVoidMethod(const char *node, const char *path, const char *interface, const char *method, ...) +{ + bool result; + va_list ap; + va_start(ap, method); + result = SDL_DBus_CallVoidMethodInternal(dbus.session_conn, node, path, interface, method, ap); + va_end(ap); + return result; +} + +bool SDL_DBus_QueryPropertyOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *property, int expectedtype, void *result) +{ + bool retval = false; + + if (conn) { + DBusMessage *msg = dbus.message_new_method_call(node, path, "org.freedesktop.DBus.Properties", "Get"); + if (msg) { + if (dbus.message_append_args(msg, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID)) { + retval = SDL_DBus_CallWithBasicReply(conn, msg, expectedtype, result); + } + dbus.message_unref(msg); + } + } + + return retval; +} + +bool SDL_DBus_QueryProperty(const char *node, const char *path, const char *interface, const char *property, int expectedtype, void *result) +{ + return SDL_DBus_QueryPropertyOnConnection(dbus.session_conn, node, path, interface, property, expectedtype, result); +} + +void SDL_DBus_ScreensaverTickle(void) +{ + if (screensaver_cookie == 0 && !inhibit_handle) { // no need to tickle if we're inhibiting. + // org.gnome.ScreenSaver is the legacy interface, but it'll either do nothing or just be a second harmless tickle on newer systems, so we leave it for now. + SDL_DBus_CallVoidMethod("org.gnome.ScreenSaver", "/org/gnome/ScreenSaver", "org.gnome.ScreenSaver", "SimulateUserActivity", DBUS_TYPE_INVALID); + SDL_DBus_CallVoidMethod("org.freedesktop.ScreenSaver", "/org/freedesktop/ScreenSaver", "org.freedesktop.ScreenSaver", "SimulateUserActivity", DBUS_TYPE_INVALID); + } +} + +static bool SDL_DBus_AppendDictWithKeysAndValues(DBusMessageIter *iterInit, const char **keys, const char **values, int count) +{ + DBusMessageIter iterDict; + + if (!dbus.message_iter_open_container(iterInit, DBUS_TYPE_ARRAY, "{sv}", &iterDict)) { + goto failed; + } + + for (int i = 0; i < count; i++) { + DBusMessageIter iterEntry, iterValue; + const char *key = keys[i]; + const char *value = values[i]; + + if (!dbus.message_iter_open_container(&iterDict, DBUS_TYPE_DICT_ENTRY, NULL, &iterEntry)) { + goto failed; + } + + if (!dbus.message_iter_append_basic(&iterEntry, DBUS_TYPE_STRING, &key)) { + goto failed; + } + + if (!dbus.message_iter_open_container(&iterEntry, DBUS_TYPE_VARIANT, DBUS_TYPE_STRING_AS_STRING, &iterValue)) { + goto failed; + } + + if (!dbus.message_iter_append_basic(&iterValue, DBUS_TYPE_STRING, &value)) { + goto failed; + } + + if (!dbus.message_iter_close_container(&iterEntry, &iterValue) || !dbus.message_iter_close_container(&iterDict, &iterEntry)) { + goto failed; + } + } + + if (!dbus.message_iter_close_container(iterInit, &iterDict)) { + goto failed; + } + + return true; + +failed: + /* message_iter_abandon_container_if_open() and message_iter_abandon_container() might be + * missing if libdbus is too old. Instead, we just return without cleaning up any eventual + * open container */ + return false; +} + +static bool SDL_DBus_AppendDictWithKeyValue(DBusMessageIter *iterInit, const char *key, const char *value) +{ + const char *keys[1]; + const char *values[1]; + + keys[0] = key; + values[0] = value; + return SDL_DBus_AppendDictWithKeysAndValues(iterInit, keys, values, 1); +} + +bool SDL_DBus_ScreensaverInhibit(bool inhibit) +{ + const char *default_inhibit_reason = "Playing a game"; + + if ((inhibit && (screensaver_cookie != 0 || inhibit_handle)) || (!inhibit && (screensaver_cookie == 0 && !inhibit_handle))) { + return true; + } + + if (!dbus.session_conn) { + /* We either lost connection to the session bus or were not able to + * load the D-Bus library at all. */ + return false; + } + + if (SDL_GetSandbox() != SDL_SANDBOX_NONE) { + const char *bus_name = "org.freedesktop.portal.Desktop"; + const char *path = "/org/freedesktop/portal/desktop"; + const char *interface = "org.freedesktop.portal.Inhibit"; + const char *window = ""; // As a future improvement we could gather the X11 XID or Wayland surface identifier + static const unsigned int INHIBIT_IDLE = 8; // Taken from the portal API reference + DBusMessageIter iterInit; + + if (inhibit) { + DBusMessage *msg; + bool result = false; + const char *key = "reason"; + const char *reply = NULL; + const char *reason = SDL_GetHint(SDL_HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME); + if (!reason || !reason[0]) { + reason = default_inhibit_reason; + } + + msg = dbus.message_new_method_call(bus_name, path, interface, "Inhibit"); + if (!msg) { + return false; + } + + if (!dbus.message_append_args(msg, DBUS_TYPE_STRING, &window, DBUS_TYPE_UINT32, &INHIBIT_IDLE, DBUS_TYPE_INVALID)) { + dbus.message_unref(msg); + return false; + } + + dbus.message_iter_init_append(msg, &iterInit); + + // a{sv} + if (!SDL_DBus_AppendDictWithKeyValue(&iterInit, key, reason)) { + dbus.message_unref(msg); + return false; + } + + if (SDL_DBus_CallWithBasicReply(dbus.session_conn, msg, DBUS_TYPE_OBJECT_PATH, &reply)) { + inhibit_handle = SDL_strdup(reply); + result = true; + } + + dbus.message_unref(msg); + return result; + } else { + if (!SDL_DBus_CallVoidMethod(bus_name, inhibit_handle, "org.freedesktop.portal.Request", "Close", DBUS_TYPE_INVALID)) { + return false; + } + SDL_free(inhibit_handle); + inhibit_handle = NULL; + } + } else { + const char *bus_name = "org.freedesktop.ScreenSaver"; + const char *path = "/org/freedesktop/ScreenSaver"; + const char *interface = "org.freedesktop.ScreenSaver"; + + if (inhibit) { + const char *app = SDL_GetAppMetadataProperty(SDL_PROP_APP_METADATA_NAME_STRING); + const char *reason = SDL_GetHint(SDL_HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME); + if (!reason || !reason[0]) { + reason = default_inhibit_reason; + } + + if (!SDL_DBus_CallMethod(bus_name, path, interface, "Inhibit", + DBUS_TYPE_STRING, &app, DBUS_TYPE_STRING, &reason, DBUS_TYPE_INVALID, + DBUS_TYPE_UINT32, &screensaver_cookie, DBUS_TYPE_INVALID)) { + return false; + } + return (screensaver_cookie != 0); + } else { + if (!SDL_DBus_CallVoidMethod(bus_name, path, interface, "UnInhibit", DBUS_TYPE_UINT32, &screensaver_cookie, DBUS_TYPE_INVALID)) { + return false; + } + screensaver_cookie = 0; + } + } + + return true; +} + +void SDL_DBus_PumpEvents(void) +{ + if (dbus.session_conn) { + dbus.connection_read_write(dbus.session_conn, 0); + + while (dbus.connection_dispatch(dbus.session_conn) == DBUS_DISPATCH_DATA_REMAINS) { + // Do nothing, actual work happens in DBus_MessageFilter + SDL_DelayNS(SDL_US_TO_NS(10)); + } + } +} + +/* + * Get the machine ID if possible. Result must be freed with dbus->free(). + */ +char *SDL_DBus_GetLocalMachineId(void) +{ + DBusError err; + char *result; + + dbus.error_init(&err); + + if (dbus.try_get_local_machine_id) { + // Available since dbus 1.12.0, has proper error-handling + result = dbus.try_get_local_machine_id(&err); + } else { + /* Available since time immemorial, but has no error-handling: + * if the machine ID can't be read, many versions of libdbus will + * treat that as a fatal mis-installation and abort() */ + result = dbus.get_local_machine_id(); + } + + if (result) { + return result; + } + + if (dbus.error_is_set(&err)) { + SDL_SetError("%s: %s", err.name, err.message); + dbus.error_free(&err); + } else { + SDL_SetError("Error getting D-Bus machine ID"); + } + + return NULL; +} + +/* + * Convert file drops with mime type "application/vnd.portal.filetransfer" to file paths + * Result must be freed with dbus->free_string_array(). + * https://flatpak.github.io/xdg-desktop-portal/#gdbus-method-org-freedesktop-portal-FileTransfer.RetrieveFiles + */ +char **SDL_DBus_DocumentsPortalRetrieveFiles(const char *key, int *path_count) +{ + DBusError err; + DBusMessageIter iter, iterDict; + char **paths = NULL; + DBusMessage *reply = NULL; + DBusMessage *msg = dbus.message_new_method_call("org.freedesktop.portal.Documents", // Node + "/org/freedesktop/portal/documents", // Path + "org.freedesktop.portal.FileTransfer", // Interface + "RetrieveFiles"); // Method + + // Make sure we have a connection to the dbus session bus + if (!SDL_DBus_GetContext() || !dbus.session_conn) { + /* We either cannot connect to the session bus or were unable to + * load the D-Bus library at all. */ + return NULL; + } + + dbus.error_init(&err); + + // First argument is a "application/vnd.portal.filetransfer" key from a DnD or clipboard event + if (!dbus.message_append_args(msg, DBUS_TYPE_STRING, &key, DBUS_TYPE_INVALID)) { + SDL_OutOfMemory(); + dbus.message_unref(msg); + goto failed; + } + + /* Second argument is a variant dictionary for options. + * The spec doesn't define any entries yet so it's empty. */ + dbus.message_iter_init_append(msg, &iter); + if (!dbus.message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &iterDict) || + !dbus.message_iter_close_container(&iter, &iterDict)) { + SDL_OutOfMemory(); + dbus.message_unref(msg); + goto failed; + } + + reply = dbus.connection_send_with_reply_and_block(dbus.session_conn, msg, DBUS_TIMEOUT_USE_DEFAULT, &err); + dbus.message_unref(msg); + + if (reply) { + dbus.message_get_args(reply, &err, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &paths, path_count, DBUS_TYPE_INVALID); + dbus.message_unref(reply); + } + + if (paths) { + return paths; + } + +failed: + if (dbus.error_is_set(&err)) { + SDL_SetError("%s: %s", err.name, err.message); + dbus.error_free(&err); + } else { + SDL_SetError("Error retrieving paths for documents portal \"%s\"", key); + } + + return NULL; +} + +#endif diff --git a/thirdparty/sdl/core/linux/SDL_dbus.h b/thirdparty/sdl/core/linux/SDL_dbus.h new file mode 100644 index 00000000000..2073d6cee8b --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_dbus.h @@ -0,0 +1,114 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_dbus_h_ +#define SDL_dbus_h_ + +#ifdef HAVE_DBUS_DBUS_H +#define SDL_USE_LIBDBUS 1 +#include + +#ifndef DBUS_TIMEOUT_USE_DEFAULT +#define DBUS_TIMEOUT_USE_DEFAULT -1 +#endif +#ifndef DBUS_TIMEOUT_INFINITE +#define DBUS_TIMEOUT_INFINITE ((int) 0x7fffffff) +#endif + +typedef struct SDL_DBusContext +{ + DBusConnection *session_conn; + DBusConnection *system_conn; + + DBusConnection *(*bus_get_private)(DBusBusType, DBusError *); + dbus_bool_t (*bus_register)(DBusConnection *, DBusError *); + void (*bus_add_match)(DBusConnection *, const char *, DBusError *); + DBusConnection *(*connection_open_private)(const char *, DBusError *); + void (*connection_set_exit_on_disconnect)(DBusConnection *, dbus_bool_t); + dbus_bool_t (*connection_get_is_connected)(DBusConnection *); + dbus_bool_t (*connection_add_filter)(DBusConnection *, DBusHandleMessageFunction, void *, DBusFreeFunction); + dbus_bool_t (*connection_remove_filter)(DBusConnection *, DBusHandleMessageFunction, void *); + dbus_bool_t (*connection_try_register_object_path)(DBusConnection *, const char *, + const DBusObjectPathVTable *, void *, DBusError *); + dbus_bool_t (*connection_send)(DBusConnection *, DBusMessage *, dbus_uint32_t *); + DBusMessage *(*connection_send_with_reply_and_block)(DBusConnection *, DBusMessage *, int, DBusError *); + void (*connection_close)(DBusConnection *); + void (*connection_ref)(DBusConnection *); + void (*connection_unref)(DBusConnection *); + void (*connection_flush)(DBusConnection *); + dbus_bool_t (*connection_read_write)(DBusConnection *, int); + DBusDispatchStatus (*connection_dispatch)(DBusConnection *); + dbus_bool_t (*message_is_signal)(DBusMessage *, const char *, const char *); + dbus_bool_t (*message_has_path)(DBusMessage *, const char *); + DBusMessage *(*message_new_method_call)(const char *, const char *, const char *, const char *); + dbus_bool_t (*message_append_args)(DBusMessage *, int, ...); + dbus_bool_t (*message_append_args_valist)(DBusMessage *, int, va_list); + void (*message_iter_init_append)(DBusMessage *, DBusMessageIter *); + dbus_bool_t (*message_iter_open_container)(DBusMessageIter *, int, const char *, DBusMessageIter *); + dbus_bool_t (*message_iter_append_basic)(DBusMessageIter *, int, const void *); + dbus_bool_t (*message_iter_close_container)(DBusMessageIter *, DBusMessageIter *); + dbus_bool_t (*message_get_args)(DBusMessage *, DBusError *, int, ...); + dbus_bool_t (*message_get_args_valist)(DBusMessage *, DBusError *, int, va_list); + dbus_bool_t (*message_iter_init)(DBusMessage *, DBusMessageIter *); + dbus_bool_t (*message_iter_next)(DBusMessageIter *); + void (*message_iter_get_basic)(DBusMessageIter *, void *); + int (*message_iter_get_arg_type)(DBusMessageIter *); + void (*message_iter_recurse)(DBusMessageIter *, DBusMessageIter *); + void (*message_unref)(DBusMessage *); + dbus_bool_t (*threads_init_default)(void); + void (*error_init)(DBusError *); + dbus_bool_t (*error_is_set)(const DBusError *); + void (*error_free)(DBusError *); + char *(*get_local_machine_id)(void); + char *(*try_get_local_machine_id)(DBusError *); + void (*free)(void *); + void (*free_string_array)(char **); + void (*shutdown)(void); + +} SDL_DBusContext; + +extern void SDL_DBus_Init(void); +extern void SDL_DBus_Quit(void); +extern SDL_DBusContext *SDL_DBus_GetContext(void); + +// These use the built-in Session connection. +extern bool SDL_DBus_CallMethod(const char *node, const char *path, const char *interface, const char *method, ...); +extern bool SDL_DBus_CallVoidMethod(const char *node, const char *path, const char *interface, const char *method, ...); +extern bool SDL_DBus_QueryProperty(const char *node, const char *path, const char *interface, const char *property, int expectedtype, void *result); + +// These use whatever connection you like. +extern bool SDL_DBus_CallMethodOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, ...); +extern bool SDL_DBus_CallVoidMethodOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, ...); +extern bool SDL_DBus_QueryPropertyOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *property, int expectedtype, void *result); + +extern void SDL_DBus_ScreensaverTickle(void); +extern bool SDL_DBus_ScreensaverInhibit(bool inhibit); + +extern void SDL_DBus_PumpEvents(void); +extern char *SDL_DBus_GetLocalMachineId(void); + +extern char **SDL_DBus_DocumentsPortalRetrieveFiles(const char *key, int *files_count); + +#endif // HAVE_DBUS_DBUS_H + +#endif // SDL_dbus_h_ diff --git a/thirdparty/sdl/core/linux/SDL_evdev.c b/thirdparty/sdl/core/linux/SDL_evdev.c new file mode 100644 index 00000000000..04e3e9d6b65 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_evdev.c @@ -0,0 +1,1037 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_INPUT_LINUXEV + +// This is based on the linux joystick driver +/* References: https://www.kernel.org/doc/Documentation/input/input.txt + * https://www.kernel.org/doc/Documentation/input/event-codes.txt + * /usr/include/linux/input.h + * The evtest application is also useful to debug the protocol + */ + +#include "SDL_evdev.h" +#include "SDL_evdev_kbd.h" + +#include +#include +#include +#include +#include + +#include "../../events/SDL_events_c.h" +#include "../../core/linux/SDL_evdev_capabilities.h" +#include "../../core/linux/SDL_udev.h" + +// These are not defined in older Linux kernel headers +#ifndef SYN_DROPPED +#define SYN_DROPPED 3 +#endif +#ifndef ABS_MT_SLOT +#define ABS_MT_SLOT 0x2f +#define ABS_MT_POSITION_X 0x35 +#define ABS_MT_POSITION_Y 0x36 +#define ABS_MT_TRACKING_ID 0x39 +#define ABS_MT_PRESSURE 0x3a +#endif +#ifndef REL_WHEEL_HI_RES +#define REL_WHEEL_HI_RES 0x0b +#define REL_HWHEEL_HI_RES 0x0c +#endif + +// The field to look up in struct input_event for integer seconds +#ifndef input_event_sec +#define input_event_sec time.tv_sec +#endif + +// The field to look up in struct input_event for fractional seconds +#ifndef input_event_usec +#define input_event_usec time.tv_usec +#endif + +typedef struct SDL_evdevlist_item +{ + char *path; + int fd; + int udev_class; + + // TODO: use this for every device, not just touchscreen + bool out_of_sync; + + /* TODO: expand on this to have data for every possible class (mouse, + keyboard, touchpad, etc.). Also there's probably some things in here we + can pull out to the SDL_evdevlist_item i.e. name */ + bool is_touchscreen; + struct + { + char *name; + + int min_x, max_x, range_x; + int min_y, max_y, range_y; + int min_pressure, max_pressure, range_pressure; + + int max_slots; + int current_slot; + struct + { + enum + { + EVDEV_TOUCH_SLOTDELTA_NONE = 0, + EVDEV_TOUCH_SLOTDELTA_DOWN, + EVDEV_TOUCH_SLOTDELTA_UP, + EVDEV_TOUCH_SLOTDELTA_MOVE + } delta; + int tracking_id; + int x, y, pressure; + } *slots; + + } *touchscreen_data; + + // Mouse state + bool high_res_wheel; + bool high_res_hwheel; + bool relative_mouse; + int mouse_x, mouse_y; + int mouse_wheel, mouse_hwheel; + int min_x, max_x, range_x; + int min_y, max_y, range_y; + + struct SDL_evdevlist_item *next; +} SDL_evdevlist_item; + +typedef struct SDL_EVDEV_PrivateData +{ + int ref_count; + int num_devices; + SDL_evdevlist_item *first; + SDL_evdevlist_item *last; + SDL_EVDEV_keyboard_state *kbd; +} SDL_EVDEV_PrivateData; + +static SDL_EVDEV_PrivateData *_this = NULL; + +static SDL_Scancode SDL_EVDEV_translate_keycode(int keycode); +static void SDL_EVDEV_sync_device(SDL_evdevlist_item *item); +static bool SDL_EVDEV_device_removed(const char *dev_path); +static bool SDL_EVDEV_device_added(const char *dev_path, int udev_class); +#ifdef SDL_USE_LIBUDEV +static void SDL_EVDEV_udev_callback(SDL_UDEV_deviceevent udev_event, int udev_class, const char *dev_path); +#endif // SDL_USE_LIBUDEV + +static Uint8 EVDEV_MouseButtons[] = { + SDL_BUTTON_LEFT, // BTN_LEFT 0x110 + SDL_BUTTON_RIGHT, // BTN_RIGHT 0x111 + SDL_BUTTON_MIDDLE, // BTN_MIDDLE 0x112 + SDL_BUTTON_X1, // BTN_SIDE 0x113 + SDL_BUTTON_X2, // BTN_EXTRA 0x114 + SDL_BUTTON_X2 + 1, // BTN_FORWARD 0x115 + SDL_BUTTON_X2 + 2, // BTN_BACK 0x116 + SDL_BUTTON_X2 + 3 // BTN_TASK 0x117 +}; + +static bool SDL_EVDEV_SetRelativeMouseMode(bool enabled) +{ + // Mice already send relative events through this interface + return true; +} + +static void SDL_EVDEV_UpdateKeyboardMute(void) +{ + if (SDL_EVDEV_GetDeviceCount(SDL_UDEV_DEVICE_KEYBOARD) > 0) { + SDL_EVDEV_kbd_set_muted(_this->kbd, true); + } else { + SDL_EVDEV_kbd_set_muted(_this->kbd, false); + } +} + +bool SDL_EVDEV_Init(void) +{ + if (!_this) { + _this = (SDL_EVDEV_PrivateData *)SDL_calloc(1, sizeof(*_this)); + if (!_this) { + return false; + } + +#ifdef SDL_USE_LIBUDEV + if (!SDL_UDEV_Init()) { + SDL_free(_this); + _this = NULL; + return false; + } + + // Set up the udev callback + if (!SDL_UDEV_AddCallback(SDL_EVDEV_udev_callback)) { + SDL_UDEV_Quit(); + SDL_free(_this); + _this = NULL; + return false; + } + + // Force a scan to build the initial device list + SDL_UDEV_Scan(); +#else + { + /* Allow the user to specify a list of devices explicitly of + the form: + deviceclass:path[,deviceclass:path[,...]] + where device class is an integer representing the + SDL_UDEV_deviceclass and path is the full path to + the event device. */ + const char *devices = SDL_GetHint(SDL_HINT_EVDEV_DEVICES); + if (devices) { + /* Assume this is the old use of the env var and it is not in + ROM. */ + char *rest = (char *)devices; + char *spec; + while ((spec = SDL_strtok_r(rest, ",", &rest))) { + char *endofcls = 0; + long cls = SDL_strtol(spec, &endofcls, 0); + if (endofcls) { + SDL_EVDEV_device_added(endofcls + 1, cls); + } + } + } else { + // TODO: Scan the devices manually, like a caveman + } + } +#endif // SDL_USE_LIBUDEV + + _this->kbd = SDL_EVDEV_kbd_init(); + + SDL_EVDEV_UpdateKeyboardMute(); + } + + //SDL_GetMouse()->SetRelativeMouseMode = SDL_EVDEV_SetRelativeMouseMode; + + _this->ref_count += 1; + + return true; +} + +void SDL_EVDEV_Quit(void) +{ + if (!_this) { + return; + } + + _this->ref_count -= 1; + + if (_this->ref_count < 1) { +#ifdef SDL_USE_LIBUDEV + SDL_UDEV_DelCallback(SDL_EVDEV_udev_callback); + SDL_UDEV_Quit(); +#endif // SDL_USE_LIBUDEV + + // Remove existing devices + while (_this->first) { + SDL_EVDEV_device_removed(_this->first->path); + } + + SDL_EVDEV_kbd_quit(_this->kbd); + + SDL_assert(_this->first == NULL); + SDL_assert(_this->last == NULL); + SDL_assert(_this->num_devices == 0); + + SDL_free(_this); + _this = NULL; + } +} + +#ifdef SDL_USE_LIBUDEV +static void SDL_EVDEV_udev_callback(SDL_UDEV_deviceevent udev_event, int udev_class, + const char *dev_path) +{ + if (!dev_path) { + return; + } + + switch (udev_event) { + case SDL_UDEV_DEVICEADDED: + if (!(udev_class & (SDL_UDEV_DEVICE_MOUSE | SDL_UDEV_DEVICE_HAS_KEYS | SDL_UDEV_DEVICE_TOUCHSCREEN | SDL_UDEV_DEVICE_TOUCHPAD))) { + return; + } + + if (udev_class & SDL_UDEV_DEVICE_JOYSTICK) { + return; + } + + SDL_EVDEV_device_added(dev_path, udev_class); + break; + case SDL_UDEV_DEVICEREMOVED: + SDL_EVDEV_device_removed(dev_path); + break; + default: + break; + } +} +#endif // SDL_USE_LIBUDEV + +void SDL_EVDEV_SetVTSwitchCallbacks(void (*release_callback)(void*), void *release_callback_data, + void (*acquire_callback)(void*), void *acquire_callback_data) +{ + SDL_EVDEV_kbd_set_vt_switch_callbacks(_this->kbd, + release_callback, release_callback_data, + acquire_callback, acquire_callback_data); +} + +int SDL_EVDEV_GetDeviceCount(int device_class) +{ + SDL_evdevlist_item *item; + int count = 0; + + for (item = _this->first; item; item = item->next) { + if ((item->udev_class & device_class) == device_class) { + ++count; + } + } + return count; +} + +void SDL_EVDEV_Poll(void) +{ + struct input_event events[32]; + int i, j, len; + SDL_evdevlist_item *item; + SDL_Scancode scancode; + int mouse_button; + SDL_Mouse *mouse; + float norm_x, norm_y, norm_pressure; + + if (!_this) { + return; + } + +#ifdef SDL_USE_LIBUDEV + SDL_UDEV_Poll(); +#endif + + SDL_EVDEV_kbd_update(_this->kbd); + + mouse = NULL; //SDL_GetMouse(); + + for (item = _this->first; item; item = item->next) { + while ((len = read(item->fd, events, sizeof(events))) > 0) { + len /= sizeof(events[0]); + for (i = 0; i < len; ++i) { + struct input_event *event = &events[i]; + + /* special handling for touchscreen, that should eventually be + used for all devices */ + if (item->out_of_sync && item->is_touchscreen && + event->type == EV_SYN && event->code != SYN_REPORT) { + break; + } + + switch (event->type) { + case EV_KEY: + break; + if (event->code >= BTN_MOUSE && event->code < BTN_MOUSE + SDL_arraysize(EVDEV_MouseButtons)) { + Uint64 timestamp = SDL_EVDEV_GetEventTimestamp(event); + mouse_button = event->code - BTN_MOUSE; + //SDL_SendMouseButton(timestamp, mouse->focus, (SDL_MouseID)item->fd, EVDEV_MouseButtons[mouse_button], (event->value != 0)); + break; + } + + /* BTN_TOUCH event value 1 indicates there is contact with + a touchscreen or trackpad (earliest finger's current + position is sent in EV_ABS ABS_X/ABS_Y, switching to + next finger after earliest is released) */ + if (item->is_touchscreen && event->code == BTN_TOUCH) { + if (item->touchscreen_data->max_slots == 1) { + if (event->value) { + item->touchscreen_data->slots[0].delta = EVDEV_TOUCH_SLOTDELTA_DOWN; + } else { + item->touchscreen_data->slots[0].delta = EVDEV_TOUCH_SLOTDELTA_UP; + } + } + break; + } + + // Probably keyboard + { + Uint64 timestamp = SDL_EVDEV_GetEventTimestamp(event); + scancode = SDL_EVDEV_translate_keycode(event->code); + // if (event->value == 0) { + // SDL_SendKeyboardKey(timestamp, (SDL_KeyboardID)item->fd, event->code, scancode, false); + // } else if (event->value == 1 || event->value == 2 /* key repeated */) { + // SDL_SendKeyboardKey(timestamp, (SDL_KeyboardID)item->fd, event->code, scancode, true); + // } + SDL_EVDEV_kbd_keycode(_this->kbd, event->code, event->value); + } + break; + case EV_ABS: + switch (event->code) { + case ABS_MT_SLOT: + if (!item->is_touchscreen) { // FIXME: temp hack + break; + } + item->touchscreen_data->current_slot = event->value; + break; + case ABS_MT_TRACKING_ID: + if (!item->is_touchscreen) { // FIXME: temp hack + break; + } + if (event->value >= 0) { + item->touchscreen_data->slots[item->touchscreen_data->current_slot].tracking_id = event->value + 1; + item->touchscreen_data->slots[item->touchscreen_data->current_slot].delta = EVDEV_TOUCH_SLOTDELTA_DOWN; + } else { + item->touchscreen_data->slots[item->touchscreen_data->current_slot].delta = EVDEV_TOUCH_SLOTDELTA_UP; + } + break; + case ABS_MT_POSITION_X: + if (!item->is_touchscreen) { // FIXME: temp hack + break; + } + item->touchscreen_data->slots[item->touchscreen_data->current_slot].x = event->value; + if (item->touchscreen_data->slots[item->touchscreen_data->current_slot].delta == EVDEV_TOUCH_SLOTDELTA_NONE) { + item->touchscreen_data->slots[item->touchscreen_data->current_slot].delta = EVDEV_TOUCH_SLOTDELTA_MOVE; + } + break; + case ABS_MT_POSITION_Y: + if (!item->is_touchscreen) { // FIXME: temp hack + break; + } + item->touchscreen_data->slots[item->touchscreen_data->current_slot].y = event->value; + if (item->touchscreen_data->slots[item->touchscreen_data->current_slot].delta == EVDEV_TOUCH_SLOTDELTA_NONE) { + item->touchscreen_data->slots[item->touchscreen_data->current_slot].delta = EVDEV_TOUCH_SLOTDELTA_MOVE; + } + break; + case ABS_MT_PRESSURE: + if (!item->is_touchscreen) { // FIXME: temp hack + break; + } + item->touchscreen_data->slots[item->touchscreen_data->current_slot].pressure = event->value; + if (item->touchscreen_data->slots[item->touchscreen_data->current_slot].delta == EVDEV_TOUCH_SLOTDELTA_NONE) { + item->touchscreen_data->slots[item->touchscreen_data->current_slot].delta = EVDEV_TOUCH_SLOTDELTA_MOVE; + } + break; + case ABS_X: + if (item->is_touchscreen) { + if (item->touchscreen_data->max_slots != 1) { + break; + } + item->touchscreen_data->slots[0].x = event->value; + } else if (!item->relative_mouse) { + item->mouse_x = event->value; + } + break; + case ABS_Y: + if (item->is_touchscreen) { + if (item->touchscreen_data->max_slots != 1) { + break; + } + item->touchscreen_data->slots[0].y = event->value; + } else if (!item->relative_mouse) { + item->mouse_y = event->value; + } + break; + default: + break; + } + break; + case EV_REL: + switch (event->code) { + case REL_X: + if (item->relative_mouse) { + item->mouse_x += event->value; + } + break; + case REL_Y: + if (item->relative_mouse) { + item->mouse_y += event->value; + } + break; + case REL_WHEEL: + if (!item->high_res_wheel) { + item->mouse_wheel += event->value; + } + break; + case REL_WHEEL_HI_RES: + SDL_assert(item->high_res_wheel); + item->mouse_wheel += event->value; + break; + case REL_HWHEEL: + if (!item->high_res_hwheel) { + item->mouse_hwheel += event->value; + } + break; + case REL_HWHEEL_HI_RES: + SDL_assert(item->high_res_hwheel); + item->mouse_hwheel += event->value; + break; + default: + break; + } + break; + case EV_SYN: + switch (event->code) { + case SYN_REPORT: + // Send mouse axis changes together to ensure consistency and reduce event processing overhead + if (item->relative_mouse) { + if (item->mouse_x != 0 || item->mouse_y != 0) { + Uint64 timestamp = SDL_EVDEV_GetEventTimestamp(event); + //SDL_SendMouseMotion(timestamp, mouse->focus, (SDL_MouseID)item->fd, item->relative_mouse, (float)item->mouse_x, (float)item->mouse_y); + item->mouse_x = item->mouse_y = 0; + } + } else if (item->range_x > 0 && item->range_y > 0) { + int screen_w = 0, screen_h = 0; + const SDL_DisplayMode *mode = NULL; + + if (mode) { + screen_w = mode->w; + screen_h = mode->h; + } + //SDL_SendMouseMotion(SDL_EVDEV_GetEventTimestamp(event), mouse->focus, (SDL_MouseID)item->fd, item->relative_mouse, + // (float)(item->mouse_x - item->min_x) * screen_w / item->range_x, + // (float)(item->mouse_y - item->min_y) * screen_h / item->range_y); + } + + if (item->mouse_wheel != 0 || item->mouse_hwheel != 0) { + Uint64 timestamp = SDL_EVDEV_GetEventTimestamp(event); + const float denom = (item->high_res_hwheel ? 120.0f : 1.0f); + //SDL_SendMouseWheel(timestamp, + // mouse->focus, (SDL_MouseID)item->fd, + // item->mouse_hwheel / denom, + // item->mouse_wheel / denom, + // SDL_MOUSEWHEEL_NORMAL); + item->mouse_wheel = item->mouse_hwheel = 0; + } + + if (!item->is_touchscreen) { // FIXME: temp hack + break; + } + + for (j = 0; j < item->touchscreen_data->max_slots; j++) { + norm_x = (float)(item->touchscreen_data->slots[j].x - item->touchscreen_data->min_x) / + (float)item->touchscreen_data->range_x; + norm_y = (float)(item->touchscreen_data->slots[j].y - item->touchscreen_data->min_y) / + (float)item->touchscreen_data->range_y; + + if (item->touchscreen_data->range_pressure > 0) { + norm_pressure = (float)(item->touchscreen_data->slots[j].pressure - item->touchscreen_data->min_pressure) / + (float)item->touchscreen_data->range_pressure; + } else { + // This touchscreen does not support pressure + norm_pressure = 1.0f; + } + + /* FIXME: the touch's window shouldn't be null, but + * the coordinate space of touch positions needs to + * be window-relative in that case. */ + switch (item->touchscreen_data->slots[j].delta) { + case EVDEV_TOUCH_SLOTDELTA_DOWN: + //SDL_SendTouch(SDL_EVDEV_GetEventTimestamp(event), item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, SDL_EVENT_FINGER_DOWN, norm_x, norm_y, norm_pressure); + item->touchscreen_data->slots[j].delta = EVDEV_TOUCH_SLOTDELTA_NONE; + break; + case EVDEV_TOUCH_SLOTDELTA_UP: + //SDL_SendTouch(SDL_EVDEV_GetEventTimestamp(event), item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, SDL_EVENT_FINGER_UP, norm_x, norm_y, norm_pressure); + item->touchscreen_data->slots[j].tracking_id = 0; + item->touchscreen_data->slots[j].delta = EVDEV_TOUCH_SLOTDELTA_NONE; + break; + case EVDEV_TOUCH_SLOTDELTA_MOVE: + //SDL_SendTouchMotion(SDL_EVDEV_GetEventTimestamp(event), item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, norm_x, norm_y, norm_pressure); + item->touchscreen_data->slots[j].delta = EVDEV_TOUCH_SLOTDELTA_NONE; + break; + default: + break; + } + } + + if (item->out_of_sync) { + item->out_of_sync = false; + } + break; + case SYN_DROPPED: + if (item->is_touchscreen) { + item->out_of_sync = true; + } + SDL_EVDEV_sync_device(item); + break; + default: + break; + } + break; + } + } + } + } +} + +static SDL_Scancode SDL_EVDEV_translate_keycode(int keycode) +{ + //SDL_Scancode scancode = SDL_GetScancodeFromTable(SDL_SCANCODE_TABLE_LINUX, keycode); + +#ifdef DEBUG_SCANCODES + if (scancode == SDL_SCANCODE_UNKNOWN) { + /* BTN_TOUCH is handled elsewhere, but we might still end up here if + you get an unexpected BTN_TOUCH from something SDL believes is not + a touch device. In this case, we'd rather not get a misleading + SDL_Log message about an unknown key. */ + if (keycode != BTN_TOUCH) { + SDL_Log("The key you just pressed is not recognized by SDL. To help " + "get this fixed, please report this to the SDL forums/mailing list " + " EVDEV KeyCode %d", + keycode); + } + } +#endif // DEBUG_SCANCODES + + return 0; //scancode; +} + +static bool SDL_EVDEV_init_keyboard(SDL_evdevlist_item *item, int udev_class) +{ + char name[128]; + + name[0] = '\0'; + ioctl(item->fd, EVIOCGNAME(sizeof(name)), name); + + //SDL_AddKeyboard((SDL_KeyboardID)item->fd, name, true); + + return true; +} + +static void SDL_EVDEV_destroy_keyboard(SDL_evdevlist_item *item) +{ + //SDL_RemoveKeyboard((SDL_KeyboardID)item->fd, true); +} + +static bool SDL_EVDEV_init_mouse(SDL_evdevlist_item *item, int udev_class) +{ + char name[128]; + int ret; + struct input_absinfo abs_info; + + name[0] = '\0'; + ioctl(item->fd, EVIOCGNAME(sizeof(name)), name); + + //SDL_AddMouse((SDL_MouseID)item->fd, name, true); + + ret = ioctl(item->fd, EVIOCGABS(ABS_X), &abs_info); + if (ret < 0) { + // no absolute mode info, continue + return true; + } + item->min_x = abs_info.minimum; + item->max_x = abs_info.maximum; + item->range_x = abs_info.maximum - abs_info.minimum; + + ret = ioctl(item->fd, EVIOCGABS(ABS_Y), &abs_info); + if (ret < 0) { + // no absolute mode info, continue + return true; + } + item->min_y = abs_info.minimum; + item->max_y = abs_info.maximum; + item->range_y = abs_info.maximum - abs_info.minimum; + + return true; +} + +static void SDL_EVDEV_destroy_mouse(SDL_evdevlist_item *item) +{ + //SDL_RemoveMouse((SDL_MouseID)item->fd, true); +} + +static bool SDL_EVDEV_init_touchscreen(SDL_evdevlist_item *item, int udev_class) +{ + int ret; + unsigned long xreq, yreq; + char name[64]; + struct input_absinfo abs_info; + + if (!item->is_touchscreen) { + return true; + } + + item->touchscreen_data = SDL_calloc(1, sizeof(*item->touchscreen_data)); + if (!item->touchscreen_data) { + return false; + } + + ret = ioctl(item->fd, EVIOCGNAME(sizeof(name)), name); + if (ret < 0) { + SDL_free(item->touchscreen_data); + return SDL_SetError("Failed to get evdev touchscreen name"); + } + + item->touchscreen_data->name = SDL_strdup(name); + if (!item->touchscreen_data->name) { + SDL_free(item->touchscreen_data); + return false; + } + + ret = ioctl(item->fd, EVIOCGABS(ABS_MT_SLOT), &abs_info); + if (ret < 0) { + SDL_free(item->touchscreen_data->name); + SDL_free(item->touchscreen_data); + return SDL_SetError("Failed to get evdev touchscreen limits"); + } + + if (abs_info.maximum == 0) { + item->touchscreen_data->max_slots = 1; + xreq = EVIOCGABS(ABS_X); + yreq = EVIOCGABS(ABS_Y); + } else { + item->touchscreen_data->max_slots = abs_info.maximum + 1; + xreq = EVIOCGABS(ABS_MT_POSITION_X); + yreq = EVIOCGABS(ABS_MT_POSITION_Y); + } + + ret = ioctl(item->fd, xreq, &abs_info); + if (ret < 0) { + SDL_free(item->touchscreen_data->name); + SDL_free(item->touchscreen_data); + return SDL_SetError("Failed to get evdev touchscreen limits"); + } + item->touchscreen_data->min_x = abs_info.minimum; + item->touchscreen_data->max_x = abs_info.maximum; + item->touchscreen_data->range_x = abs_info.maximum - abs_info.minimum; + + ret = ioctl(item->fd, yreq, &abs_info); + if (ret < 0) { + SDL_free(item->touchscreen_data->name); + SDL_free(item->touchscreen_data); + return SDL_SetError("Failed to get evdev touchscreen limits"); + } + item->touchscreen_data->min_y = abs_info.minimum; + item->touchscreen_data->max_y = abs_info.maximum; + item->touchscreen_data->range_y = abs_info.maximum - abs_info.minimum; + + ret = ioctl(item->fd, EVIOCGABS(ABS_MT_PRESSURE), &abs_info); + if (ret < 0) { + SDL_free(item->touchscreen_data->name); + SDL_free(item->touchscreen_data); + return SDL_SetError("Failed to get evdev touchscreen limits"); + } + item->touchscreen_data->min_pressure = abs_info.minimum; + item->touchscreen_data->max_pressure = abs_info.maximum; + item->touchscreen_data->range_pressure = abs_info.maximum - abs_info.minimum; + + item->touchscreen_data->slots = SDL_calloc( + item->touchscreen_data->max_slots, + sizeof(*item->touchscreen_data->slots)); + if (!item->touchscreen_data->slots) { + SDL_free(item->touchscreen_data->name); + SDL_free(item->touchscreen_data); + return false; + } + + //ret = SDL_AddTouch(item->fd, // I guess our fd is unique enough + // (udev_class & SDL_UDEV_DEVICE_TOUCHPAD) ? SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE : SDL_TOUCH_DEVICE_DIRECT, + // item->touchscreen_data->name); + ret = -1; + if (ret < 0) { + SDL_free(item->touchscreen_data->slots); + SDL_free(item->touchscreen_data->name); + SDL_free(item->touchscreen_data); + return false; + } + + return true; +} + +static void SDL_EVDEV_destroy_touchscreen(SDL_evdevlist_item *item) +{ + if (!item->is_touchscreen) { + return; + } + + //SDL_DelTouch(item->fd); + SDL_free(item->touchscreen_data->slots); + SDL_free(item->touchscreen_data->name); + SDL_free(item->touchscreen_data); +} + +static void SDL_EVDEV_sync_device(SDL_evdevlist_item *item) +{ +#ifdef EVIOCGMTSLOTS + int i, ret; + struct input_absinfo abs_info; + /* + * struct input_mt_request_layout { + * __u32 code; + * __s32 values[num_slots]; + * }; + * + * this is the structure we're trying to emulate + */ + Uint32 *mt_req_code; + Sint32 *mt_req_values; + size_t mt_req_size; + + // TODO: sync devices other than touchscreen + if (!item->is_touchscreen) { + return; + } + + mt_req_size = sizeof(*mt_req_code) + + sizeof(*mt_req_values) * item->touchscreen_data->max_slots; + + mt_req_code = SDL_calloc(1, mt_req_size); + if (!mt_req_code) { + return; + } + + mt_req_values = (Sint32 *)mt_req_code + 1; + + *mt_req_code = ABS_MT_TRACKING_ID; + ret = ioctl(item->fd, EVIOCGMTSLOTS(mt_req_size), mt_req_code); + if (ret < 0) { + SDL_free(mt_req_code); + return; + } + for (i = 0; i < item->touchscreen_data->max_slots; i++) { + /* + * This doesn't account for the very edge case of the user removing their + * finger and replacing it on the screen during the time we're out of sync, + * which'll mean that we're not going from down -> up or up -> down, we're + * going from down -> down but with a different tracking id, meaning we'd + * have to tell SDL of the two events, but since we wait till SYN_REPORT in + * SDL_EVDEV_Poll to tell SDL, the current structure of this code doesn't + * allow it. Lets just pray to God it doesn't happen. + */ + if (item->touchscreen_data->slots[i].tracking_id == 0 && + mt_req_values[i] >= 0) { + item->touchscreen_data->slots[i].tracking_id = mt_req_values[i] + 1; + item->touchscreen_data->slots[i].delta = EVDEV_TOUCH_SLOTDELTA_DOWN; + } else if (item->touchscreen_data->slots[i].tracking_id != 0 && + mt_req_values[i] < 0) { + item->touchscreen_data->slots[i].tracking_id = 0; + item->touchscreen_data->slots[i].delta = EVDEV_TOUCH_SLOTDELTA_UP; + } + } + + *mt_req_code = ABS_MT_POSITION_X; + ret = ioctl(item->fd, EVIOCGMTSLOTS(mt_req_size), mt_req_code); + if (ret < 0) { + SDL_free(mt_req_code); + return; + } + for (i = 0; i < item->touchscreen_data->max_slots; i++) { + if (item->touchscreen_data->slots[i].tracking_id != 0 && + item->touchscreen_data->slots[i].x != mt_req_values[i]) { + item->touchscreen_data->slots[i].x = mt_req_values[i]; + if (item->touchscreen_data->slots[i].delta == + EVDEV_TOUCH_SLOTDELTA_NONE) { + item->touchscreen_data->slots[i].delta = + EVDEV_TOUCH_SLOTDELTA_MOVE; + } + } + } + + *mt_req_code = ABS_MT_POSITION_Y; + ret = ioctl(item->fd, EVIOCGMTSLOTS(mt_req_size), mt_req_code); + if (ret < 0) { + SDL_free(mt_req_code); + return; + } + for (i = 0; i < item->touchscreen_data->max_slots; i++) { + if (item->touchscreen_data->slots[i].tracking_id != 0 && + item->touchscreen_data->slots[i].y != mt_req_values[i]) { + item->touchscreen_data->slots[i].y = mt_req_values[i]; + if (item->touchscreen_data->slots[i].delta == + EVDEV_TOUCH_SLOTDELTA_NONE) { + item->touchscreen_data->slots[i].delta = + EVDEV_TOUCH_SLOTDELTA_MOVE; + } + } + } + + *mt_req_code = ABS_MT_PRESSURE; + ret = ioctl(item->fd, EVIOCGMTSLOTS(mt_req_size), mt_req_code); + if (ret < 0) { + SDL_free(mt_req_code); + return; + } + for (i = 0; i < item->touchscreen_data->max_slots; i++) { + if (item->touchscreen_data->slots[i].tracking_id != 0 && + item->touchscreen_data->slots[i].pressure != mt_req_values[i]) { + item->touchscreen_data->slots[i].pressure = mt_req_values[i]; + if (item->touchscreen_data->slots[i].delta == + EVDEV_TOUCH_SLOTDELTA_NONE) { + item->touchscreen_data->slots[i].delta = + EVDEV_TOUCH_SLOTDELTA_MOVE; + } + } + } + + ret = ioctl(item->fd, EVIOCGABS(ABS_MT_SLOT), &abs_info); + if (ret < 0) { + SDL_free(mt_req_code); + return; + } + item->touchscreen_data->current_slot = abs_info.value; + + SDL_free(mt_req_code); + +#endif // EVIOCGMTSLOTS +} + +static bool SDL_EVDEV_device_added(const char *dev_path, int udev_class) +{ + SDL_evdevlist_item *item; + unsigned long relbit[NBITS(REL_MAX)] = { 0 }; + + // Check to make sure it's not already in list. + for (item = _this->first; item; item = item->next) { + if (SDL_strcmp(dev_path, item->path) == 0) { + return false; // already have this one + } + } + + item = (SDL_evdevlist_item *)SDL_calloc(1, sizeof(SDL_evdevlist_item)); + if (!item) { + return false; + } + + item->fd = open(dev_path, O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (item->fd < 0) { + SDL_free(item); + return SDL_SetError("Unable to open %s", dev_path); + } + + item->path = SDL_strdup(dev_path); + if (!item->path) { + close(item->fd); + SDL_free(item); + return false; + } + + item->udev_class = udev_class; + + if (ioctl(item->fd, EVIOCGBIT(EV_REL, sizeof(relbit)), relbit) >= 0) { + item->relative_mouse = test_bit(REL_X, relbit) && test_bit(REL_Y, relbit); + item->high_res_wheel = test_bit(REL_WHEEL_HI_RES, relbit); + item->high_res_hwheel = test_bit(REL_HWHEEL_HI_RES, relbit); + } + + // For now, we just treat a touchpad like a touchscreen + if (udev_class & (SDL_UDEV_DEVICE_TOUCHSCREEN | SDL_UDEV_DEVICE_TOUCHPAD)) { + item->is_touchscreen = true; + if (!SDL_EVDEV_init_touchscreen(item, udev_class)) { + close(item->fd); + SDL_free(item->path); + SDL_free(item); + return false; + } + } + + if (udev_class & SDL_UDEV_DEVICE_MOUSE) { + if (!SDL_EVDEV_init_mouse(item, udev_class)) { + close(item->fd); + SDL_free(item->path); + SDL_free(item); + return false; + } + } + + if (udev_class & SDL_UDEV_DEVICE_KEYBOARD) { + if (!SDL_EVDEV_init_keyboard(item, udev_class)) { + close(item->fd); + SDL_free(item->path); + SDL_free(item); + return false; + } + } + + if (!_this->last) { + _this->first = _this->last = item; + } else { + _this->last->next = item; + _this->last = item; + } + + SDL_EVDEV_sync_device(item); + + SDL_EVDEV_UpdateKeyboardMute(); + + ++_this->num_devices; + return true; +} + +static bool SDL_EVDEV_device_removed(const char *dev_path) +{ + SDL_evdevlist_item *item; + SDL_evdevlist_item *prev = NULL; + + for (item = _this->first; item; item = item->next) { + // found it, remove it. + if (SDL_strcmp(dev_path, item->path) == 0) { + if (prev) { + prev->next = item->next; + } else { + SDL_assert(_this->first == item); + _this->first = item->next; + } + if (item == _this->last) { + _this->last = prev; + } + + if (item->is_touchscreen) { + SDL_EVDEV_destroy_touchscreen(item); + } + if (item->udev_class & SDL_UDEV_DEVICE_MOUSE) { + SDL_EVDEV_destroy_mouse(item); + } + if (item->udev_class & SDL_UDEV_DEVICE_KEYBOARD) { + SDL_EVDEV_destroy_keyboard(item); + } + close(item->fd); + SDL_free(item->path); + SDL_free(item); + SDL_EVDEV_UpdateKeyboardMute(); + _this->num_devices--; + return true; + } + prev = item; + } + + return false; +} + +Uint64 SDL_EVDEV_GetEventTimestamp(struct input_event *event) +{ + static Uint64 timestamp_offset; + Uint64 timestamp; + Uint64 now = SDL_GetTicksNS(); + + /* The kernel internally has nanosecond timestamps, but converts it + to microseconds when delivering the events */ + timestamp = event->input_event_sec; + timestamp *= SDL_NS_PER_SECOND; + timestamp += SDL_US_TO_NS(event->input_event_usec); + + if (!timestamp_offset) { + timestamp_offset = (now - timestamp); + } + timestamp += timestamp_offset; + + if (timestamp > now) { + timestamp_offset -= (timestamp - now); + timestamp = now; + } + return timestamp; +} + +#endif // SDL_INPUT_LINUXEV diff --git a/thirdparty/sdl/core/linux/SDL_evdev.h b/thirdparty/sdl/core/linux/SDL_evdev.h new file mode 100644 index 00000000000..d3e2fe165e5 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_evdev.h @@ -0,0 +1,41 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_evdev_h_ +#define SDL_evdev_h_ + +#ifdef SDL_INPUT_LINUXEV + +struct input_event; + +extern bool SDL_EVDEV_Init(void); +extern void SDL_EVDEV_Quit(void); +extern void SDL_EVDEV_SetVTSwitchCallbacks(void (*release_callback)(void*), void *release_callback_data, + void (*acquire_callback)(void*), void *acquire_callback_data); +extern int SDL_EVDEV_GetDeviceCount(int device_class); +extern void SDL_EVDEV_Poll(void); +extern Uint64 SDL_EVDEV_GetEventTimestamp(struct input_event *event); + +#endif // SDL_INPUT_LINUXEV + +#endif // SDL_evdev_h_ diff --git a/thirdparty/sdl/core/linux/SDL_evdev_capabilities.c b/thirdparty/sdl/core/linux/SDL_evdev_capabilities.c new file mode 100644 index 00000000000..61e240e7e12 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_evdev_capabilities.c @@ -0,0 +1,168 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + Copyright (C) 2020 Collabora Ltd. + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_evdev_capabilities.h" + +#ifdef HAVE_LINUX_INPUT_H + +// missing defines in older Linux kernel headers +#ifndef BTN_TRIGGER_HAPPY +#define BTN_TRIGGER_HAPPY 0x2c0 +#endif +#ifndef BTN_DPAD_UP +#define BTN_DPAD_UP 0x220 +#endif +#ifndef KEY_ALS_TOGGLE +#define KEY_ALS_TOGGLE 0x230 +#endif + +extern int +SDL_EVDEV_GuessDeviceClass(const unsigned long bitmask_props[NBITS(INPUT_PROP_MAX)], + const unsigned long bitmask_ev[NBITS(EV_MAX)], + const unsigned long bitmask_abs[NBITS(ABS_MAX)], + const unsigned long bitmask_key[NBITS(KEY_MAX)], + const unsigned long bitmask_rel[NBITS(REL_MAX)]) +{ + struct range + { + unsigned start; + unsigned end; + }; + + // key code ranges above BTN_MISC (start is inclusive, stop is exclusive) + static const struct range high_key_blocks[] = { + { KEY_OK, BTN_DPAD_UP }, + { KEY_ALS_TOGGLE, BTN_TRIGGER_HAPPY } + }; + + int devclass = 0; + unsigned long keyboard_mask; + + // If the kernel specifically says it's an accelerometer, believe it + if (test_bit(INPUT_PROP_ACCELEROMETER, bitmask_props)) { + return SDL_UDEV_DEVICE_ACCELEROMETER; + } + + // We treat pointing sticks as indistinguishable from mice + if (test_bit(INPUT_PROP_POINTING_STICK, bitmask_props)) { + return SDL_UDEV_DEVICE_MOUSE; + } + + // We treat buttonpads as equivalent to touchpads + if (test_bit(INPUT_PROP_TOPBUTTONPAD, bitmask_props) || + test_bit(INPUT_PROP_BUTTONPAD, bitmask_props) || + test_bit(INPUT_PROP_SEMI_MT, bitmask_props)) { + return SDL_UDEV_DEVICE_TOUCHPAD; + } + + // X, Y, Z axes but no buttons probably means an accelerometer + if (test_bit(EV_ABS, bitmask_ev) && + test_bit(ABS_X, bitmask_abs) && + test_bit(ABS_Y, bitmask_abs) && + test_bit(ABS_Z, bitmask_abs) && + !test_bit(EV_KEY, bitmask_ev)) { + return SDL_UDEV_DEVICE_ACCELEROMETER; + } + + /* RX, RY, RZ axes but no buttons probably means a gyro or + * accelerometer (we don't distinguish) */ + if (test_bit(EV_ABS, bitmask_ev) && + test_bit(ABS_RX, bitmask_abs) && + test_bit(ABS_RY, bitmask_abs) && + test_bit(ABS_RZ, bitmask_abs) && + !test_bit(EV_KEY, bitmask_ev)) { + return SDL_UDEV_DEVICE_ACCELEROMETER; + } + + if (test_bit(EV_ABS, bitmask_ev) && + test_bit(ABS_X, bitmask_abs) && test_bit(ABS_Y, bitmask_abs)) { + if (test_bit(BTN_STYLUS, bitmask_key) || test_bit(BTN_TOOL_PEN, bitmask_key)) { + ; // ID_INPUT_TABLET + } else if (test_bit(BTN_TOOL_FINGER, bitmask_key) && !test_bit(BTN_TOOL_PEN, bitmask_key)) { + devclass |= SDL_UDEV_DEVICE_TOUCHPAD; // ID_INPUT_TOUCHPAD + } else if (test_bit(BTN_MOUSE, bitmask_key)) { + devclass |= SDL_UDEV_DEVICE_MOUSE; // ID_INPUT_MOUSE + } else if (test_bit(BTN_TOUCH, bitmask_key)) { + /* TODO: better determining between touchscreen and multitouch touchpad, + see https://github.com/systemd/systemd/blob/master/src/udev/udev-builtin-input_id.c */ + devclass |= SDL_UDEV_DEVICE_TOUCHSCREEN; // ID_INPUT_TOUCHSCREEN + } + + if (test_bit(BTN_TRIGGER, bitmask_key) || + test_bit(BTN_A, bitmask_key) || + test_bit(BTN_1, bitmask_key) || + test_bit(ABS_RX, bitmask_abs) || + test_bit(ABS_RY, bitmask_abs) || + test_bit(ABS_RZ, bitmask_abs) || + test_bit(ABS_THROTTLE, bitmask_abs) || + test_bit(ABS_RUDDER, bitmask_abs) || + test_bit(ABS_WHEEL, bitmask_abs) || + test_bit(ABS_GAS, bitmask_abs) || + test_bit(ABS_BRAKE, bitmask_abs)) { + devclass |= SDL_UDEV_DEVICE_JOYSTICK; // ID_INPUT_JOYSTICK + } + } + + if (test_bit(EV_REL, bitmask_ev) && + test_bit(REL_X, bitmask_rel) && test_bit(REL_Y, bitmask_rel) && + test_bit(BTN_MOUSE, bitmask_key)) { + devclass |= SDL_UDEV_DEVICE_MOUSE; // ID_INPUT_MOUSE + } + + if (test_bit(EV_KEY, bitmask_ev)) { + unsigned i; + unsigned long found = 0; + + for (i = 0; i < BTN_MISC / BITS_PER_LONG; ++i) { + found |= bitmask_key[i]; + } + // If there are no keys in the lower block, check the higher blocks + if (!found) { + unsigned block; + for (block = 0; block < (sizeof(high_key_blocks) / sizeof(struct range)); ++block) { + for (i = high_key_blocks[block].start; i < high_key_blocks[block].end; ++i) { + if (test_bit(i, bitmask_key)) { + found = 1; + break; + } + } + } + } + + if (found > 0) { + devclass |= SDL_UDEV_DEVICE_HAS_KEYS; // ID_INPUT_KEY + } + } + + /* the first 32 bits are ESC, numbers, and Q to D, so if we have all of + * those, consider it to be a fully-featured keyboard; + * do not test KEY_RESERVED, though */ + keyboard_mask = 0xFFFFFFFE; + if ((bitmask_key[0] & keyboard_mask) == keyboard_mask) { + devclass |= SDL_UDEV_DEVICE_KEYBOARD; // ID_INPUT_KEYBOARD + } + + return devclass; +} + +#endif // HAVE_LINUX_INPUT_H diff --git a/thirdparty/sdl/core/linux/SDL_evdev_capabilities.h b/thirdparty/sdl/core/linux/SDL_evdev_capabilities.h new file mode 100644 index 00000000000..5a70bdd6911 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_evdev_capabilities.h @@ -0,0 +1,76 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + Copyright (C) 2020 Collabora Ltd. + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_evdev_capabilities_h_ +#define SDL_evdev_capabilities_h_ + +#ifdef HAVE_LINUX_INPUT_H + +#include + +#ifndef INPUT_PROP_SEMI_MT +#define INPUT_PROP_SEMI_MT 0x03 +#endif +#ifndef INPUT_PROP_TOPBUTTONPAD +#define INPUT_PROP_TOPBUTTONPAD 0x04 +#endif +#ifndef INPUT_PROP_POINTING_STICK +#define INPUT_PROP_POINTING_STICK 0x05 +#endif +#ifndef INPUT_PROP_ACCELEROMETER +#define INPUT_PROP_ACCELEROMETER 0x06 +#endif +#ifndef INPUT_PROP_MAX +#define INPUT_PROP_MAX 0x1f +#endif + +// A device can be any combination of these classes +typedef enum +{ + SDL_UDEV_DEVICE_UNKNOWN = 0x0000, + SDL_UDEV_DEVICE_MOUSE = 0x0001, + SDL_UDEV_DEVICE_KEYBOARD = 0x0002, + SDL_UDEV_DEVICE_JOYSTICK = 0x0004, + SDL_UDEV_DEVICE_SOUND = 0x0008, + SDL_UDEV_DEVICE_TOUCHSCREEN = 0x0010, + SDL_UDEV_DEVICE_ACCELEROMETER = 0x0020, + SDL_UDEV_DEVICE_TOUCHPAD = 0x0040, + SDL_UDEV_DEVICE_HAS_KEYS = 0x0080, + SDL_UDEV_DEVICE_VIDEO_CAPTURE = 0x0100, +} SDL_UDEV_deviceclass; + +#define BITS_PER_LONG (sizeof(unsigned long) * 8) +#define NBITS(x) ((((x)-1) / BITS_PER_LONG) + 1) +#define EVDEV_OFF(x) ((x) % BITS_PER_LONG) +#define EVDEV_LONG(x) ((x) / BITS_PER_LONG) +#define test_bit(bit, array) ((array[EVDEV_LONG(bit)] >> EVDEV_OFF(bit)) & 1) + +extern int SDL_EVDEV_GuessDeviceClass(const unsigned long bitmask_props[NBITS(INPUT_PROP_MAX)], + const unsigned long bitmask_ev[NBITS(EV_MAX)], + const unsigned long bitmask_abs[NBITS(ABS_MAX)], + const unsigned long bitmask_key[NBITS(KEY_MAX)], + const unsigned long bitmask_rel[NBITS(REL_MAX)]); + +#endif // HAVE_LINUX_INPUT_H + +#endif // SDL_evdev_capabilities_h_ diff --git a/thirdparty/sdl/core/linux/SDL_evdev_kbd.c b/thirdparty/sdl/core/linux/SDL_evdev_kbd.c new file mode 100644 index 00000000000..b1a56644af9 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_evdev_kbd.c @@ -0,0 +1,997 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_evdev_kbd.h" + +#ifdef SDL_INPUT_LINUXKD + +// This logic is adapted from drivers/tty/vt/keyboard.c in the Linux kernel source + +#include +#include +#include +#include +#include +#include +#include // for TIOCL_GETSHIFTSTATE + +#include + +#include "../../events/SDL_events_c.h" +#include "SDL_evdev_kbd_default_accents.h" +#include "SDL_evdev_kbd_default_keymap.h" + +// These are not defined in older Linux kernel headers +#ifndef K_UNICODE +#define K_UNICODE 0x03 +#endif +#ifndef K_OFF +#define K_OFF 0x04 +#endif + +/* + * Handler Tables. + */ + +#define K_HANDLERS \ + k_self, k_fn, k_spec, k_pad, \ + k_dead, k_cons, k_cur, k_shift, \ + k_meta, k_ascii, k_lock, k_lowercase, \ + k_slock, k_dead2, k_brl, k_ignore + +typedef void(k_handler_fn)(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag); +static k_handler_fn K_HANDLERS; +static k_handler_fn *k_handler[16] = { K_HANDLERS }; + +typedef void(fn_handler_fn)(SDL_EVDEV_keyboard_state *kbd); +static void fn_enter(SDL_EVDEV_keyboard_state *kbd); +static void fn_caps_toggle(SDL_EVDEV_keyboard_state *kbd); +static void fn_caps_on(SDL_EVDEV_keyboard_state *kbd); +static void fn_num(SDL_EVDEV_keyboard_state *kbd); +static void fn_compose(SDL_EVDEV_keyboard_state *kbd); + +static fn_handler_fn *fn_handler[] = { + NULL, fn_enter, NULL, NULL, + NULL, NULL, NULL, fn_caps_toggle, + fn_num, NULL, NULL, NULL, + NULL, fn_caps_on, fn_compose, NULL, + NULL, NULL, NULL, fn_num +}; + +/* + * Keyboard State + */ + +struct SDL_EVDEV_keyboard_state +{ + int console_fd; + bool muted; + int old_kbd_mode; + unsigned short **key_maps; + unsigned char shift_down[NR_SHIFT]; // shift state counters.. + bool dead_key_next; + int npadch; // -1 or number assembled on pad + struct kbdiacrs *accents; + unsigned int diacr; + bool rep; // flag telling character repeat + unsigned char lockstate; + unsigned char slockstate; + unsigned char ledflagstate; + char shift_state; + char text[128]; + unsigned int text_len; + void (*vt_release_callback)(void *); + void *vt_release_callback_data; + void (*vt_acquire_callback)(void *); + void *vt_acquire_callback_data; +}; + +#ifdef DUMP_ACCENTS +static void SDL_EVDEV_dump_accents(SDL_EVDEV_keyboard_state *kbd) +{ + unsigned int i; + + printf("static struct kbdiacrs default_accents = {\n"); + printf(" %d,\n", kbd->accents->kb_cnt); + printf(" {\n"); + for (i = 0; i < kbd->accents->kb_cnt; ++i) { + struct kbdiacr *diacr = &kbd->accents->kbdiacr[i]; + printf(" { 0x%.2x, 0x%.2x, 0x%.2x },\n", + diacr->diacr, diacr->base, diacr->result); + } + while (i < 256) { + printf(" { 0x00, 0x00, 0x00 },\n"); + ++i; + } + printf(" }\n"); + printf("};\n"); +} +#endif // DUMP_ACCENTS + +#ifdef DUMP_KEYMAP +static void SDL_EVDEV_dump_keymap(SDL_EVDEV_keyboard_state *kbd) +{ + int i, j; + + for (i = 0; i < MAX_NR_KEYMAPS; ++i) { + if (kbd->key_maps[i]) { + printf("static unsigned short default_key_map_%d[NR_KEYS] = {", i); + for (j = 0; j < NR_KEYS; ++j) { + if ((j % 8) == 0) { + printf("\n "); + } + printf("0x%.4x, ", kbd->key_maps[i][j]); + } + printf("\n};\n"); + } + } + printf("\n"); + printf("static unsigned short *default_key_maps[MAX_NR_KEYMAPS] = {\n"); + for (i = 0; i < MAX_NR_KEYMAPS; ++i) { + if (kbd->key_maps[i]) { + printf(" default_key_map_%d,\n", i); + } else { + printf(" NULL,\n"); + } + } + printf("};\n"); +} +#endif // DUMP_KEYMAP + +static SDL_EVDEV_keyboard_state *kbd_cleanup_state = NULL; +static int kbd_cleanup_sigactions_installed = 0; +static int kbd_cleanup_atexit_installed = 0; + +static struct sigaction old_sigaction[NSIG]; + +static int fatal_signals[] = { + // Handlers for SIGTERM and SIGINT are installed in SDL_InitQuit. + SIGHUP, SIGQUIT, SIGILL, SIGABRT, + SIGFPE, SIGSEGV, SIGPIPE, SIGBUS, + SIGSYS +}; + +static void kbd_cleanup(void) +{ + SDL_EVDEV_keyboard_state *kbd = kbd_cleanup_state; + if (!kbd) { + return; + } + kbd_cleanup_state = NULL; + + ioctl(kbd->console_fd, KDSKBMODE, kbd->old_kbd_mode); +} + +static void SDL_EVDEV_kbd_reraise_signal(int sig) +{ + (void)raise(sig); +} + +static siginfo_t *SDL_EVDEV_kdb_cleanup_siginfo = NULL; +static void *SDL_EVDEV_kdb_cleanup_ucontext = NULL; + +static void kbd_cleanup_signal_action(int signum, siginfo_t *info, void *ucontext) +{ + struct sigaction *old_action_p = &(old_sigaction[signum]); + sigset_t sigset; + + // Restore original signal handler before going any further. + sigaction(signum, old_action_p, NULL); + + // Unmask current signal. + sigemptyset(&sigset); + sigaddset(&sigset, signum); + sigprocmask(SIG_UNBLOCK, &sigset, NULL); + + // Save original signal info and context for archeologists. + SDL_EVDEV_kdb_cleanup_siginfo = info; + SDL_EVDEV_kdb_cleanup_ucontext = ucontext; + + // Restore keyboard. + kbd_cleanup(); + + // Reraise signal. + SDL_EVDEV_kbd_reraise_signal(signum); +} + +static void kbd_unregister_emerg_cleanup(void) +{ + int tabidx; + + kbd_cleanup_state = NULL; + + if (!kbd_cleanup_sigactions_installed) { + return; + } + kbd_cleanup_sigactions_installed = 0; + + for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) { + struct sigaction *old_action_p; + struct sigaction cur_action; + int signum = fatal_signals[tabidx]; + old_action_p = &(old_sigaction[signum]); + + // Examine current signal action + if (sigaction(signum, NULL, &cur_action)) { + continue; + } + + // Check if action installed and not modified + if (!(cur_action.sa_flags & SA_SIGINFO) || cur_action.sa_sigaction != &kbd_cleanup_signal_action) { + continue; + } + + // Restore original action + sigaction(signum, old_action_p, NULL); + } +} + +static void kbd_cleanup_atexit(void) +{ + // Restore keyboard. + kbd_cleanup(); + + // Try to restore signal handlers in case shared library is being unloaded + kbd_unregister_emerg_cleanup(); +} + +static void kbd_register_emerg_cleanup(SDL_EVDEV_keyboard_state *kbd) +{ + int tabidx; + + if (kbd_cleanup_state) { + return; + } + kbd_cleanup_state = kbd; + + if (!kbd_cleanup_atexit_installed) { + /* Since glibc 2.2.3, atexit() (and on_exit(3)) can be used within a shared library to establish + * functions that are called when the shared library is unloaded. + * -- man atexit(3) + */ + (void)atexit(kbd_cleanup_atexit); + kbd_cleanup_atexit_installed = 1; + } + + if (kbd_cleanup_sigactions_installed) { + return; + } + kbd_cleanup_sigactions_installed = 1; + + for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) { + struct sigaction *old_action_p; + struct sigaction new_action; + int signum = fatal_signals[tabidx]; + old_action_p = &(old_sigaction[signum]); + if (sigaction(signum, NULL, old_action_p)) { + continue; + } + + /* Skip SIGHUP and SIGPIPE if handler is already installed + * - assume the handler will do the cleanup + */ + if ((signum == SIGHUP || signum == SIGPIPE) && (old_action_p->sa_handler != SIG_DFL || (void (*)(int))old_action_p->sa_sigaction != SIG_DFL)) { + continue; + } + + new_action = *old_action_p; + new_action.sa_flags |= SA_SIGINFO; + new_action.sa_sigaction = &kbd_cleanup_signal_action; + sigaction(signum, &new_action, NULL); + } +} + +enum { + VT_SIGNAL_NONE, + VT_SIGNAL_RELEASE, + VT_SIGNAL_ACQUIRE, +}; +static int vt_release_signal; +static int vt_acquire_signal; +static SDL_AtomicInt vt_signal_pending; + +typedef void (*signal_handler)(int signum); + +static void kbd_vt_release_signal_action(int signum) +{ + SDL_SetAtomicInt(&vt_signal_pending, VT_SIGNAL_RELEASE); +} + +static void kbd_vt_acquire_signal_action(int signum) +{ + SDL_SetAtomicInt(&vt_signal_pending, VT_SIGNAL_ACQUIRE); +} + +static bool setup_vt_signal(int signum, signal_handler handler) +{ + struct sigaction *old_action_p; + struct sigaction new_action; + old_action_p = &(old_sigaction[signum]); + SDL_zero(new_action); + new_action.sa_handler = handler; + new_action.sa_flags = SA_RESTART; + if (sigaction(signum, &new_action, old_action_p) < 0) { + return false; + } + if (old_action_p->sa_handler != SIG_DFL) { + // This signal is already in use + sigaction(signum, old_action_p, NULL); + return false; + } + return true; +} + +static int find_free_signal(signal_handler handler) +{ +#ifdef SIGRTMIN + int i; + + for (i = SIGRTMIN + 2; i <= SIGRTMAX; ++i) { + if (setup_vt_signal(i, handler)) { + return i; + } + } +#endif + if (setup_vt_signal(SIGUSR1, handler)) { + return SIGUSR1; + } + if (setup_vt_signal(SIGUSR2, handler)) { + return SIGUSR2; + } + return 0; +} + +static void kbd_vt_quit(int console_fd) +{ + struct vt_mode mode; + + if (vt_release_signal) { + sigaction(vt_release_signal, &old_sigaction[vt_release_signal], NULL); + vt_release_signal = 0; + } + if (vt_acquire_signal) { + sigaction(vt_acquire_signal, &old_sigaction[vt_acquire_signal], NULL); + vt_acquire_signal = 0; + } + + SDL_zero(mode); + mode.mode = VT_AUTO; + ioctl(console_fd, VT_SETMODE, &mode); +} + +static bool kbd_vt_init(int console_fd) +{ + struct vt_mode mode; + + vt_release_signal = find_free_signal(kbd_vt_release_signal_action); + vt_acquire_signal = find_free_signal(kbd_vt_acquire_signal_action); + if (!vt_release_signal || !vt_acquire_signal ) { + kbd_vt_quit(console_fd); + return false; + } + + SDL_zero(mode); + mode.mode = VT_PROCESS; + mode.relsig = vt_release_signal; + mode.acqsig = vt_acquire_signal; + mode.frsig = SIGIO; + if (ioctl(console_fd, VT_SETMODE, &mode) < 0) { + kbd_vt_quit(console_fd); + return false; + } + return true; +} + +static void kbd_vt_update(SDL_EVDEV_keyboard_state *state) +{ + int signal_pending = SDL_GetAtomicInt(&vt_signal_pending); + if (signal_pending != VT_SIGNAL_NONE) { + if (signal_pending == VT_SIGNAL_RELEASE) { + if (state->vt_release_callback) { + state->vt_release_callback(state->vt_release_callback_data); + } + ioctl(state->console_fd, VT_RELDISP, 1); + } else { + if (state->vt_acquire_callback) { + state->vt_acquire_callback(state->vt_acquire_callback_data); + } + ioctl(state->console_fd, VT_RELDISP, VT_ACKACQ); + } + SDL_CompareAndSwapAtomicInt(&vt_signal_pending, signal_pending, VT_SIGNAL_NONE); + } +} + +SDL_EVDEV_keyboard_state *SDL_EVDEV_kbd_init(void) +{ + SDL_EVDEV_keyboard_state *kbd; + char flag_state; + char kbtype; + char shift_state[sizeof(long)] = { TIOCL_GETSHIFTSTATE, 0 }; + + kbd = (SDL_EVDEV_keyboard_state *)SDL_calloc(1, sizeof(*kbd)); + if (!kbd) { + return NULL; + } + + // This might fail if we're not connected to a tty (e.g. on the Steam Link) + kbd->console_fd = open("/dev/tty", O_RDONLY | O_CLOEXEC); + if (!((ioctl(kbd->console_fd, KDGKBTYPE, &kbtype) == 0) && ((kbtype == KB_101) || (kbtype == KB_84)))) { + close(kbd->console_fd); + kbd->console_fd = -1; + } + + kbd->npadch = -1; + + if (ioctl(kbd->console_fd, TIOCLINUX, shift_state) == 0) { + kbd->shift_state = *shift_state; + } + + if (ioctl(kbd->console_fd, KDGKBLED, &flag_state) == 0) { + kbd->ledflagstate = flag_state; + } + + kbd->accents = &default_accents; + kbd->key_maps = default_key_maps; + + if (ioctl(kbd->console_fd, KDGKBMODE, &kbd->old_kbd_mode) == 0) { + // Set the keyboard in UNICODE mode and load the keymaps + ioctl(kbd->console_fd, KDSKBMODE, K_UNICODE); + } + + kbd_vt_init(kbd->console_fd); + + return kbd; +} + +void SDL_EVDEV_kbd_set_muted(SDL_EVDEV_keyboard_state *state, bool muted) +{ + if (!state) { + return; + } + + if (muted == state->muted) { + return; + } + + if (muted) { + if (SDL_GetHintBoolean(SDL_HINT_MUTE_CONSOLE_KEYBOARD, true)) { + /* Mute the keyboard so keystrokes only generate evdev events + * and do not leak through to the console + */ + ioctl(state->console_fd, KDSKBMODE, K_OFF); + + /* Make sure to restore keyboard if application fails to call + * SDL_Quit before exit or fatal signal is raised. + */ + if (!SDL_GetHintBoolean(SDL_HINT_NO_SIGNAL_HANDLERS, false)) { + kbd_register_emerg_cleanup(state); + } + } + } else { + kbd_unregister_emerg_cleanup(); + + // Restore the original keyboard mode + ioctl(state->console_fd, KDSKBMODE, state->old_kbd_mode); + } + state->muted = muted; +} + +void SDL_EVDEV_kbd_set_vt_switch_callbacks(SDL_EVDEV_keyboard_state *state, void (*release_callback)(void*), void *release_callback_data, void (*acquire_callback)(void*), void *acquire_callback_data) +{ + if (state == NULL) { + return; + } + + state->vt_release_callback = release_callback; + state->vt_release_callback_data = release_callback_data; + state->vt_acquire_callback = acquire_callback; + state->vt_acquire_callback_data = acquire_callback_data; +} + +void SDL_EVDEV_kbd_update(SDL_EVDEV_keyboard_state *state) +{ + if (!state) { + return; + } + + kbd_vt_update(state); +} + +void SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *state) +{ + if (state == NULL) { + return; + } + + SDL_EVDEV_kbd_set_muted(state, false); + + kbd_vt_quit(state->console_fd); + + if (state->console_fd >= 0) { + close(state->console_fd); + state->console_fd = -1; + } + + if (state->key_maps && state->key_maps != default_key_maps) { + int i; + for (i = 0; i < MAX_NR_KEYMAPS; ++i) { + if (state->key_maps[i]) { + SDL_free(state->key_maps[i]); + } + } + SDL_free(state->key_maps); + } + + SDL_free(state); +} + +/* + * Helper Functions. + */ +static void put_queue(SDL_EVDEV_keyboard_state *kbd, uint c) +{ + // c is already part of a UTF-8 sequence and safe to add as a character + if (kbd->text_len < (sizeof(kbd->text) - 1)) { + kbd->text[kbd->text_len++] = (char)c; + } +} + +static void put_utf8(SDL_EVDEV_keyboard_state *kbd, uint c) +{ + if (c < 0x80) { + put_queue(kbd, c); /* 0******* */ + } else if (c < 0x800) { + /* 110***** 10****** */ + put_queue(kbd, 0xc0 | (c >> 6)); + put_queue(kbd, 0x80 | (c & 0x3f)); + } else if (c < 0x10000) { + if (c >= 0xD800 && c < 0xE000) { + return; + } + if (c == 0xFFFF) { + return; + } + /* 1110**** 10****** 10****** */ + put_queue(kbd, 0xe0 | (c >> 12)); + put_queue(kbd, 0x80 | ((c >> 6) & 0x3f)); + put_queue(kbd, 0x80 | (c & 0x3f)); + } else if (c < 0x110000) { + /* 11110*** 10****** 10****** 10****** */ + put_queue(kbd, 0xf0 | (c >> 18)); + put_queue(kbd, 0x80 | ((c >> 12) & 0x3f)); + put_queue(kbd, 0x80 | ((c >> 6) & 0x3f)); + put_queue(kbd, 0x80 | (c & 0x3f)); + } +} + +/* + * We have a combining character DIACR here, followed by the character CH. + * If the combination occurs in the table, return the corresponding value. + * Otherwise, if CH is a space or equals DIACR, return DIACR. + * Otherwise, conclude that DIACR was not combining after all, + * queue it and return CH. + */ +static unsigned int handle_diacr(SDL_EVDEV_keyboard_state *kbd, unsigned int ch) +{ + unsigned int d = kbd->diacr; + unsigned int i; + + kbd->diacr = 0; + + if (kbd->console_fd >= 0) + if (ioctl(kbd->console_fd, KDGKBDIACR, kbd->accents) < 0) { + // No worries, we'll use the default accent table + } + + for (i = 0; i < kbd->accents->kb_cnt; i++) { + if (kbd->accents->kbdiacr[i].diacr == d && + kbd->accents->kbdiacr[i].base == ch) { + return kbd->accents->kbdiacr[i].result; + } + } + + if (ch == ' ' || ch == d) { + return d; + } + + put_utf8(kbd, d); + + return ch; +} + +static bool vc_kbd_led(SDL_EVDEV_keyboard_state *kbd, int flag) +{ + return (kbd->ledflagstate & flag) != 0; +} + +static void set_vc_kbd_led(SDL_EVDEV_keyboard_state *kbd, int flag) +{ + kbd->ledflagstate |= flag; + ioctl(kbd->console_fd, KDSETLED, (unsigned long)(kbd->ledflagstate)); +} + +static void clr_vc_kbd_led(SDL_EVDEV_keyboard_state *kbd, int flag) +{ + kbd->ledflagstate &= ~flag; + ioctl(kbd->console_fd, KDSETLED, (unsigned long)(kbd->ledflagstate)); +} + +static void chg_vc_kbd_lock(SDL_EVDEV_keyboard_state *kbd, int flag) +{ + kbd->lockstate ^= 1 << flag; +} + +static void chg_vc_kbd_slock(SDL_EVDEV_keyboard_state *kbd, int flag) +{ + kbd->slockstate ^= 1 << flag; +} + +static void chg_vc_kbd_led(SDL_EVDEV_keyboard_state *kbd, int flag) +{ + kbd->ledflagstate ^= flag; + ioctl(kbd->console_fd, KDSETLED, (unsigned long)(kbd->ledflagstate)); +} + +/* + * Special function handlers + */ + +static void fn_enter(SDL_EVDEV_keyboard_state *kbd) +{ + if (kbd->diacr) { + put_utf8(kbd, kbd->diacr); + kbd->diacr = 0; + } +} + +static void fn_caps_toggle(SDL_EVDEV_keyboard_state *kbd) +{ + if (kbd->rep) { + return; + } + + chg_vc_kbd_led(kbd, K_CAPSLOCK); +} + +static void fn_caps_on(SDL_EVDEV_keyboard_state *kbd) +{ + if (kbd->rep) { + return; + } + + set_vc_kbd_led(kbd, K_CAPSLOCK); +} + +static void fn_num(SDL_EVDEV_keyboard_state *kbd) +{ + if (!kbd->rep) { + chg_vc_kbd_led(kbd, K_NUMLOCK); + } +} + +static void fn_compose(SDL_EVDEV_keyboard_state *kbd) +{ + kbd->dead_key_next = true; +} + +/* + * Special key handlers + */ + +static void k_ignore(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ +} + +static void k_spec(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ + if (up_flag) { + return; + } + if (value >= SDL_arraysize(fn_handler)) { + return; + } + if (fn_handler[value]) { + fn_handler[value](kbd); + } +} + +static void k_lowercase(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ +} + +static void k_self(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ + if (up_flag) { + return; // no action, if this is a key release + } + + if (kbd->diacr) { + value = handle_diacr(kbd, value); + } + + if (kbd->dead_key_next) { + kbd->dead_key_next = false; + kbd->diacr = value; + return; + } + put_utf8(kbd, value); +} + +static void k_deadunicode(SDL_EVDEV_keyboard_state *kbd, unsigned int value, char up_flag) +{ + if (up_flag) { + return; + } + + kbd->diacr = (kbd->diacr ? handle_diacr(kbd, value) : value); +} + +static void k_dead(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ + const unsigned char ret_diacr[NR_DEAD] = { '`', '\'', '^', '~', '"', ',' }; + + k_deadunicode(kbd, ret_diacr[value], up_flag); +} + +static void k_dead2(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ + k_deadunicode(kbd, value, up_flag); +} + +static void k_cons(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ +} + +static void k_fn(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ +} + +static void k_cur(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ +} + +static void k_pad(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ + static const char pad_chars[] = "0123456789+-*/\015,.?()#"; + + if (up_flag) { + return; // no action, if this is a key release + } + + if (!vc_kbd_led(kbd, K_NUMLOCK)) { + // unprintable action + return; + } + + put_queue(kbd, pad_chars[value]); +} + +static void k_shift(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ + int old_state = kbd->shift_state; + + if (kbd->rep) { + return; + } + /* + * Mimic typewriter: + * a CapsShift key acts like Shift but undoes CapsLock + */ + if (value == KVAL(K_CAPSSHIFT)) { + value = KVAL(K_SHIFT); + if (!up_flag) { + clr_vc_kbd_led(kbd, K_CAPSLOCK); + } + } + + if (up_flag) { + /* + * handle the case that two shift or control + * keys are depressed simultaneously + */ + if (kbd->shift_down[value]) { + kbd->shift_down[value]--; + } + } else { + kbd->shift_down[value]++; + } + + if (kbd->shift_down[value]) { + kbd->shift_state |= (1 << value); + } else { + kbd->shift_state &= ~(1 << value); + } + + // kludge + if (up_flag && kbd->shift_state != old_state && kbd->npadch != -1) { + put_utf8(kbd, kbd->npadch); + kbd->npadch = -1; + } +} + +static void k_meta(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ +} + +static void k_ascii(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ + int base; + + if (up_flag) { + return; + } + + if (value < 10) { + // decimal input of code, while Alt depressed + base = 10; + } else { + // hexadecimal input of code, while AltGr depressed + value -= 10; + base = 16; + } + + if (kbd->npadch == -1) { + kbd->npadch = value; + } else { + kbd->npadch = kbd->npadch * base + value; + } +} + +static void k_lock(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ + if (up_flag || kbd->rep) { + return; + } + + chg_vc_kbd_lock(kbd, value); +} + +static void k_slock(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ + k_shift(kbd, value, up_flag); + if (up_flag || kbd->rep) { + return; + } + + chg_vc_kbd_slock(kbd, value); + // try to make Alt, oops, AltGr and such work + if (!kbd->key_maps[kbd->lockstate ^ kbd->slockstate]) { + kbd->slockstate = 0; + chg_vc_kbd_slock(kbd, value); + } +} + +static void k_brl(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) +{ +} + +void SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *state, unsigned int keycode, int down) +{ + unsigned char shift_final; + unsigned char type; + unsigned short *key_map; + unsigned short keysym; + + if (!state) { + return; + } + + state->rep = (down == 2); + + shift_final = (state->shift_state | state->slockstate) ^ state->lockstate; + key_map = state->key_maps[shift_final]; + if (!key_map) { + // Unsupported shift state (e.g. ctrl = 4, alt = 8), just reset to the default state + state->shift_state = 0; + state->slockstate = 0; + state->lockstate = 0; + return; + } + + if (keycode < NR_KEYS) { + if (state->console_fd < 0) { + keysym = key_map[keycode]; + } else { + struct kbentry kbe; + kbe.kb_table = shift_final; + kbe.kb_index = keycode; + if (ioctl(state->console_fd, KDGKBENT, &kbe) == 0) + keysym = (kbe.kb_value ^ 0xf000); + else + return; + } + } else { + return; + } + + type = KTYP(keysym); + + if (type < 0xf0) { + if (down) { + put_utf8(state, keysym); + } + } else { + type -= 0xf0; + + // if type is KT_LETTER then it can be affected by Caps Lock + if (type == KT_LETTER) { + type = KT_LATIN; + + if (vc_kbd_led(state, K_CAPSLOCK)) { + shift_final = shift_final ^ (1 << KG_SHIFT); + key_map = state->key_maps[shift_final]; + if (key_map) { + if (state->console_fd < 0) { + keysym = key_map[keycode]; + } else { + struct kbentry kbe; + kbe.kb_table = shift_final; + kbe.kb_index = keycode; + if (ioctl(state->console_fd, KDGKBENT, &kbe) == 0) + keysym = (kbe.kb_value ^ 0xf000); + } + } + } + } + + (*k_handler[type])(state, keysym & 0xff, !down); + + if (type != KT_SLOCK) { + state->slockstate = 0; + } + } + + if (state->text_len > 0) { + state->text[state->text_len] = '\0'; + SDL_SendKeyboardText(state->text); + state->text_len = 0; + } +} + +#elif !defined(SDL_INPUT_FBSDKBIO) // !SDL_INPUT_LINUXKD + +SDL_EVDEV_keyboard_state *SDL_EVDEV_kbd_init(void) +{ + return NULL; +} + +void SDL_EVDEV_kbd_set_muted(SDL_EVDEV_keyboard_state *state, bool muted) +{ +} + +void SDL_EVDEV_kbd_set_vt_switch_callbacks(SDL_EVDEV_keyboard_state *state, void (*release_callback)(void*), void *release_callback_data, void (*acquire_callback)(void*), void *acquire_callback_data) +{ +} + +void SDL_EVDEV_kbd_update(SDL_EVDEV_keyboard_state *state) +{ +} + +void SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *state, unsigned int keycode, int down) +{ +} + +void SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *state) +{ +} + +#endif // SDL_INPUT_LINUXKD diff --git a/thirdparty/sdl/core/linux/SDL_evdev_kbd.h b/thirdparty/sdl/core/linux/SDL_evdev_kbd.h new file mode 100644 index 00000000000..6ea19fb05a7 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_evdev_kbd.h @@ -0,0 +1,35 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_evdev_kbd_h_ +#define SDL_evdev_kbd_h_ + +struct SDL_EVDEV_keyboard_state; +typedef struct SDL_EVDEV_keyboard_state SDL_EVDEV_keyboard_state; + +extern SDL_EVDEV_keyboard_state *SDL_EVDEV_kbd_init(void); +extern void SDL_EVDEV_kbd_set_muted(SDL_EVDEV_keyboard_state *state, bool muted); +extern void SDL_EVDEV_kbd_set_vt_switch_callbacks(SDL_EVDEV_keyboard_state *state, void (*release_callback)(void*), void *release_callback_data, void (*acquire_callback)(void*), void *acquire_callback_data); +extern void SDL_EVDEV_kbd_update(SDL_EVDEV_keyboard_state *state); +extern void SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *state, unsigned int keycode, int down); +extern void SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *state); + +#endif // SDL_evdev_kbd_h_ diff --git a/thirdparty/sdl/core/linux/SDL_evdev_kbd_default_accents.h b/thirdparty/sdl/core/linux/SDL_evdev_kbd_default_accents.h new file mode 100644 index 00000000000..b6d034c4928 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_evdev_kbd_default_accents.h @@ -0,0 +1,282 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +static struct kbdiacrs default_accents = { + 68, + { + { 0x60, 0x41, 0xc0 }, + { 0x60, 0x61, 0xe0 }, + { 0x27, 0x41, 0xc1 }, + { 0x27, 0x61, 0xe1 }, + { 0x5e, 0x41, 0xc2 }, + { 0x5e, 0x61, 0xe2 }, + { 0x7e, 0x41, 0xc3 }, + { 0x7e, 0x61, 0xe3 }, + { 0x22, 0x41, 0xc4 }, + { 0x22, 0x61, 0xe4 }, + { 0x4f, 0x41, 0xc5 }, + { 0x6f, 0x61, 0xe5 }, + { 0x30, 0x41, 0xc5 }, + { 0x30, 0x61, 0xe5 }, + { 0x41, 0x41, 0xc5 }, + { 0x61, 0x61, 0xe5 }, + { 0x41, 0x45, 0xc6 }, + { 0x61, 0x65, 0xe6 }, + { 0x2c, 0x43, 0xc7 }, + { 0x2c, 0x63, 0xe7 }, + { 0x60, 0x45, 0xc8 }, + { 0x60, 0x65, 0xe8 }, + { 0x27, 0x45, 0xc9 }, + { 0x27, 0x65, 0xe9 }, + { 0x5e, 0x45, 0xca }, + { 0x5e, 0x65, 0xea }, + { 0x22, 0x45, 0xcb }, + { 0x22, 0x65, 0xeb }, + { 0x60, 0x49, 0xcc }, + { 0x60, 0x69, 0xec }, + { 0x27, 0x49, 0xcd }, + { 0x27, 0x69, 0xed }, + { 0x5e, 0x49, 0xce }, + { 0x5e, 0x69, 0xee }, + { 0x22, 0x49, 0xcf }, + { 0x22, 0x69, 0xef }, + { 0x2d, 0x44, 0xd0 }, + { 0x2d, 0x64, 0xf0 }, + { 0x7e, 0x4e, 0xd1 }, + { 0x7e, 0x6e, 0xf1 }, + { 0x60, 0x4f, 0xd2 }, + { 0x60, 0x6f, 0xf2 }, + { 0x27, 0x4f, 0xd3 }, + { 0x27, 0x6f, 0xf3 }, + { 0x5e, 0x4f, 0xd4 }, + { 0x5e, 0x6f, 0xf4 }, + { 0x7e, 0x4f, 0xd5 }, + { 0x7e, 0x6f, 0xf5 }, + { 0x22, 0x4f, 0xd6 }, + { 0x22, 0x6f, 0xf6 }, + { 0x2f, 0x4f, 0xd8 }, + { 0x2f, 0x6f, 0xf8 }, + { 0x60, 0x55, 0xd9 }, + { 0x60, 0x75, 0xf9 }, + { 0x27, 0x55, 0xda }, + { 0x27, 0x75, 0xfa }, + { 0x5e, 0x55, 0xdb }, + { 0x5e, 0x75, 0xfb }, + { 0x22, 0x55, 0xdc }, + { 0x22, 0x75, 0xfc }, + { 0x27, 0x59, 0xdd }, + { 0x27, 0x79, 0xfd }, + { 0x54, 0x48, 0xde }, + { 0x74, 0x68, 0xfe }, + { 0x73, 0x73, 0xdf }, + { 0x22, 0x79, 0xff }, + { 0x73, 0x7a, 0xdf }, + { 0x69, 0x6a, 0xff }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + { 0x00, 0x00, 0x00 }, + } +}; diff --git a/thirdparty/sdl/core/linux/SDL_evdev_kbd_default_keymap.h b/thirdparty/sdl/core/linux/SDL_evdev_kbd_default_keymap.h new file mode 100644 index 00000000000..05294546a29 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_evdev_kbd_default_keymap.h @@ -0,0 +1,4765 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* *INDENT-OFF* */ /* clang-format off */ + +static unsigned short default_key_map_0[NR_KEYS] = { + 0xf200, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +}; +static unsigned short default_key_map_1[NR_KEYS] = { + 0xf200, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, + 0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, + 0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, + 0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +}; +static unsigned short default_key_map_2[NR_KEYS] = { + 0xf200, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, + 0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +}; +static unsigned short default_key_map_3[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +#ifdef INCLUDE_EXTENDED_KEYMAP +static unsigned short default_key_map_4[NR_KEYS] = { + 0xf200, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, + 0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, + 0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +}; +static unsigned short default_key_map_5[NR_KEYS] = { + 0xf200, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, + 0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, + 0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +}; +static unsigned short default_key_map_6[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_7[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_8[NR_KEYS] = { + 0xf200, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, + 0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, + 0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, + 0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +}; +static unsigned short default_key_map_9[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, + 0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_10[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_11[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_12[NR_KEYS] = { + 0xf200, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +}; +static unsigned short default_key_map_13[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_14[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_15[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_16[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_17[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, + 0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, + 0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_18[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, + 0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_19[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_20[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, + 0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, + 0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_21[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, + 0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, + 0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_22[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_23[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_24[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, + 0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, + 0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, + 0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_25[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, + 0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_26[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_27[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_28[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_29[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_30[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_31[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_32[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_33[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, + 0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, + 0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_34[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, + 0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_35[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_36[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, + 0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, + 0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_37[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, + 0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, + 0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_38[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_39[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_40[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, + 0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, + 0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, + 0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_41[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, + 0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_42[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_43[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_44[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_45[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_46[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_47[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_48[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_49[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, + 0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, + 0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_50[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, + 0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_51[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_52[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, + 0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, + 0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_53[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, + 0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, + 0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_54[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_55[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_56[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, + 0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, + 0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, + 0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_57[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, + 0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_58[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_59[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_60[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_61[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_62[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_63[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_64[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_65[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, + 0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, + 0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_66[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, + 0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_67[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_68[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, + 0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, + 0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_69[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, + 0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, + 0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_70[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_71[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_72[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, + 0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, + 0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, + 0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_73[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, + 0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_74[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_75[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_76[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_77[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_78[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_79[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_80[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_81[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, + 0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, + 0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_82[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, + 0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_83[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_84[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, + 0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, + 0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_85[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, + 0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, + 0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_86[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_87[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_88[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, + 0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, + 0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, + 0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_89[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, + 0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_90[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_91[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_92[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_93[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_94[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_95[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_96[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_97[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, + 0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, + 0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_98[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, + 0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_99[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_100[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, + 0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, + 0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_101[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, + 0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, + 0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_102[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_103[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_104[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, + 0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, + 0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, + 0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_105[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, + 0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_106[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_107[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_108[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_109[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_110[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_111[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_112[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_113[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, + 0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, + 0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_114[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, + 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, + 0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, + 0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, + 0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, + 0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, + 0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, + 0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_115[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, + 0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, + 0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, + 0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, + 0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, + 0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, + 0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, + 0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_116[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, + 0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, + 0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_117[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, + 0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, + 0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_118[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_119[NR_KEYS] = { + 0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, + 0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, + 0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, + 0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, + 0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, + 0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, + 0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, + 0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, + 0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_120[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, + 0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, + 0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, + 0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_121[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, + 0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, + 0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, + 0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_122[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, + 0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, + 0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, + 0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, + 0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, + 0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, + 0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_123[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, + 0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, + 0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, + 0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, + 0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, + 0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, + 0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, + 0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_124[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, + 0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, + 0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_125[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, + 0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, + 0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_126[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +static unsigned short default_key_map_127[NR_KEYS] = { + 0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, + 0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, + 0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, + 0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, + 0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, + 0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, + 0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, + 0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, + 0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, + 0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, + 0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, + 0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, + 0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, + 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, +}; +#endif /* INCLUDE_EXTENDED_KEYMAP */ + +/* *INDENT-ON* */ /* clang-format on */ + +static unsigned short *default_key_maps[MAX_NR_KEYMAPS] = { + default_key_map_0, + default_key_map_1, + default_key_map_2, + default_key_map_3, +#ifdef INCLUDE_EXTENDED_KEYMAP + default_key_map_4, + default_key_map_5, + default_key_map_6, + default_key_map_7, + default_key_map_8, + default_key_map_9, + default_key_map_10, + default_key_map_11, + default_key_map_12, + default_key_map_13, + default_key_map_14, + default_key_map_15, + default_key_map_16, + default_key_map_17, + default_key_map_18, + default_key_map_19, + default_key_map_20, + default_key_map_21, + default_key_map_22, + default_key_map_23, + default_key_map_24, + default_key_map_25, + default_key_map_26, + default_key_map_27, + default_key_map_28, + default_key_map_29, + default_key_map_30, + default_key_map_31, + default_key_map_32, + default_key_map_33, + default_key_map_34, + default_key_map_35, + default_key_map_36, + default_key_map_37, + default_key_map_38, + default_key_map_39, + default_key_map_40, + default_key_map_41, + default_key_map_42, + default_key_map_43, + default_key_map_44, + default_key_map_45, + default_key_map_46, + default_key_map_47, + default_key_map_48, + default_key_map_49, + default_key_map_50, + default_key_map_51, + default_key_map_52, + default_key_map_53, + default_key_map_54, + default_key_map_55, + default_key_map_56, + default_key_map_57, + default_key_map_58, + default_key_map_59, + default_key_map_60, + default_key_map_61, + default_key_map_62, + default_key_map_63, + default_key_map_64, + default_key_map_65, + default_key_map_66, + default_key_map_67, + default_key_map_68, + default_key_map_69, + default_key_map_70, + default_key_map_71, + default_key_map_72, + default_key_map_73, + default_key_map_74, + default_key_map_75, + default_key_map_76, + default_key_map_77, + default_key_map_78, + default_key_map_79, + default_key_map_80, + default_key_map_81, + default_key_map_82, + default_key_map_83, + default_key_map_84, + default_key_map_85, + default_key_map_86, + default_key_map_87, + default_key_map_88, + default_key_map_89, + default_key_map_90, + default_key_map_91, + default_key_map_92, + default_key_map_93, + default_key_map_94, + default_key_map_95, + default_key_map_96, + default_key_map_97, + default_key_map_98, + default_key_map_99, + default_key_map_100, + default_key_map_101, + default_key_map_102, + default_key_map_103, + default_key_map_104, + default_key_map_105, + default_key_map_106, + default_key_map_107, + default_key_map_108, + default_key_map_109, + default_key_map_110, + default_key_map_111, + default_key_map_112, + default_key_map_113, + default_key_map_114, + default_key_map_115, + default_key_map_116, + default_key_map_117, + default_key_map_118, + default_key_map_119, + default_key_map_120, + default_key_map_121, + default_key_map_122, + default_key_map_123, + default_key_map_124, + default_key_map_125, + default_key_map_126, + default_key_map_127, +#else /* !INCLUDE_EXTENDED_KEYMAP */ + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, +#endif /* INCLUDE_EXTENDED_KEYMAP */ + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, +}; diff --git a/thirdparty/sdl/core/linux/SDL_fcitx.c b/thirdparty/sdl/core/linux/SDL_fcitx.c new file mode 100644 index 00000000000..c6bce5f796d --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_fcitx.c @@ -0,0 +1,414 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include + +#include "SDL_fcitx.h" +//#include "../../video/SDL_sysvideo.h" +#include "SDL_dbus.h" + +#ifdef SDL_VIDEO_DRIVER_X11 +#include "../../video/x11/SDL_x11video.h" +#endif + +#define FCITX_DBUS_SERVICE "org.freedesktop.portal.Fcitx" + +#define FCITX_IM_DBUS_PATH "/org/freedesktop/portal/inputmethod" + +#define FCITX_IM_DBUS_INTERFACE "org.fcitx.Fcitx.InputMethod1" +#define FCITX_IC_DBUS_INTERFACE "org.fcitx.Fcitx.InputContext1" + +#define DBUS_TIMEOUT 500 + +typedef struct FcitxClient +{ + SDL_DBusContext *dbus; + + char *ic_path; + + int id; + + SDL_Rect cursor_rect; +} FcitxClient; + +static FcitxClient fcitx_client; + +static char *GetAppName(void) +{ +#if defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_FREEBSD) + char *spot; + char procfile[1024]; + char linkfile[1024]; + int linksize; + +#ifdef SDL_PLATFORM_LINUX + (void)SDL_snprintf(procfile, sizeof(procfile), "/proc/%d/exe", getpid()); +#elif defined(SDL_PLATFORM_FREEBSD) + (void)SDL_snprintf(procfile, sizeof(procfile), "/proc/%d/file", getpid()); +#endif + linksize = readlink(procfile, linkfile, sizeof(linkfile) - 1); + if (linksize > 0) { + linkfile[linksize] = '\0'; + spot = SDL_strrchr(linkfile, '/'); + if (spot) { + return SDL_strdup(spot + 1); + } else { + return SDL_strdup(linkfile); + } + } +#endif // SDL_PLATFORM_LINUX || SDL_PLATFORM_FREEBSD + + return SDL_strdup("SDL_App"); +} + +static size_t Fcitx_GetPreeditString(SDL_DBusContext *dbus, + DBusMessage *msg, + char **ret, + Sint32 *start_pos, + Sint32 *end_pos) +{ + char *text = NULL, *subtext; + size_t text_bytes = 0; + DBusMessageIter iter, array, sub; + Sint32 p_start_pos = -1; + Sint32 p_end_pos = -1; + + dbus->message_iter_init(msg, &iter); + // Message type is a(si)i, we only need string part + if (dbus->message_iter_get_arg_type(&iter) == DBUS_TYPE_ARRAY) { + size_t pos = 0; + // First pass: calculate string length + dbus->message_iter_recurse(&iter, &array); + while (dbus->message_iter_get_arg_type(&array) == DBUS_TYPE_STRUCT) { + dbus->message_iter_recurse(&array, &sub); + subtext = NULL; + if (dbus->message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) { + dbus->message_iter_get_basic(&sub, &subtext); + if (subtext && *subtext) { + text_bytes += SDL_strlen(subtext); + } + } + dbus->message_iter_next(&sub); + if (dbus->message_iter_get_arg_type(&sub) == DBUS_TYPE_INT32 && p_end_pos == -1) { + // Type is a bit field defined as follows: + // bit 3: Underline, bit 4: HighLight, bit 5: DontCommit, + // bit 6: Bold, bit 7: Strike, bit 8: Italic + Sint32 type; + dbus->message_iter_get_basic(&sub, &type); + // We only consider highlight + if (type & (1 << 4)) { + if (p_start_pos == -1) { + p_start_pos = pos; + } + } else if (p_start_pos != -1 && p_end_pos == -1) { + p_end_pos = pos; + } + } + dbus->message_iter_next(&array); + if (subtext && *subtext) { + pos += SDL_utf8strlen(subtext); + } + } + if (p_start_pos != -1 && p_end_pos == -1) { + p_end_pos = pos; + } + if (text_bytes) { + text = SDL_malloc(text_bytes + 1); + } + + if (text) { + char *pivot = text; + // Second pass: join all the sub string + dbus->message_iter_recurse(&iter, &array); + while (dbus->message_iter_get_arg_type(&array) == DBUS_TYPE_STRUCT) { + dbus->message_iter_recurse(&array, &sub); + if (dbus->message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) { + dbus->message_iter_get_basic(&sub, &subtext); + if (subtext && *subtext) { + size_t length = SDL_strlen(subtext); + SDL_strlcpy(pivot, subtext, length + 1); + pivot += length; + } + } + dbus->message_iter_next(&array); + } + } else { + text_bytes = 0; + } + } + + *ret = text; + *start_pos = p_start_pos; + *end_pos = p_end_pos; + return text_bytes; +} + +static Sint32 Fcitx_GetPreeditCursorByte(SDL_DBusContext *dbus, DBusMessage *msg) +{ + Sint32 byte = -1; + DBusMessageIter iter; + + dbus->message_iter_init(msg, &iter); + + dbus->message_iter_next(&iter); + + if (dbus->message_iter_get_arg_type(&iter) != DBUS_TYPE_INT32) { + return -1; + } + + dbus->message_iter_get_basic(&iter, &byte); + + return byte; +} + +static DBusHandlerResult DBus_MessageFilter(DBusConnection *conn, DBusMessage *msg, void *data) +{ + SDL_DBusContext *dbus = (SDL_DBusContext *)data; + + if (dbus->message_is_signal(msg, FCITX_IC_DBUS_INTERFACE, "CommitString")) { + DBusMessageIter iter; + const char *text = NULL; + + dbus->message_iter_init(msg, &iter); + dbus->message_iter_get_basic(&iter, &text); + + //SDL_SendKeyboardText(text); + + return DBUS_HANDLER_RESULT_HANDLED; + } + + if (dbus->message_is_signal(msg, FCITX_IC_DBUS_INTERFACE, "UpdateFormattedPreedit")) { + char *text = NULL; + Sint32 start_pos, end_pos; + size_t text_bytes = Fcitx_GetPreeditString(dbus, msg, &text, &start_pos, &end_pos); + if (text_bytes) { + if (start_pos == -1) { + Sint32 byte_pos = Fcitx_GetPreeditCursorByte(dbus, msg); + start_pos = byte_pos >= 0 ? SDL_utf8strnlen(text, byte_pos) : -1; + } + //SDL_SendEditingText(text, start_pos, end_pos >= 0 ? end_pos - start_pos : -1); + SDL_free(text); + } else { + //SDL_SendEditingText("", 0, 0); + } + + //SDL_Fcitx_UpdateTextInputArea(SDL_GetKeyboardFocus()); + return DBUS_HANDLER_RESULT_HANDLED; + } + + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +static void FcitxClientICCallMethod(FcitxClient *client, const char *method) +{ + if (!client->ic_path) { + return; + } + SDL_DBus_CallVoidMethod(FCITX_DBUS_SERVICE, client->ic_path, FCITX_IC_DBUS_INTERFACE, method, DBUS_TYPE_INVALID); +} + +static void SDLCALL Fcitx_SetCapabilities(void *data, + const char *name, + const char *old_val, + const char *hint) +{ + FcitxClient *client = (FcitxClient *)data; + Uint64 caps = 0; + if (!client->ic_path) { + return; + } + + if (hint && SDL_strstr(hint, "composition")) { + caps |= (1 << 1); // Preedit Flag + caps |= (1 << 4); // Formatted Preedit Flag + } + if (hint && SDL_strstr(hint, "candidates")) { + // FIXME, turn off native candidate rendering + } + + SDL_DBus_CallVoidMethod(FCITX_DBUS_SERVICE, client->ic_path, FCITX_IC_DBUS_INTERFACE, "SetCapability", DBUS_TYPE_UINT64, &caps, DBUS_TYPE_INVALID); +} + +static bool FcitxCreateInputContext(SDL_DBusContext *dbus, const char *appname, char **ic_path) +{ + const char *program = "program"; + bool result = false; + + if (dbus && dbus->session_conn) { + DBusMessage *msg = dbus->message_new_method_call(FCITX_DBUS_SERVICE, FCITX_IM_DBUS_PATH, FCITX_IM_DBUS_INTERFACE, "CreateInputContext"); + if (msg) { + DBusMessage *reply = NULL; + DBusMessageIter args, array, sub; + dbus->message_iter_init_append(msg, &args); + dbus->message_iter_open_container(&args, DBUS_TYPE_ARRAY, "(ss)", &array); + dbus->message_iter_open_container(&array, DBUS_TYPE_STRUCT, 0, &sub); + dbus->message_iter_append_basic(&sub, DBUS_TYPE_STRING, &program); + dbus->message_iter_append_basic(&sub, DBUS_TYPE_STRING, &appname); + dbus->message_iter_close_container(&array, &sub); + dbus->message_iter_close_container(&args, &array); + reply = dbus->connection_send_with_reply_and_block(dbus->session_conn, msg, 300, NULL); + if (reply) { + if (dbus->message_get_args(reply, NULL, DBUS_TYPE_OBJECT_PATH, ic_path, DBUS_TYPE_INVALID)) { + result = true; + } + dbus->message_unref(reply); + } + dbus->message_unref(msg); + } + } + return result; +} + +static bool FcitxClientCreateIC(FcitxClient *client) +{ + char *appname = GetAppName(); + char *ic_path = NULL; + SDL_DBusContext *dbus = client->dbus; + + // SDL_DBus_CallMethod cannot handle a(ss) type, call dbus function directly + if (!FcitxCreateInputContext(dbus, appname, &ic_path)) { + ic_path = NULL; // just in case. + } + + SDL_free(appname); + + if (ic_path) { + SDL_free(client->ic_path); + client->ic_path = SDL_strdup(ic_path); + + dbus->bus_add_match(dbus->session_conn, + "type='signal', interface='org.fcitx.Fcitx.InputContext1'", + NULL); + dbus->connection_add_filter(dbus->session_conn, + &DBus_MessageFilter, dbus, + NULL); + dbus->connection_flush(dbus->session_conn); + + SDL_AddHintCallback(SDL_HINT_IME_IMPLEMENTED_UI, Fcitx_SetCapabilities, client); + return true; + } + + return false; +} + +static Uint32 Fcitx_ModState(void) +{ + Uint32 fcitx_mods = 0; + SDL_Keymod sdl_mods = SDL_GetModState(); + + if (sdl_mods & SDL_KMOD_SHIFT) { + fcitx_mods |= (1 << 0); + } + if (sdl_mods & SDL_KMOD_CAPS) { + fcitx_mods |= (1 << 1); + } + if (sdl_mods & SDL_KMOD_CTRL) { + fcitx_mods |= (1 << 2); + } + if (sdl_mods & SDL_KMOD_ALT) { + fcitx_mods |= (1 << 3); + } + if (sdl_mods & SDL_KMOD_NUM) { + fcitx_mods |= (1 << 4); + } + if (sdl_mods & SDL_KMOD_MODE) { + fcitx_mods |= (1 << 7); + } + if (sdl_mods & SDL_KMOD_LGUI) { + fcitx_mods |= (1 << 6); + } + if (sdl_mods & SDL_KMOD_RGUI) { + fcitx_mods |= (1 << 28); + } + + return fcitx_mods; +} + +bool SDL_Fcitx_Init(void) +{ + fcitx_client.dbus = SDL_DBus_GetContext(); + + fcitx_client.cursor_rect.x = -1; + fcitx_client.cursor_rect.y = -1; + fcitx_client.cursor_rect.w = 0; + fcitx_client.cursor_rect.h = 0; + + return FcitxClientCreateIC(&fcitx_client); +} + +void SDL_Fcitx_Quit(void) +{ + FcitxClientICCallMethod(&fcitx_client, "DestroyIC"); + if (fcitx_client.ic_path) { + SDL_free(fcitx_client.ic_path); + fcitx_client.ic_path = NULL; + } +} + +void SDL_Fcitx_SetFocus(bool focused) +{ + if (focused) { + FcitxClientICCallMethod(&fcitx_client, "FocusIn"); + } else { + FcitxClientICCallMethod(&fcitx_client, "FocusOut"); + } +} + +void SDL_Fcitx_Reset(void) +{ + FcitxClientICCallMethod(&fcitx_client, "Reset"); +} + +bool SDL_Fcitx_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, bool down) +{ + Uint32 mod_state = Fcitx_ModState(); + Uint32 handled = false; + Uint32 is_release = !down; + Uint32 event_time = 0; + + if (!fcitx_client.ic_path) { + return false; + } + + if (SDL_DBus_CallMethod(FCITX_DBUS_SERVICE, fcitx_client.ic_path, FCITX_IC_DBUS_INTERFACE, "ProcessKeyEvent", + DBUS_TYPE_UINT32, &keysym, DBUS_TYPE_UINT32, &keycode, DBUS_TYPE_UINT32, &mod_state, DBUS_TYPE_BOOLEAN, &is_release, DBUS_TYPE_UINT32, &event_time, DBUS_TYPE_INVALID, + DBUS_TYPE_BOOLEAN, &handled, DBUS_TYPE_INVALID)) { + if (handled) { + //SDL_Fcitx_UpdateTextInputArea(SDL_GetKeyboardFocus()); + return true; + } + } + + return false; +} + +void SDL_Fcitx_PumpEvents(void) +{ + SDL_DBusContext *dbus = fcitx_client.dbus; + DBusConnection *conn = dbus->session_conn; + + dbus->connection_read_write(conn, 0); + + while (dbus->connection_dispatch(conn) == DBUS_DISPATCH_DATA_REMAINS) { + // Do nothing, actual work happens in DBus_MessageFilter + } +} diff --git a/thirdparty/sdl/core/linux/SDL_fcitx.h b/thirdparty/sdl/core/linux/SDL_fcitx.h new file mode 100644 index 00000000000..82c544e8b83 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_fcitx.h @@ -0,0 +1,35 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_fcitx_h_ +#define SDL_fcitx_h_ + +#include "SDL_internal.h" + +extern bool SDL_Fcitx_Init(void); +extern void SDL_Fcitx_Quit(void); +extern void SDL_Fcitx_SetFocus(bool focused); +extern void SDL_Fcitx_Reset(void); +extern bool SDL_Fcitx_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, bool down); +extern void SDL_Fcitx_UpdateTextInputArea(SDL_Window *window); +extern void SDL_Fcitx_PumpEvents(void); + +#endif // SDL_fcitx_h_ diff --git a/thirdparty/sdl/core/linux/SDL_ibus.c b/thirdparty/sdl/core/linux/SDL_ibus.c new file mode 100644 index 00000000000..3d4bb836949 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_ibus.c @@ -0,0 +1,694 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef HAVE_IBUS_IBUS_H +#include "SDL_ibus.h" +#include "SDL_dbus.h" + +#ifdef SDL_USE_LIBDBUS + +//#include "../../video/SDL_sysvideo.h" +#include "../../events/SDL_keyboard_c.h" + +#ifdef SDL_VIDEO_DRIVER_X11 +#include "../../video/x11/SDL_x11video.h" +#endif + +#include +#include +#include + +static const char IBUS_PATH[] = "/org/freedesktop/IBus"; + +static const char IBUS_SERVICE[] = "org.freedesktop.IBus"; +static const char IBUS_INTERFACE[] = "org.freedesktop.IBus"; +static const char IBUS_INPUT_INTERFACE[] = "org.freedesktop.IBus.InputContext"; + +static const char IBUS_PORTAL_SERVICE[] = "org.freedesktop.portal.IBus"; +static const char IBUS_PORTAL_INTERFACE[] = "org.freedesktop.IBus.Portal"; +static const char IBUS_PORTAL_INPUT_INTERFACE[] = "org.freedesktop.IBus.InputContext"; + +static const char *ibus_service = NULL; +static const char *ibus_interface = NULL; +static const char *ibus_input_interface = NULL; +static char *input_ctx_path = NULL; +static SDL_Rect ibus_cursor_rect = { 0, 0, 0, 0 }; +static DBusConnection *ibus_conn = NULL; +static bool ibus_is_portal_interface = false; +static char *ibus_addr_file = NULL; +static int inotify_fd = -1, inotify_wd = -1; + +static Uint32 IBus_ModState(void) +{ + Uint32 ibus_mods = 0; + SDL_Keymod sdl_mods = SDL_GetModState(); + + // Not sure about MOD3, MOD4 and HYPER mappings + if (sdl_mods & SDL_KMOD_LSHIFT) { + ibus_mods |= IBUS_SHIFT_MASK; + } + if (sdl_mods & SDL_KMOD_CAPS) { + ibus_mods |= IBUS_LOCK_MASK; + } + if (sdl_mods & SDL_KMOD_LCTRL) { + ibus_mods |= IBUS_CONTROL_MASK; + } + if (sdl_mods & SDL_KMOD_LALT) { + ibus_mods |= IBUS_MOD1_MASK; + } + if (sdl_mods & SDL_KMOD_NUM) { + ibus_mods |= IBUS_MOD2_MASK; + } + if (sdl_mods & SDL_KMOD_MODE) { + ibus_mods |= IBUS_MOD5_MASK; + } + if (sdl_mods & SDL_KMOD_LGUI) { + ibus_mods |= IBUS_SUPER_MASK; + } + if (sdl_mods & SDL_KMOD_RGUI) { + ibus_mods |= IBUS_META_MASK; + } + + return ibus_mods; +} + +static bool IBus_EnterVariant(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus, + DBusMessageIter *inside, const char *struct_id, size_t id_size) +{ + DBusMessageIter sub; + if (dbus->message_iter_get_arg_type(iter) != DBUS_TYPE_VARIANT) { + return false; + } + + dbus->message_iter_recurse(iter, &sub); + + if (dbus->message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) { + return false; + } + + dbus->message_iter_recurse(&sub, inside); + + if (dbus->message_iter_get_arg_type(inside) != DBUS_TYPE_STRING) { + return false; + } + + dbus->message_iter_get_basic(inside, &struct_id); + if (!struct_id || SDL_strncmp(struct_id, struct_id, id_size) != 0) { + return false; + } + return true; +} + +static bool IBus_GetDecorationPosition(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus, + Uint32 *start_pos, Uint32 *end_pos) +{ + DBusMessageIter sub1, sub2, array; + + if (!IBus_EnterVariant(conn, iter, dbus, &sub1, "IBusText", sizeof("IBusText"))) { + return false; + } + + dbus->message_iter_next(&sub1); + dbus->message_iter_next(&sub1); + dbus->message_iter_next(&sub1); + + if (!IBus_EnterVariant(conn, &sub1, dbus, &sub2, "IBusAttrList", sizeof("IBusAttrList"))) { + return false; + } + + dbus->message_iter_next(&sub2); + dbus->message_iter_next(&sub2); + + if (dbus->message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY) { + return false; + } + + dbus->message_iter_recurse(&sub2, &array); + + while (dbus->message_iter_get_arg_type(&array) == DBUS_TYPE_VARIANT) { + DBusMessageIter sub; + if (IBus_EnterVariant(conn, &array, dbus, &sub, "IBusAttribute", sizeof("IBusAttribute"))) { + Uint32 type; + + dbus->message_iter_next(&sub); + dbus->message_iter_next(&sub); + + // From here on, the structure looks like this: + // Uint32 type: 1=underline, 2=foreground, 3=background + // Uint32 value: for underline it's 0=NONE, 1=SINGLE, 2=DOUBLE, + // 3=LOW, 4=ERROR + // for foreground and background it's a color + // Uint32 start_index: starting position for the style (utf8-char) + // Uint32 end_index: end position for the style (utf8-char) + + dbus->message_iter_get_basic(&sub, &type); + // We only use the background type to determine the selection + if (type == 3) { + Uint32 start = -1; + dbus->message_iter_next(&sub); + dbus->message_iter_next(&sub); + if (dbus->message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32) { + dbus->message_iter_get_basic(&sub, &start); + dbus->message_iter_next(&sub); + if (dbus->message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32) { + dbus->message_iter_get_basic(&sub, end_pos); + *start_pos = start; + return true; + } + } + } + } + dbus->message_iter_next(&array); + } + return false; +} + +static const char *IBus_GetVariantText(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus) +{ + // The text we need is nested weirdly, use dbus-monitor to see the structure better + const char *text = NULL; + DBusMessageIter sub; + + if (!IBus_EnterVariant(conn, iter, dbus, &sub, "IBusText", sizeof("IBusText"))) { + return NULL; + } + + dbus->message_iter_next(&sub); + dbus->message_iter_next(&sub); + + if (dbus->message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) { + return NULL; + } + dbus->message_iter_get_basic(&sub, &text); + + return text; +} + +static bool IBus_GetVariantCursorPos(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus, + Uint32 *pos) +{ + dbus->message_iter_next(iter); + + if (dbus->message_iter_get_arg_type(iter) != DBUS_TYPE_UINT32) { + return false; + } + + dbus->message_iter_get_basic(iter, pos); + + return true; +} + +static DBusHandlerResult IBus_MessageHandler(DBusConnection *conn, DBusMessage *msg, void *user_data) +{ + SDL_DBusContext *dbus = (SDL_DBusContext *)user_data; + + if (dbus->message_is_signal(msg, ibus_input_interface, "CommitText")) { + DBusMessageIter iter; + const char *text; + + dbus->message_iter_init(msg, &iter); + text = IBus_GetVariantText(conn, &iter, dbus); + + SDL_SendKeyboardText(text); + + return DBUS_HANDLER_RESULT_HANDLED; + } + + if (dbus->message_is_signal(msg, ibus_input_interface, "UpdatePreeditText")) { + DBusMessageIter iter; + const char *text; + + dbus->message_iter_init(msg, &iter); + text = IBus_GetVariantText(conn, &iter, dbus); + + if (text) { + Uint32 pos, start_pos, end_pos; + bool has_pos = false; + bool has_dec_pos = false; + + dbus->message_iter_init(msg, &iter); + has_dec_pos = IBus_GetDecorationPosition(conn, &iter, dbus, &start_pos, &end_pos); + if (!has_dec_pos) { + dbus->message_iter_init(msg, &iter); + has_pos = IBus_GetVariantCursorPos(conn, &iter, dbus, &pos); + } + + if (has_dec_pos) { + SDL_SendEditingText(text, start_pos, end_pos - start_pos); + } else if (has_pos) { + SDL_SendEditingText(text, pos, -1); + } else { + SDL_SendEditingText(text, -1, -1); + } + } + + //SDL_IBus_UpdateTextInputArea(SDL_GetKeyboardFocus()); + + return DBUS_HANDLER_RESULT_HANDLED; + } + + if (dbus->message_is_signal(msg, ibus_input_interface, "HidePreeditText")) { + SDL_SendEditingText("", 0, 0); + return DBUS_HANDLER_RESULT_HANDLED; + } + + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +static char *IBus_ReadAddressFromFile(const char *file_path) +{ + char addr_buf[1024]; + bool success = false; + FILE *addr_file; + + addr_file = fopen(file_path, "r"); + if (!addr_file) { + return NULL; + } + + while (fgets(addr_buf, sizeof(addr_buf), addr_file)) { + if (SDL_strncmp(addr_buf, "IBUS_ADDRESS=", sizeof("IBUS_ADDRESS=") - 1) == 0) { + size_t sz = SDL_strlen(addr_buf); + if (addr_buf[sz - 1] == '\n') { + addr_buf[sz - 1] = 0; + } + if (addr_buf[sz - 2] == '\r') { + addr_buf[sz - 2] = 0; + } + success = true; + break; + } + } + + (void)fclose(addr_file); + + if (success) { + return SDL_strdup(addr_buf + (sizeof("IBUS_ADDRESS=") - 1)); + } else { + return NULL; + } +} + +static char *IBus_GetDBusAddressFilename(void) +{ + SDL_DBusContext *dbus; + const char *disp_env; + char config_dir[PATH_MAX]; + char *display = NULL; + const char *addr; + const char *conf_env; + char *key; + char file_path[PATH_MAX]; + const char *host; + char *disp_num, *screen_num; + + if (ibus_addr_file) { + return SDL_strdup(ibus_addr_file); + } + + dbus = SDL_DBus_GetContext(); + if (!dbus) { + return NULL; + } + + // Use this environment variable if it exists. + addr = SDL_getenv("IBUS_ADDRESS"); + if (addr && *addr) { + return SDL_strdup(addr); + } + + /* Otherwise, we have to get the hostname, display, machine id, config dir + and look up the address from a filepath using all those bits, eek. */ + disp_env = SDL_getenv("DISPLAY"); + + if (!disp_env || !*disp_env) { + display = SDL_strdup(":0.0"); + } else { + display = SDL_strdup(disp_env); + } + + host = display; + disp_num = SDL_strrchr(display, ':'); + screen_num = SDL_strrchr(display, '.'); + + if (!disp_num) { + SDL_free(display); + return NULL; + } + + *disp_num = 0; + disp_num++; + + if (screen_num) { + *screen_num = 0; + } + + if (!*host) { + const char *session = SDL_getenv("XDG_SESSION_TYPE"); + if (session && SDL_strcmp(session, "wayland") == 0) { + host = "unix-wayland"; + } else { + host = "unix"; + } + } + + SDL_memset(config_dir, 0, sizeof(config_dir)); + + conf_env = SDL_getenv("XDG_CONFIG_HOME"); + if (conf_env && *conf_env) { + SDL_strlcpy(config_dir, conf_env, sizeof(config_dir)); + } else { + const char *home_env = SDL_getenv("HOME"); + if (!home_env || !*home_env) { + SDL_free(display); + return NULL; + } + (void)SDL_snprintf(config_dir, sizeof(config_dir), "%s/.config", home_env); + } + + key = SDL_DBus_GetLocalMachineId(); + + if (!key) { + SDL_free(display); + return NULL; + } + + SDL_memset(file_path, 0, sizeof(file_path)); + (void)SDL_snprintf(file_path, sizeof(file_path), "%s/ibus/bus/%s-%s-%s", + config_dir, key, host, disp_num); + dbus->free(key); + SDL_free(display); + + return SDL_strdup(file_path); +} + +static bool IBus_CheckConnection(SDL_DBusContext *dbus); + +static void SDLCALL IBus_SetCapabilities(void *data, const char *name, const char *old_val, + const char *hint) +{ + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + + if (IBus_CheckConnection(dbus)) { + Uint32 caps = IBUS_CAP_FOCUS; + + if (hint && SDL_strstr(hint, "composition")) { + caps |= IBUS_CAP_PREEDIT_TEXT; + } + if (hint && SDL_strstr(hint, "candidates")) { + // FIXME, turn off native candidate rendering + } + + SDL_DBus_CallVoidMethodOnConnection(ibus_conn, ibus_service, input_ctx_path, ibus_input_interface, "SetCapabilities", + DBUS_TYPE_UINT32, &caps, DBUS_TYPE_INVALID); + } +} + +static bool IBus_SetupConnection(SDL_DBusContext *dbus, const char *addr) +{ + const char *client_name = "SDL3_Application"; + const char *path = NULL; + bool result = false; + DBusObjectPathVTable ibus_vtable; + + SDL_zero(ibus_vtable); + ibus_vtable.message_function = &IBus_MessageHandler; + + /* try the portal interface first. Modern systems have this in general, + and sandbox things like FlakPak and Snaps, etc, require it. */ + + ibus_is_portal_interface = true; + ibus_service = IBUS_PORTAL_SERVICE; + ibus_interface = IBUS_PORTAL_INTERFACE; + ibus_input_interface = IBUS_PORTAL_INPUT_INTERFACE; + ibus_conn = dbus->session_conn; + + result = SDL_DBus_CallMethodOnConnection(ibus_conn, ibus_service, IBUS_PATH, ibus_interface, "CreateInputContext", + DBUS_TYPE_STRING, &client_name, DBUS_TYPE_INVALID, + DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID); + if (!result) { + ibus_is_portal_interface = false; + ibus_service = IBUS_SERVICE; + ibus_interface = IBUS_INTERFACE; + ibus_input_interface = IBUS_INPUT_INTERFACE; + ibus_conn = dbus->connection_open_private(addr, NULL); + + if (!ibus_conn) { + return false; // oh well. + } + + dbus->connection_flush(ibus_conn); + + if (!dbus->bus_register(ibus_conn, NULL)) { + ibus_conn = NULL; + return false; + } + + dbus->connection_flush(ibus_conn); + + result = SDL_DBus_CallMethodOnConnection(ibus_conn, ibus_service, IBUS_PATH, ibus_interface, "CreateInputContext", + DBUS_TYPE_STRING, &client_name, DBUS_TYPE_INVALID, + DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID); + } else { + // re-using dbus->session_conn + dbus->connection_ref(ibus_conn); + } + + if (result) { + char matchstr[128]; + (void)SDL_snprintf(matchstr, sizeof(matchstr), "type='signal',interface='%s'", ibus_input_interface); + SDL_free(input_ctx_path); + input_ctx_path = SDL_strdup(path); + SDL_AddHintCallback(SDL_HINT_IME_IMPLEMENTED_UI, IBus_SetCapabilities, NULL); + dbus->bus_add_match(ibus_conn, matchstr, NULL); + dbus->connection_try_register_object_path(ibus_conn, input_ctx_path, &ibus_vtable, dbus, NULL); + dbus->connection_flush(ibus_conn); + } + + return result; +} + +static bool IBus_CheckConnection(SDL_DBusContext *dbus) +{ + if (!dbus) { + return false; + } + + if (ibus_conn && dbus->connection_get_is_connected(ibus_conn)) { + return true; + } + + if (inotify_fd > 0 && inotify_wd > 0) { + char buf[1024]; + ssize_t readsize = read(inotify_fd, buf, sizeof(buf)); + if (readsize > 0) { + + char *p; + bool file_updated = false; + + for (p = buf; p < buf + readsize; /**/) { + struct inotify_event *event = (struct inotify_event *)p; + if (event->len > 0) { + char *addr_file_no_path = SDL_strrchr(ibus_addr_file, '/'); + if (!addr_file_no_path) { + return false; + } + + if (SDL_strcmp(addr_file_no_path + 1, event->name) == 0) { + file_updated = true; + break; + } + } + + p += sizeof(struct inotify_event) + event->len; + } + + if (file_updated) { + char *addr = IBus_ReadAddressFromFile(ibus_addr_file); + if (addr) { + bool result = IBus_SetupConnection(dbus, addr); + SDL_free(addr); + return result; + } + } + } + } + + return false; +} + +bool SDL_IBus_Init(void) +{ + bool result = false; + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + + if (dbus) { + char *addr_file = IBus_GetDBusAddressFilename(); + char *addr; + char *addr_file_dir; + + if (!addr_file) { + return false; + } + + addr = IBus_ReadAddressFromFile(addr_file); + if (!addr) { + SDL_free(addr_file); + return false; + } + + if (ibus_addr_file) { + SDL_free(ibus_addr_file); + } + ibus_addr_file = SDL_strdup(addr_file); + + if (inotify_fd < 0) { + inotify_fd = inotify_init(); + fcntl(inotify_fd, F_SETFL, O_NONBLOCK); + } + + addr_file_dir = SDL_strrchr(addr_file, '/'); + if (addr_file_dir) { + *addr_file_dir = 0; + } + + inotify_wd = inotify_add_watch(inotify_fd, addr_file, IN_CREATE | IN_MODIFY); + SDL_free(addr_file); + + result = IBus_SetupConnection(dbus, addr); + SDL_free(addr); + + // don't use the addr_file if using the portal interface. + if (result && ibus_is_portal_interface) { + if (inotify_fd > 0) { + if (inotify_wd > 0) { + inotify_rm_watch(inotify_fd, inotify_wd); + inotify_wd = -1; + } + close(inotify_fd); + inotify_fd = -1; + } + } + } + + return result; +} + +void SDL_IBus_Quit(void) +{ + SDL_DBusContext *dbus; + + if (input_ctx_path) { + SDL_free(input_ctx_path); + input_ctx_path = NULL; + } + + if (ibus_addr_file) { + SDL_free(ibus_addr_file); + ibus_addr_file = NULL; + } + + dbus = SDL_DBus_GetContext(); + + // if using portal, ibus_conn == session_conn; don't release it here. + if (dbus && ibus_conn && !ibus_is_portal_interface) { + dbus->connection_close(ibus_conn); + dbus->connection_unref(ibus_conn); + } + + ibus_conn = NULL; + ibus_service = NULL; + ibus_interface = NULL; + ibus_input_interface = NULL; + ibus_is_portal_interface = false; + + if (inotify_fd > 0 && inotify_wd > 0) { + inotify_rm_watch(inotify_fd, inotify_wd); + inotify_wd = -1; + } + + // !!! FIXME: should we close(inotify_fd) here? + + SDL_RemoveHintCallback(SDL_HINT_IME_IMPLEMENTED_UI, IBus_SetCapabilities, NULL); + + SDL_memset(&ibus_cursor_rect, 0, sizeof(ibus_cursor_rect)); +} + +static void IBus_SimpleMessage(const char *method) +{ + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + + if ((input_ctx_path) && (IBus_CheckConnection(dbus))) { + SDL_DBus_CallVoidMethodOnConnection(ibus_conn, ibus_service, input_ctx_path, ibus_input_interface, method, DBUS_TYPE_INVALID); + } +} + +void SDL_IBus_SetFocus(bool focused) +{ + const char *method = focused ? "FocusIn" : "FocusOut"; + IBus_SimpleMessage(method); +} + +void SDL_IBus_Reset(void) +{ + IBus_SimpleMessage("Reset"); +} + +bool SDL_IBus_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, bool down) +{ + Uint32 result = 0; + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + + if (IBus_CheckConnection(dbus)) { + Uint32 mods = IBus_ModState(); + Uint32 ibus_keycode = keycode - 8; + if (!down) { + mods |= (1 << 30); // IBUS_RELEASE_MASK + } + if (!SDL_DBus_CallMethodOnConnection(ibus_conn, ibus_service, input_ctx_path, ibus_input_interface, "ProcessKeyEvent", + DBUS_TYPE_UINT32, &keysym, DBUS_TYPE_UINT32, &ibus_keycode, DBUS_TYPE_UINT32, &mods, DBUS_TYPE_INVALID, + DBUS_TYPE_BOOLEAN, &result, DBUS_TYPE_INVALID)) { + result = 0; + } + } + + //SDL_IBus_UpdateTextInputArea(SDL_GetKeyboardFocus()); + + return (result != 0); +} + +void SDL_IBus_PumpEvents(void) +{ + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + + if (IBus_CheckConnection(dbus)) { + dbus->connection_read_write(ibus_conn, 0); + + while (dbus->connection_dispatch(ibus_conn) == DBUS_DISPATCH_DATA_REMAINS) { + // Do nothing, actual work happens in IBus_MessageHandler + } + } +} + +#endif // SDL_USE_LIBDBUS + +#endif diff --git a/thirdparty/sdl/core/linux/SDL_ibus.h b/thirdparty/sdl/core/linux/SDL_ibus.h new file mode 100644 index 00000000000..ba08be6971a --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_ibus.h @@ -0,0 +1,55 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_ibus_h_ +#define SDL_ibus_h_ + +#ifdef HAVE_IBUS_IBUS_H +#define SDL_USE_IBUS 1 +#include + +extern bool SDL_IBus_Init(void); +extern void SDL_IBus_Quit(void); + +// Lets the IBus server know about changes in window focus +extern void SDL_IBus_SetFocus(bool focused); + +// Closes the candidate list and resets any text currently being edited +extern void SDL_IBus_Reset(void); + +/* Sends a keypress event to IBus, returns true if IBus used this event to + update its candidate list or change input methods. PumpEvents should be + called some time after this, to receive the TextInput / TextEditing event back. */ +extern bool SDL_IBus_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, bool down); + +/* Update the position of IBus' candidate list. If rect is NULL then this will + just reposition it relative to the focused window's new position. */ +extern void SDL_IBus_UpdateTextInputArea(SDL_Window *window); + +/* Checks DBus for new IBus events, and calls SDL_SendKeyboardText / + SDL_SendEditingText for each event it finds */ +extern void SDL_IBus_PumpEvents(void); + +#endif // HAVE_IBUS_IBUS_H + +#endif // SDL_ibus_h_ diff --git a/thirdparty/sdl/core/linux/SDL_ime.c b/thirdparty/sdl/core/linux/SDL_ime.c new file mode 100644 index 00000000000..c15defb84da --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_ime.c @@ -0,0 +1,150 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_ime.h" +#include "SDL_ibus.h" +#include "SDL_fcitx.h" + +typedef bool (*SDL_IME_Init_t)(void); +typedef void (*SDL_IME_Quit_t)(void); +typedef void (*SDL_IME_SetFocus_t)(bool); +typedef void (*SDL_IME_Reset_t)(void); +typedef bool (*SDL_IME_ProcessKeyEvent_t)(Uint32, Uint32, bool down); +typedef void (*SDL_IME_UpdateTextInputArea_t)(SDL_Window *window); +typedef void (*SDL_IME_PumpEvents_t)(void); + +static SDL_IME_Init_t SDL_IME_Init_Real = NULL; +static SDL_IME_Quit_t SDL_IME_Quit_Real = NULL; +static SDL_IME_SetFocus_t SDL_IME_SetFocus_Real = NULL; +static SDL_IME_Reset_t SDL_IME_Reset_Real = NULL; +static SDL_IME_ProcessKeyEvent_t SDL_IME_ProcessKeyEvent_Real = NULL; +static SDL_IME_UpdateTextInputArea_t SDL_IME_UpdateTextInputArea_Real = NULL; +static SDL_IME_PumpEvents_t SDL_IME_PumpEvents_Real = NULL; + +static void InitIME(void) +{ + static bool inited = false; +#ifdef HAVE_FCITX + const char *im_module = SDL_getenv("SDL_IM_MODULE"); + const char *xmodifiers = SDL_getenv("XMODIFIERS"); +#endif + + if (inited == true) { + return; + } + + inited = true; + + // See if fcitx IME support is being requested +#ifdef HAVE_FCITX + if (!SDL_IME_Init_Real && + ((im_module && SDL_strcmp(im_module, "fcitx") == 0) || + (!im_module && xmodifiers && SDL_strstr(xmodifiers, "@im=fcitx") != NULL))) { + SDL_IME_Init_Real = SDL_Fcitx_Init; + SDL_IME_Quit_Real = SDL_Fcitx_Quit; + SDL_IME_SetFocus_Real = SDL_Fcitx_SetFocus; + SDL_IME_Reset_Real = SDL_Fcitx_Reset; + SDL_IME_ProcessKeyEvent_Real = SDL_Fcitx_ProcessKeyEvent; + SDL_IME_UpdateTextInputArea_Real = SDL_Fcitx_UpdateTextInputArea; + SDL_IME_PumpEvents_Real = SDL_Fcitx_PumpEvents; + } +#endif // HAVE_FCITX + + // default to IBus +#ifdef HAVE_IBUS_IBUS_H + if (!SDL_IME_Init_Real) { + SDL_IME_Init_Real = SDL_IBus_Init; + SDL_IME_Quit_Real = SDL_IBus_Quit; + SDL_IME_SetFocus_Real = SDL_IBus_SetFocus; + SDL_IME_Reset_Real = SDL_IBus_Reset; + SDL_IME_ProcessKeyEvent_Real = SDL_IBus_ProcessKeyEvent; + SDL_IME_UpdateTextInputArea_Real = SDL_IBus_UpdateTextInputArea; + SDL_IME_PumpEvents_Real = SDL_IBus_PumpEvents; + } +#endif // HAVE_IBUS_IBUS_H +} + +bool SDL_IME_Init(void) +{ + InitIME(); + + if (SDL_IME_Init_Real) { + if (SDL_IME_Init_Real()) { + return true; + } + + // uhoh, the IME implementation's init failed! Disable IME support. + SDL_IME_Init_Real = NULL; + SDL_IME_Quit_Real = NULL; + SDL_IME_SetFocus_Real = NULL; + SDL_IME_Reset_Real = NULL; + SDL_IME_ProcessKeyEvent_Real = NULL; + SDL_IME_UpdateTextInputArea_Real = NULL; + SDL_IME_PumpEvents_Real = NULL; + } + + return false; +} + +void SDL_IME_Quit(void) +{ + if (SDL_IME_Quit_Real) { + SDL_IME_Quit_Real(); + } +} + +void SDL_IME_SetFocus(bool focused) +{ + if (SDL_IME_SetFocus_Real) { + SDL_IME_SetFocus_Real(focused); + } +} + +void SDL_IME_Reset(void) +{ + if (SDL_IME_Reset_Real) { + SDL_IME_Reset_Real(); + } +} + +bool SDL_IME_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, bool down) +{ + if (SDL_IME_ProcessKeyEvent_Real) { + return SDL_IME_ProcessKeyEvent_Real(keysym, keycode, down); + } + + return false; +} + +void SDL_IME_UpdateTextInputArea(SDL_Window *window) +{ + if (SDL_IME_UpdateTextInputArea_Real) { + SDL_IME_UpdateTextInputArea_Real(window); + } +} + +void SDL_IME_PumpEvents(void) +{ + if (SDL_IME_PumpEvents_Real) { + SDL_IME_PumpEvents_Real(); + } +} diff --git a/thirdparty/sdl/core/linux/SDL_ime.h b/thirdparty/sdl/core/linux/SDL_ime.h new file mode 100644 index 00000000000..ac192fa046f --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_ime.h @@ -0,0 +1,35 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_ime_h_ +#define SDL_ime_h_ + +#include "SDL_internal.h" + +extern bool SDL_IME_Init(void); +extern void SDL_IME_Quit(void); +extern void SDL_IME_SetFocus(bool focused); +extern void SDL_IME_Reset(void); +extern bool SDL_IME_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, bool down); +extern void SDL_IME_UpdateTextInputArea(SDL_Window *window); +extern void SDL_IME_PumpEvents(void); + +#endif // SDL_ime_h_ diff --git a/thirdparty/sdl/core/linux/SDL_system_theme.c b/thirdparty/sdl/core/linux/SDL_system_theme.c new file mode 100644 index 00000000000..f5ef92dd053 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_system_theme.c @@ -0,0 +1,156 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_dbus.h" +#include "SDL_system_theme.h" +//#include "../../video/SDL_sysvideo.h" + +#include + +#define PORTAL_DESTINATION "org.freedesktop.portal.Desktop" +#define PORTAL_PATH "/org/freedesktop/portal/desktop" +#define PORTAL_INTERFACE "org.freedesktop.portal.Settings" +#define PORTAL_METHOD "Read" + +#define SIGNAL_INTERFACE "org.freedesktop.portal.Settings" +#define SIGNAL_NAMESPACE "org.freedesktop.appearance" +#define SIGNAL_NAME "SettingChanged" +#define SIGNAL_KEY "color-scheme" + +typedef struct SystemThemeData +{ + SDL_DBusContext *dbus; + SDL_SystemTheme theme; +} SystemThemeData; + +static SystemThemeData system_theme_data; + +static bool DBus_ExtractThemeVariant(DBusMessageIter *iter, SDL_SystemTheme *theme) { + SDL_DBusContext *dbus = system_theme_data.dbus; + Uint32 color_scheme; + DBusMessageIter variant_iter; + + if (dbus->message_iter_get_arg_type(iter) != DBUS_TYPE_VARIANT) + return false; + dbus->message_iter_recurse(iter, &variant_iter); + if (dbus->message_iter_get_arg_type(&variant_iter) != DBUS_TYPE_UINT32) + return false; + dbus->message_iter_get_basic(&variant_iter, &color_scheme); + switch (color_scheme) { + case 0: + *theme = SDL_SYSTEM_THEME_UNKNOWN; + break; + case 1: + *theme = SDL_SYSTEM_THEME_DARK; + break; + case 2: + *theme = SDL_SYSTEM_THEME_LIGHT; + break; + } + return true; +} + +static DBusHandlerResult DBus_MessageFilter(DBusConnection *conn, DBusMessage *msg, void *data) { + SDL_DBusContext *dbus = (SDL_DBusContext *)data; + + if (dbus->message_is_signal(msg, SIGNAL_INTERFACE, SIGNAL_NAME)) { + DBusMessageIter signal_iter; + const char *namespace, *key; + + dbus->message_iter_init(msg, &signal_iter); + // Check if the parameters are what we expect + if (dbus->message_iter_get_arg_type(&signal_iter) != DBUS_TYPE_STRING) + goto not_our_signal; + dbus->message_iter_get_basic(&signal_iter, &namespace); + if (SDL_strcmp(SIGNAL_NAMESPACE, namespace) != 0) + goto not_our_signal; + + if (!dbus->message_iter_next(&signal_iter)) + goto not_our_signal; + + if (dbus->message_iter_get_arg_type(&signal_iter) != DBUS_TYPE_STRING) + goto not_our_signal; + dbus->message_iter_get_basic(&signal_iter, &key); + if (SDL_strcmp(SIGNAL_KEY, key) != 0) + goto not_our_signal; + + if (!dbus->message_iter_next(&signal_iter)) + goto not_our_signal; + + if (!DBus_ExtractThemeVariant(&signal_iter, &system_theme_data.theme)) + goto not_our_signal; + + //SDL_SetSystemTheme(system_theme_data.theme); + return DBUS_HANDLER_RESULT_HANDLED; + } +not_our_signal: + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +bool SDL_SystemTheme_Init(void) +{ + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + DBusMessage *msg; + static const char *namespace = SIGNAL_NAMESPACE; + static const char *key = SIGNAL_KEY; + + system_theme_data.theme = SDL_SYSTEM_THEME_UNKNOWN; + system_theme_data.dbus = dbus; + if (!dbus) { + return false; + } + + msg = dbus->message_new_method_call(PORTAL_DESTINATION, PORTAL_PATH, PORTAL_INTERFACE, PORTAL_METHOD); + if (msg) { + if (dbus->message_append_args(msg, DBUS_TYPE_STRING, &namespace, DBUS_TYPE_STRING, &key, DBUS_TYPE_INVALID)) { + DBusMessage *reply = dbus->connection_send_with_reply_and_block(dbus->session_conn, msg, 300, NULL); + if (reply) { + DBusMessageIter reply_iter, variant_outer_iter; + + dbus->message_iter_init(reply, &reply_iter); + // The response has signature <> + if (dbus->message_iter_get_arg_type(&reply_iter) != DBUS_TYPE_VARIANT) + goto incorrect_type; + dbus->message_iter_recurse(&reply_iter, &variant_outer_iter); + if (!DBus_ExtractThemeVariant(&variant_outer_iter, &system_theme_data.theme)) + goto incorrect_type; +incorrect_type: + dbus->message_unref(reply); + } + } + dbus->message_unref(msg); + } + + dbus->bus_add_match(dbus->session_conn, + "type='signal', interface='"SIGNAL_INTERFACE"'," + "member='"SIGNAL_NAME"', arg0='"SIGNAL_NAMESPACE"'," + "arg1='"SIGNAL_KEY"'", NULL); + dbus->connection_add_filter(dbus->session_conn, + &DBus_MessageFilter, dbus, NULL); + dbus->connection_flush(dbus->session_conn); + return true; +} + +SDL_SystemTheme SDL_SystemTheme_Get(void) +{ + return system_theme_data.theme; +} diff --git a/thirdparty/sdl/core/linux/SDL_system_theme.h b/thirdparty/sdl/core/linux/SDL_system_theme.h new file mode 100644 index 00000000000..2cd55cd686c --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_system_theme.h @@ -0,0 +1,30 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_system_theme_h_ +#define SDL_system_theme_h_ + +#include "SDL_internal.h" + +extern bool SDL_SystemTheme_Init(void); +extern SDL_SystemTheme SDL_SystemTheme_Get(void); + +#endif // SDL_system_theme_h_ diff --git a/thirdparty/sdl/core/linux/SDL_threadprio.c b/thirdparty/sdl/core/linux/SDL_threadprio.c new file mode 100644 index 00000000000..1a3e22faf63 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_threadprio.c @@ -0,0 +1,345 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_PLATFORM_LINUX + +#ifndef SDL_THREADS_DISABLED +#include +#include +#include +#include +#include + +// RLIMIT_RTTIME requires kernel >= 2.6.25 and is in glibc >= 2.14 +#ifndef RLIMIT_RTTIME +#define RLIMIT_RTTIME 15 +#endif +// SCHED_RESET_ON_FORK is in kernel >= 2.6.32. +#ifndef SCHED_RESET_ON_FORK +#define SCHED_RESET_ON_FORK 0x40000000 +#endif + +#include "SDL_dbus.h" + +#ifdef SDL_USE_LIBDBUS + +// d-bus queries to org.freedesktop.RealtimeKit1. +#define RTKIT_DBUS_NODE "org.freedesktop.RealtimeKit1" +#define RTKIT_DBUS_PATH "/org/freedesktop/RealtimeKit1" +#define RTKIT_DBUS_INTERFACE "org.freedesktop.RealtimeKit1" + +// d-bus queries to the XDG portal interface to RealtimeKit1 +#define XDG_PORTAL_DBUS_NODE "org.freedesktop.portal.Desktop" +#define XDG_PORTAL_DBUS_PATH "/org/freedesktop/portal/desktop" +#define XDG_PORTAL_DBUS_INTERFACE "org.freedesktop.portal.Realtime" + +static bool rtkit_use_session_conn; +static const char *rtkit_dbus_node; +static const char *rtkit_dbus_path; +static const char *rtkit_dbus_interface; + +static pthread_once_t rtkit_initialize_once = PTHREAD_ONCE_INIT; +static Sint32 rtkit_min_nice_level = -20; +static Sint32 rtkit_max_realtime_priority = 99; +static Sint64 rtkit_max_rttime_usec = 200000; + +/* + * Checking that the RTTimeUSecMax property exists and is an int64 confirms that: + * - The desktop portal exists and supports the realtime interface. + * - The realtime interface is new enough to have the required bug fixes applied. + */ +static bool realtime_portal_supported(DBusConnection *conn) +{ + Sint64 res; + return SDL_DBus_QueryPropertyOnConnection(conn, XDG_PORTAL_DBUS_NODE, XDG_PORTAL_DBUS_PATH, XDG_PORTAL_DBUS_INTERFACE, + "RTTimeUSecMax", DBUS_TYPE_INT64, &res); +} + +static void set_rtkit_interface(void) +{ + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + + // xdg-desktop-portal works in all instances, so check for it first. + if (dbus && realtime_portal_supported(dbus->session_conn)) { + rtkit_use_session_conn = true; + rtkit_dbus_node = XDG_PORTAL_DBUS_NODE; + rtkit_dbus_path = XDG_PORTAL_DBUS_PATH; + rtkit_dbus_interface = XDG_PORTAL_DBUS_INTERFACE; + } else { // Fall back to the standard rtkit interface in all other cases. + rtkit_use_session_conn = false; + rtkit_dbus_node = RTKIT_DBUS_NODE; + rtkit_dbus_path = RTKIT_DBUS_PATH; + rtkit_dbus_interface = RTKIT_DBUS_INTERFACE; + } +} + +static DBusConnection *get_rtkit_dbus_connection(void) +{ + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + + if (dbus) { + return rtkit_use_session_conn ? dbus->session_conn : dbus->system_conn; + } + + return NULL; +} + +static void rtkit_initialize(void) +{ + DBusConnection *dbus_conn; + + set_rtkit_interface(); + dbus_conn = get_rtkit_dbus_connection(); + + // Try getting minimum nice level: this is often greater than PRIO_MIN (-20). + if (!dbus_conn || !SDL_DBus_QueryPropertyOnConnection(dbus_conn, rtkit_dbus_node, rtkit_dbus_path, rtkit_dbus_interface, "MinNiceLevel", + DBUS_TYPE_INT32, &rtkit_min_nice_level)) { + rtkit_min_nice_level = -20; + } + + // Try getting maximum realtime priority: this can be less than the POSIX default (99). + if (!dbus_conn || !SDL_DBus_QueryPropertyOnConnection(dbus_conn, rtkit_dbus_node, rtkit_dbus_path, rtkit_dbus_interface, "MaxRealtimePriority", + DBUS_TYPE_INT32, &rtkit_max_realtime_priority)) { + rtkit_max_realtime_priority = 99; + } + + // Try getting maximum rttime allowed by rtkit: exceeding this value will result in SIGKILL + if (!dbus_conn || !SDL_DBus_QueryPropertyOnConnection(dbus_conn, rtkit_dbus_node, rtkit_dbus_path, rtkit_dbus_interface, "RTTimeUSecMax", + DBUS_TYPE_INT64, &rtkit_max_rttime_usec)) { + rtkit_max_rttime_usec = 200000; + } +} + +static bool rtkit_initialize_realtime_thread(void) +{ + // Following is an excerpt from rtkit README that outlines the requirements + // a thread must meet before making rtkit requests: + // + // * Only clients with RLIMIT_RTTIME set will get RT scheduling + // + // * RT scheduling will only be handed out to processes with + // SCHED_RESET_ON_FORK set to guarantee that the scheduling + // settings cannot 'leak' to child processes, thus making sure + // that 'RT fork bombs' cannot be used to bypass RLIMIT_RTTIME + // and take the system down. + // + // * Limits are enforced on all user controllable resources, only + // a maximum number of users, processes, threads can request RT + // scheduling at the same time. + // + // * Only a limited number of threads may be made RT in a + // specific time frame. + // + // * Client authorization is verified with PolicyKit + + int err; + struct rlimit rlimit; + int nLimit = RLIMIT_RTTIME; + pid_t nPid = 0; // self + int nSchedPolicy = sched_getscheduler(nPid) | SCHED_RESET_ON_FORK; + struct sched_param schedParam; + + SDL_zero(schedParam); + + // Requirement #1: Set RLIMIT_RTTIME + err = getrlimit(nLimit, &rlimit); + if (err) { + return false; + } + + // Current rtkit allows a max of 200ms right now + rlimit.rlim_max = rtkit_max_rttime_usec; + rlimit.rlim_cur = rlimit.rlim_max / 2; + err = setrlimit(nLimit, &rlimit); + if (err) { + return false; + } + + // Requirement #2: Add SCHED_RESET_ON_FORK to the scheduler policy + err = sched_getparam(nPid, &schedParam); + if (err) { + return false; + } + + err = sched_setscheduler(nPid, nSchedPolicy, &schedParam); + if (err) { + return false; + } + + return true; +} + +static bool rtkit_setpriority_nice(pid_t thread, int nice_level) +{ + DBusConnection *dbus_conn; + Uint64 pid = (Uint64)getpid(); + Uint64 tid = (Uint64)thread; + Sint32 nice = (Sint32)nice_level; + + pthread_once(&rtkit_initialize_once, rtkit_initialize); + dbus_conn = get_rtkit_dbus_connection(); + + if (nice < rtkit_min_nice_level) { + nice = rtkit_min_nice_level; + } + + if (!dbus_conn || !SDL_DBus_CallMethodOnConnection(dbus_conn, + rtkit_dbus_node, rtkit_dbus_path, rtkit_dbus_interface, "MakeThreadHighPriorityWithPID", + DBUS_TYPE_UINT64, &pid, DBUS_TYPE_UINT64, &tid, DBUS_TYPE_INT32, &nice, DBUS_TYPE_INVALID, + DBUS_TYPE_INVALID)) { + return false; + } + return true; +} + +static bool rtkit_setpriority_realtime(pid_t thread, int rt_priority) +{ + DBusConnection *dbus_conn; + Uint64 pid = (Uint64)getpid(); + Uint64 tid = (Uint64)thread; + Uint32 priority = (Uint32)rt_priority; + + pthread_once(&rtkit_initialize_once, rtkit_initialize); + dbus_conn = get_rtkit_dbus_connection(); + + if (priority > rtkit_max_realtime_priority) { + priority = rtkit_max_realtime_priority; + } + + // We always perform the thread state changes necessary for rtkit. + // This wastes some system calls if the state is already set but + // typically code sets a thread priority and leaves it so it's + // not expected that this wasted effort will be an issue. + // We also do not quit if this fails, we let the rtkit request + // go through to determine whether it really needs to fail or not. + rtkit_initialize_realtime_thread(); + + if (!dbus_conn || !SDL_DBus_CallMethodOnConnection(dbus_conn, + rtkit_dbus_node, rtkit_dbus_path, rtkit_dbus_interface, "MakeThreadRealtimeWithPID", + DBUS_TYPE_UINT64, &pid, DBUS_TYPE_UINT64, &tid, DBUS_TYPE_UINT32, &priority, DBUS_TYPE_INVALID, + DBUS_TYPE_INVALID)) { + return false; + } + return true; +} +#else + +#define rtkit_max_realtime_priority 99 + +#endif // dbus +#endif // threads + +// this is a public symbol, so it has to exist even if threads are disabled. +bool SDL_SetLinuxThreadPriority(Sint64 threadID, int priority) +{ +#ifdef SDL_THREADS_DISABLED + return SDL_Unsupported(); +#else + if (setpriority(PRIO_PROCESS, (id_t)threadID, priority) == 0) { + return true; + } + +#ifdef SDL_USE_LIBDBUS + /* Note that this fails you most likely: + * Have your process's scheduler incorrectly configured. + See the requirements at: + http://git.0pointer.net/rtkit.git/tree/README#n16 + * Encountered dbus/polkit security restrictions. Note + that the RealtimeKit1 dbus endpoint is inaccessible + over ssh connections for most common distro configs. + You might want to check your local config for details: + /usr/share/polkit-1/actions/org.freedesktop.RealtimeKit1.policy + + README and sample code at: http://git.0pointer.net/rtkit.git + */ + if (rtkit_setpriority_nice((pid_t)threadID, priority)) { + return true; + } +#endif + + return SDL_SetError("setpriority() failed"); +#endif +} + +// this is a public symbol, so it has to exist even if threads are disabled. +bool SDL_SetLinuxThreadPriorityAndPolicy(Sint64 threadID, int sdlPriority, int schedPolicy) +{ +#ifdef SDL_THREADS_DISABLED + return SDL_Unsupported(); +#else + int osPriority; + + if (schedPolicy == SCHED_RR || schedPolicy == SCHED_FIFO) { + if (sdlPriority == SDL_THREAD_PRIORITY_LOW) { + osPriority = 1; + } else if (sdlPriority == SDL_THREAD_PRIORITY_HIGH) { + osPriority = rtkit_max_realtime_priority * 3 / 4; + } else if (sdlPriority == SDL_THREAD_PRIORITY_TIME_CRITICAL) { + osPriority = rtkit_max_realtime_priority; + } else { + osPriority = rtkit_max_realtime_priority / 2; + } + } else { + if (sdlPriority == SDL_THREAD_PRIORITY_LOW) { + osPriority = 19; + } else if (sdlPriority == SDL_THREAD_PRIORITY_HIGH) { + osPriority = -10; + } else if (sdlPriority == SDL_THREAD_PRIORITY_TIME_CRITICAL) { + osPriority = -20; + } else { + osPriority = 0; + } + + if (setpriority(PRIO_PROCESS, (id_t)threadID, osPriority) == 0) { + return true; + } + } + +#ifdef SDL_USE_LIBDBUS + /* Note that this fails you most likely: + * Have your process's scheduler incorrectly configured. + See the requirements at: + http://git.0pointer.net/rtkit.git/tree/README#n16 + * Encountered dbus/polkit security restrictions. Note + that the RealtimeKit1 dbus endpoint is inaccessible + over ssh connections for most common distro configs. + You might want to check your local config for details: + /usr/share/polkit-1/actions/org.freedesktop.RealtimeKit1.policy + + README and sample code at: http://git.0pointer.net/rtkit.git + */ + if (schedPolicy == SCHED_RR || schedPolicy == SCHED_FIFO) { + if (rtkit_setpriority_realtime((pid_t)threadID, osPriority)) { + return true; + } + } else { + if (rtkit_setpriority_nice((pid_t)threadID, osPriority)) { + return true; + } + } +#endif + + return SDL_SetError("setpriority() failed"); +#endif +} + +#endif // SDL_PLATFORM_LINUX diff --git a/thirdparty/sdl/core/linux/SDL_udev.c b/thirdparty/sdl/core/linux/SDL_udev.c new file mode 100644 index 00000000000..907c34c7f66 --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_udev.c @@ -0,0 +1,596 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +/* + * To list the properties of a device, try something like: + * udevadm info -a -n snd/hwC0D0 (for a sound card) + * udevadm info --query=all -n input/event3 (for a keyboard, mouse, etc) + * udevadm info --query=property -n input/event2 + */ +#include "SDL_udev.h" + +#ifdef SDL_USE_LIBUDEV + +#include +#include + +#include "SDL_evdev_capabilities.h" +#include "../unix/SDL_poll.h" + +static const char *SDL_UDEV_LIBS[] = { "libudev.so.1", "libudev.so.0" }; + +static SDL_UDEV_PrivateData *_this = NULL; + +static bool SDL_UDEV_load_sym(const char *fn, void **addr); +static bool SDL_UDEV_load_syms(void); +static bool SDL_UDEV_hotplug_update_available(void); +static void get_caps(struct udev_device *dev, struct udev_device *pdev, const char *attr, unsigned long *bitmask, size_t bitmask_len); +static int guess_device_class(struct udev_device *dev); +static int device_class(struct udev_device *dev); +static void device_event(SDL_UDEV_deviceevent type, struct udev_device *dev); + +static bool SDL_UDEV_load_sym(const char *fn, void **addr) +{ + *addr = SDL_LoadFunction(_this->udev_handle, fn); + if (!*addr) { + // Don't call SDL_SetError(): SDL_LoadFunction already did. + return false; + } + + return true; +} + +static bool SDL_UDEV_load_syms(void) +{ +/* cast funcs to char* first, to please GCC's strict aliasing rules. */ +#define SDL_UDEV_SYM(x) \ + if (!SDL_UDEV_load_sym(#x, (void **)(char *)&_this->syms.x)) \ + return false + + SDL_UDEV_SYM(udev_device_get_action); + SDL_UDEV_SYM(udev_device_get_devnode); + SDL_UDEV_SYM(udev_device_get_syspath); + SDL_UDEV_SYM(udev_device_get_subsystem); + SDL_UDEV_SYM(udev_device_get_parent_with_subsystem_devtype); + SDL_UDEV_SYM(udev_device_get_property_value); + SDL_UDEV_SYM(udev_device_get_sysattr_value); + SDL_UDEV_SYM(udev_device_new_from_syspath); + SDL_UDEV_SYM(udev_device_unref); + SDL_UDEV_SYM(udev_enumerate_add_match_property); + SDL_UDEV_SYM(udev_enumerate_add_match_subsystem); + SDL_UDEV_SYM(udev_enumerate_get_list_entry); + SDL_UDEV_SYM(udev_enumerate_new); + SDL_UDEV_SYM(udev_enumerate_scan_devices); + SDL_UDEV_SYM(udev_enumerate_unref); + SDL_UDEV_SYM(udev_list_entry_get_name); + SDL_UDEV_SYM(udev_list_entry_get_next); + SDL_UDEV_SYM(udev_monitor_enable_receiving); + SDL_UDEV_SYM(udev_monitor_filter_add_match_subsystem_devtype); + SDL_UDEV_SYM(udev_monitor_get_fd); + SDL_UDEV_SYM(udev_monitor_new_from_netlink); + SDL_UDEV_SYM(udev_monitor_receive_device); + SDL_UDEV_SYM(udev_monitor_unref); + SDL_UDEV_SYM(udev_new); + SDL_UDEV_SYM(udev_unref); + SDL_UDEV_SYM(udev_device_new_from_devnum); + SDL_UDEV_SYM(udev_device_get_devnum); +#undef SDL_UDEV_SYM + + return true; +} + +static bool SDL_UDEV_hotplug_update_available(void) +{ + if (_this->udev_mon) { + const int fd = _this->syms.udev_monitor_get_fd(_this->udev_mon); + if (SDL_IOReady(fd, SDL_IOR_READ, 0)) { + return true; + } + } + return false; +} + +bool SDL_UDEV_Init(void) +{ + if (!_this) { + _this = (SDL_UDEV_PrivateData *)SDL_calloc(1, sizeof(*_this)); + if (!_this) { + return false; + } + + if (!SDL_UDEV_LoadLibrary()) { + SDL_UDEV_Quit(); + return false; + } + + /* Set up udev monitoring + * Listen for input devices (mouse, keyboard, joystick, etc) and sound devices + */ + + _this->udev = _this->syms.udev_new(); + if (!_this->udev) { + SDL_UDEV_Quit(); + return SDL_SetError("udev_new() failed"); + } + + _this->udev_mon = _this->syms.udev_monitor_new_from_netlink(_this->udev, "udev"); + if (!_this->udev_mon) { + SDL_UDEV_Quit(); + return SDL_SetError("udev_monitor_new_from_netlink() failed"); + } + + _this->syms.udev_monitor_filter_add_match_subsystem_devtype(_this->udev_mon, "input", NULL); + _this->syms.udev_monitor_filter_add_match_subsystem_devtype(_this->udev_mon, "sound", NULL); + _this->syms.udev_monitor_filter_add_match_subsystem_devtype(_this->udev_mon, "video4linux", NULL); + _this->syms.udev_monitor_enable_receiving(_this->udev_mon); + + // Do an initial scan of existing devices + SDL_UDEV_Scan(); + } + + _this->ref_count += 1; + + return true; +} + +void SDL_UDEV_Quit(void) +{ + if (!_this) { + return; + } + + _this->ref_count -= 1; + + if (_this->ref_count < 1) { + + if (_this->udev_mon) { + _this->syms.udev_monitor_unref(_this->udev_mon); + _this->udev_mon = NULL; + } + if (_this->udev) { + _this->syms.udev_unref(_this->udev); + _this->udev = NULL; + } + + // Remove existing devices + while (_this->first) { + SDL_UDEV_CallbackList *item = _this->first; + _this->first = _this->first->next; + SDL_free(item); + } + + SDL_UDEV_UnloadLibrary(); + SDL_free(_this); + _this = NULL; + } +} + +bool SDL_UDEV_Scan(void) +{ + struct udev_enumerate *enumerate = NULL; + struct udev_list_entry *devs = NULL; + struct udev_list_entry *item = NULL; + + if (!_this) { + return true; + } + + enumerate = _this->syms.udev_enumerate_new(_this->udev); + if (!enumerate) { + SDL_UDEV_Quit(); + return SDL_SetError("udev_enumerate_new() failed"); + } + + _this->syms.udev_enumerate_add_match_subsystem(enumerate, "input"); + _this->syms.udev_enumerate_add_match_subsystem(enumerate, "sound"); + _this->syms.udev_enumerate_add_match_subsystem(enumerate, "video4linux"); + + _this->syms.udev_enumerate_scan_devices(enumerate); + devs = _this->syms.udev_enumerate_get_list_entry(enumerate); + for (item = devs; item; item = _this->syms.udev_list_entry_get_next(item)) { + const char *path = _this->syms.udev_list_entry_get_name(item); + struct udev_device *dev = _this->syms.udev_device_new_from_syspath(_this->udev, path); + if (dev) { + device_event(SDL_UDEV_DEVICEADDED, dev); + _this->syms.udev_device_unref(dev); + } + } + + _this->syms.udev_enumerate_unref(enumerate); + return true; +} + +bool SDL_UDEV_GetProductInfo(const char *device_path, Uint16 *vendor, Uint16 *product, Uint16 *version, int *class) +{ + struct stat statbuf; + char type; + struct udev_device *dev; + const char* val; + int class_temp; + + if (!_this) { + return false; + } + + if (stat(device_path, &statbuf) == -1) { + return false; + } + + if (S_ISBLK(statbuf.st_mode)) { + type = 'b'; + } + else if (S_ISCHR(statbuf.st_mode)) { + type = 'c'; + } + else { + return false; + } + + dev = _this->syms.udev_device_new_from_devnum(_this->udev, type, statbuf.st_rdev); + + if (!dev) { + return false; + } + + val = _this->syms.udev_device_get_property_value(dev, "ID_VENDOR_ID"); + if (val) { + *vendor = (Uint16)SDL_strtol(val, NULL, 16); + } + + val = _this->syms.udev_device_get_property_value(dev, "ID_MODEL_ID"); + if (val) { + *product = (Uint16)SDL_strtol(val, NULL, 16); + } + + val = _this->syms.udev_device_get_property_value(dev, "ID_REVISION"); + if (val) { + *version = (Uint16)SDL_strtol(val, NULL, 16); + } + + class_temp = device_class(dev); + if (class_temp) { + *class = class_temp; + } + + _this->syms.udev_device_unref(dev); + + return true; +} + +void SDL_UDEV_UnloadLibrary(void) +{ + if (!_this) { + return; + } + + if (_this->udev_handle) { + SDL_UnloadObject(_this->udev_handle); + _this->udev_handle = NULL; + } +} + +bool SDL_UDEV_LoadLibrary(void) +{ + bool result = true; + + if (!_this) { + return SDL_SetError("UDEV not initialized"); + } + + // See if there is a udev library already loaded + if (SDL_UDEV_load_syms()) { + return true; + } + +#ifdef SDL_UDEV_DYNAMIC + // Check for the build environment's libudev first + if (!_this->udev_handle) { + _this->udev_handle = SDL_LoadObject(SDL_UDEV_DYNAMIC); + if (_this->udev_handle) { + result = SDL_UDEV_load_syms(); + if (!result) { + SDL_UDEV_UnloadLibrary(); + } + } + } +#endif + + if (!_this->udev_handle) { + for (int i = 0; i < SDL_arraysize(SDL_UDEV_LIBS); i++) { + _this->udev_handle = SDL_LoadObject(SDL_UDEV_LIBS[i]); + if (_this->udev_handle) { + result = SDL_UDEV_load_syms(); + if (!result) { + SDL_UDEV_UnloadLibrary(); + } else { + break; + } + } + } + + if (!_this->udev_handle) { + result = false; + // Don't call SDL_SetError(): SDL_LoadObject already did. + } + } + + return result; +} + +static void get_caps(struct udev_device *dev, struct udev_device *pdev, const char *attr, unsigned long *bitmask, size_t bitmask_len) +{ + const char *value; + char text[4096]; + char *word; + int i; + unsigned long v; + + SDL_memset(bitmask, 0, bitmask_len * sizeof(*bitmask)); + value = _this->syms.udev_device_get_sysattr_value(pdev, attr); + if (!value) { + return; + } + + SDL_strlcpy(text, value, sizeof(text)); + i = 0; + while ((word = SDL_strrchr(text, ' ')) != NULL) { + v = SDL_strtoul(word + 1, NULL, 16); + if (i < bitmask_len) { + bitmask[i] = v; + } + ++i; + *word = '\0'; + } + v = SDL_strtoul(text, NULL, 16); + if (i < bitmask_len) { + bitmask[i] = v; + } +} + +static int guess_device_class(struct udev_device *dev) +{ + struct udev_device *pdev; + unsigned long bitmask_props[NBITS(INPUT_PROP_MAX)]; + unsigned long bitmask_ev[NBITS(EV_MAX)]; + unsigned long bitmask_abs[NBITS(ABS_MAX)]; + unsigned long bitmask_key[NBITS(KEY_MAX)]; + unsigned long bitmask_rel[NBITS(REL_MAX)]; + + /* walk up the parental chain until we find the real input device; the + * argument is very likely a subdevice of this, like eventN */ + pdev = dev; + while (pdev && !_this->syms.udev_device_get_sysattr_value(pdev, "capabilities/ev")) { + pdev = _this->syms.udev_device_get_parent_with_subsystem_devtype(pdev, "input", NULL); + } + if (!pdev) { + return 0; + } + + get_caps(dev, pdev, "properties", bitmask_props, SDL_arraysize(bitmask_props)); + get_caps(dev, pdev, "capabilities/ev", bitmask_ev, SDL_arraysize(bitmask_ev)); + get_caps(dev, pdev, "capabilities/abs", bitmask_abs, SDL_arraysize(bitmask_abs)); + get_caps(dev, pdev, "capabilities/rel", bitmask_rel, SDL_arraysize(bitmask_rel)); + get_caps(dev, pdev, "capabilities/key", bitmask_key, SDL_arraysize(bitmask_key)); + + return SDL_EVDEV_GuessDeviceClass(&bitmask_props[0], + &bitmask_ev[0], + &bitmask_abs[0], + &bitmask_key[0], + &bitmask_rel[0]); +} + +static int device_class(struct udev_device *dev) +{ + const char *subsystem; + const char *val = NULL; + int devclass = 0; + + subsystem = _this->syms.udev_device_get_subsystem(dev); + if (!subsystem) { + return 0; + } + + if (SDL_strcmp(subsystem, "sound") == 0) { + devclass = SDL_UDEV_DEVICE_SOUND; + } else if (SDL_strcmp(subsystem, "video4linux") == 0) { + val = _this->syms.udev_device_get_property_value(dev, "ID_V4L_CAPABILITIES"); + if (val && SDL_strcasestr(val, "capture")) { + devclass = SDL_UDEV_DEVICE_VIDEO_CAPTURE; + } + } else if (SDL_strcmp(subsystem, "input") == 0) { + // udev rules reference: http://cgit.freedesktop.org/systemd/systemd/tree/src/udev/udev-builtin-input_id.c + + val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_JOYSTICK"); + if (val && SDL_strcmp(val, "1") == 0) { + devclass |= SDL_UDEV_DEVICE_JOYSTICK; + } + + val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_ACCELEROMETER"); + if (val && SDL_strcmp(val, "1") == 0) { + devclass |= SDL_UDEV_DEVICE_ACCELEROMETER; + } + + val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_MOUSE"); + if (val && SDL_strcmp(val, "1") == 0) { + devclass |= SDL_UDEV_DEVICE_MOUSE; + } + + val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_TOUCHSCREEN"); + if (val && SDL_strcmp(val, "1") == 0) { + devclass |= SDL_UDEV_DEVICE_TOUCHSCREEN; + } + + /* The undocumented rule is: + - All devices with keys get ID_INPUT_KEY + - From this subset, if they have ESC, numbers, and Q to D, it also gets ID_INPUT_KEYBOARD + + Ref: http://cgit.freedesktop.org/systemd/systemd/tree/src/udev/udev-builtin-input_id.c#n183 + */ + val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_KEY"); + if (val && SDL_strcmp(val, "1") == 0) { + devclass |= SDL_UDEV_DEVICE_HAS_KEYS; + } + + val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_KEYBOARD"); + if (val && SDL_strcmp(val, "1") == 0) { + devclass |= SDL_UDEV_DEVICE_KEYBOARD; + } + + if (devclass == 0) { + // Fall back to old style input classes + val = _this->syms.udev_device_get_property_value(dev, "ID_CLASS"); + if (val) { + if (SDL_strcmp(val, "joystick") == 0) { + devclass = SDL_UDEV_DEVICE_JOYSTICK; + } else if (SDL_strcmp(val, "mouse") == 0) { + devclass = SDL_UDEV_DEVICE_MOUSE; + } else if (SDL_strcmp(val, "kbd") == 0) { + devclass = SDL_UDEV_DEVICE_HAS_KEYS | SDL_UDEV_DEVICE_KEYBOARD; + } + } else { + // We could be linked with libudev on a system that doesn't have udev running + devclass = guess_device_class(dev); + } + } + } + + return devclass; +} + +static void device_event(SDL_UDEV_deviceevent type, struct udev_device *dev) +{ + int devclass = 0; + const char *path; + SDL_UDEV_CallbackList *item; + + path = _this->syms.udev_device_get_devnode(dev); + if (!path) { + return; + } + + if (type == SDL_UDEV_DEVICEADDED) { + devclass = device_class(dev); + if (!devclass) { + return; + } + } else { + // The device has been removed, the class isn't available + } + + // Process callbacks + for (item = _this->first; item; item = item->next) { + item->callback(type, devclass, path); + } +} + +void SDL_UDEV_Poll(void) +{ + struct udev_device *dev = NULL; + const char *action = NULL; + + if (!_this) { + return; + } + + while (SDL_UDEV_hotplug_update_available()) { + dev = _this->syms.udev_monitor_receive_device(_this->udev_mon); + if (!dev) { + break; + } + action = _this->syms.udev_device_get_action(dev); + + if (action) { + if (SDL_strcmp(action, "add") == 0) { + device_event(SDL_UDEV_DEVICEADDED, dev); + } else if (SDL_strcmp(action, "remove") == 0) { + device_event(SDL_UDEV_DEVICEREMOVED, dev); + } + } + + _this->syms.udev_device_unref(dev); + } +} + +bool SDL_UDEV_AddCallback(SDL_UDEV_Callback cb) +{ + SDL_UDEV_CallbackList *item; + item = (SDL_UDEV_CallbackList *)SDL_calloc(1, sizeof(SDL_UDEV_CallbackList)); + if (!item) { + return false; + } + + item->callback = cb; + + if (!_this->last) { + _this->first = _this->last = item; + } else { + _this->last->next = item; + _this->last = item; + } + + return true; +} + +void SDL_UDEV_DelCallback(SDL_UDEV_Callback cb) +{ + SDL_UDEV_CallbackList *item; + SDL_UDEV_CallbackList *prev = NULL; + + if (!_this) { + return; + } + + for (item = _this->first; item; item = item->next) { + // found it, remove it. + if (item->callback == cb) { + if (prev) { + prev->next = item->next; + } else { + SDL_assert(_this->first == item); + _this->first = item->next; + } + if (item == _this->last) { + _this->last = prev; + } + SDL_free(item); + return; + } + prev = item; + } +} + +const SDL_UDEV_Symbols *SDL_UDEV_GetUdevSyms(void) +{ + if (!SDL_UDEV_Init()) { + SDL_SetError("Could not initialize UDEV"); + return NULL; + } + + return &_this->syms; +} + +void SDL_UDEV_ReleaseUdevSyms(void) +{ + SDL_UDEV_Quit(); +} + +#endif // SDL_USE_LIBUDEV diff --git a/thirdparty/sdl/core/linux/SDL_udev.h b/thirdparty/sdl/core/linux/SDL_udev.h new file mode 100644 index 00000000000..738f4bafe3f --- /dev/null +++ b/thirdparty/sdl/core/linux/SDL_udev.h @@ -0,0 +1,113 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_udev_h_ +#define SDL_udev_h_ + +#if defined(HAVE_LIBUDEV_H) && defined(HAVE_LINUX_INPUT_H) + +#ifndef SDL_USE_LIBUDEV +#define SDL_USE_LIBUDEV 1 +#endif + +#include +#include +#include + +/** + * Device type + */ + +typedef enum +{ + SDL_UDEV_DEVICEADDED = 1, + SDL_UDEV_DEVICEREMOVED +} SDL_UDEV_deviceevent; + +typedef void (*SDL_UDEV_Callback)(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath); + +typedef struct SDL_UDEV_CallbackList +{ + SDL_UDEV_Callback callback; + struct SDL_UDEV_CallbackList *next; +} SDL_UDEV_CallbackList; + +typedef struct SDL_UDEV_Symbols +{ + const char *(*udev_device_get_action)(struct udev_device *); + const char *(*udev_device_get_devnode)(struct udev_device *); + const char *(*udev_device_get_syspath)(struct udev_device *); + const char *(*udev_device_get_subsystem)(struct udev_device *); + struct udev_device *(*udev_device_get_parent_with_subsystem_devtype)(struct udev_device *udev_device, const char *subsystem, const char *devtype); + const char *(*udev_device_get_property_value)(struct udev_device *, const char *); + const char *(*udev_device_get_sysattr_value)(struct udev_device *udev_device, const char *sysattr); + struct udev_device *(*udev_device_new_from_syspath)(struct udev *, const char *); + void (*udev_device_unref)(struct udev_device *); + int (*udev_enumerate_add_match_property)(struct udev_enumerate *, const char *, const char *); + int (*udev_enumerate_add_match_subsystem)(struct udev_enumerate *, const char *); + struct udev_list_entry *(*udev_enumerate_get_list_entry)(struct udev_enumerate *); + struct udev_enumerate *(*udev_enumerate_new)(struct udev *); + int (*udev_enumerate_scan_devices)(struct udev_enumerate *); + void (*udev_enumerate_unref)(struct udev_enumerate *); + const char *(*udev_list_entry_get_name)(struct udev_list_entry *); + struct udev_list_entry *(*udev_list_entry_get_next)(struct udev_list_entry *); + int (*udev_monitor_enable_receiving)(struct udev_monitor *); + int (*udev_monitor_filter_add_match_subsystem_devtype)(struct udev_monitor *, const char *, const char *); + int (*udev_monitor_get_fd)(struct udev_monitor *); + struct udev_monitor *(*udev_monitor_new_from_netlink)(struct udev *, const char *); + struct udev_device *(*udev_monitor_receive_device)(struct udev_monitor *); + void (*udev_monitor_unref)(struct udev_monitor *); + struct udev *(*udev_new)(void); + void (*udev_unref)(struct udev *); + struct udev_device *(*udev_device_new_from_devnum)(struct udev *udev, char type, dev_t devnum); + dev_t (*udev_device_get_devnum)(struct udev_device *udev_device); +} SDL_UDEV_Symbols; + +typedef struct SDL_UDEV_PrivateData +{ + const char *udev_library; + SDL_SharedObject *udev_handle; + struct udev *udev; + struct udev_monitor *udev_mon; + int ref_count; + SDL_UDEV_CallbackList *first, *last; + + // Function pointers + SDL_UDEV_Symbols syms; +} SDL_UDEV_PrivateData; + +extern bool SDL_UDEV_Init(void); +extern void SDL_UDEV_Quit(void); +extern void SDL_UDEV_UnloadLibrary(void); +extern bool SDL_UDEV_LoadLibrary(void); +extern void SDL_UDEV_Poll(void); +extern bool SDL_UDEV_Scan(void); +extern bool SDL_UDEV_GetProductInfo(const char *device_path, Uint16 *vendor, Uint16 *product, Uint16 *version, int *class); +extern bool SDL_UDEV_AddCallback(SDL_UDEV_Callback cb); +extern void SDL_UDEV_DelCallback(SDL_UDEV_Callback cb); +extern const SDL_UDEV_Symbols *SDL_UDEV_GetUdevSyms(void); +extern void SDL_UDEV_ReleaseUdevSyms(void); + +#endif // HAVE_LIBUDEV_H && HAVE_LINUX_INPUT_H + +#endif // SDL_udev_h_ diff --git a/thirdparty/sdl/core/unix/SDL_appid.c b/thirdparty/sdl/core/unix/SDL_appid.c new file mode 100644 index 00000000000..996e216cd54 --- /dev/null +++ b/thirdparty/sdl/core/unix/SDL_appid.c @@ -0,0 +1,75 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#include "SDL_appid.h" +#include + +const char *SDL_GetExeName(void) +{ + static const char *proc_name = NULL; + + // TODO: Use a fallback if BSD has no mounted procfs (OpenBSD has no procfs at all) + if (!proc_name) { +#if defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_FREEBSD) || defined (SDL_PLATFORM_NETBSD) + static char linkfile[1024]; + int linksize; + +#if defined(SDL_PLATFORM_LINUX) + const char *proc_path = "/proc/self/exe"; +#elif defined(SDL_PLATFORM_FREEBSD) + const char *proc_path = "/proc/curproc/file"; +#elif defined(SDL_PLATFORM_NETBSD) + const char *proc_path = "/proc/curproc/exe"; +#endif + linksize = readlink(proc_path, linkfile, sizeof(linkfile) - 1); + if (linksize > 0) { + linkfile[linksize] = '\0'; + proc_name = SDL_strrchr(linkfile, '/'); + if (proc_name) { + ++proc_name; + } else { + proc_name = linkfile; + } + } +#endif + } + + return proc_name; +} + +const char *SDL_GetAppID(void) +{ + const char *id_str = SDL_GetAppMetadataProperty(SDL_PROP_APP_METADATA_IDENTIFIER_STRING); + + if (!id_str) { + // If the hint isn't set, try to use the application's executable name + id_str = SDL_GetExeName(); + } + + if (!id_str) { + // Finally, use the default we've used forever + id_str = "SDL_App"; + } + + return id_str; +} diff --git a/thirdparty/sdl/core/unix/SDL_appid.h b/thirdparty/sdl/core/unix/SDL_appid.h new file mode 100644 index 00000000000..34825212747 --- /dev/null +++ b/thirdparty/sdl/core/unix/SDL_appid.h @@ -0,0 +1,30 @@ +/* +Simple DirectMedia Layer +Copyright (C) 1997-2025 Sam Lantinga + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_appid_h_ +#define SDL_appid_h_ + +extern const char *SDL_GetExeName(void); +extern const char *SDL_GetAppID(void); + +#endif // SDL_appid_h_ diff --git a/thirdparty/sdl/core/unix/SDL_poll.c b/thirdparty/sdl/core/unix/SDL_poll.c new file mode 100644 index 00000000000..572ed5a65b8 --- /dev/null +++ b/thirdparty/sdl/core/unix/SDL_poll.c @@ -0,0 +1,95 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#include "SDL_poll.h" + +#ifdef HAVE_POLL +#include +#else +#include +#include +#include +#endif +#include + +int SDL_IOReady(int fd, int flags, Sint64 timeoutNS) +{ + int result; + + SDL_assert(flags & (SDL_IOR_READ | SDL_IOR_WRITE)); + + // Note: We don't bother to account for elapsed time if we get EINTR + do { +#ifdef HAVE_POLL + struct pollfd info; + int timeoutMS; + + info.fd = fd; + info.events = 0; + if (flags & SDL_IOR_READ) { + info.events |= POLLIN | POLLPRI; + } + if (flags & SDL_IOR_WRITE) { + info.events |= POLLOUT; + } + // FIXME: Add support for ppoll() for nanosecond precision + if (timeoutNS > 0) { + timeoutMS = (int)SDL_NS_TO_MS(timeoutNS + (SDL_NS_PER_MS - 1)); + } else if (timeoutNS == 0) { + timeoutMS = 0; + } else { + timeoutMS = -1; + } + result = poll(&info, 1, timeoutMS); +#else + fd_set rfdset, *rfdp = NULL; + fd_set wfdset, *wfdp = NULL; + struct timeval tv, *tvp = NULL; + + // If this assert triggers we'll corrupt memory here + SDL_assert(fd >= 0 && fd < FD_SETSIZE); + + if (flags & SDL_IOR_READ) { + FD_ZERO(&rfdset); + FD_SET(fd, &rfdset); + rfdp = &rfdset; + } + if (flags & SDL_IOR_WRITE) { + FD_ZERO(&wfdset); + FD_SET(fd, &wfdset); + wfdp = &wfdset; + } + + if (timeoutNS >= 0) { + tv.tv_sec = (timeoutNS / SDL_NS_PER_SECOND); + tv.tv_usec = SDL_NS_TO_US((timeoutNS % SDL_NS_PER_SECOND) + (SDL_NS_PER_US - 1)); + tvp = &tv; + } + + result = select(fd + 1, rfdp, wfdp, NULL, tvp); +#endif // HAVE_POLL + + } while (result < 0 && errno == EINTR && !(flags & SDL_IOR_NO_RETRY)); + + return result; +} diff --git a/thirdparty/sdl/core/unix/SDL_poll.h b/thirdparty/sdl/core/unix/SDL_poll.h new file mode 100644 index 00000000000..571619d4fe7 --- /dev/null +++ b/thirdparty/sdl/core/unix/SDL_poll.h @@ -0,0 +1,33 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_poll_h_ +#define SDL_poll_h_ + +#define SDL_IOR_READ 0x1 +#define SDL_IOR_WRITE 0x2 +#define SDL_IOR_NO_RETRY 0x4 + +extern int SDL_IOReady(int fd, int flags, Sint64 timeoutNS); + +#endif // SDL_poll_h_ diff --git a/thirdparty/sdl/core/windows/SDL_directx.h b/thirdparty/sdl/core/windows/SDL_directx.h new file mode 100644 index 00000000000..6101e922341 --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_directx.h @@ -0,0 +1,112 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_directx_h_ +#define SDL_directx_h_ + +// Include all of the DirectX 8.0 headers and adds any necessary tweaks + +#include "SDL_windows.h" +#include +#ifndef WIN32 +#define WIN32 +#endif +#undef WINNT + +// Far pointers don't exist in 32-bit code +#ifndef FAR +#define FAR +#endif + +// Error codes not yet included in Win32 API header files +#ifndef MAKE_HRESULT +#define MAKE_HRESULT(sev, fac, code) \ + ((HRESULT)(((unsigned long)(sev) << 31) | ((unsigned long)(fac) << 16) | ((unsigned long)(code)))) +#endif + +#ifndef S_OK +#define S_OK (HRESULT)0x00000000L +#endif + +#ifndef SUCCEEDED +#define SUCCEEDED(x) ((HRESULT)(x) >= 0) +#endif +#ifndef FAILED +#define FAILED(x) ((HRESULT)(x) < 0) +#endif + +#ifndef E_FAIL +#define E_FAIL (HRESULT)0x80000008L +#endif +#ifndef E_NOINTERFACE +#define E_NOINTERFACE (HRESULT)0x80004002L +#endif +#ifndef E_OUTOFMEMORY +#define E_OUTOFMEMORY (HRESULT)0x8007000EL +#endif +#ifndef E_INVALIDARG +#define E_INVALIDARG (HRESULT)0x80070057L +#endif +#ifndef E_NOTIMPL +#define E_NOTIMPL (HRESULT)0x80004001L +#endif +#ifndef REGDB_E_CLASSNOTREG +#define REGDB_E_CLASSNOTREG (HRESULT)0x80040154L +#endif + +// Severity codes +#ifndef SEVERITY_ERROR +#define SEVERITY_ERROR 1 +#endif + +// Error facility codes +#ifndef FACILITY_WIN32 +#define FACILITY_WIN32 7 +#endif + +#ifndef FIELD_OFFSET +#define FIELD_OFFSET(type, field) ((LONG) & (((type *)0)->field)) +#endif + +/* DirectX headers (if it isn't included, I haven't tested it yet) + */ +// We need these defines to mark what version of DirectX API we use +#define DIRECTDRAW_VERSION 0x0700 +#define DIRECTSOUND_VERSION 0x0800 +#define DIRECTINPUT_VERSION 0x0800 // Need version 7 for force feedback. Need version 8 so IDirectInput8_EnumDevices doesn't leak like a sieve... + +#ifdef HAVE_DDRAW_H +#include +#endif +#ifdef HAVE_DSOUND_H +#include +#endif +#ifdef HAVE_DINPUT_H +#include +#else +typedef struct +{ + int unused; +} DIDEVICEINSTANCE; +#endif + +#endif // SDL_directx_h_ diff --git a/thirdparty/sdl/core/windows/SDL_gameinput.c b/thirdparty/sdl/core/windows/SDL_gameinput.c new file mode 100644 index 00000000000..9ac5912db9d --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_gameinput.c @@ -0,0 +1,98 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef HAVE_GAMEINPUT_H + +#include "SDL_windows.h" +#include "SDL_gameinput.h" + +#ifdef SDL_PLATFORM_WIN32 +#include +// {11BE2A7E-4254-445A-9C09-FFC40F006918} +DEFINE_GUID(SDL_IID_GameInput, 0x11BE2A7E, 0x4254, 0x445A, 0x9C, 0x09, 0xFF, 0xC4, 0x0F, 0x00, 0x69, 0x18); +#endif + +static SDL_SharedObject *g_hGameInputDLL; +static IGameInput *g_pGameInput; +static int g_nGameInputRefCount; + +bool SDL_InitGameInput(IGameInput **ppGameInput) +{ + if (g_nGameInputRefCount == 0) { + g_hGameInputDLL = SDL_LoadObject("gameinput.dll"); + if (!g_hGameInputDLL) { + return false; + } + + typedef HRESULT (WINAPI *GameInputCreate_t)(IGameInput * *gameInput); + GameInputCreate_t GameInputCreateFunc = (GameInputCreate_t)SDL_LoadFunction(g_hGameInputDLL, "GameInputCreate"); + if (!GameInputCreateFunc) { + SDL_UnloadObject(g_hGameInputDLL); + return false; + } + + IGameInput *pGameInput = NULL; + HRESULT hr = GameInputCreateFunc(&pGameInput); + if (FAILED(hr)) { + SDL_UnloadObject(g_hGameInputDLL); + return WIN_SetErrorFromHRESULT("GameInputCreate failed", hr); + } + +#ifdef SDL_PLATFORM_WIN32 + hr = IGameInput_QueryInterface(pGameInput, &SDL_IID_GameInput, (void **)&g_pGameInput); + IGameInput_Release(pGameInput); + if (FAILED(hr)) { + SDL_UnloadObject(g_hGameInputDLL); + return WIN_SetErrorFromHRESULT("GameInput QueryInterface failed", hr); + } +#else + // Assume that the version we get is compatible with the current SDK + // If that isn't the case, define the correct GUID for SDL_IID_GameInput above + g_pGameInput = pGameInput; +#endif + } + ++g_nGameInputRefCount; + + if (ppGameInput) { + *ppGameInput = g_pGameInput; + } + return true; +} + +void SDL_QuitGameInput(void) +{ + SDL_assert(g_nGameInputRefCount > 0); + + --g_nGameInputRefCount; + if (g_nGameInputRefCount == 0) { + if (g_pGameInput) { + IGameInput_Release(g_pGameInput); + g_pGameInput = NULL; + } + if (g_hGameInputDLL) { + SDL_UnloadObject(g_hGameInputDLL); + g_hGameInputDLL = NULL; + } + } +} + +#endif // HAVE_GAMEINPUT_H diff --git a/thirdparty/sdl/core/windows/SDL_gameinput.h b/thirdparty/sdl/core/windows/SDL_gameinput.h new file mode 100644 index 00000000000..0022c0bdde1 --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_gameinput.h @@ -0,0 +1,36 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_gameinput_h_ +#define SDL_gameinput_h_ + +#ifdef HAVE_GAMEINPUT_H + +#define COBJMACROS +#include + +extern bool SDL_InitGameInput(IGameInput **ppGameInput); +extern void SDL_QuitGameInput(void); + +#endif // HAVE_GAMEINPUT_H + +#endif // SDL_gameinput_h_ diff --git a/thirdparty/sdl/core/windows/SDL_hid.c b/thirdparty/sdl/core/windows/SDL_hid.c new file mode 100644 index 00000000000..87e873544ab --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_hid.c @@ -0,0 +1,254 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_hid.h" + +HidD_GetAttributes_t SDL_HidD_GetAttributes; +HidD_GetString_t SDL_HidD_GetManufacturerString; +HidD_GetString_t SDL_HidD_GetProductString; +HidP_GetCaps_t SDL_HidP_GetCaps; +HidP_GetButtonCaps_t SDL_HidP_GetButtonCaps; +HidP_GetValueCaps_t SDL_HidP_GetValueCaps; +HidP_MaxDataListLength_t SDL_HidP_MaxDataListLength; +HidP_GetData_t SDL_HidP_GetData; + +static HMODULE s_pHIDDLL = 0; +static int s_HIDDLLRefCount = 0; + + +bool WIN_LoadHIDDLL(void) +{ + if (s_pHIDDLL) { + SDL_assert(s_HIDDLLRefCount > 0); + s_HIDDLLRefCount++; + return true; // already loaded + } + + s_pHIDDLL = LoadLibrary(TEXT("hid.dll")); + if (!s_pHIDDLL) { + return false; + } + + SDL_assert(s_HIDDLLRefCount == 0); + s_HIDDLLRefCount = 1; + + SDL_HidD_GetAttributes = (HidD_GetAttributes_t)GetProcAddress(s_pHIDDLL, "HidD_GetAttributes"); + SDL_HidD_GetManufacturerString = (HidD_GetString_t)GetProcAddress(s_pHIDDLL, "HidD_GetManufacturerString"); + SDL_HidD_GetProductString = (HidD_GetString_t)GetProcAddress(s_pHIDDLL, "HidD_GetProductString"); + SDL_HidP_GetCaps = (HidP_GetCaps_t)GetProcAddress(s_pHIDDLL, "HidP_GetCaps"); + SDL_HidP_GetButtonCaps = (HidP_GetButtonCaps_t)GetProcAddress(s_pHIDDLL, "HidP_GetButtonCaps"); + SDL_HidP_GetValueCaps = (HidP_GetValueCaps_t)GetProcAddress(s_pHIDDLL, "HidP_GetValueCaps"); + SDL_HidP_MaxDataListLength = (HidP_MaxDataListLength_t)GetProcAddress(s_pHIDDLL, "HidP_MaxDataListLength"); + SDL_HidP_GetData = (HidP_GetData_t)GetProcAddress(s_pHIDDLL, "HidP_GetData"); + if (!SDL_HidD_GetManufacturerString || !SDL_HidD_GetProductString || + !SDL_HidP_GetCaps || !SDL_HidP_GetButtonCaps || + !SDL_HidP_GetValueCaps || !SDL_HidP_MaxDataListLength || !SDL_HidP_GetData) { + WIN_UnloadHIDDLL(); + return false; + } + + return true; +} + +void WIN_UnloadHIDDLL(void) +{ + if (s_pHIDDLL) { + SDL_assert(s_HIDDLLRefCount > 0); + if (--s_HIDDLLRefCount == 0) { + FreeLibrary(s_pHIDDLL); + s_pHIDDLL = NULL; + } + } else { + SDL_assert(s_HIDDLLRefCount == 0); + } +} + +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + +// CM_Register_Notification definitions + +#define CR_SUCCESS 0 + +DECLARE_HANDLE(HCMNOTIFICATION); +typedef HCMNOTIFICATION *PHCMNOTIFICATION; + +typedef enum _CM_NOTIFY_FILTER_TYPE +{ + CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE = 0, + CM_NOTIFY_FILTER_TYPE_DEVICEHANDLE, + CM_NOTIFY_FILTER_TYPE_DEVICEINSTANCE, + CM_NOTIFY_FILTER_TYPE_MAX +} CM_NOTIFY_FILTER_TYPE, *PCM_NOTIFY_FILTER_TYPE; + +typedef struct _CM_NOTIFY_FILTER +{ + DWORD cbSize; + DWORD Flags; + CM_NOTIFY_FILTER_TYPE FilterType; + DWORD Reserved; + union + { + struct + { + GUID ClassGuid; + } DeviceInterface; + struct + { + HANDLE hTarget; + } DeviceHandle; + struct + { + WCHAR InstanceId[200]; + } DeviceInstance; + } u; +} CM_NOTIFY_FILTER, *PCM_NOTIFY_FILTER; + +typedef enum _CM_NOTIFY_ACTION +{ + CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL = 0, + CM_NOTIFY_ACTION_DEVICEINTERFACEREMOVAL, + CM_NOTIFY_ACTION_DEVICEQUERYREMOVE, + CM_NOTIFY_ACTION_DEVICEQUERYREMOVEFAILED, + CM_NOTIFY_ACTION_DEVICEREMOVEPENDING, + CM_NOTIFY_ACTION_DEVICEREMOVECOMPLETE, + CM_NOTIFY_ACTION_DEVICECUSTOMEVENT, + CM_NOTIFY_ACTION_DEVICEINSTANCEENUMERATED, + CM_NOTIFY_ACTION_DEVICEINSTANCESTARTED, + CM_NOTIFY_ACTION_DEVICEINSTANCEREMOVED, + CM_NOTIFY_ACTION_MAX +} CM_NOTIFY_ACTION, *PCM_NOTIFY_ACTION; + +typedef struct _CM_NOTIFY_EVENT_DATA +{ + CM_NOTIFY_FILTER_TYPE FilterType; + DWORD Reserved; + union + { + struct + { + GUID ClassGuid; + WCHAR SymbolicLink[ANYSIZE_ARRAY]; + } DeviceInterface; + struct + { + GUID EventGuid; + LONG NameOffset; + DWORD DataSize; + BYTE Data[ANYSIZE_ARRAY]; + } DeviceHandle; + struct + { + WCHAR InstanceId[ANYSIZE_ARRAY]; + } DeviceInstance; + } u; +} CM_NOTIFY_EVENT_DATA, *PCM_NOTIFY_EVENT_DATA; + +typedef DWORD (CALLBACK *PCM_NOTIFY_CALLBACK)(HCMNOTIFICATION hNotify, PVOID Context, CM_NOTIFY_ACTION Action, PCM_NOTIFY_EVENT_DATA EventData, DWORD EventDataSize); + +typedef DWORD (WINAPI *CM_Register_NotificationFunc)(PCM_NOTIFY_FILTER pFilter, PVOID pContext, PCM_NOTIFY_CALLBACK pCallback, PHCMNOTIFICATION pNotifyContext); +typedef DWORD (WINAPI *CM_Unregister_NotificationFunc)(HCMNOTIFICATION NotifyContext); + +static GUID GUID_DEVINTERFACE_HID = { 0x4D1E55B2L, 0xF16F, 0x11CF, { 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } }; + +static int s_DeviceNotificationsRequested; +static HMODULE cfgmgr32_lib_handle; +static CM_Register_NotificationFunc CM_Register_Notification; +static CM_Unregister_NotificationFunc CM_Unregister_Notification; +static HCMNOTIFICATION s_DeviceNotificationFuncHandle; +static Uint64 s_LastDeviceNotification = 1; + +static DWORD CALLBACK SDL_DeviceNotificationFunc(HCMNOTIFICATION hNotify, PVOID context, CM_NOTIFY_ACTION action, PCM_NOTIFY_EVENT_DATA eventData, DWORD event_data_size) +{ + if (action == CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL || + action == CM_NOTIFY_ACTION_DEVICEINTERFACEREMOVAL) { + s_LastDeviceNotification = SDL_GetTicksNS(); + } + return ERROR_SUCCESS; +} + +void WIN_InitDeviceNotification(void) +{ + ++s_DeviceNotificationsRequested; + if (s_DeviceNotificationsRequested > 1) { + return; + } + + cfgmgr32_lib_handle = LoadLibraryA("cfgmgr32.dll"); + if (cfgmgr32_lib_handle) { + CM_Register_Notification = (CM_Register_NotificationFunc)GetProcAddress(cfgmgr32_lib_handle, "CM_Register_Notification"); + CM_Unregister_Notification = (CM_Unregister_NotificationFunc)GetProcAddress(cfgmgr32_lib_handle, "CM_Unregister_Notification"); + if (CM_Register_Notification && CM_Unregister_Notification) { + CM_NOTIFY_FILTER notify_filter; + + SDL_zero(notify_filter); + notify_filter.cbSize = sizeof(notify_filter); + notify_filter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE; + notify_filter.u.DeviceInterface.ClassGuid = GUID_DEVINTERFACE_HID; + if (CM_Register_Notification(¬ify_filter, NULL, SDL_DeviceNotificationFunc, &s_DeviceNotificationFuncHandle) == CR_SUCCESS) { + return; + } + } + } + + // FIXME: Should we log errors? +} + +Uint64 WIN_GetLastDeviceNotification(void) +{ + return s_LastDeviceNotification; +} + +void WIN_QuitDeviceNotification(void) +{ + if (--s_DeviceNotificationsRequested > 0) { + return; + } + // Make sure we have balanced calls to init/quit + SDL_assert(s_DeviceNotificationsRequested == 0); + + if (cfgmgr32_lib_handle) { + if (s_DeviceNotificationFuncHandle && CM_Unregister_Notification) { + CM_Unregister_Notification(s_DeviceNotificationFuncHandle); + s_DeviceNotificationFuncHandle = NULL; + } + + FreeLibrary(cfgmgr32_lib_handle); + cfgmgr32_lib_handle = NULL; + } +} + +#else + +void WIN_InitDeviceNotification(void) +{ +} + +Uint64 WIN_GetLastDeviceNotification( void ) +{ + return 0; +} + +void WIN_QuitDeviceNotification(void) +{ +} + +#endif // !SDL_PLATFORM_XBOXONE && !SDL_PLATFORM_XBOXSERIES diff --git a/thirdparty/sdl/core/windows/SDL_hid.h b/thirdparty/sdl/core/windows/SDL_hid.h new file mode 100644 index 00000000000..46c22f243cf --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_hid.h @@ -0,0 +1,215 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_hid_h_ +#define SDL_hid_h_ + +#include "SDL_windows.h" + +typedef LONG NTSTATUS; +typedef USHORT USAGE; +typedef struct _HIDP_PREPARSED_DATA *PHIDP_PREPARSED_DATA; + +typedef struct _HIDD_ATTRIBUTES +{ + ULONG Size; + USHORT VendorID; + USHORT ProductID; + USHORT VersionNumber; +} HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES; + +typedef enum +{ + HidP_Input = 0, + HidP_Output = 1, + HidP_Feature = 2 +} HIDP_REPORT_TYPE; + +typedef struct +{ + USAGE UsagePage; + UCHAR ReportID; + BOOLEAN IsAlias; + USHORT BitField; + USHORT LinkCollection; + USAGE LinkUsage; + USAGE LinkUsagePage; + BOOLEAN IsRange; + BOOLEAN IsStringRange; + BOOLEAN IsDesignatorRange; + BOOLEAN IsAbsolute; + ULONG Reserved[10]; + union + { + struct + { + USAGE UsageMin; + USAGE UsageMax; + USHORT StringMin; + USHORT StringMax; + USHORT DesignatorMin; + USHORT DesignatorMax; + USHORT DataIndexMin; + USHORT DataIndexMax; + } Range; + struct + { + USAGE Usage; + USAGE Reserved1; + USHORT StringIndex; + USHORT Reserved2; + USHORT DesignatorIndex; + USHORT Reserved3; + USHORT DataIndex; + USHORT Reserved4; + } NotRange; + }; +} HIDP_BUTTON_CAPS, *PHIDP_BUTTON_CAPS; + +typedef struct +{ + USAGE UsagePage; + UCHAR ReportID; + BOOLEAN IsAlias; + USHORT BitField; + USHORT LinkCollection; + USAGE LinkUsage; + USAGE LinkUsagePage; + BOOLEAN IsRange; + BOOLEAN IsStringRange; + BOOLEAN IsDesignatorRange; + BOOLEAN IsAbsolute; + BOOLEAN HasNull; + UCHAR Reserved; + USHORT BitSize; + USHORT ReportCount; + USHORT Reserved2[5]; + ULONG UnitsExp; + ULONG Units; + LONG LogicalMin; + LONG LogicalMax; + LONG PhysicalMin; + LONG PhysicalMax; + union + { + struct + { + USAGE UsageMin; + USAGE UsageMax; + USHORT StringMin; + USHORT StringMax; + USHORT DesignatorMin; + USHORT DesignatorMax; + USHORT DataIndexMin; + USHORT DataIndexMax; + } Range; + struct + { + USAGE Usage; + USAGE Reserved1; + USHORT StringIndex; + USHORT Reserved2; + USHORT DesignatorIndex; + USHORT Reserved3; + USHORT DataIndex; + USHORT Reserved4; + } NotRange; + }; +} HIDP_VALUE_CAPS, *PHIDP_VALUE_CAPS; + +typedef struct +{ + USAGE Usage; + USAGE UsagePage; + USHORT InputReportByteLength; + USHORT OutputReportByteLength; + USHORT FeatureReportByteLength; + USHORT Reserved[17]; + USHORT NumberLinkCollectionNodes; + USHORT NumberInputButtonCaps; + USHORT NumberInputValueCaps; + USHORT NumberInputDataIndices; + USHORT NumberOutputButtonCaps; + USHORT NumberOutputValueCaps; + USHORT NumberOutputDataIndices; + USHORT NumberFeatureButtonCaps; + USHORT NumberFeatureValueCaps; + USHORT NumberFeatureDataIndices; +} HIDP_CAPS, *PHIDP_CAPS; + +typedef struct +{ + USHORT DataIndex; + USHORT Reserved; + union + { + ULONG RawValue; + BOOLEAN On; + }; +} HIDP_DATA, *PHIDP_DATA; + +#define HIDP_ERROR_CODES(p1, p2) ((NTSTATUS)(((p1) << 28) | (0x11 << 16) | (p2))) +#define HIDP_STATUS_SUCCESS HIDP_ERROR_CODES(0x0, 0x0000) +#define HIDP_STATUS_NULL HIDP_ERROR_CODES(0x8, 0x0001) +#define HIDP_STATUS_INVALID_PREPARSED_DATA HIDP_ERROR_CODES(0xC, 0x0001) +#define HIDP_STATUS_INVALID_REPORT_TYPE HIDP_ERROR_CODES(0xC, 0x0002) +#define HIDP_STATUS_INVALID_REPORT_LENGTH HIDP_ERROR_CODES(0xC, 0x0003) +#define HIDP_STATUS_USAGE_NOT_FOUND HIDP_ERROR_CODES(0xC, 0x0004) +#define HIDP_STATUS_VALUE_OUT_OF_RANGE HIDP_ERROR_CODES(0xC, 0x0005) +#define HIDP_STATUS_BAD_LOG_PHY_VALUES HIDP_ERROR_CODES(0xC, 0x0006) +#define HIDP_STATUS_BUFFER_TOO_SMALL HIDP_ERROR_CODES(0xC, 0x0007) +#define HIDP_STATUS_INTERNAL_ERROR HIDP_ERROR_CODES(0xC, 0x0008) +#define HIDP_STATUS_I8042_TRANS_UNKNOWN HIDP_ERROR_CODES(0xC, 0x0009) +#define HIDP_STATUS_INCOMPATIBLE_REPORT_ID HIDP_ERROR_CODES(0xC, 0x000A) +#define HIDP_STATUS_NOT_VALUE_ARRAY HIDP_ERROR_CODES(0xC, 0x000B) +#define HIDP_STATUS_IS_VALUE_ARRAY HIDP_ERROR_CODES(0xC, 0x000C) +#define HIDP_STATUS_DATA_INDEX_NOT_FOUND HIDP_ERROR_CODES(0xC, 0x000D) +#define HIDP_STATUS_DATA_INDEX_OUT_OF_RANGE HIDP_ERROR_CODES(0xC, 0x000E) +#define HIDP_STATUS_BUTTON_NOT_PRESSED HIDP_ERROR_CODES(0xC, 0x000F) +#define HIDP_STATUS_REPORT_DOES_NOT_EXIST HIDP_ERROR_CODES(0xC, 0x0010) +#define HIDP_STATUS_NOT_IMPLEMENTED HIDP_ERROR_CODES(0xC, 0x0020) + +extern bool WIN_LoadHIDDLL(void); +extern void WIN_UnloadHIDDLL(void); + +typedef BOOLEAN (WINAPI *HidD_GetAttributes_t)(HANDLE HidDeviceObject, PHIDD_ATTRIBUTES Attributes); +typedef BOOLEAN (WINAPI *HidD_GetString_t)(HANDLE HidDeviceObject, PVOID Buffer, ULONG BufferLength); +typedef NTSTATUS (WINAPI *HidP_GetCaps_t)(PHIDP_PREPARSED_DATA PreparsedData, PHIDP_CAPS Capabilities); +typedef NTSTATUS (WINAPI *HidP_GetButtonCaps_t)(HIDP_REPORT_TYPE ReportType, PHIDP_BUTTON_CAPS ButtonCaps, PUSHORT ButtonCapsLength, PHIDP_PREPARSED_DATA PreparsedData); +typedef NTSTATUS (WINAPI *HidP_GetValueCaps_t)(HIDP_REPORT_TYPE ReportType, PHIDP_VALUE_CAPS ValueCaps, PUSHORT ValueCapsLength, PHIDP_PREPARSED_DATA PreparsedData); +typedef ULONG (WINAPI *HidP_MaxDataListLength_t)(HIDP_REPORT_TYPE ReportType, PHIDP_PREPARSED_DATA PreparsedData); +typedef NTSTATUS (WINAPI *HidP_GetData_t)(HIDP_REPORT_TYPE ReportType, PHIDP_DATA DataList, PULONG DataLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength); + +extern HidD_GetAttributes_t SDL_HidD_GetAttributes; +extern HidD_GetString_t SDL_HidD_GetManufacturerString; +extern HidD_GetString_t SDL_HidD_GetProductString; +extern HidP_GetCaps_t SDL_HidP_GetCaps; +extern HidP_GetButtonCaps_t SDL_HidP_GetButtonCaps; +extern HidP_GetValueCaps_t SDL_HidP_GetValueCaps; +extern HidP_MaxDataListLength_t SDL_HidP_MaxDataListLength; +extern HidP_GetData_t SDL_HidP_GetData; + +void WIN_InitDeviceNotification(void); +Uint64 WIN_GetLastDeviceNotification(void); +void WIN_QuitDeviceNotification(void); + +#endif // SDL_hid_h_ diff --git a/thirdparty/sdl/core/windows/SDL_immdevice.c b/thirdparty/sdl/core/windows/SDL_immdevice.c new file mode 100644 index 00000000000..802a412e15e --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_immdevice.c @@ -0,0 +1,434 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(SDL_PLATFORM_WINDOWS) && defined(HAVE_MMDEVICEAPI_H) + +#include "SDL_windows.h" +#include "SDL_immdevice.h" +#include "../../audio/SDL_sysaudio.h" +#include // For CLSIDFromString + +typedef struct SDL_IMMDevice_HandleData +{ + LPWSTR immdevice_id; + GUID directsound_guid; +} SDL_IMMDevice_HandleData; + +static const ERole SDL_IMMDevice_role = eConsole; // !!! FIXME: should this be eMultimedia? Should be a hint? + +// This is global to the WASAPI target, to handle hotplug and default device lookup. +static IMMDeviceEnumerator *enumerator = NULL; +static SDL_IMMDevice_callbacks immcallbacks; + +// PropVariantInit() is an inline function/macro in PropIdl.h that calls the C runtime's memset() directly. Use ours instead, to avoid dependency. +#ifdef PropVariantInit +#undef PropVariantInit +#endif +#define PropVariantInit(p) SDL_zerop(p) + +// Some GUIDs we need to know without linking to libraries that aren't available before Vista. +/* *INDENT-OFF* */ // clang-format off +static const CLSID SDL_CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c,{ 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } }; +static const IID SDL_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35,{ 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } }; +static const IID SDL_IID_IMMNotificationClient = { 0x7991eec9, 0x7e89, 0x4d85,{ 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0 } }; +static const IID SDL_IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089,{ 0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5 } }; +static const PROPERTYKEY SDL_PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd,{ 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, } }, 14 }; +static const PROPERTYKEY SDL_PKEY_AudioEngine_DeviceFormat = { { 0xf19f064d, 0x82c, 0x4e27,{ 0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c, } }, 0 }; +static const PROPERTYKEY SDL_PKEY_AudioEndpoint_GUID = { { 0x1da5d803, 0xd492, 0x4edd,{ 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, } }, 4 }; +/* *INDENT-ON* */ // clang-format on + +static bool FindByDevIDCallback(SDL_AudioDevice *device, void *userdata) +{ + LPCWSTR devid = (LPCWSTR)userdata; + if (devid && device && device->handle) { + const SDL_IMMDevice_HandleData *handle = (const SDL_IMMDevice_HandleData *)device->handle; + if (handle->immdevice_id && SDL_wcscmp(handle->immdevice_id, devid) == 0) { + return true; + } + } + return false; +} + +static SDL_AudioDevice *SDL_IMMDevice_FindByDevID(LPCWSTR devid) +{ + return SDL_FindPhysicalAudioDeviceByCallback(FindByDevIDCallback, (void *) devid); +} + +LPGUID SDL_IMMDevice_GetDirectSoundGUID(SDL_AudioDevice *device) +{ + return (device && device->handle) ? &(((SDL_IMMDevice_HandleData *) device->handle)->directsound_guid) : NULL; +} + +LPCWSTR SDL_IMMDevice_GetDevID(SDL_AudioDevice *device) +{ + return (device && device->handle) ? ((const SDL_IMMDevice_HandleData *) device->handle)->immdevice_id : NULL; +} + +static void GetMMDeviceInfo(IMMDevice *device, char **utf8dev, WAVEFORMATEXTENSIBLE *fmt, GUID *guid) +{ + /* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be + "SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in + its own UIs, like Volume Control, etc. */ + IPropertyStore *props = NULL; + *utf8dev = NULL; + SDL_zerop(fmt); + if (SUCCEEDED(IMMDevice_OpenPropertyStore(device, STGM_READ, &props))) { + PROPVARIANT var; + PropVariantInit(&var); + if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_Device_FriendlyName, &var))) { + *utf8dev = WIN_StringToUTF8W(var.pwszVal); + } + PropVariantClear(&var); + if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_AudioEngine_DeviceFormat, &var))) { + SDL_memcpy(fmt, var.blob.pBlobData, SDL_min(var.blob.cbSize, sizeof(WAVEFORMATEXTENSIBLE))); + } + PropVariantClear(&var); + if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_AudioEndpoint_GUID, &var))) { + (void)CLSIDFromString(var.pwszVal, guid); + } + PropVariantClear(&var); + IPropertyStore_Release(props); + } +} + +void SDL_IMMDevice_FreeDeviceHandle(SDL_AudioDevice *device) +{ + if (device && device->handle) { + SDL_IMMDevice_HandleData *handle = (SDL_IMMDevice_HandleData *) device->handle; + SDL_free(handle->immdevice_id); + SDL_free(handle); + device->handle = NULL; + } +} + +static SDL_AudioDevice *SDL_IMMDevice_Add(const bool recording, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid, GUID *dsoundguid) +{ + /* You can have multiple endpoints on a device that are mutually exclusive ("Speakers" vs "Line Out" or whatever). + In a perfect world, things that are unplugged won't be in this collection. The only gotcha is probably for + phones and tablets, where you might have an internal speaker and a headphone jack and expect both to be + available and switch automatically. (!!! FIXME...?) */ + + if (!devname) { + return NULL; + } + + // see if we already have this one first. + SDL_AudioDevice *device = SDL_IMMDevice_FindByDevID(devid); + if (device) { + if (SDL_GetAtomicInt(&device->zombie)) { + // whoa, it came back! This can happen if you unplug and replug USB headphones while we're still keeping the SDL object alive. + // Kill this device's IMMDevice id; the device will go away when the app closes it, or maybe a new default device is chosen + // (possibly this reconnected device), so we just want to make sure IMMDevice doesn't try to find the old device by the existing ID string. + SDL_IMMDevice_HandleData *handle = (SDL_IMMDevice_HandleData *) device->handle; + SDL_free(handle->immdevice_id); + handle->immdevice_id = NULL; + device = NULL; // add a new device, below. + } + } + + if (!device) { + // handle is freed by SDL_IMMDevice_FreeDeviceHandle! + SDL_IMMDevice_HandleData *handle = (SDL_IMMDevice_HandleData *)SDL_malloc(sizeof(SDL_IMMDevice_HandleData)); + if (!handle) { + return NULL; + } + handle->immdevice_id = SDL_wcsdup(devid); + if (!handle->immdevice_id) { + SDL_free(handle); + return NULL; + } + SDL_memcpy(&handle->directsound_guid, dsoundguid, sizeof(GUID)); + + SDL_AudioSpec spec; + SDL_zero(spec); + spec.channels = (Uint8)fmt->Format.nChannels; + spec.freq = fmt->Format.nSamplesPerSec; + spec.format = SDL_WaveFormatExToSDLFormat((WAVEFORMATEX *)fmt); + + device = SDL_AddAudioDevice(recording, devname, &spec, handle); + if (!device) { + SDL_free(handle->immdevice_id); + SDL_free(handle); + } + } + + return device; +} + +/* We need a COM subclass of IMMNotificationClient for hotplug support, which is + easy in C++, but we have to tapdance more to make work in C. + Thanks to this page for coaching on how to make this work: + https://www.codeproject.com/Articles/13601/COM-in-plain-C */ + +typedef struct SDLMMNotificationClient +{ + const IMMNotificationClientVtbl *lpVtbl; + SDL_AtomicInt refcount; +} SDLMMNotificationClient; + +static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_QueryInterface(IMMNotificationClient *client, REFIID iid, void **ppv) +{ + if ((WIN_IsEqualIID(iid, &IID_IUnknown)) || (WIN_IsEqualIID(iid, &SDL_IID_IMMNotificationClient))) { + *ppv = client; + client->lpVtbl->AddRef(client); + return S_OK; + } + + *ppv = NULL; + return E_NOINTERFACE; +} + +static ULONG STDMETHODCALLTYPE SDLMMNotificationClient_AddRef(IMMNotificationClient *iclient) +{ + SDLMMNotificationClient *client = (SDLMMNotificationClient *)iclient; + return (ULONG)(SDL_AtomicIncRef(&client->refcount) + 1); +} + +static ULONG STDMETHODCALLTYPE SDLMMNotificationClient_Release(IMMNotificationClient *iclient) +{ + // client is a static object; we don't ever free it. + SDLMMNotificationClient *client = (SDLMMNotificationClient *)iclient; + const ULONG rc = SDL_AtomicDecRef(&client->refcount); + if (rc == 0) { + SDL_SetAtomicInt(&client->refcount, 0); // uhh... + return 0; + } + return rc - 1; +} + +// These are the entry points called when WASAPI device endpoints change. +static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *iclient, EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId) +{ + if (role == SDL_IMMDevice_role) { + immcallbacks.default_audio_device_changed(SDL_IMMDevice_FindByDevID(pwstrDeviceId)); + } + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *iclient, LPCWSTR pwstrDeviceId) +{ + /* we ignore this; devices added here then progress to ACTIVE, if appropriate, in + OnDeviceStateChange, making that a better place to deal with device adds. More + importantly: the first time you plug in a USB audio device, this callback will + fire, but when you unplug it, it isn't removed (it's state changes to NOTPRESENT). + Plugging it back in won't fire this callback again. */ + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceRemoved(IMMNotificationClient *iclient, LPCWSTR pwstrDeviceId) +{ + return S_OK; // See notes in OnDeviceAdded handler about why we ignore this. +} + +static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *iclient, LPCWSTR pwstrDeviceId, DWORD dwNewState) +{ + IMMDevice *device = NULL; + + if (SUCCEEDED(IMMDeviceEnumerator_GetDevice(enumerator, pwstrDeviceId, &device))) { + IMMEndpoint *endpoint = NULL; + if (SUCCEEDED(IMMDevice_QueryInterface(device, &SDL_IID_IMMEndpoint, (void **)&endpoint))) { + EDataFlow flow; + if (SUCCEEDED(IMMEndpoint_GetDataFlow(endpoint, &flow))) { + const bool recording = (flow == eCapture); + if (dwNewState == DEVICE_STATE_ACTIVE) { + char *utf8dev; + WAVEFORMATEXTENSIBLE fmt; + GUID dsoundguid; + GetMMDeviceInfo(device, &utf8dev, &fmt, &dsoundguid); + if (utf8dev) { + SDL_IMMDevice_Add(recording, utf8dev, &fmt, pwstrDeviceId, &dsoundguid); + SDL_free(utf8dev); + } + } else { + immcallbacks.audio_device_disconnected(SDL_IMMDevice_FindByDevID(pwstrDeviceId)); + } + } + IMMEndpoint_Release(endpoint); + } + IMMDevice_Release(device); + } + + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnPropertyValueChanged(IMMNotificationClient *client, LPCWSTR pwstrDeviceId, const PROPERTYKEY key) +{ + return S_OK; // we don't care about these. +} + +static const IMMNotificationClientVtbl notification_client_vtbl = { + SDLMMNotificationClient_QueryInterface, + SDLMMNotificationClient_AddRef, + SDLMMNotificationClient_Release, + SDLMMNotificationClient_OnDeviceStateChanged, + SDLMMNotificationClient_OnDeviceAdded, + SDLMMNotificationClient_OnDeviceRemoved, + SDLMMNotificationClient_OnDefaultDeviceChanged, + SDLMMNotificationClient_OnPropertyValueChanged +}; + +static SDLMMNotificationClient notification_client = { ¬ification_client_vtbl, { 1 } }; + +bool SDL_IMMDevice_Init(const SDL_IMMDevice_callbacks *callbacks) +{ + HRESULT ret; + + // just skip the discussion with COM here. + if (!WIN_IsWindowsVistaOrGreater()) { + return SDL_SetError("IMMDevice support requires Windows Vista or later"); + } + + if (FAILED(WIN_CoInitialize())) { + return SDL_SetError("IMMDevice: CoInitialize() failed"); + } + + ret = CoCreateInstance(&SDL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &SDL_IID_IMMDeviceEnumerator, (LPVOID *)&enumerator); + if (FAILED(ret)) { + WIN_CoUninitialize(); + return WIN_SetErrorFromHRESULT("IMMDevice CoCreateInstance(MMDeviceEnumerator)", ret); + } + + if (callbacks) { + SDL_copyp(&immcallbacks, callbacks); + } else { + SDL_zero(immcallbacks); + } + + if (!immcallbacks.audio_device_disconnected) { + immcallbacks.audio_device_disconnected = SDL_AudioDeviceDisconnected; + } + if (!immcallbacks.default_audio_device_changed) { + immcallbacks.default_audio_device_changed = SDL_DefaultAudioDeviceChanged; + } + + return true; +} + +void SDL_IMMDevice_Quit(void) +{ + if (enumerator) { + IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *)¬ification_client); + IMMDeviceEnumerator_Release(enumerator); + enumerator = NULL; + } + + SDL_zero(immcallbacks); + + WIN_CoUninitialize(); +} + +bool SDL_IMMDevice_Get(SDL_AudioDevice *device, IMMDevice **immdevice, bool recording) +{ + const Uint64 timeout = SDL_GetTicks() + 8000; // intel's audio drivers can fail for up to EIGHT SECONDS after a device is connected or we wake from sleep. + + SDL_assert(device != NULL); + SDL_assert(immdevice != NULL); + + LPCWSTR devid = SDL_IMMDevice_GetDevID(device); + SDL_assert(devid != NULL); + + HRESULT ret; + while ((ret = IMMDeviceEnumerator_GetDevice(enumerator, devid, immdevice)) == E_NOTFOUND) { + const Uint64 now = SDL_GetTicks(); + if (timeout > now) { + const Uint64 ticksleft = timeout - now; + SDL_Delay((Uint32)SDL_min(ticksleft, 300)); // wait awhile and try again. + continue; + } + break; + } + + if (!SUCCEEDED(ret)) { + return WIN_SetErrorFromHRESULT("WASAPI can't find requested audio endpoint", ret); + } + return true; +} + +static void EnumerateEndpointsForFlow(const bool recording, SDL_AudioDevice **default_device) +{ + /* Note that WASAPI separates "adapter devices" from "audio endpoint devices" + ...one adapter device ("SoundBlaster Pro") might have multiple endpoint devices ("Speakers", "Line-Out"). */ + + IMMDeviceCollection *collection = NULL; + if (FAILED(IMMDeviceEnumerator_EnumAudioEndpoints(enumerator, recording ? eCapture : eRender, DEVICE_STATE_ACTIVE, &collection))) { + return; + } + + UINT total = 0; + if (FAILED(IMMDeviceCollection_GetCount(collection, &total))) { + IMMDeviceCollection_Release(collection); + return; + } + + LPWSTR default_devid = NULL; + if (default_device) { + IMMDevice *default_immdevice = NULL; + const EDataFlow dataflow = recording ? eCapture : eRender; + if (SUCCEEDED(IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_IMMDevice_role, &default_immdevice))) { + LPWSTR devid = NULL; + if (SUCCEEDED(IMMDevice_GetId(default_immdevice, &devid))) { + default_devid = SDL_wcsdup(devid); // if this fails, oh well. + CoTaskMemFree(devid); + } + IMMDevice_Release(default_immdevice); + } + } + + for (UINT i = 0; i < total; i++) { + IMMDevice *immdevice = NULL; + if (SUCCEEDED(IMMDeviceCollection_Item(collection, i, &immdevice))) { + LPWSTR devid = NULL; + if (SUCCEEDED(IMMDevice_GetId(immdevice, &devid))) { + char *devname = NULL; + WAVEFORMATEXTENSIBLE fmt; + GUID dsoundguid; + SDL_zero(fmt); + SDL_zero(dsoundguid); + GetMMDeviceInfo(immdevice, &devname, &fmt, &dsoundguid); + if (devname) { + SDL_AudioDevice *sdldevice = SDL_IMMDevice_Add(recording, devname, &fmt, devid, &dsoundguid); + if (default_device && default_devid && SDL_wcscmp(default_devid, devid) == 0) { + *default_device = sdldevice; + } + SDL_free(devname); + } + CoTaskMemFree(devid); + } + IMMDevice_Release(immdevice); + } + } + + SDL_free(default_devid); + + IMMDeviceCollection_Release(collection); +} + +void SDL_IMMDevice_EnumerateEndpoints(SDL_AudioDevice **default_playback, SDL_AudioDevice **default_recording) +{ + EnumerateEndpointsForFlow(false, default_playback); + EnumerateEndpointsForFlow(true, default_recording); + + // if this fails, we just won't get hotplug events. Carry on anyhow. + IMMDeviceEnumerator_RegisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *)¬ification_client); +} + +#endif // defined(SDL_PLATFORM_WINDOWS) && defined(HAVE_MMDEVICEAPI_H) diff --git a/thirdparty/sdl/core/windows/SDL_immdevice.h b/thirdparty/sdl/core/windows/SDL_immdevice.h new file mode 100644 index 00000000000..66fdf13b814 --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_immdevice.h @@ -0,0 +1,45 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_IMMDEVICE_H +#define SDL_IMMDEVICE_H + +#define COBJMACROS +#include +#include + +struct SDL_AudioDevice; // defined in src/audio/SDL_sysaudio.h + +typedef struct SDL_IMMDevice_callbacks +{ + void (*audio_device_disconnected)(struct SDL_AudioDevice *device); + void (*default_audio_device_changed)(struct SDL_AudioDevice *new_default_device); +} SDL_IMMDevice_callbacks; + +bool SDL_IMMDevice_Init(const SDL_IMMDevice_callbacks *callbacks); +void SDL_IMMDevice_Quit(void); +bool SDL_IMMDevice_Get(struct SDL_AudioDevice *device, IMMDevice **immdevice, bool recording); +void SDL_IMMDevice_EnumerateEndpoints(struct SDL_AudioDevice **default_playback, struct SDL_AudioDevice **default_recording); +LPGUID SDL_IMMDevice_GetDirectSoundGUID(struct SDL_AudioDevice *device); +LPCWSTR SDL_IMMDevice_GetDevID(struct SDL_AudioDevice *device); +void SDL_IMMDevice_FreeDeviceHandle(struct SDL_AudioDevice *device); + +#endif // SDL_IMMDEVICE_H diff --git a/thirdparty/sdl/core/windows/SDL_windows.c b/thirdparty/sdl/core/windows/SDL_windows.c new file mode 100644 index 00000000000..3259e787d4e --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_windows.c @@ -0,0 +1,375 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(SDL_PLATFORM_WINDOWS) + +#include "SDL_windows.h" + +#include // for CoInitialize/CoUninitialize (Win32 only) +#ifdef HAVE_ROAPI_H +#include // For RoInitialize/RoUninitialize (Win32 only) +#else +typedef enum RO_INIT_TYPE +{ + RO_INIT_SINGLETHREADED = 0, + RO_INIT_MULTITHREADED = 1 +} RO_INIT_TYPE; +#endif + +#ifndef _WIN32_WINNT_VISTA +#define _WIN32_WINNT_VISTA 0x0600 +#endif +#ifndef _WIN32_WINNT_WIN7 +#define _WIN32_WINNT_WIN7 0x0601 +#endif +#ifndef _WIN32_WINNT_WIN8 +#define _WIN32_WINNT_WIN8 0x0602 +#endif + +#ifndef LOAD_LIBRARY_SEARCH_SYSTEM32 +#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800 +#endif + +#ifndef WC_ERR_INVALID_CHARS +#define WC_ERR_INVALID_CHARS 0x00000080 +#endif + +// Sets an error message based on an HRESULT +bool WIN_SetErrorFromHRESULT(const char *prefix, HRESULT hr) +{ + TCHAR buffer[1024]; + char *message; + TCHAR *p = buffer; + DWORD c = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, hr, 0, + buffer, SDL_arraysize(buffer), NULL); + buffer[c] = 0; + // kill CR/LF that FormatMessage() sticks at the end + while (*p) { + if (*p == '\r') { + *p = 0; + break; + } + ++p; + } + message = WIN_StringToUTF8(buffer); + SDL_SetError("%s%s%s", prefix ? prefix : "", prefix ? ": " : "", message); + SDL_free(message); + return false; +} + +// Sets an error message based on GetLastError() +bool WIN_SetError(const char *prefix) +{ + return WIN_SetErrorFromHRESULT(prefix, GetLastError()); +} + +HRESULT +WIN_CoInitialize(void) +{ + /* SDL handles any threading model, so initialize with the default, which + is compatible with OLE and if that doesn't work, try multi-threaded mode. + + If you need multi-threaded mode, call CoInitializeEx() before SDL_Init() + */ +#if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) + // On Xbox, there's no need to call CoInitializeEx (and it's not implemented) + return S_OK; +#else + HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); + if (hr == RPC_E_CHANGED_MODE) { + hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); + } + + // S_FALSE means success, but someone else already initialized. + // You still need to call CoUninitialize in this case! + if (hr == S_FALSE) { + return S_OK; + } + + return hr; +#endif +} + +void WIN_CoUninitialize(void) +{ + CoUninitialize(); +} + +FARPROC WIN_LoadComBaseFunction(const char *name) +{ + static bool s_bLoaded; + static HMODULE s_hComBase; + + if (!s_bLoaded) { + s_hComBase = LoadLibraryEx(TEXT("combase.dll"), NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); + s_bLoaded = true; + } + if (s_hComBase) { + return GetProcAddress(s_hComBase, name); + } else { + return NULL; + } +} + +HRESULT +WIN_RoInitialize(void) +{ + typedef HRESULT(WINAPI * RoInitialize_t)(RO_INIT_TYPE initType); + RoInitialize_t RoInitializeFunc = (RoInitialize_t)WIN_LoadComBaseFunction("RoInitialize"); + if (RoInitializeFunc) { + // RO_INIT_SINGLETHREADED is equivalent to COINIT_APARTMENTTHREADED + HRESULT hr = RoInitializeFunc(RO_INIT_SINGLETHREADED); + if (hr == RPC_E_CHANGED_MODE) { + hr = RoInitializeFunc(RO_INIT_MULTITHREADED); + } + + // S_FALSE means success, but someone else already initialized. + // You still need to call RoUninitialize in this case! + if (hr == S_FALSE) { + return S_OK; + } + + return hr; + } else { + return E_NOINTERFACE; + } +} + +void WIN_RoUninitialize(void) +{ + typedef void(WINAPI * RoUninitialize_t)(void); + RoUninitialize_t RoUninitializeFunc = (RoUninitialize_t)WIN_LoadComBaseFunction("RoUninitialize"); + if (RoUninitializeFunc) { + RoUninitializeFunc(); + } +} + +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) +static BOOL IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor) +{ + OSVERSIONINFOEXW osvi; + DWORDLONG const dwlConditionMask = VerSetConditionMask( + VerSetConditionMask( + VerSetConditionMask( + 0, VER_MAJORVERSION, VER_GREATER_EQUAL), + VER_MINORVERSION, VER_GREATER_EQUAL), + VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); + + SDL_zero(osvi); + osvi.dwOSVersionInfoSize = sizeof(osvi); + osvi.dwMajorVersion = wMajorVersion; + osvi.dwMinorVersion = wMinorVersion; + osvi.wServicePackMajor = wServicePackMajor; + + return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE; +} +#endif + +// apply some static variables so we only call into the Win32 API once per process for each check. +#if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) + #define CHECKWINVER(notdesktop_platform_result, test) return (notdesktop_platform_result); +#else + #define CHECKWINVER(notdesktop_platform_result, test) \ + static bool checked = false; \ + static BOOL result = FALSE; \ + if (!checked) { \ + result = (test); \ + checked = true; \ + } \ + return result; +#endif + +// this is the oldest thing we run on (and we may lose support for this in SDL3 at any time!), +// so there's no "OrGreater" as that would always be TRUE. The other functions are here to +// ask "can we support a specific feature?" but this function is here to ask "do we need to do +// something different for an OS version we probably should abandon?" :) +BOOL WIN_IsWindowsXP(void) +{ + CHECKWINVER(FALSE, !WIN_IsWindowsVistaOrGreater() && IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0)); +} + +BOOL WIN_IsWindowsVistaOrGreater(void) +{ + CHECKWINVER(TRUE, IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0)); +} + +BOOL WIN_IsWindows7OrGreater(void) +{ + CHECKWINVER(TRUE, IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0)); +} + +BOOL WIN_IsWindows8OrGreater(void) +{ + CHECKWINVER(TRUE, IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8), 0)); +} + +#undef CHECKWINVER + + +/* +WAVExxxCAPS gives you 31 bytes for the device name, and just truncates if it's +longer. However, since WinXP, you can use the WAVExxxCAPS2 structure, which +will give you a name GUID. The full name is in the Windows Registry under +that GUID, located here: HKLM\System\CurrentControlSet\Control\MediaCategories + +Note that drivers can report GUID_NULL for the name GUID, in which case, +Windows makes a best effort to fill in those 31 bytes in the usual place. +This info summarized from MSDN: + +http://web.archive.org/web/20131027093034/http://msdn.microsoft.com/en-us/library/windows/hardware/ff536382(v=vs.85).aspx + +Always look this up in the registry if possible, because the strings are +different! At least on Win10, I see "Yeti Stereo Microphone" in the +Registry, and a unhelpful "Microphone(Yeti Stereo Microph" in winmm. Sigh. + +(Also, DirectSound shouldn't be limited to 32 chars, but its device enum +has the same problem.) + +WASAPI doesn't need this. This is just for DirectSound/WinMM. +*/ +char *WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid) +{ +#if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) + return WIN_StringToUTF8W(name); // No registry access on Xbox, go with what we've got. +#else + static const GUID nullguid = { 0 }; + const unsigned char *ptr; + char keystr[128]; + WCHAR *strw = NULL; + bool rc; + HKEY hkey; + DWORD len = 0; + char *result = NULL; + + if (WIN_IsEqualGUID(guid, &nullguid)) { + return WIN_StringToUTF8(name); // No GUID, go with what we've got. + } + + ptr = (const unsigned char *)guid; + (void)SDL_snprintf(keystr, sizeof(keystr), + "System\\CurrentControlSet\\Control\\MediaCategories\\{%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X}", + ptr[3], ptr[2], ptr[1], ptr[0], ptr[5], ptr[4], ptr[7], ptr[6], + ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]); + + strw = WIN_UTF8ToString(keystr); + rc = (RegOpenKeyExW(HKEY_LOCAL_MACHINE, strw, 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS); + SDL_free(strw); + if (!rc) { + return WIN_StringToUTF8(name); // oh well. + } + + rc = (RegQueryValueExW(hkey, L"Name", NULL, NULL, NULL, &len) == ERROR_SUCCESS); + if (!rc) { + RegCloseKey(hkey); + return WIN_StringToUTF8(name); // oh well. + } + + strw = (WCHAR *)SDL_malloc(len + sizeof(WCHAR)); + if (!strw) { + RegCloseKey(hkey); + return WIN_StringToUTF8(name); // oh well. + } + + rc = (RegQueryValueExW(hkey, L"Name", NULL, NULL, (LPBYTE)strw, &len) == ERROR_SUCCESS); + RegCloseKey(hkey); + if (!rc) { + SDL_free(strw); + return WIN_StringToUTF8(name); // oh well. + } + + strw[len / 2] = 0; // make sure it's null-terminated. + + result = WIN_StringToUTF8(strw); + SDL_free(strw); + return result ? result : WIN_StringToUTF8(name); +#endif +} + +BOOL WIN_IsEqualGUID(const GUID *a, const GUID *b) +{ + return (SDL_memcmp(a, b, sizeof(*a)) == 0); +} + +BOOL WIN_IsEqualIID(REFIID a, REFIID b) +{ + return (SDL_memcmp(a, b, sizeof(*a)) == 0); +} + +void WIN_RECTToRect(const RECT *winrect, SDL_Rect *sdlrect) +{ + sdlrect->x = winrect->left; + sdlrect->w = (winrect->right - winrect->left) + 1; + sdlrect->y = winrect->top; + sdlrect->h = (winrect->bottom - winrect->top) + 1; +} + +void WIN_RectToRECT(const SDL_Rect *sdlrect, RECT *winrect) +{ + winrect->left = sdlrect->x; + winrect->right = sdlrect->x + sdlrect->w - 1; + winrect->top = sdlrect->y; + winrect->bottom = sdlrect->y + sdlrect->h - 1; +} + +bool WIN_WindowRectValid(const RECT *rect) +{ + // A window can be resized to zero height, but not zero width + return (rect->right > 0); +} + +// Some GUIDs we need to know without linking to libraries that aren't available before Vista. +/* *INDENT-OFF* */ // clang-format off +static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; +static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; +/* *INDENT-ON* */ // clang-format on + +SDL_AudioFormat SDL_WaveFormatExToSDLFormat(WAVEFORMATEX *waveformat) +{ + if ((waveformat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) && (waveformat->wBitsPerSample == 32)) { + return SDL_AUDIO_F32; + } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 16)) { + return SDL_AUDIO_S16; + } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 32)) { + return SDL_AUDIO_S32; + } else if (waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { + const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *)waveformat; + if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 32)) { + return SDL_AUDIO_F32; + } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 16)) { + return SDL_AUDIO_S16; + } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 32)) { + return SDL_AUDIO_S32; + } + } + return SDL_AUDIO_UNKNOWN; +} + + +int WIN_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWCH lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar) +{ + if (WIN_IsWindowsXP()) { + dwFlags &= ~WC_ERR_INVALID_CHARS; // not supported before Vista. Without this flag, it will just replace bogus chars with U+FFFD. You're on your own, WinXP. + } + return WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr, cbMultiByte, lpDefaultChar, lpUsedDefaultChar); +} + +#endif // defined(SDL_PLATFORM_WINDOWS) diff --git a/thirdparty/sdl/core/windows/SDL_windows.h b/thirdparty/sdl/core/windows/SDL_windows.h new file mode 100644 index 00000000000..ef54fe379e6 --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_windows.h @@ -0,0 +1,172 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +// This is an include file for windows.h with the SDL build settings + +#ifndef _INCLUDED_WINDOWS_H +#define _INCLUDED_WINDOWS_H + +#ifdef SDL_PLATFORM_WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#ifndef STRICT +#define STRICT 1 +#endif +#ifndef UNICODE +#define UNICODE 1 +#endif +#undef WINVER +#undef _WIN32_WINNT +#if defined(SDL_VIDEO_RENDER_D3D12) || defined(HAVE_DXGI1_6_H) +#define _WIN32_WINNT 0xA00 // For D3D12, 0xA00 is required +#elif defined(HAVE_SHELLSCALINGAPI_H) +#define _WIN32_WINNT 0x603 // For DPI support +#else +#define _WIN32_WINNT 0x501 // Need 0x410 for AlphaBlend() and 0x500 for EnumDisplayDevices(), 0x501 for raw input +#endif +#define WINVER _WIN32_WINNT + +#elif defined(SDL_PLATFORM_WINGDK) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#ifndef STRICT +#define STRICT 1 +#endif +#ifndef UNICODE +#define UNICODE 1 +#endif +#undef WINVER +#undef _WIN32_WINNT +#define _WIN32_WINNT 0xA00 +#define WINVER _WIN32_WINNT + +#elif defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#ifndef STRICT +#define STRICT 1 +#endif +#ifndef UNICODE +#define UNICODE 1 +#endif +#undef WINVER +#undef _WIN32_WINNT +#define _WIN32_WINNT 0xA00 +#define WINVER _WIN32_WINNT +#endif + +// See https://github.com/libsdl-org/SDL/pull/7607 +// force_align_arg_pointer attribute requires gcc >= 4.2.x. +#if defined(__clang__) +#define HAVE_FORCE_ALIGN_ARG_POINTER +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2)) +#define HAVE_FORCE_ALIGN_ARG_POINTER +#endif +#if defined(__GNUC__) && defined(__i386__) && defined(HAVE_FORCE_ALIGN_ARG_POINTER) +#define MINGW32_FORCEALIGN __attribute__((force_align_arg_pointer)) +#else +#define MINGW32_FORCEALIGN +#endif + +#include +#include // for REFIID with broken mingw.org headers +#include + +// Routines to convert from UTF8 to native Windows text +#define WIN_StringToUTF8W(S) SDL_iconv_string("UTF-8", "UTF-16LE", (const char *)(S), (SDL_wcslen(S) + 1) * sizeof(WCHAR)) +#define WIN_UTF8ToStringW(S) (WCHAR *)SDL_iconv_string("UTF-16LE", "UTF-8", (const char *)(S), SDL_strlen(S) + 1) +// !!! FIXME: UTF8ToString() can just be a SDL_strdup() here. +#define WIN_StringToUTF8A(S) SDL_iconv_string("UTF-8", "ASCII", (const char *)(S), (SDL_strlen(S) + 1)) +#define WIN_UTF8ToStringA(S) SDL_iconv_string("ASCII", "UTF-8", (const char *)(S), SDL_strlen(S) + 1) +#if UNICODE +#define WIN_StringToUTF8 WIN_StringToUTF8W +#define WIN_UTF8ToString WIN_UTF8ToStringW +#define SDL_tcslen SDL_wcslen +#define SDL_tcsstr SDL_wcsstr +#else +#define WIN_StringToUTF8 WIN_StringToUTF8A +#define WIN_UTF8ToString WIN_UTF8ToStringA +#define SDL_tcslen SDL_strlen +#define SDL_tcsstr SDL_strstr +#endif + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +// Sets an error message based on a given HRESULT +extern bool WIN_SetErrorFromHRESULT(const char *prefix, HRESULT hr); + +// Sets an error message based on GetLastError(). Always returns false. +extern bool WIN_SetError(const char *prefix); + +// Load a function from combase.dll +FARPROC WIN_LoadComBaseFunction(const char *name); + +// Wrap up the oddities of CoInitialize() into a common function. +extern HRESULT WIN_CoInitialize(void); +extern void WIN_CoUninitialize(void); + +// Wrap up the oddities of RoInitialize() into a common function. +extern HRESULT WIN_RoInitialize(void); +extern void WIN_RoUninitialize(void); + +// Returns true if we're running on Windows XP (any service pack). DOES NOT CHECK XP "OR GREATER"! +extern BOOL WIN_IsWindowsXP(void); + +// Returns true if we're running on Windows Vista and newer +extern BOOL WIN_IsWindowsVistaOrGreater(void); + +// Returns true if we're running on Windows 7 and newer +extern BOOL WIN_IsWindows7OrGreater(void); + +// Returns true if we're running on Windows 8 and newer +extern BOOL WIN_IsWindows8OrGreater(void); + +// You need to SDL_free() the result of this call. +extern char *WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid); + +// Checks to see if two GUID are the same. +extern BOOL WIN_IsEqualGUID(const GUID *a, const GUID *b); +extern BOOL WIN_IsEqualIID(REFIID a, REFIID b); + +// Convert between SDL_rect and RECT +extern void WIN_RECTToRect(const RECT *winrect, SDL_Rect *sdlrect); +extern void WIN_RectToRECT(const SDL_Rect *sdlrect, RECT *winrect); + +// Returns false if a window client rect is not valid +bool WIN_WindowRectValid(const RECT *rect); + +extern SDL_AudioFormat SDL_WaveFormatExToSDLFormat(WAVEFORMATEX *waveformat); + +// WideCharToMultiByte, but with some WinXP management. +extern int WIN_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWCH lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar); + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif + +#endif // _INCLUDED_WINDOWS_H diff --git a/thirdparty/sdl/core/windows/SDL_xinput.c b/thirdparty/sdl/core/windows/SDL_xinput.c new file mode 100644 index 00000000000..ba5e4c10786 --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_xinput.c @@ -0,0 +1,140 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_xinput.h" + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +XInputGetState_t SDL_XInputGetState = NULL; +XInputSetState_t SDL_XInputSetState = NULL; +XInputGetCapabilities_t SDL_XInputGetCapabilities = NULL; +XInputGetCapabilitiesEx_t SDL_XInputGetCapabilitiesEx = NULL; +XInputGetBatteryInformation_t SDL_XInputGetBatteryInformation = NULL; +DWORD SDL_XInputVersion = 0; + +static HMODULE s_pXInputDLL = NULL; +static int s_XInputDLLRefCount = 0; + +#if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) + +bool WIN_LoadXInputDLL(void) +{ + /* Getting handles to system dlls (via LoadLibrary and its variants) is not + * supported on Xbox, thus, pointers to XInput's functions can't be + * retrieved via GetProcAddress. + * + * When on Xbox, assume that XInput is already loaded, and directly map + * its XInput.h-declared functions to the SDL_XInput* set of function + * pointers. + */ + SDL_XInputGetState = (XInputGetState_t)XInputGetState; + SDL_XInputSetState = (XInputSetState_t)XInputSetState; + SDL_XInputGetCapabilities = (XInputGetCapabilities_t)XInputGetCapabilities; + SDL_XInputGetBatteryInformation = (XInputGetBatteryInformation_t)XInputGetBatteryInformation; + + // XInput 1.4 ships with Windows 8 and 8.1: + SDL_XInputVersion = (1 << 16) | 4; + + return true; +} + +void WIN_UnloadXInputDLL(void) +{ +} + +#else // !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)) + +bool WIN_LoadXInputDLL(void) +{ + DWORD version = 0; + + if (s_pXInputDLL) { + SDL_assert(s_XInputDLLRefCount > 0); + s_XInputDLLRefCount++; + return true; // already loaded + } + + /* NOTE: Don't load XinputUap.dll + * This is XInput emulation over Windows.Gaming.Input, and has all the + * limitations of that API (no devices at startup, no background input, etc.) + */ + version = (1 << 16) | 4; + s_pXInputDLL = LoadLibrary(TEXT("XInput1_4.dll")); // 1.4 Ships with Windows 8. + if (!s_pXInputDLL) { + version = (1 << 16) | 3; + s_pXInputDLL = LoadLibrary(TEXT("XInput1_3.dll")); // 1.3 can be installed as a redistributable component. + } + if (!s_pXInputDLL) { + s_pXInputDLL = LoadLibrary(TEXT("bin\\XInput1_3.dll")); + } + if (!s_pXInputDLL) { + // "9.1.0" Ships with Vista and Win7, and is more limited than 1.3+ (e.g. XInputGetStateEx is not available.) + s_pXInputDLL = LoadLibrary(TEXT("XInput9_1_0.dll")); + } + if (!s_pXInputDLL) { + return false; + } + + SDL_assert(s_XInputDLLRefCount == 0); + SDL_XInputVersion = version; + s_XInputDLLRefCount = 1; + + // 100 is the ordinal for _XInputGetStateEx, which returns the same struct as XinputGetState, but with extra data in wButtons for the guide button, we think... + SDL_XInputGetState = (XInputGetState_t)GetProcAddress(s_pXInputDLL, (LPCSTR)100); + if (!SDL_XInputGetState) { + SDL_XInputGetState = (XInputGetState_t)GetProcAddress(s_pXInputDLL, "XInputGetState"); + } + SDL_XInputSetState = (XInputSetState_t)GetProcAddress(s_pXInputDLL, "XInputSetState"); + SDL_XInputGetCapabilities = (XInputGetCapabilities_t)GetProcAddress(s_pXInputDLL, "XInputGetCapabilities"); + // 108 is the ordinal for _XInputGetCapabilitiesEx, which additionally returns VID/PID of the controller. + SDL_XInputGetCapabilitiesEx = (XInputGetCapabilitiesEx_t)GetProcAddress(s_pXInputDLL, (LPCSTR)108); + SDL_XInputGetBatteryInformation = (XInputGetBatteryInformation_t)GetProcAddress(s_pXInputDLL, "XInputGetBatteryInformation"); + if (!SDL_XInputGetState || !SDL_XInputSetState || !SDL_XInputGetCapabilities) { + WIN_UnloadXInputDLL(); + return false; + } + + return true; +} + +void WIN_UnloadXInputDLL(void) +{ + if (s_pXInputDLL) { + SDL_assert(s_XInputDLLRefCount > 0); + if (--s_XInputDLLRefCount == 0) { + FreeLibrary(s_pXInputDLL); + s_pXInputDLL = NULL; + } + } else { + SDL_assert(s_XInputDLLRefCount == 0); + } +} + +#endif + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif diff --git a/thirdparty/sdl/core/windows/SDL_xinput.h b/thirdparty/sdl/core/windows/SDL_xinput.h new file mode 100644 index 00000000000..d499cd58c2b --- /dev/null +++ b/thirdparty/sdl/core/windows/SDL_xinput.h @@ -0,0 +1,276 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_xinput_h_ +#define SDL_xinput_h_ + +#include "SDL_windows.h" + +#ifdef HAVE_XINPUT_H +#if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) +// Xbox supports an XInput wrapper which is a C++-only header... +#include // Required to compile with recent MSVC... +#include +using namespace XInputOnGameInput; +#else +#include +#endif +#endif // HAVE_XINPUT_H + +#ifndef XUSER_MAX_COUNT +#define XUSER_MAX_COUNT 4 +#endif +#ifndef XUSER_INDEX_ANY +#define XUSER_INDEX_ANY 0x000000FF +#endif +#ifndef XINPUT_CAPS_FFB_SUPPORTED +#define XINPUT_CAPS_FFB_SUPPORTED 0x0001 +#endif +#ifndef XINPUT_CAPS_WIRELESS +#define XINPUT_CAPS_WIRELESS 0x0002 +#endif + +#ifndef XINPUT_DEVSUBTYPE_UNKNOWN +#define XINPUT_DEVSUBTYPE_UNKNOWN 0x00 +#endif +#ifndef XINPUT_DEVSUBTYPE_GAMEPAD +#define XINPUT_DEVSUBTYPE_GAMEPAD 0x01 +#endif +#ifndef XINPUT_DEVSUBTYPE_WHEEL +#define XINPUT_DEVSUBTYPE_WHEEL 0x02 +#endif +#ifndef XINPUT_DEVSUBTYPE_ARCADE_STICK +#define XINPUT_DEVSUBTYPE_ARCADE_STICK 0x03 +#endif +#ifndef XINPUT_DEVSUBTYPE_FLIGHT_STICK +#define XINPUT_DEVSUBTYPE_FLIGHT_STICK 0x04 +#endif +#ifndef XINPUT_DEVSUBTYPE_DANCE_PAD +#define XINPUT_DEVSUBTYPE_DANCE_PAD 0x05 +#endif +#ifndef XINPUT_DEVSUBTYPE_GUITAR +#define XINPUT_DEVSUBTYPE_GUITAR 0x06 +#endif +#ifndef XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE +#define XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE 0x07 +#endif +#ifndef XINPUT_DEVSUBTYPE_DRUM_KIT +#define XINPUT_DEVSUBTYPE_DRUM_KIT 0x08 +#endif +#ifndef XINPUT_DEVSUBTYPE_GUITAR_BASS +#define XINPUT_DEVSUBTYPE_GUITAR_BASS 0x0B +#endif +#ifndef XINPUT_DEVSUBTYPE_ARCADE_PAD +#define XINPUT_DEVSUBTYPE_ARCADE_PAD 0x13 +#endif + +#ifndef XINPUT_FLAG_GAMEPAD +#define XINPUT_FLAG_GAMEPAD 0x01 +#endif + +#ifndef XINPUT_GAMEPAD_DPAD_UP +#define XINPUT_GAMEPAD_DPAD_UP 0x0001 +#endif +#ifndef XINPUT_GAMEPAD_DPAD_DOWN +#define XINPUT_GAMEPAD_DPAD_DOWN 0x0002 +#endif +#ifndef XINPUT_GAMEPAD_DPAD_LEFT +#define XINPUT_GAMEPAD_DPAD_LEFT 0x0004 +#endif +#ifndef XINPUT_GAMEPAD_DPAD_RIGHT +#define XINPUT_GAMEPAD_DPAD_RIGHT 0x0008 +#endif +#ifndef XINPUT_GAMEPAD_START +#define XINPUT_GAMEPAD_START 0x0010 +#endif +#ifndef XINPUT_GAMEPAD_BACK +#define XINPUT_GAMEPAD_BACK 0x0020 +#endif +#ifndef XINPUT_GAMEPAD_LEFT_THUMB +#define XINPUT_GAMEPAD_LEFT_THUMB 0x0040 +#endif +#ifndef XINPUT_GAMEPAD_RIGHT_THUMB +#define XINPUT_GAMEPAD_RIGHT_THUMB 0x0080 +#endif +#ifndef XINPUT_GAMEPAD_LEFT_SHOULDER +#define XINPUT_GAMEPAD_LEFT_SHOULDER 0x0100 +#endif +#ifndef XINPUT_GAMEPAD_RIGHT_SHOULDER +#define XINPUT_GAMEPAD_RIGHT_SHOULDER 0x0200 +#endif +#ifndef XINPUT_GAMEPAD_A +#define XINPUT_GAMEPAD_A 0x1000 +#endif +#ifndef XINPUT_GAMEPAD_B +#define XINPUT_GAMEPAD_B 0x2000 +#endif +#ifndef XINPUT_GAMEPAD_X +#define XINPUT_GAMEPAD_X 0x4000 +#endif +#ifndef XINPUT_GAMEPAD_Y +#define XINPUT_GAMEPAD_Y 0x8000 +#endif + +#ifndef XINPUT_GAMEPAD_GUIDE +#define XINPUT_GAMEPAD_GUIDE 0x0400 +#endif + +#ifndef BATTERY_DEVTYPE_GAMEPAD +#define BATTERY_DEVTYPE_GAMEPAD 0x00 +#endif + +#ifndef BATTERY_TYPE_DISCONNECTED +#define BATTERY_TYPE_DISCONNECTED 0x00 +#endif +#ifndef BATTERY_TYPE_WIRED +#define BATTERY_TYPE_WIRED 0x01 +#endif +#ifndef BATTERY_TYPE_UNKNOWN +#define BATTERY_TYPE_UNKNOWN 0xFF +#endif +#ifndef BATTERY_LEVEL_EMPTY +#define BATTERY_LEVEL_EMPTY 0x00 +#endif +#ifndef BATTERY_LEVEL_LOW +#define BATTERY_LEVEL_LOW 0x01 +#endif +#ifndef BATTERY_LEVEL_MEDIUM +#define BATTERY_LEVEL_MEDIUM 0x02 +#endif +#ifndef BATTERY_LEVEL_FULL +#define BATTERY_LEVEL_FULL 0x03 +#endif + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +// typedef's for XInput structs we use + + +// This is the same as XINPUT_BATTERY_INFORMATION, but always defined instead of just if WIN32_WINNT >= _WIN32_WINNT_WIN8 +typedef struct +{ + BYTE BatteryType; + BYTE BatteryLevel; +} XINPUT_BATTERY_INFORMATION_EX; + +#ifndef HAVE_XINPUT_H + +typedef struct +{ + WORD wButtons; + BYTE bLeftTrigger; + BYTE bRightTrigger; + SHORT sThumbLX; + SHORT sThumbLY; + SHORT sThumbRX; + SHORT sThumbRY; +} XINPUT_GAMEPAD; + +typedef struct +{ + DWORD dwPacketNumber; + XINPUT_GAMEPAD Gamepad; +} XINPUT_STATE; + +typedef struct +{ + WORD wLeftMotorSpeed; + WORD wRightMotorSpeed; +} XINPUT_VIBRATION; + +typedef struct +{ + BYTE Type; + BYTE SubType; + WORD Flags; + XINPUT_GAMEPAD Gamepad; + XINPUT_VIBRATION Vibration; +} XINPUT_CAPABILITIES; + +#endif // HAVE_XINPUT_H + +// This struct is not defined in XInput headers. +typedef struct +{ + XINPUT_CAPABILITIES Capabilities; + WORD VendorId; + WORD ProductId; + WORD ProductVersion; + WORD unk1; + DWORD unk2; +} SDL_XINPUT_CAPABILITIES_EX; + +// Forward decl's for XInput API's we load dynamically and use if available +typedef DWORD(WINAPI *XInputGetState_t)( + DWORD dwUserIndex, // [in] Index of the gamer associated with the device + XINPUT_STATE *pState // [out] Receives the current state +); + +typedef DWORD(WINAPI *XInputSetState_t)( + DWORD dwUserIndex, // [in] Index of the gamer associated with the device + XINPUT_VIBRATION *pVibration // [in, out] The vibration information to send to the controller +); + +typedef DWORD(WINAPI *XInputGetCapabilities_t)( + DWORD dwUserIndex, // [in] Index of the gamer associated with the device + DWORD dwFlags, // [in] Input flags that identify the device type + XINPUT_CAPABILITIES *pCapabilities // [out] Receives the capabilities +); + +// Only available in XInput 1.4 that is shipped with Windows 8 and newer. +typedef DWORD(WINAPI *XInputGetCapabilitiesEx_t)( + DWORD dwReserved, // [in] Must be 1 + DWORD dwUserIndex, // [in] Index of the gamer associated with the device + DWORD dwFlags, // [in] Input flags that identify the device type + SDL_XINPUT_CAPABILITIES_EX *pCapabilitiesEx // [out] Receives the capabilities +); + +typedef DWORD(WINAPI *XInputGetBatteryInformation_t)( + DWORD dwUserIndex, + BYTE devType, + XINPUT_BATTERY_INFORMATION_EX *pBatteryInformation); + +extern bool WIN_LoadXInputDLL(void); +extern void WIN_UnloadXInputDLL(void); + +extern XInputGetState_t SDL_XInputGetState; +extern XInputSetState_t SDL_XInputSetState; +extern XInputGetCapabilities_t SDL_XInputGetCapabilities; +extern XInputGetCapabilitiesEx_t SDL_XInputGetCapabilitiesEx; +extern XInputGetBatteryInformation_t SDL_XInputGetBatteryInformation; +extern DWORD SDL_XInputVersion; // ((major << 16) & 0xFF00) | (minor & 0xFF) + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif + +#define XINPUTGETSTATE SDL_XInputGetState +#define XINPUTSETSTATE SDL_XInputSetState +#define XINPUTGETCAPABILITIES SDL_XInputGetCapabilities +#define XINPUTGETCAPABILITIESEX SDL_XInputGetCapabilitiesEx +#define XINPUTGETBATTERYINFORMATION SDL_XInputGetBatteryInformation + +#endif // SDL_xinput_h_ diff --git a/thirdparty/sdl/core/windows/pch.c b/thirdparty/sdl/core/windows/pch.c new file mode 100644 index 00000000000..4b0c6f8fcc8 --- /dev/null +++ b/thirdparty/sdl/core/windows/pch.c @@ -0,0 +1,21 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" diff --git a/thirdparty/sdl/core/windows/pch_cpp.cpp b/thirdparty/sdl/core/windows/pch_cpp.cpp new file mode 100644 index 00000000000..4b0c6f8fcc8 --- /dev/null +++ b/thirdparty/sdl/core/windows/pch_cpp.cpp @@ -0,0 +1,21 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" diff --git a/thirdparty/sdl/events/SDL_events.c b/thirdparty/sdl/events/SDL_events.c new file mode 100644 index 00000000000..24c2c4270f4 --- /dev/null +++ b/thirdparty/sdl/events/SDL_events.c @@ -0,0 +1,1833 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// General event handling code for SDL + +#include "SDL_events_c.h" +#include "SDL_eventwatch_c.h" +#include "../SDL_hints_c.h" +#include "../timer/SDL_timer_c.h" +#ifndef SDL_JOYSTICK_DISABLED +#include "../joystick/SDL_joystick_c.h" +#endif +#ifndef SDL_SENSOR_DISABLED +#include "../sensor/SDL_sensor_c.h" +#endif +//#include "../video/SDL_sysvideo.h" + +#ifdef SDL_PLATFORM_ANDROID +#include "../core/android/SDL_android.h" +#include "../video/android/SDL_androidevents.h" +#endif + +// An arbitrary limit so we don't have unbounded growth +#define SDL_MAX_QUEUED_EVENTS 65535 + +// Determines how often we pump events if joystick or sensor subsystems are active +#define ENUMERATION_POLL_INTERVAL_NS (3 * SDL_NS_PER_SECOND) + +// Determines how often to pump events if joysticks or sensors are actively being read +#define EVENT_POLL_INTERVAL_NS SDL_MS_TO_NS(1) + +// Make sure the type in the SDL_Event aligns properly across the union +SDL_COMPILE_TIME_ASSERT(SDL_Event_type, sizeof(Uint32) == sizeof(SDL_EventType)); + +#define SDL2_SYSWMEVENT 0x201 + +#ifdef SDL_VIDEO_DRIVER_WINDOWS +#include "../core/windows/SDL_windows.h" +#endif + +#ifdef SDL_VIDEO_DRIVER_X11 +#include +#endif + +typedef struct SDL2_version +{ + Uint8 major; + Uint8 minor; + Uint8 patch; +} SDL2_version; + +typedef enum +{ + SDL2_SYSWM_UNKNOWN +} SDL2_SYSWM_TYPE; + +typedef struct SDL2_SysWMmsg +{ + SDL2_version version; + SDL2_SYSWM_TYPE subsystem; + union + { +#ifdef SDL_VIDEO_DRIVER_WINDOWS + struct { + HWND hwnd; /**< The window for the message */ + UINT msg; /**< The type of message */ + WPARAM wParam; /**< WORD message parameter */ + LPARAM lParam; /**< LONG message parameter */ + } win; +#endif +#ifdef SDL_VIDEO_DRIVER_X11 + struct { + XEvent event; + } x11; +#endif + /* Can't have an empty union */ + int dummy; + } msg; +} SDL2_SysWMmsg; + +static SDL_EventWatchList SDL_event_watchers; +static SDL_AtomicInt SDL_sentinel_pending; +static Uint32 SDL_last_event_id = 0; + +typedef struct +{ + Uint32 bits[8]; +} SDL_DisabledEventBlock; + +static SDL_DisabledEventBlock *SDL_disabled_events[256]; +static SDL_AtomicInt SDL_userevents; + +typedef struct SDL_TemporaryMemory +{ + void *memory; + struct SDL_TemporaryMemory *prev; + struct SDL_TemporaryMemory *next; +} SDL_TemporaryMemory; + +typedef struct SDL_TemporaryMemoryState +{ + SDL_TemporaryMemory *head; + SDL_TemporaryMemory *tail; +} SDL_TemporaryMemoryState; + +static SDL_TLSID SDL_temporary_memory; + +typedef struct SDL_EventEntry +{ + SDL_Event event; + SDL_TemporaryMemory *memory; + struct SDL_EventEntry *prev; + struct SDL_EventEntry *next; +} SDL_EventEntry; + +static struct +{ + SDL_Mutex *lock; + bool active; + SDL_AtomicInt count; + int max_events_seen; + SDL_EventEntry *head; + SDL_EventEntry *tail; + SDL_EventEntry *free; +} SDL_EventQ = { NULL, false, { 0 }, 0, NULL, NULL, NULL }; + + +static void SDL_CleanupTemporaryMemory(void *data) +{ + SDL_TemporaryMemoryState *state = (SDL_TemporaryMemoryState *)data; + + SDL_FreeTemporaryMemory(); + SDL_free(state); +} + +static SDL_TemporaryMemoryState *SDL_GetTemporaryMemoryState(bool create) +{ + SDL_TemporaryMemoryState *state; + + state = (SDL_TemporaryMemoryState *)SDL_GetTLS(&SDL_temporary_memory); + if (!state) { + if (!create) { + return NULL; + } + + state = (SDL_TemporaryMemoryState *)SDL_calloc(1, sizeof(*state)); + if (!state) { + return NULL; + } + + if (!SDL_SetTLS(&SDL_temporary_memory, state, SDL_CleanupTemporaryMemory)) { + SDL_free(state); + return NULL; + } + } + return state; +} + +static SDL_TemporaryMemory *SDL_GetTemporaryMemoryEntry(SDL_TemporaryMemoryState *state, const void *mem) +{ + SDL_TemporaryMemory *entry; + + // Start from the end, it's likely to have been recently allocated + for (entry = state->tail; entry; entry = entry->prev) { + if (mem == entry->memory) { + return entry; + } + } + return NULL; +} + +static void SDL_LinkTemporaryMemoryEntry(SDL_TemporaryMemoryState *state, SDL_TemporaryMemory *entry) +{ + entry->prev = state->tail; + entry->next = NULL; + + if (state->tail) { + state->tail->next = entry; + } else { + state->head = entry; + } + state->tail = entry; +} + +static void SDL_UnlinkTemporaryMemoryEntry(SDL_TemporaryMemoryState *state, SDL_TemporaryMemory *entry) +{ + if (state->head == entry) { + state->head = entry->next; + } + if (state->tail == entry) { + state->tail = entry->prev; + } + + if (entry->prev) { + entry->prev->next = entry->next; + } + if (entry->next) { + entry->next->prev = entry->prev; + } + + entry->prev = NULL; + entry->next = NULL; +} + +static void SDL_FreeTemporaryMemoryEntry(SDL_TemporaryMemoryState *state, SDL_TemporaryMemory *entry, bool free_data) +{ + if (free_data) { + SDL_free(entry->memory); + } + SDL_free(entry); +} + +static void SDL_LinkTemporaryMemoryToEvent(SDL_EventEntry *event, const void *mem) +{ + SDL_TemporaryMemoryState *state; + SDL_TemporaryMemory *entry; + + state = SDL_GetTemporaryMemoryState(false); + if (!state) { + return; + } + + entry = SDL_GetTemporaryMemoryEntry(state, mem); + if (entry) { + SDL_UnlinkTemporaryMemoryEntry(state, entry); + entry->next = event->memory; + event->memory = entry; + } +} + +static void SDL_TransferSysWMMemoryToEvent(SDL_EventEntry *event) +{ + SDL2_SysWMmsg **wmmsg = (SDL2_SysWMmsg **)((&event->event.common)+1); + SDL2_SysWMmsg *mem = SDL_AllocateTemporaryMemory(sizeof(*mem)); + if (mem) { + SDL_copyp(mem, *wmmsg); + *wmmsg = mem; + SDL_LinkTemporaryMemoryToEvent(event, mem); + } +} + +// Transfer the event memory from the thread-local event memory list to the event +static void SDL_TransferTemporaryMemoryToEvent(SDL_EventEntry *event) +{ + switch (event->event.type) { + case SDL_EVENT_TEXT_EDITING: + SDL_LinkTemporaryMemoryToEvent(event, event->event.edit.text); + break; + case SDL_EVENT_TEXT_EDITING_CANDIDATES: + SDL_LinkTemporaryMemoryToEvent(event, event->event.edit_candidates.candidates); + break; + case SDL_EVENT_TEXT_INPUT: + SDL_LinkTemporaryMemoryToEvent(event, event->event.text.text); + break; + case SDL_EVENT_DROP_BEGIN: + case SDL_EVENT_DROP_FILE: + case SDL_EVENT_DROP_TEXT: + case SDL_EVENT_DROP_COMPLETE: + case SDL_EVENT_DROP_POSITION: + SDL_LinkTemporaryMemoryToEvent(event, event->event.drop.source); + SDL_LinkTemporaryMemoryToEvent(event, event->event.drop.data); + break; + case SDL_EVENT_CLIPBOARD_UPDATE: + SDL_LinkTemporaryMemoryToEvent(event, event->event.clipboard.mime_types); + break; + case SDL2_SYSWMEVENT: + // We need to copy the stack pointer into temporary memory + SDL_TransferSysWMMemoryToEvent(event); + break; + default: + break; + } +} + +// Transfer the event memory from the event to the thread-local event memory list +static void SDL_TransferTemporaryMemoryFromEvent(SDL_EventEntry *event) +{ + SDL_TemporaryMemoryState *state; + SDL_TemporaryMemory *entry, *next; + + if (!event->memory) { + return; + } + + state = SDL_GetTemporaryMemoryState(true); + if (!state) { + return; // this is now a leak, but you probably have bigger problems if malloc failed. + } + + for (entry = event->memory; entry; entry = next) { + next = entry->next; + SDL_LinkTemporaryMemoryEntry(state, entry); + } + event->memory = NULL; +} + +static void *SDL_FreeLater(void *memory) +{ + SDL_TemporaryMemoryState *state; + + if (memory == NULL) { + return NULL; + } + + // Make sure we're not adding this to the list twice + //SDL_assert(!SDL_ClaimTemporaryMemory(memory)); + + state = SDL_GetTemporaryMemoryState(true); + if (!state) { + return memory; // this is now a leak, but you probably have bigger problems if malloc failed. + } + + SDL_TemporaryMemory *entry = (SDL_TemporaryMemory *)SDL_malloc(sizeof(*entry)); + if (!entry) { + return memory; // this is now a leak, but you probably have bigger problems if malloc failed. We could probably pool up and reuse entries, though. + } + + entry->memory = memory; + + SDL_LinkTemporaryMemoryEntry(state, entry); + + return memory; +} + +void *SDL_AllocateTemporaryMemory(size_t size) +{ + return SDL_FreeLater(SDL_malloc(size)); +} + +const char *SDL_CreateTemporaryString(const char *string) +{ + if (string) { + return (const char *)SDL_FreeLater(SDL_strdup(string)); + } + return NULL; +} + +void *SDL_ClaimTemporaryMemory(const void *mem) +{ + SDL_TemporaryMemoryState *state; + + state = SDL_GetTemporaryMemoryState(false); + if (state && mem) { + SDL_TemporaryMemory *entry = SDL_GetTemporaryMemoryEntry(state, mem); + if (entry) { + SDL_UnlinkTemporaryMemoryEntry(state, entry); + SDL_FreeTemporaryMemoryEntry(state, entry, false); + return (void *)mem; + } + } + return NULL; +} + +void SDL_FreeTemporaryMemory(void) +{ + SDL_TemporaryMemoryState *state; + + state = SDL_GetTemporaryMemoryState(false); + if (!state) { + return; + } + + while (state->head) { + SDL_TemporaryMemory *entry = state->head; + + SDL_UnlinkTemporaryMemoryEntry(state, entry); + SDL_FreeTemporaryMemoryEntry(state, entry, true); + } +} + +#ifndef SDL_JOYSTICK_DISABLED + +static bool SDL_update_joysticks = true; + +static void SDLCALL SDL_AutoUpdateJoysticksChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_update_joysticks = SDL_GetStringBoolean(hint, true); +} + +#endif // !SDL_JOYSTICK_DISABLED + +#ifndef SDL_SENSOR_DISABLED + +static bool SDL_update_sensors = true; + +static void SDLCALL SDL_AutoUpdateSensorsChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_update_sensors = SDL_GetStringBoolean(hint, true); +} + +#endif // !SDL_SENSOR_DISABLED + +static void SDLCALL SDL_PollSentinelChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_SetEventEnabled(SDL_EVENT_POLL_SENTINEL, SDL_GetStringBoolean(hint, true)); +} + +/** + * Verbosity of logged events as defined in SDL_HINT_EVENT_LOGGING: + * - 0: (default) no logging + * - 1: logging of most events + * - 2: as above, plus mouse, pen, and finger motion + */ +static int SDL_EventLoggingVerbosity = 0; + +static void SDLCALL SDL_EventLoggingChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_EventLoggingVerbosity = (hint && *hint) ? SDL_clamp(SDL_atoi(hint), 0, 3) : 0; +} + +static void SDL_LogEvent(const SDL_Event *event) +{ + static const char *pen_axisnames[] = { "PRESSURE", "XTILT", "YTILT", "DISTANCE", "ROTATION", "SLIDER", "TANGENTIAL_PRESSURE" }; + SDL_COMPILE_TIME_ASSERT(pen_axisnames_array_matches, SDL_arraysize(pen_axisnames) == SDL_PEN_AXIS_COUNT); + + char name[64]; + char details[128]; + + // sensor/mouse/pen/finger motion are spammy, ignore these if they aren't demanded. + if ((SDL_EventLoggingVerbosity < 2) && + ((event->type == SDL_EVENT_MOUSE_MOTION) || + (event->type == SDL_EVENT_FINGER_MOTION) || + (event->type == SDL_EVENT_PEN_AXIS) || + (event->type == SDL_EVENT_PEN_MOTION) || + (event->type == SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION) || + (event->type == SDL_EVENT_GAMEPAD_SENSOR_UPDATE) || + (event->type == SDL_EVENT_SENSOR_UPDATE))) { + return; + } + +// this is to make (void)SDL_snprintf() calls cleaner. +#define uint unsigned int + + name[0] = '\0'; + details[0] = '\0'; + + // !!! FIXME: This code is kinda ugly, sorry. + + if ((event->type >= SDL_EVENT_USER) && (event->type <= SDL_EVENT_LAST)) { + char plusstr[16]; + SDL_strlcpy(name, "SDL_EVENT_USER", sizeof(name)); + if (event->type > SDL_EVENT_USER) { + (void)SDL_snprintf(plusstr, sizeof(plusstr), "+%u", ((uint)event->type) - SDL_EVENT_USER); + } else { + plusstr[0] = '\0'; + } + (void)SDL_snprintf(details, sizeof(details), "%s (timestamp=%u windowid=%u code=%d data1=%p data2=%p)", + plusstr, (uint)event->user.timestamp, (uint)event->user.windowID, + (int)event->user.code, event->user.data1, event->user.data2); + } + + switch (event->type) { +#define SDL_EVENT_CASE(x) \ + case x: \ + SDL_strlcpy(name, #x, sizeof(name)); + SDL_EVENT_CASE(SDL_EVENT_FIRST) + SDL_strlcpy(details, " (THIS IS PROBABLY A BUG!)", sizeof(details)); + break; + SDL_EVENT_CASE(SDL_EVENT_QUIT) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u)", (uint)event->quit.timestamp); + break; + SDL_EVENT_CASE(SDL_EVENT_TERMINATING) + break; + SDL_EVENT_CASE(SDL_EVENT_LOW_MEMORY) + break; + SDL_EVENT_CASE(SDL_EVENT_WILL_ENTER_BACKGROUND) + break; + SDL_EVENT_CASE(SDL_EVENT_DID_ENTER_BACKGROUND) + break; + SDL_EVENT_CASE(SDL_EVENT_WILL_ENTER_FOREGROUND) + break; + SDL_EVENT_CASE(SDL_EVENT_DID_ENTER_FOREGROUND) + break; + SDL_EVENT_CASE(SDL_EVENT_LOCALE_CHANGED) + break; + SDL_EVENT_CASE(SDL_EVENT_SYSTEM_THEME_CHANGED) + break; + SDL_EVENT_CASE(SDL_EVENT_KEYMAP_CHANGED) + break; + SDL_EVENT_CASE(SDL_EVENT_CLIPBOARD_UPDATE) + break; + +#define SDL_RENDEREVENT_CASE(x) \ + case x: \ + SDL_strlcpy(name, #x, sizeof(name)); \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u event=%s windowid=%u)", \ + (uint)event->display.timestamp, name, (uint)event->render.windowID); \ + break + SDL_RENDEREVENT_CASE(SDL_EVENT_RENDER_TARGETS_RESET); + SDL_RENDEREVENT_CASE(SDL_EVENT_RENDER_DEVICE_RESET); + SDL_RENDEREVENT_CASE(SDL_EVENT_RENDER_DEVICE_LOST); + +#define SDL_DISPLAYEVENT_CASE(x) \ + case x: \ + SDL_strlcpy(name, #x, sizeof(name)); \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u display=%u event=%s data1=%d, data2=%d)", \ + (uint)event->display.timestamp, (uint)event->display.displayID, name, (int)event->display.data1, (int)event->display.data2); \ + break + SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_ORIENTATION); + SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_ADDED); + SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_REMOVED); + SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_MOVED); + SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_DESKTOP_MODE_CHANGED); + SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_CURRENT_MODE_CHANGED); + SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_CONTENT_SCALE_CHANGED); +#undef SDL_DISPLAYEVENT_CASE + +#define SDL_WINDOWEVENT_CASE(x) \ + case x: \ + SDL_strlcpy(name, #x, sizeof(name)); \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u event=%s data1=%d data2=%d)", \ + (uint)event->window.timestamp, (uint)event->window.windowID, name, (int)event->window.data1, (int)event->window.data2); \ + break + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_SHOWN); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_HIDDEN); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_EXPOSED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_MOVED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_RESIZED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_METAL_VIEW_RESIZED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_SAFE_AREA_CHANGED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_MINIMIZED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_MAXIMIZED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_RESTORED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_MOUSE_ENTER); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_MOUSE_LEAVE); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_FOCUS_GAINED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_FOCUS_LOST); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_CLOSE_REQUESTED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_HIT_TEST); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_ICCPROF_CHANGED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_DISPLAY_CHANGED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_OCCLUDED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_ENTER_FULLSCREEN); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_LEAVE_FULLSCREEN); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_DESTROYED); + SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_HDR_STATE_CHANGED); +#undef SDL_WINDOWEVENT_CASE + +#define PRINT_KEYDEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%u)", (uint)event->kdevice.timestamp, (uint)event->kdevice.which) + SDL_EVENT_CASE(SDL_EVENT_KEYBOARD_ADDED) + PRINT_KEYDEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_KEYBOARD_REMOVED) + PRINT_KEYDEV_EVENT(event); + break; +#undef PRINT_KEYDEV_EVENT + +#define PRINT_KEY_EVENT(event) \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u state=%s repeat=%s scancode=%u keycode=%u mod=0x%x)", \ + (uint)event->key.timestamp, (uint)event->key.windowID, (uint)event->key.which, \ + event->key.down ? "pressed" : "released", \ + event->key.repeat ? "true" : "false", \ + (uint)event->key.scancode, \ + (uint)event->key.key, \ + (uint)event->key.mod) + SDL_EVENT_CASE(SDL_EVENT_KEY_DOWN) + PRINT_KEY_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_KEY_UP) + PRINT_KEY_EVENT(event); + break; +#undef PRINT_KEY_EVENT + + SDL_EVENT_CASE(SDL_EVENT_TEXT_EDITING) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u text='%s' start=%d length=%d)", + (uint)event->edit.timestamp, (uint)event->edit.windowID, + event->edit.text, (int)event->edit.start, (int)event->edit.length); + break; + + SDL_EVENT_CASE(SDL_EVENT_TEXT_EDITING_CANDIDATES) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u num_candidates=%d selected_candidate=%d)", + (uint)event->edit_candidates.timestamp, (uint)event->edit_candidates.windowID, + (int)event->edit_candidates.num_candidates, (int)event->edit_candidates.selected_candidate); + break; + + SDL_EVENT_CASE(SDL_EVENT_TEXT_INPUT) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u text='%s')", (uint)event->text.timestamp, (uint)event->text.windowID, event->text.text); + break; + +#define PRINT_MOUSEDEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%u)", (uint)event->mdevice.timestamp, (uint)event->mdevice.which) + SDL_EVENT_CASE(SDL_EVENT_MOUSE_ADDED) + PRINT_MOUSEDEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_MOUSE_REMOVED) + PRINT_MOUSEDEV_EVENT(event); + break; +#undef PRINT_MOUSEDEV_EVENT + + SDL_EVENT_CASE(SDL_EVENT_MOUSE_MOTION) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u state=%u x=%g y=%g xrel=%g yrel=%g)", + (uint)event->motion.timestamp, (uint)event->motion.windowID, + (uint)event->motion.which, (uint)event->motion.state, + event->motion.x, event->motion.y, + event->motion.xrel, event->motion.yrel); + break; + +#define PRINT_MBUTTON_EVENT(event) \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u button=%u state=%s clicks=%u x=%g y=%g)", \ + (uint)event->button.timestamp, (uint)event->button.windowID, \ + (uint)event->button.which, (uint)event->button.button, \ + event->button.down ? "pressed" : "released", \ + (uint)event->button.clicks, event->button.x, event->button.y) + SDL_EVENT_CASE(SDL_EVENT_MOUSE_BUTTON_DOWN) + PRINT_MBUTTON_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_MOUSE_BUTTON_UP) + PRINT_MBUTTON_EVENT(event); + break; +#undef PRINT_MBUTTON_EVENT + + SDL_EVENT_CASE(SDL_EVENT_MOUSE_WHEEL) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u x=%g y=%g integer_x=%d integer_y=%d direction=%s)", + (uint)event->wheel.timestamp, (uint)event->wheel.windowID, + (uint)event->wheel.which, event->wheel.x, event->wheel.y, + (int)event->wheel.integer_x, (int)event->wheel.integer_y, + event->wheel.direction == SDL_MOUSEWHEEL_NORMAL ? "normal" : "flipped"); + break; + + SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_AXIS_MOTION) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d axis=%u value=%d)", + (uint)event->jaxis.timestamp, (int)event->jaxis.which, + (uint)event->jaxis.axis, (int)event->jaxis.value); + break; + + SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_BALL_MOTION) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d ball=%u xrel=%d yrel=%d)", + (uint)event->jball.timestamp, (int)event->jball.which, + (uint)event->jball.ball, (int)event->jball.xrel, (int)event->jball.yrel); + break; + + SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_HAT_MOTION) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d hat=%u value=%u)", + (uint)event->jhat.timestamp, (int)event->jhat.which, + (uint)event->jhat.hat, (uint)event->jhat.value); + break; + +#define PRINT_JBUTTON_EVENT(event) \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d button=%u state=%s)", \ + (uint)event->jbutton.timestamp, (int)event->jbutton.which, \ + (uint)event->jbutton.button, event->jbutton.down ? "pressed" : "released") + SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_BUTTON_DOWN) + PRINT_JBUTTON_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_BUTTON_UP) + PRINT_JBUTTON_EVENT(event); + break; +#undef PRINT_JBUTTON_EVENT + + SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_BATTERY_UPDATED) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d state=%u percent=%d)", + (uint)event->jbattery.timestamp, (int)event->jbattery.which, + event->jbattery.state, event->jbattery.percent); + break; + +#define PRINT_JOYDEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d)", (uint)event->jdevice.timestamp, (int)event->jdevice.which) + SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_ADDED) + PRINT_JOYDEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_REMOVED) + PRINT_JOYDEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_UPDATE_COMPLETE) + PRINT_JOYDEV_EVENT(event); + break; +#undef PRINT_JOYDEV_EVENT + + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_AXIS_MOTION) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d axis=%u value=%d)", + (uint)event->gaxis.timestamp, (int)event->gaxis.which, + (uint)event->gaxis.axis, (int)event->gaxis.value); + break; + +#define PRINT_CBUTTON_EVENT(event) \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d button=%u state=%s)", \ + (uint)event->gbutton.timestamp, (int)event->gbutton.which, \ + (uint)event->gbutton.button, event->gbutton.down ? "pressed" : "released") + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_BUTTON_DOWN) + PRINT_CBUTTON_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_BUTTON_UP) + PRINT_CBUTTON_EVENT(event); + break; +#undef PRINT_CBUTTON_EVENT + +#define PRINT_GAMEPADDEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d)", (uint)event->gdevice.timestamp, (int)event->gdevice.which) + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_ADDED) + PRINT_GAMEPADDEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_REMOVED) + PRINT_GAMEPADDEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_REMAPPED) + PRINT_GAMEPADDEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_UPDATE_COMPLETE) + PRINT_GAMEPADDEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_STEAM_HANDLE_UPDATED) + PRINT_GAMEPADDEV_EVENT(event); + break; +#undef PRINT_GAMEPADDEV_EVENT + +#define PRINT_CTOUCHPAD_EVENT(event) \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d touchpad=%d finger=%d x=%f y=%f pressure=%f)", \ + (uint)event->gtouchpad.timestamp, (int)event->gtouchpad.which, \ + (int)event->gtouchpad.touchpad, (int)event->gtouchpad.finger, \ + event->gtouchpad.x, event->gtouchpad.y, event->gtouchpad.pressure) + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN) + PRINT_CTOUCHPAD_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_TOUCHPAD_UP) + PRINT_CTOUCHPAD_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION) + PRINT_CTOUCHPAD_EVENT(event); + break; +#undef PRINT_CTOUCHPAD_EVENT + + SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_SENSOR_UPDATE) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d sensor=%d data[0]=%f data[1]=%f data[2]=%f)", + (uint)event->gsensor.timestamp, (int)event->gsensor.which, (int)event->gsensor.sensor, + event->gsensor.data[0], event->gsensor.data[1], event->gsensor.data[2]); + break; + +#define PRINT_FINGER_EVENT(event) \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u touchid=%" SDL_PRIu64 " fingerid=%" SDL_PRIu64 " x=%f y=%f dx=%f dy=%f pressure=%f)", \ + (uint)event->tfinger.timestamp, event->tfinger.touchID, \ + event->tfinger.fingerID, event->tfinger.x, event->tfinger.y, \ + event->tfinger.dx, event->tfinger.dy, event->tfinger.pressure) + SDL_EVENT_CASE(SDL_EVENT_FINGER_DOWN) + PRINT_FINGER_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_FINGER_UP) + PRINT_FINGER_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_FINGER_CANCELED) + PRINT_FINGER_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_FINGER_MOTION) + PRINT_FINGER_EVENT(event); + break; +#undef PRINT_FINGER_EVENT + +#define PRINT_PTOUCH_EVENT(event) \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u pen_state=%u x=%g y=%g eraser=%s state=%s)", \ + (uint)event->ptouch.timestamp, (uint)event->ptouch.windowID, (uint)event->ptouch.which, (uint)event->ptouch.pen_state, event->ptouch.x, event->ptouch.y, \ + event->ptouch.eraser ? "yes" : "no", event->ptouch.down ? "down" : "up"); + SDL_EVENT_CASE(SDL_EVENT_PEN_DOWN) + PRINT_PTOUCH_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_PEN_UP) + PRINT_PTOUCH_EVENT(event); + break; +#undef PRINT_PTOUCH_EVENT + +#define PRINT_PPROXIMITY_EVENT(event) \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u)", \ + (uint)event->pproximity.timestamp, (uint)event->pproximity.windowID, (uint)event->pproximity.which); + SDL_EVENT_CASE(SDL_EVENT_PEN_PROXIMITY_IN) + PRINT_PPROXIMITY_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_PEN_PROXIMITY_OUT) + PRINT_PPROXIMITY_EVENT(event); + break; +#undef PRINT_PPROXIMITY_EVENT + + SDL_EVENT_CASE(SDL_EVENT_PEN_AXIS) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u pen_state=%u x=%g y=%g axis=%s value=%g)", + (uint)event->paxis.timestamp, (uint)event->paxis.windowID, (uint)event->paxis.which, (uint)event->paxis.pen_state, event->paxis.x, event->paxis.y, + ((((int) event->paxis.axis) >= 0) && (event->paxis.axis < SDL_arraysize(pen_axisnames))) ? pen_axisnames[event->paxis.axis] : "[UNKNOWN]", event->paxis.value); + break; + + SDL_EVENT_CASE(SDL_EVENT_PEN_MOTION) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u pen_state=%u x=%g y=%g)", + (uint)event->pmotion.timestamp, (uint)event->pmotion.windowID, (uint)event->pmotion.which, (uint)event->pmotion.pen_state, event->pmotion.x, event->pmotion.y); + break; + +#define PRINT_PBUTTON_EVENT(event) \ + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u pen_state=%u x=%g y=%g button=%u state=%s)", \ + (uint)event->pbutton.timestamp, (uint)event->pbutton.windowID, (uint)event->pbutton.which, (uint)event->pbutton.pen_state, event->pbutton.x, event->pbutton.y, \ + (uint)event->pbutton.button, event->pbutton.down ? "down" : "up"); + SDL_EVENT_CASE(SDL_EVENT_PEN_BUTTON_DOWN) + PRINT_PBUTTON_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_PEN_BUTTON_UP) + PRINT_PBUTTON_EVENT(event); + break; +#undef PRINT_PBUTTON_EVENT + +#define PRINT_DROP_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (data='%s' timestamp=%u windowid=%u x=%f y=%f)", event->drop.data, (uint)event->drop.timestamp, (uint)event->drop.windowID, event->drop.x, event->drop.y) + SDL_EVENT_CASE(SDL_EVENT_DROP_FILE) + PRINT_DROP_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_DROP_TEXT) + PRINT_DROP_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_DROP_BEGIN) + PRINT_DROP_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_DROP_COMPLETE) + PRINT_DROP_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_DROP_POSITION) + PRINT_DROP_EVENT(event); + break; +#undef PRINT_DROP_EVENT + +#define PRINT_AUDIODEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%u recording=%s)", (uint)event->adevice.timestamp, (uint)event->adevice.which, event->adevice.recording ? "true" : "false") + SDL_EVENT_CASE(SDL_EVENT_AUDIO_DEVICE_ADDED) + PRINT_AUDIODEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_AUDIO_DEVICE_REMOVED) + PRINT_AUDIODEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED) + PRINT_AUDIODEV_EVENT(event); + break; +#undef PRINT_AUDIODEV_EVENT + +#define PRINT_CAMERADEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%u)", (uint)event->cdevice.timestamp, (uint)event->cdevice.which) + SDL_EVENT_CASE(SDL_EVENT_CAMERA_DEVICE_ADDED) + PRINT_CAMERADEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_CAMERA_DEVICE_REMOVED) + PRINT_CAMERADEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_CAMERA_DEVICE_APPROVED) + PRINT_CAMERADEV_EVENT(event); + break; + SDL_EVENT_CASE(SDL_EVENT_CAMERA_DEVICE_DENIED) + PRINT_CAMERADEV_EVENT(event); + break; +#undef PRINT_CAMERADEV_EVENT + + SDL_EVENT_CASE(SDL_EVENT_SENSOR_UPDATE) + (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d data[0]=%f data[1]=%f data[2]=%f data[3]=%f data[4]=%f data[5]=%f)", + (uint)event->sensor.timestamp, (int)event->sensor.which, + event->sensor.data[0], event->sensor.data[1], event->sensor.data[2], + event->sensor.data[3], event->sensor.data[4], event->sensor.data[5]); + break; + +#undef SDL_EVENT_CASE + + case SDL_EVENT_POLL_SENTINEL: + // No logging necessary for this one + break; + + default: + if (!name[0]) { + if (event->type >= SDL_EVENT_USER) { + SDL_strlcpy(name, "USER", sizeof(name)); + } else { + SDL_strlcpy(name, "UNKNOWN", sizeof(name)); + } + (void)SDL_snprintf(details, sizeof(details), " 0x%x", (uint)event->type); + } + break; + } + + if (name[0]) { + SDL_Log("SDL EVENT: %s%s", name, details); + } + +#undef uint +} + +void SDL_StopEventLoop(void) +{ + const char *report = SDL_GetHint("SDL_EVENT_QUEUE_STATISTICS"); + int i; + SDL_EventEntry *entry; + + SDL_LockMutex(SDL_EventQ.lock); + + SDL_EventQ.active = false; + + if (report && SDL_atoi(report)) { + SDL_Log("SDL EVENT QUEUE: Maximum events in-flight: %d", + SDL_EventQ.max_events_seen); + } + + // Clean out EventQ + for (entry = SDL_EventQ.head; entry;) { + SDL_EventEntry *next = entry->next; + SDL_TransferTemporaryMemoryFromEvent(entry); + SDL_free(entry); + entry = next; + } + for (entry = SDL_EventQ.free; entry;) { + SDL_EventEntry *next = entry->next; + SDL_free(entry); + entry = next; + } + + SDL_SetAtomicInt(&SDL_EventQ.count, 0); + SDL_EventQ.max_events_seen = 0; + SDL_EventQ.head = NULL; + SDL_EventQ.tail = NULL; + SDL_EventQ.free = NULL; + SDL_SetAtomicInt(&SDL_sentinel_pending, 0); + + // Clear disabled event state + for (i = 0; i < SDL_arraysize(SDL_disabled_events); ++i) { + SDL_free(SDL_disabled_events[i]); + SDL_disabled_events[i] = NULL; + } + + SDL_QuitEventWatchList(&SDL_event_watchers); + //SDL_QuitWindowEventWatch(); + + SDL_Mutex *lock = NULL; + if (SDL_EventQ.lock) { + lock = SDL_EventQ.lock; + SDL_EventQ.lock = NULL; + } + + SDL_UnlockMutex(lock); + + if (lock) { + SDL_DestroyMutex(lock); + } +} + +// This function (and associated calls) may be called more than once +bool SDL_StartEventLoop(void) +{ + /* We'll leave the event queue alone, since we might have gotten + some important events at launch (like SDL_EVENT_DROP_FILE) + + FIXME: Does this introduce any other bugs with events at startup? + */ + + // Create the lock and set ourselves active +#ifndef SDL_THREADS_DISABLED + if (!SDL_EventQ.lock) { + SDL_EventQ.lock = SDL_CreateMutex(); + if (SDL_EventQ.lock == NULL) { + return false; + } + } + SDL_LockMutex(SDL_EventQ.lock); + + if (!SDL_InitEventWatchList(&SDL_event_watchers)) { + SDL_UnlockMutex(SDL_EventQ.lock); + return false; + } +#endif // !SDL_THREADS_DISABLED + + //SDL_InitWindowEventWatch(); + + SDL_EventQ.active = true; + +#ifndef SDL_THREADS_DISABLED + SDL_UnlockMutex(SDL_EventQ.lock); +#endif + return true; +} + +// Add an event to the event queue -- called with the queue locked +static int SDL_AddEvent(SDL_Event *event) +{ + SDL_EventEntry *entry; + const int initial_count = SDL_GetAtomicInt(&SDL_EventQ.count); + int final_count; + + if (initial_count >= SDL_MAX_QUEUED_EVENTS) { + SDL_SetError("Event queue is full (%d events)", initial_count); + return 0; + } + + if (SDL_EventQ.free == NULL) { + entry = (SDL_EventEntry *)SDL_malloc(sizeof(*entry)); + if (entry == NULL) { + return 0; + } + } else { + entry = SDL_EventQ.free; + SDL_EventQ.free = entry->next; + } + + if (SDL_EventLoggingVerbosity > 0) { + SDL_LogEvent(event); + } + + SDL_copyp(&entry->event, event); + if (event->type == SDL_EVENT_POLL_SENTINEL) { + SDL_AddAtomicInt(&SDL_sentinel_pending, 1); + } + entry->memory = NULL; + SDL_TransferTemporaryMemoryToEvent(entry); + + if (SDL_EventQ.tail) { + SDL_EventQ.tail->next = entry; + entry->prev = SDL_EventQ.tail; + SDL_EventQ.tail = entry; + entry->next = NULL; + } else { + SDL_assert(!SDL_EventQ.head); + SDL_EventQ.head = entry; + SDL_EventQ.tail = entry; + entry->prev = NULL; + entry->next = NULL; + } + + final_count = SDL_AddAtomicInt(&SDL_EventQ.count, 1) + 1; + if (final_count > SDL_EventQ.max_events_seen) { + SDL_EventQ.max_events_seen = final_count; + } + + ++SDL_last_event_id; + + return 1; +} + +// Remove an event from the queue -- called with the queue locked +static void SDL_CutEvent(SDL_EventEntry *entry) +{ + SDL_TransferTemporaryMemoryFromEvent(entry); + + if (entry->prev) { + entry->prev->next = entry->next; + } + if (entry->next) { + entry->next->prev = entry->prev; + } + + if (entry == SDL_EventQ.head) { + SDL_assert(entry->prev == NULL); + SDL_EventQ.head = entry->next; + } + if (entry == SDL_EventQ.tail) { + SDL_assert(entry->next == NULL); + SDL_EventQ.tail = entry->prev; + } + + if (entry->event.type == SDL_EVENT_POLL_SENTINEL) { + SDL_AddAtomicInt(&SDL_sentinel_pending, -1); + } + + entry->next = SDL_EventQ.free; + SDL_EventQ.free = entry; + SDL_assert(SDL_GetAtomicInt(&SDL_EventQ.count) > 0); + SDL_AddAtomicInt(&SDL_EventQ.count, -1); +} + +static void SDL_SendWakeupEvent(void) +{ +#ifdef SDL_PLATFORM_ANDROID + Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_WAKE); +#endif +} + +// Lock the event queue, take a peep at it, and unlock it +static int SDL_PeepEventsInternal(SDL_Event *events, int numevents, SDL_EventAction action, + Uint32 minType, Uint32 maxType, bool include_sentinel) +{ + int i, used, sentinels_expected = 0; + + // Lock the event queue + used = 0; + + SDL_LockMutex(SDL_EventQ.lock); + { + // Don't look after we've quit + if (!SDL_EventQ.active) { + // We get a few spurious events at shutdown, so don't warn then + if (action == SDL_GETEVENT) { + SDL_SetError("The event system has been shut down"); + } + SDL_UnlockMutex(SDL_EventQ.lock); + return -1; + } + if (action == SDL_ADDEVENT) { + if (!events) { + SDL_UnlockMutex(SDL_EventQ.lock); + return SDL_InvalidParamError("events"); + } + for (i = 0; i < numevents; ++i) { + used += SDL_AddEvent(&events[i]); + } + } else { + SDL_EventEntry *entry, *next; + Uint32 type; + + for (entry = SDL_EventQ.head; entry && (events == NULL || used < numevents); entry = next) { + next = entry->next; + type = entry->event.type; + if (minType <= type && type <= maxType) { + if (events) { + SDL_copyp(&events[used], &entry->event); + + if (action == SDL_GETEVENT) { + SDL_CutEvent(entry); + } + } + if (type == SDL_EVENT_POLL_SENTINEL) { + // Special handling for the sentinel event + if (!include_sentinel) { + // Skip it, we don't want to include it + continue; + } + if (events == NULL || action != SDL_GETEVENT) { + ++sentinels_expected; + } + if (SDL_GetAtomicInt(&SDL_sentinel_pending) > sentinels_expected) { + // Skip it, there's another one pending + continue; + } + } + ++used; + } + } + } + } + SDL_UnlockMutex(SDL_EventQ.lock); + + if (used > 0 && action == SDL_ADDEVENT) { + SDL_SendWakeupEvent(); + } + + return used; +} +int SDL_PeepEvents(SDL_Event *events, int numevents, SDL_EventAction action, + Uint32 minType, Uint32 maxType) +{ + return SDL_PeepEventsInternal(events, numevents, action, minType, maxType, false); +} + +bool SDL_HasEvent(Uint32 type) +{ + return SDL_HasEvents(type, type); +} + +bool SDL_HasEvents(Uint32 minType, Uint32 maxType) +{ + bool found = false; + + SDL_LockMutex(SDL_EventQ.lock); + { + if (SDL_EventQ.active) { + for (SDL_EventEntry *entry = SDL_EventQ.head; entry; entry = entry->next) { + const Uint32 type = entry->event.type; + if (minType <= type && type <= maxType) { + found = true; + break; + } + } + } + } + SDL_UnlockMutex(SDL_EventQ.lock); + + return found; +} + +void SDL_FlushEvent(Uint32 type) +{ + SDL_FlushEvents(type, type); +} + +void SDL_FlushEvents(Uint32 minType, Uint32 maxType) +{ + SDL_EventEntry *entry, *next; + Uint32 type; + + // Make sure the events are current +#if 0 + /* Actually, we can't do this since we might be flushing while processing + a resize event, and calling this might trigger further resize events. + */ + SDL_PumpEvents(); +#endif + + // Lock the event queue + SDL_LockMutex(SDL_EventQ.lock); + { + // Don't look after we've quit + if (!SDL_EventQ.active) { + SDL_UnlockMutex(SDL_EventQ.lock); + return; + } + for (entry = SDL_EventQ.head; entry; entry = next) { + next = entry->next; + type = entry->event.type; + if (minType <= type && type <= maxType) { + SDL_CutEvent(entry); + } + } + } + SDL_UnlockMutex(SDL_EventQ.lock); +} + +typedef enum +{ + SDL_MAIN_CALLBACK_WAITING, + SDL_MAIN_CALLBACK_COMPLETE, + SDL_MAIN_CALLBACK_CANCELED, +} SDL_MainThreadCallbackState; + +typedef struct SDL_MainThreadCallbackEntry +{ + SDL_MainThreadCallback callback; + void *userdata; + SDL_AtomicInt state; + SDL_Semaphore *semaphore; + struct SDL_MainThreadCallbackEntry *next; +} SDL_MainThreadCallbackEntry; + +static SDL_Mutex *SDL_main_callbacks_lock; +static SDL_MainThreadCallbackEntry *SDL_main_callbacks_head; +static SDL_MainThreadCallbackEntry *SDL_main_callbacks_tail; + +static SDL_MainThreadCallbackEntry *SDL_CreateMainThreadCallback(SDL_MainThreadCallback callback, void *userdata, bool wait_complete) +{ + SDL_MainThreadCallbackEntry *entry = (SDL_MainThreadCallbackEntry *)SDL_malloc(sizeof(*entry)); + if (!entry) { + return NULL; + } + + entry->callback = callback; + entry->userdata = userdata; + SDL_SetAtomicInt(&entry->state, SDL_MAIN_CALLBACK_WAITING); + if (wait_complete) { + entry->semaphore = SDL_CreateSemaphore(0); + if (!entry->semaphore) { + SDL_free(entry); + return NULL; + } + } else { + entry->semaphore = NULL; + } + entry->next = NULL; + + return entry; +} + +static void SDL_DestroyMainThreadCallback(SDL_MainThreadCallbackEntry *entry) +{ + if (entry->semaphore) { + SDL_DestroySemaphore(entry->semaphore); + } + SDL_free(entry); +} + +static void SDL_InitMainThreadCallbacks(void) +{ + SDL_main_callbacks_lock = SDL_CreateMutex(); + SDL_assert(SDL_main_callbacks_head == NULL && + SDL_main_callbacks_tail == NULL); +} + +static void SDL_QuitMainThreadCallbacks(void) +{ + SDL_MainThreadCallbackEntry *entry; + + SDL_LockMutex(SDL_main_callbacks_lock); + { + entry = SDL_main_callbacks_head; + SDL_main_callbacks_head = NULL; + SDL_main_callbacks_tail = NULL; + } + SDL_UnlockMutex(SDL_main_callbacks_lock); + + while (entry) { + SDL_MainThreadCallbackEntry *next = entry->next; + + if (entry->semaphore) { + // Let the waiting thread know this is canceled + SDL_SetAtomicInt(&entry->state, SDL_MAIN_CALLBACK_CANCELED); + SDL_SignalSemaphore(entry->semaphore); + } else { + // Nobody's waiting for this, clean it up + SDL_DestroyMainThreadCallback(entry); + } + entry = next; + } + + SDL_DestroyMutex(SDL_main_callbacks_lock); + SDL_main_callbacks_lock = NULL; +} + +static void SDL_RunMainThreadCallbacks(void) +{ + SDL_MainThreadCallbackEntry *entry; + + SDL_LockMutex(SDL_main_callbacks_lock); + { + entry = SDL_main_callbacks_head; + SDL_main_callbacks_head = NULL; + SDL_main_callbacks_tail = NULL; + } + SDL_UnlockMutex(SDL_main_callbacks_lock); + + while (entry) { + SDL_MainThreadCallbackEntry *next = entry->next; + + entry->callback(entry->userdata); + + if (entry->semaphore) { + // Let the waiting thread know this is done + SDL_SetAtomicInt(&entry->state, SDL_MAIN_CALLBACK_COMPLETE); + SDL_SignalSemaphore(entry->semaphore); + } else { + // Nobody's waiting for this, clean it up + SDL_DestroyMainThreadCallback(entry); + } + entry = next; + } +} + +bool SDL_RunOnMainThread(SDL_MainThreadCallback callback, void *userdata, bool wait_complete) +{ + if (SDL_IsMainThread() || !SDL_WasInit(SDL_INIT_EVENTS)) { + // No need to queue the callback + callback(userdata); + return true; + } + + SDL_MainThreadCallbackEntry *entry = SDL_CreateMainThreadCallback(callback, userdata, wait_complete); + if (!entry) { + return false; + } + + SDL_LockMutex(SDL_main_callbacks_lock); + { + if (SDL_main_callbacks_tail) { + SDL_main_callbacks_tail->next = entry; + SDL_main_callbacks_tail = entry; + } else { + SDL_main_callbacks_head = entry; + SDL_main_callbacks_tail = entry; + } + } + SDL_UnlockMutex(SDL_main_callbacks_lock); + + // If the main thread is waiting for events, wake it up + SDL_SendWakeupEvent(); + + if (!wait_complete) { + // Queued for execution, wait not requested + return true; + } + + SDL_WaitSemaphore(entry->semaphore); + + switch (SDL_GetAtomicInt(&entry->state)) { + case SDL_MAIN_CALLBACK_COMPLETE: + // Execution complete! + SDL_DestroyMainThreadCallback(entry); + return true; + + case SDL_MAIN_CALLBACK_CANCELED: + // The callback was canceled on the main thread + SDL_DestroyMainThreadCallback(entry); + return SDL_SetError("Callback canceled"); + + default: + // Probably hit a deadlock in the callback + // We can't destroy the entry as the semaphore will be signaled + // if it ever comes back, just leak it here. + return SDL_SetError("Callback timed out"); + } +} + +void SDL_PumpEventMaintenance(void) +{ +#ifndef SDL_AUDIO_DISABLED + SDL_UpdateAudio(); +#endif + +#ifndef SDL_CAMERA_DISABLED + SDL_UpdateCamera(); +#endif + +#ifndef SDL_SENSOR_DISABLED + // Check for sensor state change + if (SDL_update_sensors) { + SDL_UpdateSensors(); + } +#endif + +#ifndef SDL_JOYSTICK_DISABLED + // Check for joystick state change + if (SDL_update_joysticks) { + SDL_UpdateJoysticks(); + } +#endif + + //SDL_UpdateTrays(); + + //SDL_SendPendingSignalEvents(); // in case we had a signal handler fire, etc. +} + +// Run the system dependent event loops +static void SDL_PumpEventsInternal(bool push_sentinel) +{ + // Free any temporary memory from old events + SDL_FreeTemporaryMemory(); + + // Release any keys held down from last frame + //SDL_ReleaseAutoReleaseKeys(); + + // Run any pending main thread callbacks + SDL_RunMainThreadCallbacks(); + +#ifdef SDL_PLATFORM_ANDROID + // Android event processing is independent of the video subsystem + Android_PumpEvents(0); +#endif + + SDL_PumpEventMaintenance(); + + if (push_sentinel && SDL_EventEnabled(SDL_EVENT_POLL_SENTINEL)) { + SDL_Event sentinel; + + // Make sure we don't already have a sentinel in the queue, and add one to the end + if (SDL_GetAtomicInt(&SDL_sentinel_pending) > 0) { + SDL_PeepEventsInternal(&sentinel, 1, SDL_GETEVENT, SDL_EVENT_POLL_SENTINEL, SDL_EVENT_POLL_SENTINEL, true); + } + + sentinel.type = SDL_EVENT_POLL_SENTINEL; + sentinel.common.timestamp = 0; + SDL_PushEvent(&sentinel); + } +} + +void SDL_PumpEvents(void) +{ + SDL_PumpEventsInternal(false); +} + +// Public functions + +bool SDL_PollEvent(SDL_Event *event) +{ + return SDL_WaitEventTimeoutNS(event, 0); +} + +bool SDL_WaitEvent(SDL_Event *event) +{ + return SDL_WaitEventTimeoutNS(event, -1); +} + +bool SDL_WaitEventTimeout(SDL_Event *event, Sint32 timeoutMS) +{ + Sint64 timeoutNS; + + if (timeoutMS > 0) { + timeoutNS = SDL_MS_TO_NS(timeoutMS); + } else { + timeoutNS = timeoutMS; + } + return SDL_WaitEventTimeoutNS(event, timeoutNS); +} + +bool SDL_WaitEventTimeoutNS(SDL_Event *event, Sint64 timeoutNS) +{ + Uint64 start, expiration; + bool include_sentinel = (timeoutNS == 0); + int result; + + if (timeoutNS > 0) { + start = SDL_GetTicksNS(); + expiration = start + timeoutNS; + } else { + start = 0; + expiration = 0; + } + + // If there isn't a poll sentinel event pending, pump events and add one + if (SDL_GetAtomicInt(&SDL_sentinel_pending) == 0) { + SDL_PumpEventsInternal(true); + } + + // First check for existing events + result = SDL_PeepEventsInternal(event, 1, SDL_GETEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST, include_sentinel); + if (result < 0) { + return false; + } + if (include_sentinel) { + if (event) { + if (event->type == SDL_EVENT_POLL_SENTINEL) { + // Reached the end of a poll cycle, and not willing to wait + return false; + } + } else { + // Need to peek the next event to check for sentinel + SDL_Event dummy; + + if (SDL_PeepEventsInternal(&dummy, 1, SDL_PEEKEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST, true) && + dummy.type == SDL_EVENT_POLL_SENTINEL) { + SDL_PeepEventsInternal(&dummy, 1, SDL_GETEVENT, SDL_EVENT_POLL_SENTINEL, SDL_EVENT_POLL_SENTINEL, true); + // Reached the end of a poll cycle, and not willing to wait + return false; + } + } + } + if (result == 0) { + if (timeoutNS == 0) { + // No events available, and not willing to wait + return false; + } + } else { + // Has existing events + return true; + } + // We should have completely handled timeoutNS == 0 above + SDL_assert(timeoutNS != 0); + +#ifdef SDL_PLATFORM_ANDROID + for (;;) { + if (SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST) > 0) { + return true; + } + + Uint64 delay = -1; + if (timeoutNS > 0) { + Uint64 now = SDL_GetTicksNS(); + if (now >= expiration) { + // Timeout expired and no events + return false; + } + delay = (expiration - now); + } + Android_PumpEvents(delay); + } +#else + for (;;) { + SDL_PumpEventsInternal(true); + + if (SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST) > 0) { + return true; + } + + Uint64 delay = EVENT_POLL_INTERVAL_NS; + if (timeoutNS > 0) { + Uint64 now = SDL_GetTicksNS(); + if (now >= expiration) { + // Timeout expired and no events + return false; + } + delay = SDL_min((expiration - now), delay); + } + SDL_DelayNS(delay); + } +#endif // SDL_PLATFORM_ANDROID +} + +static bool SDL_CallEventWatchers(SDL_Event *event) +{ + if (event->common.type == SDL_EVENT_POLL_SENTINEL) { + return true; + } + + return SDL_DispatchEventWatchList(&SDL_event_watchers, event); +} + +bool SDL_PushEvent(SDL_Event *event) +{ + if (!event->common.timestamp) { + event->common.timestamp = SDL_GetTicksNS(); + } + + if (!SDL_CallEventWatchers(event)) { + SDL_ClearError(); + return false; + } + + if (SDL_PeepEvents(event, 1, SDL_ADDEVENT, 0, 0) <= 0) { + return false; + } + + return true; +} + +void SDL_SetEventFilter(SDL_EventFilter filter, void *userdata) +{ + SDL_EventEntry *event, *next; + SDL_LockMutex(SDL_event_watchers.lock); + { + // Set filter and discard pending events + SDL_event_watchers.filter.callback = filter; + SDL_event_watchers.filter.userdata = userdata; + if (filter) { + // Cut all events not accepted by the filter + SDL_LockMutex(SDL_EventQ.lock); + { + for (event = SDL_EventQ.head; event; event = next) { + next = event->next; + if (!filter(userdata, &event->event)) { + SDL_CutEvent(event); + } + } + } + SDL_UnlockMutex(SDL_EventQ.lock); + } + } + SDL_UnlockMutex(SDL_event_watchers.lock); +} + +bool SDL_GetEventFilter(SDL_EventFilter *filter, void **userdata) +{ + SDL_EventWatcher event_ok; + + SDL_LockMutex(SDL_event_watchers.lock); + { + event_ok = SDL_event_watchers.filter; + } + SDL_UnlockMutex(SDL_event_watchers.lock); + + if (filter) { + *filter = event_ok.callback; + } + if (userdata) { + *userdata = event_ok.userdata; + } + return event_ok.callback ? true : false; +} + +bool SDL_AddEventWatch(SDL_EventFilter filter, void *userdata) +{ + return SDL_AddEventWatchList(&SDL_event_watchers, filter, userdata); +} + +void SDL_RemoveEventWatch(SDL_EventFilter filter, void *userdata) +{ + SDL_RemoveEventWatchList(&SDL_event_watchers, filter, userdata); +} + +void SDL_FilterEvents(SDL_EventFilter filter, void *userdata) +{ + SDL_LockMutex(SDL_EventQ.lock); + { + SDL_EventEntry *entry, *next; + for (entry = SDL_EventQ.head; entry; entry = next) { + next = entry->next; + if (!filter(userdata, &entry->event)) { + SDL_CutEvent(entry); + } + } + } + SDL_UnlockMutex(SDL_EventQ.lock); +} + +void SDL_SetEventEnabled(Uint32 type, bool enabled) +{ + bool current_state; + Uint8 hi = ((type >> 8) & 0xff); + Uint8 lo = (type & 0xff); + + if (SDL_disabled_events[hi] && + (SDL_disabled_events[hi]->bits[lo / 32] & (1U << (lo & 31)))) { + current_state = false; + } else { + current_state = true; + } + + if ((enabled != false) != current_state) { + if (enabled) { + SDL_assert(SDL_disabled_events[hi] != NULL); + SDL_disabled_events[hi]->bits[lo / 32] &= ~(1U << (lo & 31)); + + // Gamepad events depend on joystick events + switch (type) { + case SDL_EVENT_GAMEPAD_ADDED: + SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_ADDED, true); + break; + case SDL_EVENT_GAMEPAD_REMOVED: + SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_REMOVED, true); + break; + case SDL_EVENT_GAMEPAD_AXIS_MOTION: + case SDL_EVENT_GAMEPAD_BUTTON_DOWN: + case SDL_EVENT_GAMEPAD_BUTTON_UP: + SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_AXIS_MOTION, true); + SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_HAT_MOTION, true); + SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_BUTTON_DOWN, true); + SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_BUTTON_UP, true); + break; + case SDL_EVENT_GAMEPAD_UPDATE_COMPLETE: + SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_UPDATE_COMPLETE, true); + break; + default: + break; + } + } else { + // Disable this event type and discard pending events + if (!SDL_disabled_events[hi]) { + SDL_disabled_events[hi] = (SDL_DisabledEventBlock *)SDL_calloc(1, sizeof(SDL_DisabledEventBlock)); + } + // Out of memory, nothing we can do... + if (SDL_disabled_events[hi]) { + SDL_disabled_events[hi]->bits[lo / 32] |= (1U << (lo & 31)); + SDL_FlushEvent(type); + } + } + + /* turn off drag'n'drop support if we've disabled the events. + This might change some UI details at the OS level. */ + if (type == SDL_EVENT_DROP_FILE || type == SDL_EVENT_DROP_TEXT) { + //SDL_ToggleDragAndDropSupport(); + } + } +} + +bool SDL_EventEnabled(Uint32 type) +{ + Uint8 hi = ((type >> 8) & 0xff); + Uint8 lo = (type & 0xff); + + if (SDL_disabled_events[hi] && + (SDL_disabled_events[hi]->bits[lo / 32] & (1U << (lo & 31)))) { + return false; + } else { + return true; + } +} + +Uint32 SDL_RegisterEvents(int numevents) +{ + Uint32 event_base = 0; + + if (numevents > 0) { + int value = SDL_AddAtomicInt(&SDL_userevents, numevents); + if (value >= 0 && value <= (SDL_EVENT_LAST - SDL_EVENT_USER)) { + event_base = (Uint32)(SDL_EVENT_USER + value); + } + } + return event_base; +} + +void SDL_SendAppEvent(SDL_EventType eventType) +{ + if (SDL_EventEnabled(eventType)) { + SDL_Event event; + event.type = eventType; + event.common.timestamp = 0; + + switch (eventType) { + case SDL_EVENT_TERMINATING: + case SDL_EVENT_LOW_MEMORY: + case SDL_EVENT_WILL_ENTER_BACKGROUND: + case SDL_EVENT_DID_ENTER_BACKGROUND: + case SDL_EVENT_WILL_ENTER_FOREGROUND: + case SDL_EVENT_DID_ENTER_FOREGROUND: + // We won't actually queue this event, it needs to be handled in this call stack by an event watcher + if (SDL_EventLoggingVerbosity > 0) { + SDL_LogEvent(&event); + } + SDL_CallEventWatchers(&event); + break; + default: + SDL_PushEvent(&event); + break; + } + } +} + +void SDL_SendKeymapChangedEvent(void) +{ + SDL_SendAppEvent(SDL_EVENT_KEYMAP_CHANGED); +} + +void SDL_SendLocaleChangedEvent(void) +{ + SDL_SendAppEvent(SDL_EVENT_LOCALE_CHANGED); +} + +void SDL_SendSystemThemeChangedEvent(void) +{ + SDL_SendAppEvent(SDL_EVENT_SYSTEM_THEME_CHANGED); +} + +bool SDL_InitEvents(void) +{ +#ifdef SDL_PLATFORM_ANDROID + Android_InitEvents(); +#endif +#ifndef SDL_JOYSTICK_DISABLED + SDL_AddHintCallback(SDL_HINT_AUTO_UPDATE_JOYSTICKS, SDL_AutoUpdateJoysticksChanged, NULL); +#endif +#ifndef SDL_SENSOR_DISABLED + SDL_AddHintCallback(SDL_HINT_AUTO_UPDATE_SENSORS, SDL_AutoUpdateSensorsChanged, NULL); +#endif + SDL_AddHintCallback(SDL_HINT_EVENT_LOGGING, SDL_EventLoggingChanged, NULL); + SDL_AddHintCallback(SDL_HINT_POLL_SENTINEL, SDL_PollSentinelChanged, NULL); + SDL_InitMainThreadCallbacks(); + if (!SDL_StartEventLoop()) { + SDL_RemoveHintCallback(SDL_HINT_EVENT_LOGGING, SDL_EventLoggingChanged, NULL); + return false; + } + + //SDL_InitQuit(); + + return true; +} + +void SDL_QuitEvents(void) +{ + //SDL_QuitQuit(); + SDL_StopEventLoop(); + SDL_QuitMainThreadCallbacks(); + SDL_RemoveHintCallback(SDL_HINT_POLL_SENTINEL, SDL_PollSentinelChanged, NULL); + SDL_RemoveHintCallback(SDL_HINT_EVENT_LOGGING, SDL_EventLoggingChanged, NULL); +#ifndef SDL_JOYSTICK_DISABLED + SDL_RemoveHintCallback(SDL_HINT_AUTO_UPDATE_JOYSTICKS, SDL_AutoUpdateJoysticksChanged, NULL); +#endif +#ifndef SDL_SENSOR_DISABLED + SDL_RemoveHintCallback(SDL_HINT_AUTO_UPDATE_SENSORS, SDL_AutoUpdateSensorsChanged, NULL); +#endif +#ifdef SDL_PLATFORM_ANDROID + Android_QuitEvents(); +#endif +} diff --git a/thirdparty/sdl/events/SDL_events_c.h b/thirdparty/sdl/events/SDL_events_c.h new file mode 100644 index 00000000000..f3a0744d1cf --- /dev/null +++ b/thirdparty/sdl/events/SDL_events_c.h @@ -0,0 +1,59 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_events_c_h_ +#define SDL_events_c_h_ + +#include "SDL_internal.h" + +// Useful functions and variables from SDL_events.c +//#include "../video/SDL_sysvideo.h" + +#include "SDL_mouse_c.h" + +// Start and stop the event processing loop +extern bool SDL_StartEventLoop(void); +extern void SDL_StopEventLoop(void); +extern void SDL_QuitInterrupt(void); + +extern void SDL_SendAppEvent(SDL_EventType eventType); +extern void SDL_SendKeymapChangedEvent(void); +extern void SDL_SendLocaleChangedEvent(void); +extern void SDL_SendSystemThemeChangedEvent(void); + +extern void *SDL_AllocateTemporaryMemory(size_t size); +extern const char *SDL_CreateTemporaryString(const char *string); +extern void *SDL_ClaimTemporaryMemory(const void *mem); +extern void SDL_FreeTemporaryMemory(void); + +extern void SDL_PumpEventMaintenance(void); + +extern void SDL_SendQuit(void); + +extern bool SDL_InitEvents(void); +extern void SDL_QuitEvents(void); + +extern void SDL_SendPendingSignalEvents(void); + +extern bool SDL_InitQuit(void); +extern void SDL_QuitQuit(void); + +#endif // SDL_events_c_h_ diff --git a/thirdparty/sdl/events/SDL_eventwatch.c b/thirdparty/sdl/events/SDL_eventwatch.c new file mode 100644 index 00000000000..08e7248c6a4 --- /dev/null +++ b/thirdparty/sdl/events/SDL_eventwatch.c @@ -0,0 +1,143 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_eventwatch_c.h" + + +bool SDL_InitEventWatchList(SDL_EventWatchList *list) +{ + if (list->lock == NULL) { + list->lock = SDL_CreateMutex(); + if (list->lock == NULL) { + return false; + } + } + return true; +} + +void SDL_QuitEventWatchList(SDL_EventWatchList *list) +{ + if (list->lock) { + SDL_DestroyMutex(list->lock); + list->lock = NULL; + } + if (list->watchers) { + SDL_free(list->watchers); + list->watchers = NULL; + list->count = 0; + } + SDL_zero(list->filter); +} + +bool SDL_DispatchEventWatchList(SDL_EventWatchList *list, SDL_Event *event) +{ + SDL_EventWatcher *filter = &list->filter; + + if (!filter->callback && list->count == 0) { + return true; + } + + SDL_LockMutex(list->lock); + { + // Make sure we only dispatch the current watcher list + int i, count = list->count; + + if (filter->callback && !filter->callback(filter->userdata, event)) { + SDL_UnlockMutex(list->lock); + return false; + } + + list->dispatching = true; + for (i = 0; i < count; ++i) { + if (!list->watchers[i].removed) { + list->watchers[i].callback(list->watchers[i].userdata, event); + } + } + list->dispatching = false; + + if (list->removed) { + for (i = list->count; i--;) { + if (list->watchers[i].removed) { + --list->count; + if (i < list->count) { + SDL_memmove(&list->watchers[i], &list->watchers[i + 1], (list->count - i) * sizeof(list->watchers[i])); + } + } + } + list->removed = false; + } + } + SDL_UnlockMutex(list->lock); + + return true; +} + +bool SDL_AddEventWatchList(SDL_EventWatchList *list, SDL_EventFilter filter, void *userdata) +{ + bool result = true; + + SDL_LockMutex(list->lock); + { + SDL_EventWatcher *watchers; + + watchers = (SDL_EventWatcher *)SDL_realloc(list->watchers, (list->count + 1) * sizeof(*watchers)); + if (watchers) { + SDL_EventWatcher *watcher; + + list->watchers = watchers; + watcher = &list->watchers[list->count]; + watcher->callback = filter; + watcher->userdata = userdata; + watcher->removed = false; + ++list->count; + } else { + result = false; + } + } + SDL_UnlockMutex(list->lock); + + return result; +} + +void SDL_RemoveEventWatchList(SDL_EventWatchList *list, SDL_EventFilter filter, void *userdata) +{ + SDL_LockMutex(list->lock); + { + int i; + + for (i = 0; i < list->count; ++i) { + if (list->watchers[i].callback == filter && list->watchers[i].userdata == userdata) { + if (list->dispatching) { + list->watchers[i].removed = true; + list->removed = true; + } else { + --list->count; + if (i < list->count) { + SDL_memmove(&list->watchers[i], &list->watchers[i + 1], (list->count - i) * sizeof(list->watchers[i])); + } + } + break; + } + } + } + SDL_UnlockMutex(list->lock); +} diff --git a/thirdparty/sdl/events/SDL_eventwatch_c.h b/thirdparty/sdl/events/SDL_eventwatch_c.h new file mode 100644 index 00000000000..c9aea38c0dd --- /dev/null +++ b/thirdparty/sdl/events/SDL_eventwatch_c.h @@ -0,0 +1,45 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +typedef struct SDL_EventWatcher +{ + SDL_EventFilter callback; + void *userdata; + bool removed; +} SDL_EventWatcher; + +typedef struct SDL_EventWatchList +{ + SDL_Mutex *lock; + SDL_EventWatcher filter; + SDL_EventWatcher *watchers; + int count; + bool dispatching; + bool removed; +} SDL_EventWatchList; + + +extern bool SDL_InitEventWatchList(SDL_EventWatchList *list); +extern void SDL_QuitEventWatchList(SDL_EventWatchList *list); +extern bool SDL_DispatchEventWatchList(SDL_EventWatchList *list, SDL_Event *event); +extern bool SDL_AddEventWatchList(SDL_EventWatchList *list, SDL_EventFilter filter, void *userdata); +extern void SDL_RemoveEventWatchList(SDL_EventWatchList *list, SDL_EventFilter filter, void *userdata); diff --git a/thirdparty/sdl/events/SDL_mouse_c.h b/thirdparty/sdl/events/SDL_mouse_c.h new file mode 100644 index 00000000000..5927b8bd75f --- /dev/null +++ b/thirdparty/sdl/events/SDL_mouse_c.h @@ -0,0 +1,215 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_mouse_c_h_ +#define SDL_mouse_c_h_ + +// Mouse events not associated with a specific input device +#define SDL_GLOBAL_MOUSE_ID 0 + +// The default mouse input device, for platforms that don't have multiple mice +#define SDL_DEFAULT_MOUSE_ID 1 + +typedef struct SDL_CursorData SDL_CursorData; + +struct SDL_Cursor +{ + struct SDL_Cursor *next; + SDL_CursorData *internal; +}; + +typedef struct +{ + Uint64 last_timestamp; + double click_motion_x; + double click_motion_y; + Uint8 click_count; +} SDL_MouseClickState; + +typedef struct +{ + SDL_MouseID mouseID; + Uint32 buttonstate; + + // Data for double-click tracking + int num_clickstates; + SDL_MouseClickState *clickstate; +} SDL_MouseInputSource; + +typedef struct +{ + // Create a cursor from a surface + SDL_Cursor *(*CreateCursor)(SDL_Surface *surface, int hot_x, int hot_y); + + // Create a system cursor + SDL_Cursor *(*CreateSystemCursor)(SDL_SystemCursor id); + + // Show the specified cursor, or hide if cursor is NULL + bool (*ShowCursor)(SDL_Cursor *cursor); + + // This is called when a mouse motion event occurs + bool (*MoveCursor)(SDL_Cursor *cursor); + + // Free a window manager cursor + void (*FreeCursor)(SDL_Cursor *cursor); + + // Warp the mouse to (x,y) within a window + bool (*WarpMouse)(SDL_Window *window, float x, float y); + + // Warp the mouse to (x,y) in screen space + bool (*WarpMouseGlobal)(float x, float y); + + // Set relative mode + bool (*SetRelativeMouseMode)(bool enabled); + + // Set mouse capture + bool (*CaptureMouse)(SDL_Window *window); + + // Get absolute mouse coordinates. (x) and (y) are never NULL and set to zero before call. + SDL_MouseButtonFlags (*GetGlobalMouseState)(float *x, float *y); + + // Platform-specific system mouse transform + void (*ApplySystemScale)(void *internal, Uint64 timestamp, SDL_Window *window, SDL_MouseID mouseID, float *x, float *y); + void *system_scale_data; + + // integer mode data + Uint8 integer_mode_flags; // 1 to enable mouse quantization, 2 to enable wheel quantization + float integer_mode_residual_motion_x; + float integer_mode_residual_motion_y; + + // Data common to all mice + SDL_Window *focus; + float x; + float y; + float x_accu; + float y_accu; + float last_x, last_y; // the last reported x and y coordinates + float residual_scroll_x; + float residual_scroll_y; + double click_motion_x; + double click_motion_y; + bool has_position; + bool relative_mode; + bool relative_mode_warp_motion; + bool relative_mode_cursor_visible; + bool relative_mode_center; + bool warp_emulation_hint; + bool warp_emulation_active; + bool warp_emulation_prohibited; + Uint64 last_center_warp_time_ns; + bool enable_normal_speed_scale; + float normal_speed_scale; + bool enable_relative_speed_scale; + float relative_speed_scale; + bool enable_relative_system_scale; + Uint32 double_click_time; + int double_click_radius; + bool touch_mouse_events; + bool mouse_touch_events; + bool pen_mouse_events; + bool pen_touch_events; + bool was_touch_mouse_events; // Was a touch-mouse event pending? + bool added_mouse_touch_device; // did we SDL_AddTouch() a virtual touch device for the mouse? + bool added_pen_touch_device; // did we SDL_AddTouch() a virtual touch device for pens? +#ifdef SDL_PLATFORM_VITA + Uint8 vita_touch_mouse_device; +#endif + bool auto_capture; + bool capture_desired; + SDL_Window *capture_window; + + // Data for input source state + int num_sources; + SDL_MouseInputSource *sources; + + SDL_Cursor *cursors; + SDL_Cursor *def_cursor; + SDL_Cursor *cur_cursor; + bool cursor_shown; + + // Driver-dependent data. + void *internal; +} SDL_Mouse; + +// Initialize the mouse subsystem, called before the main video driver is initialized +extern bool SDL_PreInitMouse(void); + +// Finish initializing the mouse subsystem, called after the main video driver was initialized +extern void SDL_PostInitMouse(void); + +// Return whether a device is actually a mouse +extern bool SDL_IsMouse(Uint16 vendor, Uint16 product); + +// A mouse has been added to the system +extern void SDL_AddMouse(SDL_MouseID mouseID, const char *name, bool send_event); + +// A mouse has been removed from the system +extern void SDL_RemoveMouse(SDL_MouseID mouseID, bool send_event); + +// Get the mouse state structure +extern SDL_Mouse *SDL_GetMouse(void); + +// Set the default mouse cursor +extern void SDL_SetDefaultCursor(SDL_Cursor *cursor); + +// Get the preferred default system cursor +extern SDL_SystemCursor SDL_GetDefaultSystemCursor(void); + +// Set the mouse focus window +extern void SDL_SetMouseFocus(SDL_Window *window); + +// Update the mouse capture window +extern bool SDL_UpdateMouseCapture(bool force_release); + +// Send a mouse motion event +extern void SDL_SendMouseMotion(Uint64 timestamp, SDL_Window *window, SDL_MouseID mouseID, bool relative, float x, float y); + +// Send a mouse button event +extern void SDL_SendMouseButton(Uint64 timestamp, SDL_Window *window, SDL_MouseID mouseID, Uint8 button, bool down); + +// Send a mouse button event with a click count +extern void SDL_SendMouseButtonClicks(Uint64 timestamp, SDL_Window *window, SDL_MouseID mouseID, Uint8 button, bool down, int clicks); + +// Send a mouse wheel event +extern void SDL_SendMouseWheel(Uint64 timestamp, SDL_Window *window, SDL_MouseID mouseID, float x, float y, SDL_MouseWheelDirection direction); + +// Warp the mouse within the window, potentially overriding relative mode +extern void SDL_PerformWarpMouseInWindow(SDL_Window *window, float x, float y, bool ignore_relative_mode); + +// Relative mouse mode +extern bool SDL_SetRelativeMouseMode(bool enabled); +extern bool SDL_GetRelativeMouseMode(void); +extern void SDL_UpdateRelativeMouseMode(void); +extern void SDL_DisableMouseWarpEmulation(void); + +// TODO RECONNECT: Set mouse state to "zero" +#if 0 +extern void SDL_ResetMouse(void); +#endif // 0 + +// Check if mouse position is within window or captured by window +extern bool SDL_MousePositionInWindow(SDL_Window *window, float x, float y); + +// Shutdown the mouse subsystem +extern void SDL_QuitMouse(void); + +#endif // SDL_mouse_c_h_ diff --git a/thirdparty/sdl/haptic/SDL_haptic.c b/thirdparty/sdl/haptic/SDL_haptic.c new file mode 100644 index 00000000000..1c11db68643 --- /dev/null +++ b/thirdparty/sdl/haptic/SDL_haptic.c @@ -0,0 +1,788 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_syshaptic.h" +#include "SDL_haptic_c.h" +#include "../joystick/SDL_joystick_c.h" // For SDL_IsJoystickValid +#include "../SDL_hints_c.h" + +typedef struct SDL_Haptic_VIDPID_Naxes { + Uint16 vid; + Uint16 pid; + Uint16 naxes; +} SDL_Haptic_VIDPID_Naxes; + +static void SDL_Haptic_Load_Axes_List(SDL_Haptic_VIDPID_Naxes **entries, int *num_entries) +{ + SDL_Haptic_VIDPID_Naxes entry; + const char *spot; + int length = 0; + + spot = SDL_GetHint(SDL_HINT_JOYSTICK_HAPTIC_AXES); + if (!spot) + return; + + while (SDL_sscanf(spot, "0x%hx/0x%hx/%hu%n", &entry.vid, &entry.pid, &entry.naxes, &length) == 3) { + SDL_assert(length > 0); + spot += length; + length = 0; + + if ((*num_entries % 8) == 0) { + int new_max = *num_entries + 8; + SDL_Haptic_VIDPID_Naxes *new_entries = + (SDL_Haptic_VIDPID_Naxes *)SDL_realloc(*entries, new_max * sizeof(**entries)); + + // Out of memory, go with what we have already + if (!new_entries) + break; + + *entries = new_entries; + } + (*entries)[(*num_entries)++] = entry; + + if (spot[0] == ',') + spot++; + } +} + +// /* Return -1 if not found */ +static int SDL_Haptic_Naxes_List_Index(struct SDL_Haptic_VIDPID_Naxes *entries, int num_entries, Uint16 vid, Uint16 pid) +{ + if (!entries) + return -1; + + int i; + for (i = 0; i < num_entries; ++i) { + if (entries[i].vid == vid && entries[i].pid == pid) + return i; + } + + return -1; +} + +// Check if device needs a custom number of naxes +static int SDL_Haptic_Get_Naxes(Uint16 vid, Uint16 pid) +{ + int num_entries = 0, index = 0, naxes = -1; + SDL_Haptic_VIDPID_Naxes *naxes_list = NULL; + + SDL_Haptic_Load_Axes_List(&naxes_list, &num_entries); + if (!num_entries || !naxes_list) + return -1; + + // Perform "wildcard" pass + index = SDL_Haptic_Naxes_List_Index(naxes_list, num_entries, 0xffff, 0xffff); + if (index >= 0) + naxes = naxes_list[index].naxes; + + index = SDL_Haptic_Naxes_List_Index(naxes_list, num_entries, vid, pid); + if (index >= 0) + naxes = naxes_list[index].naxes; + + SDL_free(naxes_list); + return naxes; +} + +static SDL_Haptic *SDL_haptics = NULL; + +#define CHECK_HAPTIC_MAGIC(haptic, result) \ + if (!SDL_ObjectValid(haptic, SDL_OBJECT_TYPE_HAPTIC)) { \ + SDL_InvalidParamError("haptic"); \ + return result; \ + } + +bool SDL_InitHaptics(void) +{ + return SDL_SYS_HapticInit(); +} + +static bool SDL_GetHapticIndex(SDL_HapticID instance_id, int *driver_index) +{ + int num_haptics, device_index; + + if (instance_id > 0) { + num_haptics = SDL_SYS_NumHaptics(); + for (device_index = 0; device_index < num_haptics; ++device_index) { + SDL_HapticID haptic_id = SDL_SYS_HapticInstanceID(device_index); + if (haptic_id == instance_id) { + *driver_index = device_index; + return true; + } + } + } + + SDL_SetError("Haptic device %" SDL_PRIu32 " not found", instance_id); + return false; +} + +SDL_HapticID *SDL_GetHaptics(int *count) +{ + int device_index; + int haptic_index = 0, num_haptics = 0; + SDL_HapticID *haptics; + + num_haptics = SDL_SYS_NumHaptics(); + + haptics = (SDL_HapticID *)SDL_malloc((num_haptics + 1) * sizeof(*haptics)); + if (haptics) { + if (count) { + *count = num_haptics; + } + + for (device_index = 0; device_index < num_haptics; ++device_index) { + haptics[haptic_index] = SDL_SYS_HapticInstanceID(device_index); + SDL_assert(haptics[haptic_index] > 0); + ++haptic_index; + } + haptics[haptic_index] = 0; + } else { + if (count) { + *count = 0; + } + } + + return haptics; +} + +const char *SDL_GetHapticNameForID(SDL_HapticID instance_id) +{ + int device_index; + const char *name = NULL; + + if (SDL_GetHapticIndex(instance_id, &device_index)) { + name = SDL_GetPersistentString(SDL_SYS_HapticName(device_index)); + } + return name; +} + +SDL_Haptic *SDL_OpenHaptic(SDL_HapticID instance_id) +{ + SDL_Haptic *haptic; + SDL_Haptic *hapticlist; + const char *name; + int device_index = 0; + + if (!SDL_GetHapticIndex(instance_id, &device_index)) { + return NULL; + } + + hapticlist = SDL_haptics; + /* If the haptic device is already open, return it + * it is important that we have a single haptic device for each instance id + */ + while (hapticlist) { + if (instance_id == hapticlist->instance_id) { + haptic = hapticlist; + ++haptic->ref_count; + return haptic; + } + hapticlist = hapticlist->next; + } + + // Create the haptic device + haptic = (SDL_Haptic *)SDL_calloc(1, sizeof(*haptic)); + if (!haptic) { + return NULL; + } + + // Initialize the haptic device + SDL_SetObjectValid(haptic, SDL_OBJECT_TYPE_HAPTIC, true); + haptic->instance_id = instance_id; + haptic->rumble_id = -1; + if (!SDL_SYS_HapticOpen(haptic)) { + SDL_SetObjectValid(haptic, SDL_OBJECT_TYPE_HAPTIC, false); + SDL_free(haptic); + return NULL; + } + + if (!haptic->name) { + name = SDL_SYS_HapticName(device_index); + if (name) { + haptic->name = SDL_strdup(name); + } + } + + // Add haptic to list + ++haptic->ref_count; + // Link the haptic in the list + haptic->next = SDL_haptics; + SDL_haptics = haptic; + + // Disable autocenter and set gain to max. + if (haptic->supported & SDL_HAPTIC_GAIN) { + SDL_SetHapticGain(haptic, 100); + } + if (haptic->supported & SDL_HAPTIC_AUTOCENTER) { + SDL_SetHapticAutocenter(haptic, 0); + } + + return haptic; +} + +SDL_Haptic *SDL_GetHapticFromID(SDL_HapticID instance_id) +{ + SDL_Haptic *haptic; + + for (haptic = SDL_haptics; haptic; haptic = haptic->next) { + if (instance_id == haptic->instance_id) { + break; + } + } + return haptic; +} + +SDL_HapticID SDL_GetHapticID(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, 0); + + return haptic->instance_id; +} + +const char *SDL_GetHapticName(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, NULL); + + return SDL_GetPersistentString(haptic->name); +} + +bool SDL_IsMouseHaptic(void) +{ + if (SDL_SYS_HapticMouse() < 0) { + return false; + } + return true; +} + +SDL_Haptic *SDL_OpenHapticFromMouse(void) +{ + int device_index; + + device_index = SDL_SYS_HapticMouse(); + + if (device_index < 0) { + SDL_SetError("Haptic: Mouse isn't a haptic device."); + return NULL; + } + + return SDL_OpenHaptic(device_index); +} + +bool SDL_IsJoystickHaptic(SDL_Joystick *joystick) +{ + bool result = false; + + SDL_LockJoysticks(); + { + // Must be a valid joystick + if (SDL_IsJoystickValid(joystick) && + !SDL_IsGamepad(SDL_GetJoystickID(joystick))) { + result = SDL_SYS_JoystickIsHaptic(joystick); + } + } + SDL_UnlockJoysticks(); + + return result; +} + +SDL_Haptic *SDL_OpenHapticFromJoystick(SDL_Joystick *joystick) +{ + SDL_Haptic *haptic; + SDL_Haptic *hapticlist; + + SDL_LockJoysticks(); + { + // Must be a valid joystick + if (!SDL_IsJoystickValid(joystick)) { + SDL_SetError("Haptic: Joystick isn't valid."); + SDL_UnlockJoysticks(); + return NULL; + } + + // Joystick must be haptic + if (SDL_IsGamepad(SDL_GetJoystickID(joystick)) || + !SDL_SYS_JoystickIsHaptic(joystick)) { + SDL_SetError("Haptic: Joystick isn't a haptic device."); + SDL_UnlockJoysticks(); + return NULL; + } + + hapticlist = SDL_haptics; + // Check to see if joystick's haptic is already open + while (hapticlist) { + if (SDL_SYS_JoystickSameHaptic(hapticlist, joystick)) { + haptic = hapticlist; + ++haptic->ref_count; + SDL_UnlockJoysticks(); + return haptic; + } + hapticlist = hapticlist->next; + } + + // Create the haptic device + haptic = (SDL_Haptic *)SDL_calloc(1, sizeof(*haptic)); + if (!haptic) { + SDL_UnlockJoysticks(); + return NULL; + } + + /* Initialize the haptic device + * This function should fill in the instance ID and name. + */ + SDL_SetObjectValid(haptic, SDL_OBJECT_TYPE_HAPTIC, true); + haptic->rumble_id = -1; + if (!SDL_SYS_HapticOpenFromJoystick(haptic, joystick)) { + SDL_SetError("Haptic: SDL_SYS_HapticOpenFromJoystick failed."); + SDL_SetObjectValid(haptic, SDL_OBJECT_TYPE_HAPTIC, false); + SDL_free(haptic); + SDL_UnlockJoysticks(); + return NULL; + } + SDL_assert(haptic->instance_id != 0); + } + SDL_UnlockJoysticks(); + + // Check if custom number of haptic axes was defined + Uint16 vid = SDL_GetJoystickVendor(joystick); + Uint16 pid = SDL_GetJoystickProduct(joystick); + int general_axes = SDL_GetNumJoystickAxes(joystick); + + int naxes = SDL_Haptic_Get_Naxes(vid, pid); + if (naxes > 0) + haptic->naxes = naxes; + + // Limit to the actual number of axes found on the device + if (general_axes >= 0 && naxes > general_axes) + haptic->naxes = general_axes; + + // Add haptic to list + ++haptic->ref_count; + // Link the haptic in the list + haptic->next = SDL_haptics; + SDL_haptics = haptic; + + return haptic; +} + +void SDL_CloseHaptic(SDL_Haptic *haptic) +{ + int i; + SDL_Haptic *hapticlist; + SDL_Haptic *hapticlistprev; + + CHECK_HAPTIC_MAGIC(haptic,); + + // Check if it's still in use + if (--haptic->ref_count > 0) { + return; + } + + // Close it, properly removing effects if needed + for (i = 0; i < haptic->neffects; i++) { + if (haptic->effects[i].hweffect != NULL) { + SDL_DestroyHapticEffect(haptic, i); + } + } + SDL_SYS_HapticClose(haptic); + SDL_SetObjectValid(haptic, SDL_OBJECT_TYPE_HAPTIC, false); + + // Remove from the list + hapticlist = SDL_haptics; + hapticlistprev = NULL; + while (hapticlist) { + if (haptic == hapticlist) { + if (hapticlistprev) { + // unlink this entry + hapticlistprev->next = hapticlist->next; + } else { + SDL_haptics = haptic->next; + } + + break; + } + hapticlistprev = hapticlist; + hapticlist = hapticlist->next; + } + + // Free the data associated with this device + SDL_free(haptic->name); + SDL_free(haptic); +} + +void SDL_QuitHaptics(void) +{ + while (SDL_haptics) { + SDL_CloseHaptic(SDL_haptics); + } + + SDL_SYS_HapticQuit(); +} + +int SDL_GetMaxHapticEffects(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, -1); + + return haptic->neffects; +} + +int SDL_GetMaxHapticEffectsPlaying(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, -1); + + return haptic->nplaying; +} + +Uint32 SDL_GetHapticFeatures(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, 0); + + return haptic->supported; +} + +int SDL_GetNumHapticAxes(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, -1); + + return haptic->naxes; +} + +bool SDL_HapticEffectSupported(SDL_Haptic *haptic, const SDL_HapticEffect *effect) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + if (!effect) { + return false; + } + + if ((haptic->supported & effect->type) != 0) { + return true; + } + return false; +} + +int SDL_CreateHapticEffect(SDL_Haptic *haptic, const SDL_HapticEffect *effect) +{ + int i; + + CHECK_HAPTIC_MAGIC(haptic, -1); + + if (!effect) { + SDL_InvalidParamError("effect"); + return -1; + } + + // Check to see if effect is supported + if (SDL_HapticEffectSupported(haptic, effect) == false) { + SDL_SetError("Haptic: Effect not supported by haptic device."); + return -1; + } + + // See if there's a free slot + for (i = 0; i < haptic->neffects; i++) { + if (haptic->effects[i].hweffect == NULL) { + + // Now let the backend create the real effect + if (!SDL_SYS_HapticNewEffect(haptic, &haptic->effects[i], effect)) { + return -1; // Backend failed to create effect + } + + SDL_memcpy(&haptic->effects[i].effect, effect, + sizeof(SDL_HapticEffect)); + return i; + } + } + + SDL_SetError("Haptic: Device has no free space left."); + return -1; +} + +static bool ValidEffect(SDL_Haptic *haptic, int effect) +{ + if ((effect < 0) || (effect >= haptic->neffects)) { + SDL_SetError("Haptic: Invalid effect identifier."); + return false; + } + return true; +} + +bool SDL_UpdateHapticEffect(SDL_Haptic *haptic, int effect, const SDL_HapticEffect *data) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + if (!ValidEffect(haptic, effect)) { + return false; + } + + if (!data) { + return SDL_InvalidParamError("data"); + } + + // Can't change type dynamically. + if (data->type != haptic->effects[effect].effect.type) { + return SDL_SetError("Haptic: Updating effect type is illegal."); + } + + // Updates the effect + if (!SDL_SYS_HapticUpdateEffect(haptic, &haptic->effects[effect], data)) { + return false; + } + + SDL_memcpy(&haptic->effects[effect].effect, data, + sizeof(SDL_HapticEffect)); + return true; +} + +bool SDL_RunHapticEffect(SDL_Haptic *haptic, int effect, Uint32 iterations) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + if (!ValidEffect(haptic, effect)) { + return false; + } + + // Run the effect + if (!SDL_SYS_HapticRunEffect(haptic, &haptic->effects[effect], iterations)) { + return false; + } + + return true; +} + +bool SDL_StopHapticEffect(SDL_Haptic *haptic, int effect) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + if (!ValidEffect(haptic, effect)) { + return false; + } + + // Stop the effect + if (!SDL_SYS_HapticStopEffect(haptic, &haptic->effects[effect])) { + return false; + } + + return true; +} + +void SDL_DestroyHapticEffect(SDL_Haptic *haptic, int effect) +{ + CHECK_HAPTIC_MAGIC(haptic,); + + if (!ValidEffect(haptic, effect)) { + return; + } + + // Not allocated + if (haptic->effects[effect].hweffect == NULL) { + return; + } + + SDL_SYS_HapticDestroyEffect(haptic, &haptic->effects[effect]); +} + +bool SDL_GetHapticEffectStatus(SDL_Haptic *haptic, int effect) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + if (!ValidEffect(haptic, effect)) { + return false; + } + + if (!(haptic->supported & SDL_HAPTIC_STATUS)) { + return SDL_SetError("Haptic: Device does not support status queries."); + } + + SDL_ClearError(); + + return (SDL_SYS_HapticGetEffectStatus(haptic, &haptic->effects[effect]) > 0); +} + +bool SDL_SetHapticGain(SDL_Haptic *haptic, int gain) +{ + const char *env; + int real_gain, max_gain; + + CHECK_HAPTIC_MAGIC(haptic, false); + + if (!(haptic->supported & SDL_HAPTIC_GAIN)) { + return SDL_SetError("Haptic: Device does not support setting gain."); + } + + if ((gain < 0) || (gain > 100)) { + return SDL_SetError("Haptic: Gain must be between 0 and 100."); + } + + // The user can use an environment variable to override the max gain. + env = SDL_getenv("SDL_HAPTIC_GAIN_MAX"); + if (env) { + max_gain = SDL_atoi(env); + + // Check for sanity. + if (max_gain < 0) { + max_gain = 0; + } else if (max_gain > 100) { + max_gain = 100; + } + + // We'll scale it linearly with SDL_HAPTIC_GAIN_MAX + real_gain = (gain * max_gain) / 100; + } else { + real_gain = gain; + } + + return SDL_SYS_HapticSetGain(haptic, real_gain); +} + +bool SDL_SetHapticAutocenter(SDL_Haptic *haptic, int autocenter) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + if (!(haptic->supported & SDL_HAPTIC_AUTOCENTER)) { + return SDL_SetError("Haptic: Device does not support setting autocenter."); + } + + if ((autocenter < 0) || (autocenter > 100)) { + return SDL_SetError("Haptic: Autocenter must be between 0 and 100."); + } + + return SDL_SYS_HapticSetAutocenter(haptic, autocenter); +} + +bool SDL_PauseHaptic(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + if (!(haptic->supported & SDL_HAPTIC_PAUSE)) { + return SDL_SetError("Haptic: Device does not support setting pausing."); + } + + return SDL_SYS_HapticPause(haptic); +} + +bool SDL_ResumeHaptic(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + if (!(haptic->supported & SDL_HAPTIC_PAUSE)) { + return true; // Not going to be paused, so we pretend it's unpaused. + } + + return SDL_SYS_HapticResume(haptic); +} + +bool SDL_StopHapticEffects(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + return SDL_SYS_HapticStopAll(haptic); +} + +bool SDL_HapticRumbleSupported(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + // Most things can use SINE, but XInput only has LEFTRIGHT. + return (haptic->supported & (SDL_HAPTIC_SINE | SDL_HAPTIC_LEFTRIGHT)) != 0; +} + +bool SDL_InitHapticRumble(SDL_Haptic *haptic) +{ + SDL_HapticEffect *efx = &haptic->rumble_effect; + + CHECK_HAPTIC_MAGIC(haptic, false); + + // Already allocated. + if (haptic->rumble_id >= 0) { + return true; + } + + SDL_zerop(efx); + if (haptic->supported & SDL_HAPTIC_SINE) { + efx->type = SDL_HAPTIC_SINE; + efx->periodic.direction.type = SDL_HAPTIC_CARTESIAN; + efx->periodic.period = 1000; + efx->periodic.magnitude = 0x4000; + efx->periodic.length = 5000; + efx->periodic.attack_length = 0; + efx->periodic.fade_length = 0; + } else if (haptic->supported & SDL_HAPTIC_LEFTRIGHT) { // XInput? + efx->type = SDL_HAPTIC_LEFTRIGHT; + efx->leftright.length = 5000; + efx->leftright.large_magnitude = 0x4000; + efx->leftright.small_magnitude = 0x4000; + } else { + return SDL_SetError("Device doesn't support rumble"); + } + + haptic->rumble_id = SDL_CreateHapticEffect(haptic, &haptic->rumble_effect); + if (haptic->rumble_id >= 0) { + return true; + } + return false; +} + +bool SDL_PlayHapticRumble(SDL_Haptic *haptic, float strength, Uint32 length) +{ + SDL_HapticEffect *efx; + Sint16 magnitude; + + CHECK_HAPTIC_MAGIC(haptic, false); + + if (haptic->rumble_id < 0) { + return SDL_SetError("Haptic: Rumble effect not initialized on haptic device"); + } + + // Clamp strength. + if (strength > 1.0f) { + strength = 1.0f; + } else if (strength < 0.0f) { + strength = 0.0f; + } + magnitude = (Sint16)(32767.0f * strength); + + efx = &haptic->rumble_effect; + if (efx->type == SDL_HAPTIC_SINE) { + efx->periodic.magnitude = magnitude; + efx->periodic.length = length; + } else if (efx->type == SDL_HAPTIC_LEFTRIGHT) { + efx->leftright.small_magnitude = efx->leftright.large_magnitude = magnitude; + efx->leftright.length = length; + } else { + SDL_assert(!"This should have been caught elsewhere"); + } + + if (!SDL_UpdateHapticEffect(haptic, haptic->rumble_id, &haptic->rumble_effect)) { + return false; + } + + return SDL_RunHapticEffect(haptic, haptic->rumble_id, 1); +} + +bool SDL_StopHapticRumble(SDL_Haptic *haptic) +{ + CHECK_HAPTIC_MAGIC(haptic, false); + + if (haptic->rumble_id < 0) { + return SDL_SetError("Haptic: Rumble effect not initialized on haptic device"); + } + + return SDL_StopHapticEffect(haptic, haptic->rumble_id); +} diff --git a/thirdparty/sdl/haptic/SDL_haptic_c.h b/thirdparty/sdl/haptic/SDL_haptic_c.h new file mode 100644 index 00000000000..3f5ce873c64 --- /dev/null +++ b/thirdparty/sdl/haptic/SDL_haptic_c.h @@ -0,0 +1,28 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_haptic_c_h_ +#define SDL_haptic_c_h_ + +extern bool SDL_InitHaptics(void); +extern void SDL_QuitHaptics(void); + +#endif // SDL_haptic_c_h_ diff --git a/thirdparty/sdl/haptic/SDL_syshaptic.h b/thirdparty/sdl/haptic/SDL_syshaptic.h new file mode 100644 index 00000000000..ec60a71e78e --- /dev/null +++ b/thirdparty/sdl/haptic/SDL_syshaptic.h @@ -0,0 +1,194 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_syshaptic_h_ +#define SDL_syshaptic_h_ + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +struct haptic_effect +{ + SDL_HapticEffect effect; // The current event + struct haptic_hweffect *hweffect; // The hardware behind the event +}; + +/* + * The real SDL_Haptic struct. + */ +struct SDL_Haptic +{ + SDL_HapticID instance_id; // Device instance, monotonically increasing from 0 + char *name; // Device name - system dependent + + struct haptic_effect *effects; // Allocated effects + int neffects; // Maximum amount of effects + int nplaying; // Maximum amount of effects to play at the same time + Uint32 supported; // Supported effects and features + int naxes; // Number of axes on the device. + + struct haptic_hwdata *hwdata; // Driver dependent + int ref_count; // Count for multiple opens + + int rumble_id; // ID of rumble effect for simple rumble API. + SDL_HapticEffect rumble_effect; // Rumble effect. + struct SDL_Haptic *next; // pointer to next haptic we have allocated +}; + +/* + * Scans the system for haptic devices. + * + * Returns number of devices on success, -1 on error. + */ +extern bool SDL_SYS_HapticInit(void); + +// Function to return the number of haptic devices plugged in right now +extern int SDL_SYS_NumHaptics(void); + +/* + * Gets the instance ID of the haptic device + */ +extern SDL_HapticID SDL_SYS_HapticInstanceID(int index); + +/* + * Gets the device dependent name of the haptic device + */ +extern const char *SDL_SYS_HapticName(int index); + +/* + * Opens the haptic device for usage. The haptic device should have + * the index value set previously. + */ +extern bool SDL_SYS_HapticOpen(SDL_Haptic *haptic); + +/* + * Returns the index of the haptic core pointer or -1 if none is found. + */ +extern int SDL_SYS_HapticMouse(void); + +/* + * Checks to see if the joystick has haptic capabilities. + */ +extern bool SDL_SYS_JoystickIsHaptic(SDL_Joystick *joystick); + +/* + * Opens the haptic device for usage using the same device as + * the joystick. + */ +extern bool SDL_SYS_HapticOpenFromJoystick(SDL_Haptic *haptic, + SDL_Joystick *joystick); +/* + * Checks to see if haptic device and joystick device are the same. + * + * Returns true if they are the same, false if they aren't. + */ +extern bool SDL_SYS_JoystickSameHaptic(SDL_Haptic *haptic, + SDL_Joystick *joystick); + +/* + * Closes a haptic device after usage. + */ +extern void SDL_SYS_HapticClose(SDL_Haptic *haptic); + +/* + * Performs a cleanup on the haptic subsystem. + */ +extern void SDL_SYS_HapticQuit(void); + +/* + * Creates a new haptic effect on the haptic device using base + * as a template for the effect. + */ +extern bool SDL_SYS_HapticNewEffect(SDL_Haptic *haptic, + struct haptic_effect *effect, + const SDL_HapticEffect *base); + +/* + * Updates the haptic effect on the haptic device using data + * as a template. + */ +extern bool SDL_SYS_HapticUpdateEffect(SDL_Haptic *haptic, + struct haptic_effect *effect, + const SDL_HapticEffect *data); + +/* + * Runs the effect on the haptic device. + */ +extern bool SDL_SYS_HapticRunEffect(SDL_Haptic *haptic, + struct haptic_effect *effect, + Uint32 iterations); + +/* + * Stops the effect on the haptic device. + */ +extern bool SDL_SYS_HapticStopEffect(SDL_Haptic *haptic, + struct haptic_effect *effect); + +/* + * Cleanups up the effect on the haptic device. + */ +extern void SDL_SYS_HapticDestroyEffect(SDL_Haptic *haptic, + struct haptic_effect *effect); + +/* + * Queries the device for the status of effect. + * + * Returns 0 if device is stopped, >0 if device is playing and + * -1 on error. + */ +extern int SDL_SYS_HapticGetEffectStatus(SDL_Haptic *haptic, + struct haptic_effect *effect); + +/* + * Sets the global gain of the haptic device. + */ +extern bool SDL_SYS_HapticSetGain(SDL_Haptic *haptic, int gain); + +/* + * Sets the autocenter feature of the haptic device. + */ +extern bool SDL_SYS_HapticSetAutocenter(SDL_Haptic *haptic, int autocenter); + +/* + * Pauses the haptic device. + */ +extern bool SDL_SYS_HapticPause(SDL_Haptic *haptic); + +/* + * Unpauses the haptic device. + */ +extern bool SDL_SYS_HapticResume(SDL_Haptic *haptic); + +/* + * Stops all the currently playing haptic effects on the device. + */ +extern bool SDL_SYS_HapticStopAll(SDL_Haptic *haptic); + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif + +#endif // SDL_syshaptic_h_ diff --git a/thirdparty/sdl/haptic/darwin/SDL_syshaptic.c b/thirdparty/sdl/haptic/darwin/SDL_syshaptic.c new file mode 100644 index 00000000000..b48a3feb71a --- /dev/null +++ b/thirdparty/sdl/haptic/darwin/SDL_syshaptic.c @@ -0,0 +1,1373 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_HAPTIC_IOKIT + +#include "../SDL_syshaptic.h" +#include "../../joystick/SDL_sysjoystick.h" // For the real SDL_Joystick +#include "../../joystick/darwin/SDL_iokitjoystick_c.h" // For joystick hwdata +#include "SDL_syshaptic_c.h" + +#include +#include +#include +#include +#include + +#ifndef IO_OBJECT_NULL +#define IO_OBJECT_NULL ((io_service_t)0) +#endif + +/* + * List of available haptic devices. + */ +typedef struct SDL_hapticlist_item +{ + SDL_HapticID instance_id; + char name[256]; // Name of the device. + + io_service_t dev; // Node we use to create the device. + SDL_Haptic *haptic; // Haptic currently associated with it. + + // Usage pages for determining if it's a mouse or not. + long usage; + long usagePage; + + struct SDL_hapticlist_item *next; +} SDL_hapticlist_item; + +/* + * Haptic system hardware data. + */ +struct haptic_hwdata +{ + FFDeviceObjectReference device; // Hardware device. + UInt8 axes[3]; +}; + +/* + * Haptic system effect data. + */ +struct haptic_hweffect +{ + FFEffectObjectReference ref; // Reference. + struct FFEFFECT effect; // Hardware effect. +}; + +/* + * Prototypes. + */ +static void SDL_SYS_HapticFreeFFEFFECT(FFEFFECT *effect, int type); +static bool HIDGetDeviceProduct(io_service_t dev, char *name); + +static SDL_hapticlist_item *SDL_hapticlist = NULL; +static SDL_hapticlist_item *SDL_hapticlist_tail = NULL; +static int numhaptics = -1; + +/* + * Like strerror but for force feedback errors. + */ +static const char *FFStrError(unsigned int err) +{ + switch (err) { + case FFERR_DEVICEFULL: + return "device full"; + // This should be valid, but for some reason isn't defined... + /* case FFERR_DEVICENOTREG: + return "device not registered"; */ + case FFERR_DEVICEPAUSED: + return "device paused"; + case FFERR_DEVICERELEASED: + return "device released"; + case FFERR_EFFECTPLAYING: + return "effect playing"; + case FFERR_EFFECTTYPEMISMATCH: + return "effect type mismatch"; + case FFERR_EFFECTTYPENOTSUPPORTED: + return "effect type not supported"; + case FFERR_GENERIC: + return "undetermined error"; + case FFERR_HASEFFECTS: + return "device has effects"; + case FFERR_INCOMPLETEEFFECT: + return "incomplete effect"; + case FFERR_INTERNAL: + return "internal fault"; + case FFERR_INVALIDDOWNLOADID: + return "invalid download id"; + case FFERR_INVALIDPARAM: + return "invalid parameter"; + case FFERR_MOREDATA: + return "more data"; + case FFERR_NOINTERFACE: + return "interface not supported"; + case FFERR_NOTDOWNLOADED: + return "effect is not downloaded"; + case FFERR_NOTINITIALIZED: + return "object has not been initialized"; + case FFERR_OUTOFMEMORY: + return "out of memory"; + case FFERR_UNPLUGGED: + return "device is unplugged"; + case FFERR_UNSUPPORTED: + return "function call unsupported"; + case FFERR_UNSUPPORTEDAXIS: + return "axis unsupported"; + + default: + return "unknown error"; + } +} + +/* + * Initializes the haptic subsystem. + */ +bool SDL_SYS_HapticInit(void) +{ + IOReturn result; + io_iterator_t iter; + CFDictionaryRef match; + io_service_t device; + + if (numhaptics != -1) { + return SDL_SetError("Haptic subsystem already initialized!"); + } + numhaptics = 0; + + // Get HID devices. + match = IOServiceMatching(kIOHIDDeviceKey); + if (!match) { + return SDL_SetError("Haptic: Failed to get IOServiceMatching."); + } + + // Now search I/O Registry for matching devices. + result = IOServiceGetMatchingServices(kIOMainPortDefault, match, &iter); + if (result != kIOReturnSuccess) { + return SDL_SetError("Haptic: Couldn't create a HID object iterator."); + } + // IOServiceGetMatchingServices consumes dictionary. + + if (!IOIteratorIsValid(iter)) { // No iterator. + return true; + } + + while ((device = IOIteratorNext(iter)) != IO_OBJECT_NULL) { + MacHaptic_MaybeAddDevice(device); + // always release as the AddDevice will retain IF it's a forcefeedback device + IOObjectRelease(device); + } + IOObjectRelease(iter); + + return true; +} + +int SDL_SYS_NumHaptics(void) +{ + return numhaptics; +} + +static SDL_hapticlist_item *HapticByDevIndex(int device_index) +{ + SDL_hapticlist_item *item = SDL_hapticlist; + + if ((device_index < 0) || (device_index >= numhaptics)) { + return NULL; + } + + while (device_index > 0) { + SDL_assert(item != NULL); + --device_index; + item = item->next; + } + + return item; +} + +static SDL_hapticlist_item *HapticByInstanceID(SDL_HapticID instance_id) +{ + SDL_hapticlist_item *item; + for (item = SDL_hapticlist; item; item = item->next) { + if (instance_id == item->instance_id) { + return item; + } + } + return NULL; +} + +bool MacHaptic_MaybeAddDevice(io_object_t device) +{ + IOReturn result; + CFMutableDictionaryRef hidProperties; + CFTypeRef refCF; + SDL_hapticlist_item *item; + + if (numhaptics == -1) { + return false; // not initialized. We'll pick these up on enumeration if we init later. + } + + // Check for force feedback. + if (FFIsForceFeedback(device) != FF_OK) { + return false; + } + + // Make sure we don't already have it + for (item = SDL_hapticlist; item; item = item->next) { + if (IOObjectIsEqualTo((io_object_t)item->dev, device)) { + // Already added + return false; + } + } + + item = (SDL_hapticlist_item *)SDL_calloc(1, sizeof(SDL_hapticlist_item)); + if (!item) { + return SDL_SetError("Could not allocate haptic storage"); + } + item->instance_id = SDL_GetNextObjectID(); + + // retain it as we are going to keep it around a while + IOObjectRetain(device); + + // Set basic device data. + HIDGetDeviceProduct(device, item->name); + item->dev = device; + + // Set usage pages. + hidProperties = 0; + refCF = 0; + result = IORegistryEntryCreateCFProperties(device, + &hidProperties, + kCFAllocatorDefault, + kNilOptions); + if ((result == KERN_SUCCESS) && hidProperties) { + refCF = CFDictionaryGetValue(hidProperties, + CFSTR(kIOHIDPrimaryUsagePageKey)); + if (refCF) { + if (!CFNumberGetValue(refCF, kCFNumberLongType, &item->usagePage)) { + SDL_SetError("Haptic: Receiving device's usage page."); + } + refCF = CFDictionaryGetValue(hidProperties, + CFSTR(kIOHIDPrimaryUsageKey)); + if (refCF) { + if (!CFNumberGetValue(refCF, kCFNumberLongType, &item->usage)) { + SDL_SetError("Haptic: Receiving device's usage."); + } + } + } + CFRelease(hidProperties); + } + + if (!SDL_hapticlist_tail) { + SDL_hapticlist = SDL_hapticlist_tail = item; + } else { + SDL_hapticlist_tail->next = item; + SDL_hapticlist_tail = item; + } + + // Device has been added. + ++numhaptics; + + return true; +} + +bool MacHaptic_MaybeRemoveDevice(io_object_t device) +{ + SDL_hapticlist_item *item; + SDL_hapticlist_item *prev = NULL; + + if (numhaptics == -1) { + return false; // not initialized. ignore this. + } + + for (item = SDL_hapticlist; item; item = item->next) { + // found it, remove it. + if (IOObjectIsEqualTo((io_object_t)item->dev, device)) { + bool result = item->haptic ? true : false; + + if (prev) { + prev->next = item->next; + } else { + SDL_assert(SDL_hapticlist == item); + SDL_hapticlist = item->next; + } + if (item == SDL_hapticlist_tail) { + SDL_hapticlist_tail = prev; + } + + // Need to decrement the haptic count + --numhaptics; + // !!! TODO: Send a haptic remove event? + + IOObjectRelease(item->dev); + SDL_free(item); + return result; + } + prev = item; + } + + return false; +} + +SDL_HapticID SDL_SYS_HapticInstanceID(int index) +{ + SDL_hapticlist_item *item; + item = HapticByDevIndex(index); + if (item) { + return item->instance_id; + } + return 0; +} + +/* + * Return the name of a haptic device, does not need to be opened. + */ +const char *SDL_SYS_HapticName(int index) +{ + SDL_hapticlist_item *item; + item = HapticByDevIndex(index); + if (item) { + return item->name; + } + return NULL; +} + +/* + * Gets the device's product name. + */ +static bool HIDGetDeviceProduct(io_service_t dev, char *name) +{ + CFMutableDictionaryRef hidProperties, usbProperties; + io_registry_entry_t parent1, parent2; + kern_return_t ret; + + hidProperties = usbProperties = 0; + + ret = IORegistryEntryCreateCFProperties(dev, &hidProperties, + kCFAllocatorDefault, kNilOptions); + if ((ret != KERN_SUCCESS) || !hidProperties) { + return SDL_SetError("Haptic: Unable to create CFProperties."); + } + + /* macOS currently is not mirroring all USB properties to HID page so need to look at USB device page also + * get dictionary for USB properties: step up two levels and get CF dictionary for USB properties + */ + if ((KERN_SUCCESS == + IORegistryEntryGetParentEntry(dev, kIOServicePlane, &parent1)) && + (KERN_SUCCESS == + IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2)) && + (KERN_SUCCESS == + IORegistryEntryCreateCFProperties(parent2, &usbProperties, + kCFAllocatorDefault, + kNilOptions))) { + if (usbProperties) { + CFTypeRef refCF = 0; + /* get device info + * try hid dictionary first, if fail then go to USB dictionary + */ + + // Get product name + refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey)); + if (!refCF) { + refCF = CFDictionaryGetValue(usbProperties, + CFSTR("USB Product Name")); + } + if (refCF) { + if (!CFStringGetCString(refCF, name, 256, + CFStringGetSystemEncoding())) { + return SDL_SetError("Haptic: CFStringGetCString error retrieving pDevice->product."); + } + } + + CFRelease(usbProperties); + } else { + return SDL_SetError("Haptic: IORegistryEntryCreateCFProperties failed to create usbProperties."); + } + + // Release stuff. + if (kIOReturnSuccess != IOObjectRelease(parent2)) { + SDL_SetError("Haptic: IOObjectRelease error with parent2."); + } + if (kIOReturnSuccess != IOObjectRelease(parent1)) { + SDL_SetError("Haptic: IOObjectRelease error with parent1."); + } + } else { + return SDL_SetError("Haptic: Error getting registry entries."); + } + + return true; +} + +#define FF_TEST(ff, s) \ + if (features.supportedEffects & (ff)) \ + supported |= (s) +/* + * Gets supported features. + */ +static bool GetSupportedFeatures(SDL_Haptic *haptic) +{ + HRESULT ret; + FFDeviceObjectReference device; + FFCAPABILITIES features; + unsigned int supported; + Uint32 val; + + device = haptic->hwdata->device; + + ret = FFDeviceGetForceFeedbackCapabilities(device, &features); + if (ret != FF_OK) { + return SDL_SetError("Haptic: Unable to get device's supported features."); + } + + supported = 0; + + // Get maximum effects. + haptic->neffects = features.storageCapacity; + haptic->nplaying = features.playbackCapacity; + + // Test for effects. + FF_TEST(FFCAP_ET_CONSTANTFORCE, SDL_HAPTIC_CONSTANT); + FF_TEST(FFCAP_ET_RAMPFORCE, SDL_HAPTIC_RAMP); + FF_TEST(FFCAP_ET_SQUARE, SDL_HAPTIC_SQUARE); + FF_TEST(FFCAP_ET_SINE, SDL_HAPTIC_SINE); + FF_TEST(FFCAP_ET_TRIANGLE, SDL_HAPTIC_TRIANGLE); + FF_TEST(FFCAP_ET_SAWTOOTHUP, SDL_HAPTIC_SAWTOOTHUP); + FF_TEST(FFCAP_ET_SAWTOOTHDOWN, SDL_HAPTIC_SAWTOOTHDOWN); + FF_TEST(FFCAP_ET_SPRING, SDL_HAPTIC_SPRING); + FF_TEST(FFCAP_ET_DAMPER, SDL_HAPTIC_DAMPER); + FF_TEST(FFCAP_ET_INERTIA, SDL_HAPTIC_INERTIA); + FF_TEST(FFCAP_ET_FRICTION, SDL_HAPTIC_FRICTION); + FF_TEST(FFCAP_ET_CUSTOMFORCE, SDL_HAPTIC_CUSTOM); + + // Check if supports gain. + ret = FFDeviceGetForceFeedbackProperty(device, FFPROP_FFGAIN, + &val, sizeof(val)); + if (ret == FF_OK) { + supported |= SDL_HAPTIC_GAIN; + } else if (ret != FFERR_UNSUPPORTED) { + return SDL_SetError("Haptic: Unable to get if device supports gain: %s.", + FFStrError(ret)); + } + + // Checks if supports autocenter. + ret = FFDeviceGetForceFeedbackProperty(device, FFPROP_AUTOCENTER, + &val, sizeof(val)); + if (ret == FF_OK) { + supported |= SDL_HAPTIC_AUTOCENTER; + } else if (ret != FFERR_UNSUPPORTED) { + return SDL_SetError("Haptic: Unable to get if device supports autocenter: %s.", + FFStrError(ret)); + } + + // Check for axes, we have an artificial limit on axes + haptic->naxes = ((features.numFfAxes) > 3) ? 3 : features.numFfAxes; + // Actually store the axes we want to use + SDL_memcpy(haptic->hwdata->axes, features.ffAxes, + haptic->naxes * sizeof(Uint8)); + + // Always supported features. + supported |= SDL_HAPTIC_STATUS | SDL_HAPTIC_PAUSE; + + haptic->supported = supported; + return true; +} + +/* + * Opens the haptic device from the file descriptor. + */ +static bool SDL_SYS_HapticOpenFromService(SDL_Haptic *haptic, io_service_t service) +{ + HRESULT ret; + + // Allocate the hwdata + haptic->hwdata = (struct haptic_hwdata *) SDL_calloc(1, sizeof(*haptic->hwdata)); + if (!haptic->hwdata) { + goto creat_err; + } + + // Open the device + ret = FFCreateDevice(service, &haptic->hwdata->device); + if (ret != FF_OK) { + SDL_SetError("Haptic: Unable to create device from service: %s.", FFStrError(ret)); + goto creat_err; + } + + // Get supported features. + if (!GetSupportedFeatures(haptic)) { + goto open_err; + } + + // Reset and then enable actuators. + ret = FFDeviceSendForceFeedbackCommand(haptic->hwdata->device, + FFSFFC_RESET); + if (ret != FF_OK) { + SDL_SetError("Haptic: Unable to reset device: %s.", FFStrError(ret)); + goto open_err; + } + ret = FFDeviceSendForceFeedbackCommand(haptic->hwdata->device, + FFSFFC_SETACTUATORSON); + if (ret != FF_OK) { + SDL_SetError("Haptic: Unable to enable actuators: %s.", + FFStrError(ret)); + goto open_err; + } + + // Allocate effects memory. + haptic->effects = (struct haptic_effect *) + SDL_malloc(sizeof(struct haptic_effect) * haptic->neffects); + if (!haptic->effects) { + goto open_err; + } + // Clear the memory + SDL_memset(haptic->effects, 0, + sizeof(struct haptic_effect) * haptic->neffects); + + return true; + + // Error handling +open_err: + FFReleaseDevice(haptic->hwdata->device); +creat_err: + if (haptic->hwdata) { + SDL_free(haptic->hwdata); + haptic->hwdata = NULL; + } + return false; +} + +/* + * Opens a haptic device for usage. + */ +bool SDL_SYS_HapticOpen(SDL_Haptic *haptic) +{ + SDL_hapticlist_item *item; + item = HapticByInstanceID(haptic->instance_id); + + return SDL_SYS_HapticOpenFromService(haptic, item->dev); +} + +/* + * Opens a haptic device from first mouse it finds for usage. + */ +int SDL_SYS_HapticMouse(void) +{ + int device_index = 0; + SDL_hapticlist_item *item; + + for (item = SDL_hapticlist; item; item = item->next) { + if ((item->usagePage == kHIDPage_GenericDesktop) && + (item->usage == kHIDUsage_GD_Mouse)) { + return device_index; + } + ++device_index; + } + + return 0; +} + +/* + * Checks to see if a joystick has haptic features. + */ +bool SDL_SYS_JoystickIsHaptic(SDL_Joystick *joystick) +{ +#ifdef SDL_JOYSTICK_IOKIT + if (joystick->driver != &SDL_DARWIN_JoystickDriver) { + return false; + } + if (joystick->hwdata->ffservice != 0) { + return true; + } +#endif + return false; +} + +/* + * Checks to see if the haptic device and joystick are in reality the same. + */ +bool SDL_SYS_JoystickSameHaptic(SDL_Haptic *haptic, SDL_Joystick *joystick) +{ +#ifdef SDL_JOYSTICK_IOKIT + if (joystick->driver != &SDL_DARWIN_JoystickDriver) { + return false; + } + if (IOObjectIsEqualTo((io_object_t)((size_t)haptic->hwdata->device), + joystick->hwdata->ffservice)) { + return true; + } +#endif + return false; +} + +/* + * Opens a SDL_Haptic from a SDL_Joystick. + */ +bool SDL_SYS_HapticOpenFromJoystick(SDL_Haptic *haptic, SDL_Joystick *joystick) +{ +#ifdef SDL_JOYSTICK_IOKIT + SDL_hapticlist_item *item; + + if (joystick->driver != &SDL_DARWIN_JoystickDriver) { + return false; + } + for (item = SDL_hapticlist; item; item = item->next) { + if (IOObjectIsEqualTo((io_object_t)item->dev, + joystick->hwdata->ffservice)) { + haptic->instance_id = item->instance_id; + break; + } + } + + if (joystick->name) { + haptic->name = SDL_strdup(joystick->name); + } + + return SDL_SYS_HapticOpenFromService(haptic, joystick->hwdata->ffservice); +#else + return false; +#endif +} + +/* + * Closes the haptic device. + */ +void SDL_SYS_HapticClose(SDL_Haptic *haptic) +{ + if (haptic->hwdata) { + + // Free Effects. + SDL_free(haptic->effects); + haptic->effects = NULL; + haptic->neffects = 0; + + // Clean up + FFReleaseDevice(haptic->hwdata->device); + + // Free + SDL_free(haptic->hwdata); + haptic->hwdata = NULL; + } +} + +/* + * Clean up after system specific haptic stuff + */ +void SDL_SYS_HapticQuit(void) +{ + SDL_hapticlist_item *item; + SDL_hapticlist_item *next = NULL; + + for (item = SDL_hapticlist; item; item = next) { + next = item->next; + /* Opened and not closed haptics are leaked, this is on purpose. + * Close your haptic devices after usage. */ + + // Free the io_service_t + IOObjectRelease(item->dev); + SDL_free(item); + } + + numhaptics = -1; + SDL_hapticlist = NULL; + SDL_hapticlist_tail = NULL; +} + +/* + * Converts an SDL trigger button to an FFEFFECT trigger button. + */ +static DWORD FFGetTriggerButton(Uint16 button) +{ + DWORD dwTriggerButton; + + dwTriggerButton = FFEB_NOTRIGGER; + + if (button != 0) { + dwTriggerButton = FFJOFS_BUTTON(button - 1); + } + + return dwTriggerButton; +} + +/* + * Sets the direction. + */ +static bool SDL_SYS_SetDirection(FFEFFECT *effect, const SDL_HapticDirection *dir, int naxes) +{ + LONG *rglDir; + + // Handle no axes a part. + if (naxes == 0) { + effect->dwFlags |= FFEFF_SPHERICAL; // Set as default. + effect->rglDirection = NULL; + return true; + } + + // Has axes. + rglDir = SDL_malloc(sizeof(LONG) * naxes); + if (!rglDir) { + return false; + } + SDL_memset(rglDir, 0, sizeof(LONG) * naxes); + effect->rglDirection = rglDir; + + switch (dir->type) { + case SDL_HAPTIC_POLAR: + effect->dwFlags |= FFEFF_POLAR; + rglDir[0] = dir->dir[0]; + return true; + case SDL_HAPTIC_CARTESIAN: + effect->dwFlags |= FFEFF_CARTESIAN; + rglDir[0] = dir->dir[0]; + if (naxes > 1) { + rglDir[1] = dir->dir[1]; + } + if (naxes > 2) { + rglDir[2] = dir->dir[2]; + } + return true; + case SDL_HAPTIC_SPHERICAL: + effect->dwFlags |= FFEFF_SPHERICAL; + rglDir[0] = dir->dir[0]; + if (naxes > 1) { + rglDir[1] = dir->dir[1]; + } + if (naxes > 2) { + rglDir[2] = dir->dir[2]; + } + return true; + case SDL_HAPTIC_STEERING_AXIS: + effect->dwFlags |= FFEFF_CARTESIAN; + rglDir[0] = 0; + return true; + + default: + return SDL_SetError("Haptic: Unknown direction type."); + } +} + +// Clamps and converts. +#define CCONVERT(x) (((x) > 0x7FFF) ? 10000 : ((x)*10000) / 0x7FFF) +// Just converts. +#define CONVERT(x) (((x)*10000) / 0x7FFF) +/* + * Creates the FFEFFECT from a SDL_HapticEffect. + */ +static bool SDL_SYS_ToFFEFFECT(SDL_Haptic *haptic, FFEFFECT *dest, const SDL_HapticEffect *src) +{ + int i; + FFCONSTANTFORCE *constant = NULL; + FFPERIODIC *periodic = NULL; + FFCONDITION *condition = NULL; // Actually an array of conditions - one per axis. + FFRAMPFORCE *ramp = NULL; + FFCUSTOMFORCE *custom = NULL; + FFENVELOPE *envelope = NULL; + const SDL_HapticConstant *hap_constant = NULL; + const SDL_HapticPeriodic *hap_periodic = NULL; + const SDL_HapticCondition *hap_condition = NULL; + const SDL_HapticRamp *hap_ramp = NULL; + const SDL_HapticCustom *hap_custom = NULL; + DWORD *axes = NULL; + + // Set global stuff. + SDL_memset(dest, 0, sizeof(FFEFFECT)); + dest->dwSize = sizeof(FFEFFECT); // Set the structure size. + dest->dwSamplePeriod = 0; // Not used by us. + dest->dwGain = 10000; // Gain is set globally, not locally. + dest->dwFlags = FFEFF_OBJECTOFFSETS; // Seems obligatory. + + // Envelope. + envelope = SDL_calloc(1, sizeof(FFENVELOPE)); + if (!envelope) { + return false; + } + dest->lpEnvelope = envelope; + envelope->dwSize = sizeof(FFENVELOPE); // Always should be this. + + // Axes. + if (src->constant.direction.type == SDL_HAPTIC_STEERING_AXIS) { + dest->cAxes = 1; + } else { + dest->cAxes = haptic->naxes; + } + if (dest->cAxes > 0) { + axes = SDL_malloc(sizeof(DWORD) * dest->cAxes); + if (!axes) { + return false; + } + axes[0] = haptic->hwdata->axes[0]; // Always at least one axis. + if (dest->cAxes > 1) { + axes[1] = haptic->hwdata->axes[1]; + } + if (dest->cAxes > 2) { + axes[2] = haptic->hwdata->axes[2]; + } + dest->rgdwAxes = axes; + } + + // The big type handling switch, even bigger then Linux's version. + switch (src->type) { + case SDL_HAPTIC_CONSTANT: + hap_constant = &src->constant; + constant = SDL_calloc(1, sizeof(FFCONSTANTFORCE)); + if (!constant) { + return false; + } + + // Specifics + constant->lMagnitude = CONVERT(hap_constant->level); + dest->cbTypeSpecificParams = sizeof(FFCONSTANTFORCE); + dest->lpvTypeSpecificParams = constant; + + // Generics + dest->dwDuration = hap_constant->length * 1000; // In microseconds. + dest->dwTriggerButton = FFGetTriggerButton(hap_constant->button); + dest->dwTriggerRepeatInterval = hap_constant->interval; + dest->dwStartDelay = hap_constant->delay * 1000; // In microseconds. + + // Direction. + if (!SDL_SYS_SetDirection(dest, &hap_constant->direction, dest->cAxes)) { + return false; + } + + // Envelope + if ((hap_constant->attack_length == 0) && (hap_constant->fade_length == 0)) { + SDL_free(envelope); + dest->lpEnvelope = NULL; + } else { + envelope->dwAttackLevel = CCONVERT(hap_constant->attack_level); + envelope->dwAttackTime = hap_constant->attack_length * 1000; + envelope->dwFadeLevel = CCONVERT(hap_constant->fade_level); + envelope->dwFadeTime = hap_constant->fade_length * 1000; + } + + break; + + case SDL_HAPTIC_SINE: + case SDL_HAPTIC_SQUARE: + case SDL_HAPTIC_TRIANGLE: + case SDL_HAPTIC_SAWTOOTHUP: + case SDL_HAPTIC_SAWTOOTHDOWN: + hap_periodic = &src->periodic; + periodic = SDL_calloc(1, sizeof(FFPERIODIC)); + if (!periodic) { + return false; + } + + // Specifics + periodic->dwMagnitude = CONVERT(SDL_abs(hap_periodic->magnitude)); + periodic->lOffset = CONVERT(hap_periodic->offset); + periodic->dwPhase = + (hap_periodic->phase + (hap_periodic->magnitude < 0 ? 18000 : 0)) % 36000; + periodic->dwPeriod = hap_periodic->period * 1000; + dest->cbTypeSpecificParams = sizeof(FFPERIODIC); + dest->lpvTypeSpecificParams = periodic; + + // Generics + dest->dwDuration = hap_periodic->length * 1000; // In microseconds. + dest->dwTriggerButton = FFGetTriggerButton(hap_periodic->button); + dest->dwTriggerRepeatInterval = hap_periodic->interval; + dest->dwStartDelay = hap_periodic->delay * 1000; // In microseconds. + + // Direction. + if (!SDL_SYS_SetDirection(dest, &hap_periodic->direction, dest->cAxes)) { + return false; + } + + // Envelope + if ((hap_periodic->attack_length == 0) && (hap_periodic->fade_length == 0)) { + SDL_free(envelope); + dest->lpEnvelope = NULL; + } else { + envelope->dwAttackLevel = CCONVERT(hap_periodic->attack_level); + envelope->dwAttackTime = hap_periodic->attack_length * 1000; + envelope->dwFadeLevel = CCONVERT(hap_periodic->fade_level); + envelope->dwFadeTime = hap_periodic->fade_length * 1000; + } + + break; + + case SDL_HAPTIC_SPRING: + case SDL_HAPTIC_DAMPER: + case SDL_HAPTIC_INERTIA: + case SDL_HAPTIC_FRICTION: + hap_condition = &src->condition; + if (dest->cAxes > 0) { + condition = SDL_calloc(dest->cAxes, sizeof(FFCONDITION)); + if (!condition) { + return false; + } + + // Specifics + for (i = 0; i < dest->cAxes; i++) { + condition[i].lOffset = CONVERT(hap_condition->center[i]); + condition[i].lPositiveCoefficient = + CONVERT(hap_condition->right_coeff[i]); + condition[i].lNegativeCoefficient = + CONVERT(hap_condition->left_coeff[i]); + condition[i].dwPositiveSaturation = + CCONVERT(hap_condition->right_sat[i] / 2); + condition[i].dwNegativeSaturation = + CCONVERT(hap_condition->left_sat[i] / 2); + condition[i].lDeadBand = CCONVERT(hap_condition->deadband[i] / 2); + } + } + + dest->cbTypeSpecificParams = sizeof(FFCONDITION) * dest->cAxes; + dest->lpvTypeSpecificParams = condition; + + // Generics + dest->dwDuration = hap_condition->length * 1000; // In microseconds. + dest->dwTriggerButton = FFGetTriggerButton(hap_condition->button); + dest->dwTriggerRepeatInterval = hap_condition->interval; + dest->dwStartDelay = hap_condition->delay * 1000; // In microseconds. + + // Direction. + if (!SDL_SYS_SetDirection(dest, &hap_condition->direction, dest->cAxes)) { + return false; + } + + // Envelope - Not actually supported by most CONDITION implementations. + SDL_free(dest->lpEnvelope); + dest->lpEnvelope = NULL; + + break; + + case SDL_HAPTIC_RAMP: + hap_ramp = &src->ramp; + ramp = SDL_calloc(1, sizeof(FFRAMPFORCE)); + if (!ramp) { + return false; + } + + // Specifics + ramp->lStart = CONVERT(hap_ramp->start); + ramp->lEnd = CONVERT(hap_ramp->end); + dest->cbTypeSpecificParams = sizeof(FFRAMPFORCE); + dest->lpvTypeSpecificParams = ramp; + + // Generics + dest->dwDuration = hap_ramp->length * 1000; // In microseconds. + dest->dwTriggerButton = FFGetTriggerButton(hap_ramp->button); + dest->dwTriggerRepeatInterval = hap_ramp->interval; + dest->dwStartDelay = hap_ramp->delay * 1000; // In microseconds. + + // Direction. + if (!SDL_SYS_SetDirection(dest, &hap_ramp->direction, dest->cAxes)) { + return false; + } + + // Envelope + if ((hap_ramp->attack_length == 0) && (hap_ramp->fade_length == 0)) { + SDL_free(envelope); + dest->lpEnvelope = NULL; + } else { + envelope->dwAttackLevel = CCONVERT(hap_ramp->attack_level); + envelope->dwAttackTime = hap_ramp->attack_length * 1000; + envelope->dwFadeLevel = CCONVERT(hap_ramp->fade_level); + envelope->dwFadeTime = hap_ramp->fade_length * 1000; + } + + break; + + case SDL_HAPTIC_CUSTOM: + hap_custom = &src->custom; + custom = SDL_calloc(1, sizeof(FFCUSTOMFORCE)); + if (!custom) { + return false; + } + + // Specifics + custom->cChannels = hap_custom->channels; + custom->dwSamplePeriod = hap_custom->period * 1000; + custom->cSamples = hap_custom->samples; + custom->rglForceData = + SDL_malloc(sizeof(LONG) * custom->cSamples * custom->cChannels); + for (i = 0; i < hap_custom->samples * hap_custom->channels; i++) { // Copy data. + custom->rglForceData[i] = CCONVERT(hap_custom->data[i]); + } + dest->cbTypeSpecificParams = sizeof(FFCUSTOMFORCE); + dest->lpvTypeSpecificParams = custom; + + // Generics + dest->dwDuration = hap_custom->length * 1000; // In microseconds. + dest->dwTriggerButton = FFGetTriggerButton(hap_custom->button); + dest->dwTriggerRepeatInterval = hap_custom->interval; + dest->dwStartDelay = hap_custom->delay * 1000; // In microseconds. + + // Direction. + if (!SDL_SYS_SetDirection(dest, &hap_custom->direction, dest->cAxes)) { + return false; + } + + // Envelope + if ((hap_custom->attack_length == 0) && (hap_custom->fade_length == 0)) { + SDL_free(envelope); + dest->lpEnvelope = NULL; + } else { + envelope->dwAttackLevel = CCONVERT(hap_custom->attack_level); + envelope->dwAttackTime = hap_custom->attack_length * 1000; + envelope->dwFadeLevel = CCONVERT(hap_custom->fade_level); + envelope->dwFadeTime = hap_custom->fade_length * 1000; + } + + break; + + default: + return SDL_SetError("Haptic: Unknown effect type."); + } + + return true; +} + +/* + * Frees an FFEFFECT allocated by SDL_SYS_ToFFEFFECT. + */ +static void SDL_SYS_HapticFreeFFEFFECT(FFEFFECT *effect, int type) +{ + FFCUSTOMFORCE *custom; + + SDL_free(effect->lpEnvelope); + effect->lpEnvelope = NULL; + SDL_free(effect->rgdwAxes); + effect->rgdwAxes = NULL; + if (effect->lpvTypeSpecificParams) { + if (type == SDL_HAPTIC_CUSTOM) { // Must free the custom data. + custom = (FFCUSTOMFORCE *)effect->lpvTypeSpecificParams; + SDL_free(custom->rglForceData); + custom->rglForceData = NULL; + } + SDL_free(effect->lpvTypeSpecificParams); + effect->lpvTypeSpecificParams = NULL; + } + SDL_free(effect->rglDirection); + effect->rglDirection = NULL; +} + +/* + * Gets the effect type from the generic SDL haptic effect wrapper. + */ +CFUUIDRef +SDL_SYS_HapticEffectType(Uint16 type) +{ + switch (type) { + case SDL_HAPTIC_CONSTANT: + return kFFEffectType_ConstantForce_ID; + + case SDL_HAPTIC_RAMP: + return kFFEffectType_RampForce_ID; + + case SDL_HAPTIC_SQUARE: + return kFFEffectType_Square_ID; + + case SDL_HAPTIC_SINE: + return kFFEffectType_Sine_ID; + + case SDL_HAPTIC_TRIANGLE: + return kFFEffectType_Triangle_ID; + + case SDL_HAPTIC_SAWTOOTHUP: + return kFFEffectType_SawtoothUp_ID; + + case SDL_HAPTIC_SAWTOOTHDOWN: + return kFFEffectType_SawtoothDown_ID; + + case SDL_HAPTIC_SPRING: + return kFFEffectType_Spring_ID; + + case SDL_HAPTIC_DAMPER: + return kFFEffectType_Damper_ID; + + case SDL_HAPTIC_INERTIA: + return kFFEffectType_Inertia_ID; + + case SDL_HAPTIC_FRICTION: + return kFFEffectType_Friction_ID; + + case SDL_HAPTIC_CUSTOM: + return kFFEffectType_CustomForce_ID; + + default: + SDL_SetError("Haptic: Unknown effect type."); + return NULL; + } +} + +/* + * Creates a new haptic effect. + */ +bool SDL_SYS_HapticNewEffect(SDL_Haptic *haptic, struct haptic_effect *effect, + const SDL_HapticEffect *base) +{ + HRESULT ret; + CFUUIDRef type; + + // Alloc the effect. + effect->hweffect = (struct haptic_hweffect *) + SDL_calloc(1, sizeof(struct haptic_hweffect)); + if (!effect->hweffect) { + goto err_hweffect; + } + + // Get the type. + type = SDL_SYS_HapticEffectType(base->type); + if (!type) { + goto err_hweffect; + } + + // Get the effect. + if (!SDL_SYS_ToFFEFFECT(haptic, &effect->hweffect->effect, base)) { + goto err_effectdone; + } + + // Create the actual effect. + ret = FFDeviceCreateEffect(haptic->hwdata->device, type, + &effect->hweffect->effect, + &effect->hweffect->ref); + if (ret != FF_OK) { + SDL_SetError("Haptic: Unable to create effect: %s.", FFStrError(ret)); + goto err_effectdone; + } + + return true; + +err_effectdone: + SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, base->type); +err_hweffect: + SDL_free(effect->hweffect); + effect->hweffect = NULL; + return false; +} + +/* + * Updates an effect. + */ +bool SDL_SYS_HapticUpdateEffect(SDL_Haptic *haptic, + struct haptic_effect *effect, + const SDL_HapticEffect *data) +{ + HRESULT ret; + FFEffectParameterFlag flags; + FFEFFECT temp; + + // Get the effect. + SDL_memset(&temp, 0, sizeof(FFEFFECT)); + if (!SDL_SYS_ToFFEFFECT(haptic, &temp, data)) { + goto err_update; + } + + /* Set the flags. Might be worthwhile to diff temp with loaded effect and + * only change those parameters. */ + flags = FFEP_DIRECTION | + FFEP_DURATION | + FFEP_ENVELOPE | + FFEP_STARTDELAY | + FFEP_TRIGGERBUTTON | + FFEP_TRIGGERREPEATINTERVAL | FFEP_TYPESPECIFICPARAMS; + + // Create the actual effect. + ret = FFEffectSetParameters(effect->hweffect->ref, &temp, flags); + if (ret != FF_OK) { + SDL_SetError("Haptic: Unable to update effect: %s.", FFStrError(ret)); + goto err_update; + } + + // Copy it over. + SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, data->type); + SDL_memcpy(&effect->hweffect->effect, &temp, sizeof(FFEFFECT)); + + return true; + +err_update: + SDL_SYS_HapticFreeFFEFFECT(&temp, data->type); + return false; +} + +/* + * Runs an effect. + */ +bool SDL_SYS_HapticRunEffect(SDL_Haptic *haptic, struct haptic_effect *effect, + Uint32 iterations) +{ + HRESULT ret; + Uint32 iter; + + // Check if it's infinite. + if (iterations == SDL_HAPTIC_INFINITY) { + iter = FF_INFINITE; + } else { + iter = iterations; + } + + // Run the effect. + ret = FFEffectStart(effect->hweffect->ref, iter, 0); + if (ret != FF_OK) { + return SDL_SetError("Haptic: Unable to run the effect: %s.", + FFStrError(ret)); + } + + return true; +} + +/* + * Stops an effect. + */ +bool SDL_SYS_HapticStopEffect(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + HRESULT ret; + + ret = FFEffectStop(effect->hweffect->ref); + if (ret != FF_OK) { + return SDL_SetError("Haptic: Unable to stop the effect: %s.", + FFStrError(ret)); + } + + return true; +} + +/* + * Frees the effect. + */ +void SDL_SYS_HapticDestroyEffect(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + HRESULT ret; + + ret = FFDeviceReleaseEffect(haptic->hwdata->device, effect->hweffect->ref); + if (ret != FF_OK) { + SDL_SetError("Haptic: Error removing the effect from the device: %s.", + FFStrError(ret)); + } + SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, + effect->effect.type); + SDL_free(effect->hweffect); + effect->hweffect = NULL; +} + +/* + * Gets the status of a haptic effect. + */ +int SDL_SYS_HapticGetEffectStatus(SDL_Haptic *haptic, + struct haptic_effect *effect) +{ + HRESULT ret; + FFEffectStatusFlag status; + + ret = FFEffectGetEffectStatus(effect->hweffect->ref, &status); + if (ret != FF_OK) { + SDL_SetError("Haptic: Unable to get effect status: %s.", FFStrError(ret)); + return -1; + } + + if (status == 0) { + return 0; + } + return 1; // Assume it's playing or emulated. +} + +/* + * Sets the gain. + */ +bool SDL_SYS_HapticSetGain(SDL_Haptic *haptic, int gain) +{ + HRESULT ret; + Uint32 val; + + val = gain * 100; // macOS uses 0 to 10,000 + ret = FFDeviceSetForceFeedbackProperty(haptic->hwdata->device, + FFPROP_FFGAIN, &val); + if (ret != FF_OK) { + return SDL_SetError("Haptic: Error setting gain: %s.", FFStrError(ret)); + } + + return true; +} + +/* + * Sets the autocentering. + */ +bool SDL_SYS_HapticSetAutocenter(SDL_Haptic *haptic, int autocenter) +{ + HRESULT ret; + Uint32 val; + + // macOS only has 0 (off) and 1 (on) + if (autocenter == 0) { + val = 0; + } else { + val = 1; + } + + ret = FFDeviceSetForceFeedbackProperty(haptic->hwdata->device, + FFPROP_AUTOCENTER, &val); + if (ret != FF_OK) { + return SDL_SetError("Haptic: Error setting autocenter: %s.", + FFStrError(ret)); + } + + return true; +} + +/* + * Pauses the device. + */ +bool SDL_SYS_HapticPause(SDL_Haptic *haptic) +{ + HRESULT ret; + + ret = FFDeviceSendForceFeedbackCommand(haptic->hwdata->device, + FFSFFC_PAUSE); + if (ret != FF_OK) { + return SDL_SetError("Haptic: Error pausing device: %s.", FFStrError(ret)); + } + + return true; +} + +/* + * Unpauses the device. + */ +bool SDL_SYS_HapticResume(SDL_Haptic *haptic) +{ + HRESULT ret; + + ret = FFDeviceSendForceFeedbackCommand(haptic->hwdata->device, + FFSFFC_CONTINUE); + if (ret != FF_OK) { + return SDL_SetError("Haptic: Error resuming device: %s.", FFStrError(ret)); + } + + return true; +} + +/* + * Stops all currently playing effects. + */ +bool SDL_SYS_HapticStopAll(SDL_Haptic *haptic) +{ + HRESULT ret; + + ret = FFDeviceSendForceFeedbackCommand(haptic->hwdata->device, + FFSFFC_STOPALL); + if (ret != FF_OK) { + return SDL_SetError("Haptic: Error stopping device: %s.", FFStrError(ret)); + } + + return true; +} + +#endif // SDL_HAPTIC_IOKIT diff --git a/thirdparty/sdl/haptic/darwin/SDL_syshaptic_c.h b/thirdparty/sdl/haptic/darwin/SDL_syshaptic_c.h new file mode 100644 index 00000000000..03c67ec7e2c --- /dev/null +++ b/thirdparty/sdl/haptic/darwin/SDL_syshaptic_c.h @@ -0,0 +1,29 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +// Things named "Master" were renamed to "Main" in macOS 12.0's SDK. +#include +#if MAC_OS_X_VERSION_MIN_REQUIRED < 120000 +#define kIOMainPortDefault kIOMasterPortDefault +#endif + +extern bool MacHaptic_MaybeAddDevice(io_object_t device); +extern bool MacHaptic_MaybeRemoveDevice(io_object_t device); diff --git a/thirdparty/sdl/haptic/linux/SDL_syshaptic.c b/thirdparty/sdl/haptic/linux/SDL_syshaptic.c new file mode 100644 index 00000000000..842f577cfa8 --- /dev/null +++ b/thirdparty/sdl/haptic/linux/SDL_syshaptic.c @@ -0,0 +1,1134 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_HAPTIC_LINUX + +#include "../SDL_syshaptic.h" +#include "../../joystick/SDL_sysjoystick.h" // For the real SDL_Joystick +#include "../../joystick/linux/SDL_sysjoystick_c.h" // For joystick hwdata +#include "../../core/linux/SDL_evdev_capabilities.h" +#include "../../core/linux/SDL_udev.h" + +#include // close +#include // Force feedback linux stuff. +#include // O_RDWR +#include // INT_MAX +#include // errno +#include // strerror +#include // stat + +#define MAX_HAPTICS 32 // It's doubtful someone has more then 32 evdev + +static bool MaybeAddDevice(const char *path); +#ifdef SDL_USE_LIBUDEV +static bool MaybeRemoveDevice(const char *path); +static void haptic_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath); +#endif // SDL_USE_LIBUDEV + +/* + * List of available haptic devices. + */ +typedef struct SDL_hapticlist_item +{ + SDL_HapticID instance_id; + char *fname; // Dev path name (like /dev/input/event1) + SDL_Haptic *haptic; // Associated haptic. + dev_t dev_num; + struct SDL_hapticlist_item *next; +} SDL_hapticlist_item; + +/* + * Haptic system hardware data. + */ +struct haptic_hwdata +{ + int fd; // File descriptor of the device. + char *fname; // Points to the name in SDL_hapticlist. +}; + +/* + * Haptic system effect data. + */ +struct haptic_hweffect +{ + struct ff_effect effect; // The linux kernel effect structure. +}; + +static SDL_hapticlist_item *SDL_hapticlist = NULL; +static SDL_hapticlist_item *SDL_hapticlist_tail = NULL; +static int numhaptics = 0; + +#define EV_TEST(ev, f) \ + if (test_bit((ev), features)) { \ + ret |= (f); \ + } +/* + * Test whether a device has haptic properties. + * Returns available properties or 0 if there are none. + */ +static Uint32 EV_IsHaptic(int fd) +{ + unsigned long features[1 + FF_MAX / sizeof(unsigned long)]; + Uint32 ret = 0; + + // Ask device for what it has. + if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(features)), features) < 0) { + SDL_SetError("Haptic: Unable to get device's features: %s", strerror(errno)); + return 0; + } + + // Convert supported features to SDL_HAPTIC platform-neutral features. + EV_TEST(FF_CONSTANT, SDL_HAPTIC_CONSTANT); + EV_TEST(FF_SINE, SDL_HAPTIC_SINE); + EV_TEST(FF_SQUARE, SDL_HAPTIC_SQUARE); + EV_TEST(FF_TRIANGLE, SDL_HAPTIC_TRIANGLE); + EV_TEST(FF_SAW_UP, SDL_HAPTIC_SAWTOOTHUP); + EV_TEST(FF_SAW_DOWN, SDL_HAPTIC_SAWTOOTHDOWN); + EV_TEST(FF_RAMP, SDL_HAPTIC_RAMP); + EV_TEST(FF_SPRING, SDL_HAPTIC_SPRING); + EV_TEST(FF_FRICTION, SDL_HAPTIC_FRICTION); + EV_TEST(FF_DAMPER, SDL_HAPTIC_DAMPER); + EV_TEST(FF_INERTIA, SDL_HAPTIC_INERTIA); + EV_TEST(FF_CUSTOM, SDL_HAPTIC_CUSTOM); + EV_TEST(FF_GAIN, SDL_HAPTIC_GAIN); + EV_TEST(FF_AUTOCENTER, SDL_HAPTIC_AUTOCENTER); + EV_TEST(FF_RUMBLE, SDL_HAPTIC_LEFTRIGHT); + + // Return what it supports. + return ret; +} + +/* + * Tests whether a device is a mouse or not. + */ +static bool EV_IsMouse(int fd) +{ + unsigned long argp[40]; + + // Ask for supported features. + if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(argp)), argp) < 0) { + return false; + } + + // Currently we only test for BTN_MOUSE which can give fake positives. + if (test_bit(BTN_MOUSE, argp) != 0) { + return true; + } + + return true; +} + +/* + * Initializes the haptic subsystem by finding available devices. + */ +bool SDL_SYS_HapticInit(void) +{ + const char joydev_pattern[] = "/dev/input/event%d"; + char path[PATH_MAX]; + int i, j; + + /* + * Limit amount of checks to MAX_HAPTICS since we may or may not have + * permission to some or all devices. + */ + i = 0; + for (j = 0; j < MAX_HAPTICS; ++j) { + (void)SDL_snprintf(path, PATH_MAX, joydev_pattern, i++); + MaybeAddDevice(path); + } + +#ifdef SDL_USE_LIBUDEV + if (!SDL_UDEV_Init()) { + return SDL_SetError("Could not initialize UDEV"); + } + + if (!SDL_UDEV_AddCallback(haptic_udev_callback)) { + SDL_UDEV_Quit(); + return SDL_SetError("Could not setup haptic <-> udev callback"); + } + + // Force a scan to build the initial device list + SDL_UDEV_Scan(); +#endif // SDL_USE_LIBUDEV + + return true; +} + +int SDL_SYS_NumHaptics(void) +{ + return numhaptics; +} + +static SDL_hapticlist_item *HapticByDevIndex(int device_index) +{ + SDL_hapticlist_item *item = SDL_hapticlist; + + if ((device_index < 0) || (device_index >= numhaptics)) { + return NULL; + } + + while (device_index > 0) { + SDL_assert(item != NULL); + --device_index; + item = item->next; + } + + return item; +} + +static SDL_hapticlist_item *HapticByInstanceID(SDL_HapticID instance_id) +{ + SDL_hapticlist_item *item; + for (item = SDL_hapticlist; item; item = item->next) { + if (instance_id == item->instance_id) { + return item; + } + } + return NULL; +} + +#ifdef SDL_USE_LIBUDEV +static void haptic_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath) +{ + if (!devpath || !(udev_class & SDL_UDEV_DEVICE_JOYSTICK)) { + return; + } + + switch (udev_type) { + case SDL_UDEV_DEVICEADDED: + MaybeAddDevice(devpath); + break; + + case SDL_UDEV_DEVICEREMOVED: + MaybeRemoveDevice(devpath); + break; + + default: + break; + } +} +#endif // SDL_USE_LIBUDEV + +static bool MaybeAddDevice(const char *path) +{ + struct stat sb; + int fd; + Uint32 supported; + SDL_hapticlist_item *item; + + if (!path) { + return false; + } + + // try to open + fd = open(path, O_RDWR | O_CLOEXEC, 0); + if (fd < 0) { + return false; + } + + // get file status + if (fstat(fd, &sb) != 0) { + close(fd); + return false; + } + + // check for duplicates + for (item = SDL_hapticlist; item; item = item->next) { + if (item->dev_num == sb.st_rdev) { + close(fd); + return false; // duplicate. + } + } + +#ifdef DEBUG_INPUT_EVENTS + printf("Checking %s\n", path); +#endif + + // see if it works + supported = EV_IsHaptic(fd); + close(fd); + if (!supported) { + return false; + } + + item = (SDL_hapticlist_item *)SDL_calloc(1, sizeof(SDL_hapticlist_item)); + if (!item) { + return false; + } + + item->instance_id = SDL_GetNextObjectID(); + item->fname = SDL_strdup(path); + if (!item->fname) { + SDL_free(item); + return false; + } + + item->dev_num = sb.st_rdev; + + // TODO: should we add instance IDs? + if (!SDL_hapticlist_tail) { + SDL_hapticlist = SDL_hapticlist_tail = item; + } else { + SDL_hapticlist_tail->next = item; + SDL_hapticlist_tail = item; + } + + ++numhaptics; + + // !!! TODO: Send a haptic add event? + + return true; +} + +#ifdef SDL_USE_LIBUDEV +static bool MaybeRemoveDevice(const char *path) +{ + SDL_hapticlist_item *item; + SDL_hapticlist_item *prev = NULL; + + if (!path) { + return false; + } + + for (item = SDL_hapticlist; item; item = item->next) { + // found it, remove it. + if (SDL_strcmp(path, item->fname) == 0) { + const bool result = item->haptic ? true : false; + + if (prev) { + prev->next = item->next; + } else { + SDL_assert(SDL_hapticlist == item); + SDL_hapticlist = item->next; + } + if (item == SDL_hapticlist_tail) { + SDL_hapticlist_tail = prev; + } + + // Need to decrement the haptic count + --numhaptics; + // !!! TODO: Send a haptic remove event? + + SDL_free(item->fname); + SDL_free(item); + return result; + } + prev = item; + } + + return false; +} +#endif // SDL_USE_LIBUDEV + +/* + * Return the instance ID of a haptic device, does not need to be opened. + */ +SDL_HapticID SDL_SYS_HapticInstanceID(int index) +{ + SDL_hapticlist_item *item; + + item = HapticByDevIndex(index); + if (item) { + return item->instance_id; + } + return 0; +} + +/* + * Gets the name from a file descriptor. + */ +static const char *SDL_SYS_HapticNameFromFD(int fd) +{ + static char namebuf[128]; + + // We use the evdev name ioctl. + if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) <= 0) { + return NULL; + } + + return namebuf; +} + +/* + * Return the name of a haptic device, does not need to be opened. + */ +const char *SDL_SYS_HapticName(int index) +{ + SDL_hapticlist_item *item; + int fd; + const char *name = NULL; + + item = HapticByDevIndex(index); + if (item) { + // Open the haptic device. + fd = open(item->fname, O_RDONLY | O_CLOEXEC, 0); + + if (fd >= 0) { + + name = SDL_SYS_HapticNameFromFD(fd); + if (!name) { + // No name found, return device character device + name = item->fname; + } + close(fd); + } + } + return name; +} + +/* + * Opens the haptic device from the file descriptor. + */ +static bool SDL_SYS_HapticOpenFromFD(SDL_Haptic *haptic, int fd) +{ + // Allocate the hwdata + haptic->hwdata = (struct haptic_hwdata *) + SDL_calloc(1, sizeof(*haptic->hwdata)); + if (!haptic->hwdata) { + goto open_err; + } + + // Set the data. + haptic->hwdata->fd = fd; + haptic->supported = EV_IsHaptic(fd); + haptic->naxes = 2; // Hardcoded for now, not sure if it's possible to find out. + + // Set the effects + if (ioctl(fd, EVIOCGEFFECTS, &haptic->neffects) < 0) { + SDL_SetError("Haptic: Unable to query device memory: %s", + strerror(errno)); + goto open_err; + } + haptic->nplaying = haptic->neffects; // Linux makes no distinction. + haptic->effects = (struct haptic_effect *) + SDL_malloc(sizeof(struct haptic_effect) * haptic->neffects); + if (!haptic->effects) { + goto open_err; + } + // Clear the memory + SDL_memset(haptic->effects, 0, + sizeof(struct haptic_effect) * haptic->neffects); + + return true; + + // Error handling +open_err: + close(fd); + if (haptic->hwdata) { + SDL_free(haptic->hwdata); + haptic->hwdata = NULL; + } + return false; +} + +/* + * Opens a haptic device for usage. + */ +bool SDL_SYS_HapticOpen(SDL_Haptic *haptic) +{ + int fd; + SDL_hapticlist_item *item; + + item = HapticByInstanceID(haptic->instance_id); + // Open the character device + fd = open(item->fname, O_RDWR | O_CLOEXEC, 0); + if (fd < 0) { + return SDL_SetError("Haptic: Unable to open %s: %s", + item->fname, strerror(errno)); + } + + // Try to create the haptic. + if (!SDL_SYS_HapticOpenFromFD(haptic, fd)) { + // Already closes on error. + return false; + } + + // Set the fname. + haptic->hwdata->fname = SDL_strdup(item->fname); + return true; +} + +/* + * Opens a haptic device from first mouse it finds for usage. + */ +int SDL_SYS_HapticMouse(void) +{ + int fd; + int device_index = 0; + SDL_hapticlist_item *item; + + for (item = SDL_hapticlist; item; item = item->next) { + // Open the device. + fd = open(item->fname, O_RDWR | O_CLOEXEC, 0); + if (fd < 0) { + return SDL_SetError("Haptic: Unable to open %s: %s", + item->fname, strerror(errno)); + } + + // Is it a mouse? + if (EV_IsMouse(fd)) { + close(fd); + return device_index; + } + + close(fd); + + ++device_index; + } + + return -1; +} + +/* + * Checks to see if a joystick has haptic features. + */ +bool SDL_SYS_JoystickIsHaptic(SDL_Joystick *joystick) +{ +#ifdef SDL_JOYSTICK_LINUX + SDL_AssertJoysticksLocked(); + + if (joystick->driver != &SDL_LINUX_JoystickDriver) { + return false; + } + if (EV_IsHaptic(joystick->hwdata->fd)) { + return true; + } +#endif + return false; +} + +/* + * Checks to see if the haptic device and joystick are in reality the same. + */ +bool SDL_SYS_JoystickSameHaptic(SDL_Haptic *haptic, SDL_Joystick *joystick) +{ +#ifdef SDL_JOYSTICK_LINUX + SDL_AssertJoysticksLocked(); + + if (joystick->driver != &SDL_LINUX_JoystickDriver) { + return false; + } + /* We are assuming Linux is using evdev which should trump the old + * joystick methods. */ + if (SDL_strcmp(joystick->hwdata->fname, haptic->hwdata->fname) == 0) { + return true; + } +#endif + return false; +} + +/* + * Opens a SDL_Haptic from a SDL_Joystick. + */ +bool SDL_SYS_HapticOpenFromJoystick(SDL_Haptic *haptic, SDL_Joystick *joystick) +{ +#ifdef SDL_JOYSTICK_LINUX + int fd; + SDL_hapticlist_item *item; + const char *name; + + SDL_AssertJoysticksLocked(); + + if (joystick->driver != &SDL_LINUX_JoystickDriver) { + return false; + } + // Find the joystick in the haptic list. + for (item = SDL_hapticlist; item; item = item->next) { + if (SDL_strcmp(item->fname, joystick->hwdata->fname) == 0) { + haptic->instance_id = item->instance_id; + break; + } + } + + fd = open(joystick->hwdata->fname, O_RDWR | O_CLOEXEC, 0); + if (fd < 0) { + return SDL_SetError("Haptic: Unable to open %s: %s", + joystick->hwdata->fname, strerror(errno)); + } + if (!SDL_SYS_HapticOpenFromFD(haptic, fd)) { + // Already closes on error. + return false; + } + + haptic->hwdata->fname = SDL_strdup(joystick->hwdata->fname); + + name = SDL_SYS_HapticNameFromFD(fd); + if (name) { + haptic->name = SDL_strdup(name); + } + return true; +#else + return false; +#endif +} + +/* + * Closes the haptic device. + */ +void SDL_SYS_HapticClose(SDL_Haptic *haptic) +{ + if (haptic->hwdata) { + + // Free effects. + SDL_free(haptic->effects); + haptic->effects = NULL; + haptic->neffects = 0; + + // Clean up + close(haptic->hwdata->fd); + + // Free + SDL_free(haptic->hwdata->fname); + SDL_free(haptic->hwdata); + haptic->hwdata = NULL; + } + + // Clear the rest. + SDL_memset(haptic, 0, sizeof(SDL_Haptic)); +} + +/* + * Clean up after system specific haptic stuff + */ +void SDL_SYS_HapticQuit(void) +{ + SDL_hapticlist_item *item = NULL; + SDL_hapticlist_item *next = NULL; + + for (item = SDL_hapticlist; item; item = next) { + next = item->next; + /* Opened and not closed haptics are leaked, this is on purpose. + * Close your haptic devices after usage. */ + SDL_free(item->fname); + SDL_free(item); + } + +#ifdef SDL_USE_LIBUDEV + SDL_UDEV_DelCallback(haptic_udev_callback); + SDL_UDEV_Quit(); +#endif // SDL_USE_LIBUDEV + + numhaptics = 0; + SDL_hapticlist = NULL; + SDL_hapticlist_tail = NULL; +} + +/* + * Converts an SDL button to a ff_trigger button. + */ +static Uint16 SDL_SYS_ToButton(Uint16 button) +{ + Uint16 ff_button; + + ff_button = 0; + + /* + * Not sure what the proper syntax is because this actually isn't implemented + * in the current kernel from what I've seen (2.6.26). + */ + if (button != 0) { + ff_button = BTN_GAMEPAD + button - 1; + } + + return ff_button; +} + +/* + * Initializes the ff_effect usable direction from a SDL_HapticDirection. + */ +static bool SDL_SYS_ToDirection(Uint16 *dest, const SDL_HapticDirection *src) +{ + Uint32 tmp; + + switch (src->type) { + case SDL_HAPTIC_POLAR: + tmp = ((src->dir[0] % 36000) * 0x8000) / 18000; // convert to range [0,0xFFFF] + *dest = (Uint16)tmp; + break; + + case SDL_HAPTIC_SPHERICAL: + /* + We convert to polar, because that's the only supported direction on Linux. + The first value of a spherical direction is practically the same as a + Polar direction, except that we have to add 90 degrees. It is the angle + from EAST {1,0} towards SOUTH {0,1}. + --> add 9000 + --> finally convert to [0,0xFFFF] as in case SDL_HAPTIC_POLAR. + */ + tmp = ((src->dir[0]) + 9000) % 36000; // Convert to polars + tmp = (tmp * 0x8000) / 18000; // convert to range [0,0xFFFF] + *dest = (Uint16)tmp; + break; + + case SDL_HAPTIC_CARTESIAN: + if (!src->dir[1]) { + *dest = (src->dir[0] >= 0 ? 0x4000 : 0xC000); + } else if (!src->dir[0]) { + *dest = (src->dir[1] >= 0 ? 0x8000 : 0); + } else { + float f = SDL_atan2f(src->dir[1], src->dir[0]); // Ideally we'd use fixed point math instead of floats... + /* + SDL_atan2 takes the parameters: Y-axis-value and X-axis-value (in that order) + - Y-axis-value is the second coordinate (from center to SOUTH) + - X-axis-value is the first coordinate (from center to EAST) + We add 36000, because SDL_atan2 also returns negative values. Then we practically + have the first spherical value. Therefore we proceed as in case + SDL_HAPTIC_SPHERICAL and add another 9000 to get the polar value. + --> add 45000 in total + --> finally convert to [0,0xFFFF] as in case SDL_HAPTIC_POLAR. + */ + tmp = (((Sint32)(f * 18000.0 / SDL_PI_D)) + 45000) % 36000; + tmp = (tmp * 0x8000) / 18000; // convert to range [0,0xFFFF] + *dest = (Uint16)tmp; + } + break; + case SDL_HAPTIC_STEERING_AXIS: + *dest = 0x4000; + break; + default: + return SDL_SetError("Haptic: Unsupported direction type."); + } + + return true; +} + +#define CLAMP(x) (((x) > 32767) ? 32767 : x) +/* + * Initializes the Linux effect struct from a haptic_effect. + * Values above 32767 (for unsigned) are unspecified so we must clamp. + */ +static bool SDL_SYS_ToFFEffect(struct ff_effect *dest, const SDL_HapticEffect *src) +{ + const SDL_HapticConstant *constant; + const SDL_HapticPeriodic *periodic; + const SDL_HapticCondition *condition; + const SDL_HapticRamp *ramp; + const SDL_HapticLeftRight *leftright; + + // Clear up + SDL_memset(dest, 0, sizeof(struct ff_effect)); + + switch (src->type) { + case SDL_HAPTIC_CONSTANT: + constant = &src->constant; + + // Header + dest->type = FF_CONSTANT; + if (!SDL_SYS_ToDirection(&dest->direction, &constant->direction)) { + return false; + } + + // Replay + dest->replay.length = (constant->length == SDL_HAPTIC_INFINITY) ? 0 : CLAMP(constant->length); + dest->replay.delay = CLAMP(constant->delay); + + // Trigger + dest->trigger.button = SDL_SYS_ToButton(constant->button); + dest->trigger.interval = CLAMP(constant->interval); + + // Constant + dest->u.constant.level = constant->level; + + // Envelope + dest->u.constant.envelope.attack_length = + CLAMP(constant->attack_length); + dest->u.constant.envelope.attack_level = + CLAMP(constant->attack_level); + dest->u.constant.envelope.fade_length = CLAMP(constant->fade_length); + dest->u.constant.envelope.fade_level = CLAMP(constant->fade_level); + + break; + + case SDL_HAPTIC_SINE: + case SDL_HAPTIC_SQUARE: + case SDL_HAPTIC_TRIANGLE: + case SDL_HAPTIC_SAWTOOTHUP: + case SDL_HAPTIC_SAWTOOTHDOWN: + periodic = &src->periodic; + + // Header + dest->type = FF_PERIODIC; + if (!SDL_SYS_ToDirection(&dest->direction, &periodic->direction)) { + return false; + } + + // Replay + dest->replay.length = (periodic->length == SDL_HAPTIC_INFINITY) ? 0 : CLAMP(periodic->length); + dest->replay.delay = CLAMP(periodic->delay); + + // Trigger + dest->trigger.button = SDL_SYS_ToButton(periodic->button); + dest->trigger.interval = CLAMP(periodic->interval); + + // Periodic + if (periodic->type == SDL_HAPTIC_SINE) { + dest->u.periodic.waveform = FF_SINE; + } else if (periodic->type == SDL_HAPTIC_SQUARE) { + dest->u.periodic.waveform = FF_SQUARE; + } else if (periodic->type == SDL_HAPTIC_TRIANGLE) { + dest->u.periodic.waveform = FF_TRIANGLE; + } else if (periodic->type == SDL_HAPTIC_SAWTOOTHUP) { + dest->u.periodic.waveform = FF_SAW_UP; + } else if (periodic->type == SDL_HAPTIC_SAWTOOTHDOWN) { + dest->u.periodic.waveform = FF_SAW_DOWN; + } + dest->u.periodic.period = CLAMP(periodic->period); + dest->u.periodic.magnitude = periodic->magnitude; + dest->u.periodic.offset = periodic->offset; + // Linux phase is defined in interval "[0x0000, 0x10000[", corresponds with "[0deg, 360deg[" phase shift. + dest->u.periodic.phase = ((Uint32)periodic->phase * 0x10000U) / 36000; + + // Envelope + dest->u.periodic.envelope.attack_length = + CLAMP(periodic->attack_length); + dest->u.periodic.envelope.attack_level = + CLAMP(periodic->attack_level); + dest->u.periodic.envelope.fade_length = CLAMP(periodic->fade_length); + dest->u.periodic.envelope.fade_level = CLAMP(periodic->fade_level); + + break; + + case SDL_HAPTIC_SPRING: + case SDL_HAPTIC_DAMPER: + case SDL_HAPTIC_INERTIA: + case SDL_HAPTIC_FRICTION: + condition = &src->condition; + + // Header + if (condition->type == SDL_HAPTIC_SPRING) { + dest->type = FF_SPRING; + } else if (condition->type == SDL_HAPTIC_DAMPER) { + dest->type = FF_DAMPER; + } else if (condition->type == SDL_HAPTIC_INERTIA) { + dest->type = FF_INERTIA; + } else if (condition->type == SDL_HAPTIC_FRICTION) { + dest->type = FF_FRICTION; + } + + if (!SDL_SYS_ToDirection(&dest->direction, &condition->direction)) { + return false; + } + + // Replay + dest->replay.length = (condition->length == SDL_HAPTIC_INFINITY) ? 0 : CLAMP(condition->length); + dest->replay.delay = CLAMP(condition->delay); + + // Trigger + dest->trigger.button = SDL_SYS_ToButton(condition->button); + dest->trigger.interval = CLAMP(condition->interval); + + // Condition + // X axis + dest->u.condition[0].right_saturation = condition->right_sat[0]; + dest->u.condition[0].left_saturation = condition->left_sat[0]; + dest->u.condition[0].right_coeff = condition->right_coeff[0]; + dest->u.condition[0].left_coeff = condition->left_coeff[0]; + dest->u.condition[0].deadband = condition->deadband[0]; + dest->u.condition[0].center = condition->center[0]; + // Y axis + dest->u.condition[1].right_saturation = condition->right_sat[1]; + dest->u.condition[1].left_saturation = condition->left_sat[1]; + dest->u.condition[1].right_coeff = condition->right_coeff[1]; + dest->u.condition[1].left_coeff = condition->left_coeff[1]; + dest->u.condition[1].deadband = condition->deadband[1]; + dest->u.condition[1].center = condition->center[1]; + + /* + * There is no envelope in the linux force feedback api for conditions. + */ + + break; + + case SDL_HAPTIC_RAMP: + ramp = &src->ramp; + + // Header + dest->type = FF_RAMP; + if (!SDL_SYS_ToDirection(&dest->direction, &ramp->direction)) { + return false; + } + + // Replay + dest->replay.length = (ramp->length == SDL_HAPTIC_INFINITY) ? 0 : CLAMP(ramp->length); + dest->replay.delay = CLAMP(ramp->delay); + + // Trigger + dest->trigger.button = SDL_SYS_ToButton(ramp->button); + dest->trigger.interval = CLAMP(ramp->interval); + + // Ramp + dest->u.ramp.start_level = ramp->start; + dest->u.ramp.end_level = ramp->end; + + // Envelope + dest->u.ramp.envelope.attack_length = CLAMP(ramp->attack_length); + dest->u.ramp.envelope.attack_level = CLAMP(ramp->attack_level); + dest->u.ramp.envelope.fade_length = CLAMP(ramp->fade_length); + dest->u.ramp.envelope.fade_level = CLAMP(ramp->fade_level); + + break; + + case SDL_HAPTIC_LEFTRIGHT: + leftright = &src->leftright; + + // Header + dest->type = FF_RUMBLE; + dest->direction = 0x4000; + + // Replay + dest->replay.length = (leftright->length == SDL_HAPTIC_INFINITY) ? 0 : CLAMP(leftright->length); + + // Trigger + dest->trigger.button = 0; + dest->trigger.interval = 0; + + // Rumble (Linux expects 0-65535, so multiply by 2) + dest->u.rumble.strong_magnitude = CLAMP(leftright->large_magnitude) * 2; + dest->u.rumble.weak_magnitude = CLAMP(leftright->small_magnitude) * 2; + + break; + + default: + return SDL_SetError("Haptic: Unknown effect type."); + } + + return true; +} + +/* + * Creates a new haptic effect. + */ +bool SDL_SYS_HapticNewEffect(SDL_Haptic *haptic, struct haptic_effect *effect, + const SDL_HapticEffect *base) +{ + struct ff_effect *linux_effect; + + // Allocate the hardware effect + effect->hweffect = (struct haptic_hweffect *) + SDL_calloc(1, sizeof(struct haptic_hweffect)); + if (!effect->hweffect) { + return false; + } + + // Prepare the ff_effect + linux_effect = &effect->hweffect->effect; + if (!SDL_SYS_ToFFEffect(linux_effect, base)) { + goto new_effect_err; + } + linux_effect->id = -1; // Have the kernel give it an id + + // Upload the effect + if (ioctl(haptic->hwdata->fd, EVIOCSFF, linux_effect) < 0) { + SDL_SetError("Haptic: Error uploading effect to the device: %s", + strerror(errno)); + goto new_effect_err; + } + + return true; + +new_effect_err: + SDL_free(effect->hweffect); + effect->hweffect = NULL; + return false; +} + +/* + * Updates an effect. + * + * Note: Dynamically updating the direction can in some cases force + * the effect to restart and run once. + */ +bool SDL_SYS_HapticUpdateEffect(SDL_Haptic *haptic, + struct haptic_effect *effect, + const SDL_HapticEffect *data) +{ + struct ff_effect linux_effect; + + // Create the new effect + if (!SDL_SYS_ToFFEffect(&linux_effect, data)) { + return false; + } + linux_effect.id = effect->hweffect->effect.id; + + // See if it can be uploaded. + if (ioctl(haptic->hwdata->fd, EVIOCSFF, &linux_effect) < 0) { + return SDL_SetError("Haptic: Error updating the effect: %s", + strerror(errno)); + } + + // Copy the new effect into memory. + SDL_memcpy(&effect->hweffect->effect, &linux_effect, + sizeof(struct ff_effect)); + + return true; +} + +/* + * Runs an effect. + */ +bool SDL_SYS_HapticRunEffect(SDL_Haptic *haptic, struct haptic_effect *effect, + Uint32 iterations) +{ + struct input_event run; + + // Prepare to run the effect + run.type = EV_FF; + run.code = effect->hweffect->effect.id; + // We don't actually have infinity here, so we just do INT_MAX which is pretty damn close. + run.value = (iterations > INT_MAX) ? INT_MAX : iterations; + + if (write(haptic->hwdata->fd, (const void *)&run, sizeof(run)) < 0) { + return SDL_SetError("Haptic: Unable to run the effect: %s", strerror(errno)); + } + + return true; +} + +/* + * Stops an effect. + */ +bool SDL_SYS_HapticStopEffect(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + struct input_event stop; + + stop.type = EV_FF; + stop.code = effect->hweffect->effect.id; + stop.value = 0; + + if (write(haptic->hwdata->fd, (const void *)&stop, sizeof(stop)) < 0) { + return SDL_SetError("Haptic: Unable to stop the effect: %s", + strerror(errno)); + } + + return true; +} + +/* + * Frees the effect. + */ +void SDL_SYS_HapticDestroyEffect(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + if (ioctl(haptic->hwdata->fd, EVIOCRMFF, effect->hweffect->effect.id) < 0) { + SDL_SetError("Haptic: Error removing the effect from the device: %s", + strerror(errno)); + } + SDL_free(effect->hweffect); + effect->hweffect = NULL; +} + +/* + * Gets the status of a haptic effect. + */ +int SDL_SYS_HapticGetEffectStatus(SDL_Haptic *haptic, + struct haptic_effect *effect) +{ +#if 0 // Not supported atm. + struct input_event ie; + + ie.type = EV_FF; + ie.type = EV_FF_STATUS; + ie.code = effect->hweffect->effect.id; + + if (write(haptic->hwdata->fd, &ie, sizeof(ie)) < 0) { + SDL_SetError("Haptic: Error getting device status."); + return -1; + } + + return 1; +#endif + + SDL_Unsupported(); + return -1; +} + +/* + * Sets the gain. + */ +bool SDL_SYS_HapticSetGain(SDL_Haptic *haptic, int gain) +{ + struct input_event ie; + + ie.type = EV_FF; + ie.code = FF_GAIN; + ie.value = (0xFFFFUL * gain) / 100; + + if (write(haptic->hwdata->fd, &ie, sizeof(ie)) < 0) { + return SDL_SetError("Haptic: Error setting gain: %s", strerror(errno)); + } + + return true; +} + +/* + * Sets the autocentering. + */ +bool SDL_SYS_HapticSetAutocenter(SDL_Haptic *haptic, int autocenter) +{ + struct input_event ie; + + ie.type = EV_FF; + ie.code = FF_AUTOCENTER; + ie.value = (0xFFFFUL * autocenter) / 100; + + if (write(haptic->hwdata->fd, &ie, sizeof(ie)) < 0) { + return SDL_SetError("Haptic: Error setting autocenter: %s", strerror(errno)); + } + + return true; +} + +/* + * Pausing is not supported atm by linux. + */ +bool SDL_SYS_HapticPause(SDL_Haptic *haptic) +{ + return SDL_Unsupported(); +} + +/* + * Unpausing is not supported atm by linux. + */ +bool SDL_SYS_HapticResume(SDL_Haptic *haptic) +{ + return SDL_Unsupported(); +} + +/* + * Stops all the currently playing effects. + */ +bool SDL_SYS_HapticStopAll(SDL_Haptic *haptic) +{ + int i, ret; + + // Linux does not support this natively so we have to loop. + for (i = 0; i < haptic->neffects; i++) { + if (haptic->effects[i].hweffect != NULL) { + ret = SDL_SYS_HapticStopEffect(haptic, &haptic->effects[i]); + if (ret < 0) { + return SDL_SetError("Haptic: Error while trying to stop all playing effects."); + } + } + } + return true; +} + +#endif // SDL_HAPTIC_LINUX diff --git a/thirdparty/sdl/haptic/windows/SDL_dinputhaptic.c b/thirdparty/sdl/haptic/windows/SDL_dinputhaptic.c new file mode 100644 index 00000000000..255aac015d8 --- /dev/null +++ b/thirdparty/sdl/haptic/windows/SDL_dinputhaptic.c @@ -0,0 +1,1244 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "../SDL_syshaptic.h" + +#ifdef SDL_HAPTIC_DINPUT + +#include "SDL_windowshaptic_c.h" +#include "SDL_dinputhaptic_c.h" +#include "../../joystick/windows/SDL_windowsjoystick_c.h" + +/* + * External stuff. + */ +#ifdef SDL_VIDEO_DRIVER_WINDOWS +extern HWND SDL_HelperWindow; +#else +static const HWND SDL_HelperWindow = NULL; +#endif + +/* + * Internal stuff. + */ +static bool coinitialized = false; +static LPDIRECTINPUT8 dinput = NULL; + +/* + * Like SDL_SetError but for DX error codes. + */ +static bool DI_SetError(const char *str, HRESULT err) +{ + return SDL_SetError("Haptic error %s", str); +} + +/* + * Callback to find the haptic devices. + */ +static BOOL CALLBACK EnumHapticsCallback(const DIDEVICEINSTANCE *pdidInstance, VOID *pContext) +{ + (void)pContext; + SDL_DINPUT_HapticMaybeAddDevice(pdidInstance); + return DIENUM_CONTINUE; // continue enumerating +} + +bool SDL_DINPUT_HapticInit(void) +{ + HRESULT ret; + HINSTANCE instance; + DWORD devClass; + + if (dinput != NULL) { // Already open. + return SDL_SetError("Haptic: SubSystem already open."); + } + + if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_DIRECTINPUT, true)) { + // In some environments, IDirectInput8_Initialize / _EnumDevices can take a minute even with no controllers. + return true; + } + + ret = WIN_CoInitialize(); + if (FAILED(ret)) { + return DI_SetError("Coinitialize", ret); + } + + coinitialized = true; + + ret = CoCreateInstance(&CLSID_DirectInput8, NULL, CLSCTX_INPROC_SERVER, + &IID_IDirectInput8, (LPVOID *)&dinput); + if (FAILED(ret)) { + SDL_SYS_HapticQuit(); + return DI_SetError("CoCreateInstance", ret); + } + + // Because we used CoCreateInstance, we need to Initialize it, first. + instance = GetModuleHandle(NULL); + if (!instance) { + SDL_SYS_HapticQuit(); + return SDL_SetError("GetModuleHandle() failed with error code %lu.", + GetLastError()); + } + ret = IDirectInput8_Initialize(dinput, instance, DIRECTINPUT_VERSION); + if (FAILED(ret)) { + SDL_SYS_HapticQuit(); + return DI_SetError("Initializing DirectInput device", ret); + } + + // Look for haptic devices. + for (devClass = DI8DEVCLASS_DEVICE; devClass <= DI8DEVCLASS_GAMECTRL; devClass++) { + if (devClass == DI8DEVCLASS_GAMECTRL && SDL_WasInit(SDL_INIT_JOYSTICK)) { + // The joystick subsystem will manage adding DInput joystick haptic devices + continue; + } + + ret = IDirectInput8_EnumDevices(dinput, + devClass, + EnumHapticsCallback, + NULL, + DIEDFL_FORCEFEEDBACK | + DIEDFL_ATTACHEDONLY); + if (FAILED(ret)) { + SDL_SYS_HapticQuit(); + return DI_SetError("Enumerating DirectInput devices", ret); + } + } + + return true; +} + +bool SDL_DINPUT_HapticMaybeAddDevice(const DIDEVICEINSTANCE *pdidInstance) +{ + HRESULT ret; + LPDIRECTINPUTDEVICE8 device; + const DWORD needflags = DIDC_ATTACHED | DIDC_FORCEFEEDBACK; + DIDEVCAPS capabilities; + SDL_hapticlist_item *item = NULL; + + if (!dinput) { + return false; // not initialized. We'll pick these up on enumeration if we init later. + } + + // Make sure we don't already have it + for (item = SDL_hapticlist; item; item = item->next) { + if (SDL_memcmp(&item->instance, pdidInstance, sizeof(*pdidInstance)) == 0) { + return false; // Already added + } + } + + // Open the device + ret = IDirectInput8_CreateDevice(dinput, &pdidInstance->guidInstance, &device, NULL); + if (FAILED(ret)) { + // DI_SetError("Creating DirectInput device",ret); + return false; + } + + // Get capabilities. + SDL_zero(capabilities); + capabilities.dwSize = sizeof(DIDEVCAPS); + ret = IDirectInputDevice8_GetCapabilities(device, &capabilities); + IDirectInputDevice8_Release(device); + if (FAILED(ret)) { + // DI_SetError("Getting device capabilities",ret); + return false; + } + + if ((capabilities.dwFlags & needflags) != needflags) { + return false; // not a device we can use. + } + + item = (SDL_hapticlist_item *)SDL_calloc(1, sizeof(SDL_hapticlist_item)); + if (!item) { + return false; + } + + item->instance_id = SDL_GetNextObjectID(); + item->name = WIN_StringToUTF8(pdidInstance->tszProductName); + if (!item->name) { + SDL_free(item); + return false; + } + + // Copy the instance over, useful for creating devices. + SDL_memcpy(&item->instance, pdidInstance, sizeof(DIDEVICEINSTANCE)); + SDL_memcpy(&item->capabilities, &capabilities, sizeof(capabilities)); + + return SDL_SYS_AddHapticDevice(item); +} + +bool SDL_DINPUT_HapticMaybeRemoveDevice(const DIDEVICEINSTANCE *pdidInstance) +{ + SDL_hapticlist_item *item; + SDL_hapticlist_item *prev = NULL; + + if (!dinput) { + return false; // not initialized, ignore this. + } + + for (item = SDL_hapticlist; item; item = item->next) { + if (SDL_memcmp(&item->instance, pdidInstance, sizeof(*pdidInstance)) == 0) { + // found it, remove it. + return SDL_SYS_RemoveHapticDevice(prev, item); + } + prev = item; + } + return false; +} + +/* + * Callback to get supported axes. + */ +static BOOL CALLBACK DI_DeviceObjectCallback(LPCDIDEVICEOBJECTINSTANCE dev, LPVOID pvRef) +{ + SDL_Haptic *haptic = (SDL_Haptic *)pvRef; + + if ((dev->dwType & DIDFT_AXIS) && (dev->dwFlags & DIDOI_FFACTUATOR)) { + const GUID *guid = &dev->guidType; + DWORD offset = 0; + if (WIN_IsEqualGUID(guid, &GUID_XAxis)) { + offset = DIJOFS_X; + } else if (WIN_IsEqualGUID(guid, &GUID_YAxis)) { + offset = DIJOFS_Y; + } else if (WIN_IsEqualGUID(guid, &GUID_ZAxis)) { + offset = DIJOFS_Z; + } else if (WIN_IsEqualGUID(guid, &GUID_RxAxis)) { + offset = DIJOFS_RX; + } else if (WIN_IsEqualGUID(guid, &GUID_RyAxis)) { + offset = DIJOFS_RY; + } else if (WIN_IsEqualGUID(guid, &GUID_RzAxis)) { + offset = DIJOFS_RZ; + } else { + return DIENUM_CONTINUE; // can't use this, go on. + } + + haptic->hwdata->axes[haptic->naxes] = offset; + haptic->naxes++; + + // Currently using the artificial limit of 3 axes. + if (haptic->naxes >= 3) { + return DIENUM_STOP; + } + } + + return DIENUM_CONTINUE; +} + +/* + * Callback to get all supported effects. + */ +#define EFFECT_TEST(e, s) \ + if (WIN_IsEqualGUID(&pei->guid, &(e))) \ + haptic->supported |= (s) +static BOOL CALLBACK DI_EffectCallback(LPCDIEFFECTINFO pei, LPVOID pv) +{ + // Prepare the haptic device. + SDL_Haptic *haptic = (SDL_Haptic *)pv; + + // Get supported. + EFFECT_TEST(GUID_Spring, SDL_HAPTIC_SPRING); + EFFECT_TEST(GUID_Damper, SDL_HAPTIC_DAMPER); + EFFECT_TEST(GUID_Inertia, SDL_HAPTIC_INERTIA); + EFFECT_TEST(GUID_Friction, SDL_HAPTIC_FRICTION); + EFFECT_TEST(GUID_ConstantForce, SDL_HAPTIC_CONSTANT); + EFFECT_TEST(GUID_CustomForce, SDL_HAPTIC_CUSTOM); + EFFECT_TEST(GUID_Sine, SDL_HAPTIC_SINE); + EFFECT_TEST(GUID_Square, SDL_HAPTIC_SQUARE); + EFFECT_TEST(GUID_Triangle, SDL_HAPTIC_TRIANGLE); + EFFECT_TEST(GUID_SawtoothUp, SDL_HAPTIC_SAWTOOTHUP); + EFFECT_TEST(GUID_SawtoothDown, SDL_HAPTIC_SAWTOOTHDOWN); + EFFECT_TEST(GUID_RampForce, SDL_HAPTIC_RAMP); + + // Check for more. + return DIENUM_CONTINUE; +} + +/* + * Opens the haptic device. + * + * Steps: + * - Set cooperative level. + * - Set data format. + * - Acquire exclusiveness. + * - Reset actuators. + * - Get supported features. + */ +static bool SDL_DINPUT_HapticOpenFromDevice(SDL_Haptic *haptic, LPDIRECTINPUTDEVICE8 device8, bool is_joystick) +{ + HRESULT ret; + DIPROPDWORD dipdw; + + // Allocate the hwdata + haptic->hwdata = (struct haptic_hwdata *)SDL_calloc(1, sizeof(*haptic->hwdata)); + if (!haptic->hwdata) { + return false; + } + + // We'll use the device8 from now on. + haptic->hwdata->device = device8; + haptic->hwdata->is_joystick = is_joystick; + + /* !!! FIXME: opening a haptic device here first will make an attempt to + !!! FIXME: SDL_OpenJoystick() that same device fail later, since we + !!! FIXME: have it open in exclusive mode. But this will allow + !!! FIXME: SDL_OpenJoystick() followed by SDL_OpenHapticFromJoystick() + !!! FIXME: to work, and that's probably the common case. Still, + !!! FIXME: ideally, We need to unify the opening code. */ + + if (!is_joystick) { // if is_joystick, we already set this up elsewhere. + // Grab it exclusively to use force feedback stuff. + ret = IDirectInputDevice8_SetCooperativeLevel(haptic->hwdata->device, + SDL_HelperWindow, + DISCL_EXCLUSIVE | + DISCL_BACKGROUND); + if (FAILED(ret)) { + DI_SetError("Setting cooperative level to exclusive", ret); + goto acquire_err; + } + + // Set data format. + ret = IDirectInputDevice8_SetDataFormat(haptic->hwdata->device, + &SDL_c_dfDIJoystick2); + if (FAILED(ret)) { + DI_SetError("Setting data format", ret); + goto acquire_err; + } + + // Acquire the device. + ret = IDirectInputDevice8_Acquire(haptic->hwdata->device); + if (FAILED(ret)) { + DI_SetError("Acquiring DirectInput device", ret); + goto acquire_err; + } + } + + // Get number of axes. + ret = IDirectInputDevice8_EnumObjects(haptic->hwdata->device, + DI_DeviceObjectCallback, + haptic, DIDFT_AXIS); + if (FAILED(ret)) { + DI_SetError("Getting device axes", ret); + goto acquire_err; + } + + // Reset all actuators - just in case. + ret = IDirectInputDevice8_SendForceFeedbackCommand(haptic->hwdata->device, + DISFFC_RESET); + if (FAILED(ret)) { + DI_SetError("Resetting device", ret); + goto acquire_err; + } + + // Enabling actuators. + ret = IDirectInputDevice8_SendForceFeedbackCommand(haptic->hwdata->device, + DISFFC_SETACTUATORSON); + if (FAILED(ret)) { + DI_SetError("Enabling actuators", ret); + goto acquire_err; + } + + // Get supported effects. + ret = IDirectInputDevice8_EnumEffects(haptic->hwdata->device, + DI_EffectCallback, haptic, + DIEFT_ALL); + if (FAILED(ret)) { + DI_SetError("Enumerating supported effects", ret); + goto acquire_err; + } + if (haptic->supported == 0) { // Error since device supports nothing. + SDL_SetError("Haptic: Internal error on finding supported effects."); + goto acquire_err; + } + + // Check autogain and autocenter. + dipdw.diph.dwSize = sizeof(DIPROPDWORD); + dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); + dipdw.diph.dwObj = 0; + dipdw.diph.dwHow = DIPH_DEVICE; + dipdw.dwData = 10000; + ret = IDirectInputDevice8_SetProperty(haptic->hwdata->device, + DIPROP_FFGAIN, &dipdw.diph); + if (!FAILED(ret)) { // Gain is supported. + haptic->supported |= SDL_HAPTIC_GAIN; + } + dipdw.diph.dwObj = 0; + dipdw.diph.dwHow = DIPH_DEVICE; + dipdw.dwData = DIPROPAUTOCENTER_OFF; + ret = IDirectInputDevice8_SetProperty(haptic->hwdata->device, + DIPROP_AUTOCENTER, &dipdw.diph); + if (!FAILED(ret)) { // Autocenter is supported. + haptic->supported |= SDL_HAPTIC_AUTOCENTER; + } + + // Status is always supported. + haptic->supported |= SDL_HAPTIC_STATUS | SDL_HAPTIC_PAUSE; + + // Check maximum effects. + haptic->neffects = 128; /* This is not actually supported as thus under windows, + there is no way to tell the number of EFFECTS that a + device can hold, so we'll just use a "random" number + instead and put warnings in SDL_haptic.h */ + haptic->nplaying = 128; // Even more impossible to get this then neffects. + + // Prepare effects memory. + haptic->effects = (struct haptic_effect *) + SDL_malloc(sizeof(struct haptic_effect) * haptic->neffects); + if (!haptic->effects) { + goto acquire_err; + } + // Clear the memory + SDL_memset(haptic->effects, 0, + sizeof(struct haptic_effect) * haptic->neffects); + + return true; + + // Error handling +acquire_err: + IDirectInputDevice8_Unacquire(haptic->hwdata->device); + return false; +} + +bool SDL_DINPUT_HapticOpen(SDL_Haptic *haptic, SDL_hapticlist_item *item) +{ + HRESULT ret; + LPDIRECTINPUTDEVICE8 device; + + // Open the device + ret = IDirectInput8_CreateDevice(dinput, &item->instance.guidInstance, + &device, NULL); + if (FAILED(ret)) { + DI_SetError("Creating DirectInput device", ret); + return false; + } + + if (!SDL_DINPUT_HapticOpenFromDevice(haptic, device, false)) { + IDirectInputDevice8_Release(device); + return false; + } + return true; +} + +bool SDL_DINPUT_JoystickSameHaptic(SDL_Haptic *haptic, SDL_Joystick *joystick) +{ + HRESULT ret; + DIDEVICEINSTANCE hap_instance, joy_instance; + + hap_instance.dwSize = sizeof(DIDEVICEINSTANCE); + joy_instance.dwSize = sizeof(DIDEVICEINSTANCE); + + // Get the device instances. + ret = IDirectInputDevice8_GetDeviceInfo(haptic->hwdata->device, + &hap_instance); + if (FAILED(ret)) { + return false; + } + ret = IDirectInputDevice8_GetDeviceInfo(joystick->hwdata->InputDevice, + &joy_instance); + if (FAILED(ret)) { + return false; + } + + return (WIN_IsEqualGUID(&hap_instance.guidInstance, &joy_instance.guidInstance) == TRUE); +} + +bool SDL_DINPUT_HapticOpenFromJoystick(SDL_Haptic *haptic, SDL_Joystick *joystick) +{ + SDL_hapticlist_item *item; + HRESULT ret; + DIDEVICEINSTANCE joy_instance; + + joy_instance.dwSize = sizeof(DIDEVICEINSTANCE); + ret = IDirectInputDevice8_GetDeviceInfo(joystick->hwdata->InputDevice, &joy_instance); + if (FAILED(ret)) { + return false; + } + + // Since it comes from a joystick we have to try to match it with a haptic device on our haptic list. + for (item = SDL_hapticlist; item; item = item->next) { + if (WIN_IsEqualGUID(&item->instance.guidInstance, &joy_instance.guidInstance)) { + haptic->instance_id = item->instance_id; + haptic->name = SDL_strdup(item->name); + return SDL_DINPUT_HapticOpenFromDevice(haptic, joystick->hwdata->InputDevice, true); + } + } + + return SDL_SetError("Couldn't find joystick in haptic device list"); +} + +void SDL_DINPUT_HapticClose(SDL_Haptic *haptic) +{ + IDirectInputDevice8_Unacquire(haptic->hwdata->device); + + // Only release if isn't grabbed by a joystick. + if (haptic->hwdata->is_joystick == 0) { + IDirectInputDevice8_Release(haptic->hwdata->device); + } +} + +void SDL_DINPUT_HapticQuit(void) +{ + if (dinput != NULL) { + IDirectInput8_Release(dinput); + dinput = NULL; + } + + if (coinitialized) { + WIN_CoUninitialize(); + coinitialized = false; + } +} + +/* + * Converts an SDL trigger button to an DIEFFECT trigger button. + */ +static DWORD DIGetTriggerButton(Uint16 button) +{ + DWORD dwTriggerButton; + + dwTriggerButton = DIEB_NOTRIGGER; + + if (button != 0) { + dwTriggerButton = DIJOFS_BUTTON(button - 1); + } + + return dwTriggerButton; +} + +/* + * Sets the direction. + */ +static bool SDL_SYS_SetDirection(DIEFFECT *effect, const SDL_HapticDirection *dir, int naxes) +{ + LONG *rglDir; + + // Handle no axes a part. + if (naxes == 0) { + effect->dwFlags |= DIEFF_SPHERICAL; // Set as default. + effect->rglDirection = NULL; + return true; + } + + // Has axes. + rglDir = (LONG *)SDL_malloc(sizeof(LONG) * naxes); + if (!rglDir) { + return false; + } + SDL_memset(rglDir, 0, sizeof(LONG) * naxes); + effect->rglDirection = rglDir; + + switch (dir->type) { + case SDL_HAPTIC_POLAR: + effect->dwFlags |= DIEFF_POLAR; + rglDir[0] = dir->dir[0]; + return true; + case SDL_HAPTIC_CARTESIAN: + effect->dwFlags |= DIEFF_CARTESIAN; + rglDir[0] = dir->dir[0]; + if (naxes > 1) { + rglDir[1] = dir->dir[1]; + } + if (naxes > 2) { + rglDir[2] = dir->dir[2]; + } + return true; + case SDL_HAPTIC_SPHERICAL: + effect->dwFlags |= DIEFF_SPHERICAL; + rglDir[0] = dir->dir[0]; + if (naxes > 1) { + rglDir[1] = dir->dir[1]; + } + if (naxes > 2) { + rglDir[2] = dir->dir[2]; + } + return true; + case SDL_HAPTIC_STEERING_AXIS: + effect->dwFlags |= DIEFF_CARTESIAN; + rglDir[0] = 0; + return true; + + default: + return SDL_SetError("Haptic: Unknown direction type."); + } +} + +// Clamps and converts. +#define CCONVERT(x) (((x) > 0x7FFF) ? 10000 : ((x)*10000) / 0x7FFF) +// Just converts. +#define CONVERT(x) (((x)*10000) / 0x7FFF) +/* + * Creates the DIEFFECT from a SDL_HapticEffect. + */ +static bool SDL_SYS_ToDIEFFECT(SDL_Haptic *haptic, DIEFFECT *dest, + const SDL_HapticEffect *src) +{ + int i; + DICONSTANTFORCE *constant; + DIPERIODIC *periodic; + DICONDITION *condition; // Actually an array of conditions - one per axis. + DIRAMPFORCE *ramp; + DICUSTOMFORCE *custom; + DIENVELOPE *envelope; + const SDL_HapticConstant *hap_constant; + const SDL_HapticPeriodic *hap_periodic; + const SDL_HapticCondition *hap_condition; + const SDL_HapticRamp *hap_ramp; + const SDL_HapticCustom *hap_custom; + DWORD *axes; + + // Set global stuff. + SDL_memset(dest, 0, sizeof(DIEFFECT)); + dest->dwSize = sizeof(DIEFFECT); // Set the structure size. + dest->dwSamplePeriod = 0; // Not used by us. + dest->dwGain = 10000; // Gain is set globally, not locally. + dest->dwFlags = DIEFF_OBJECTOFFSETS; // Seems obligatory. + + // Envelope. + envelope = (DIENVELOPE *)SDL_calloc(1, sizeof(DIENVELOPE)); + if (!envelope) { + return false; + } + dest->lpEnvelope = envelope; + envelope->dwSize = sizeof(DIENVELOPE); // Always should be this. + + // Axes. + if (src->constant.direction.type == SDL_HAPTIC_STEERING_AXIS) { + dest->cAxes = 1; + } else { + dest->cAxes = haptic->naxes; + } + if (dest->cAxes > 0) { + axes = (DWORD *)SDL_malloc(sizeof(DWORD) * dest->cAxes); + if (!axes) { + return false; + } + axes[0] = haptic->hwdata->axes[0]; // Always at least one axis. + if (dest->cAxes > 1) { + axes[1] = haptic->hwdata->axes[1]; + } + if (dest->cAxes > 2) { + axes[2] = haptic->hwdata->axes[2]; + } + dest->rgdwAxes = axes; + } + + // The big type handling switch, even bigger than Linux's version. + switch (src->type) { + case SDL_HAPTIC_CONSTANT: + hap_constant = &src->constant; + constant = (DICONSTANTFORCE *)SDL_calloc(1, sizeof(DICONSTANTFORCE)); + if (!constant) { + return false; + } + + // Specifics + constant->lMagnitude = CONVERT(hap_constant->level); + dest->cbTypeSpecificParams = sizeof(DICONSTANTFORCE); + dest->lpvTypeSpecificParams = constant; + + // Generics + dest->dwDuration = hap_constant->length * 1000UL; // In microseconds. + dest->dwTriggerButton = DIGetTriggerButton(hap_constant->button); + dest->dwTriggerRepeatInterval = hap_constant->interval; + dest->dwStartDelay = hap_constant->delay * 1000UL; // In microseconds. + + // Direction. + if (!SDL_SYS_SetDirection(dest, &hap_constant->direction, dest->cAxes)) { + return false; + } + + // Envelope + if ((hap_constant->attack_length == 0) && (hap_constant->fade_length == 0)) { + SDL_free(dest->lpEnvelope); + dest->lpEnvelope = NULL; + } else { + envelope->dwAttackLevel = CCONVERT(hap_constant->attack_level); + envelope->dwAttackTime = hap_constant->attack_length * 1000UL; + envelope->dwFadeLevel = CCONVERT(hap_constant->fade_level); + envelope->dwFadeTime = hap_constant->fade_length * 1000UL; + } + + break; + + case SDL_HAPTIC_SINE: + case SDL_HAPTIC_SQUARE: + case SDL_HAPTIC_TRIANGLE: + case SDL_HAPTIC_SAWTOOTHUP: + case SDL_HAPTIC_SAWTOOTHDOWN: + hap_periodic = &src->periodic; + periodic = (DIPERIODIC *)SDL_calloc(1, sizeof(DIPERIODIC)); + if (!periodic) { + return false; + } + + // Specifics + periodic->dwMagnitude = CONVERT(SDL_abs(hap_periodic->magnitude)); + periodic->lOffset = CONVERT(hap_periodic->offset); + periodic->dwPhase = + (hap_periodic->phase + (hap_periodic->magnitude < 0 ? 18000 : 0)) % 36000; + periodic->dwPeriod = hap_periodic->period * 1000; + dest->cbTypeSpecificParams = sizeof(DIPERIODIC); + dest->lpvTypeSpecificParams = periodic; + + // Generics + dest->dwDuration = hap_periodic->length * 1000UL; // In microseconds. + dest->dwTriggerButton = DIGetTriggerButton(hap_periodic->button); + dest->dwTriggerRepeatInterval = hap_periodic->interval; + dest->dwStartDelay = hap_periodic->delay * 1000UL; // In microseconds. + + // Direction. + if (!SDL_SYS_SetDirection(dest, &hap_periodic->direction, dest->cAxes)) { + return false; + } + + // Envelope + if ((hap_periodic->attack_length == 0) && (hap_periodic->fade_length == 0)) { + SDL_free(dest->lpEnvelope); + dest->lpEnvelope = NULL; + } else { + envelope->dwAttackLevel = CCONVERT(hap_periodic->attack_level); + envelope->dwAttackTime = hap_periodic->attack_length * 1000UL; + envelope->dwFadeLevel = CCONVERT(hap_periodic->fade_level); + envelope->dwFadeTime = hap_periodic->fade_length * 1000UL; + } + + break; + + case SDL_HAPTIC_SPRING: + case SDL_HAPTIC_DAMPER: + case SDL_HAPTIC_INERTIA: + case SDL_HAPTIC_FRICTION: + hap_condition = &src->condition; + condition = (DICONDITION *)SDL_calloc(dest->cAxes, sizeof(DICONDITION)); + if (!condition) { + return false; + } + + // Specifics + for (i = 0; i < (int)dest->cAxes; i++) { + condition[i].lOffset = CONVERT(hap_condition->center[i]); + condition[i].lPositiveCoefficient = + CONVERT(hap_condition->right_coeff[i]); + condition[i].lNegativeCoefficient = + CONVERT(hap_condition->left_coeff[i]); + condition[i].dwPositiveSaturation = + CCONVERT(hap_condition->right_sat[i] / 2); + condition[i].dwNegativeSaturation = + CCONVERT(hap_condition->left_sat[i] / 2); + condition[i].lDeadBand = CCONVERT(hap_condition->deadband[i] / 2); + } + dest->cbTypeSpecificParams = sizeof(DICONDITION) * dest->cAxes; + dest->lpvTypeSpecificParams = condition; + + // Generics + dest->dwDuration = hap_condition->length * 1000UL; // In microseconds. + dest->dwTriggerButton = DIGetTriggerButton(hap_condition->button); + dest->dwTriggerRepeatInterval = hap_condition->interval; + dest->dwStartDelay = hap_condition->delay * 1000UL; // In microseconds. + + // Direction. + if (!SDL_SYS_SetDirection(dest, &hap_condition->direction, dest->cAxes)) { + return false; + } + + // Envelope - Not actually supported by most CONDITION implementations. + SDL_free(dest->lpEnvelope); + dest->lpEnvelope = NULL; + + break; + + case SDL_HAPTIC_RAMP: + hap_ramp = &src->ramp; + ramp = (DIRAMPFORCE *)SDL_calloc(1, sizeof(DIRAMPFORCE)); + if (!ramp) { + return false; + } + + // Specifics + ramp->lStart = CONVERT(hap_ramp->start); + ramp->lEnd = CONVERT(hap_ramp->end); + dest->cbTypeSpecificParams = sizeof(DIRAMPFORCE); + dest->lpvTypeSpecificParams = ramp; + + // Generics + dest->dwDuration = hap_ramp->length * 1000UL; // In microseconds. + dest->dwTriggerButton = DIGetTriggerButton(hap_ramp->button); + dest->dwTriggerRepeatInterval = hap_ramp->interval; + dest->dwStartDelay = hap_ramp->delay * 1000UL; // In microseconds. + + // Direction. + if (!SDL_SYS_SetDirection(dest, &hap_ramp->direction, dest->cAxes)) { + return false; + } + + // Envelope + if ((hap_ramp->attack_length == 0) && (hap_ramp->fade_length == 0)) { + SDL_free(dest->lpEnvelope); + dest->lpEnvelope = NULL; + } else { + envelope->dwAttackLevel = CCONVERT(hap_ramp->attack_level); + envelope->dwAttackTime = hap_ramp->attack_length * 1000UL; + envelope->dwFadeLevel = CCONVERT(hap_ramp->fade_level); + envelope->dwFadeTime = hap_ramp->fade_length * 1000UL; + } + + break; + + case SDL_HAPTIC_CUSTOM: + hap_custom = &src->custom; + custom = (DICUSTOMFORCE *)SDL_calloc(1, sizeof(DICUSTOMFORCE)); + if (!custom) { + return false; + } + + // Specifics + custom->cChannels = hap_custom->channels; + custom->dwSamplePeriod = hap_custom->period * 1000UL; + custom->cSamples = hap_custom->samples; + custom->rglForceData = (LPLONG)SDL_malloc(sizeof(LONG) * custom->cSamples * custom->cChannels); + for (i = 0; i < hap_custom->samples * hap_custom->channels; i++) { // Copy data. + custom->rglForceData[i] = CCONVERT(hap_custom->data[i]); + } + dest->cbTypeSpecificParams = sizeof(DICUSTOMFORCE); + dest->lpvTypeSpecificParams = custom; + + // Generics + dest->dwDuration = hap_custom->length * 1000UL; // In microseconds. + dest->dwTriggerButton = DIGetTriggerButton(hap_custom->button); + dest->dwTriggerRepeatInterval = hap_custom->interval; + dest->dwStartDelay = hap_custom->delay * 1000UL; // In microseconds. + + // Direction. + if (!SDL_SYS_SetDirection(dest, &hap_custom->direction, dest->cAxes)) { + return false; + } + + // Envelope + if ((hap_custom->attack_length == 0) && (hap_custom->fade_length == 0)) { + SDL_free(dest->lpEnvelope); + dest->lpEnvelope = NULL; + } else { + envelope->dwAttackLevel = CCONVERT(hap_custom->attack_level); + envelope->dwAttackTime = hap_custom->attack_length * 1000UL; + envelope->dwFadeLevel = CCONVERT(hap_custom->fade_level); + envelope->dwFadeTime = hap_custom->fade_length * 1000UL; + } + + break; + + default: + return SDL_SetError("Haptic: Unknown effect type."); + } + + return true; +} + +/* + * Frees an DIEFFECT allocated by SDL_SYS_ToDIEFFECT. + */ +static void SDL_SYS_HapticFreeDIEFFECT(DIEFFECT *effect, int type) +{ + DICUSTOMFORCE *custom; + + SDL_free(effect->lpEnvelope); + effect->lpEnvelope = NULL; + SDL_free(effect->rgdwAxes); + effect->rgdwAxes = NULL; + if (effect->lpvTypeSpecificParams) { + if (type == SDL_HAPTIC_CUSTOM) { // Must free the custom data. + custom = (DICUSTOMFORCE *)effect->lpvTypeSpecificParams; + SDL_free(custom->rglForceData); + custom->rglForceData = NULL; + } + SDL_free(effect->lpvTypeSpecificParams); + effect->lpvTypeSpecificParams = NULL; + } + SDL_free(effect->rglDirection); + effect->rglDirection = NULL; +} + +/* + * Gets the effect type from the generic SDL haptic effect wrapper. + */ +// NOLINTNEXTLINE(readability-const-return-type): Can't fix Windows' headers +static REFGUID SDL_SYS_HapticEffectType(const SDL_HapticEffect *effect) +{ + switch (effect->type) { + case SDL_HAPTIC_CONSTANT: + return &GUID_ConstantForce; + + case SDL_HAPTIC_RAMP: + return &GUID_RampForce; + + case SDL_HAPTIC_SQUARE: + return &GUID_Square; + + case SDL_HAPTIC_SINE: + return &GUID_Sine; + + case SDL_HAPTIC_TRIANGLE: + return &GUID_Triangle; + + case SDL_HAPTIC_SAWTOOTHUP: + return &GUID_SawtoothUp; + + case SDL_HAPTIC_SAWTOOTHDOWN: + return &GUID_SawtoothDown; + + case SDL_HAPTIC_SPRING: + return &GUID_Spring; + + case SDL_HAPTIC_DAMPER: + return &GUID_Damper; + + case SDL_HAPTIC_INERTIA: + return &GUID_Inertia; + + case SDL_HAPTIC_FRICTION: + return &GUID_Friction; + + case SDL_HAPTIC_CUSTOM: + return &GUID_CustomForce; + + default: + return NULL; + } +} +bool SDL_DINPUT_HapticNewEffect(SDL_Haptic *haptic, struct haptic_effect *effect, const SDL_HapticEffect *base) +{ + HRESULT ret; + REFGUID type = SDL_SYS_HapticEffectType(base); + + if (!type) { + return SDL_SetError("Haptic: Unknown effect type."); + } + + // Get the effect. + if (!SDL_SYS_ToDIEFFECT(haptic, &effect->hweffect->effect, base)) { + goto err_effectdone; + } + + // Create the actual effect. + ret = IDirectInputDevice8_CreateEffect(haptic->hwdata->device, type, + &effect->hweffect->effect, + &effect->hweffect->ref, NULL); + if (FAILED(ret)) { + DI_SetError("Unable to create effect", ret); + goto err_effectdone; + } + + return true; + +err_effectdone: + SDL_SYS_HapticFreeDIEFFECT(&effect->hweffect->effect, base->type); + return false; +} + +bool SDL_DINPUT_HapticUpdateEffect(SDL_Haptic *haptic, struct haptic_effect *effect, const SDL_HapticEffect *data) +{ + HRESULT ret; + DWORD flags; + DIEFFECT temp; + + // Get the effect. + SDL_memset(&temp, 0, sizeof(DIEFFECT)); + if (!SDL_SYS_ToDIEFFECT(haptic, &temp, data)) { + goto err_update; + } + + /* Set the flags. Might be worthwhile to diff temp with loaded effect and + * only change those parameters. */ + flags = DIEP_DIRECTION | + DIEP_DURATION | + DIEP_ENVELOPE | + DIEP_STARTDELAY | + DIEP_TRIGGERBUTTON | + DIEP_TRIGGERREPEATINTERVAL | DIEP_TYPESPECIFICPARAMS; + + // Create the actual effect. + ret = + IDirectInputEffect_SetParameters(effect->hweffect->ref, &temp, flags); + if (ret == DIERR_NOTEXCLUSIVEACQUIRED) { + IDirectInputDevice8_Unacquire(haptic->hwdata->device); + ret = IDirectInputDevice8_SetCooperativeLevel(haptic->hwdata->device, SDL_HelperWindow, DISCL_EXCLUSIVE | DISCL_BACKGROUND); + if (SUCCEEDED(ret)) { + ret = DIERR_NOTACQUIRED; + } + } + if (ret == DIERR_INPUTLOST || ret == DIERR_NOTACQUIRED) { + ret = IDirectInputDevice8_Acquire(haptic->hwdata->device); + if (SUCCEEDED(ret)) { + ret = IDirectInputEffect_SetParameters(effect->hweffect->ref, &temp, flags); + } + } + if (FAILED(ret)) { + DI_SetError("Unable to update effect", ret); + goto err_update; + } + + // Copy it over. + SDL_SYS_HapticFreeDIEFFECT(&effect->hweffect->effect, data->type); + SDL_memcpy(&effect->hweffect->effect, &temp, sizeof(DIEFFECT)); + + return true; + +err_update: + SDL_SYS_HapticFreeDIEFFECT(&temp, data->type); + return false; +} + +bool SDL_DINPUT_HapticRunEffect(SDL_Haptic *haptic, struct haptic_effect *effect, Uint32 iterations) +{ + HRESULT ret; + DWORD iter; + + // Check if it's infinite. + if (iterations == SDL_HAPTIC_INFINITY) { + iter = INFINITE; + } else { + iter = iterations; + } + + // Run the effect. + ret = IDirectInputEffect_Start(effect->hweffect->ref, iter, 0); + if (FAILED(ret)) { + return DI_SetError("Running the effect", ret); + } + return true; +} + +bool SDL_DINPUT_HapticStopEffect(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + HRESULT ret; + + ret = IDirectInputEffect_Stop(effect->hweffect->ref); + if (FAILED(ret)) { + return DI_SetError("Unable to stop effect", ret); + } + return true; +} + +void SDL_DINPUT_HapticDestroyEffect(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + HRESULT ret; + + ret = IDirectInputEffect_Unload(effect->hweffect->ref); + if (FAILED(ret)) { + DI_SetError("Removing effect from the device", ret); + } + SDL_SYS_HapticFreeDIEFFECT(&effect->hweffect->effect, effect->effect.type); +} + +int SDL_DINPUT_HapticGetEffectStatus(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + HRESULT ret; + DWORD status; + + ret = IDirectInputEffect_GetEffectStatus(effect->hweffect->ref, &status); + if (FAILED(ret)) { + DI_SetError("Getting effect status", ret); + return -1; + } + + if (status == 0) { + return 0; + } + return 1; +} + +bool SDL_DINPUT_HapticSetGain(SDL_Haptic *haptic, int gain) +{ + HRESULT ret; + DIPROPDWORD dipdw; + + // Create the weird structure thingy. + dipdw.diph.dwSize = sizeof(DIPROPDWORD); + dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); + dipdw.diph.dwObj = 0; + dipdw.diph.dwHow = DIPH_DEVICE; + dipdw.dwData = (DWORD)gain * 100; // 0 to 10,000 + + // Try to set the autocenter. + ret = IDirectInputDevice8_SetProperty(haptic->hwdata->device, + DIPROP_FFGAIN, &dipdw.diph); + if (FAILED(ret)) { + return DI_SetError("Setting gain", ret); + } + return true; +} + +bool SDL_DINPUT_HapticSetAutocenter(SDL_Haptic *haptic, int autocenter) +{ + HRESULT ret; + DIPROPDWORD dipdw; + + // Create the weird structure thingy. + dipdw.diph.dwSize = sizeof(DIPROPDWORD); + dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); + dipdw.diph.dwObj = 0; + dipdw.diph.dwHow = DIPH_DEVICE; + dipdw.dwData = (autocenter == 0) ? DIPROPAUTOCENTER_OFF : DIPROPAUTOCENTER_ON; + + // Try to set the autocenter. + ret = IDirectInputDevice8_SetProperty(haptic->hwdata->device, + DIPROP_AUTOCENTER, &dipdw.diph); + if (FAILED(ret)) { + return DI_SetError("Setting autocenter", ret); + } + return true; +} + +bool SDL_DINPUT_HapticPause(SDL_Haptic *haptic) +{ + HRESULT ret; + + // Pause the device. + ret = IDirectInputDevice8_SendForceFeedbackCommand(haptic->hwdata->device, + DISFFC_PAUSE); + if (FAILED(ret)) { + return DI_SetError("Pausing the device", ret); + } + return true; +} + +bool SDL_DINPUT_HapticResume(SDL_Haptic *haptic) +{ + HRESULT ret; + + // Unpause the device. + ret = IDirectInputDevice8_SendForceFeedbackCommand(haptic->hwdata->device, + DISFFC_CONTINUE); + if (FAILED(ret)) { + return DI_SetError("Pausing the device", ret); + } + return true; +} + +bool SDL_DINPUT_HapticStopAll(SDL_Haptic *haptic) +{ + HRESULT ret; + + // Try to stop the effects. + ret = IDirectInputDevice8_SendForceFeedbackCommand(haptic->hwdata->device, + DISFFC_STOPALL); + if (FAILED(ret)) { + return DI_SetError("Stopping the device", ret); + } + return true; +} + +#else // !SDL_HAPTIC_DINPUT + +typedef struct DIDEVICEINSTANCE DIDEVICEINSTANCE; +typedef struct SDL_hapticlist_item SDL_hapticlist_item; + +bool SDL_DINPUT_HapticInit(void) +{ + return true; +} + +bool SDL_DINPUT_HapticMaybeAddDevice(const DIDEVICEINSTANCE *pdidInstance) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_HapticMaybeRemoveDevice(const DIDEVICEINSTANCE *pdidInstance) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_HapticOpen(SDL_Haptic *haptic, SDL_hapticlist_item *item) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_JoystickSameHaptic(SDL_Haptic *haptic, SDL_Joystick *joystick) +{ + return false; +} + +bool SDL_DINPUT_HapticOpenFromJoystick(SDL_Haptic *haptic, SDL_Joystick *joystick) +{ + return SDL_Unsupported(); +} + +void SDL_DINPUT_HapticClose(SDL_Haptic *haptic) +{ +} + +void SDL_DINPUT_HapticQuit(void) +{ +} + +bool SDL_DINPUT_HapticNewEffect(SDL_Haptic *haptic, struct haptic_effect *effect, const SDL_HapticEffect *base) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_HapticUpdateEffect(SDL_Haptic *haptic, struct haptic_effect *effect, const SDL_HapticEffect *data) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_HapticRunEffect(SDL_Haptic *haptic, struct haptic_effect *effect, Uint32 iterations) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_HapticStopEffect(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + return SDL_Unsupported(); +} + +void SDL_DINPUT_HapticDestroyEffect(SDL_Haptic *haptic, struct haptic_effect *effect) +{ +} + +int SDL_DINPUT_HapticGetEffectStatus(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + SDL_Unsupported(); + return -1; +} + +bool SDL_DINPUT_HapticSetGain(SDL_Haptic *haptic, int gain) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_HapticSetAutocenter(SDL_Haptic *haptic, int autocenter) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_HapticPause(SDL_Haptic *haptic) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_HapticResume(SDL_Haptic *haptic) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_HapticStopAll(SDL_Haptic *haptic) +{ + return SDL_Unsupported(); +} + +#endif // SDL_HAPTIC_DINPUT diff --git a/thirdparty/sdl/haptic/windows/SDL_dinputhaptic_c.h b/thirdparty/sdl/haptic/windows/SDL_dinputhaptic_c.h new file mode 100644 index 00000000000..d6265c926cb --- /dev/null +++ b/thirdparty/sdl/haptic/windows/SDL_dinputhaptic_c.h @@ -0,0 +1,53 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_windowshaptic_c.h" + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +extern bool SDL_DINPUT_HapticInit(void); +extern bool SDL_DINPUT_HapticMaybeAddDevice(const DIDEVICEINSTANCE *pdidInstance); +extern bool SDL_DINPUT_HapticMaybeRemoveDevice(const DIDEVICEINSTANCE *pdidInstance); +extern bool SDL_DINPUT_HapticOpen(SDL_Haptic *haptic, SDL_hapticlist_item *item); +extern bool SDL_DINPUT_JoystickSameHaptic(SDL_Haptic *haptic, SDL_Joystick *joystick); +extern bool SDL_DINPUT_HapticOpenFromJoystick(SDL_Haptic *haptic, SDL_Joystick *joystick); +extern void SDL_DINPUT_HapticClose(SDL_Haptic *haptic); +extern void SDL_DINPUT_HapticQuit(void); +extern bool SDL_DINPUT_HapticNewEffect(SDL_Haptic *haptic, struct haptic_effect *effect, const SDL_HapticEffect *base); +extern bool SDL_DINPUT_HapticUpdateEffect(SDL_Haptic *haptic, struct haptic_effect *effect, const SDL_HapticEffect *data); +extern bool SDL_DINPUT_HapticRunEffect(SDL_Haptic *haptic, struct haptic_effect *effect, Uint32 iterations); +extern bool SDL_DINPUT_HapticStopEffect(SDL_Haptic *haptic, struct haptic_effect *effect); +extern void SDL_DINPUT_HapticDestroyEffect(SDL_Haptic *haptic, struct haptic_effect *effect); +extern int SDL_DINPUT_HapticGetEffectStatus(SDL_Haptic *haptic, struct haptic_effect *effect); +extern bool SDL_DINPUT_HapticSetGain(SDL_Haptic *haptic, int gain); +extern bool SDL_DINPUT_HapticSetAutocenter(SDL_Haptic *haptic, int autocenter); +extern bool SDL_DINPUT_HapticPause(SDL_Haptic *haptic); +extern bool SDL_DINPUT_HapticResume(SDL_Haptic *haptic); +extern bool SDL_DINPUT_HapticStopAll(SDL_Haptic *haptic); + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif diff --git a/thirdparty/sdl/haptic/windows/SDL_windowshaptic.c b/thirdparty/sdl/haptic/windows/SDL_windowshaptic.c new file mode 100644 index 00000000000..e21ab918da0 --- /dev/null +++ b/thirdparty/sdl/haptic/windows/SDL_windowshaptic.c @@ -0,0 +1,369 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_HAPTIC_DINPUT + +#include "../SDL_syshaptic.h" +#include "../../joystick/SDL_sysjoystick.h" // For the real SDL_Joystick +#include "../../joystick/windows/SDL_windowsjoystick_c.h" // For joystick hwdata +#include "../../joystick/windows/SDL_xinputjoystick_c.h" // For xinput rumble + +#include "SDL_windowshaptic_c.h" +#include "SDL_dinputhaptic_c.h" + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Internal stuff. + */ +SDL_hapticlist_item *SDL_hapticlist = NULL; +static SDL_hapticlist_item *SDL_hapticlist_tail = NULL; +static int numhaptics = 0; + +/* + * Initializes the haptic subsystem. + */ +bool SDL_SYS_HapticInit(void) +{ + JoyStick_DeviceData *device; + + if (!SDL_DINPUT_HapticInit()) { + return false; + } + + /* The joystick subsystem will usually be initialized before haptics, + * so the initial HapticMaybeAddDevice() calls from the joystick + * subsystem will arrive too early to create haptic devices. We will + * invoke those callbacks again here to pick up any joysticks that + * were added prior to haptics initialization. */ + for (device = SYS_Joystick; device; device = device->pNext) { + SDL_DINPUT_HapticMaybeAddDevice(&device->dxdevice); + } + + return true; +} + +bool SDL_SYS_AddHapticDevice(SDL_hapticlist_item *item) +{ + if (!SDL_hapticlist_tail) { + SDL_hapticlist = SDL_hapticlist_tail = item; + } else { + SDL_hapticlist_tail->next = item; + SDL_hapticlist_tail = item; + } + + // Device has been added. + ++numhaptics; + + return true; +} + +bool SDL_SYS_RemoveHapticDevice(SDL_hapticlist_item *prev, SDL_hapticlist_item *item) +{ + const bool result = item->haptic ? true : false; + if (prev) { + prev->next = item->next; + } else { + SDL_assert(SDL_hapticlist == item); + SDL_hapticlist = item->next; + } + if (item == SDL_hapticlist_tail) { + SDL_hapticlist_tail = prev; + } + --numhaptics; + // !!! TODO: Send a haptic remove event? + SDL_free(item); + return result; +} + +int SDL_SYS_NumHaptics(void) +{ + return numhaptics; +} + +static SDL_hapticlist_item *HapticByDevIndex(int device_index) +{ + SDL_hapticlist_item *item = SDL_hapticlist; + + if ((device_index < 0) || (device_index >= numhaptics)) { + return NULL; + } + + while (device_index > 0) { + SDL_assert(item != NULL); + --device_index; + item = item->next; + } + return item; +} + +static SDL_hapticlist_item *HapticByInstanceID(SDL_HapticID instance_id) +{ + SDL_hapticlist_item *item; + for (item = SDL_hapticlist; item; item = item->next) { + if (instance_id == item->instance_id) { + return item; + } + } + return NULL; +} + +SDL_HapticID SDL_SYS_HapticInstanceID(int index) +{ + SDL_hapticlist_item *item = HapticByDevIndex(index); + if (item) { + return item->instance_id; + } + return 0; +} + +/* + * Return the name of a haptic device, does not need to be opened. + */ +const char *SDL_SYS_HapticName(int index) +{ + SDL_hapticlist_item *item = HapticByDevIndex(index); + return item->name; +} + +/* + * Opens a haptic device for usage. + */ +bool SDL_SYS_HapticOpen(SDL_Haptic *haptic) +{ + SDL_hapticlist_item *item = HapticByInstanceID(haptic->instance_id); + return SDL_DINPUT_HapticOpen(haptic, item); +} + +/* + * Opens a haptic device from first mouse it finds for usage. + */ +int SDL_SYS_HapticMouse(void) +{ +#ifdef SDL_HAPTIC_DINPUT + SDL_hapticlist_item *item; + int index = 0; + + // Grab the first mouse haptic device we find. + for (item = SDL_hapticlist; item; item = item->next) { + if (item->capabilities.dwDevType == DI8DEVCLASS_POINTER) { + return index; + } + ++index; + } +#endif // SDL_HAPTIC_DINPUT + return -1; +} + +/* + * Checks to see if a joystick has haptic features. + */ +bool SDL_SYS_JoystickIsHaptic(SDL_Joystick *joystick) +{ + if (joystick->driver != &SDL_WINDOWS_JoystickDriver) { + return false; + } + if (joystick->hwdata->Capabilities.dwFlags & DIDC_FORCEFEEDBACK) { + return true; + } + return false; +} + +/* + * Checks to see if the haptic device and joystick are in reality the same. + */ +bool SDL_SYS_JoystickSameHaptic(SDL_Haptic *haptic, SDL_Joystick *joystick) +{ + if (joystick->driver != &SDL_WINDOWS_JoystickDriver) { + return false; + } + return SDL_DINPUT_JoystickSameHaptic(haptic, joystick); +} + +/* + * Opens a SDL_Haptic from a SDL_Joystick. + */ +bool SDL_SYS_HapticOpenFromJoystick(SDL_Haptic *haptic, SDL_Joystick *joystick) +{ + SDL_assert(joystick->driver == &SDL_WINDOWS_JoystickDriver); + + return SDL_DINPUT_HapticOpenFromJoystick(haptic, joystick); +} + +/* + * Closes the haptic device. + */ +void SDL_SYS_HapticClose(SDL_Haptic *haptic) +{ + if (haptic->hwdata) { + + // Free effects. + SDL_free(haptic->effects); + haptic->effects = NULL; + haptic->neffects = 0; + + // Clean up + SDL_DINPUT_HapticClose(haptic); + + // Free + SDL_free(haptic->hwdata); + haptic->hwdata = NULL; + } +} + +/* + * Clean up after system specific haptic stuff + */ +void SDL_SYS_HapticQuit(void) +{ + SDL_hapticlist_item *item; + SDL_hapticlist_item *next = NULL; + + for (item = SDL_hapticlist; item; item = next) { + /* Opened and not closed haptics are leaked, this is on purpose. + * Close your haptic devices after usage. */ + // !!! FIXME: (...is leaking on purpose a good idea?) - No, of course not. + next = item->next; + SDL_free(item->name); + SDL_free(item); + } + + SDL_DINPUT_HapticQuit(); + + numhaptics = 0; + SDL_hapticlist = NULL; + SDL_hapticlist_tail = NULL; +} + +/* + * Creates a new haptic effect. + */ +bool SDL_SYS_HapticNewEffect(SDL_Haptic *haptic, struct haptic_effect *effect, + const SDL_HapticEffect *base) +{ + bool result; + + // Alloc the effect. + effect->hweffect = (struct haptic_hweffect *) SDL_calloc(1, sizeof(struct haptic_hweffect)); + if (!effect->hweffect) { + return false; + } + + result = SDL_DINPUT_HapticNewEffect(haptic, effect, base); + if (!result) { + SDL_free(effect->hweffect); + effect->hweffect = NULL; + } + return result; +} + +/* + * Updates an effect. + */ +bool SDL_SYS_HapticUpdateEffect(SDL_Haptic *haptic, struct haptic_effect *effect, const SDL_HapticEffect *data) +{ + return SDL_DINPUT_HapticUpdateEffect(haptic, effect, data); +} + +/* + * Runs an effect. + */ +bool SDL_SYS_HapticRunEffect(SDL_Haptic *haptic, struct haptic_effect *effect, Uint32 iterations) +{ + return SDL_DINPUT_HapticRunEffect(haptic, effect, iterations); +} + +/* + * Stops an effect. + */ +bool SDL_SYS_HapticStopEffect(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + return SDL_DINPUT_HapticStopEffect(haptic, effect); +} + +/* + * Frees the effect. + */ +void SDL_SYS_HapticDestroyEffect(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + SDL_DINPUT_HapticDestroyEffect(haptic, effect); + SDL_free(effect->hweffect); + effect->hweffect = NULL; +} + +/* + * Gets the status of a haptic effect. + */ +int SDL_SYS_HapticGetEffectStatus(SDL_Haptic *haptic, struct haptic_effect *effect) +{ + return SDL_DINPUT_HapticGetEffectStatus(haptic, effect); +} + +/* + * Sets the gain. + */ +bool SDL_SYS_HapticSetGain(SDL_Haptic *haptic, int gain) +{ + return SDL_DINPUT_HapticSetGain(haptic, gain); +} + +/* + * Sets the autocentering. + */ +bool SDL_SYS_HapticSetAutocenter(SDL_Haptic *haptic, int autocenter) +{ + return SDL_DINPUT_HapticSetAutocenter(haptic, autocenter); +} + +/* + * Pauses the device. + */ +bool SDL_SYS_HapticPause(SDL_Haptic *haptic) +{ + return SDL_DINPUT_HapticPause(haptic); +} + +/* + * Pauses the device. + */ +bool SDL_SYS_HapticResume(SDL_Haptic *haptic) +{ + return SDL_DINPUT_HapticResume(haptic); +} + +/* + * Stops all the playing effects on the device. + */ +bool SDL_SYS_HapticStopAll(SDL_Haptic *haptic) +{ + return SDL_DINPUT_HapticStopAll(haptic); +} + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif + +#endif // SDL_HAPTIC_DINPUT diff --git a/thirdparty/sdl/haptic/windows/SDL_windowshaptic_c.h b/thirdparty/sdl/haptic/windows/SDL_windowshaptic_c.h new file mode 100644 index 00000000000..c4b69287ba1 --- /dev/null +++ b/thirdparty/sdl/haptic/windows/SDL_windowshaptic_c.h @@ -0,0 +1,87 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_windowshaptic_c_h_ +#define SDL_windowshaptic_c_h_ + +#include "../SDL_syshaptic.h" +#include "../../core/windows/SDL_directx.h" +#include "../../core/windows/SDL_xinput.h" + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Haptic system hardware data. + */ +struct haptic_hwdata +{ +#ifdef SDL_HAPTIC_DINPUT + LPDIRECTINPUTDEVICE8 device; +#endif + DWORD axes[3]; // Axes to use. + bool is_joystick; // Device is loaded as joystick. + SDL_Thread *thread; + SDL_Mutex *mutex; + Uint64 stopTicks; + SDL_AtomicInt stopThread; +}; + +/* + * Haptic system effect data. + */ +#ifdef SDL_HAPTIC_DINPUT +struct haptic_hweffect +{ + DIEFFECT effect; + LPDIRECTINPUTEFFECT ref; +}; +#endif + +/* + * List of available haptic devices. + */ +typedef struct SDL_hapticlist_item +{ + SDL_HapticID instance_id; + char *name; + SDL_Haptic *haptic; +#ifdef SDL_HAPTIC_DINPUT + DIDEVICEINSTANCE instance; + DIDEVCAPS capabilities; +#endif + struct SDL_hapticlist_item *next; +} SDL_hapticlist_item; + +extern SDL_hapticlist_item *SDL_hapticlist; + +extern bool SDL_SYS_AddHapticDevice(SDL_hapticlist_item *item); +extern bool SDL_SYS_RemoveHapticDevice(SDL_hapticlist_item *prev, SDL_hapticlist_item *item); + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif + +#endif // SDL_windowshaptic_c_h_ diff --git a/thirdparty/sdl/hidapi/AUTHORS.txt b/thirdparty/sdl/hidapi/AUTHORS.txt new file mode 100644 index 00000000000..7c2a0358420 --- /dev/null +++ b/thirdparty/sdl/hidapi/AUTHORS.txt @@ -0,0 +1,18 @@ + +HIDAPI Authors: + +Alan Ott : + Original Author and Maintainer + Linux, Windows, and Mac implementations + +Ludovic Rousseau : + Formatting for Doxygen documentation + Bug fixes + Correctness fixes + +libusb/hidapi Team: + Development/maintenance since June 4th 2019 + +For a comprehensive list of contributions, see the commit list at github: + https://github.com/libusb/hidapi/graphs/contributors + diff --git a/thirdparty/sdl/hidapi/LICENSE-bsd.txt b/thirdparty/sdl/hidapi/LICENSE-bsd.txt new file mode 100644 index 00000000000..538cdf95cf6 --- /dev/null +++ b/thirdparty/sdl/hidapi/LICENSE-bsd.txt @@ -0,0 +1,26 @@ +Copyright (c) 2010, Alan Ott, Signal 11 Software +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Signal 11 Software nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/thirdparty/sdl/hidapi/LICENSE.txt b/thirdparty/sdl/hidapi/LICENSE.txt new file mode 100644 index 00000000000..e1676d4c42d --- /dev/null +++ b/thirdparty/sdl/hidapi/LICENSE.txt @@ -0,0 +1,13 @@ +HIDAPI can be used under one of three licenses. + +1. The GNU General Public License, version 3.0, in LICENSE-gpl3.txt +2. A BSD-Style License, in LICENSE-bsd.txt. +3. The more liberal original HIDAPI license. LICENSE-orig.txt + +The license chosen is at the discretion of the user of HIDAPI. For example: +1. An author of GPL software would likely use HIDAPI under the terms of the +GPL. + +2. An author of commercial closed-source software would likely use HIDAPI +under the terms of the BSD-style license or the original HIDAPI license. + diff --git a/thirdparty/sdl/hidapi/SDL_hidapi.c b/thirdparty/sdl/hidapi/SDL_hidapi.c new file mode 100644 index 00000000000..2378db68bd7 --- /dev/null +++ b/thirdparty/sdl/hidapi/SDL_hidapi.c @@ -0,0 +1,1752 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* Original hybrid wrapper for Linux by Valve Software. Their original notes: + * + * The libusb version doesn't support Bluetooth, but not all Linux + * distributions allow access to /dev/hidraw* + * + * This merges the two, at a small performance cost, until distributions + * have granted access to /dev/hidraw* + */ + +#include "SDL_internal.h" + +#include "SDL_hidapi_c.h" +#include "../joystick/usb_ids.h" +#include "../SDL_hints_c.h" + +// Initial type declarations +#define HID_API_NO_EXPORT_DEFINE // do not export hidapi procedures +#include "hidapi/hidapi.h" + +#ifndef SDL_HIDAPI_DISABLED + +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) +#include "../core/windows/SDL_windows.h" +#endif + +#ifdef SDL_PLATFORM_MACOS +#include +#include +#include +#include +#include +#include +// Things named "Master" were renamed to "Main" in macOS 12.0's SDK. +#if MAC_OS_X_VERSION_MIN_REQUIRED < 120000 +#define kIOMainPortDefault kIOMasterPortDefault +#endif +#endif + +#include "../core/linux/SDL_udev.h" +#ifdef SDL_USE_LIBUDEV +#include +#endif + +#ifdef HAVE_INOTIFY +#include // strerror +#include // errno +#include +#include // For the definition of NAME_MAX +#include +#endif + +#if defined(SDL_USE_LIBUDEV) || defined(HAVE_INOTIFY) +#include +#endif + +#ifdef SDL_USE_LIBUDEV +typedef enum +{ + ENUMERATION_UNSET, + ENUMERATION_LIBUDEV, + ENUMERATION_FALLBACK +} LinuxEnumerationMethod; + +static LinuxEnumerationMethod linux_enumeration_method = ENUMERATION_UNSET; +#endif + +#ifdef HAVE_INOTIFY +static int inotify_fd = -1; +#endif + +#ifdef SDL_USE_LIBUDEV +static const SDL_UDEV_Symbols *usyms = NULL; +#endif + +static struct +{ + bool m_bInitialized; + Uint32 m_unDeviceChangeCounter; + bool m_bCanGetNotifications; + Uint64 m_unLastDetect; + +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) + SDL_ThreadID m_nThreadID; + WNDCLASSEXA m_wndClass; + HWND m_hwndMsg; + HDEVNOTIFY m_hNotify; + double m_flLastWin32MessageCheck; +#endif + +#ifdef SDL_PLATFORM_MACOS + IONotificationPortRef m_notificationPort; + mach_port_t m_notificationMach; +#endif + +#ifdef SDL_USE_LIBUDEV + struct udev *m_pUdev; + struct udev_monitor *m_pUdevMonitor; + int m_nUdevFd; +#endif +} SDL_HIDAPI_discovery; + +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) +struct _DEV_BROADCAST_HDR +{ + DWORD dbch_size; + DWORD dbch_devicetype; + DWORD dbch_reserved; +}; + +typedef struct _DEV_BROADCAST_DEVICEINTERFACE_A +{ + DWORD dbcc_size; + DWORD dbcc_devicetype; + DWORD dbcc_reserved; + GUID dbcc_classguid; + char dbcc_name[1]; +} DEV_BROADCAST_DEVICEINTERFACE_A, *PDEV_BROADCAST_DEVICEINTERFACE_A; + +typedef struct _DEV_BROADCAST_HDR DEV_BROADCAST_HDR; +#define DBT_DEVICEARRIVAL 0x8000 // system detected a new device +#define DBT_DEVICEREMOVECOMPLETE 0x8004 // device was removed from the system +#define DBT_DEVTYP_DEVICEINTERFACE 0x00000005 // device interface class +#define DBT_DEVNODES_CHANGED 0x0007 +#define DBT_CONFIGCHANGED 0x0018 +#define DBT_DEVICETYPESPECIFIC 0x8005 // type specific event +#define DBT_DEVINSTSTARTED 0x8008 // device installed and started + +#include +DEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED); + +static LRESULT CALLBACK ControllerWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + switch (message) { + case WM_DEVICECHANGE: + switch (wParam) { + case DBT_DEVICEARRIVAL: + case DBT_DEVICEREMOVECOMPLETE: + if (((DEV_BROADCAST_HDR *)lParam)->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) { + ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter; + } + break; + } + return TRUE; + } + + return DefWindowProc(hwnd, message, wParam, lParam); +} +#endif // defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) + +#ifdef SDL_PLATFORM_MACOS +static void CallbackIOServiceFunc(void *context, io_iterator_t portIterator) +{ + // Must drain the iterator, or we won't receive new notifications + io_object_t entry; + while ((entry = IOIteratorNext(portIterator)) != 0) { + IOObjectRelease(entry); + ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter; + } +} +#endif // SDL_PLATFORM_MACOS + +#ifdef HAVE_INOTIFY +#ifdef HAVE_INOTIFY_INIT1 +static int SDL_inotify_init1(void) +{ + return inotify_init1(IN_NONBLOCK | IN_CLOEXEC); +} +#else +static int SDL_inotify_init1(void) +{ + int fd = inotify_init(); + if (fd < 0) { + return -1; + } + fcntl(fd, F_SETFL, O_NONBLOCK); + fcntl(fd, F_SETFD, FD_CLOEXEC); + return fd; +} +#endif + +static int StrHasPrefix(const char *string, const char *prefix) +{ + return SDL_strncmp(string, prefix, SDL_strlen(prefix)) == 0; +} + +static int StrIsInteger(const char *string) +{ + const char *p; + + if (*string == '\0') { + return 0; + } + + for (p = string; *p != '\0'; p++) { + if (*p < '0' || *p > '9') { + return 0; + } + } + + return 1; +} +#endif // HAVE_INOTIFY + +static void HIDAPI_InitializeDiscovery(void) +{ + SDL_HIDAPI_discovery.m_bInitialized = true; + SDL_HIDAPI_discovery.m_unDeviceChangeCounter = 1; + SDL_HIDAPI_discovery.m_bCanGetNotifications = false; + SDL_HIDAPI_discovery.m_unLastDetect = 0; + +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) + SDL_HIDAPI_discovery.m_nThreadID = SDL_GetCurrentThreadID(); + + SDL_zero(SDL_HIDAPI_discovery.m_wndClass); + SDL_HIDAPI_discovery.m_wndClass.hInstance = GetModuleHandle(NULL); + SDL_HIDAPI_discovery.m_wndClass.lpszClassName = "SDL_HIDAPI_DEVICE_DETECTION"; + SDL_HIDAPI_discovery.m_wndClass.lpfnWndProc = ControllerWndProc; // This function is called by windows + SDL_HIDAPI_discovery.m_wndClass.cbSize = sizeof(WNDCLASSEX); + + RegisterClassExA(&SDL_HIDAPI_discovery.m_wndClass); + SDL_HIDAPI_discovery.m_hwndMsg = CreateWindowExA(0, "SDL_HIDAPI_DEVICE_DETECTION", NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL); + + { + DEV_BROADCAST_DEVICEINTERFACE_A devBroadcast; + + SDL_zero(devBroadcast); + devBroadcast.dbcc_size = sizeof(devBroadcast); + devBroadcast.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; + devBroadcast.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE; + + /* DEVICE_NOTIFY_ALL_INTERFACE_CLASSES is important, makes GUID_DEVINTERFACE_USB_DEVICE ignored, + * but that seems to be necessary to get a notice after each individual usb input device actually + * installs, rather than just as the composite device is seen. + */ + SDL_HIDAPI_discovery.m_hNotify = RegisterDeviceNotification(SDL_HIDAPI_discovery.m_hwndMsg, &devBroadcast, DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES); + SDL_HIDAPI_discovery.m_bCanGetNotifications = (SDL_HIDAPI_discovery.m_hNotify != 0); + } +#endif // defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) + +#ifdef SDL_PLATFORM_MACOS + SDL_HIDAPI_discovery.m_notificationPort = IONotificationPortCreate(kIOMainPortDefault); + if (SDL_HIDAPI_discovery.m_notificationPort) { + { + io_iterator_t portIterator = 0; + io_object_t entry; + IOReturn result = IOServiceAddMatchingNotification( + SDL_HIDAPI_discovery.m_notificationPort, + kIOFirstMatchNotification, + IOServiceMatching(kIOHIDDeviceKey), + CallbackIOServiceFunc, NULL, &portIterator); + + if (result == 0) { + // Must drain the existing iterator, or we won't receive new notifications + while ((entry = IOIteratorNext(portIterator)) != 0) { + IOObjectRelease(entry); + } + } else { + IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort); + SDL_HIDAPI_discovery.m_notificationPort = nil; + } + } + { + io_iterator_t portIterator = 0; + io_object_t entry; + IOReturn result = IOServiceAddMatchingNotification( + SDL_HIDAPI_discovery.m_notificationPort, + kIOTerminatedNotification, + IOServiceMatching(kIOHIDDeviceKey), + CallbackIOServiceFunc, NULL, &portIterator); + + if (result == 0) { + // Must drain the existing iterator, or we won't receive new notifications + while ((entry = IOIteratorNext(portIterator)) != 0) { + IOObjectRelease(entry); + } + } else { + IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort); + SDL_HIDAPI_discovery.m_notificationPort = nil; + } + } + } + + SDL_HIDAPI_discovery.m_notificationMach = MACH_PORT_NULL; + if (SDL_HIDAPI_discovery.m_notificationPort) { + SDL_HIDAPI_discovery.m_notificationMach = IONotificationPortGetMachPort(SDL_HIDAPI_discovery.m_notificationPort); + } + + SDL_HIDAPI_discovery.m_bCanGetNotifications = (SDL_HIDAPI_discovery.m_notificationMach != MACH_PORT_NULL); + +#endif // SDL_PLATFORM_MACOS + +#ifdef SDL_USE_LIBUDEV + if (linux_enumeration_method == ENUMERATION_LIBUDEV) { + SDL_HIDAPI_discovery.m_pUdev = NULL; + SDL_HIDAPI_discovery.m_pUdevMonitor = NULL; + SDL_HIDAPI_discovery.m_nUdevFd = -1; + + usyms = SDL_UDEV_GetUdevSyms(); + if (usyms != NULL) { + SDL_HIDAPI_discovery.m_pUdev = usyms->udev_new(); + if (SDL_HIDAPI_discovery.m_pUdev != NULL) { + SDL_HIDAPI_discovery.m_pUdevMonitor = usyms->udev_monitor_new_from_netlink(SDL_HIDAPI_discovery.m_pUdev, "udev"); + if (SDL_HIDAPI_discovery.m_pUdevMonitor != NULL) { + usyms->udev_monitor_enable_receiving(SDL_HIDAPI_discovery.m_pUdevMonitor); + SDL_HIDAPI_discovery.m_nUdevFd = usyms->udev_monitor_get_fd(SDL_HIDAPI_discovery.m_pUdevMonitor); + SDL_HIDAPI_discovery.m_bCanGetNotifications = true; + } + } + } + } else +#endif // SDL_USE_LIBUDEV + { +#ifdef HAVE_INOTIFY + inotify_fd = SDL_inotify_init1(); + + if (inotify_fd < 0) { + SDL_LogWarn(SDL_LOG_CATEGORY_INPUT, + "Unable to initialize inotify, falling back to polling: %s", + strerror(errno)); + return; + } + + /* We need to watch for attribute changes in addition to + * creation, because when a device is first created, it has + * permissions that we can't read. When udev chmods it to + * something that we maybe *can* read, we'll get an + * IN_ATTRIB event to tell us. */ + if (inotify_add_watch(inotify_fd, "/dev", + IN_CREATE | IN_DELETE | IN_MOVE | IN_ATTRIB) < 0) { + close(inotify_fd); + inotify_fd = -1; + SDL_LogWarn(SDL_LOG_CATEGORY_INPUT, + "Unable to add inotify watch, falling back to polling: %s", + strerror(errno)); + return; + } + + SDL_HIDAPI_discovery.m_bCanGetNotifications = true; +#endif // HAVE_INOTIFY + } +} + +static void HIDAPI_UpdateDiscovery(void) +{ + if (!SDL_HIDAPI_discovery.m_bInitialized) { + HIDAPI_InitializeDiscovery(); + } + + if (!SDL_HIDAPI_discovery.m_bCanGetNotifications) { + const Uint32 SDL_HIDAPI_DETECT_INTERVAL_MS = 3000; // Update every 3 seconds + Uint64 now = SDL_GetTicks(); + if (!SDL_HIDAPI_discovery.m_unLastDetect || now >= (SDL_HIDAPI_discovery.m_unLastDetect + SDL_HIDAPI_DETECT_INTERVAL_MS)) { + ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter; + SDL_HIDAPI_discovery.m_unLastDetect = now; + } + return; + } + +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) +#if 0 // just let the usual SDL_PumpEvents loop dispatch these, fixing bug 4286. --ryan. + // We'll only get messages on the same thread that created the window + if (SDL_GetCurrentThreadID() == SDL_HIDAPI_discovery.m_nThreadID) { + MSG msg; + while (PeekMessage(&msg, SDL_HIDAPI_discovery.m_hwndMsg, 0, 0, PM_NOREMOVE)) { + if (GetMessageA(&msg, SDL_HIDAPI_discovery.m_hwndMsg, 0, 0) != 0) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } + } +#endif +#endif // defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) + +#ifdef SDL_PLATFORM_MACOS + if (SDL_HIDAPI_discovery.m_notificationPort) { + struct + { + mach_msg_header_t hdr; + char payload[4096]; + } msg; + while (mach_msg(&msg.hdr, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, sizeof(msg), SDL_HIDAPI_discovery.m_notificationMach, 0, MACH_PORT_NULL) == KERN_SUCCESS) { + IODispatchCalloutFromMessage(NULL, &msg.hdr, SDL_HIDAPI_discovery.m_notificationPort); + } + } +#endif + +#ifdef SDL_USE_LIBUDEV + if (linux_enumeration_method == ENUMERATION_LIBUDEV) { + if (SDL_HIDAPI_discovery.m_nUdevFd >= 0) { + /* Drain all notification events. + * We don't expect a lot of device notifications so just + * do a new discovery on any kind or number of notifications. + * This could be made more restrictive if necessary. + */ + for (;;) { + struct pollfd PollUdev; + struct udev_device *pUdevDevice; + + PollUdev.fd = SDL_HIDAPI_discovery.m_nUdevFd; + PollUdev.events = POLLIN; + if (poll(&PollUdev, 1, 0) != 1) { + break; + } + + pUdevDevice = usyms->udev_monitor_receive_device(SDL_HIDAPI_discovery.m_pUdevMonitor); + if (pUdevDevice) { + const char *action = NULL; + action = usyms->udev_device_get_action(pUdevDevice); + if (action == NULL || SDL_strcmp(action, "add") == 0 || SDL_strcmp(action, "remove") == 0) { + ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter; + } + usyms->udev_device_unref(pUdevDevice); + } + } + } + } else +#endif // SDL_USE_LIBUDEV + { +#ifdef HAVE_INOTIFY + if (inotify_fd >= 0) { + union + { + struct inotify_event event; + char storage[4096]; + char enough_for_inotify[sizeof(struct inotify_event) + NAME_MAX + 1]; + } buf; + ssize_t bytes; + size_t remain = 0; + size_t len; + + bytes = read(inotify_fd, &buf, sizeof(buf)); + + if (bytes > 0) { + remain = (size_t)bytes; + } + + while (remain > 0) { + if (buf.event.len > 0) { + if (StrHasPrefix(buf.event.name, "hidraw") && + StrIsInteger(buf.event.name + SDL_strlen("hidraw"))) { + ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter; + /* We found an hidraw change. We still continue to + * drain the inotify fd to avoid leaving old + * notifications in the queue. */ + } + } + + len = sizeof(struct inotify_event) + buf.event.len; + remain -= len; + + if (remain != 0) { + SDL_memmove(&buf.storage[0], &buf.storage[len], remain); + } + } + } +#endif // HAVE_INOTIFY + } +} + +static void HIDAPI_ShutdownDiscovery(void) +{ + if (!SDL_HIDAPI_discovery.m_bInitialized) { + return; + } + +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) + if (SDL_HIDAPI_discovery.m_hNotify) { + UnregisterDeviceNotification(SDL_HIDAPI_discovery.m_hNotify); + } + + if (SDL_HIDAPI_discovery.m_hwndMsg) { + DestroyWindow(SDL_HIDAPI_discovery.m_hwndMsg); + } + + UnregisterClassA(SDL_HIDAPI_discovery.m_wndClass.lpszClassName, SDL_HIDAPI_discovery.m_wndClass.hInstance); +#endif + +#ifdef SDL_PLATFORM_MACOS + if (SDL_HIDAPI_discovery.m_notificationPort) { + IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort); + } +#endif + +#ifdef SDL_USE_LIBUDEV + if (linux_enumeration_method == ENUMERATION_LIBUDEV) { + if (usyms) { + if (SDL_HIDAPI_discovery.m_pUdevMonitor) { + usyms->udev_monitor_unref(SDL_HIDAPI_discovery.m_pUdevMonitor); + } + if (SDL_HIDAPI_discovery.m_pUdev) { + usyms->udev_unref(SDL_HIDAPI_discovery.m_pUdev); + } + SDL_UDEV_ReleaseUdevSyms(); + usyms = NULL; + } + } else +#endif // SDL_USE_LIBUDEV + { +#ifdef HAVE_INOTIFY + if (inotify_fd >= 0) { + close(inotify_fd); + inotify_fd = -1; + } +#endif + } + + SDL_HIDAPI_discovery.m_bInitialized = false; +} + +// Platform HIDAPI Implementation + +#define HIDAPI_USING_SDL_RUNTIME +#define HIDAPI_IGNORE_DEVICE(BUS, VID, PID, USAGE_PAGE, USAGE) \ + SDL_HIDAPI_ShouldIgnoreDevice(BUS, VID, PID, USAGE_PAGE, USAGE) + +struct PLATFORM_hid_device_; +typedef struct PLATFORM_hid_device_ PLATFORM_hid_device; + +#define api_version PLATFORM_api_version +#define create_device_info_for_device PLATFORM_create_device_info_for_device +#define free_hid_device PLATFORM_free_hid_device +#define hid_close PLATFORM_hid_close +#define hid_device PLATFORM_hid_device +#define hid_device_ PLATFORM_hid_device_ +#define hid_enumerate PLATFORM_hid_enumerate +#define hid_error PLATFORM_hid_error +#define hid_exit PLATFORM_hid_exit +#define hid_free_enumeration PLATFORM_hid_free_enumeration +#define hid_get_device_info PLATFORM_hid_get_device_info +#define hid_get_feature_report PLATFORM_hid_get_feature_report +#define hid_get_indexed_string PLATFORM_hid_get_indexed_string +#define hid_get_input_report PLATFORM_hid_get_input_report +#define hid_get_manufacturer_string PLATFORM_hid_get_manufacturer_string +#define hid_get_product_string PLATFORM_hid_get_product_string +#define hid_get_report_descriptor PLATFORM_hid_get_report_descriptor +#define hid_get_serial_number_string PLATFORM_hid_get_serial_number_string +#define hid_init PLATFORM_hid_init +#define hid_open_path PLATFORM_hid_open_path +#define hid_open PLATFORM_hid_open +#define hid_read PLATFORM_hid_read +#define hid_read_timeout PLATFORM_hid_read_timeout +#define hid_send_feature_report PLATFORM_hid_send_feature_report +#define hid_set_nonblocking PLATFORM_hid_set_nonblocking +#define hid_version PLATFORM_hid_version +#define hid_version_str PLATFORM_hid_version_str +#define hid_write PLATFORM_hid_write +#define input_report PLATFORM_input_report +#define make_path PLATFORM_make_path +#define new_hid_device PLATFORM_new_hid_device +#define read_thread PLATFORM_read_thread +#define return_data PLATFORM_return_data + +#ifdef SDL_PLATFORM_LINUX +#include "SDL_hidapi_linux.h" +#elif defined(SDL_PLATFORM_NETBSD) +#include "SDL_hidapi_netbsd.h" +#elif defined(SDL_PLATFORM_MACOS) +#include "SDL_hidapi_mac.h" +#elif defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) +#include "SDL_hidapi_windows.h" +#elif defined(SDL_PLATFORM_ANDROID) +#include "SDL_hidapi_android.h" +#elif defined(SDL_PLATFORM_IOS) || defined(SDL_PLATFORM_TVOS) +#include "SDL_hidapi_ios.h" +#endif + +#undef api_version +#undef create_device_info_for_device +#undef free_hid_device +#undef hid_close +#undef hid_device +#undef hid_device_ +#undef hid_enumerate +#undef hid_error +#undef hid_exit +#undef hid_free_enumeration +#undef hid_get_device_info +#undef hid_get_feature_report +#undef hid_get_indexed_string +#undef hid_get_input_report +#undef hid_get_manufacturer_string +#undef hid_get_product_string +#undef hid_get_report_descriptor +#undef hid_get_serial_number_string +#undef hid_init +#undef hid_open +#undef hid_open_path +#undef hid_read +#undef hid_read_timeout +#undef hid_send_feature_report +#undef hid_set_nonblocking +#undef hid_version +#undef hid_version_str +#undef hid_write +#undef input_report +#undef make_path +#undef new_hid_device +#undef read_thread +#undef return_data + +#ifdef SDL_JOYSTICK_HIDAPI_STEAMXBOX +#define HAVE_DRIVER_BACKEND 1 +#endif + +#ifdef HAVE_DRIVER_BACKEND + +// DRIVER HIDAPI Implementation + +struct DRIVER_hid_device_; +typedef struct DRIVER_hid_device_ DRIVER_hid_device; + +#define hid_close DRIVER_hid_close +#define hid_device DRIVER_hid_device +#define hid_device_ DRIVER_hid_device_ +#define hid_enumerate DRIVER_hid_enumerate +#define hid_error DRIVER_hid_error +#define hid_exit DRIVER_hid_exit +#define hid_free_enumeration DRIVER_hid_free_enumeration +#define hid_get_device_info DRIVER_hid_get_device_info +#define hid_get_feature_report DRIVER_hid_get_feature_report +#define hid_get_indexed_string DRIVER_hid_get_indexed_string +#define hid_get_input_report DRIVER_hid_get_input_report +#define hid_get_manufacturer_string DRIVER_hid_get_manufacturer_string +#define hid_get_product_string DRIVER_hid_get_product_string +#define hid_get_report_descriptor DRIVER_hid_get_report_descriptor +#define hid_get_serial_number_string DRIVER_hid_get_serial_number_string +#define hid_init DRIVER_hid_init +#define hid_open DRIVER_hid_open +#define hid_open_path DRIVER_hid_open_path +#define hid_read DRIVER_hid_read +#define hid_read_timeout DRIVER_hid_read_timeout +#define hid_send_feature_report DRIVER_hid_send_feature_report +#define hid_set_nonblocking DRIVER_hid_set_nonblocking +#define hid_write DRIVER_hid_write + +#ifdef SDL_JOYSTICK_HIDAPI_STEAMXBOX +#include "SDL_hidapi_steamxbox.h" +#else +#error Need a driver hid.c for this platform! +#endif + +#undef hid_close +#undef hid_device +#undef hid_device_ +#undef hid_enumerate +#undef hid_error +#undef hid_exit +#undef hid_free_enumeration +#undef hid_get_device_info +#undef hid_get_feature_report +#undef hid_get_indexed_string +#undef hid_get_input_report +#undef hid_get_manufacturer_string +#undef hid_get_product_string +#undef hid_get_report_descriptor +#undef hid_get_serial_number_string +#undef hid_init +#undef hid_open +#undef hid_open_path +#undef hid_read +#undef hid_read_timeout +#undef hid_send_feature_report +#undef hid_set_nonblocking +#undef hid_write + +#endif // HAVE_DRIVER_BACKEND + +#ifdef HAVE_LIBUSB +// libusb HIDAPI Implementation + +// Include this now, for our dynamically-loaded libusb context +#include + +static struct +{ + SDL_SharedObject *libhandle; + + /* *INDENT-OFF* */ // clang-format off + int (LIBUSB_CALL *init)(libusb_context **ctx); + void (LIBUSB_CALL *exit)(libusb_context *ctx); + ssize_t (LIBUSB_CALL *get_device_list)(libusb_context *ctx, libusb_device ***list); + void (LIBUSB_CALL *free_device_list)(libusb_device **list, int unref_devices); + int (LIBUSB_CALL *get_device_descriptor)(libusb_device *dev, struct libusb_device_descriptor *desc); + int (LIBUSB_CALL *get_active_config_descriptor)(libusb_device *dev, struct libusb_config_descriptor **config); + int (LIBUSB_CALL *get_config_descriptor)( + libusb_device *dev, + uint8_t config_index, + struct libusb_config_descriptor **config + ); + void (LIBUSB_CALL *free_config_descriptor)(struct libusb_config_descriptor *config); + uint8_t (LIBUSB_CALL *get_bus_number)(libusb_device *dev); + int (LIBUSB_CALL *get_port_numbers)(libusb_device *dev, uint8_t *port_numbers, int port_numbers_len); + uint8_t (LIBUSB_CALL *get_device_address)(libusb_device *dev); + int (LIBUSB_CALL *open)(libusb_device *dev, libusb_device_handle **dev_handle); + void (LIBUSB_CALL *close)(libusb_device_handle *dev_handle); + libusb_device *(LIBUSB_CALL *get_device)(libusb_device_handle *dev_handle); + int (LIBUSB_CALL *claim_interface)(libusb_device_handle *dev_handle, int interface_number); + int (LIBUSB_CALL *release_interface)(libusb_device_handle *dev_handle, int interface_number); + int (LIBUSB_CALL *kernel_driver_active)(libusb_device_handle *dev_handle, int interface_number); + int (LIBUSB_CALL *detach_kernel_driver)(libusb_device_handle *dev_handle, int interface_number); + int (LIBUSB_CALL *attach_kernel_driver)(libusb_device_handle *dev_handle, int interface_number); + int (LIBUSB_CALL *set_interface_alt_setting)(libusb_device_handle *dev, int interface_number, int alternate_setting); + struct libusb_transfer * (LIBUSB_CALL *alloc_transfer)(int iso_packets); + int (LIBUSB_CALL *submit_transfer)(struct libusb_transfer *transfer); + int (LIBUSB_CALL *cancel_transfer)(struct libusb_transfer *transfer); + void (LIBUSB_CALL *free_transfer)(struct libusb_transfer *transfer); + int (LIBUSB_CALL *control_transfer)( + libusb_device_handle *dev_handle, + uint8_t request_type, + uint8_t bRequest, + uint16_t wValue, + uint16_t wIndex, + unsigned char *data, + uint16_t wLength, + unsigned int timeout + ); + int (LIBUSB_CALL *interrupt_transfer)( + libusb_device_handle *dev_handle, + unsigned char endpoint, + unsigned char *data, + int length, + int *actual_length, + unsigned int timeout + ); + int (LIBUSB_CALL *handle_events)(libusb_context *ctx); + int (LIBUSB_CALL *handle_events_completed)(libusb_context *ctx, int *completed); + const char * (LIBUSB_CALL *error_name)(int errcode); +/* *INDENT-ON* */ // clang-format on + +} libusb_ctx; + +#define libusb_init libusb_ctx.init +#define libusb_exit libusb_ctx.exit +#define libusb_get_device_list libusb_ctx.get_device_list +#define libusb_free_device_list libusb_ctx.free_device_list +#define libusb_get_device_descriptor libusb_ctx.get_device_descriptor +#define libusb_get_active_config_descriptor libusb_ctx.get_active_config_descriptor +#define libusb_get_config_descriptor libusb_ctx.get_config_descriptor +#define libusb_free_config_descriptor libusb_ctx.free_config_descriptor +#define libusb_get_bus_number libusb_ctx.get_bus_number +#define libusb_get_port_numbers libusb_ctx.get_port_numbers +#define libusb_get_device_address libusb_ctx.get_device_address +#define libusb_open libusb_ctx.open +#define libusb_close libusb_ctx.close +#define libusb_get_device libusb_ctx.get_device +#define libusb_claim_interface libusb_ctx.claim_interface +#define libusb_release_interface libusb_ctx.release_interface +#define libusb_kernel_driver_active libusb_ctx.kernel_driver_active +#define libusb_detach_kernel_driver libusb_ctx.detach_kernel_driver +#define libusb_attach_kernel_driver libusb_ctx.attach_kernel_driver +#define libusb_set_interface_alt_setting libusb_ctx.set_interface_alt_setting +#define libusb_alloc_transfer libusb_ctx.alloc_transfer +#define libusb_submit_transfer libusb_ctx.submit_transfer +#define libusb_cancel_transfer libusb_ctx.cancel_transfer +#define libusb_free_transfer libusb_ctx.free_transfer +#define libusb_control_transfer libusb_ctx.control_transfer +#define libusb_interrupt_transfer libusb_ctx.interrupt_transfer +#define libusb_handle_events libusb_ctx.handle_events +#define libusb_handle_events_completed libusb_ctx.handle_events_completed +#define libusb_error_name libusb_ctx.error_name + +struct LIBUSB_hid_device_; +typedef struct LIBUSB_hid_device_ LIBUSB_hid_device; + +#define free_hid_device LIBUSB_free_hid_device +#define hid_close LIBUSB_hid_close +#define hid_device LIBUSB_hid_device +#define hid_device_ LIBUSB_hid_device_ +#define hid_enumerate LIBUSB_hid_enumerate +#define hid_error LIBUSB_hid_error +#define hid_exit LIBUSB_hid_exit +#define hid_free_enumeration LIBUSB_hid_free_enumeration +#define hid_get_device_info LIBUSB_hid_get_device_info +#define hid_get_feature_report LIBUSB_hid_get_feature_report +#define hid_get_indexed_string LIBUSB_hid_get_indexed_string +#define hid_get_input_report LIBUSB_hid_get_input_report +#define hid_get_manufacturer_string LIBUSB_hid_get_manufacturer_string +#define hid_get_product_string LIBUSB_hid_get_product_string +#define hid_get_report_descriptor LIBUSB_hid_get_report_descriptor +#define hid_get_serial_number_string LIBUSB_hid_get_serial_number_string +#define hid_init LIBUSB_hid_init +#define hid_open LIBUSB_hid_open +#define hid_open_path LIBUSB_hid_open_path +#define hid_read LIBUSB_hid_read +#define hid_read_timeout LIBUSB_hid_read_timeout +#define hid_send_feature_report LIBUSB_hid_send_feature_report +#define hid_set_nonblocking LIBUSB_hid_set_nonblocking +#define hid_write LIBUSB_hid_write +#define hid_version LIBUSB_hid_version +#define hid_version_str LIBUSB_hid_version_str +#define input_report LIBUSB_input_report +#define make_path LIBUSB_make_path +#define new_hid_device LIBUSB_new_hid_device +#define read_thread LIBUSB_read_thread +#define return_data LIBUSB_return_data + +#include "SDL_hidapi_libusb.h" + +#undef libusb_init +#undef libusb_exit +#undef libusb_get_device_list +#undef libusb_free_device_list +#undef libusb_get_device_descriptor +#undef libusb_get_active_config_descriptor +#undef libusb_get_config_descriptor +#undef libusb_free_config_descriptor +#undef libusb_get_bus_number +#undef libusb_get_port_numbers +#undef libusb_get_device_address +#undef libusb_open +#undef libusb_close +#undef libusb_get_device +#undef libusb_claim_interface +#undef libusb_release_interface +#undef libusb_kernel_driver_active +#undef libusb_detach_kernel_driver +#undef libusb_attach_kernel_driver +#undef libusb_set_interface_alt_setting +#undef libusb_alloc_transfer +#undef libusb_submit_transfer +#undef libusb_cancel_transfer +#undef libusb_free_transfer +#undef libusb_control_transfer +#undef libusb_interrupt_transfer +#undef libusb_handle_events +#undef libusb_handle_events_completed +#undef libusb_error_name + +#undef free_hid_device +#undef hid_close +#undef hid_device +#undef hid_device_ +#undef hid_enumerate +#undef hid_error +#undef hid_exit +#undef hid_free_enumeration +#undef hid_get_device_info +#undef hid_get_feature_report +#undef hid_get_indexed_string +#undef hid_get_input_report +#undef hid_get_manufacturer_string +#undef hid_get_product_string +#undef hid_get_report_descriptor +#undef hid_get_serial_number_string +#undef hid_init +#undef hid_open +#undef hid_open_path +#undef hid_read +#undef hid_read_timeout +#undef hid_send_feature_report +#undef hid_set_nonblocking +#undef hid_write +#undef input_report +#undef make_path +#undef new_hid_device +#undef read_thread +#undef return_data + +/* If the platform has any backend other than libusb, try to avoid using + * libusb as the main backend for devices, since it detaches drivers and + * therefore makes devices inaccessible to the rest of the OS. + * + * We do this by whitelisting devices we know to be accessible _exclusively_ + * via libusb; these are typically devices that look like HIDs but have a + * quirk that requires direct access to the hardware. + */ +static const struct { + Uint16 vendor; + Uint16 product; +} SDL_libusb_whitelist[] = { + { 0x057e, 0x0337 } // Nintendo WUP-028, Wii U/Switch GameCube Adapter +}; + +static bool IsInWhitelist(Uint16 vendor, Uint16 product) +{ + int i; + for (i = 0; i < SDL_arraysize(SDL_libusb_whitelist); i += 1) { + if (vendor == SDL_libusb_whitelist[i].vendor && + product == SDL_libusb_whitelist[i].product) { + return true; + } + } + return false; +} + +#endif // HAVE_LIBUSB + +#endif // !SDL_HIDAPI_DISABLED + +#if defined(HAVE_PLATFORM_BACKEND) || defined(HAVE_DRIVER_BACKEND) +// We have another way to get HID devices, so use the whitelist to get devices where libusb is preferred +#define SDL_HINT_HIDAPI_LIBUSB_WHITELIST_DEFAULT true +#else +// libusb is the only way to get HID devices, so don't use the whitelist, get them all +#define SDL_HINT_HIDAPI_LIBUSB_WHITELIST_DEFAULT false +#endif // HAVE_PLATFORM_BACKEND || HAVE_DRIVER_BACKEND + +static bool use_libusb_whitelist = SDL_HINT_HIDAPI_LIBUSB_WHITELIST_DEFAULT; + +// Shared HIDAPI Implementation + +struct hidapi_backend +{ + int (*hid_write)(void *device, const unsigned char *data, size_t length); + int (*hid_read_timeout)(void *device, unsigned char *data, size_t length, int milliseconds); + int (*hid_read)(void *device, unsigned char *data, size_t length); + int (*hid_set_nonblocking)(void *device, int nonblock); + int (*hid_send_feature_report)(void *device, const unsigned char *data, size_t length); + int (*hid_get_feature_report)(void *device, unsigned char *data, size_t length); + int (*hid_get_input_report)(void *device, unsigned char *data, size_t length); + void (*hid_close)(void *device); + int (*hid_get_manufacturer_string)(void *device, wchar_t *string, size_t maxlen); + int (*hid_get_product_string)(void *device, wchar_t *string, size_t maxlen); + int (*hid_get_serial_number_string)(void *device, wchar_t *string, size_t maxlen); + int (*hid_get_indexed_string)(void *device, int string_index, wchar_t *string, size_t maxlen); + struct hid_device_info *(*hid_get_device_info)(void *device); + int (*hid_get_report_descriptor)(void *device, unsigned char *buf, size_t buf_size); + const wchar_t *(*hid_error)(void *device); +}; + +#ifdef HAVE_PLATFORM_BACKEND +static const struct hidapi_backend PLATFORM_Backend = { + (void *)PLATFORM_hid_write, + (void *)PLATFORM_hid_read_timeout, + (void *)PLATFORM_hid_read, + (void *)PLATFORM_hid_set_nonblocking, + (void *)PLATFORM_hid_send_feature_report, + (void *)PLATFORM_hid_get_feature_report, + (void *)PLATFORM_hid_get_input_report, + (void *)PLATFORM_hid_close, + (void *)PLATFORM_hid_get_manufacturer_string, + (void *)PLATFORM_hid_get_product_string, + (void *)PLATFORM_hid_get_serial_number_string, + (void *)PLATFORM_hid_get_indexed_string, + (void *)PLATFORM_hid_get_device_info, + (void *)PLATFORM_hid_get_report_descriptor, + (void *)PLATFORM_hid_error +}; +#endif // HAVE_PLATFORM_BACKEND + +#ifdef HAVE_DRIVER_BACKEND +static const struct hidapi_backend DRIVER_Backend = { + (void *)DRIVER_hid_write, + (void *)DRIVER_hid_read_timeout, + (void *)DRIVER_hid_read, + (void *)DRIVER_hid_set_nonblocking, + (void *)DRIVER_hid_send_feature_report, + (void *)DRIVER_hid_get_feature_report, + (void *)DRIVER_hid_get_input_report, + (void *)DRIVER_hid_close, + (void *)DRIVER_hid_get_manufacturer_string, + (void *)DRIVER_hid_get_product_string, + (void *)DRIVER_hid_get_serial_number_string, + (void *)DRIVER_hid_get_indexed_string, + (void *)DRIVER_hid_get_device_info, + (void *)DRIVER_hid_get_report_descriptor, + (void *)DRIVER_hid_error +}; +#endif // HAVE_DRIVER_BACKEND + +#ifdef HAVE_LIBUSB +static const struct hidapi_backend LIBUSB_Backend = { + (void *)LIBUSB_hid_write, + (void *)LIBUSB_hid_read_timeout, + (void *)LIBUSB_hid_read, + (void *)LIBUSB_hid_set_nonblocking, + (void *)LIBUSB_hid_send_feature_report, + (void *)LIBUSB_hid_get_feature_report, + (void *)LIBUSB_hid_get_input_report, + (void *)LIBUSB_hid_close, + (void *)LIBUSB_hid_get_manufacturer_string, + (void *)LIBUSB_hid_get_product_string, + (void *)LIBUSB_hid_get_serial_number_string, + (void *)LIBUSB_hid_get_indexed_string, + (void *)LIBUSB_hid_get_device_info, + (void *)LIBUSB_hid_get_report_descriptor, + (void *)LIBUSB_hid_error +}; +#endif // HAVE_LIBUSB + +struct SDL_hid_device +{ + void *device; + const struct hidapi_backend *backend; + SDL_hid_device_info info; +}; + +#if defined(HAVE_PLATFORM_BACKEND) || defined(HAVE_DRIVER_BACKEND) || defined(HAVE_LIBUSB) + +static SDL_hid_device *CreateHIDDeviceWrapper(void *device, const struct hidapi_backend *backend) +{ + SDL_hid_device *wrapper = (SDL_hid_device *)SDL_malloc(sizeof(*wrapper)); + SDL_SetObjectValid(wrapper, SDL_OBJECT_TYPE_HIDAPI_DEVICE, true); + wrapper->device = device; + wrapper->backend = backend; + SDL_zero(wrapper->info); + return wrapper; +} + +#endif // HAVE_PLATFORM_BACKEND || HAVE_DRIVER_BACKEND || HAVE_LIBUSB + +static void DeleteHIDDeviceWrapper(SDL_hid_device *wrapper) +{ + SDL_SetObjectValid(wrapper, SDL_OBJECT_TYPE_HIDAPI_DEVICE, false); + SDL_free(wrapper->info.path); + SDL_free(wrapper->info.serial_number); + SDL_free(wrapper->info.manufacturer_string); + SDL_free(wrapper->info.product_string); + SDL_free(wrapper); +} + +#define CHECK_DEVICE_MAGIC(device, result) \ + if (!SDL_ObjectValid(device, SDL_OBJECT_TYPE_HIDAPI_DEVICE)) { \ + SDL_SetError("Invalid device"); \ + return result; \ + } + +#define COPY_IF_EXISTS(var) \ + if (pSrc->var != NULL) { \ + pDst->var = SDL_strdup(pSrc->var); \ + } else { \ + pDst->var = NULL; \ + } +#define WCOPY_IF_EXISTS(var) \ + if (pSrc->var != NULL) { \ + pDst->var = SDL_wcsdup(pSrc->var); \ + } else { \ + pDst->var = NULL; \ + } + +static void CopyHIDDeviceInfo(struct hid_device_info *pSrc, struct SDL_hid_device_info *pDst) +{ + COPY_IF_EXISTS(path) + pDst->vendor_id = pSrc->vendor_id; + pDst->product_id = pSrc->product_id; + WCOPY_IF_EXISTS(serial_number) + pDst->release_number = pSrc->release_number; + WCOPY_IF_EXISTS(manufacturer_string) + WCOPY_IF_EXISTS(product_string) + pDst->usage_page = pSrc->usage_page; + pDst->usage = pSrc->usage; + pDst->interface_number = pSrc->interface_number; + pDst->interface_class = pSrc->interface_class; + pDst->interface_subclass = pSrc->interface_subclass; + pDst->interface_protocol = pSrc->interface_protocol; + pDst->bus_type = (SDL_hid_bus_type)pSrc->bus_type; + pDst->next = NULL; +} + +#undef COPY_IF_EXISTS +#undef WCOPY_IF_EXISTS + +static int SDL_hidapi_refcount = 0; +static bool SDL_hidapi_only_controllers; +static char *SDL_hidapi_ignored_devices = NULL; + +static void SDLCALL OnlyControllersChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_hidapi_only_controllers = SDL_GetStringBoolean(hint, true); +} + +static void SDLCALL IgnoredDevicesChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + if (SDL_hidapi_ignored_devices) { + SDL_free(SDL_hidapi_ignored_devices); + } + if (hint && *hint) { + SDL_hidapi_ignored_devices = SDL_strdup(hint); + } else { + SDL_hidapi_ignored_devices = NULL; + } +} + +bool SDL_HIDAPI_ShouldIgnoreDevice(int bus, Uint16 vendor_id, Uint16 product_id, Uint16 usage_page, Uint16 usage) +{ + // See if there are any devices we should skip in enumeration + if (SDL_hidapi_only_controllers && usage_page) { + if (vendor_id == USB_VENDOR_VALVE) { + // Ignore the mouse/keyboard interface on Steam Controllers + if ( +#ifdef SDL_PLATFORM_WIN32 + // Check the usage page and usage on both USB and Bluetooth +#else + // Only check the usage page and usage on USB + bus == HID_API_BUS_USB && +#endif + usage_page == USB_USAGEPAGE_GENERIC_DESKTOP && + (usage == USB_USAGE_GENERIC_KEYBOARD || usage == USB_USAGE_GENERIC_MOUSE)) { + return true; + } + } else if (usage_page == USB_USAGEPAGE_GENERIC_DESKTOP && + (usage == USB_USAGE_GENERIC_JOYSTICK || usage == USB_USAGE_GENERIC_GAMEPAD || usage == USB_USAGE_GENERIC_MULTIAXISCONTROLLER)) { + // This is a controller + } else { + return true; + } + } + if (SDL_hidapi_ignored_devices) { + char vendor_match[16], product_match[16]; + SDL_snprintf(vendor_match, sizeof(vendor_match), "0x%.4x/0x0000", vendor_id); + SDL_snprintf(product_match, sizeof(product_match), "0x%.4x/0x%.4x", vendor_id, product_id); + if (SDL_strcasestr(SDL_hidapi_ignored_devices, vendor_match) || + SDL_strcasestr(SDL_hidapi_ignored_devices, product_match)) { + return true; + } + } + return false; +} + +int SDL_hid_init(void) +{ + int attempts = 0, success = 0; + + if (SDL_hidapi_refcount > 0) { + ++SDL_hidapi_refcount; + return 0; + } + + SDL_AddHintCallback(SDL_HINT_HIDAPI_ENUMERATE_ONLY_CONTROLLERS, OnlyControllersChanged, NULL); + SDL_AddHintCallback(SDL_HINT_HIDAPI_IGNORE_DEVICES, IgnoredDevicesChanged, NULL); + +#ifdef SDL_USE_LIBUDEV + if (!SDL_GetHintBoolean(SDL_HINT_HIDAPI_UDEV, true)) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "udev disabled by SDL_HINT_HIDAPI_UDEV"); + linux_enumeration_method = ENUMERATION_FALLBACK; + } else if (SDL_GetSandbox() != SDL_SANDBOX_NONE) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "Container detected, disabling HIDAPI udev integration"); + linux_enumeration_method = ENUMERATION_FALLBACK; + } else { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "Using udev for HIDAPI joystick device discovery"); + linux_enumeration_method = ENUMERATION_LIBUDEV; + } +#endif + + use_libusb_whitelist = SDL_GetHintBoolean(SDL_HINT_HIDAPI_LIBUSB_WHITELIST, + SDL_HINT_HIDAPI_LIBUSB_WHITELIST_DEFAULT); +#ifdef HAVE_LIBUSB + if (!SDL_GetHintBoolean(SDL_HINT_HIDAPI_LIBUSB, true)) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "libusb disabled with SDL_HINT_HIDAPI_LIBUSB"); + libusb_ctx.libhandle = NULL; + } else { + ++attempts; +#ifdef SDL_LIBUSB_DYNAMIC + libusb_ctx.libhandle = SDL_LoadObject(SDL_LIBUSB_DYNAMIC); +#else + libusb_ctx.libhandle = (void *)1; +#endif + if (libusb_ctx.libhandle != NULL) { + bool loaded = true; +#ifdef SDL_LIBUSB_DYNAMIC +#define LOAD_LIBUSB_SYMBOL(type, func) \ + if (!(libusb_ctx.func = (type)SDL_LoadFunction(libusb_ctx.libhandle, "libusb_" #func))) { \ + loaded = false; \ + } +#else +#define LOAD_LIBUSB_SYMBOL(type, func) \ + libusb_ctx.func = libusb_##func; +#endif + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_context **), init) + LOAD_LIBUSB_SYMBOL(void (LIBUSB_CALL *)(libusb_context *), exit) + LOAD_LIBUSB_SYMBOL(ssize_t (LIBUSB_CALL *)(libusb_context *, libusb_device ***), get_device_list) + LOAD_LIBUSB_SYMBOL(void (LIBUSB_CALL *)(libusb_device **, int), free_device_list) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device *, struct libusb_device_descriptor *), get_device_descriptor) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device *, struct libusb_config_descriptor **), get_active_config_descriptor) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device *, uint8_t, struct libusb_config_descriptor **), get_config_descriptor) + LOAD_LIBUSB_SYMBOL(void (LIBUSB_CALL *)(struct libusb_config_descriptor *), free_config_descriptor) + LOAD_LIBUSB_SYMBOL(uint8_t (LIBUSB_CALL *)(libusb_device *), get_bus_number) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device *dev, uint8_t *port_numbers, int port_numbers_len), get_port_numbers) + LOAD_LIBUSB_SYMBOL(uint8_t (LIBUSB_CALL *)(libusb_device *), get_device_address) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device *, libusb_device_handle **), open) + LOAD_LIBUSB_SYMBOL(void (LIBUSB_CALL *)(libusb_device_handle *), close) + LOAD_LIBUSB_SYMBOL(libusb_device * (LIBUSB_CALL *)(libusb_device_handle *dev_handle), get_device) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device_handle *, int), claim_interface) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device_handle *, int), release_interface) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device_handle *, int), kernel_driver_active) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device_handle *, int), detach_kernel_driver) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device_handle *, int), attach_kernel_driver) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device_handle *, int, int), set_interface_alt_setting) + LOAD_LIBUSB_SYMBOL(struct libusb_transfer * (LIBUSB_CALL *)(int), alloc_transfer) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(struct libusb_transfer *), submit_transfer) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(struct libusb_transfer *), cancel_transfer) + LOAD_LIBUSB_SYMBOL(void (LIBUSB_CALL *)(struct libusb_transfer *), free_transfer) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device_handle *, uint8_t, uint8_t, uint16_t, uint16_t, unsigned char *, uint16_t, unsigned int), control_transfer) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_device_handle *, unsigned char, unsigned char *, int, int *, unsigned int), interrupt_transfer) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_context *), handle_events) + LOAD_LIBUSB_SYMBOL(int (LIBUSB_CALL *)(libusb_context *, int *), handle_events_completed) + LOAD_LIBUSB_SYMBOL(const char * (LIBUSB_CALL *)(int), error_name) +#undef LOAD_LIBUSB_SYMBOL + + if (!loaded) { +#ifdef SDL_LIBUSB_DYNAMIC + SDL_UnloadObject(libusb_ctx.libhandle); +#endif + libusb_ctx.libhandle = NULL; + // SDL_LogWarn(SDL_LOG_CATEGORY_INPUT, SDL_LIBUSB_DYNAMIC " found but could not load function"); + } else if (LIBUSB_hid_init() < 0) { +#ifdef SDL_LIBUSB_DYNAMIC + SDL_UnloadObject(libusb_ctx.libhandle); +#endif + libusb_ctx.libhandle = NULL; + } else { + ++success; + } + } + } +#endif // HAVE_LIBUSB + +#ifdef HAVE_PLATFORM_BACKEND + ++attempts; +#ifdef SDL_PLATFORM_LINUX + udev_ctx = SDL_UDEV_GetUdevSyms(); +#endif // __LINUX __ + if (udev_ctx && PLATFORM_hid_init() == 0) { + ++success; + } +#endif // HAVE_PLATFORM_BACKEND + + if (attempts > 0 && success == 0) { + return -1; + } + +#if defined(SDL_PLATFORM_MACOS) && !defined(SDL_HIDAPI_DISABLED) + hid_darwin_set_open_exclusive(0); +#endif + + ++SDL_hidapi_refcount; + return 0; +} + +int SDL_hid_exit(void) +{ + int result = 0; + + if (SDL_hidapi_refcount == 0) { + return 0; + } + --SDL_hidapi_refcount; + if (SDL_hidapi_refcount > 0) { + return 0; + } + SDL_hidapi_refcount = 0; + +#ifndef SDL_HIDAPI_DISABLED + HIDAPI_ShutdownDiscovery(); +#endif + +#ifdef HAVE_PLATFORM_BACKEND + if (udev_ctx) { + result |= PLATFORM_hid_exit(); + } +#ifdef SDL_PLATFORM_LINUX + SDL_UDEV_ReleaseUdevSyms(); +#endif // __LINUX __ +#endif // HAVE_PLATFORM_BACKEND + +#ifdef HAVE_LIBUSB + if (libusb_ctx.libhandle) { + result |= LIBUSB_hid_exit(); +#ifdef SDL_LIBUSB_DYNAMIC + SDL_UnloadObject(libusb_ctx.libhandle); +#endif + libusb_ctx.libhandle = NULL; + } +#endif // HAVE_LIBUSB + + SDL_RemoveHintCallback(SDL_HINT_HIDAPI_ENUMERATE_ONLY_CONTROLLERS, OnlyControllersChanged, NULL); + SDL_RemoveHintCallback(SDL_HINT_HIDAPI_IGNORE_DEVICES, IgnoredDevicesChanged, NULL); + + if (SDL_hidapi_ignored_devices) { + SDL_free(SDL_hidapi_ignored_devices); + SDL_hidapi_ignored_devices = NULL; + } + + return result; +} + +Uint32 SDL_hid_device_change_count(void) +{ + Uint32 counter = 0; + +#ifndef SDL_HIDAPI_DISABLED + if (SDL_hidapi_refcount == 0 && SDL_hid_init() < 0) { + return 0; + } + + HIDAPI_UpdateDiscovery(); + + if (SDL_HIDAPI_discovery.m_unDeviceChangeCounter == 0) { + // Counter wrapped! + ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter; + } + counter = SDL_HIDAPI_discovery.m_unDeviceChangeCounter; + +#endif // !SDL_HIDAPI_DISABLED + + return counter; +} + +static void AddDeviceToEnumeration(const char *driver_name, struct hid_device_info *dev, struct SDL_hid_device_info **devs, struct SDL_hid_device_info **last) +{ + struct SDL_hid_device_info *new_dev; + +#ifdef DEBUG_HIDAPI + SDL_Log("Adding %s device to enumeration: %ls %ls 0x%.4hx/0x%.4hx/%d", + driver_name, dev->manufacturer_string, dev->product_string, dev->vendor_id, dev->product_id, dev->interface_number); +#else + (void)driver_name; +#endif + + new_dev = (struct SDL_hid_device_info *)SDL_malloc(sizeof(struct SDL_hid_device_info)); + if (new_dev == NULL) { + // Don't bother returning an error, get as many devices as possible + return; + } + CopyHIDDeviceInfo(dev, new_dev); + + if ((*last) != NULL) { + (*last)->next = new_dev; + } else { + *devs = new_dev; + } + *last = new_dev; +} + +#if defined(HAVE_LIBUSB) || defined(HAVE_PLATFORM_BACKEND) +static void RemoveDeviceFromEnumeration(const char *driver_name, struct hid_device_info *dev, struct hid_device_info **devs, void (*free_device_info)(struct hid_device_info *)) +{ + struct hid_device_info *last = NULL, *curr, *next; + + for (curr = *devs; curr; curr = next) { + next = curr->next; + + if (dev->vendor_id == curr->vendor_id && + dev->product_id == curr->product_id && + (dev->interface_number < 0 || curr->interface_number < 0 || dev->interface_number == curr->interface_number)) { +#ifdef DEBUG_HIDAPI + SDL_Log("Skipping %s device: %ls %ls 0x%.4hx/0x%.4hx/%d", + driver_name, curr->manufacturer_string, curr->product_string, curr->vendor_id, curr->product_id, curr->interface_number); +#else + (void)driver_name; +#endif + if (last) { + last->next = next; + } else { + *devs = next; + } + + curr->next = NULL; + free_device_info(curr); + continue; + } + last = curr; + } +} +#endif // HAVE_LIBUSB || HAVE_PLATFORM_BACKEND + +#ifdef HAVE_LIBUSB +static void RemoveNonWhitelistedDevicesFromEnumeration(struct hid_device_info **devs, void (*free_device_info)(struct hid_device_info *)) +{ + struct hid_device_info *last = NULL, *curr, *next; + + for (curr = *devs; curr; curr = next) { + next = curr->next; + + if (!IsInWhitelist(curr->vendor_id, curr->product_id)) { +#ifdef DEBUG_HIDAPI + SDL_Log("Device was not in libusb whitelist, skipping: %ls %ls 0x%.4hx/0x%.4hx/%d", + curr->manufacturer_string, curr->product_string, curr->vendor_id, curr->product_id, curr->interface_number); +#endif + if (last) { + last->next = next; + } else { + *devs = next; + } + + curr->next = NULL; + free_device_info(curr); + continue; + } + last = curr; + } +} +#endif // HAVE_LIBUSB + +struct SDL_hid_device_info *SDL_hid_enumerate(unsigned short vendor_id, unsigned short product_id) +{ + struct hid_device_info *driver_devs = NULL; + struct hid_device_info *usb_devs = NULL; + struct hid_device_info *raw_devs = NULL; + struct hid_device_info *dev; + struct SDL_hid_device_info *devs = NULL, *last = NULL; + + if (SDL_hidapi_refcount == 0 && SDL_hid_init() < 0) { + return NULL; + } + + // Collect the available devices +#ifdef HAVE_DRIVER_BACKEND + driver_devs = DRIVER_hid_enumerate(vendor_id, product_id); +#endif + +#ifdef HAVE_LIBUSB + if (libusb_ctx.libhandle) { + usb_devs = LIBUSB_hid_enumerate(vendor_id, product_id); + + if (use_libusb_whitelist) { + RemoveNonWhitelistedDevicesFromEnumeration(&usb_devs, LIBUSB_hid_free_enumeration); + } + } +#endif // HAVE_LIBUSB + +#ifdef HAVE_PLATFORM_BACKEND + if (udev_ctx) { + raw_devs = PLATFORM_hid_enumerate(vendor_id, product_id); + } +#endif + + // Highest priority are custom driver devices + for (dev = driver_devs; dev; dev = dev->next) { + AddDeviceToEnumeration("driver", dev, &devs, &last); +#ifdef HAVE_LIBUSB + RemoveDeviceFromEnumeration("libusb", dev, &usb_devs, LIBUSB_hid_free_enumeration); +#endif +#ifdef HAVE_PLATFORM_BACKEND + RemoveDeviceFromEnumeration("raw", dev, &raw_devs, PLATFORM_hid_free_enumeration); +#endif + } + + // If whitelist is in effect, libusb has priority, otherwise raw devices do + if (use_libusb_whitelist) { + for (dev = usb_devs; dev; dev = dev->next) { + AddDeviceToEnumeration("libusb", dev, &devs, &last); +#ifdef HAVE_PLATFORM_BACKEND + RemoveDeviceFromEnumeration("raw", dev, &raw_devs, PLATFORM_hid_free_enumeration); +#endif + } + for (dev = raw_devs; dev; dev = dev->next) { + AddDeviceToEnumeration("platform", dev, &devs, &last); + } + } else { + for (dev = raw_devs; dev; dev = dev->next) { + AddDeviceToEnumeration("raw", dev, &devs, &last); +#ifdef HAVE_LIBUSB + RemoveDeviceFromEnumeration("libusb", dev, &usb_devs, LIBUSB_hid_free_enumeration); +#endif + } + for (dev = usb_devs; dev; dev = dev->next) { + AddDeviceToEnumeration("libusb", dev, &devs, &last); + } + } + +#ifdef HAVE_DRIVER_BACKEND + DRIVER_hid_free_enumeration(driver_devs); +#endif +#ifdef HAVE_LIBUSB + LIBUSB_hid_free_enumeration(usb_devs); +#endif +#ifdef HAVE_PLATFORM_BACKEND + PLATFORM_hid_free_enumeration(raw_devs); +#endif + + return devs; +} + +void SDL_hid_free_enumeration(struct SDL_hid_device_info *devs) +{ + while (devs) { + struct SDL_hid_device_info *next = devs->next; + SDL_free(devs->path); + SDL_free(devs->serial_number); + SDL_free(devs->manufacturer_string); + SDL_free(devs->product_string); + SDL_free(devs); + devs = next; + } +} + +SDL_hid_device *SDL_hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) +{ +#if defined(HAVE_PLATFORM_BACKEND) || defined(HAVE_DRIVER_BACKEND) || defined(HAVE_LIBUSB) + void *pDevice = NULL; + + if (SDL_hidapi_refcount == 0 && SDL_hid_init() < 0) { + return NULL; + } + +#ifdef HAVE_PLATFORM_BACKEND + if (udev_ctx) { + pDevice = PLATFORM_hid_open(vendor_id, product_id, serial_number); + if (pDevice != NULL) { + return CreateHIDDeviceWrapper(pDevice, &PLATFORM_Backend); + } + } +#endif // HAVE_PLATFORM_BACKEND + +#ifdef HAVE_DRIVER_BACKEND + pDevice = DRIVER_hid_open(vendor_id, product_id, serial_number); + if (pDevice != NULL) { + return CreateHIDDeviceWrapper(pDevice, &DRIVER_Backend); + } +#endif // HAVE_DRIVER_BACKEND + +#ifdef HAVE_LIBUSB + if (libusb_ctx.libhandle != NULL) { + pDevice = LIBUSB_hid_open(vendor_id, product_id, serial_number); + if (pDevice != NULL) { + return CreateHIDDeviceWrapper(pDevice, &LIBUSB_Backend); + } + } +#endif // HAVE_LIBUSB + +#endif // HAVE_PLATFORM_BACKEND || HAVE_DRIVER_BACKEND || HAVE_LIBUSB + + return NULL; +} + +SDL_hid_device *SDL_hid_open_path(const char *path) +{ +#if defined(HAVE_PLATFORM_BACKEND) || defined(HAVE_DRIVER_BACKEND) || defined(HAVE_LIBUSB) + void *pDevice = NULL; + + if (SDL_hidapi_refcount == 0 && SDL_hid_init() < 0) { + return NULL; + } + +#ifdef HAVE_PLATFORM_BACKEND + if (udev_ctx) { + pDevice = PLATFORM_hid_open_path(path); + if (pDevice != NULL) { + return CreateHIDDeviceWrapper(pDevice, &PLATFORM_Backend); + } + } +#endif // HAVE_PLATFORM_BACKEND + +#ifdef HAVE_DRIVER_BACKEND + pDevice = DRIVER_hid_open_path(path); + if (pDevice != NULL) { + return CreateHIDDeviceWrapper(pDevice, &DRIVER_Backend); + } +#endif // HAVE_DRIVER_BACKEND + +#ifdef HAVE_LIBUSB + if (libusb_ctx.libhandle != NULL) { + pDevice = LIBUSB_hid_open_path(path); + if (pDevice != NULL) { + return CreateHIDDeviceWrapper(pDevice, &LIBUSB_Backend); + } + } +#endif // HAVE_LIBUSB + +#endif // HAVE_PLATFORM_BACKEND || HAVE_DRIVER_BACKEND || HAVE_LIBUSB + + return NULL; +} + +int SDL_hid_write(SDL_hid_device *device, const unsigned char *data, size_t length) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_write(device->device, data, length); +} + +int SDL_hid_read_timeout(SDL_hid_device *device, unsigned char *data, size_t length, int milliseconds) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_read_timeout(device->device, data, length, milliseconds); +} + +int SDL_hid_read(SDL_hid_device *device, unsigned char *data, size_t length) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_read(device->device, data, length); +} + +int SDL_hid_set_nonblocking(SDL_hid_device *device, int nonblock) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_set_nonblocking(device->device, nonblock); +} + +int SDL_hid_send_feature_report(SDL_hid_device *device, const unsigned char *data, size_t length) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_send_feature_report(device->device, data, length); +} + +int SDL_hid_get_feature_report(SDL_hid_device *device, unsigned char *data, size_t length) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_get_feature_report(device->device, data, length); +} + +int SDL_hid_get_input_report(SDL_hid_device *device, unsigned char *data, size_t length) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_get_input_report(device->device, data, length); +} + +int SDL_hid_close(SDL_hid_device *device) +{ + CHECK_DEVICE_MAGIC(device, -1); + + device->backend->hid_close(device->device); + DeleteHIDDeviceWrapper(device); + return 0; +} + +int SDL_hid_get_manufacturer_string(SDL_hid_device *device, wchar_t *string, size_t maxlen) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_get_manufacturer_string(device->device, string, maxlen); +} + +int SDL_hid_get_product_string(SDL_hid_device *device, wchar_t *string, size_t maxlen) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_get_product_string(device->device, string, maxlen); +} + +int SDL_hid_get_serial_number_string(SDL_hid_device *device, wchar_t *string, size_t maxlen) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_get_serial_number_string(device->device, string, maxlen); +} + +int SDL_hid_get_indexed_string(SDL_hid_device *device, int string_index, wchar_t *string, size_t maxlen) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_get_indexed_string(device->device, string_index, string, maxlen); +} + +SDL_hid_device_info *SDL_hid_get_device_info(SDL_hid_device *device) +{ + struct hid_device_info *info; + + CHECK_DEVICE_MAGIC(device, NULL); + + info = device->backend->hid_get_device_info(device->device); + if (info) { + CopyHIDDeviceInfo(info, &device->info); + return &device->info; + } else { + return NULL; + } +} + +int SDL_hid_get_report_descriptor(SDL_hid_device *device, unsigned char *buf, size_t buf_size) +{ + CHECK_DEVICE_MAGIC(device, -1); + + return device->backend->hid_get_report_descriptor(device->device, buf, buf_size); +} + +void SDL_hid_ble_scan(bool active) +{ +#if !defined(SDL_HIDAPI_DISABLED) && (defined(SDL_PLATFORM_IOS) || defined(SDL_PLATFORM_TVOS)) + extern void hid_ble_scan(int bStart); + hid_ble_scan(active); +#endif +} + +#ifdef HAVE_ENABLE_GAMECUBE_ADAPTORS +// This is needed to enable input for Nyko and EVORETRO GameCube adaptors +void SDL_EnableGameCubeAdaptors(void) +{ +#ifdef HAVE_LIBUSB + libusb_context *context = NULL; + libusb_device **devs = NULL; + libusb_device_handle *handle = NULL; + struct libusb_device_descriptor desc; + ssize_t i, num_devs; + int kernel_detached = 0; + + if (libusb_ctx.libhandle == NULL) { + return; + } + + if (libusb_ctx.init(&context) == 0) { + num_devs = libusb_ctx.get_device_list(context, &devs); + for (i = 0; i < num_devs; ++i) { + if (libusb_ctx.get_device_descriptor(devs[i], &desc) != 0) { + continue; + } + + if (desc.idVendor != 0x057e || desc.idProduct != 0x0337) { + continue; + } + + if (libusb_ctx.open(devs[i], &handle) != 0) { + continue; + } + + if (libusb_ctx.kernel_driver_active(handle, 0)) { + if (libusb_ctx.detach_kernel_driver(handle, 0) == 0) { + kernel_detached = 1; + } + } + + if (libusb_ctx.claim_interface(handle, 0) == 0) { + libusb_ctx.control_transfer(handle, 0x21, 11, 0x0001, 0, NULL, 0, 1000); + libusb_ctx.release_interface(handle, 0); + } + + if (kernel_detached) { + libusb_ctx.attach_kernel_driver(handle, 0); + } + + libusb_ctx.close(handle); + } + + libusb_ctx.free_device_list(devs, 1); + + libusb_ctx.exit(context); + } +#endif // HAVE_LIBUSB +} +#endif // HAVE_ENABLE_GAMECUBE_ADAPTORS diff --git a/thirdparty/sdl/hidapi/SDL_hidapi_android.h b/thirdparty/sdl/hidapi/SDL_hidapi_android.h new file mode 100644 index 00000000000..2f3851f8f54 --- /dev/null +++ b/thirdparty/sdl/hidapi/SDL_hidapi_android.h @@ -0,0 +1,26 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* The implementation for Android is in a separate .cpp file */ +#undef HIDAPI_H__ +#include "hidapi/hidapi.h" +#define HAVE_PLATFORM_BACKEND 1 +#define udev_ctx 1 diff --git a/thirdparty/sdl/hidapi/SDL_hidapi_c.h b/thirdparty/sdl/hidapi/SDL_hidapi_c.h new file mode 100644 index 00000000000..6d94f77eb95 --- /dev/null +++ b/thirdparty/sdl/hidapi/SDL_hidapi_c.h @@ -0,0 +1,35 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + + +/* Return true if the HIDAPI should ignore a device during enumeration */ +extern bool SDL_HIDAPI_ShouldIgnoreDevice(int bus_type, Uint16 vendor_id, Uint16 product_id, Uint16 usage_page, Uint16 usage); + +#ifdef SDL_JOYSTICK_HIDAPI +#ifdef HAVE_LIBUSB +#define HAVE_ENABLE_GAMECUBE_ADAPTORS +#endif + +#ifdef HAVE_ENABLE_GAMECUBE_ADAPTORS +extern void SDL_EnableGameCubeAdaptors(void); +#endif +#endif /* SDL_JOYSTICK_HIDAPI */ diff --git a/thirdparty/sdl/hidapi/SDL_hidapi_ios.h b/thirdparty/sdl/hidapi/SDL_hidapi_ios.h new file mode 100644 index 00000000000..f58f10d5a61 --- /dev/null +++ b/thirdparty/sdl/hidapi/SDL_hidapi_ios.h @@ -0,0 +1,26 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* The implementation for iOS and tvOS is in a separate .m file */ +#undef HIDAPI_H__ +#include "hidapi/hidapi.h" +#define HAVE_PLATFORM_BACKEND 1 +#define udev_ctx 1 diff --git a/thirdparty/sdl/hidapi/SDL_hidapi_libusb.h b/thirdparty/sdl/hidapi/SDL_hidapi_libusb.h new file mode 100644 index 00000000000..ed8b4a35d70 --- /dev/null +++ b/thirdparty/sdl/hidapi/SDL_hidapi_libusb.h @@ -0,0 +1,134 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* Define standard library functions in terms of SDL */ + +/* #pragma push_macro/pop_macro works correctly only as of gcc >= 4.4.3 + clang-3.0 _seems_ to be OK. */ +#pragma push_macro("calloc") +#pragma push_macro("malloc") +#pragma push_macro("realloc") +#pragma push_macro("free") +#pragma push_macro("iconv_t") +#pragma push_macro("iconv") +#pragma push_macro("iconv_open") +#pragma push_macro("iconv_close") +#pragma push_macro("setlocale") +#pragma push_macro("snprintf") +#pragma push_macro("strcmp") +#pragma push_macro("strdup") +#pragma push_macro("strncpy") +#pragma push_macro("tolower") +#pragma push_macro("wcscmp") +#pragma push_macro("wcsdup") +#pragma push_macro("wcsncpy") + +#undef calloc +#undef malloc +#undef realloc +#undef free +#undef iconv_t +#undef iconv +#undef iconv_open +#undef iconv_close +#undef setlocale +#undef snprintf +#undef strcmp +#undef strdup +#undef strncpy +#undef tolower +#undef wcscmp +#undef wcsdup +#undef wcsncpy + +#define calloc SDL_calloc +#define malloc SDL_malloc +#define realloc SDL_realloc +#define free SDL_free +#define iconv_t SDL_iconv_t +#ifndef ICONV_CONST +#define ICONV_CONST +#define UNDEF_ICONV_CONST +#endif +#define iconv(a,b,c,d,e) SDL_iconv(a, (const char **)b, c, d, e) +#define iconv_open SDL_iconv_open +#define iconv_close SDL_iconv_close +#define setlocale(X, Y) NULL +#define snprintf SDL_snprintf +#define strcmp SDL_strcmp +#define strdup SDL_strdup +#define strncpy SDL_strlcpy +#define tolower SDL_tolower +#define wcscmp SDL_wcscmp +#define wcsdup SDL_wcsdup +#define wcsncpy SDL_wcslcpy + + +#ifndef SDL_PLATFORM_FREEBSD +/* this is awkwardly inlined, so we need to re-implement it here + * so we can override the libusb_control_transfer call */ +static int SDL_libusb_get_string_descriptor(libusb_device_handle *dev, + uint8_t descriptor_index, uint16_t lang_id, + unsigned char *data, int length) +{ + return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN | 0x0, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8) | descriptor_index, lang_id, + data, (uint16_t)length, 1000); /* Endpoint 0 IN */ +} +#define libusb_get_string_descriptor SDL_libusb_get_string_descriptor +#endif /* SDL_PLATFORM_FREEBSD */ + +#define HIDAPI_THREAD_MODEL_INCLUDE "hidapi_thread_sdl.h" +#ifndef LIBUSB_API_VERSION +#ifdef LIBUSBX_API_VERSION +#define LIBUSB_API_VERSION LIBUSBX_API_VERSION +#else +#define LIBUSB_API_VERSION 0x0 +#endif +#endif +/* we need libusb >= 1.0.16 because of libusb_get_port_numbers */ +/* we don't need libusb_wrap_sys_device: */ +#define HIDAPI_TARGET_LIBUSB_API_VERSION 0x01000102 + +#undef HIDAPI_H__ +#include "libusb/hid.c" + +/* restore libc function macros */ +#ifdef UNDEF_ICONV_CONST +#undef ICONV_CONST +#undef UNDEF_ICONV_CONST +#endif +#pragma pop_macro("calloc") +#pragma pop_macro("malloc") +#pragma pop_macro("realloc") +#pragma pop_macro("free") +#pragma pop_macro("iconv_t") +#pragma pop_macro("iconv") +#pragma pop_macro("iconv_open") +#pragma pop_macro("iconv_close") +#pragma pop_macro("setlocale") +#pragma pop_macro("snprintf") +#pragma pop_macro("strcmp") +#pragma pop_macro("strdup") +#pragma pop_macro("strncpy") +#pragma pop_macro("tolower") +#pragma pop_macro("wcscmp") +#pragma pop_macro("wcsdup") +#pragma pop_macro("wcsncpy") diff --git a/thirdparty/sdl/hidapi/SDL_hidapi_linux.h b/thirdparty/sdl/hidapi/SDL_hidapi_linux.h new file mode 100644 index 00000000000..29723d7501b --- /dev/null +++ b/thirdparty/sdl/hidapi/SDL_hidapi_linux.h @@ -0,0 +1,47 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifdef SDL_USE_LIBUDEV +static const SDL_UDEV_Symbols *udev_ctx = NULL; + +#define udev_device_get_devnode udev_ctx->udev_device_get_devnode +#define udev_device_get_parent_with_subsystem_devtype udev_ctx->udev_device_get_parent_with_subsystem_devtype +#define udev_device_get_sysattr_value udev_ctx->udev_device_get_sysattr_value +#define udev_device_get_syspath udev_ctx->udev_device_get_syspath +#define udev_device_new_from_devnum udev_ctx->udev_device_new_from_devnum +#define udev_device_new_from_syspath udev_ctx->udev_device_new_from_syspath +#define udev_device_unref udev_ctx->udev_device_unref +#define udev_enumerate_add_match_subsystem udev_ctx->udev_enumerate_add_match_subsystem +#define udev_enumerate_get_list_entry udev_ctx->udev_enumerate_get_list_entry +#define udev_enumerate_new udev_ctx->udev_enumerate_new +#define udev_enumerate_scan_devices udev_ctx->udev_enumerate_scan_devices +#define udev_enumerate_unref udev_ctx->udev_enumerate_unref +#define udev_list_entry_get_name udev_ctx->udev_list_entry_get_name +#define udev_list_entry_get_next udev_ctx->udev_list_entry_get_next +#define udev_new udev_ctx->udev_new +#define udev_unref udev_ctx->udev_unref + +#undef HIDAPI_H__ +#define HIDAPI_ALLOW_BUILD_WORKAROUND_KERNEL_2_6_39 +#include "linux/hid.c" +#define HAVE_PLATFORM_BACKEND 1 + +#endif /* SDL_USE_LIBUDEV */ diff --git a/thirdparty/sdl/hidapi/SDL_hidapi_mac.h b/thirdparty/sdl/hidapi/SDL_hidapi_mac.h new file mode 100644 index 00000000000..820b67d6bc9 --- /dev/null +++ b/thirdparty/sdl/hidapi/SDL_hidapi_mac.h @@ -0,0 +1,25 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#undef HIDAPI_H__ +#include "mac/hid.c" +#define HAVE_PLATFORM_BACKEND 1 +#define udev_ctx 1 diff --git a/thirdparty/sdl/hidapi/SDL_hidapi_netbsd.h b/thirdparty/sdl/hidapi/SDL_hidapi_netbsd.h new file mode 100644 index 00000000000..1b39e225c1d --- /dev/null +++ b/thirdparty/sdl/hidapi/SDL_hidapi_netbsd.h @@ -0,0 +1,25 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#undef HIDAPI_H__ +#include "netbsd/hid.c" +#define HAVE_PLATFORM_BACKEND 1 +#define udev_ctx 1 diff --git a/thirdparty/sdl/hidapi/SDL_hidapi_steamxbox.h b/thirdparty/sdl/hidapi/SDL_hidapi_steamxbox.h new file mode 100644 index 00000000000..b6294a3b772 --- /dev/null +++ b/thirdparty/sdl/hidapi/SDL_hidapi_steamxbox.h @@ -0,0 +1,23 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#undef HIDAPI_H__ +#include "steamxbox/hid.c" diff --git a/thirdparty/sdl/hidapi/SDL_hidapi_windows.h b/thirdparty/sdl/hidapi/SDL_hidapi_windows.h new file mode 100644 index 00000000000..91f71c20793 --- /dev/null +++ b/thirdparty/sdl/hidapi/SDL_hidapi_windows.h @@ -0,0 +1,86 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* Define standard library functions in terms of SDL */ + +/* #pragma push_macro/pop_macro works correctly only as of gcc >= 4.4.3 + clang-3.0 _seems_ to be OK. */ +#pragma push_macro("calloc") +#pragma push_macro("free") +#pragma push_macro("malloc") +#pragma push_macro("memcmp") +#pragma push_macro("swprintf") +#pragma push_macro("towupper") +#pragma push_macro("wcscmp") +#pragma push_macro("_wcsdup") +#pragma push_macro("wcslen") +#pragma push_macro("wcsncpy") +#pragma push_macro("wcsstr") +#pragma push_macro("wcstol") + +#undef calloc +#undef free +#undef malloc +#undef memcmp +#undef swprintf +#undef towupper +#undef wcscmp +#undef _wcsdup +#undef wcslen +#undef wcsncpy +#undef wcsstr +#undef wcstol + +#define calloc SDL_calloc +#define free SDL_free +#define malloc SDL_malloc +#define memcmp SDL_memcmp +#define swprintf SDL_swprintf +#define towupper (wchar_t)SDL_toupper +#define wcscmp SDL_wcscmp +#define _wcsdup SDL_wcsdup +#define wcslen SDL_wcslen +#define wcsncpy SDL_wcslcpy +#define wcsstr SDL_wcsstr +#define wcstol SDL_wcstol + +// These functions conflict when linking both SDL and hidapi statically +#define hid_winapi_descriptor_reconstruct_pp_data SDL_hid_winapi_descriptor_reconstruct_pp_data +#define hid_winapi_get_container_id SDL_hid_winapi_get_container_id + +#undef HIDAPI_H__ +#include "windows/hid.c" +#define HAVE_PLATFORM_BACKEND 1 +#define udev_ctx 1 + +/* restore libc function macros */ +#pragma pop_macro("calloc") +#pragma pop_macro("free") +#pragma pop_macro("malloc") +#pragma pop_macro("memcmp") +#pragma pop_macro("swprintf") +#pragma pop_macro("towupper") +#pragma pop_macro("wcscmp") +#pragma pop_macro("_wcsdup") +#pragma pop_macro("wcslen") +#pragma pop_macro("wcsncpy") +#pragma pop_macro("wcsstr") +#pragma pop_macro("wcstol") diff --git a/thirdparty/sdl/hidapi/VERSION b/thirdparty/sdl/hidapi/VERSION new file mode 100644 index 00000000000..0548fb4e9b2 --- /dev/null +++ b/thirdparty/sdl/hidapi/VERSION @@ -0,0 +1 @@ +0.14.0 \ No newline at end of file diff --git a/thirdparty/sdl/hidapi/hidapi/hidapi.h b/thirdparty/sdl/hidapi/hidapi/hidapi.h new file mode 100644 index 00000000000..0e75f0de971 --- /dev/null +++ b/thirdparty/sdl/hidapi/hidapi/hidapi.h @@ -0,0 +1,634 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + Alan Ott + Signal 11 Software + + libusb/hidapi Team + + Copyright 2023, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +/** @file + * @defgroup API hidapi API + */ + +#ifndef HIDAPI_H__ +#define HIDAPI_H__ + +#include + +/* #480: this is to be refactored properly for v1.0 */ +#ifdef _WIN32 + #ifndef HID_API_NO_EXPORT_DEFINE + #define HID_API_EXPORT __declspec(dllexport) + #endif +#endif +#ifndef HID_API_EXPORT + #define HID_API_EXPORT /**< API export macro */ +#endif +/* To be removed in v1.0 */ +#define HID_API_CALL /**< API call macro */ + +#define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/ + +/** @brief Static/compile-time major version of the library. + + @ingroup API +*/ +#define HID_API_VERSION_MAJOR 0 +/** @brief Static/compile-time minor version of the library. + + @ingroup API +*/ +#define HID_API_VERSION_MINOR 14 +/** @brief Static/compile-time patch version of the library. + + @ingroup API +*/ +#define HID_API_VERSION_PATCH 0 + +/* Helper macros */ +#define HID_API_AS_STR_IMPL(x) #x +#define HID_API_AS_STR(x) HID_API_AS_STR_IMPL(x) +#define HID_API_TO_VERSION_STR(v1, v2, v3) HID_API_AS_STR(v1.v2.v3) + +/** @brief Coverts a version as Major/Minor/Patch into a number: + <8 bit major><16 bit minor><8 bit patch>. + + This macro was added in version 0.12.0. + + Convenient function to be used for compile-time checks, like: + @code{.c} + #if HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) + @endcode + + @ingroup API +*/ +#define HID_API_MAKE_VERSION(mj, mn, p) (((mj) << 24) | ((mn) << 8) | (p)) + +/** @brief Static/compile-time version of the library. + + This macro was added in version 0.12.0. + + @see @ref HID_API_MAKE_VERSION. + + @ingroup API +*/ +#define HID_API_VERSION HID_API_MAKE_VERSION(HID_API_VERSION_MAJOR, HID_API_VERSION_MINOR, HID_API_VERSION_PATCH) + +/** @brief Static/compile-time string version of the library. + + @ingroup API +*/ +#define HID_API_VERSION_STR HID_API_TO_VERSION_STR(HID_API_VERSION_MAJOR, HID_API_VERSION_MINOR, HID_API_VERSION_PATCH) + +/** @brief Maximum expected HID Report descriptor size in bytes. + + Since version 0.13.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 13, 0) + + @ingroup API +*/ +#define HID_API_MAX_REPORT_DESCRIPTOR_SIZE 4096 + +#ifdef __cplusplus +extern "C" { +#endif +#ifndef DEFINED_HID_TYPES +#define DEFINED_HID_TYPES + /** A structure to hold the version numbers. */ + struct hid_api_version { + int major; /**< major version number */ + int minor; /**< minor version number */ + int patch; /**< patch version number */ + }; + + struct hid_device_; + typedef struct hid_device_ hid_device; /**< opaque hidapi structure */ + + /** @brief HID underlying bus types. + + @ingroup API + */ + typedef enum { + /** Unknown bus type */ + HID_API_BUS_UNKNOWN = 0x00, + + /** USB bus + Specifications: + https://usb.org/hid */ + HID_API_BUS_USB = 0x01, + + /** Bluetooth or Bluetooth LE bus + Specifications: + https://www.bluetooth.com/specifications/specs/human-interface-device-profile-1-1-1/ + https://www.bluetooth.com/specifications/specs/hid-service-1-0/ + https://www.bluetooth.com/specifications/specs/hid-over-gatt-profile-1-0/ */ + HID_API_BUS_BLUETOOTH = 0x02, + + /** I2C bus + Specifications: + https://docs.microsoft.com/previous-versions/windows/hardware/design/dn642101(v=vs.85) */ + HID_API_BUS_I2C = 0x03, + + /** SPI bus + Specifications: + https://www.microsoft.com/download/details.aspx?id=103325 */ + HID_API_BUS_SPI = 0x04, + } hid_bus_type; + + /** hidapi info structure */ + struct hid_device_info { + /** Platform-specific device path */ + char *path; + /** Device Vendor ID */ + unsigned short vendor_id; + /** Device Product ID */ + unsigned short product_id; + /** Serial Number */ + wchar_t *serial_number; + /** Device Release Number in binary-coded decimal, + also known as Device Version Number */ + unsigned short release_number; + /** Manufacturer String */ + wchar_t *manufacturer_string; + /** Product string */ + wchar_t *product_string; + /** Usage Page for this Device/Interface + (Windows/Mac/hidraw only) */ + unsigned short usage_page; + /** Usage for this Device/Interface + (Windows/Mac/hidraw only) */ + unsigned short usage; + /** The USB interface which this logical device + represents. + + Valid only if the device is a USB HID device. + Set to -1 in all other cases. + */ + int interface_number; + + /** Pointer to the next device */ + struct hid_device_info *next; + + /** Underlying bus type + Since version 0.13.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 13, 0) + */ + hid_bus_type bus_type; + + /** Additional information about the USB interface. + (libusb only) */ + int interface_class; + int interface_subclass; + int interface_protocol; + }; + +#endif /* DEFINED_HID_TYPES */ + + + /** @brief Initialize the HIDAPI library. + + This function initializes the HIDAPI library. Calling it is not + strictly necessary, as it will be called automatically by + hid_enumerate() and any of the hid_open_*() functions if it is + needed. This function should be called at the beginning of + execution however, if there is a chance of HIDAPI handles + being opened by different threads simultaneously. + + @ingroup API + + @returns + This function returns 0 on success and -1 on error. + Call hid_error(NULL) to get the failure reason. + */ + int HID_API_EXPORT HID_API_CALL hid_init(void); + + /** @brief Finalize the HIDAPI library. + + This function frees all of the static data associated with + HIDAPI. It should be called at the end of execution to avoid + memory leaks. + + @ingroup API + + @returns + This function returns 0 on success and -1 on error. + */ + int HID_API_EXPORT HID_API_CALL hid_exit(void); + + /** @brief Enumerate the HID Devices. + + This function returns a linked list of all the HID devices + attached to the system which match vendor_id and product_id. + If @p vendor_id is set to 0 then any vendor matches. + If @p product_id is set to 0 then any product matches. + If @p vendor_id and @p product_id are both set to 0, then + all HID devices will be returned. + + @ingroup API + @param vendor_id The Vendor ID (VID) of the types of device + to open. + @param product_id The Product ID (PID) of the types of + device to open. + + @returns + This function returns a pointer to a linked list of type + struct #hid_device_info, containing information about the HID devices + attached to the system, + or NULL in the case of failure or if no HID devices present in the system. + Call hid_error(NULL) to get the failure reason. + + @note The returned value by this function must to be freed by calling hid_free_enumeration(), + when not needed anymore. + */ + struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id); + + /** @brief Free an enumeration Linked List + + This function frees a linked list created by hid_enumerate(). + + @ingroup API + @param devs Pointer to a list of struct_device returned from + hid_enumerate(). + */ + void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs); + + /** @brief Open a HID device using a Vendor ID (VID), Product ID + (PID) and optionally a serial number. + + If @p serial_number is NULL, the first device with the + specified VID and PID is opened. + + @ingroup API + @param vendor_id The Vendor ID (VID) of the device to open. + @param product_id The Product ID (PID) of the device to open. + @param serial_number The Serial Number of the device to open + (Optionally NULL). + + @returns + This function returns a pointer to a #hid_device object on + success or NULL on failure. + Call hid_error(NULL) to get the failure reason. + + @note The returned object must be freed by calling hid_close(), + when not needed anymore. + */ + HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number); + + /** @brief Open a HID device by its path name. + + The path name be determined by calling hid_enumerate(), or a + platform-specific path name can be used (eg: /dev/hidraw0 on + Linux). + + @ingroup API + @param path The path name of the device to open + + @returns + This function returns a pointer to a #hid_device object on + success or NULL on failure. + Call hid_error(NULL) to get the failure reason. + + @note The returned object must be freed by calling hid_close(), + when not needed anymore. + */ + HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path); + + /** @brief Write an Output report to a HID device. + + The first byte of @p data[] must contain the Report ID. For + devices which only support a single report, this must be set + to 0x0. The remaining bytes contain the report data. Since + the Report ID is mandatory, calls to hid_write() will always + contain one more byte than the report contains. For example, + if a hid report is 16 bytes long, 17 bytes must be passed to + hid_write(), the Report ID (or 0x0, for devices with a + single report), followed by the report data (16 bytes). In + this example, the length passed in would be 17. + + hid_write() will send the data on the first OUT endpoint, if + one exists. If it does not, it will send the data through + the Control Endpoint (Endpoint 0). + + @ingroup API + @param dev A device handle returned from hid_open(). + @param data The data to send, including the report number as + the first byte. + @param length The length in bytes of the data to send. + + @returns + This function returns the actual number of bytes written and + -1 on error. + Call hid_error(dev) to get the failure reason. + */ + int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length); + + /** @brief Read an Input report from a HID device with timeout. + + Input reports are returned + to the host through the INTERRUPT IN endpoint. The first byte will + contain the Report number if the device uses numbered reports. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param data A buffer to put the read data into. + @param length The number of bytes to read. For devices with + multiple reports, make sure to read an extra byte for + the report number. + @param milliseconds timeout in milliseconds or -1 for blocking wait. + + @returns + This function returns the actual number of bytes read and + -1 on error. + Call hid_error(dev) to get the failure reason. + If no packet was available to be read within + the timeout period, this function returns 0. + */ + int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds); + + /** @brief Read an Input report from a HID device. + + Input reports are returned + to the host through the INTERRUPT IN endpoint. The first byte will + contain the Report number if the device uses numbered reports. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param data A buffer to put the read data into. + @param length The number of bytes to read. For devices with + multiple reports, make sure to read an extra byte for + the report number. + + @returns + This function returns the actual number of bytes read and + -1 on error. + Call hid_error(dev) to get the failure reason. + If no packet was available to be read and + the handle is in non-blocking mode, this function returns 0. + */ + int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length); + + /** @brief Set the device handle to be non-blocking. + + In non-blocking mode calls to hid_read() will return + immediately with a value of 0 if there is no data to be + read. In blocking mode, hid_read() will wait (block) until + there is data to read before returning. + + Nonblocking can be turned on and off at any time. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param nonblock enable or not the nonblocking reads + - 1 to enable nonblocking + - 0 to disable nonblocking. + + @returns + This function returns 0 on success and -1 on error. + Call hid_error(dev) to get the failure reason. + */ + int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonblock); + + /** @brief Send a Feature report to the device. + + Feature reports are sent over the Control endpoint as a + Set_Report transfer. The first byte of @p data[] must + contain the Report ID. For devices which only support a + single report, this must be set to 0x0. The remaining bytes + contain the report data. Since the Report ID is mandatory, + calls to hid_send_feature_report() will always contain one + more byte than the report contains. For example, if a hid + report is 16 bytes long, 17 bytes must be passed to + hid_send_feature_report(): the Report ID (or 0x0, for + devices which do not use numbered reports), followed by the + report data (16 bytes). In this example, the length passed + in would be 17. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param data The data to send, including the report number as + the first byte. + @param length The length in bytes of the data to send, including + the report number. + + @returns + This function returns the actual number of bytes written and + -1 on error. + Call hid_error(dev) to get the failure reason. + */ + int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length); + + /** @brief Get a feature report from a HID device. + + Set the first byte of @p data[] to the Report ID of the + report to be read. Make sure to allow space for this + extra byte in @p data[]. Upon return, the first byte will + still contain the Report ID, and the report data will + start in data[1]. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param data A buffer to put the read data into, including + the Report ID. Set the first byte of @p data[] to the + Report ID of the report to be read, or set it to zero + if your device does not use numbered reports. + @param length The number of bytes to read, including an + extra byte for the report ID. The buffer can be longer + than the actual report. + + @returns + This function returns the number of bytes read plus + one for the report ID (which is still in the first + byte), or -1 on error. + Call hid_error(dev) to get the failure reason. + */ + int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length); + + /** @brief Get a input report from a HID device. + + Since version 0.10.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 10, 0) + + Set the first byte of @p data[] to the Report ID of the + report to be read. Make sure to allow space for this + extra byte in @p data[]. Upon return, the first byte will + still contain the Report ID, and the report data will + start in data[1]. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param data A buffer to put the read data into, including + the Report ID. Set the first byte of @p data[] to the + Report ID of the report to be read, or set it to zero + if your device does not use numbered reports. + @param length The number of bytes to read, including an + extra byte for the report ID. The buffer can be longer + than the actual report. + + @returns + This function returns the number of bytes read plus + one for the report ID (which is still in the first + byte), or -1 on error. + Call hid_error(dev) to get the failure reason. + */ + int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length); + + /** @brief Close a HID device. + + @ingroup API + @param dev A device handle returned from hid_open(). + */ + void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev); + + /** @brief Get The Manufacturer String from a HID device. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param string A wide string buffer to put the data into. + @param maxlen The length of the buffer in multiples of wchar_t. + + @returns + This function returns 0 on success and -1 on error. + Call hid_error(dev) to get the failure reason. + */ + int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen); + + /** @brief Get The Product String from a HID device. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param string A wide string buffer to put the data into. + @param maxlen The length of the buffer in multiples of wchar_t. + + @returns + This function returns 0 on success and -1 on error. + Call hid_error(dev) to get the failure reason. + */ + int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen); + + /** @brief Get The Serial Number String from a HID device. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param string A wide string buffer to put the data into. + @param maxlen The length of the buffer in multiples of wchar_t. + + @returns + This function returns 0 on success and -1 on error. + Call hid_error(dev) to get the failure reason. + */ + int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen); + + /** @brief Get The struct #hid_device_info from a HID device. + + Since version 0.13.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 13, 0) + + @ingroup API + @param dev A device handle returned from hid_open(). + + @returns + This function returns a pointer to the struct #hid_device_info + for this hid_device, or NULL in the case of failure. + Call hid_error(dev) to get the failure reason. + This struct is valid until the device is closed with hid_close(). + + @note The returned object is owned by the @p dev, and SHOULD NOT be freed by the user. + */ + struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_get_device_info(hid_device *dev); + + /** @brief Get a string from a HID device, based on its string index. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param string_index The index of the string to get. + @param string A wide string buffer to put the data into. + @param maxlen The length of the buffer in multiples of wchar_t. + + @returns + This function returns 0 on success and -1 on error. + Call hid_error(dev) to get the failure reason. + */ + int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen); + + /** @brief Get a report descriptor from a HID device. + + Since version 0.14.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 14, 0) + + User has to provide a preallocated buffer where descriptor will be copied to. + The recommended size for preallocated buffer is @ref HID_API_MAX_REPORT_DESCRIPTOR_SIZE bytes. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param buf The buffer to copy descriptor into. + @param buf_size The size of the buffer in bytes. + + @returns + This function returns non-negative number of bytes actually copied, or -1 on error. + */ + int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size); + + /** @brief Get a string describing the last error which occurred. + + This function is intended for logging/debugging purposes. + + This function guarantees to never return NULL. + If there was no error in the last function call - + the returned string clearly indicates that. + + Any HIDAPI function that can explicitly indicate an execution failure + (e.g. by an error code, or by returning NULL) - may set the error string, + to be returned by this function. + + Strings returned from hid_error() must not be freed by the user, + i.e. owned by HIDAPI library. + Device-specific error string may remain allocated at most until hid_close() is called. + Global error string may remain allocated at most until hid_exit() is called. + + @ingroup API + @param dev A device handle returned from hid_open(), + or NULL to get the last non-device-specific error + (e.g. for errors in hid_open() or hid_enumerate()). + + @returns + A string describing the last error (if any). + */ + HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *dev); + + /** @brief Get a runtime version of the library. + + This function is thread-safe. + + @ingroup API + + @returns + Pointer to statically allocated struct, that contains version. + */ + HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void); + + + /** @brief Get a runtime version string of the library. + + This function is thread-safe. + + @ingroup API + + @returns + Pointer to statically allocated string, that contains version string. + */ + HID_API_EXPORT const char* HID_API_CALL hid_version_str(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/thirdparty/sdl/hidapi/linux/hid.c b/thirdparty/sdl/hidapi/linux/hid.c new file mode 100644 index 00000000000..dbbb3277854 --- /dev/null +++ b/thirdparty/sdl/hidapi/linux/hid.c @@ -0,0 +1,1492 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + Alan Ott + Signal 11 Software + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +/* C */ +#include +#include +#include +#include +#include + +/* Unix */ +#include +#include +#include +#include +#include +#include +#include + +/* Linux */ +#include +#include +#include +#include + +#include "../hidapi/hidapi.h" + +#ifndef BUS_SPI +#define BUS_SPI 0x1C +#endif + +#ifdef HIDAPI_ALLOW_BUILD_WORKAROUND_KERNEL_2_6_39 +/* This definitions first appeared in Linux Kernel 2.6.39 in linux/hidraw.h. + hidapi doesn't support kernels older than that, + so we don't define macros below explicitly, to fail builds on old kernels. + For those who really need this as a workaround (e.g. to be able to build on old build machines), + can workaround by defining the macro above. +*/ +#ifndef HIDIOCSFEATURE +#define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len) +#endif +#ifndef HIDIOCGFEATURE +#define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len) +#endif + +#endif + + +// HIDIOCGINPUT is not defined in Linux kernel headers < 5.11. +// This definition is from hidraw.h in Linux >= 5.11. +// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f43d3870cafa2a0f3854c1819c8385733db8f9ae +#ifndef HIDIOCGINPUT +#define HIDIOCGINPUT(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x0A, len) +#endif + +struct hid_device_ { + int device_handle; + int blocking; + int needs_ble_hack; + wchar_t *last_error_str; + struct hid_device_info* device_info; +}; + +static struct hid_api_version api_version = { + .major = HID_API_VERSION_MAJOR, + .minor = HID_API_VERSION_MINOR, + .patch = HID_API_VERSION_PATCH +}; + +static wchar_t *last_global_error_str = NULL; + + +static hid_device *new_hid_device(void) +{ + hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device)); + if (dev == NULL) { + return NULL; + } + + dev->device_handle = -1; + dev->blocking = 1; + dev->last_error_str = NULL; + dev->device_info = NULL; + + return dev; +} + + +/* The caller must free the returned string with free(). */ +static wchar_t *utf8_to_wchar_t(const char *utf8) +{ + wchar_t *ret = NULL; + + if (utf8) { + size_t wlen = mbstowcs(NULL, utf8, 0); + if ((size_t) -1 == wlen) { + return wcsdup(L""); + } + ret = (wchar_t*) calloc(wlen+1, sizeof(wchar_t)); + if (ret == NULL) { + /* as much as we can do at this point */ + return NULL; + } + mbstowcs(ret, utf8, wlen+1); + ret[wlen] = 0x0000; + } + + return ret; +} + + +/* Makes a copy of the given error message (and decoded according to the + * currently locale) into the wide string pointer pointed by error_str. + * The last stored error string is freed. + * Use register_error_str(NULL) to free the error message completely. */ +static void register_error_str(wchar_t **error_str, const char *msg) +{ + free(*error_str); +#ifdef HIDAPI_USING_SDL_RUNTIME + /* Thread-safe error handling */ + if (msg) { + SDL_SetError("%s", msg); + } else { + SDL_ClearError(); + } +#else + *error_str = utf8_to_wchar_t(msg); +#endif +} + +/* Semilar to register_error_str, but allows passing a format string with va_list args into this function. */ +static void register_error_str_vformat(wchar_t **error_str, const char *format, va_list args) +{ + char msg[256]; + vsnprintf(msg, sizeof(msg), format, args); + + register_error_str(error_str, msg); +} + +/* Set the last global error to be reported by hid_error(NULL). + * The given error message will be copied (and decoded according to the + * currently locale, so do not pass in string constants). + * The last stored global error message is freed. + * Use register_global_error(NULL) to indicate "no error". */ +static void register_global_error(const char *msg) +{ + register_error_str(&last_global_error_str, msg); +} + +/* Similar to register_global_error, but allows passing a format string into this function. */ +static void register_global_error_format(const char *format, ...) +{ + va_list args; + va_start(args, format); + register_error_str_vformat(&last_global_error_str, format, args); + va_end(args); +} + +/* Set the last error for a device to be reported by hid_error(dev). + * The given error message will be copied (and decoded according to the + * currently locale, so do not pass in string constants). + * The last stored device error message is freed. + * Use register_device_error(dev, NULL) to indicate "no error". */ +static void register_device_error(hid_device *dev, const char *msg) +{ + register_error_str(&dev->last_error_str, msg); +} + +/* Similar to register_device_error, but you can pass a format string into this function. */ +static void register_device_error_format(hid_device *dev, const char *format, ...) +{ + va_list args; + va_start(args, format); + register_error_str_vformat(&dev->last_error_str, format, args); + va_end(args); +} + +/* Get an attribute value from a udev_device and return it as a whar_t + string. The returned string must be freed with free() when done.*/ +static wchar_t *copy_udev_string(struct udev_device *dev, const char *udev_name) +{ + return utf8_to_wchar_t(udev_device_get_sysattr_value(dev, udev_name)); +} + +/* + * Gets the size of the HID item at the given position + * Returns 1 if successful, 0 if an invalid key + * Sets data_len and key_size when successful + */ +static int get_hid_item_size(const __u8 *report_descriptor, __u32 size, unsigned int pos, int *data_len, int *key_size) +{ + int key = report_descriptor[pos]; + int size_code; + + /* + * This is a Long Item. The next byte contains the + * length of the data section (value) for this key. + * See the HID specification, version 1.11, section + * 6.2.2.3, titled "Long Items." + */ + if ((key & 0xf0) == 0xf0) { + if (pos + 1 < size) + { + *data_len = report_descriptor[pos + 1]; + *key_size = 3; + return 1; + } + *data_len = 0; /* malformed report */ + *key_size = 0; + } + + /* + * This is a Short Item. The bottom two bits of the + * key contain the size code for the data section + * (value) for this key. Refer to the HID + * specification, version 1.11, section 6.2.2.2, + * titled "Short Items." + */ + size_code = key & 0x3; + switch (size_code) { + case 0: + case 1: + case 2: + *data_len = size_code; + *key_size = 1; + return 1; + case 3: + *data_len = 4; + *key_size = 1; + return 1; + default: + /* Can't ever happen since size_code is & 0x3 */ + *data_len = 0; + *key_size = 0; + break; + } + + /* malformed report */ + return 0; +} + +/* + * Get bytes from a HID Report Descriptor. + * Only call with a num_bytes of 0, 1, 2, or 4. + */ +static __u32 get_hid_report_bytes(const __u8 *rpt, size_t len, size_t num_bytes, size_t cur) +{ + /* Return if there aren't enough bytes. */ + if (cur + num_bytes >= len) + return 0; + + if (num_bytes == 0) + return 0; + else if (num_bytes == 1) + return rpt[cur + 1]; + else if (num_bytes == 2) + return (rpt[cur + 2] * 256 + rpt[cur + 1]); + else if (num_bytes == 4) + return ( + rpt[cur + 4] * 0x01000000 + + rpt[cur + 3] * 0x00010000 + + rpt[cur + 2] * 0x00000100 + + rpt[cur + 1] * 0x00000001 + ); + else + return 0; +} + +/* + * Iterates until the end of a Collection. + * Assumes that *pos is exactly at the beginning of a Collection. + * Skips all nested Collection, i.e. iterates until the end of current level Collection. + * + * The return value is non-0 when an end of current Collection is found, + * 0 when error is occurred (broken Descriptor, end of a Collection is found before its begin, + * or no Collection is found at all). + */ +static int hid_iterate_over_collection(const __u8 *report_descriptor, __u32 size, unsigned int *pos, int *data_len, int *key_size) +{ + int collection_level = 0; + + while (*pos < size) { + int key = report_descriptor[*pos]; + int key_cmd = key & 0xfc; + + /* Determine data_len and key_size */ + if (!get_hid_item_size(report_descriptor, size, *pos, data_len, key_size)) + return 0; /* malformed report */ + + switch (key_cmd) { + case 0xa0: /* Collection 6.2.2.4 (Main) */ + collection_level++; + break; + case 0xc0: /* End Collection 6.2.2.4 (Main) */ + collection_level--; + break; + } + + if (collection_level < 0) { + /* Broken descriptor or someone is using this function wrong, + * i.e. should be called exactly at the collection start */ + return 0; + } + + if (collection_level == 0) { + /* Found it! + * Also possible when called not at the collection start, but should not happen if used correctly */ + return 1; + } + + *pos += *data_len + *key_size; + } + + return 0; /* Did not find the end of a Collection */ +} + +struct hid_usage_iterator { + unsigned int pos; + int usage_page_found; + unsigned short usage_page; +}; + +/* + * Retrieves the device's Usage Page and Usage from the report descriptor. + * The algorithm returns the current Usage Page/Usage pair whenever a new + * Collection is found and a Usage Local Item is currently in scope. + * Usage Local Items are consumed by each Main Item (See. 6.2.2.8). + * The algorithm should give similar results as Apple's: + * https://developer.apple.com/documentation/iokit/kiohiddeviceusagepairskey?language=objc + * Physical Collections are also matched (macOS does the same). + * + * This function can be called repeatedly until it returns non-0 + * Usage is found. pos is the starting point (initially 0) and will be updated + * to the next search position. + * + * The return value is 0 when a pair is found. + * 1 when finished processing descriptor. + * -1 on a malformed report. + */ +static int get_next_hid_usage(const __u8 *report_descriptor, __u32 size, struct hid_usage_iterator *ctx, unsigned short *usage_page, unsigned short *usage) +{ + int data_len, key_size; + int initial = ctx->pos == 0; /* Used to handle case where no top-level application collection is defined */ + + int usage_found = 0; + + while (ctx->pos < size) { + int key = report_descriptor[ctx->pos]; + int key_cmd = key & 0xfc; + + /* Determine data_len and key_size */ + if (!get_hid_item_size(report_descriptor, size, ctx->pos, &data_len, &key_size)) + return -1; /* malformed report */ + + switch (key_cmd) { + case 0x4: /* Usage Page 6.2.2.7 (Global) */ + ctx->usage_page = get_hid_report_bytes(report_descriptor, size, data_len, ctx->pos); + ctx->usage_page_found = 1; + break; + + case 0x8: /* Usage 6.2.2.8 (Local) */ + if (data_len == 4) { /* Usages 5.5 / Usage Page 6.2.2.7 */ + ctx->usage_page = get_hid_report_bytes(report_descriptor, size, 2, ctx->pos + 2); + ctx->usage_page_found = 1; + *usage = get_hid_report_bytes(report_descriptor, size, 2, ctx->pos); + usage_found = 1; + } + else { + *usage = get_hid_report_bytes(report_descriptor, size, data_len, ctx->pos); + usage_found = 1; + } + break; + + case 0xa0: /* Collection 6.2.2.4 (Main) */ + if (!hid_iterate_over_collection(report_descriptor, size, &ctx->pos, &data_len, &key_size)) { + return -1; + } + + /* A pair is valid - to be reported when Collection is found */ + if (usage_found && ctx->usage_page_found) { + *usage_page = ctx->usage_page; + return 0; + } + + break; + } + + /* Skip over this key and its associated data */ + ctx->pos += data_len + key_size; + } + + /* If no top-level application collection is found and usage page/usage pair is found, pair is valid + https://docs.microsoft.com/en-us/windows-hardware/drivers/hid/top-level-collections */ + if (initial && usage_found && ctx->usage_page_found) { + *usage_page = ctx->usage_page; + return 0; /* success */ + } + + return 1; /* finished processing */ +} + +/* + * Retrieves the hidraw report descriptor from a file. + * When using this form, /device/report_descriptor, elevated privileges are not required. + */ +static int get_hid_report_descriptor(const char *rpt_path, struct hidraw_report_descriptor *rpt_desc) +{ + int rpt_handle; + ssize_t res; + + rpt_handle = open(rpt_path, O_RDONLY | O_CLOEXEC); + if (rpt_handle < 0) { + register_global_error_format("open failed (%s): %s", rpt_path, strerror(errno)); + return -1; + } + + /* + * Read in the Report Descriptor + * The sysfs file has a maximum size of 4096 (which is the same as HID_MAX_DESCRIPTOR_SIZE) so we should always + * be ok when reading the descriptor. + * In practice if the HID descriptor is any larger I suspect many other things will break. + */ + memset(rpt_desc, 0x0, sizeof(*rpt_desc)); + res = read(rpt_handle, rpt_desc->value, HID_MAX_DESCRIPTOR_SIZE); + if (res < 0) { + register_global_error_format("read failed (%s): %s", rpt_path, strerror(errno)); + } + rpt_desc->size = (__u32) res; + + close(rpt_handle); + return (int) res; +} + +/* return size of the descriptor, or -1 on failure */ +static int get_hid_report_descriptor_from_sysfs(const char *sysfs_path, struct hidraw_report_descriptor *rpt_desc) +{ + int res = -1; + /* Construct /device/report_descriptor */ + size_t rpt_path_len = strlen(sysfs_path) + 25 + 1; + char* rpt_path = (char*) calloc(1, rpt_path_len); + snprintf(rpt_path, rpt_path_len, "%s/device/report_descriptor", sysfs_path); + + res = get_hid_report_descriptor(rpt_path, rpt_desc); + free(rpt_path); + + return res; +} + +/* return non-zero if successfully parsed */ +static int parse_hid_vid_pid_from_uevent(const char *uevent, unsigned *bus_type, unsigned short *vendor_id, unsigned short *product_id) +{ + char tmp[1024]; + size_t uevent_len = strlen(uevent); + if (uevent_len > sizeof(tmp) - 1) + uevent_len = sizeof(tmp) - 1; + memcpy(tmp, uevent, uevent_len); + tmp[uevent_len] = '\0'; + + char *saveptr = NULL; + char *line; + char *key; + char *value; + + line = strtok_r(tmp, "\n", &saveptr); + while (line != NULL) { + /* line: "KEY=value" */ + key = line; + value = strchr(line, '='); + if (!value) { + goto next_line; + } + *value = '\0'; + value++; + + if (strcmp(key, "HID_ID") == 0) { + /** + * type vendor product + * HID_ID=0003:000005AC:00008242 + **/ + int ret = sscanf(value, "%x:%hx:%hx", bus_type, vendor_id, product_id); + if (ret == 3) { + return 1; + } + } + +next_line: + line = strtok_r(NULL, "\n", &saveptr); + } + + register_global_error("Couldn't find/parse HID_ID"); + return 0; +} + +/* return non-zero if successfully parsed */ +static int parse_hid_vid_pid_from_uevent_path(const char *uevent_path, unsigned *bus_type, unsigned short *vendor_id, unsigned short *product_id) +{ + int handle; + ssize_t res; + + handle = open(uevent_path, O_RDONLY | O_CLOEXEC); + if (handle < 0) { + register_global_error_format("open failed (%s): %s", uevent_path, strerror(errno)); + return 0; + } + + char buf[1024]; + res = read(handle, buf, sizeof(buf) - 1); /* -1 for '\0' at the end */ + close(handle); + + if (res < 0) { + register_global_error_format("read failed (%s): %s", uevent_path, strerror(errno)); + return 0; + } + + buf[res] = '\0'; + return parse_hid_vid_pid_from_uevent(buf, bus_type, vendor_id, product_id); +} + +/* return non-zero if successfully read/parsed */ +static int parse_hid_vid_pid_from_sysfs(const char *sysfs_path, unsigned *bus_type, unsigned short *vendor_id, unsigned short *product_id) +{ + int res = 0; + /* Construct /device/uevent */ + size_t uevent_path_len = strlen(sysfs_path) + 14 + 1; + char* uevent_path = (char*) calloc(1, uevent_path_len); + snprintf(uevent_path, uevent_path_len, "%s/device/uevent", sysfs_path); + + res = parse_hid_vid_pid_from_uevent_path(uevent_path, bus_type, vendor_id, product_id); + free(uevent_path); + + return res; +} + +static int get_hid_report_descriptor_from_hidraw(hid_device *dev, struct hidraw_report_descriptor *rpt_desc) +{ + int desc_size = 0; + + /* Get Report Descriptor Size */ + int res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size); + if (res < 0) { + register_device_error_format(dev, "ioctl(GRDESCSIZE): %s", strerror(errno)); + return res; + } + + /* Get Report Descriptor */ + memset(rpt_desc, 0x0, sizeof(*rpt_desc)); + rpt_desc->size = desc_size; + res = ioctl(dev->device_handle, HIDIOCGRDESC, rpt_desc); + if (res < 0) { + register_device_error_format(dev, "ioctl(GRDESC): %s", strerror(errno)); + } + + return res; +} + +/* + * The caller is responsible for free()ing the (newly-allocated) character + * strings pointed to by serial_number_utf8 and product_name_utf8 after use. + */ +static int parse_uevent_info(const char *uevent, unsigned *bus_type, + unsigned short *vendor_id, unsigned short *product_id, + char **serial_number_utf8, char **product_name_utf8) +{ + char tmp[1024]; + + if (!uevent) { + return 0; + } + + size_t uevent_len = strlen(uevent); + if (uevent_len > sizeof(tmp) - 1) + uevent_len = sizeof(tmp) - 1; + memcpy(tmp, uevent, uevent_len); + tmp[uevent_len] = '\0'; + + char *saveptr = NULL; + char *line; + char *key; + char *value; + + int found_id = 0; + int found_serial = 0; + int found_name = 0; + + line = strtok_r(tmp, "\n", &saveptr); + while (line != NULL) { + /* line: "KEY=value" */ + key = line; + value = strchr(line, '='); + if (!value) { + goto next_line; + } + *value = '\0'; + value++; + + if (strcmp(key, "HID_ID") == 0) { + /** + * type vendor product + * HID_ID=0003:000005AC:00008242 + **/ + int ret = sscanf(value, "%x:%hx:%hx", bus_type, vendor_id, product_id); + if (ret == 3) { + found_id = 1; + } + } else if (strcmp(key, "HID_NAME") == 0) { + /* The caller has to free the product name */ + *product_name_utf8 = strdup(value); + found_name = 1; + } else if (strcmp(key, "HID_UNIQ") == 0) { + /* The caller has to free the serial number */ + *serial_number_utf8 = strdup(value); + found_serial = 1; + } + +next_line: + line = strtok_r(NULL, "\n", &saveptr); + } + + return (found_id && found_name && found_serial); +} + +static int is_BLE(hid_device *dev) +{ + struct udev *udev; + struct udev_device *udev_dev, *hid_dev; + struct stat s; + int ret; + + /* Create the udev object */ + udev = udev_new(); + if (!udev) { + printf("Can't create udev\n"); + return -1; + } + + /* Get the dev_t (major/minor numbers) from the file handle. */ + if (fstat(dev->device_handle, &s) < 0) { + udev_unref(udev); + return -1; + } + + /* Open a udev device from the dev_t. 'c' means character device. */ + ret = 0; + udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev); + if (udev_dev) { + hid_dev = udev_device_get_parent_with_subsystem_devtype( + udev_dev, + "hid", + NULL); + if (hid_dev) { + unsigned short dev_vid = 0; + unsigned short dev_pid = 0; + unsigned bus_type = 0; + char *serial_number_utf8 = NULL; + char *product_name_utf8 = NULL; + + parse_uevent_info( + udev_device_get_sysattr_value(hid_dev, "uevent"), + &bus_type, + &dev_vid, + &dev_pid, + &serial_number_utf8, + &product_name_utf8); + free(serial_number_utf8); + free(product_name_utf8); + + if (bus_type == BUS_BLUETOOTH) { + /* Right now the Steam Controller is the only BLE device that we send feature reports to */ + if (dev_vid == 0x28de /* Valve */) { + ret = 1; + } + } + + /* hid_dev doesn't need to be (and can't be) unref'd. + I'm not sure why, but it'll throw double-free() errors. */ + } + udev_device_unref(udev_dev); + } + + udev_unref(udev); + + return ret; +} + + +static struct hid_device_info * create_device_info_for_device(struct udev_device *raw_dev) +{ + struct hid_device_info *root = NULL; + struct hid_device_info *cur_dev = NULL; + + const char *sysfs_path; + const char *dev_path; + const char *str; + struct udev_device *hid_dev; /* The device's HID udev node. */ + struct udev_device *usb_dev; /* The device's USB udev node. */ + struct udev_device *intf_dev; /* The device's interface (in the USB sense). */ + unsigned short dev_vid; + unsigned short dev_pid; + char *serial_number_utf8 = NULL; + char *product_name_utf8 = NULL; + unsigned bus_type; + int result; + struct hidraw_report_descriptor report_desc; + + sysfs_path = udev_device_get_syspath(raw_dev); + dev_path = udev_device_get_devnode(raw_dev); + + hid_dev = udev_device_get_parent_with_subsystem_devtype( + raw_dev, + "hid", + NULL); + + if (!hid_dev) { + /* Unable to find parent hid device. */ + goto end; + } + + result = parse_uevent_info( + udev_device_get_sysattr_value(hid_dev, "uevent"), + &bus_type, + &dev_vid, + &dev_pid, + &serial_number_utf8, + &product_name_utf8); + + if (!result) { + /* parse_uevent_info() failed for at least one field. */ + goto end; + } + + /* Filter out unhandled devices right away */ + switch (bus_type) { + case BUS_BLUETOOTH: + case BUS_I2C: + case BUS_USB: + case BUS_SPI: + break; + + default: + goto end; + } + + /* Create the record. */ + root = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info)); + if (!root) + goto end; + + cur_dev = root; + + /* Fill out the record */ + cur_dev->next = NULL; + cur_dev->path = dev_path? strdup(dev_path): NULL; + + /* VID/PID */ + cur_dev->vendor_id = dev_vid; + cur_dev->product_id = dev_pid; + + /* Serial Number */ + cur_dev->serial_number = utf8_to_wchar_t(serial_number_utf8); + + /* Release Number */ + cur_dev->release_number = 0x0; + + /* Interface Number */ + cur_dev->interface_number = -1; + + switch (bus_type) { + case BUS_USB: + /* The device pointed to by raw_dev contains information about + the hidraw device. In order to get information about the + USB device, get the parent device with the + subsystem/devtype pair of "usb"/"usb_device". This will + be several levels up the tree, but the function will find + it. */ + usb_dev = udev_device_get_parent_with_subsystem_devtype( + raw_dev, + "usb", + "usb_device"); + + /* uhid USB devices + * Since this is a virtual hid interface, no USB information will + * be available. */ + if (!usb_dev) { + /* Manufacturer and Product strings */ + cur_dev->manufacturer_string = wcsdup(L""); + cur_dev->product_string = utf8_to_wchar_t(product_name_utf8); + break; + } + + cur_dev->manufacturer_string = copy_udev_string(usb_dev, "manufacturer"); + cur_dev->product_string = copy_udev_string(usb_dev, "product"); + + cur_dev->bus_type = HID_API_BUS_USB; + + str = udev_device_get_sysattr_value(usb_dev, "bcdDevice"); + cur_dev->release_number = (str)? strtol(str, NULL, 16): 0x0; + + /* Get a handle to the interface's udev node. */ + intf_dev = udev_device_get_parent_with_subsystem_devtype( + raw_dev, + "usb", + "usb_interface"); + if (intf_dev) { + str = udev_device_get_sysattr_value(intf_dev, "bInterfaceNumber"); + cur_dev->interface_number = (str)? strtol(str, NULL, 16): -1; + } + + break; + + case BUS_BLUETOOTH: + cur_dev->manufacturer_string = wcsdup(L""); + cur_dev->product_string = utf8_to_wchar_t(product_name_utf8); + + cur_dev->bus_type = HID_API_BUS_BLUETOOTH; + + break; + case BUS_I2C: + cur_dev->manufacturer_string = wcsdup(L""); + cur_dev->product_string = utf8_to_wchar_t(product_name_utf8); + + cur_dev->bus_type = HID_API_BUS_I2C; + + break; + + case BUS_SPI: + cur_dev->manufacturer_string = wcsdup(L""); + cur_dev->product_string = utf8_to_wchar_t(product_name_utf8); + + cur_dev->bus_type = HID_API_BUS_SPI; + + break; + + default: + /* Unknown device type - this should never happen, as we + * check for USB and Bluetooth devices above */ + break; + } + + /* Usage Page and Usage */ + result = get_hid_report_descriptor_from_sysfs(sysfs_path, &report_desc); + if (result >= 0) { + unsigned short page = 0, usage = 0; + struct hid_usage_iterator usage_iterator; + memset(&usage_iterator, 0, sizeof(usage_iterator)); + + /* + * Parse the first usage and usage page + * out of the report descriptor. + */ + if (!get_next_hid_usage(report_desc.value, report_desc.size, &usage_iterator, &page, &usage)) { + cur_dev->usage_page = page; + cur_dev->usage = usage; + } + + /* + * Parse any additional usage and usage pages + * out of the report descriptor. + */ + while (!get_next_hid_usage(report_desc.value, report_desc.size, &usage_iterator, &page, &usage)) { + /* Create new record for additional usage pairs */ + struct hid_device_info *tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info)); + struct hid_device_info *prev_dev = cur_dev; + + if (!tmp) + continue; + cur_dev->next = tmp; + cur_dev = tmp; + + /* Update fields */ + cur_dev->path = dev_path? strdup(dev_path): NULL; + cur_dev->vendor_id = dev_vid; + cur_dev->product_id = dev_pid; + cur_dev->serial_number = prev_dev->serial_number? wcsdup(prev_dev->serial_number): NULL; + cur_dev->release_number = prev_dev->release_number; + cur_dev->interface_number = prev_dev->interface_number; + cur_dev->manufacturer_string = prev_dev->manufacturer_string? wcsdup(prev_dev->manufacturer_string): NULL; + cur_dev->product_string = prev_dev->product_string? wcsdup(prev_dev->product_string): NULL; + cur_dev->usage_page = page; + cur_dev->usage = usage; + cur_dev->bus_type = prev_dev->bus_type; + } + } + +#ifdef HIDAPI_IGNORE_DEVICE + { + struct hid_device_info *prev_dev = NULL; + + cur_dev = root; + while (cur_dev) { + if (HIDAPI_IGNORE_DEVICE(cur_dev->bus_type, cur_dev->vendor_id, cur_dev->product_id, cur_dev->usage_page, cur_dev->usage)) { + struct hid_device_info *tmp = cur_dev; + + cur_dev = tmp->next; + if (prev_dev) { + prev_dev->next = cur_dev; + } else { + root = cur_dev; + } + tmp->next = NULL; + + hid_free_enumeration(tmp); + } else { + prev_dev = cur_dev; + cur_dev = cur_dev->next; + } + } + } +#endif + +end: + free(serial_number_utf8); + free(product_name_utf8); + + return root; +} + +static struct hid_device_info * create_device_info_for_hid_device(hid_device *dev) { + struct udev *udev; + struct udev_device *udev_dev; + struct stat s; + int ret = -1; + struct hid_device_info *root = NULL; + + register_device_error(dev, NULL); + + /* Get the dev_t (major/minor numbers) from the file handle. */ + ret = fstat(dev->device_handle, &s); + if (-1 == ret) { + register_device_error(dev, "Failed to stat device handle"); + return NULL; + } + + /* Create the udev object */ + udev = udev_new(); + if (!udev) { + register_device_error(dev, "Couldn't create udev context"); + return NULL; + } + + /* Open a udev device from the dev_t. 'c' means character device. */ + udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev); + if (udev_dev) { + root = create_device_info_for_device(udev_dev); + } + + if (!root) { + /* TODO: have a better error reporting via create_device_info_for_device */ + register_device_error(dev, "Couldn't create hid_device_info"); + } + + udev_device_unref(udev_dev); + udev_unref(udev); + + return root; +} + +HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void) +{ + return &api_version; +} + +HID_API_EXPORT const char* HID_API_CALL hid_version_str(void) +{ + return HID_API_VERSION_STR; +} + +int HID_API_EXPORT hid_init(void) +{ + const char *locale; + + /* indicate no error */ + register_global_error(NULL); + + /* Set the locale if it's not set. */ + locale = setlocale(LC_CTYPE, NULL); + if (!locale) + setlocale(LC_CTYPE, ""); + + return 0; +} + +int HID_API_EXPORT hid_exit(void) +{ + /* Free global error message */ + register_global_error(NULL); + + return 0; +} + +struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id) +{ + struct udev *udev; + struct udev_enumerate *enumerate; + struct udev_list_entry *devices, *dev_list_entry; + + struct hid_device_info *root = NULL; /* return object */ + struct hid_device_info *cur_dev = NULL; + + hid_init(); + /* register_global_error: global error is reset by hid_init */ + + /* Create the udev object */ + udev = udev_new(); + if (!udev) { + register_global_error("Couldn't create udev context"); + return NULL; + } + + /* Create a list of the devices in the 'hidraw' subsystem. */ + enumerate = udev_enumerate_new(udev); + udev_enumerate_add_match_subsystem(enumerate, "hidraw"); + udev_enumerate_scan_devices(enumerate); + devices = udev_enumerate_get_list_entry(enumerate); + /* For each item, see if it matches the vid/pid, and if so + create a udev_device record for it */ + udev_list_entry_foreach(dev_list_entry, devices) { + const char *sysfs_path; + unsigned short dev_vid = 0; + unsigned short dev_pid = 0; + unsigned bus_type = 0; + struct udev_device *raw_dev; /* The device's hidraw udev node. */ + struct hid_device_info * tmp; + + /* Get the filename of the /sys entry for the device + and create a udev_device object (dev) representing it */ + sysfs_path = udev_list_entry_get_name(dev_list_entry); + if (!sysfs_path) + continue; + + if (vendor_id != 0 || product_id != 0) { + if (!parse_hid_vid_pid_from_sysfs(sysfs_path, &bus_type, &dev_vid, &dev_pid)) + continue; + + if (vendor_id != 0 && vendor_id != dev_vid) + continue; + if (product_id != 0 && product_id != dev_pid) + continue; + } + + raw_dev = udev_device_new_from_syspath(udev, sysfs_path); + if (!raw_dev) + continue; + + tmp = create_device_info_for_device(raw_dev); + if (tmp) { + if (cur_dev) { + cur_dev->next = tmp; + } + else { + root = tmp; + } + cur_dev = tmp; + + /* move the pointer to the tail of returned list */ + while (cur_dev->next != NULL) { + cur_dev = cur_dev->next; + } + } + + udev_device_unref(raw_dev); + } + /* Free the enumerator and udev objects. */ + udev_enumerate_unref(enumerate); + udev_unref(udev); + + if (root == NULL) { + if (vendor_id == 0 && product_id == 0) { + register_global_error("No HID devices found in the system."); + } else { + register_global_error("No HID devices with requested VID/PID found in the system."); + } + } + + return root; +} + +void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs) +{ + struct hid_device_info *d = devs; + while (d) { + struct hid_device_info *next = d->next; + free(d->path); + free(d->serial_number); + free(d->manufacturer_string); + free(d->product_string); + free(d); + d = next; + } +} + +hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) +{ + struct hid_device_info *devs, *cur_dev; + const char *path_to_open = NULL; + hid_device *handle = NULL; + + /* register_global_error: global error is reset by hid_enumerate/hid_init */ + devs = hid_enumerate(vendor_id, product_id); + if (devs == NULL) { + /* register_global_error: global error is already set by hid_enumerate */ + return NULL; + } + + cur_dev = devs; + while (cur_dev) { + if (cur_dev->vendor_id == vendor_id && + cur_dev->product_id == product_id) { + if (serial_number) { + if (wcscmp(serial_number, cur_dev->serial_number) == 0) { + path_to_open = cur_dev->path; + break; + } + } + else { + path_to_open = cur_dev->path; + break; + } + } + cur_dev = cur_dev->next; + } + + if (path_to_open) { + /* Open the device */ + handle = hid_open_path(path_to_open); + } else { + register_global_error("Device with requested VID/PID/(SerialNumber) not found"); + } + + hid_free_enumeration(devs); + + return handle; +} + +hid_device * HID_API_EXPORT hid_open_path(const char *path) +{ + hid_device *dev = NULL; + + hid_init(); + /* register_global_error: global error is reset by hid_init */ + + dev = new_hid_device(); + if (!dev) { + register_global_error("Couldn't allocate memory"); + return NULL; + } + + const int MAX_ATTEMPTS = 50; + int attempt; + for (attempt = 1; attempt <= MAX_ATTEMPTS; ++attempt) { + dev->device_handle = open(path, O_RDWR | O_CLOEXEC); + if (dev->device_handle < 0 && errno == EACCES) { + /* udev might be setting up permissions, wait a bit and try again */ + usleep(1 * 1000); + continue; + } + break; + } + + if (dev->device_handle >= 0) { + int res, desc_size = 0; + + /* Make sure this is a HIDRAW device - responds to HIDIOCGRDESCSIZE */ + res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size); + if (res < 0) { + hid_close(dev); + register_global_error_format("ioctl(GRDESCSIZE) error for '%s', not a HIDRAW device?: %s", path, strerror(errno)); + return NULL; + } + + dev->needs_ble_hack = (is_BLE(dev) == 1); + + return dev; + } + else { + /* Unable to open a device. */ + free(dev); + register_global_error_format("Failed to open a device with path '%s': %s", path, strerror(errno)); + return NULL; + } +} + + +int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length) +{ + int bytes_written; + + if (!data || (length == 0)) { + errno = EINVAL; + register_device_error(dev, strerror(errno)); + return -1; + } + + bytes_written = write(dev->device_handle, data, length); + + register_device_error(dev, (bytes_written == -1)? strerror(errno): NULL); + + return bytes_written; +} + + +int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) +{ + /* Set device error to none */ + register_device_error(dev, NULL); + + int bytes_read; + + if (milliseconds >= 0) { + /* Milliseconds is either 0 (non-blocking) or > 0 (contains + a valid timeout). In both cases we want to call poll() + and wait for data to arrive. Don't rely on non-blocking + operation (O_NONBLOCK) since some kernels don't seem to + properly report device disconnection through read() when + in non-blocking mode. */ + int ret; + struct pollfd fds; + + fds.fd = dev->device_handle; + fds.events = POLLIN; + fds.revents = 0; + ret = poll(&fds, 1, milliseconds); + if (ret == 0) { + /* Timeout */ + return ret; + } + if (ret == -1) { + /* Error */ + register_device_error(dev, strerror(errno)); + return ret; + } + else { + /* Check for errors on the file descriptor. This will + indicate a device disconnection. */ + if (fds.revents & (POLLERR | POLLHUP | POLLNVAL)) { + // We cannot use strerror() here as no -1 was returned from poll(). + register_device_error(dev, "hid_read_timeout: unexpected poll error (device disconnected)"); + return -1; + } + } + } + + bytes_read = read(dev->device_handle, data, length); + if (bytes_read < 0) { + if (errno == EAGAIN || errno == EINPROGRESS) + bytes_read = 0; + else + register_device_error(dev, strerror(errno)); + } + + return bytes_read; +} + +int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length) +{ + return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0); +} + +int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock) +{ + /* Do all non-blocking in userspace using poll(), since it looks + like there's a bug in the kernel in some versions where + read() will not return -1 on disconnection of the USB device */ + + dev->blocking = !nonblock; + return 0; /* Success */ +} + + +int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) +{ + static const int MAX_RETRIES = 50; + int retry; + int res; + + register_device_error(dev, NULL); + + for (retry = 0; retry < MAX_RETRIES; ++retry) { + res = ioctl(dev->device_handle, HIDIOCSFEATURE(length), data); + if (res < 0 && errno == EPIPE) { + /* Try again... */ + continue; + } + + if (res < 0) + register_device_error_format(dev, "ioctl (SFEATURE): %s", strerror(errno)); + break; + } + return res; +} + +int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) +{ + int res; + unsigned char report = data[0]; + + register_device_error(dev, NULL); + + res = ioctl(dev->device_handle, HIDIOCGFEATURE(length), data); + if (res < 0) + register_device_error_format(dev, "ioctl (GFEATURE): %s", strerror(errno)); + else if (dev->needs_ble_hack) { + /* Versions of BlueZ before 5.56 don't include the report in the data, + * and versions of BlueZ >= 5.56 include 2 copies of the report. + * We'll fix it so that there is a single copy of the report in both cases + */ + if (data[0] == report && data[1] == report) { + memmove(&data[0], &data[1], res); + } else if (data[0] != report) { + memmove(&data[1], &data[0], res); + data[0] = report; + ++res; + } + } + + return res; +} + +int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length) +{ + int res; + + register_device_error(dev, NULL); + + res = ioctl(dev->device_handle, HIDIOCGINPUT(length), data); + if (res < 0) + register_device_error_format(dev, "ioctl (GINPUT): %s", strerror(errno)); + + return res; +} + +void HID_API_EXPORT hid_close(hid_device *dev) +{ + if (!dev) + return; + + close(dev->device_handle); + + /* Free the device error message */ + register_device_error(dev, NULL); + + hid_free_enumeration(dev->device_info); + + free(dev); +} + + +int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) +{ + if (!string || !maxlen) { + register_device_error(dev, "Zero buffer/length"); + return -1; + } + + struct hid_device_info *info = hid_get_device_info(dev); + if (!info) { + // hid_get_device_info will have set an error already + return -1; + } + + if (info->manufacturer_string) { + wcsncpy(string, info->manufacturer_string, maxlen); + string[maxlen - 1] = L'\0'; + } + else { + string[0] = L'\0'; + } + + return 0; +} + +int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) +{ + if (!string || !maxlen) { + register_device_error(dev, "Zero buffer/length"); + return -1; + } + + struct hid_device_info *info = hid_get_device_info(dev); + if (!info) { + // hid_get_device_info will have set an error already + return -1; + } + + if (info->product_string) { + wcsncpy(string, info->product_string, maxlen); + string[maxlen - 1] = L'\0'; + } + else { + string[0] = L'\0'; + } + + return 0; +} + +int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) +{ + if (!string || !maxlen) { + register_device_error(dev, "Zero buffer/length"); + return -1; + } + + struct hid_device_info *info = hid_get_device_info(dev); + if (!info) { + // hid_get_device_info will have set an error already + return -1; + } + + if (info->serial_number) { + wcsncpy(string, info->serial_number, maxlen); + string[maxlen - 1] = L'\0'; + } + else { + string[0] = L'\0'; + } + + return 0; +} + + +HID_API_EXPORT struct hid_device_info *HID_API_CALL hid_get_device_info(hid_device *dev) { + if (!dev->device_info) { + // Lazy initialize device_info + dev->device_info = create_device_info_for_hid_device(dev); + } + + // create_device_info_for_hid_device will set an error if needed + return dev->device_info; +} + +int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) +{ + (void)string_index; + (void)string; + (void)maxlen; + + register_device_error(dev, "hid_get_indexed_string: not supported by hidraw"); + + return -1; +} + + +int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size) +{ + struct hidraw_report_descriptor rpt_desc; + int res = get_hid_report_descriptor_from_hidraw(dev, &rpt_desc); + if (res < 0) { + /* error already registered */ + return res; + } + + if (rpt_desc.size < buf_size) { + buf_size = (size_t) rpt_desc.size; + } + + memcpy(buf, rpt_desc.value, buf_size); + + return (int) buf_size; +} + + +/* Passing in NULL means asking for the last global error message. */ +HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) +{ + if (dev) { + if (dev->last_error_str == NULL) + return L"Success"; + return dev->last_error_str; + } + + if (last_global_error_str == NULL) + return L"Success"; + return last_global_error_str; +} diff --git a/thirdparty/sdl/hidapi/mac/hid.c b/thirdparty/sdl/hidapi/mac/hid.c new file mode 100644 index 00000000000..8acb6da7feb --- /dev/null +++ b/thirdparty/sdl/hidapi/mac/hid.c @@ -0,0 +1,1594 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + Alan Ott + Signal 11 Software + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +/* See Apple Technical Note TN2187 for details on IOHidManager. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "hidapi_darwin.h" + +/* Barrier implementation because Mac OSX doesn't have pthread_barrier. + It also doesn't have clock_gettime(). So much for POSIX and SUSv2. + This implementation came from Brent Priddy and was posted on + StackOverflow. It is used with his permission. */ +typedef int pthread_barrierattr_t; +typedef struct pthread_barrier { + pthread_mutex_t mutex; + pthread_cond_t cond; + int count; + int trip_count; +} pthread_barrier_t; + +static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count) +{ + (void) attr; + + if (count == 0) { + errno = EINVAL; + return -1; + } + + if (pthread_mutex_init(&barrier->mutex, 0) < 0) { + return -1; + } + if (pthread_cond_init(&barrier->cond, 0) < 0) { + pthread_mutex_destroy(&barrier->mutex); + return -1; + } + barrier->trip_count = count; + barrier->count = 0; + + return 0; +} + +static int pthread_barrier_destroy(pthread_barrier_t *barrier) +{ + pthread_cond_destroy(&barrier->cond); + pthread_mutex_destroy(&barrier->mutex); + return 0; +} + +static int pthread_barrier_wait(pthread_barrier_t *barrier) +{ + pthread_mutex_lock(&barrier->mutex); + ++(barrier->count); + if (barrier->count >= barrier->trip_count) { + barrier->count = 0; + pthread_mutex_unlock(&barrier->mutex); + pthread_cond_broadcast(&barrier->cond); + return 1; + } + else { + do { + pthread_cond_wait(&barrier->cond, &(barrier->mutex)); + } + while (barrier->count != 0); + + pthread_mutex_unlock(&barrier->mutex); + return 0; + } +} + +static int return_data(hid_device *dev, unsigned char *data, size_t length); + +/* Linked List of input reports received from the device. */ +struct input_report { + uint8_t *data; + size_t len; + struct input_report *next; +}; + +static struct hid_api_version api_version = { + .major = HID_API_VERSION_MAJOR, + .minor = HID_API_VERSION_MINOR, + .patch = HID_API_VERSION_PATCH +}; + +/* - Run context - */ +static IOHIDManagerRef hid_mgr = 0x0; +static int is_macos_10_10_or_greater = 0; +static IOOptionBits device_open_options = 0; +static wchar_t *last_global_error_str = NULL; +/* --- */ + +struct hid_device_ { + IOHIDDeviceRef device_handle; + IOOptionBits open_options; + int blocking; + int disconnected; + CFStringRef run_loop_mode; + CFRunLoopRef run_loop; + CFRunLoopSourceRef source; + uint8_t *input_report_buf; + CFIndex max_input_report_len; + struct input_report *input_reports; + struct hid_device_info* device_info; + + pthread_t thread; + pthread_mutex_t mutex; /* Protects input_reports */ + pthread_cond_t condition; + pthread_barrier_t barrier; /* Ensures correct startup sequence */ + pthread_barrier_t shutdown_barrier; /* Ensures correct shutdown sequence */ + int shutdown_thread; + wchar_t *last_error_str; +}; + +static hid_device *new_hid_device(void) +{ + hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device)); + if (dev == NULL) { + return NULL; + } + + dev->device_handle = NULL; + dev->open_options = device_open_options; + dev->blocking = 1; + dev->disconnected = 0; + dev->run_loop_mode = NULL; + dev->run_loop = NULL; + dev->source = NULL; + dev->input_report_buf = NULL; + dev->input_reports = NULL; + dev->device_info = NULL; + dev->shutdown_thread = 0; + dev->last_error_str = NULL; + + /* Thread objects */ + pthread_mutex_init(&dev->mutex, NULL); + pthread_cond_init(&dev->condition, NULL); + pthread_barrier_init(&dev->barrier, NULL, 2); + pthread_barrier_init(&dev->shutdown_barrier, NULL, 2); + + return dev; +} + +static void free_hid_device(hid_device *dev) +{ + if (!dev) + return; + + /* Delete any input reports still left over. */ + struct input_report *rpt = dev->input_reports; + while (rpt) { + struct input_report *next = rpt->next; + free(rpt->data); + free(rpt); + rpt = next; + } + + /* Free the string and the report buffer. The check for NULL + is necessary here as CFRelease() doesn't handle NULL like + free() and others do. */ + if (dev->run_loop_mode) + CFRelease(dev->run_loop_mode); + if (dev->source) + CFRelease(dev->source); + free(dev->input_report_buf); + hid_free_enumeration(dev->device_info); + + /* Clean up the thread objects */ + pthread_barrier_destroy(&dev->shutdown_barrier); + pthread_barrier_destroy(&dev->barrier); + pthread_cond_destroy(&dev->condition); + pthread_mutex_destroy(&dev->mutex); + + /* Free the structure itself. */ + free(dev); +} + + +#ifndef HIDAPI_USING_SDL_RUNTIME +/* The caller must free the returned string with free(). */ +static wchar_t *utf8_to_wchar_t(const char *utf8) +{ + wchar_t *ret = NULL; + + if (utf8) { + size_t wlen = mbstowcs(NULL, utf8, 0); + if ((size_t) -1 == wlen) { + return wcsdup(L""); + } + ret = (wchar_t*) calloc(wlen+1, sizeof(wchar_t)); + if (ret == NULL) { + /* as much as we can do at this point */ + return NULL; + } + mbstowcs(ret, utf8, wlen+1); + ret[wlen] = 0x0000; + } + + return ret; +} +#endif + + +/* Makes a copy of the given error message (and decoded according to the + * currently locale) into the wide string pointer pointed by error_str. + * The last stored error string is freed. + * Use register_error_str(NULL) to free the error message completely. */ +static void register_error_str(wchar_t **error_str, const char *msg) +{ + free(*error_str); +#ifdef HIDAPI_USING_SDL_RUNTIME + /* Thread-safe error handling */ + if (msg) { + SDL_SetError("%s", msg); + } else { + SDL_ClearError(); + } +#else + *error_str = utf8_to_wchar_t(msg); +#endif +} + +/* Similar to register_error_str, but allows passing a format string with va_list args into this function. */ +static void register_error_str_vformat(wchar_t **error_str, const char *format, va_list args) +{ + char msg[1024]; + vsnprintf(msg, sizeof(msg), format, args); + + register_error_str(error_str, msg); +} + +/* Set the last global error to be reported by hid_error(NULL). + * The given error message will be copied (and decoded according to the + * currently locale, so do not pass in string constants). + * The last stored global error message is freed. + * Use register_global_error(NULL) to indicate "no error". */ +static void register_global_error(const char *msg) +{ + register_error_str(&last_global_error_str, msg); +} + +/* Similar to register_global_error, but allows passing a format string into this function. */ +static void register_global_error_format(const char *format, ...) +{ + va_list args; + va_start(args, format); + register_error_str_vformat(&last_global_error_str, format, args); + va_end(args); +} + +/* Set the last error for a device to be reported by hid_error(dev). + * The given error message will be copied (and decoded according to the + * currently locale, so do not pass in string constants). + * The last stored device error message is freed. + * Use register_device_error(dev, NULL) to indicate "no error". */ +static void register_device_error(hid_device *dev, const char *msg) +{ + register_error_str(&dev->last_error_str, msg); +} + +/* Similar to register_device_error, but you can pass a format string into this function. */ +static void register_device_error_format(hid_device *dev, const char *format, ...) +{ + va_list args; + va_start(args, format); + register_error_str_vformat(&dev->last_error_str, format, args); + va_end(args); +} + + +static CFArrayRef get_array_property(IOHIDDeviceRef device, CFStringRef key) +{ + CFTypeRef ref = IOHIDDeviceGetProperty(device, key); + if (ref != NULL && CFGetTypeID(ref) == CFArrayGetTypeID()) { + return (CFArrayRef)ref; + } else { + return NULL; + } +} + +static int32_t get_int_property(IOHIDDeviceRef device, CFStringRef key) +{ + CFTypeRef ref; + int32_t value = 0; + + ref = IOHIDDeviceGetProperty(device, key); + if (ref) { + if (CFGetTypeID(ref) == CFNumberGetTypeID()) { + CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &value); + return value; + } + } + return 0; +} + +static bool try_get_int_property(IOHIDDeviceRef device, CFStringRef key, int32_t *out_val) +{ + bool result = false; + CFTypeRef ref; + + ref = IOHIDDeviceGetProperty(device, key); + if (ref) { + if (CFGetTypeID(ref) == CFNumberGetTypeID()) { + result = CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, out_val); + } + } + return result; +} + +static bool try_get_ioregistry_int_property(io_service_t service, CFStringRef property, int32_t *out_val) +{ + bool result = false; + CFTypeRef ref = IORegistryEntryCreateCFProperty(service, property, kCFAllocatorDefault, 0); + + if (ref) { + if (CFGetTypeID(ref) == CFNumberGetTypeID()) { + result = CFNumberGetValue(ref, kCFNumberSInt32Type, out_val); + } + + CFRelease(ref); + } + + return result; +} + +static CFArrayRef get_usage_pairs(IOHIDDeviceRef device) +{ + return get_array_property(device, CFSTR(kIOHIDDeviceUsagePairsKey)); +} + +static unsigned short get_vendor_id(IOHIDDeviceRef device) +{ + return get_int_property(device, CFSTR(kIOHIDVendorIDKey)); +} + +static unsigned short get_product_id(IOHIDDeviceRef device) +{ + return get_int_property(device, CFSTR(kIOHIDProductIDKey)); +} + +static int32_t get_max_report_length(IOHIDDeviceRef device) +{ + return get_int_property(device, CFSTR(kIOHIDMaxInputReportSizeKey)); +} + +static int get_string_property(IOHIDDeviceRef device, CFStringRef prop, wchar_t *buf, size_t len) +{ + CFStringRef str; + + if (!len) + return 0; + + str = (CFStringRef) IOHIDDeviceGetProperty(device, prop); + + buf[0] = 0; + + if (str && CFGetTypeID(str) == CFStringGetTypeID()) { + CFIndex str_len = CFStringGetLength(str); + CFRange range; + CFIndex used_buf_len; + CFIndex chars_copied; + + len --; + + range.location = 0; + range.length = ((size_t) str_len > len)? len: (size_t) str_len; + chars_copied = CFStringGetBytes(str, + range, + kCFStringEncodingUTF32LE, + (char) '?', + FALSE, + (UInt8*)buf, + len * sizeof(wchar_t), + &used_buf_len); + + if (chars_copied <= 0) + buf[0] = 0; + else + buf[chars_copied] = 0; + + return 0; + } + else + return -1; + +} + +static int get_serial_number(IOHIDDeviceRef device, wchar_t *buf, size_t len) +{ + return get_string_property(device, CFSTR(kIOHIDSerialNumberKey), buf, len); +} + +static int get_manufacturer_string(IOHIDDeviceRef device, wchar_t *buf, size_t len) +{ + return get_string_property(device, CFSTR(kIOHIDManufacturerKey), buf, len); +} + +static int get_product_string(IOHIDDeviceRef device, wchar_t *buf, size_t len) +{ + return get_string_property(device, CFSTR(kIOHIDProductKey), buf, len); +} + + +/* Implementation of wcsdup() for Mac. */ +static wchar_t *dup_wcs(const wchar_t *s) +{ + size_t len = wcslen(s); + wchar_t *ret = (wchar_t*) malloc((len+1)*sizeof(wchar_t)); + wcscpy(ret, s); + + return ret; +} + +/* Initialize the IOHIDManager. Return 0 for success and -1 for failure. */ +static int init_hid_manager(void) +{ + /* Initialize all the HID Manager Objects */ + hid_mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); + if (hid_mgr) { + IOHIDManagerSetDeviceMatching(hid_mgr, NULL); + IOHIDManagerScheduleWithRunLoop(hid_mgr, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); + return 0; + } + + register_global_error("Failed to create IOHIDManager"); + return -1; +} + +HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void) +{ + return &api_version; +} + +HID_API_EXPORT const char* HID_API_CALL hid_version_str(void) +{ + return HID_API_VERSION_STR; +} + +/* Initialize the IOHIDManager if necessary. This is the public function, and + it is safe to call this function repeatedly. Return 0 for success and -1 + for failure. */ +int HID_API_EXPORT hid_init(void) +{ + register_global_error(NULL); + + if (!hid_mgr) { + is_macos_10_10_or_greater = (kCFCoreFoundationVersionNumber >= 1151.16); /* kCFCoreFoundationVersionNumber10_10 */ + hid_darwin_set_open_exclusive(1); /* Backward compatibility */ + return init_hid_manager(); + } + + /* Already initialized. */ + return 0; +} + +int HID_API_EXPORT hid_exit(void) +{ + if (hid_mgr) { + /* Close the HID manager. */ + IOHIDManagerClose(hid_mgr, kIOHIDOptionsTypeNone); + CFRelease(hid_mgr); + hid_mgr = NULL; + } + + /* Free global error message */ + register_global_error(NULL); + + return 0; +} + +static void process_pending_events(void) { + SInt32 res; + do { + res = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, FALSE); + } while(res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut); +} + +static int read_usb_interface_from_hid_service_parent(io_service_t hid_service) +{ + int32_t result = -1; + bool success = false; + io_registry_entry_t current = IO_OBJECT_NULL; + kern_return_t res; + int parent_number = 0; + + res = IORegistryEntryGetParentEntry(hid_service, kIOServicePlane, ¤t); + while (KERN_SUCCESS == res + /* Only search up to 3 parent entries. + * With the default driver - the parent-of-interest supposed to be the first one, + * but lets assume some custom drivers or so, with deeper tree. */ + && parent_number < 3) { + io_registry_entry_t parent = IO_OBJECT_NULL; + int32_t interface_number = -1; + parent_number++; + + success = try_get_ioregistry_int_property(current, CFSTR(kUSBInterfaceNumber), &interface_number); + if (success) { + result = interface_number; + break; + } + + res = IORegistryEntryGetParentEntry(current, kIOServicePlane, &parent); + if (parent) { + IOObjectRelease(current); + current = parent; + } + + } + + if (current) { + IOObjectRelease(current); + current = IO_OBJECT_NULL; + } + + return result; +} + +#ifdef HIDAPI_IGNORE_DEVICE +static hid_bus_type get_bus_type(IOHIDDeviceRef dev) +{ + hid_bus_type bus_type = HID_API_BUS_UNKNOWN; + + CFTypeRef transport_prop = IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDTransportKey)); + + if (transport_prop != NULL && CFGetTypeID(transport_prop) == CFStringGetTypeID()) { + if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportUSBValue), 0) == kCFCompareEqualTo) { + bus_type = HID_API_BUS_USB; + } else if (CFStringHasPrefix((CFStringRef)transport_prop, CFSTR(kIOHIDTransportBluetoothValue))) { + bus_type = HID_API_BUS_BLUETOOTH; + } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportI2CValue), 0) == kCFCompareEqualTo) { + bus_type = HID_API_BUS_I2C; + } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportSPIValue), 0) == kCFCompareEqualTo) { + bus_type = HID_API_BUS_SPI; + } + } + return bus_type; +} +#endif /* HIDAPI_IGNORE_DEVICE */ + +static struct hid_device_info *create_device_info_with_usage(IOHIDDeviceRef dev, int32_t usage_page, int32_t usage) +{ + unsigned short dev_vid; + unsigned short dev_pid; + int BUF_LEN = 256; + wchar_t buf[BUF_LEN]; + CFTypeRef transport_prop; + + struct hid_device_info *cur_dev; + io_service_t hid_service; + kern_return_t res; + uint64_t entry_id = 0; + + if (dev == NULL) { + return NULL; + } + + cur_dev = (struct hid_device_info *)calloc(1, sizeof(struct hid_device_info)); + if (cur_dev == NULL) { + return NULL; + } + + dev_vid = get_vendor_id(dev); + dev_pid = get_product_id(dev); + +#ifdef HIDAPI_IGNORE_DEVICE + /* See if there are any devices we should skip in enumeration */ + if (HIDAPI_IGNORE_DEVICE(get_bus_type(dev), dev_vid, dev_pid, usage_page, usage)) { + free(cur_dev); + return NULL; + } +#endif + + cur_dev->usage_page = usage_page; + cur_dev->usage = usage; + + /* Fill out the record */ + cur_dev->next = NULL; + + /* Fill in the path (as a unique ID of the service entry) */ + cur_dev->path = NULL; + hid_service = IOHIDDeviceGetService(dev); + if (hid_service != MACH_PORT_NULL) { + res = IORegistryEntryGetRegistryEntryID(hid_service, &entry_id); + } + else { + res = KERN_INVALID_ARGUMENT; + } + + if (res == KERN_SUCCESS) { + /* max value of entry_id(uint64_t) is 18446744073709551615 which is 20 characters long, + so for (max) "path" string 'DevSrvsID:18446744073709551615' we would need + 9+1+20+1=31 bytes buffer, but allocate 32 for simple alignment */ + const size_t path_len = 32; + cur_dev->path = calloc(1, path_len); + if (cur_dev->path != NULL) { + snprintf(cur_dev->path, path_len, "DevSrvsID:%llu", entry_id); + } + } + + if (cur_dev->path == NULL) { + /* for whatever reason, trying to keep it a non-NULL string */ + cur_dev->path = strdup(""); + } + + /* Serial Number */ + get_serial_number(dev, buf, BUF_LEN); + cur_dev->serial_number = dup_wcs(buf); + + /* Manufacturer and Product strings */ + get_manufacturer_string(dev, buf, BUF_LEN); + cur_dev->manufacturer_string = dup_wcs(buf); + get_product_string(dev, buf, BUF_LEN); + cur_dev->product_string = dup_wcs(buf); + + /* VID/PID */ + cur_dev->vendor_id = dev_vid; + cur_dev->product_id = dev_pid; + + /* Release Number */ + cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey)); + + /* Interface Number. + * We can only retrieve the interface number for USB HID devices. + * See below */ + cur_dev->interface_number = -1; + + /* Bus Type */ + transport_prop = IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDTransportKey)); + + if (transport_prop != NULL && CFGetTypeID(transport_prop) == CFStringGetTypeID()) { + if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportUSBValue), 0) == kCFCompareEqualTo) { + int32_t interface_number = -1; + cur_dev->bus_type = HID_API_BUS_USB; + + /* A IOHIDDeviceRef used to have this simple property, + * until macOS 13.3 - we will try to use it. */ + if (try_get_int_property(dev, CFSTR(kUSBInterfaceNumber), &interface_number)) { + cur_dev->interface_number = interface_number; + } else { + /* Otherwise fallback to io_service_t property. + * (of one of the parent services). */ + cur_dev->interface_number = read_usb_interface_from_hid_service_parent(hid_service); + + /* If the above doesn't work - + * no (known) fallback exists at this point. */ + } + + /* Match "Bluetooth", "BluetoothLowEnergy" and "Bluetooth Low Energy" strings */ + } else if (CFStringHasPrefix((CFStringRef)transport_prop, CFSTR(kIOHIDTransportBluetoothValue))) { + cur_dev->bus_type = HID_API_BUS_BLUETOOTH; + } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportI2CValue), 0) == kCFCompareEqualTo) { + cur_dev->bus_type = HID_API_BUS_I2C; + } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportSPIValue), 0) == kCFCompareEqualTo) { + cur_dev->bus_type = HID_API_BUS_SPI; + } + } + + return cur_dev; +} + +static struct hid_device_info *create_device_info(IOHIDDeviceRef device) +{ + const int32_t primary_usage_page = get_int_property(device, CFSTR(kIOHIDPrimaryUsagePageKey)); + const int32_t primary_usage = get_int_property(device, CFSTR(kIOHIDPrimaryUsageKey)); + + /* Primary should always be first, to match previous behavior. */ + struct hid_device_info *root = create_device_info_with_usage(device, primary_usage_page, primary_usage); + struct hid_device_info *cur = root; + + CFArrayRef usage_pairs = get_usage_pairs(device); + + if (usage_pairs != NULL) { + struct hid_device_info *next = NULL; + for (CFIndex i = 0; i < CFArrayGetCount(usage_pairs); i++) { + CFTypeRef dict = CFArrayGetValueAtIndex(usage_pairs, i); + if (CFGetTypeID(dict) != CFDictionaryGetTypeID()) { + continue; + } + + CFTypeRef usage_page_ref, usage_ref; + int32_t usage_page, usage; + + if (!CFDictionaryGetValueIfPresent((CFDictionaryRef)dict, CFSTR(kIOHIDDeviceUsagePageKey), &usage_page_ref) || + !CFDictionaryGetValueIfPresent((CFDictionaryRef)dict, CFSTR(kIOHIDDeviceUsageKey), &usage_ref) || + CFGetTypeID(usage_page_ref) != CFNumberGetTypeID() || + CFGetTypeID(usage_ref) != CFNumberGetTypeID() || + !CFNumberGetValue((CFNumberRef)usage_page_ref, kCFNumberSInt32Type, &usage_page) || + !CFNumberGetValue((CFNumberRef)usage_ref, kCFNumberSInt32Type, &usage)) { + continue; + } + if (usage_page == primary_usage_page && usage == primary_usage) + continue; /* Already added. */ + + next = create_device_info_with_usage(device, usage_page, usage); + if (cur) { + if (next != NULL) { + cur->next = next; + cur = next; + } + } else { + root = cur = next; + } + } + } + + return root; +} + +struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id) +{ + struct hid_device_info *root = NULL; /* return object */ + struct hid_device_info *cur_dev = NULL; + CFIndex num_devices; + int i; + + /* Set up the HID Manager if it hasn't been done */ + if (hid_init() < 0) { + return NULL; + } + /* register_global_error: global error is set/reset by hid_init */ + + /* give the IOHIDManager a chance to update itself */ + process_pending_events(); + + /* Get a list of the Devices */ + CFMutableDictionaryRef matching = NULL; + if (vendor_id != 0 || product_id != 0) { + matching = CFDictionaryCreateMutable(kCFAllocatorDefault, kIOHIDOptionsTypeNone, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + + if (matching && vendor_id != 0) { + CFNumberRef v = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &vendor_id); + CFDictionarySetValue(matching, CFSTR(kIOHIDVendorIDKey), v); + CFRelease(v); + } + + if (matching && product_id != 0) { + CFNumberRef p = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &product_id); + CFDictionarySetValue(matching, CFSTR(kIOHIDProductIDKey), p); + CFRelease(p); + } + } + IOHIDManagerSetDeviceMatching(hid_mgr, matching); + if (matching != NULL) { + CFRelease(matching); + } + + CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr); + + IOHIDDeviceRef *device_array = NULL; + + if (device_set != NULL) { + /* Convert the list into a C array so we can iterate easily. */ + num_devices = CFSetGetCount(device_set); + device_array = (IOHIDDeviceRef*) calloc(num_devices, sizeof(IOHIDDeviceRef)); + CFSetGetValues(device_set, (const void **) device_array); + } else { + num_devices = 0; + } + + /* Iterate over each device, making an entry for it. */ + for (i = 0; i < num_devices; i++) { + + IOHIDDeviceRef dev = device_array[i]; + if (!dev) { + continue; + } + + struct hid_device_info *tmp = create_device_info(dev); + if (tmp == NULL) { + continue; + } + + if (cur_dev) { + cur_dev->next = tmp; + } + else { + root = tmp; + } + cur_dev = tmp; + + /* move the pointer to the tail of returned list */ + while (cur_dev->next != NULL) { + cur_dev = cur_dev->next; + } + } + + free(device_array); + if (device_set != NULL) + CFRelease(device_set); + + if (root == NULL) { + if (vendor_id == 0 && product_id == 0) { + register_global_error("No HID devices found in the system."); + } else { + register_global_error("No HID devices with requested VID/PID found in the system."); + } + } + + return root; +} + +void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs) +{ + /* This function is identical to the Linux version. Platform independent. */ + struct hid_device_info *d = devs; + while (d) { + struct hid_device_info *next = d->next; + free(d->path); + free(d->serial_number); + free(d->manufacturer_string); + free(d->product_string); + free(d); + d = next; + } +} + +hid_device * HID_API_EXPORT hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) +{ + /* This function is identical to the Linux version. Platform independent. */ + + struct hid_device_info *devs, *cur_dev; + const char *path_to_open = NULL; + hid_device * handle = NULL; + + /* register_global_error: global error is reset by hid_enumerate/hid_init */ + devs = hid_enumerate(vendor_id, product_id); + if (devs == NULL) { + /* register_global_error: global error is already set by hid_enumerate */ + return NULL; + } + + cur_dev = devs; + while (cur_dev) { + if (cur_dev->vendor_id == vendor_id && + cur_dev->product_id == product_id) { + if (serial_number) { + if (wcscmp(serial_number, cur_dev->serial_number) == 0) { + path_to_open = cur_dev->path; + break; + } + } + else { + path_to_open = cur_dev->path; + break; + } + } + cur_dev = cur_dev->next; + } + + if (path_to_open) { + handle = hid_open_path(path_to_open); + } else { + register_global_error("Device with requested VID/PID/(SerialNumber) not found"); + } + + hid_free_enumeration(devs); + + return handle; +} + +static void hid_device_removal_callback(void *context, IOReturn result, + void *sender) +{ + (void) result; + (void) sender; + + /* Stop the Run Loop for this device. */ + hid_device *d = (hid_device*) context; + + d->disconnected = 1; + CFRunLoopStop(d->run_loop); +} + +/* The Run Loop calls this function for each input report received. + This function puts the data into a linked list to be picked up by + hid_read(). */ +static void hid_report_callback(void *context, IOReturn result, void *sender, + IOHIDReportType report_type, uint32_t report_id, + uint8_t *report, CFIndex report_length) +{ + (void) result; + (void) sender; + (void) report_type; + (void) report_id; + + struct input_report *rpt; + hid_device *dev = (hid_device*) context; + + /* Make a new Input Report object */ + rpt = (struct input_report*) calloc(1, sizeof(struct input_report)); + rpt->data = (uint8_t*) calloc(1, report_length); + memcpy(rpt->data, report, report_length); + rpt->len = report_length; + rpt->next = NULL; + + /* Lock this section */ + pthread_mutex_lock(&dev->mutex); + + /* Attach the new report object to the end of the list. */ + if (dev->input_reports == NULL) { + /* The list is empty. Put it at the root. */ + dev->input_reports = rpt; + } + else { + /* Find the end of the list and attach. */ + struct input_report *cur = dev->input_reports; + int num_queued = 0; + while (cur->next != NULL) { + cur = cur->next; + num_queued++; + } + cur->next = rpt; + + /* Pop one off if we've reached 30 in the queue. This + way we don't grow forever if the user never reads + anything from the device. */ + if (num_queued > 30) { + return_data(dev, NULL, 0); + } + } + + /* Signal a waiting thread that there is data. */ + pthread_cond_signal(&dev->condition); + + /* Unlock */ + pthread_mutex_unlock(&dev->mutex); + +} + +/* This gets called when the read_thread's run loop gets signaled by + hid_close(), and serves to stop the read_thread's run loop. */ +static void perform_signal_callback(void *context) +{ + hid_device *dev = (hid_device*) context; + CFRunLoopStop(dev->run_loop); /*TODO: CFRunLoopGetCurrent()*/ +} + +static void *read_thread(void *param) +{ + hid_device *dev = (hid_device*) param; + SInt32 code; + + /* Move the device's run loop to this thread. */ + IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode); + + /* Create the RunLoopSource which is used to signal the + event loop to stop when hid_close() is called. */ + CFRunLoopSourceContext ctx; + memset(&ctx, 0, sizeof(ctx)); + ctx.version = 0; + ctx.info = dev; + ctx.perform = &perform_signal_callback; + dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx); + CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode); + + /* Store off the Run Loop so it can be stopped from hid_close() + and on device disconnection. */ + dev->run_loop = CFRunLoopGetCurrent(); + + /* Notify the main thread that the read thread is up and running. */ + pthread_barrier_wait(&dev->barrier); + + /* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input + reports into the hid_report_callback(). */ + while (!dev->shutdown_thread && !dev->disconnected) { + code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE); + /* Return if the device has been disconnected */ + if (code == kCFRunLoopRunFinished || code == kCFRunLoopRunStopped) { + dev->disconnected = 1; + break; + } + + + /* Break if The Run Loop returns Finished or Stopped. */ + if (code != kCFRunLoopRunTimedOut && + code != kCFRunLoopRunHandledSource) { + /* There was some kind of error. Setting + shutdown seems to make sense, but + there may be something else more appropriate */ + dev->shutdown_thread = 1; + break; + } + } + + /* Now that the read thread is stopping, Wake any threads which are + waiting on data (in hid_read_timeout()). Do this under a mutex to + make sure that a thread which is about to go to sleep waiting on + the condition actually will go to sleep before the condition is + signaled. */ + pthread_mutex_lock(&dev->mutex); + pthread_cond_broadcast(&dev->condition); + pthread_mutex_unlock(&dev->mutex); + + /* Wait here until hid_close() is called and makes it past + the call to CFRunLoopWakeUp(). This thread still needs to + be valid when that function is called on the other thread. */ + pthread_barrier_wait(&dev->shutdown_barrier); + + return NULL; +} + +/* \p path must be one of: + - in format 'DevSrvsID:' (as returned by hid_enumerate); + - a valid path to an IOHIDDevice in the IOService plane (as returned by IORegistryEntryGetPath, + e.g.: "IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/EHC1@1D,7/AppleUSBEHCI/PLAYSTATION(R)3 Controller@fd120000/IOUSBInterface@0/IOUSBHIDDriver"); + Second format is for compatibility with paths accepted by older versions of HIDAPI. +*/ +static io_registry_entry_t hid_open_service_registry_from_path(const char *path) +{ + if (path == NULL) + return MACH_PORT_NULL; + + /* Get the IORegistry entry for the given path */ + if (strncmp("DevSrvsID:", path, 10) == 0) { + char *endptr; + uint64_t entry_id = strtoull(path + 10, &endptr, 10); + if (*endptr == '\0') { + return IOServiceGetMatchingService((mach_port_t) 0, IORegistryEntryIDMatching(entry_id)); + } + } + else { + /* Fallback to older format of the path */ + return IORegistryEntryFromPath((mach_port_t) 0, path); + } + + return MACH_PORT_NULL; +} + +hid_device * HID_API_EXPORT hid_open_path(const char *path) +{ + hid_device *dev = NULL; + io_registry_entry_t entry = MACH_PORT_NULL; + IOReturn ret = kIOReturnInvalid; + char str[32]; + + /* Set up the HID Manager if it hasn't been done */ + if (hid_init() < 0) { + return NULL; + } + /* register_global_error: global error is set/reset by hid_init */ + + dev = new_hid_device(); + if (!dev) { + register_global_error("Couldn't allocate memory"); + return NULL; + } + + /* Get the IORegistry entry for the given path */ + entry = hid_open_service_registry_from_path(path); + if (entry == MACH_PORT_NULL) { + /* Path wasn't valid (maybe device was removed?) */ + register_global_error("hid_open_path: device mach entry not found with the given path"); + goto return_error; + } + + /* Create an IOHIDDevice for the entry */ + dev->device_handle = IOHIDDeviceCreate(kCFAllocatorDefault, entry); + if (dev->device_handle == NULL) { + /* Error creating the HID device */ + register_global_error("hid_open_path: failed to create IOHIDDevice from the mach entry"); + goto return_error; + } + + /* Open the IOHIDDevice */ + ret = IOHIDDeviceOpen(dev->device_handle, dev->open_options); + if (ret != kIOReturnSuccess) { + register_global_error_format("hid_open_path: failed to open IOHIDDevice from mach entry: (0x%08X) %s", ret, mach_error_string(ret)); + goto return_error; + } + + /* Create the buffers for receiving data */ + dev->max_input_report_len = (CFIndex) get_max_report_length(dev->device_handle); + dev->input_report_buf = (uint8_t*) calloc(dev->max_input_report_len, sizeof(uint8_t)); + + /* Create the Run Loop Mode for this device. + printing the reference seems to work. */ + snprintf(str, sizeof(str), "HIDAPI_%p", (void*) dev->device_handle); + dev->run_loop_mode = + CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII); + + /* Attach the device to a Run Loop */ + IOHIDDeviceRegisterInputReportCallback( + dev->device_handle, dev->input_report_buf, dev->max_input_report_len, + &hid_report_callback, dev); + IOHIDDeviceRegisterRemovalCallback(dev->device_handle, hid_device_removal_callback, dev); + + /* Start the read thread */ + pthread_create(&dev->thread, NULL, read_thread, dev); + + /* Wait here for the read thread to be initialized. */ + pthread_barrier_wait(&dev->barrier); + + IOObjectRelease(entry); + return dev; + +return_error: + if (dev->device_handle != NULL) + CFRelease(dev->device_handle); + + if (entry != MACH_PORT_NULL) + IOObjectRelease(entry); + + free_hid_device(dev); + return NULL; +} + +static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char *data, size_t length) +{ + const unsigned char *data_to_send = data; + CFIndex length_to_send = length; + IOReturn res; + unsigned char report_id; + + register_device_error(dev, NULL); + + if (!data || (length == 0)) { + register_device_error(dev, strerror(EINVAL)); + return -1; + } + + report_id = data[0]; + + if (report_id == 0x0) { + /* Not using numbered Reports. + Don't send the report number. */ + data_to_send = data+1; + length_to_send = length-1; + } + + /* Avoid crash if the device has been unplugged. */ + if (dev->disconnected) { + register_device_error(dev, "Device is disconnected"); + return -1; + } + + res = IOHIDDeviceSetReport(dev->device_handle, + type, + report_id, + data_to_send, length_to_send); + + if (res != kIOReturnSuccess) { + register_device_error_format(dev, "IOHIDDeviceSetReport failed: (0x%08X) %s", res, mach_error_string(res)); + return -1; + } + + return (int) length; +} + +static int get_report(hid_device *dev, IOHIDReportType type, unsigned char *data, size_t length) +{ + unsigned char *report = data; + CFIndex report_length = length; + IOReturn res = kIOReturnSuccess; + const unsigned char report_id = data[0]; + + register_device_error(dev, NULL); + + if (report_id == 0x0) { + /* Not using numbered Reports. + Don't send the report number. */ + report = data+1; + report_length = length-1; + } + + /* Avoid crash if the device has been unplugged. */ + if (dev->disconnected) { + register_device_error(dev, "Device is disconnected"); + return -1; + } + + res = IOHIDDeviceGetReport(dev->device_handle, + type, + report_id, + report, &report_length); + + if (res != kIOReturnSuccess) { + register_device_error_format(dev, "IOHIDDeviceGetReport failed: (0x%08X) %s", res, mach_error_string(res)); + return -1; + } + + if (report_id == 0x0) { /* 0 report number still present at the beginning */ + report_length++; + } + + return (int) report_length; +} + +int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length) +{ + return set_report(dev, kIOHIDReportTypeOutput, data, length); +} + +/* Helper function, so that this isn't duplicated in hid_read(). */ +static int return_data(hid_device *dev, unsigned char *data, size_t length) +{ + /* Copy the data out of the linked list item (rpt) into the + return buffer (data), and delete the liked list item. */ + struct input_report *rpt = dev->input_reports; + size_t len = (length < rpt->len)? length: rpt->len; + if (data != NULL) { + memcpy(data, rpt->data, len); + } + dev->input_reports = rpt->next; + free(rpt->data); + free(rpt); + return (int) len; +} + +static int cond_wait(hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex) +{ + while (!dev->input_reports) { + int res = pthread_cond_wait(cond, mutex); + if (res != 0) + return res; + + /* A res of 0 means we may have been signaled or it may + be a spurious wakeup. Check to see that there's actually + data in the queue before returning, and if not, go back + to sleep. See the pthread_cond_timedwait() man page for + details. */ + + if (dev->shutdown_thread || dev->disconnected) { + return -1; + } + } + + return 0; +} + +static int cond_timedwait(hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) +{ + while (!dev->input_reports) { + int res = pthread_cond_timedwait(cond, mutex, abstime); + if (res != 0) + return res; + + /* A res of 0 means we may have been signaled or it may + be a spurious wakeup. Check to see that there's actually + data in the queue before returning, and if not, go back + to sleep. See the pthread_cond_timedwait() man page for + details. */ + + if (dev->shutdown_thread || dev->disconnected) { + return -1; + } + } + + return 0; + +} + +int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) +{ + int bytes_read = -1; + + /* Lock the access to the report list. */ + pthread_mutex_lock(&dev->mutex); + + /* There's an input report queued up. Return it. */ + if (dev->input_reports) { + /* Return the first one */ + bytes_read = return_data(dev, data, length); + goto ret; + } + + /* Return if the device has been disconnected. */ + if (dev->disconnected) { + bytes_read = -1; + register_device_error(dev, "hid_read_timeout: device disconnected"); + goto ret; + } + + if (dev->shutdown_thread) { + /* This means the device has been closed (or there + has been an error. An error code of -1 should + be returned. */ + bytes_read = -1; + register_device_error(dev, "hid_read_timeout: thread shutdown"); + goto ret; + } + + /* There is no data. Go to sleep and wait for data. */ + + if (milliseconds == -1) { + /* Blocking */ + int res; + res = cond_wait(dev, &dev->condition, &dev->mutex); + if (res == 0) + bytes_read = return_data(dev, data, length); + else { + /* There was an error, or a device disconnection. */ + register_device_error(dev, "hid_read_timeout: error waiting for more data"); + bytes_read = -1; + } + } + else if (milliseconds > 0) { + /* Non-blocking, but called with timeout. */ + int res; + struct timespec ts; + struct timeval tv; + gettimeofday(&tv, NULL); + TIMEVAL_TO_TIMESPEC(&tv, &ts); + ts.tv_sec += milliseconds / 1000; + ts.tv_nsec += (milliseconds % 1000) * 1000000; + if (ts.tv_nsec >= 1000000000L) { + ts.tv_sec++; + ts.tv_nsec -= 1000000000L; + } + + res = cond_timedwait(dev, &dev->condition, &dev->mutex, &ts); + if (res == 0) { + bytes_read = return_data(dev, data, length); + } else if (res == ETIMEDOUT) { + bytes_read = 0; + } else { + register_device_error(dev, "hid_read_timeout: error waiting for more data"); + bytes_read = -1; + } + } + else { + /* Purely non-blocking */ + bytes_read = 0; + } + +ret: + /* Unlock */ + pthread_mutex_unlock(&dev->mutex); + return bytes_read; +} + +int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length) +{ + return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0); +} + +int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock) +{ + /* All Nonblocking operation is handled by the library. */ + dev->blocking = !nonblock; + + return 0; +} + +int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) +{ + return set_report(dev, kIOHIDReportTypeFeature, data, length); +} + +int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) +{ + return get_report(dev, kIOHIDReportTypeFeature, data, length); +} + +int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length) +{ + return get_report(dev, kIOHIDReportTypeInput, data, length); +} + +void HID_API_EXPORT hid_close(hid_device *dev) +{ + if (!dev) + return; + + /* Disconnect the report callback before close. + See comment below. + */ + if (is_macos_10_10_or_greater || !dev->disconnected) { + IOHIDDeviceRegisterInputReportCallback( + dev->device_handle, dev->input_report_buf, dev->max_input_report_len, + NULL, dev); + IOHIDDeviceRegisterRemovalCallback(dev->device_handle, NULL, dev); + IOHIDDeviceUnscheduleFromRunLoop(dev->device_handle, dev->run_loop, dev->run_loop_mode); + IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetMain(), kCFRunLoopDefaultMode); + } + + /* Cause read_thread() to stop. */ + dev->shutdown_thread = 1; + + /* Wake up the run thread's event loop so that the thread can exit. */ + CFRunLoopSourceSignal(dev->source); + CFRunLoopWakeUp(dev->run_loop); + + /* Notify the read thread that it can shut down now. */ + pthread_barrier_wait(&dev->shutdown_barrier); + + /* Wait for read_thread() to end. */ + pthread_join(dev->thread, NULL); + + /* Close the OS handle to the device, but only if it's not + been unplugged. If it's been unplugged, then calling + IOHIDDeviceClose() will crash. + + UPD: The crash part was true in/until some version of macOS. + Starting with macOS 10.15, there is an opposite effect in some environments: + crash happenes if IOHIDDeviceClose() is not called. + Not leaking a resource in all tested environments. + */ + if (is_macos_10_10_or_greater || !dev->disconnected) { + IOHIDDeviceClose(dev->device_handle, dev->open_options); + } + + /* Clear out the queue of received reports. */ + pthread_mutex_lock(&dev->mutex); + while (dev->input_reports) { + return_data(dev, NULL, 0); + } + pthread_mutex_unlock(&dev->mutex); + CFRelease(dev->device_handle); + + free_hid_device(dev); +} + +int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) +{ + if (!string || !maxlen) + { + register_device_error(dev, "Zero buffer/length"); + return -1; + } + + struct hid_device_info *info = hid_get_device_info(dev); + if (!info) + { + // hid_get_device_info will have set an error already + return -1; + } + + wcsncpy(string, info->manufacturer_string, maxlen); + string[maxlen - 1] = L'\0'; + + return 0; +} + +int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) +{ + if (!string || !maxlen) { + register_device_error(dev, "Zero buffer/length"); + return -1; + } + + struct hid_device_info *info = hid_get_device_info(dev); + if (!info) { + // hid_get_device_info will have set an error already + return -1; + } + + wcsncpy(string, info->product_string, maxlen); + string[maxlen - 1] = L'\0'; + + return 0; +} + +int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) +{ + if (!string || !maxlen) { + register_device_error(dev, "Zero buffer/length"); + return -1; + } + + struct hid_device_info *info = hid_get_device_info(dev); + if (!info) { + // hid_get_device_info will have set an error already + return -1; + } + + wcsncpy(string, info->serial_number, maxlen); + string[maxlen - 1] = L'\0'; + + return 0; +} + +HID_API_EXPORT struct hid_device_info *HID_API_CALL hid_get_device_info(hid_device *dev) { + if (!dev->device_info) { + dev->device_info = create_device_info(dev->device_handle); + if (!dev->device_info) { + register_device_error(dev, "Failed to create hid_device_info"); + } + } + + return dev->device_info; +} + +int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) +{ + (void) dev; + (void) string_index; + (void) string; + (void) maxlen; + + register_device_error(dev, "hid_get_indexed_string: not available on this platform"); + return -1; +} + +int HID_API_EXPORT_CALL hid_darwin_get_location_id(hid_device *dev, uint32_t *location_id) +{ + int res = get_int_property(dev->device_handle, CFSTR(kIOHIDLocationIDKey)); + if (res != 0) { + *location_id = (uint32_t) res; + return 0; + } else { + register_device_error(dev, "Failed to get IOHIDLocationID property"); + return -1; + } +} + +void HID_API_EXPORT_CALL hid_darwin_set_open_exclusive(int open_exclusive) +{ + device_open_options = (open_exclusive == 0) ? kIOHIDOptionsTypeNone : kIOHIDOptionsTypeSeizeDevice; +} + +int HID_API_EXPORT_CALL hid_darwin_get_open_exclusive(void) +{ + return (device_open_options == kIOHIDOptionsTypeSeizeDevice) ? 1 : 0; +} + +int HID_API_EXPORT_CALL hid_darwin_is_device_open_exclusive(hid_device *dev) +{ + if (!dev) + return -1; + + return (dev->open_options == kIOHIDOptionsTypeSeizeDevice) ? 1 : 0; +} + +int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size) +{ + CFTypeRef ref = IOHIDDeviceGetProperty(dev->device_handle, CFSTR(kIOHIDReportDescriptorKey)); + if (ref != NULL && CFGetTypeID(ref) == CFDataGetTypeID()) { + CFDataRef report_descriptor = (CFDataRef) ref; + const UInt8 *descriptor_buf = CFDataGetBytePtr(report_descriptor); + CFIndex descriptor_buf_len = CFDataGetLength(report_descriptor); + size_t copy_len = (size_t) descriptor_buf_len; + + if (descriptor_buf == NULL || descriptor_buf_len < 0) { + register_device_error(dev, "Zero buffer/length"); + return -1; + } + + if (buf_size < copy_len) { + copy_len = buf_size; + } + + memcpy(buf, descriptor_buf, copy_len); + return (int)copy_len; + } + else { + register_device_error(dev, "Failed to get kIOHIDReportDescriptorKey property"); + return -1; + } +} + +HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) +{ + if (dev) { + if (dev->last_error_str == NULL) + return L"Success"; + return dev->last_error_str; + } + + if (last_global_error_str == NULL) + return L"Success"; + return last_global_error_str; +} diff --git a/thirdparty/sdl/hidapi/mac/hidapi_darwin.h b/thirdparty/sdl/hidapi/mac/hidapi_darwin.h new file mode 100644 index 00000000000..14655836d25 --- /dev/null +++ b/thirdparty/sdl/hidapi/mac/hidapi_darwin.h @@ -0,0 +1,98 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +/** @file + * @defgroup API hidapi API + + * Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) + */ + +#ifndef HIDAPI_DARWIN_H__ +#define HIDAPI_DARWIN_H__ + +#include + +#include "../hidapi/hidapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + /** @brief Get the location ID for a HID device. + + Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) + + @ingroup API + @param dev A device handle returned from hid_open(). + @param location_id The device's location ID on return. + + @returns + This function returns 0 on success and -1 on error. + */ + int HID_API_EXPORT_CALL hid_darwin_get_location_id(hid_device *dev, uint32_t *location_id); + + + /** @brief Changes the behavior of all further calls to @ref hid_open or @ref hid_open_path. + + By default on Darwin platform all devices opened by HIDAPI with @ref hid_open or @ref hid_open_path + are opened in exclusive mode (see kIOHIDOptionsTypeSeizeDevice). + + Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) + + @ingroup API + @param open_exclusive When set to 0 - all further devices will be opened + in non-exclusive mode. Otherwise - all further devices will be opened + in exclusive mode. + + @note During the initialisation by @ref hid_init - this property is set to 1 (TRUE). + This is done to preserve full backward compatibility with previous behavior. + + @note Calling this function before @ref hid_init or after @ref hid_exit has no effect. + */ + void HID_API_EXPORT_CALL hid_darwin_set_open_exclusive(int open_exclusive); + + /** @brief Getter for option set by @ref hid_darwin_set_open_exclusive. + + Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) + + @ingroup API + @return 1 if all further devices will be opened in exclusive mode. + + @note Value returned by this function before calling to @ref hid_init or after @ref hid_exit + is not reliable. + */ + int HID_API_EXPORT_CALL hid_darwin_get_open_exclusive(void); + + /** @brief Check how the device was opened. + + Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) + + @ingroup API + @param dev A device to get property from. + + @return 1 if the device is opened in exclusive mode, 0 - opened in non-exclusive, + -1 - if dev is invalid. + */ + int HID_API_EXPORT_CALL hid_darwin_is_device_open_exclusive(hid_device *dev); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/thirdparty/sdl/hidapi/windows/hid.c b/thirdparty/sdl/hidapi/windows/hid.c new file mode 100644 index 00000000000..3376ba96e55 --- /dev/null +++ b/thirdparty/sdl/hidapi/windows/hid.c @@ -0,0 +1,1728 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + Alan Ott + Signal 11 Software + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +/* Do not warn about wcsncpy usage. + https://docs.microsoft.com/cpp/c-runtime-library/security-features-in-the-crt */ +#define _CRT_SECURE_NO_WARNINGS +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#include "hidapi_winapi.h" + +#include + +#ifndef _NTDEF_ +typedef LONG NTSTATUS; +#endif + +#ifndef WC_ERR_INVALID_CHARS +#define WC_ERR_INVALID_CHARS 0x00000080 +#endif +#ifndef _WIN32_WINNT_WIN8 +#define _WIN32_WINNT_WIN8 0x0602 +#endif + +#ifdef __CYGWIN__ +#include +#include +#define _wcsdup wcsdup +#endif + +/*#define HIDAPI_USE_DDK*/ + +#include "hidapi_cfgmgr32.h" +#include "hidapi_hidclass.h" +#include "hidapi_hidsdi.h" + +#ifndef HIDAPI_USING_SDL_RUNTIME +#include +#include +#include +#endif + +#ifdef MIN +#undef MIN +#endif +#define MIN(x,y) ((x) < (y)? (x): (y)) + +/* MAXIMUM_USB_STRING_LENGTH from usbspec.h is 255 */ +/* BLUETOOTH_DEVICE_NAME_SIZE from bluetoothapis.h is 256 */ +#define MAX_STRING_WCHARS 256 + +/* For certain USB devices, using a buffer larger or equal to 127 wchars results + in successful completion of HID API functions, but a broken string is stored + in the output buffer. This behaviour persists even if HID API is bypassed and + HID IOCTLs are passed to the HID driver directly. Therefore, for USB devices, + the buffer MUST NOT exceed 126 WCHARs. +*/ + +#define MAX_STRING_WCHARS_USB 126 + +static struct hid_api_version api_version = { + .major = HID_API_VERSION_MAJOR, + .minor = HID_API_VERSION_MINOR, + .patch = HID_API_VERSION_PATCH +}; + +#ifndef HIDAPI_USE_DDK +/* Since we're not building with the DDK, and the HID header + files aren't part of the Windows SDK, we define what we need ourselves. + In lookup_functions(), the function pointers + defined below are set. */ + +static HidD_GetHidGuid_ HidD_GetHidGuid; +static HidD_GetAttributes_ HidD_GetAttributes; +static HidD_GetSerialNumberString_ HidD_GetSerialNumberString; +static HidD_GetManufacturerString_ HidD_GetManufacturerString; +static HidD_GetProductString_ HidD_GetProductString; +static HidD_SetFeature_ HidD_SetFeature; +static HidD_GetFeature_ HidD_GetFeature; +static HidD_GetInputReport_ HidD_GetInputReport; +static HidD_GetIndexedString_ HidD_GetIndexedString; +static HidD_GetPreparsedData_ HidD_GetPreparsedData; +static HidD_FreePreparsedData_ HidD_FreePreparsedData; +static HidP_GetCaps_ HidP_GetCaps; +static HidD_SetNumInputBuffers_ HidD_SetNumInputBuffers; +static HidD_SetOutputReport_ HidD_SetOutputReport; + +static CM_Locate_DevNodeW_ CM_Locate_DevNodeW = NULL; +static CM_Get_Parent_ CM_Get_Parent = NULL; +static CM_Get_DevNode_PropertyW_ CM_Get_DevNode_PropertyW = NULL; +static CM_Get_Device_Interface_PropertyW_ CM_Get_Device_Interface_PropertyW = NULL; +static CM_Get_Device_Interface_List_SizeW_ CM_Get_Device_Interface_List_SizeW = NULL; +static CM_Get_Device_Interface_ListW_ CM_Get_Device_Interface_ListW = NULL; + +static HMODULE hid_lib_handle = NULL; +static HMODULE cfgmgr32_lib_handle = NULL; +static BOOLEAN hidapi_initialized = FALSE; + +static void free_library_handles(void) +{ + if (hid_lib_handle) + FreeLibrary(hid_lib_handle); + hid_lib_handle = NULL; + if (cfgmgr32_lib_handle) + FreeLibrary(cfgmgr32_lib_handle); + cfgmgr32_lib_handle = NULL; +} + +#if defined(__GNUC__) && __GNUC__ >= 8 +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wcast-function-type" +#endif + +static int lookup_functions(void) +{ + hid_lib_handle = LoadLibraryW(L"hid.dll"); + if (hid_lib_handle == NULL) { + goto err; + } + + cfgmgr32_lib_handle = LoadLibraryW(L"cfgmgr32.dll"); + if (cfgmgr32_lib_handle == NULL) { + goto err; + } + +#define RESOLVE(lib_handle, x) x = (x##_)GetProcAddress(lib_handle, #x); if (!x) goto err; + + RESOLVE(hid_lib_handle, HidD_GetHidGuid); + RESOLVE(hid_lib_handle, HidD_GetAttributes); + RESOLVE(hid_lib_handle, HidD_GetSerialNumberString); + RESOLVE(hid_lib_handle, HidD_GetManufacturerString); + RESOLVE(hid_lib_handle, HidD_GetProductString); + RESOLVE(hid_lib_handle, HidD_SetFeature); + RESOLVE(hid_lib_handle, HidD_GetFeature); + RESOLVE(hid_lib_handle, HidD_GetInputReport); + RESOLVE(hid_lib_handle, HidD_GetIndexedString); + RESOLVE(hid_lib_handle, HidD_GetPreparsedData); + RESOLVE(hid_lib_handle, HidD_FreePreparsedData); + RESOLVE(hid_lib_handle, HidP_GetCaps); + RESOLVE(hid_lib_handle, HidD_SetNumInputBuffers); + RESOLVE(hid_lib_handle, HidD_SetOutputReport); + + RESOLVE(cfgmgr32_lib_handle, CM_Locate_DevNodeW); + RESOLVE(cfgmgr32_lib_handle, CM_Get_Parent); + RESOLVE(cfgmgr32_lib_handle, CM_Get_DevNode_PropertyW); + RESOLVE(cfgmgr32_lib_handle, CM_Get_Device_Interface_PropertyW); + RESOLVE(cfgmgr32_lib_handle, CM_Get_Device_Interface_List_SizeW); + RESOLVE(cfgmgr32_lib_handle, CM_Get_Device_Interface_ListW); + +#undef RESOLVE + + return 0; + +err: + free_library_handles(); + return -1; +} + +#if defined(__GNUC__) && __GNUC__ >= 8 +# pragma GCC diagnostic pop +#endif + +#endif /* HIDAPI_USE_DDK */ + +struct hid_device_ { + HANDLE device_handle; + BOOL blocking; + USHORT output_report_length; + unsigned char *write_buf; + size_t input_report_length; + USHORT feature_report_length; + unsigned char *feature_buf; + wchar_t *last_error_str; + BOOL read_pending; + char *read_buf; + OVERLAPPED ol; + OVERLAPPED write_ol; + struct hid_device_info* device_info; + BOOL use_hid_write_output_report; +}; + +static BOOL IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor) +{ + OSVERSIONINFOEXW osvi; + DWORDLONG const dwlConditionMask = VerSetConditionMask( + VerSetConditionMask( + VerSetConditionMask( + 0, VER_MAJORVERSION, VER_GREATER_EQUAL ), + VER_MINORVERSION, VER_GREATER_EQUAL ), + VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL ); + + memset(&osvi, 0, sizeof(osvi)); + osvi.dwOSVersionInfoSize = sizeof( osvi ); + osvi.dwMajorVersion = wMajorVersion; + osvi.dwMinorVersion = wMinorVersion; + osvi.wServicePackMajor = wServicePackMajor; + + return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE; +} + +static hid_device *new_hid_device(void) +{ + hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device)); + + if (dev == NULL) { + return NULL; + } + + dev->device_handle = INVALID_HANDLE_VALUE; + dev->blocking = TRUE; + dev->output_report_length = 0; + dev->write_buf = NULL; + dev->input_report_length = 0; + dev->feature_report_length = 0; + dev->feature_buf = NULL; + dev->last_error_str = NULL; + dev->read_pending = FALSE; + dev->read_buf = NULL; + memset(&dev->ol, 0, sizeof(dev->ol)); + dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL); + memset(&dev->write_ol, 0, sizeof(dev->write_ol)); + dev->write_ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL); + dev->device_info = NULL; + + return dev; +} + +static void free_hid_device(hid_device *dev) +{ + CloseHandle(dev->ol.hEvent); + CloseHandle(dev->write_ol.hEvent); + CloseHandle(dev->device_handle); + free(dev->last_error_str); + dev->last_error_str = NULL; + free(dev->write_buf); + free(dev->feature_buf); + free(dev->read_buf); + hid_free_enumeration(dev->device_info); + free(dev); +} + +static void register_winapi_error_to_buffer(wchar_t **error_buffer, const WCHAR *op) +{ + WCHAR system_err_buf[1024]; + DWORD error_code = GetLastError(); + + free(*error_buffer); + *error_buffer = NULL; + +#ifdef HIDAPI_USING_SDL_RUNTIME + /* Thread-safe error handling */ + SDL_ClearError(); +#endif + + /* Only clear out error messages if NULL is passed into op */ + if (!op) { + return; + } + + DWORD system_err_len = FormatMessageW( + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + error_code, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + system_err_buf, ARRAYSIZE(system_err_buf), + NULL); + + DWORD op_len = (DWORD)wcslen(op); + + DWORD op_prefix_len = + op_len + + 15 /*: (0x00000000) */ + ; + DWORD msg_len = + + op_prefix_len + + system_err_len + ; + + WCHAR *msg = (WCHAR *)calloc(msg_len + 1, sizeof (WCHAR)); + + if (!msg) + return; + + int printf_written = swprintf(msg, msg_len + 1, L"%.*ls: (0x%08X) %.*ls", (int)op_len, op, error_code, (int)system_err_len, system_err_buf); + + if (printf_written < 0) + { + /* Highly unlikely */ + msg[0] = L'\0'; + return; + } + + /* Get rid of the CR and LF that FormatMessage() sticks at the + end of the message. Thanks Microsoft! */ + while(msg[msg_len-1] == L'\r' || msg[msg_len-1] == L'\n' || msg[msg_len-1] == L' ') + { + msg[msg_len-1] = L'\0'; + msg_len--; + } + +#ifdef HIDAPI_USING_SDL_RUNTIME + /* Thread-safe error handling */ + char *error_utf8 = SDL_iconv_wchar_utf8(msg); + if (error_utf8) { + SDL_SetError("%s", error_utf8); + SDL_free(error_utf8); + } + free(msg); +#else + *error_buffer = msg; +#endif +} + +#if defined(__GNUC__) && (__GNUC__ + (__GNUC_MINOR__ >= 6) > 4) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Warray-bounds" +#endif +/* A bug in GCC/mingw gives: + * error: array subscript 0 is outside array bounds of 'wchar_t *[0]' {aka 'short unsigned int *[]'} [-Werror=array-bounds] + * | free(*error_buffer); + * Which doesn't make sense in this context. */ + +static void register_string_error_to_buffer(wchar_t **error_buffer, const WCHAR *string_error) +{ + free(*error_buffer); + *error_buffer = NULL; + +#ifdef HIDAPI_USING_SDL_RUNTIME + /* Thread-safe error handling */ + char *error_utf8 = string_error ? SDL_iconv_wchar_utf8(string_error) : NULL; + if (error_utf8) { + SDL_SetError("%s", error_utf8); + SDL_free(error_utf8); + } else { + SDL_ClearError(); + } +#else + if (string_error) { + *error_buffer = _wcsdup(string_error); + } +#endif /* HIDAPI_USING_SDL_RUNTIME */ +} + +#if defined(__GNUC__) && (__GNUC__ + (__GNUC_MINOR__ >= 6) > 4) +# pragma GCC diagnostic pop +#endif + +static void register_winapi_error(hid_device *dev, const WCHAR *op) +{ + register_winapi_error_to_buffer(&dev->last_error_str, op); +} + +static void register_string_error(hid_device *dev, const WCHAR *string_error) +{ + register_string_error_to_buffer(&dev->last_error_str, string_error); +} + +static wchar_t *last_global_error_str = NULL; + +static void register_global_winapi_error(const WCHAR *op) +{ + register_winapi_error_to_buffer(&last_global_error_str, op); +} + +static void register_global_error(const WCHAR *string_error) +{ + register_string_error_to_buffer(&last_global_error_str, string_error); +} + +static HANDLE open_device(const wchar_t *path, BOOL open_rw) +{ + HANDLE handle; + DWORD desired_access = (open_rw)? (GENERIC_WRITE | GENERIC_READ): 0; + DWORD share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE; + + handle = CreateFileW(path, + desired_access, + share_mode, + NULL, + OPEN_EXISTING, + FILE_FLAG_OVERLAPPED,/*FILE_ATTRIBUTE_NORMAL,*/ + 0); + + return handle; +} + +HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void) +{ + return &api_version; +} + +HID_API_EXPORT const char* HID_API_CALL hid_version_str(void) +{ + return HID_API_VERSION_STR; +} + +int HID_API_EXPORT hid_init(void) +{ + register_global_error(NULL); +#ifndef HIDAPI_USE_DDK + if (!hidapi_initialized) { + if (lookup_functions() < 0) { + register_global_winapi_error(L"resolve DLL functions"); + return -1; + } + hidapi_initialized = TRUE; + } +#endif + return 0; +} + +int HID_API_EXPORT hid_exit(void) +{ +#ifndef HIDAPI_USE_DDK + free_library_handles(); + hidapi_initialized = FALSE; +#endif + register_global_error(NULL); + return 0; +} + +static void* hid_internal_get_devnode_property(DEVINST dev_node, const DEVPROPKEY* property_key, DEVPROPTYPE expected_property_type) +{ + ULONG len = 0; + CONFIGRET cr; + DEVPROPTYPE property_type; + PBYTE property_value = NULL; + + cr = CM_Get_DevNode_PropertyW(dev_node, property_key, &property_type, NULL, &len, 0); + if (cr != CR_BUFFER_SMALL || property_type != expected_property_type) + return NULL; + + property_value = (PBYTE)calloc(len, sizeof(BYTE)); + cr = CM_Get_DevNode_PropertyW(dev_node, property_key, &property_type, property_value, &len, 0); + if (cr != CR_SUCCESS) { + free(property_value); + return NULL; + } + + return property_value; +} + +static void* hid_internal_get_device_interface_property(const wchar_t* interface_path, const DEVPROPKEY* property_key, DEVPROPTYPE expected_property_type) +{ + ULONG len = 0; + CONFIGRET cr; + DEVPROPTYPE property_type; + PBYTE property_value = NULL; + + cr = CM_Get_Device_Interface_PropertyW(interface_path, property_key, &property_type, NULL, &len, 0); + if (cr != CR_BUFFER_SMALL || property_type != expected_property_type) + return NULL; + + property_value = (PBYTE)calloc(len, sizeof(BYTE)); + cr = CM_Get_Device_Interface_PropertyW(interface_path, property_key, &property_type, property_value, &len, 0); + if (cr != CR_SUCCESS) { + free(property_value); + return NULL; + } + + return property_value; +} + +static void hid_internal_towupper(wchar_t* string) +{ + for (wchar_t* p = string; *p; ++p) *p = towupper(*p); +} + +static int hid_internal_extract_int_token_value(wchar_t* string, const wchar_t* token) +{ + int token_value; + wchar_t* startptr, * endptr; + + startptr = wcsstr(string, token); + if (!startptr) + return -1; + + startptr += wcslen(token); + token_value = wcstol(startptr, &endptr, 16); + if (endptr == startptr) + return -1; + + return token_value; +} + +static void hid_internal_get_usb_info(struct hid_device_info* dev, DEVINST dev_node) +{ + wchar_t *device_id = NULL, *hardware_ids = NULL; + + device_id = hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); + if (!device_id) + goto end; + + /* Normalize to upper case */ + hid_internal_towupper(device_id); + + /* Check for Xbox Common Controller class (XUSB) device. + https://docs.microsoft.com/windows/win32/xinput/directinput-and-xusb-devices + https://docs.microsoft.com/windows/win32/xinput/xinput-and-directinput + */ + if (hid_internal_extract_int_token_value(device_id, L"IG_") != -1) { + /* Get devnode parent to reach out USB device. */ + if (CM_Get_Parent(&dev_node, dev_node, 0) != CR_SUCCESS) + goto end; + } + + /* Get the hardware ids from devnode */ + hardware_ids = hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_HardwareIds, DEVPROP_TYPE_STRING_LIST); + if (!hardware_ids) + goto end; + + /* Get additional information from USB device's Hardware ID + https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers + https://docs.microsoft.com/windows-hardware/drivers/usbcon/enumeration-of-interfaces-not-grouped-in-collections + */ + for (wchar_t* hardware_id = hardware_ids; *hardware_id; hardware_id += wcslen(hardware_id) + 1) { + /* Normalize to upper case */ + hid_internal_towupper(hardware_id); + + if (dev->release_number == 0) { + /* USB_DEVICE_DESCRIPTOR.bcdDevice value. */ + int release_number = hid_internal_extract_int_token_value(hardware_id, L"REV_"); + if (release_number != -1) { + dev->release_number = (unsigned short)release_number; + } + } + + if (dev->interface_number == -1) { + /* USB_INTERFACE_DESCRIPTOR.bInterfaceNumber value. */ + int interface_number = hid_internal_extract_int_token_value(hardware_id, L"MI_"); + if (interface_number != -1) { + dev->interface_number = interface_number; + } + } + } + + /* Try to get USB device manufacturer string if not provided by HidD_GetManufacturerString. */ + if (wcslen(dev->manufacturer_string) == 0) { + wchar_t* manufacturer_string = hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_Manufacturer, DEVPROP_TYPE_STRING); + if (manufacturer_string) { + free(dev->manufacturer_string); + dev->manufacturer_string = manufacturer_string; + } + } + + /* Try to get USB device serial number if not provided by HidD_GetSerialNumberString. */ + if (wcslen(dev->serial_number) == 0) { + DEVINST usb_dev_node = dev_node; + if (dev->interface_number != -1) { + /* Get devnode parent to reach out composite parent USB device. + https://docs.microsoft.com/windows-hardware/drivers/usbcon/enumeration-of-the-composite-parent-device + */ + if (CM_Get_Parent(&usb_dev_node, dev_node, 0) != CR_SUCCESS) + goto end; + } + + /* Get the device id of the USB device. */ + free(device_id); + device_id = hid_internal_get_devnode_property(usb_dev_node, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); + if (!device_id) + goto end; + + /* Extract substring after last '\\' of Instance ID. + For USB devices it may contain device's serial number. + https://docs.microsoft.com/windows-hardware/drivers/install/instance-ids + */ + for (wchar_t *ptr = device_id + wcslen(device_id); ptr > device_id; --ptr) { + /* Instance ID is unique only within the scope of the bus. + For USB devices it means that serial number is not available. Skip. */ + if (*ptr == L'&') + break; + + if (*ptr == L'\\') { + free(dev->serial_number); + dev->serial_number = _wcsdup(ptr + 1); + break; + } + } + } + + /* If we can't get the interface number, it means that there is only one interface. */ + if (dev->interface_number == -1) + dev->interface_number = 0; + +end: + free(device_id); + free(hardware_ids); +} + +/* HidD_GetProductString/HidD_GetManufacturerString/HidD_GetSerialNumberString is not working for BLE HID devices + Request this info via dev node properties instead. + https://docs.microsoft.com/answers/questions/401236/hidd-getproductstring-with-ble-hid-device.html +*/ +static void hid_internal_get_ble_info(struct hid_device_info* dev, DEVINST dev_node) +{ + if (wcslen(dev->manufacturer_string) == 0) { + /* Manufacturer Name String (UUID: 0x2A29) */ + wchar_t* manufacturer_string = hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_Manufacturer, DEVPROP_TYPE_STRING); + if (manufacturer_string) { + free(dev->manufacturer_string); + dev->manufacturer_string = manufacturer_string; + } + } + + if (wcslen(dev->serial_number) == 0) { + /* Serial Number String (UUID: 0x2A25) */ + wchar_t* serial_number = hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_DeviceAddress, DEVPROP_TYPE_STRING); + if (serial_number) { + free(dev->serial_number); + dev->serial_number = serial_number; + } + } + + if (wcslen(dev->product_string) == 0) { + /* Model Number String (UUID: 0x2A24) */ + wchar_t* product_string = hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_ModelNumber, DEVPROP_TYPE_STRING); + if (!product_string) { + DEVINST parent_dev_node = 0; + /* Fallback: Get devnode grandparent to reach out Bluetooth LE device node */ + if (CM_Get_Parent(&parent_dev_node, dev_node, 0) == CR_SUCCESS) { + /* Device Name (UUID: 0x2A00) */ + product_string = hid_internal_get_devnode_property(parent_dev_node, &DEVPKEY_NAME, DEVPROP_TYPE_STRING); + } + } + + if (product_string) { + free(dev->product_string); + dev->product_string = product_string; + } + } +} + +#ifdef HIDAPI_IGNORE_DEVICE +static hid_bus_type get_bus_type(const wchar_t* interface_path) +{ + wchar_t *device_id = NULL, *compatible_ids = NULL; + CONFIGRET cr; + DEVINST dev_node; + hid_bus_type bus_type = HID_API_BUS_UNKNOWN; + + /* Get the device id from interface path */ + device_id = hid_internal_get_device_interface_property(interface_path, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); + if (!device_id) + goto end; + + /* Open devnode from device id */ + cr = CM_Locate_DevNodeW(&dev_node, (DEVINSTID_W)device_id, CM_LOCATE_DEVNODE_NORMAL); + if (cr != CR_SUCCESS) + goto end; + + /* Get devnode parent */ + cr = CM_Get_Parent(&dev_node, dev_node, 0); + if (cr != CR_SUCCESS) + goto end; + + /* Get the compatible ids from parent devnode */ + compatible_ids = hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_CompatibleIds, DEVPROP_TYPE_STRING_LIST); + if (!compatible_ids) + goto end; + + /* Now we can parse parent's compatible IDs to find out the device bus type */ + for (wchar_t* compatible_id = compatible_ids; *compatible_id; compatible_id += wcslen(compatible_id) + 1) { + /* Normalize to upper case */ + hid_internal_towupper(compatible_id); + + /* USB devices + https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support + https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers */ + if (wcsstr(compatible_id, L"USB") != NULL) { + bus_type = HID_API_BUS_USB; + break; + } + + /* Bluetooth devices + https://docs.microsoft.com/windows-hardware/drivers/bluetooth/installing-a-bluetooth-device */ + if (wcsstr(compatible_id, L"BTHENUM") != NULL) { + bus_type = HID_API_BUS_BLUETOOTH; + break; + } + + /* Bluetooth LE devices */ + if (wcsstr(compatible_id, L"BTHLEDEVICE") != NULL) { + bus_type = HID_API_BUS_BLUETOOTH; + break; + } + + /* I2C devices + https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support-and-power-management */ + if (wcsstr(compatible_id, L"PNP0C50") != NULL) { + bus_type = HID_API_BUS_I2C; + break; + } + + /* SPI devices + https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-for-spi */ + if (wcsstr(compatible_id, L"PNP0C51") != NULL) { + bus_type = HID_API_BUS_SPI; + break; + } + } +end: + free(device_id); + free(compatible_ids); + return bus_type; +} +#endif /* HIDAPI_IGNORE_DEVICE */ + +/* Unfortunately, HID_API_BUS_xxx constants alone aren't enough to distinguish between BLUETOOTH and BLE */ + +#define HID_API_BUS_FLAG_BLE 0x01 + +typedef struct hid_internal_detect_bus_type_result_ { + DEVINST dev_node; + hid_bus_type bus_type; + unsigned int bus_flags; +} hid_internal_detect_bus_type_result; + +static hid_internal_detect_bus_type_result hid_internal_detect_bus_type(const wchar_t* interface_path) +{ + wchar_t *device_id = NULL, *compatible_ids = NULL; + CONFIGRET cr; + DEVINST dev_node; + hid_internal_detect_bus_type_result result = { 0 }; + + /* Get the device id from interface path */ + device_id = hid_internal_get_device_interface_property(interface_path, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); + if (!device_id) + goto end; + + /* Open devnode from device id */ + cr = CM_Locate_DevNodeW(&dev_node, (DEVINSTID_W)device_id, CM_LOCATE_DEVNODE_NORMAL); + if (cr != CR_SUCCESS) + goto end; + + /* Get devnode parent */ + cr = CM_Get_Parent(&dev_node, dev_node, 0); + if (cr != CR_SUCCESS) + goto end; + + /* Get the compatible ids from parent devnode */ + compatible_ids = hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_CompatibleIds, DEVPROP_TYPE_STRING_LIST); + if (!compatible_ids) + goto end; + + /* Now we can parse parent's compatible IDs to find out the device bus type */ + for (wchar_t* compatible_id = compatible_ids; *compatible_id; compatible_id += wcslen(compatible_id) + 1) { + /* Normalize to upper case */ + hid_internal_towupper(compatible_id); + + /* USB devices + https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support + https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers */ + if (wcsstr(compatible_id, L"USB") != NULL) { + result.bus_type = HID_API_BUS_USB; + break; + } + + /* Bluetooth devices + https://docs.microsoft.com/windows-hardware/drivers/bluetooth/installing-a-bluetooth-device */ + if (wcsstr(compatible_id, L"BTHENUM") != NULL) { + result.bus_type = HID_API_BUS_BLUETOOTH; + break; + } + + /* Bluetooth LE devices */ + if (wcsstr(compatible_id, L"BTHLEDEVICE") != NULL) { + result.bus_type = HID_API_BUS_BLUETOOTH; + result.bus_flags |= HID_API_BUS_FLAG_BLE; + break; + } + + /* I2C devices + https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support-and-power-management */ + if (wcsstr(compatible_id, L"PNP0C50") != NULL) { + result.bus_type = HID_API_BUS_I2C; + break; + } + + /* SPI devices + https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-for-spi */ + if (wcsstr(compatible_id, L"PNP0C51") != NULL) { + result.bus_type = HID_API_BUS_SPI; + break; + } + } + + result.dev_node = dev_node; + +end: + free(device_id); + free(compatible_ids); + return result; +} + +static char *hid_internal_UTF16toUTF8(const wchar_t *src) +{ + char *dst = NULL; +#ifdef HIDAPI_USING_SDL_RUNTIME + int len = WIN_WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, NULL, 0, NULL, NULL); +#else + int len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, NULL, 0, NULL, NULL); +#endif + if (len) { + dst = (char*)calloc(len, sizeof(char)); + if (dst == NULL) { + return NULL; + } +#ifdef HIDAPI_USING_SDL_RUNTIME + WIN_WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, dst, len, NULL, NULL); +#else + WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, dst, len, NULL, NULL); +#endif + } + + return dst; +} + +static wchar_t *hid_internal_UTF8toUTF16(const char *src) +{ + wchar_t *dst = NULL; + int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, NULL, 0); + if (len) { + dst = (wchar_t*)calloc(len, sizeof(wchar_t)); + if (dst == NULL) { + return NULL; + } + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, dst, len); + } + + return dst; +} + +static struct hid_device_info *hid_internal_get_device_info(const wchar_t *path, HANDLE handle) +{ + struct hid_device_info *dev = NULL; /* return object */ + HIDD_ATTRIBUTES attrib; + PHIDP_PREPARSED_DATA pp_data = NULL; + HIDP_CAPS caps; + wchar_t string[MAX_STRING_WCHARS + 1]; + ULONG len; + ULONG size; + hid_internal_detect_bus_type_result detect_bus_type_result; + + /* Create the record. */ + dev = (struct hid_device_info*)calloc(1, sizeof(struct hid_device_info)); + + if (dev == NULL) { + return NULL; + } + + /* Fill out the record */ + dev->next = NULL; + dev->path = hid_internal_UTF16toUTF8(path); + dev->interface_number = -1; + + attrib.Size = sizeof(HIDD_ATTRIBUTES); + if (HidD_GetAttributes(handle, &attrib)) { + /* VID/PID */ + dev->vendor_id = attrib.VendorID; + dev->product_id = attrib.ProductID; + + /* Release Number */ + dev->release_number = attrib.VersionNumber; + } + + /* Get the Usage Page and Usage for this device. */ + if (HidD_GetPreparsedData(handle, &pp_data)) { + if (HidP_GetCaps(pp_data, &caps) == HIDP_STATUS_SUCCESS) { + dev->usage_page = caps.UsagePage; + dev->usage = caps.Usage; + } + + HidD_FreePreparsedData(pp_data); + } + + /* detect bus type before reading string descriptors */ + detect_bus_type_result = hid_internal_detect_bus_type(path); + dev->bus_type = detect_bus_type_result.bus_type; + + len = dev->bus_type == HID_API_BUS_USB ? MAX_STRING_WCHARS_USB : MAX_STRING_WCHARS; + string[len] = L'\0'; + size = len * sizeof(wchar_t); + + /* Serial Number */ + string[0] = L'\0'; + HidD_GetSerialNumberString(handle, string, size); + dev->serial_number = _wcsdup(string); + + /* Manufacturer String */ + string[0] = L'\0'; + HidD_GetManufacturerString(handle, string, size); + dev->manufacturer_string = _wcsdup(string); + + /* Product String */ + string[0] = L'\0'; + HidD_GetProductString(handle, string, size); + dev->product_string = _wcsdup(string); + + /* now, the portion that depends on string descriptors */ + switch (dev->bus_type) { + case HID_API_BUS_USB: + hid_internal_get_usb_info(dev, detect_bus_type_result.dev_node); + break; + + case HID_API_BUS_BLUETOOTH: + if (detect_bus_type_result.bus_flags & HID_API_BUS_FLAG_BLE) + hid_internal_get_ble_info(dev, detect_bus_type_result.dev_node); + break; + + case HID_API_BUS_UNKNOWN: + case HID_API_BUS_SPI: + case HID_API_BUS_I2C: + /* shut down -Wswitch */ + break; + } + + return dev; +} + +static int hid_blacklist(unsigned short vendor_id, unsigned short product_id) +{ + size_t i; + static const struct { unsigned short vid; unsigned short pid; } known_bad[] = { + { 0x045E, 0x0822 }, /* Microsoft Precision Mouse - causes deadlock asking for device details */ + { 0x0738, 0x2217 }, /* SPEEDLINK COMPETITION PRO - turns into an Android controller when enumerated */ + { 0x0D8C, 0x0014 }, /* Sharkoon Skiller SGH2 headset - causes deadlock asking for device details */ + { 0x1532, 0x0109 }, /* Razer Lycosa Gaming keyboard - causes deadlock asking for device details */ + { 0x1532, 0x010B }, /* Razer Arctosa Gaming keyboard - causes deadlock asking for device details */ + { 0x1B1C, 0x1B3D }, /* Corsair Gaming keyboard - causes deadlock asking for device details */ + { 0x1CCF, 0x0000 } /* All Konami Amusement Devices - causes deadlock asking for device details */ + }; + + for (i = 0; i < (sizeof(known_bad)/sizeof(known_bad[0])); i++) { + if ((vendor_id == known_bad[i].vid) && (product_id == known_bad[i].pid || known_bad[i].pid == 0x0000)) { + return 1; + } + } + + return 0; +} + +struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id) +{ + struct hid_device_info *root = NULL; /* return object */ + struct hid_device_info *cur_dev = NULL; + GUID interface_class_guid; + CONFIGRET cr; + wchar_t* device_interface_list = NULL; + DWORD len; + + if (hid_init() < 0) { + /* register_global_error: global error is reset by hid_init */ + return NULL; + } + + /* Retrieve HID Interface Class GUID + https://docs.microsoft.com/windows-hardware/drivers/install/guid-devinterface-hid */ + HidD_GetHidGuid(&interface_class_guid); + + /* Get the list of all device interfaces belonging to the HID class. */ + /* Retry in case of list was changed between calls to + CM_Get_Device_Interface_List_SizeW and CM_Get_Device_Interface_ListW */ + do { + cr = CM_Get_Device_Interface_List_SizeW(&len, &interface_class_guid, NULL, CM_GET_DEVICE_INTERFACE_LIST_PRESENT); + if (cr != CR_SUCCESS) { + register_global_error(L"Failed to get size of HID device interface list"); + break; + } + + if (device_interface_list != NULL) { + free(device_interface_list); + } + + device_interface_list = (wchar_t*)calloc(len, sizeof(wchar_t)); + if (device_interface_list == NULL) { + register_global_error(L"Failed to allocate memory for HID device interface list"); + return NULL; + } + cr = CM_Get_Device_Interface_ListW(&interface_class_guid, NULL, device_interface_list, len, CM_GET_DEVICE_INTERFACE_LIST_PRESENT); + if (cr != CR_SUCCESS && cr != CR_BUFFER_SMALL) { + register_global_error(L"Failed to get HID device interface list"); + } + } while (cr == CR_BUFFER_SMALL); + + if (cr != CR_SUCCESS) { + goto end_of_function; + } + + /* Iterate over each device interface in the HID class, looking for the right one. */ + for (wchar_t* device_interface = device_interface_list; *device_interface; device_interface += wcslen(device_interface) + 1) { + HANDLE device_handle = INVALID_HANDLE_VALUE; + HIDD_ATTRIBUTES attrib; + + /* XInput devices don't get real HID reports and are better handled by the raw input driver */ + if (wcsstr(device_interface, L"&IG_") != NULL) { + continue; + } + + /* Open read-only handle to the device */ + device_handle = open_device(device_interface, FALSE); + + /* Check validity of device_handle. */ + if (device_handle == INVALID_HANDLE_VALUE) { + /* Unable to open the device. */ + continue; + } + + /* Get the Vendor ID and Product ID for this device. */ + attrib.Size = sizeof(HIDD_ATTRIBUTES); + if (!HidD_GetAttributes(device_handle, &attrib)) { + goto cont_close; + } + +#ifdef HIDAPI_IGNORE_DEVICE + /* See if there are any devices we should skip in enumeration */ + hid_bus_type bus_type = get_bus_type(device_interface); + PHIDP_PREPARSED_DATA pp_data = NULL; + HIDP_CAPS caps = { 0 }; + if (HidD_GetPreparsedData(device_handle, &pp_data)) { + HidP_GetCaps(pp_data, &caps); + HidD_FreePreparsedData(pp_data); + } + if (HIDAPI_IGNORE_DEVICE(bus_type, attrib.VendorID, attrib.ProductID, caps.UsagePage, caps.Usage)) { + goto cont_close; + } +#endif + + /* Check the VID/PID to see if we should add this + device to the enumeration list. */ + if ((vendor_id == 0x0 || attrib.VendorID == vendor_id) && + (product_id == 0x0 || attrib.ProductID == product_id) && + !hid_blacklist(attrib.VendorID, attrib.ProductID)) { + + /* VID/PID match. Create the record. */ + struct hid_device_info *tmp = hid_internal_get_device_info(device_interface, device_handle); + + if (tmp == NULL) { + goto cont_close; + } + + if (cur_dev) { + cur_dev->next = tmp; + } + else { + root = tmp; + } + cur_dev = tmp; + } + +cont_close: + CloseHandle(device_handle); + } + + if (root == NULL) { + if (vendor_id == 0 && product_id == 0) { + register_global_error(L"No HID devices found in the system."); + } else { + register_global_error(L"No HID devices with requested VID/PID found in the system."); + } + } + +end_of_function: + free(device_interface_list); + + return root; +} + +void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs) +{ + /* TODO: Merge this with the Linux version. This function is platform-independent. */ + struct hid_device_info *d = devs; + while (d) { + struct hid_device_info *next = d->next; + free(d->path); + free(d->serial_number); + free(d->manufacturer_string); + free(d->product_string); + free(d); + d = next; + } +} + +HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) +{ + /* TODO: Merge this functions with the Linux version. This function should be platform independent. */ + struct hid_device_info *devs, *cur_dev; + const char *path_to_open = NULL; + hid_device *handle = NULL; + + /* register_global_error: global error is reset by hid_enumerate/hid_init */ + devs = hid_enumerate(vendor_id, product_id); + if (!devs) { + /* register_global_error: global error is already set by hid_enumerate */ + return NULL; + } + + cur_dev = devs; + while (cur_dev) { + if (cur_dev->vendor_id == vendor_id && + cur_dev->product_id == product_id) { + if (serial_number) { + if (cur_dev->serial_number && wcscmp(serial_number, cur_dev->serial_number) == 0) { + path_to_open = cur_dev->path; + break; + } + } + else { + path_to_open = cur_dev->path; + break; + } + } + cur_dev = cur_dev->next; + } + + if (path_to_open) { + /* Open the device */ + handle = hid_open_path(path_to_open); + } else { + register_global_error(L"Device with requested VID/PID/(SerialNumber) not found"); + } + + hid_free_enumeration(devs); + + return handle; +} + +HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path) +{ + hid_device *dev = NULL; + wchar_t* interface_path = NULL; + HANDLE device_handle = INVALID_HANDLE_VALUE; + PHIDP_PREPARSED_DATA pp_data = NULL; + HIDP_CAPS caps; + + if (hid_init() < 0) { + /* register_global_error: global error is reset by hid_init */ + goto end_of_function; + } + + interface_path = hid_internal_UTF8toUTF16(path); + if (!interface_path) { + register_global_error(L"Path conversion failure"); + goto end_of_function; + } + + /* Open a handle to the device */ + device_handle = open_device(interface_path, TRUE); + + /* Check validity of write_handle. */ + if (device_handle == INVALID_HANDLE_VALUE) { + /* System devices, such as keyboards and mice, cannot be opened in + read-write mode, because the system takes exclusive control over + them. This is to prevent keyloggers. However, feature reports + can still be sent and received. Retry opening the device, but + without read/write access. */ + device_handle = open_device(interface_path, FALSE); + + /* Check the validity of the limited device_handle. */ + if (device_handle == INVALID_HANDLE_VALUE) { + register_global_winapi_error(L"open_device"); + goto end_of_function; + } + } + + /* Set the Input Report buffer size to 64 reports. */ + if (!HidD_SetNumInputBuffers(device_handle, 64)) { + register_global_winapi_error(L"set input buffers"); + goto end_of_function; + } + + /* Get the Input Report length for the device. */ + if (!HidD_GetPreparsedData(device_handle, &pp_data)) { + register_global_winapi_error(L"get preparsed data"); + goto end_of_function; + } + + if (HidP_GetCaps(pp_data, &caps) != HIDP_STATUS_SUCCESS) { + register_global_error(L"HidP_GetCaps"); + goto end_of_function; + } + + dev = new_hid_device(); + + if (dev == NULL) { + register_global_error(L"hid_device allocation error"); + goto end_of_function; + } + + dev->device_handle = device_handle; + device_handle = INVALID_HANDLE_VALUE; + + dev->output_report_length = caps.OutputReportByteLength; + dev->input_report_length = caps.InputReportByteLength; + dev->feature_report_length = caps.FeatureReportByteLength; + dev->read_buf = (char*) malloc(dev->input_report_length); + dev->device_info = hid_internal_get_device_info(interface_path, dev->device_handle); + + /* On Windows 7, we need to use hid_write_output_report() over Bluetooth */ + if (dev->output_report_length > 512) { + dev->use_hid_write_output_report = !IsWindowsVersionOrGreater( HIBYTE( _WIN32_WINNT_WIN8 ), LOBYTE( _WIN32_WINNT_WIN8 ), 0 ); + } + +end_of_function: + free(interface_path); + CloseHandle(device_handle); + + if (pp_data) { + HidD_FreePreparsedData(pp_data); + } + + return dev; +} + +static int hid_write_output_report(hid_device *dev, const unsigned char *data, size_t length) +{ + BOOL res; + res = HidD_SetOutputReport(dev->device_handle, (void *)data, (ULONG)length); + if (res) + return (int)length; + else + return -1; +} + +int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length) +{ + DWORD bytes_written = 0; + int function_result = -1; + BOOL res; + BOOL overlapped = FALSE; + + unsigned char *buf; + + if (!data || !length) { + register_string_error(dev, L"Zero buffer/length"); + return function_result; + } + + register_string_error(dev, NULL); + + if (dev->use_hid_write_output_report) { + return hid_write_output_report(dev, data, length); + } + + /* Make sure the right number of bytes are passed to WriteFile. Windows + expects the number of bytes which are in the _longest_ report (plus + one for the report number) bytes even if the data is a report + which is shorter than that. Windows gives us this value in + caps.OutputReportByteLength. If a user passes in fewer bytes than this, + use cached temporary buffer which is the proper size. */ + if (length >= dev->output_report_length) { + /* The user passed the right number of bytes. Use the buffer as-is. */ + buf = (unsigned char *) data; + } else { + if (dev->write_buf == NULL) + dev->write_buf = (unsigned char *) malloc(dev->output_report_length); + buf = dev->write_buf; + memcpy(buf, data, length); + memset(buf + length, 0, dev->output_report_length - length); + length = dev->output_report_length; + } + + res = WriteFile(dev->device_handle, buf, (DWORD) length, &bytes_written, &dev->write_ol); + + if (!res) { + if (GetLastError() != ERROR_IO_PENDING) { + /* WriteFile() failed. Return error. */ + register_winapi_error(dev, L"WriteFile"); + goto end_of_function; + } + overlapped = TRUE; + } else { + /* WriteFile() succeeded synchronously. */ + function_result = bytes_written; + } + + if (overlapped) { + /* Wait for the transaction to complete. This makes + hid_write() synchronous. */ + res = WaitForSingleObject(dev->write_ol.hEvent, 1000); + if (res != WAIT_OBJECT_0) { + /* There was a Timeout. */ + register_winapi_error(dev, L"hid_write/WaitForSingleObject"); + goto end_of_function; + } + + /* Get the result. */ + res = GetOverlappedResult(dev->device_handle, &dev->write_ol, &bytes_written, FALSE/*wait*/); + if (res) { + function_result = bytes_written; + } + else { + /* The Write operation failed. */ + register_winapi_error(dev, L"hid_write/GetOverlappedResult"); + goto end_of_function; + } + } + +end_of_function: + return function_result; +} + + +int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) +{ + DWORD bytes_read = 0; + size_t copy_len = 0; + BOOL res = FALSE; + BOOL overlapped = FALSE; + + if (!data || !length) { + register_string_error(dev, L"Zero buffer/length"); + return -1; + } + + register_string_error(dev, NULL); + + /* Copy the handle for convenience. */ + HANDLE ev = dev->ol.hEvent; + + if (!dev->read_pending) { + /* Start an Overlapped I/O read. */ + dev->read_pending = TRUE; + memset(dev->read_buf, 0, dev->input_report_length); + ResetEvent(ev); + res = ReadFile(dev->device_handle, dev->read_buf, (DWORD) dev->input_report_length, &bytes_read, &dev->ol); + + if (!res) { + if (GetLastError() != ERROR_IO_PENDING) { + /* ReadFile() has failed. + Clean up and return error. */ + register_winapi_error(dev, L"ReadFile"); + CancelIo(dev->device_handle); + dev->read_pending = FALSE; + goto end_of_function; + } + overlapped = TRUE; + } + } + else { + overlapped = TRUE; + } + + if (overlapped) { + /* See if there is any data yet. */ + res = WaitForSingleObject(ev, milliseconds >= 0 ? (DWORD)milliseconds : INFINITE); + if (res != WAIT_OBJECT_0) { + /* There was no data this time. Return zero bytes available, + but leave the Overlapped I/O running. */ + return 0; + } + + /* Get the number of bytes read. The actual data has been copied to the data[] + array which was passed to ReadFile(). We must not wait here because we've + already waited on our event above, and since it's auto-reset, it will have + been reset back to unsignalled by now. */ + res = GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, FALSE/*don't wait now - already did on the prev step*/); + } + /* Set pending back to false, even if GetOverlappedResult() returned error. */ + dev->read_pending = FALSE; + + if (res && bytes_read > 0) { + if (dev->read_buf[0] == 0x0) { + /* If report numbers aren't being used, but Windows sticks a report + number (0x0) on the beginning of the report anyway. To make this + work like the other platforms, and to make it work more like the + HID spec, we'll skip over this byte. */ + bytes_read--; + copy_len = length > bytes_read ? bytes_read : length; + memcpy(data, dev->read_buf+1, copy_len); + } + else { + /* Copy the whole buffer, report number and all. */ + copy_len = length > bytes_read ? bytes_read : length; + memcpy(data, dev->read_buf, copy_len); + } + } + if (!res) { + register_winapi_error(dev, L"hid_read_timeout/GetOverlappedResult"); + } + +end_of_function: + if (!res) { + return -1; + } + + return (int) copy_len; +} + +int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length) +{ + return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0); +} + +int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonblock) +{ + dev->blocking = !nonblock; + return 0; /* Success */ +} + +int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) +{ + BOOL res = FALSE; + unsigned char *buf; + size_t length_to_send; + + if (!data || !length) { + register_string_error(dev, L"Zero buffer/length"); + return -1; + } + + register_string_error(dev, NULL); + + /* Windows expects at least caps.FeatureReportByteLength bytes passed + to HidD_SetFeature(), even if the report is shorter. Any less sent and + the function fails with error ERROR_INVALID_PARAMETER set. Any more + and HidD_SetFeature() silently truncates the data sent in the report + to caps.FeatureReportByteLength. */ + if (length >= dev->feature_report_length) { + buf = (unsigned char *) data; + length_to_send = length; + } else { + if (dev->feature_buf == NULL) + dev->feature_buf = (unsigned char *) malloc(dev->feature_report_length); + buf = dev->feature_buf; + memcpy(buf, data, length); + memset(buf + length, 0, dev->feature_report_length - length); + length_to_send = dev->feature_report_length; + } + + res = HidD_SetFeature(dev->device_handle, (PVOID)buf, (DWORD) length_to_send); + + if (!res) { + register_winapi_error(dev, L"HidD_SetFeature"); + return -1; + } + + return (int) length; +} + +static int hid_get_report(hid_device *dev, DWORD report_type, unsigned char *data, size_t length) +{ + BOOL res; + DWORD bytes_returned = 0; + + OVERLAPPED ol; + memset(&ol, 0, sizeof(ol)); + + if (!data || !length) { + register_string_error(dev, L"Zero buffer/length"); + return -1; + } + + register_string_error(dev, NULL); + + res = DeviceIoControl(dev->device_handle, + report_type, + data, (DWORD) length, + data, (DWORD) length, + &bytes_returned, &ol); + + if (!res) { + if (GetLastError() != ERROR_IO_PENDING) { + /* DeviceIoControl() failed. Return error. */ + register_winapi_error(dev, L"Get Input/Feature Report DeviceIoControl"); + return -1; + } + } + + /* Wait here until the write is done. This makes + hid_get_feature_report() synchronous. */ + res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/); + if (!res) { + /* The operation failed. */ + register_winapi_error(dev, L"Get Input/Feature Report GetOverLappedResult"); + return -1; + } + + /* When numbered reports aren't used, + bytes_returned seem to include only what is actually received from the device + (not including the first byte with 0, as an indication "no numbered reports"). */ + if (data[0] == 0x0) { + bytes_returned++; + } + + return bytes_returned; +} + +int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) +{ + /* We could use HidD_GetFeature() instead, but it doesn't give us an actual length, unfortunately */ + return hid_get_report(dev, IOCTL_HID_GET_FEATURE, data, length); +} + +int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length) +{ + /* We could use HidD_GetInputReport() instead, but it doesn't give us an actual length, unfortunately */ + return hid_get_report(dev, IOCTL_HID_GET_INPUT_REPORT, data, length); +} + +#if defined(__GNUC__) && __GNUC__ >= 8 +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wcast-function-type" +#endif +void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev) +{ + typedef BOOL (WINAPI *CancelIoEx_t)(HANDLE hFile, LPOVERLAPPED lpOverlapped); + CancelIoEx_t CancelIoExFunc = (CancelIoEx_t)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "CancelIoEx"); + + if (!dev) + return; + + if (CancelIoExFunc) { + CancelIoExFunc(dev->device_handle, NULL); + } else { + /* Windows XP, this will only cancel I/O on the current thread */ + CancelIo(dev->device_handle); + } + if (dev->read_pending) { + DWORD bytes_read = 0; + GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/); + } + free_hid_device(dev); +} +#if defined(__GNUC__) && __GNUC__ >= 8 +# pragma GCC diagnostic pop +#endif + +int HID_API_EXPORT_CALL HID_API_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) +{ + if (!string || !maxlen) { + register_string_error(dev, L"Zero buffer/length"); + return -1; + } + + if (!dev->device_info) { + register_string_error(dev, L"NULL device info"); + return -1; + } + + wcsncpy(string, dev->device_info->manufacturer_string, maxlen); + string[maxlen - 1] = L'\0'; + + register_string_error(dev, NULL); + + return 0; +} + +int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) +{ + if (!string || !maxlen) { + register_string_error(dev, L"Zero buffer/length"); + return -1; + } + + if (!dev->device_info) { + register_string_error(dev, L"NULL device info"); + return -1; + } + + wcsncpy(string, dev->device_info->product_string, maxlen); + string[maxlen - 1] = L'\0'; + + register_string_error(dev, NULL); + + return 0; +} + +int HID_API_EXPORT_CALL HID_API_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) +{ + if (!string || !maxlen) { + register_string_error(dev, L"Zero buffer/length"); + return -1; + } + + if (!dev->device_info) { + register_string_error(dev, L"NULL device info"); + return -1; + } + + wcsncpy(string, dev->device_info->serial_number, maxlen); + string[maxlen - 1] = L'\0'; + + register_string_error(dev, NULL); + + return 0; +} + +HID_API_EXPORT struct hid_device_info * HID_API_CALL hid_get_device_info(hid_device *dev) { + if (!dev->device_info) + { + register_string_error(dev, L"NULL device info"); + return NULL; + } + + return dev->device_info; +} + +int HID_API_EXPORT_CALL HID_API_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) +{ + BOOL res; + + if (dev->device_info && dev->device_info->bus_type == HID_API_BUS_USB && maxlen > MAX_STRING_WCHARS_USB) { + string[MAX_STRING_WCHARS_USB] = L'\0'; + maxlen = MAX_STRING_WCHARS_USB; + } + + res = HidD_GetIndexedString(dev->device_handle, string_index, string, (ULONG)maxlen * sizeof(wchar_t)); + if (!res) { + register_winapi_error(dev, L"HidD_GetIndexedString"); + return -1; + } + + register_string_error(dev, NULL); + + return 0; +} + +int HID_API_EXPORT_CALL hid_winapi_get_container_id(hid_device *dev, GUID *container_id) +{ + wchar_t *interface_path = NULL, *device_id = NULL; + CONFIGRET cr = CR_FAILURE; + DEVINST dev_node; + DEVPROPTYPE property_type; + ULONG len; + + if (!container_id) { + register_string_error(dev, L"Invalid Container ID"); + return -1; + } + + register_string_error(dev, NULL); + + interface_path = hid_internal_UTF8toUTF16(dev->device_info->path); + if (!interface_path) { + register_string_error(dev, L"Path conversion failure"); + goto end; + } + + /* Get the device id from interface path */ + device_id = hid_internal_get_device_interface_property(interface_path, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); + if (!device_id) { + register_string_error(dev, L"Failed to get device interface property InstanceId"); + goto end; + } + + /* Open devnode from device id */ + cr = CM_Locate_DevNodeW(&dev_node, (DEVINSTID_W)device_id, CM_LOCATE_DEVNODE_NORMAL); + if (cr != CR_SUCCESS) { + register_string_error(dev, L"Failed to locate device node"); + goto end; + } + + /* Get the container id from devnode */ + len = sizeof(*container_id); + cr = CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_Device_ContainerId, &property_type, (PBYTE)container_id, &len, 0); + if (cr == CR_SUCCESS && property_type != DEVPROP_TYPE_GUID) + cr = CR_FAILURE; + + if (cr != CR_SUCCESS) + register_string_error(dev, L"Failed to read ContainerId property from device node"); + +end: + free(interface_path); + free(device_id); + + return cr == CR_SUCCESS ? 0 : -1; +} + + +int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size) +{ + PHIDP_PREPARSED_DATA pp_data = NULL; + + if (!HidD_GetPreparsedData(dev->device_handle, &pp_data) || pp_data == NULL) { + register_string_error(dev, L"HidD_GetPreparsedData"); + return -1; + } + + int res = hid_winapi_descriptor_reconstruct_pp_data(pp_data, buf, buf_size); + + HidD_FreePreparsedData(pp_data); + + return res; +} + +HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) +{ + if (dev) { + if (dev->last_error_str == NULL) + return L"Success"; + return (wchar_t*)dev->last_error_str; + } + + if (last_global_error_str == NULL) + return L"Success"; + return last_global_error_str; +} + +#ifndef hidapi_winapi_EXPORTS +#include "hidapi_descriptor_reconstruct.c" +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif diff --git a/thirdparty/sdl/hidapi/windows/hidapi_cfgmgr32.h b/thirdparty/sdl/hidapi/windows/hidapi_cfgmgr32.h new file mode 100644 index 00000000000..09bf4d768ba --- /dev/null +++ b/thirdparty/sdl/hidapi/windows/hidapi_cfgmgr32.h @@ -0,0 +1,86 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +#ifndef HIDAPI_CFGMGR32_H +#define HIDAPI_CFGMGR32_H + +#ifdef HIDAPI_USE_DDK + +#include +#include +#include +#include + +#else + +/* This part of the header mimics cfgmgr32.h, + but only what is used by HIDAPI */ + +//#include +#include +//#include + +#ifndef PROPERTYKEY_DEFINED +#define PROPERTYKEY_DEFINED + +typedef struct +{ + GUID fmtid; + DWORD pid; +} PROPERTYKEY; + +#endif /* PROPERTYKEY_DEFINED */ + +typedef DWORD RETURN_TYPE; +typedef RETURN_TYPE CONFIGRET; +typedef DWORD DEVNODE, DEVINST; +typedef DEVNODE* PDEVNODE, * PDEVINST; +typedef WCHAR* DEVNODEID_W, * DEVINSTID_W; + +#define CR_SUCCESS (0x00000000) +#define CR_BUFFER_SMALL (0x0000001A) +#define CR_FAILURE (0x00000013) + +#define CM_LOCATE_DEVNODE_NORMAL 0x00000000 + +#define CM_GET_DEVICE_INTERFACE_LIST_PRESENT (0x00000000) + +typedef CONFIGRET(__stdcall* CM_Locate_DevNodeW_)(PDEVINST pdnDevInst, DEVINSTID_W pDeviceID, ULONG ulFlags); +typedef CONFIGRET(__stdcall* CM_Get_Parent_)(PDEVINST pdnDevInst, DEVINST dnDevInst, ULONG ulFlags); +typedef CONFIGRET(__stdcall* CM_Get_DevNode_PropertyW_)(DEVINST dnDevInst, CONST DEVPROPKEY* PropertyKey, DEVPROPTYPE* PropertyType, PBYTE PropertyBuffer, PULONG PropertyBufferSize, ULONG ulFlags); +typedef CONFIGRET(__stdcall* CM_Get_Device_Interface_PropertyW_)(LPCWSTR pszDeviceInterface, CONST DEVPROPKEY* PropertyKey, DEVPROPTYPE* PropertyType, PBYTE PropertyBuffer, PULONG PropertyBufferSize, ULONG ulFlags); +typedef CONFIGRET(__stdcall* CM_Get_Device_Interface_List_SizeW_)(PULONG pulLen, LPGUID InterfaceClassGuid, DEVINSTID_W pDeviceID, ULONG ulFlags); +typedef CONFIGRET(__stdcall* CM_Get_Device_Interface_ListW_)(LPGUID InterfaceClassGuid, DEVINSTID_W pDeviceID, WCHAR* /*PZZWSTR*/ Buffer, ULONG BufferLen, ULONG ulFlags); + +// from devpkey.h +static DEVPROPKEY DEVPKEY_NAME = { { 0xb725f130, 0x47ef, 0x101a, {0xa5, 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac} }, 10 }; // DEVPROP_TYPE_STRING +static DEVPROPKEY DEVPKEY_Device_Manufacturer = { { 0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0} }, 13 }; // DEVPROP_TYPE_STRING +static DEVPROPKEY DEVPKEY_Device_InstanceId = { { 0x78c34fc8, 0x104a, 0x4aca, {0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57} }, 256 }; // DEVPROP_TYPE_STRING +static DEVPROPKEY DEVPKEY_Device_HardwareIds = { { 0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0} }, 3 }; // DEVPROP_TYPE_STRING_LIST +static DEVPROPKEY DEVPKEY_Device_CompatibleIds = { { 0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0} }, 4 }; // DEVPROP_TYPE_STRING_LIST +static DEVPROPKEY DEVPKEY_Device_ContainerId = { { 0x8c7ed206, 0x3f8a, 0x4827, {0xb3, 0xab, 0xae, 0x9e, 0x1f, 0xae, 0xfc, 0x6c} }, 2 }; // DEVPROP_TYPE_GUID + +// from propkey.h +static PROPERTYKEY PKEY_DeviceInterface_Bluetooth_DeviceAddress = { { 0x2bd67d8b, 0x8beb, 0x48d5, {0x87, 0xe0, 0x6c, 0xda, 0x34, 0x28, 0x04, 0x0a} }, 1 }; // DEVPROP_TYPE_STRING +static PROPERTYKEY PKEY_DeviceInterface_Bluetooth_Manufacturer = { { 0x2bd67d8b, 0x8beb, 0x48d5, {0x87, 0xe0, 0x6c, 0xda, 0x34, 0x28, 0x04, 0x0a} }, 4 }; // DEVPROP_TYPE_STRING +static PROPERTYKEY PKEY_DeviceInterface_Bluetooth_ModelNumber = { { 0x2BD67D8B, 0x8BEB, 0x48D5, {0x87, 0xE0, 0x6C, 0xDA, 0x34, 0x28, 0x04, 0x0A} }, 5 }; // DEVPROP_TYPE_STRING + +#endif + +#endif /* HIDAPI_CFGMGR32_H */ diff --git a/thirdparty/sdl/hidapi/windows/hidapi_descriptor_reconstruct.c b/thirdparty/sdl/hidapi/windows/hidapi_descriptor_reconstruct.c new file mode 100644 index 00000000000..6697d3c3c3a --- /dev/null +++ b/thirdparty/sdl/hidapi/windows/hidapi_descriptor_reconstruct.c @@ -0,0 +1,990 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ +#include "hidapi_descriptor_reconstruct.h" + +/** + * @brief References to report descriptor buffer. + * + */ +struct rd_buffer { + unsigned char* buf; /* Pointer to the array which stores the reconstructed descriptor */ + size_t buf_size; /* Size of the buffer in bytes */ + size_t byte_idx; /* Index of the next report byte to write to buf array */ +}; + +/** + * @brief Function that appends a byte to encoded report descriptor buffer. + * + * @param[in] byte Single byte to append. + * @param rpt_desc Pointer to report descriptor buffer struct. + */ +static void rd_append_byte(unsigned char byte, struct rd_buffer* rpt_desc) { + if (rpt_desc->byte_idx < rpt_desc->buf_size) { + rpt_desc->buf[rpt_desc->byte_idx] = byte; + rpt_desc->byte_idx++; + } +} + +/** + * @brief Writes a short report descriptor item according USB HID spec 1.11 chapter 6.2.2.2. + * + * @param[in] rd_item Enumeration identifying type (Main, Global, Local) and function (e.g Usage or Report Count) of the item. + * @param[in] data Data (Size depends on rd_item 0,1,2 or 4bytes). + * @param rpt_desc Pointer to report descriptor buffer struct. + * + * @return Returns 0 if successful, -1 for error. + */ +static int rd_write_short_item(rd_items rd_item, LONG64 data, struct rd_buffer* rpt_desc) { + if (rd_item & 0x03) { + // Invalid input data, last to bits are reserved for data size + return -1; + } + + if (rd_item == rd_main_collection_end) { + // Item without data (1Byte prefix only) + unsigned char oneBytePrefix = (unsigned char) rd_item + 0x00; + rd_append_byte(oneBytePrefix, rpt_desc); + } + else if ((rd_item == rd_global_logical_minimum) || + (rd_item == rd_global_logical_maximum) || + (rd_item == rd_global_physical_minimum) || + (rd_item == rd_global_physical_maximum)) { + // Item with signed integer data + if ((data >= -128) && (data <= 127)) { + // 1Byte prefix + 1Byte data + unsigned char oneBytePrefix = (unsigned char) rd_item + 0x01; + char localData = (char)data; + rd_append_byte(oneBytePrefix, rpt_desc); + rd_append_byte(localData & 0xFF, rpt_desc); + } + else if ((data >= -32768) && (data <= 32767)) { + // 1Byte prefix + 2Byte data + unsigned char oneBytePrefix = (unsigned char) rd_item + 0x02; + INT16 localData = (INT16)data; + rd_append_byte(oneBytePrefix, rpt_desc); + rd_append_byte(localData & 0xFF, rpt_desc); + rd_append_byte(localData >> 8 & 0xFF, rpt_desc); + } + else if ((data >= -2147483648LL) && (data <= 2147483647)) { + // 1Byte prefix + 4Byte data + unsigned char oneBytePrefix = (unsigned char) rd_item + 0x03; + INT32 localData = (INT32)data; + rd_append_byte(oneBytePrefix, rpt_desc); + rd_append_byte(localData & 0xFF, rpt_desc); + rd_append_byte(localData >> 8 & 0xFF, rpt_desc); + rd_append_byte(localData >> 16 & 0xFF, rpt_desc); + rd_append_byte(localData >> 24 & 0xFF, rpt_desc); + } + else { + // Data out of 32 bit signed integer range + return -1; + } + } + else { + // Item with unsigned integer data + if ((data >= 0) && (data <= 0xFF)) { + // 1Byte prefix + 1Byte data + unsigned char oneBytePrefix = (unsigned char) rd_item + 0x01; + unsigned char localData = (unsigned char)data; + rd_append_byte(oneBytePrefix, rpt_desc); + rd_append_byte(localData & 0xFF, rpt_desc); + } + else if ((data >= 0) && (data <= 0xFFFF)) { + // 1Byte prefix + 2Byte data + unsigned char oneBytePrefix = (unsigned char) rd_item + 0x02; + UINT16 localData = (UINT16)data; + rd_append_byte(oneBytePrefix, rpt_desc); + rd_append_byte(localData & 0xFF, rpt_desc); + rd_append_byte(localData >> 8 & 0xFF, rpt_desc); + } + else if ((data >= 0) && (data <= 0xFFFFFFFF)) { + // 1Byte prefix + 4Byte data + unsigned char oneBytePrefix = (unsigned char) rd_item + 0x03; + UINT32 localData = (UINT32)data; + rd_append_byte(oneBytePrefix, rpt_desc); + rd_append_byte(localData & 0xFF, rpt_desc); + rd_append_byte(localData >> 8 & 0xFF, rpt_desc); + rd_append_byte(localData >> 16 & 0xFF, rpt_desc); + rd_append_byte(localData >> 24 & 0xFF, rpt_desc); + } + else { + // Data out of 32 bit unsigned integer range + return -1; + } + } + return 0; +} + +static struct rd_main_item_node * rd_append_main_item_node(int first_bit, int last_bit, rd_node_type type_of_node, int caps_index, int collection_index, rd_main_items main_item_type, unsigned char report_id, struct rd_main_item_node **list) { + struct rd_main_item_node *new_list_node; + + // Determine last node in the list + while (*list != NULL) + { + list = &(*list)->next; + } + + new_list_node = malloc(sizeof(*new_list_node)); // Create new list entry + new_list_node->FirstBit = first_bit; + new_list_node->LastBit = last_bit; + new_list_node->TypeOfNode = type_of_node; + new_list_node->CapsIndex = caps_index; + new_list_node->CollectionIndex = collection_index; + new_list_node->MainItemType = main_item_type; + new_list_node->ReportID = report_id; + new_list_node->next = NULL; // NULL marks last node in the list + + *list = new_list_node; + return new_list_node; +} + +static struct rd_main_item_node * rd_insert_main_item_node(int first_bit, int last_bit, rd_node_type type_of_node, int caps_index, int collection_index, rd_main_items main_item_type, unsigned char report_id, struct rd_main_item_node **list) { + // Insert item after the main item node referenced by list + struct rd_main_item_node *next_item = (*list)->next; + (*list)->next = NULL; + rd_append_main_item_node(first_bit, last_bit, type_of_node, caps_index, collection_index, main_item_type, report_id, list); + (*list)->next->next = next_item; + return (*list)->next; +} + +static struct rd_main_item_node * rd_search_main_item_list_for_bit_position(int search_bit, rd_main_items main_item_type, unsigned char report_id, struct rd_main_item_node **list) { + // Determine first INPUT/OUTPUT/FEATURE main item, where the last bit position is equal or greater than the search bit position + + while (((*list)->next->MainItemType != rd_collection) && + ((*list)->next->MainItemType != rd_collection_end) && + !(((*list)->next->LastBit >= search_bit) && + ((*list)->next->ReportID == report_id) && + ((*list)->next->MainItemType == main_item_type)) + ) + { + list = &(*list)->next; + } + return *list; +} + +int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned char *buf, size_t buf_size) +{ + hidp_preparsed_data *pp_data = (hidp_preparsed_data *) preparsed_data; + + // Check if MagicKey is correct, to ensure that pp_data points to an valid preparse data structure + if (memcmp(pp_data->MagicKey, "HidP KDR", 8) != 0) { + return -1; + } + + struct rd_buffer rpt_desc; + rpt_desc.buf = buf; + rpt_desc.buf_size = buf_size; + rpt_desc.byte_idx = 0; + + // Set pointer to the first node of link_collection_nodes + phid_pp_link_collection_node link_collection_nodes = (phid_pp_link_collection_node)(((unsigned char*)&pp_data->caps[0]) + pp_data->FirstByteOfLinkCollectionArray); + + // **************************************************************************************************************************** + // Create lookup tables for the bit range of each report per collection (position of first bit and last bit in each collection) + // coll_bit_range[COLLECTION_INDEX][REPORT_ID][INPUT/OUTPUT/FEATURE] + // **************************************************************************************************************************** + + // Allocate memory and initialize lookup table + rd_bit_range ****coll_bit_range; + coll_bit_range = malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_bit_range)); + for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { + coll_bit_range[collection_node_idx] = malloc(256 * sizeof(*coll_bit_range[0])); // 256 possible report IDs (incl. 0x00) + for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { + coll_bit_range[collection_node_idx][reportid_idx] = malloc(NUM_OF_HIDP_REPORT_TYPES * sizeof(*coll_bit_range[0][0])); + for (HIDP_REPORT_TYPE rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { + coll_bit_range[collection_node_idx][reportid_idx][rt_idx] = malloc(sizeof(rd_bit_range)); + coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->FirstBit = -1; + coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->LastBit = -1; + } + } + } + + // Fill the lookup table where caps exist + for (HIDP_REPORT_TYPE rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { + for (USHORT caps_idx = pp_data->caps_info[rt_idx].FirstCap; caps_idx < pp_data->caps_info[rt_idx].LastCap; caps_idx++) { + int first_bit, last_bit; + first_bit = (pp_data->caps[caps_idx].BytePosition - 1) * 8 + + pp_data->caps[caps_idx].BitPosition; + last_bit = first_bit + pp_data->caps[caps_idx].ReportSize + * pp_data->caps[caps_idx].ReportCount - 1; + if (coll_bit_range[pp_data->caps[caps_idx].LinkCollection][pp_data->caps[caps_idx].ReportID][rt_idx]->FirstBit == -1 || + coll_bit_range[pp_data->caps[caps_idx].LinkCollection][pp_data->caps[caps_idx].ReportID][rt_idx]->FirstBit > first_bit) { + coll_bit_range[pp_data->caps[caps_idx].LinkCollection][pp_data->caps[caps_idx].ReportID][rt_idx]->FirstBit = first_bit; + } + if (coll_bit_range[pp_data->caps[caps_idx].LinkCollection][pp_data->caps[caps_idx].ReportID][rt_idx]->LastBit < last_bit) { + coll_bit_range[pp_data->caps[caps_idx].LinkCollection][pp_data->caps[caps_idx].ReportID][rt_idx]->LastBit = last_bit; + } + } + } + + // ************************************************************************* + // -Determine hierarchy levels of each collections and store it in: + // coll_levels[COLLECTION_INDEX] + // -Determine number of direct childs of each collections and store it in: + // coll_number_of_direct_childs[COLLECTION_INDEX] + // ************************************************************************* + int max_coll_level = 0; + int *coll_levels = malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_levels[0])); + int *coll_number_of_direct_childs = malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_number_of_direct_childs[0])); + for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { + coll_levels[collection_node_idx] = -1; + coll_number_of_direct_childs[collection_node_idx] = 0; + } + + { + int actual_coll_level = 0; + USHORT collection_node_idx = 0; + while (actual_coll_level >= 0) { + coll_levels[collection_node_idx] = actual_coll_level; + if ((link_collection_nodes[collection_node_idx].NumberOfChildren > 0) && + (coll_levels[link_collection_nodes[collection_node_idx].FirstChild] == -1)) { + actual_coll_level++; + coll_levels[collection_node_idx] = actual_coll_level; + if (max_coll_level < actual_coll_level) { + max_coll_level = actual_coll_level; + } + coll_number_of_direct_childs[collection_node_idx]++; + collection_node_idx = link_collection_nodes[collection_node_idx].FirstChild; + } + else if (link_collection_nodes[collection_node_idx].NextSibling != 0) { + coll_number_of_direct_childs[link_collection_nodes[collection_node_idx].Parent]++; + collection_node_idx = link_collection_nodes[collection_node_idx].NextSibling; + } + else { + actual_coll_level--; + if (actual_coll_level >= 0) { + collection_node_idx = link_collection_nodes[collection_node_idx].Parent; + } + } + } + } + + // ********************************************************************************* + // Propagate the bit range of each report from the child collections to their parent + // and store the merged result for the parent + // ********************************************************************************* + for (int actual_coll_level = max_coll_level - 1; actual_coll_level >= 0; actual_coll_level--) { + for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { + if (coll_levels[collection_node_idx] == actual_coll_level) { + USHORT child_idx = link_collection_nodes[collection_node_idx].FirstChild; + while (child_idx) { + for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { + for (HIDP_REPORT_TYPE rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { + // Merge bit range from childs + if ((coll_bit_range[child_idx][reportid_idx][rt_idx]->FirstBit != -1) && + (coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->FirstBit > coll_bit_range[child_idx][reportid_idx][rt_idx]->FirstBit)) { + coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->FirstBit = coll_bit_range[child_idx][reportid_idx][rt_idx]->FirstBit; + } + if (coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->LastBit < coll_bit_range[child_idx][reportid_idx][rt_idx]->LastBit) { + coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->LastBit = coll_bit_range[child_idx][reportid_idx][rt_idx]->LastBit; + } + child_idx = link_collection_nodes[child_idx].NextSibling; + } + } + } + } + } + } + + // ************************************************************************************************** + // Determine child collection order of the whole hierarchy, based on previously determined bit ranges + // and store it this index coll_child_order[COLLECTION_INDEX][DIRECT_CHILD_INDEX] + // ************************************************************************************************** + USHORT **coll_child_order; + coll_child_order = malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_child_order)); + { + BOOLEAN *coll_parsed_flag; + coll_parsed_flag = malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_parsed_flag[0])); + for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { + coll_parsed_flag[collection_node_idx] = FALSE; + } + int actual_coll_level = 0; + USHORT collection_node_idx = 0; + while (actual_coll_level >= 0) { + if ((coll_number_of_direct_childs[collection_node_idx] != 0) && + (coll_parsed_flag[link_collection_nodes[collection_node_idx].FirstChild] == FALSE)) { + coll_parsed_flag[link_collection_nodes[collection_node_idx].FirstChild] = TRUE; + coll_child_order[collection_node_idx] = malloc((coll_number_of_direct_childs[collection_node_idx]) * sizeof(*coll_child_order[0])); + + { + // Create list of child collection indices + // sorted reverse to the order returned to HidP_GetLinkCollectionNodeschild + // which seems to match the original order, as long as no bit position needs to be considered + USHORT child_idx = link_collection_nodes[collection_node_idx].FirstChild; + int child_count = coll_number_of_direct_childs[collection_node_idx] - 1; + coll_child_order[collection_node_idx][child_count] = child_idx; + while (link_collection_nodes[child_idx].NextSibling) { + child_count--; + child_idx = link_collection_nodes[child_idx].NextSibling; + coll_child_order[collection_node_idx][child_count] = child_idx; + } + } + + if (coll_number_of_direct_childs[collection_node_idx] > 1) { + // Sort child collections indices by bit positions + for (HIDP_REPORT_TYPE rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { + for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { + for (int child_idx = 1; child_idx < coll_number_of_direct_childs[collection_node_idx]; child_idx++) { + // since the coll_bit_range array is not sorted, we need to reference the collection index in + // our sorted coll_child_order array, and look up the corresponding bit ranges for comparing values to sort + int prev_coll_idx = coll_child_order[collection_node_idx][child_idx - 1]; + int cur_coll_idx = coll_child_order[collection_node_idx][child_idx]; + if ((coll_bit_range[prev_coll_idx][reportid_idx][rt_idx]->FirstBit != -1) && + (coll_bit_range[cur_coll_idx][reportid_idx][rt_idx]->FirstBit != -1) && + (coll_bit_range[prev_coll_idx][reportid_idx][rt_idx]->FirstBit > coll_bit_range[cur_coll_idx][reportid_idx][rt_idx]->FirstBit)) { + // Swap position indices of the two compared child collections + USHORT idx_latch = coll_child_order[collection_node_idx][child_idx - 1]; + coll_child_order[collection_node_idx][child_idx - 1] = coll_child_order[collection_node_idx][child_idx]; + coll_child_order[collection_node_idx][child_idx] = idx_latch; + } + } + } + } + } + actual_coll_level++; + collection_node_idx = link_collection_nodes[collection_node_idx].FirstChild; + } + else if (link_collection_nodes[collection_node_idx].NextSibling != 0) { + collection_node_idx = link_collection_nodes[collection_node_idx].NextSibling; + } + else { + actual_coll_level--; + if (actual_coll_level >= 0) { + collection_node_idx = link_collection_nodes[collection_node_idx].Parent; + } + } + } + free(coll_parsed_flag); + } + + + // *************************************************************************************** + // Create sorted main_item_list containing all the Collection and CollectionEnd main items + // *************************************************************************************** + struct rd_main_item_node *main_item_list = NULL; // List root + // Lookup table to find the Collection items in the list by index + struct rd_main_item_node **coll_begin_lookup = malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_begin_lookup)); + struct rd_main_item_node **coll_end_lookup = malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_end_lookup)); + { + int *coll_last_written_child = malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_last_written_child[0])); + for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { + coll_last_written_child[collection_node_idx] = -1; + } + + int actual_coll_level = 0; + USHORT collection_node_idx = 0; + struct rd_main_item_node *firstDelimiterNode = NULL; + struct rd_main_item_node *delimiterCloseNode = NULL; + coll_begin_lookup[0] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_collection, 0, &main_item_list); + while (actual_coll_level >= 0) { + if ((coll_number_of_direct_childs[collection_node_idx] != 0) && + (coll_last_written_child[collection_node_idx] == -1)) { + // Collection has child collections, but none is written to the list yet + + coll_last_written_child[collection_node_idx] = coll_child_order[collection_node_idx][0]; + collection_node_idx = coll_child_order[collection_node_idx][0]; + + // In a HID Report Descriptor, the first usage declared is the most preferred usage for the control. + // While the order in the WIN32 capabiliy strutures is the opposite: + // Here the preferred usage is the last aliased usage in the sequence. + + if (link_collection_nodes[collection_node_idx].IsAlias && (firstDelimiterNode == NULL)) { + // Alliased Collection (First node in link_collection_nodes -> Last entry in report descriptor output) + firstDelimiterNode = main_item_list; + coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_usage, 0, &main_item_list); + coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_close, 0, &main_item_list); + delimiterCloseNode = main_item_list; + } + else { + // Normal not aliased collection + coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_collection, 0, &main_item_list); + actual_coll_level++; + } + + + } + else if ((coll_number_of_direct_childs[collection_node_idx] > 1) && + (coll_last_written_child[collection_node_idx] != coll_child_order[collection_node_idx][coll_number_of_direct_childs[collection_node_idx] - 1])) { + // Collection has child collections, and this is not the first child + + int nextChild = 1; + while (coll_last_written_child[collection_node_idx] != coll_child_order[collection_node_idx][nextChild - 1]) { + nextChild++; + } + coll_last_written_child[collection_node_idx] = coll_child_order[collection_node_idx][nextChild]; + collection_node_idx = coll_child_order[collection_node_idx][nextChild]; + + if (link_collection_nodes[collection_node_idx].IsAlias && (firstDelimiterNode == NULL)) { + // Alliased Collection (First node in link_collection_nodes -> Last entry in report descriptor output) + firstDelimiterNode = main_item_list; + coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_usage, 0, &main_item_list); + coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_close, 0, &main_item_list); + delimiterCloseNode = main_item_list; + } + else if (link_collection_nodes[collection_node_idx].IsAlias && (firstDelimiterNode != NULL)) { + coll_begin_lookup[collection_node_idx] = rd_insert_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_usage, 0, &firstDelimiterNode); + } + else if (!link_collection_nodes[collection_node_idx].IsAlias && (firstDelimiterNode != NULL)) { + coll_begin_lookup[collection_node_idx] = rd_insert_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_usage, 0, &firstDelimiterNode); + coll_begin_lookup[collection_node_idx] = rd_insert_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_open, 0, &firstDelimiterNode); + firstDelimiterNode = NULL; + main_item_list = delimiterCloseNode; + delimiterCloseNode = NULL; // Last entry of alias has .IsAlias == FALSE + } + if (!link_collection_nodes[collection_node_idx].IsAlias) { + coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_collection, 0, &main_item_list); + actual_coll_level++; + } + } + else { + actual_coll_level--; + coll_end_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_collection_end, 0, &main_item_list); + collection_node_idx = link_collection_nodes[collection_node_idx].Parent; + } + } + free(coll_last_written_child); + } + + + // **************************************************************** + // Inserted Input/Output/Feature main items into the main_item_list + // in order of reconstructed bit positions + // **************************************************************** + for (HIDP_REPORT_TYPE rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { + // Add all value caps to node list + struct rd_main_item_node *firstDelimiterNode = NULL; + struct rd_main_item_node *delimiterCloseNode = NULL; + for (USHORT caps_idx = pp_data->caps_info[rt_idx].FirstCap; caps_idx < pp_data->caps_info[rt_idx].LastCap; caps_idx++) { + struct rd_main_item_node *coll_begin = coll_begin_lookup[pp_data->caps[caps_idx].LinkCollection]; + int first_bit, last_bit; + first_bit = (pp_data->caps[caps_idx].BytePosition - 1) * 8 + + pp_data->caps[caps_idx].BitPosition; + last_bit = first_bit + pp_data->caps[caps_idx].ReportSize * + pp_data->caps[caps_idx].ReportCount - 1; + + for (int child_idx = 0; child_idx < coll_number_of_direct_childs[pp_data->caps[caps_idx].LinkCollection]; child_idx++) { + // Determine in which section before/between/after child collection the item should be inserted + if (first_bit < coll_bit_range[coll_child_order[pp_data->caps[caps_idx].LinkCollection][child_idx]][pp_data->caps[caps_idx].ReportID][rt_idx]->FirstBit) + { + // Note, that the default value for undefined coll_bit_range is -1, which can't be greater than the bit position + break; + } + coll_begin = coll_end_lookup[coll_child_order[pp_data->caps[caps_idx].LinkCollection][child_idx]]; + } + struct rd_main_item_node *list_node; + list_node = rd_search_main_item_list_for_bit_position(first_bit, (rd_main_items) rt_idx, pp_data->caps[caps_idx].ReportID, &coll_begin); + + // In a HID Report Descriptor, the first usage declared is the most preferred usage for the control. + // While the order in the WIN32 capabiliy strutures is the opposite: + // Here the preferred usage is the last aliased usage in the sequence. + + if (pp_data->caps[caps_idx].IsAlias && (firstDelimiterNode == NULL)) { + // Alliased Usage (First node in pp_data->caps -> Last entry in report descriptor output) + firstDelimiterNode = list_node; + rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, rd_delimiter_usage, pp_data->caps[caps_idx].ReportID, &list_node); + rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, rd_delimiter_close, pp_data->caps[caps_idx].ReportID, &list_node); + delimiterCloseNode = list_node; + } else if (pp_data->caps[caps_idx].IsAlias && (firstDelimiterNode != NULL)) { + rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, rd_delimiter_usage, pp_data->caps[caps_idx].ReportID, &list_node); + } + else if (!pp_data->caps[caps_idx].IsAlias && (firstDelimiterNode != NULL)) { + // Alliased Collection (Last node in pp_data->caps -> First entry in report descriptor output) + rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, rd_delimiter_usage, pp_data->caps[caps_idx].ReportID, &list_node); + rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, rd_delimiter_open, pp_data->caps[caps_idx].ReportID, &list_node); + firstDelimiterNode = NULL; + list_node = delimiterCloseNode; + delimiterCloseNode = NULL; // Last entry of alias has .IsAlias == FALSE + } + if (!pp_data->caps[caps_idx].IsAlias) { + rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, (rd_main_items) rt_idx, pp_data->caps[caps_idx].ReportID, &list_node); + } + } + } + + + // *********************************************************** + // Add const main items for padding to main_item_list + // -To fill all bit gaps + // -At each report end for 8bit padding + // Note that information about the padding at the report end, + // is not stored in the preparsed data, but in practice all + // report descriptors seem to have it, as assumed here. + // *********************************************************** + { + int *last_bit_position[NUM_OF_HIDP_REPORT_TYPES]; + struct rd_main_item_node **last_report_item_lookup[NUM_OF_HIDP_REPORT_TYPES]; + for (HIDP_REPORT_TYPE rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { + last_bit_position[rt_idx] = malloc(256 * sizeof(*last_bit_position[rt_idx])); + last_report_item_lookup[rt_idx] = malloc(256 * sizeof(*last_report_item_lookup[rt_idx])); + for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { + last_bit_position[rt_idx][reportid_idx] = -1; + last_report_item_lookup[rt_idx][reportid_idx] = NULL; + } + } + + struct rd_main_item_node *list = main_item_list; // List root; + + while (list->next != NULL) + { + if ((list->MainItemType >= rd_input) && + (list->MainItemType <= rd_feature)) { + // INPUT, OUTPUT or FEATURE + if (list->FirstBit != -1) { + if ((last_bit_position[list->MainItemType][list->ReportID] + 1 != list->FirstBit) && + (last_report_item_lookup[list->MainItemType][list->ReportID] != NULL) && + (last_report_item_lookup[list->MainItemType][list->ReportID]->FirstBit != list->FirstBit) // Happens in case of IsMultipleItemsForArray for multiple dedicated usages for a multi-button array + ) { + struct rd_main_item_node *list_node = rd_search_main_item_list_for_bit_position(last_bit_position[list->MainItemType][list->ReportID], list->MainItemType, list->ReportID, &last_report_item_lookup[list->MainItemType][list->ReportID]); + rd_insert_main_item_node(last_bit_position[list->MainItemType][list->ReportID] + 1, list->FirstBit - 1, rd_item_node_padding, -1, 0, list->MainItemType, list->ReportID, &list_node); + } + last_bit_position[list->MainItemType][list->ReportID] = list->LastBit; + last_report_item_lookup[list->MainItemType][list->ReportID] = list; + } + } + list = list->next; + } + // Add 8 bit padding at each report end + for (HIDP_REPORT_TYPE rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { + for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { + if (last_bit_position[rt_idx][reportid_idx] != -1) { + int padding = 8 - ((last_bit_position[rt_idx][reportid_idx] + 1) % 8); + if (padding < 8) { + // Insert padding item after item referenced in last_report_item_lookup + rd_insert_main_item_node(last_bit_position[rt_idx][reportid_idx] + 1, last_bit_position[rt_idx][reportid_idx] + padding, rd_item_node_padding, -1, 0, (rd_main_items) rt_idx, (unsigned char) reportid_idx, &last_report_item_lookup[rt_idx][reportid_idx]); + } + } + } + free(last_bit_position[rt_idx]); + free(last_report_item_lookup[rt_idx]); + } + } + + + // *********************************** + // Encode the report descriptor output + // *********************************** + UCHAR last_report_id = 0; + USAGE last_usage_page = 0; + LONG last_physical_min = 0;// If both, Physical Minimum and Physical Maximum are 0, the logical limits should be taken as physical limits according USB HID spec 1.11 chapter 6.2.2.7 + LONG last_physical_max = 0; + ULONG last_unit_exponent = 0; // If Unit Exponent is Undefined it should be considered as 0 according USB HID spec 1.11 chapter 6.2.2.7 + ULONG last_unit = 0; // If the first nibble is 7, or second nibble of Unit is 0, the unit is None according USB HID spec 1.11 chapter 6.2.2.7 + BOOLEAN inhibit_write_of_usage = FALSE; // Needed in case of delimited usage print, before the normal collection or cap + int report_count = 0; + while (main_item_list != NULL) + { + int rt_idx = main_item_list->MainItemType; + int caps_idx = main_item_list->CapsIndex; + if (main_item_list->MainItemType == rd_collection) { + if (last_usage_page != link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage) { + // Write "Usage Page" at the begin of a collection - except it refers the same table as wrote last + rd_write_short_item(rd_global_usage_page, link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage, &rpt_desc); + last_usage_page = link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage; + } + if (inhibit_write_of_usage) { + // Inhibit only once after DELIMITER statement + inhibit_write_of_usage = FALSE; + } + else { + // Write "Usage" of collection + rd_write_short_item(rd_local_usage, link_collection_nodes[main_item_list->CollectionIndex].LinkUsage, &rpt_desc); + } + // Write begin of "Collection" + rd_write_short_item(rd_main_collection, link_collection_nodes[main_item_list->CollectionIndex].CollectionType, &rpt_desc); + } + else if (main_item_list->MainItemType == rd_collection_end) { + // Write "End Collection" + rd_write_short_item(rd_main_collection_end, 0, &rpt_desc); + } + else if (main_item_list->MainItemType == rd_delimiter_open) { + if (main_item_list->CollectionIndex != -1) { + // Write "Usage Page" inside of a collection delmiter section + if (last_usage_page != link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage) { + rd_write_short_item(rd_global_usage_page, link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage, &rpt_desc); + last_usage_page = link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage; + } + } + else if (main_item_list->CapsIndex != 0) { + // Write "Usage Page" inside of a main item delmiter section + if (pp_data->caps[caps_idx].UsagePage != last_usage_page) { + rd_write_short_item(rd_global_usage_page, pp_data->caps[caps_idx].UsagePage, &rpt_desc); + last_usage_page = pp_data->caps[caps_idx].UsagePage; + } + } + // Write "Delimiter Open" + rd_write_short_item(rd_local_delimiter, 1, &rpt_desc); // 1 = open set of aliased usages + } + else if (main_item_list->MainItemType == rd_delimiter_usage) { + if (main_item_list->CollectionIndex != -1) { + // Write aliased collection "Usage" + rd_write_short_item(rd_local_usage, link_collection_nodes[main_item_list->CollectionIndex].LinkUsage, &rpt_desc); + } if (main_item_list->CapsIndex != 0) { + // Write aliased main item range from "Usage Minimum" to "Usage Maximum" + if (pp_data->caps[caps_idx].IsRange) { + rd_write_short_item(rd_local_usage_minimum, pp_data->caps[caps_idx].Range.UsageMin, &rpt_desc); + rd_write_short_item(rd_local_usage_maximum, pp_data->caps[caps_idx].Range.UsageMax, &rpt_desc); + } + else { + // Write single aliased main item "Usage" + rd_write_short_item(rd_local_usage, pp_data->caps[caps_idx].NotRange.Usage, &rpt_desc); + } + } + } + else if (main_item_list->MainItemType == rd_delimiter_close) { + // Write "Delimiter Close" + rd_write_short_item(rd_local_delimiter, 0, &rpt_desc); // 0 = close set of aliased usages + // Inhibit next usage write + inhibit_write_of_usage = TRUE; + } + else if (main_item_list->TypeOfNode == rd_item_node_padding) { + // Padding + // The preparsed data doesn't contain any information about padding. Therefore all undefined gaps + // in the reports are filled with the same style of constant padding. + + // Write "Report Size" with number of padding bits + rd_write_short_item(rd_global_report_size, (main_item_list->LastBit - main_item_list->FirstBit + 1), &rpt_desc); + + // Write "Report Count" for padding always as 1 + rd_write_short_item(rd_global_report_count, 1, &rpt_desc); + + if (rt_idx == HidP_Input) { + // Write "Input" main item - We know it's Constant - We can only guess the other bits, but they don't matter in case of const + rd_write_short_item(rd_main_input, 0x03, &rpt_desc); // Const / Abs + } + else if (rt_idx == HidP_Output) { + // Write "Output" main item - We know it's Constant - We can only guess the other bits, but they don't matter in case of const + rd_write_short_item(rd_main_output, 0x03, &rpt_desc); // Const / Abs + } + else if (rt_idx == HidP_Feature) { + // Write "Feature" main item - We know it's Constant - We can only guess the other bits, but they don't matter in case of const + rd_write_short_item(rd_main_feature, 0x03, &rpt_desc); // Const / Abs + } + report_count = 0; + } + else if (pp_data->caps[caps_idx].IsButtonCap) { + // Button + // (The preparsed data contain different data for 1 bit Button caps, than for parametric Value caps) + + if (last_report_id != pp_data->caps[caps_idx].ReportID) { + // Write "Report ID" if changed + rd_write_short_item(rd_global_report_id, pp_data->caps[caps_idx].ReportID, &rpt_desc); + last_report_id = pp_data->caps[caps_idx].ReportID; + } + + // Write "Usage Page" when changed + if (pp_data->caps[caps_idx].UsagePage != last_usage_page) { + rd_write_short_item(rd_global_usage_page, pp_data->caps[caps_idx].UsagePage, &rpt_desc); + last_usage_page = pp_data->caps[caps_idx].UsagePage; + } + + // Write only local report items for each cap, if ReportCount > 1 + if (pp_data->caps[caps_idx].IsRange) { + report_count += (pp_data->caps[caps_idx].Range.DataIndexMax - pp_data->caps[caps_idx].Range.DataIndexMin); + } + + if (inhibit_write_of_usage) { + // Inhibit only once after Delimiter - Reset flag + inhibit_write_of_usage = FALSE; + } + else { + if (pp_data->caps[caps_idx].IsRange) { + // Write range from "Usage Minimum" to "Usage Maximum" + rd_write_short_item(rd_local_usage_minimum, pp_data->caps[caps_idx].Range.UsageMin, &rpt_desc); + rd_write_short_item(rd_local_usage_maximum, pp_data->caps[caps_idx].Range.UsageMax, &rpt_desc); + } + else { + // Write single "Usage" + rd_write_short_item(rd_local_usage, pp_data->caps[caps_idx].NotRange.Usage, &rpt_desc); + } + } + + if (pp_data->caps[caps_idx].IsDesignatorRange) { + // Write physical descriptor indices range from "Designator Minimum" to "Designator Maximum" + rd_write_short_item(rd_local_designator_minimum, pp_data->caps[caps_idx].Range.DesignatorMin, &rpt_desc); + rd_write_short_item(rd_local_designator_maximum, pp_data->caps[caps_idx].Range.DesignatorMax, &rpt_desc); + } + else if (pp_data->caps[caps_idx].NotRange.DesignatorIndex != 0) { + // Designator set 0 is a special descriptor set (of the HID Physical Descriptor), + // that specifies the number of additional descriptor sets. + // Therefore Designator Index 0 can never be a useful reference for a control and we can inhibit it. + // Write single "Designator Index" + rd_write_short_item(rd_local_designator_index, pp_data->caps[caps_idx].NotRange.DesignatorIndex, &rpt_desc); + } + + if (pp_data->caps[caps_idx].IsStringRange) { + // Write range of indices of the USB string descriptor, from "String Minimum" to "String Maximum" + rd_write_short_item(rd_local_string_minimum, pp_data->caps[caps_idx].Range.StringMin, &rpt_desc); + rd_write_short_item(rd_local_string_maximum, pp_data->caps[caps_idx].Range.StringMax, &rpt_desc); + } + else if (pp_data->caps[caps_idx].NotRange.StringIndex != 0) { + // String Index 0 is a special entry of the USB string descriptor, that contains a list of supported languages, + // therefore Designator Index 0 can never be a useful reference for a control and we can inhibit it. + // Write single "String Index" + rd_write_short_item(rd_local_string, pp_data->caps[caps_idx].NotRange.StringIndex, &rpt_desc); + } + + if ((main_item_list->next != NULL) && + ((int)main_item_list->next->MainItemType == rt_idx) && + (main_item_list->next->TypeOfNode == rd_item_node_cap) && + (pp_data->caps[main_item_list->next->CapsIndex].IsButtonCap) && + (!pp_data->caps[caps_idx].IsRange) && // This node in list is no array + (!pp_data->caps[main_item_list->next->CapsIndex].IsRange) && // Next node in list is no array + (pp_data->caps[main_item_list->next->CapsIndex].UsagePage == pp_data->caps[caps_idx].UsagePage) && + (pp_data->caps[main_item_list->next->CapsIndex].ReportID == pp_data->caps[caps_idx].ReportID) && + (pp_data->caps[main_item_list->next->CapsIndex].BitField == pp_data->caps[caps_idx].BitField) + ) { + if (main_item_list->next->FirstBit != main_item_list->FirstBit) { + // In case of IsMultipleItemsForArray for multiple dedicated usages for a multi-button array, the report count should be incremented + + // Skip global items until any of them changes, than use ReportCount item to write the count of identical report fields + report_count++; + } + } + else { + + if ((pp_data->caps[caps_idx].Button.LogicalMin == 0) && + (pp_data->caps[caps_idx].Button.LogicalMax == 0)) { + // While a HID report descriptor must always contain LogicalMinimum and LogicalMaximum, + // the preparsed data contain both fields set to zero, for the case of simple buttons + // Write "Logical Minimum" set to 0 and "Logical Maximum" set to 1 + rd_write_short_item(rd_global_logical_minimum, 0, &rpt_desc); + rd_write_short_item(rd_global_logical_maximum, 1, &rpt_desc); + } + else { + // Write logical range from "Logical Minimum" to "Logical Maximum" + rd_write_short_item(rd_global_logical_minimum, pp_data->caps[caps_idx].Button.LogicalMin, &rpt_desc); + rd_write_short_item(rd_global_logical_maximum, pp_data->caps[caps_idx].Button.LogicalMax, &rpt_desc); + } + + // Write "Report Size" + rd_write_short_item(rd_global_report_size, pp_data->caps[caps_idx].ReportSize, &rpt_desc); + + // Write "Report Count" + if (!pp_data->caps[caps_idx].IsRange) { + // Variable bit field with one bit per button + // In case of multiple usages with the same items, only "Usage" is written per cap, and "Report Count" is incremented + rd_write_short_item(rd_global_report_count, pp_data->caps[caps_idx].ReportCount + report_count, &rpt_desc); + } + else { + // Button array of "Report Size" x "Report Count + rd_write_short_item(rd_global_report_count, pp_data->caps[caps_idx].ReportCount, &rpt_desc); + } + + + // Buttons have only 1 bit and therefore no physical limits/units -> Set to undefined state + if (last_physical_min != 0) { + // Write "Physical Minimum", but only if changed + last_physical_min = 0; + rd_write_short_item(rd_global_physical_minimum, last_physical_min, &rpt_desc); + } + if (last_physical_max != 0) { + // Write "Physical Maximum", but only if changed + last_physical_max = 0; + rd_write_short_item(rd_global_physical_maximum, last_physical_max, &rpt_desc); + } + if (last_unit_exponent != 0) { + // Write "Unit Exponent", but only if changed + last_unit_exponent = 0; + rd_write_short_item(rd_global_unit_exponent, last_unit_exponent, &rpt_desc); + } + if (last_unit != 0) { + // Write "Unit",but only if changed + last_unit = 0; + rd_write_short_item(rd_global_unit, last_unit, &rpt_desc); + } + + // Write "Input" main item + if (rt_idx == HidP_Input) { + rd_write_short_item(rd_main_input, pp_data->caps[caps_idx].BitField, &rpt_desc); + } + // Write "Output" main item + else if (rt_idx == HidP_Output) { + rd_write_short_item(rd_main_output, pp_data->caps[caps_idx].BitField, &rpt_desc); + } + // Write "Feature" main item + else if (rt_idx == HidP_Feature) { + rd_write_short_item(rd_main_feature, pp_data->caps[caps_idx].BitField, &rpt_desc); + } + report_count = 0; + } + } + else { + + if (last_report_id != pp_data->caps[caps_idx].ReportID) { + // Write "Report ID" if changed + rd_write_short_item(rd_global_report_id, pp_data->caps[caps_idx].ReportID, &rpt_desc); + last_report_id = pp_data->caps[caps_idx].ReportID; + } + + // Write "Usage Page" if changed + if (pp_data->caps[caps_idx].UsagePage != last_usage_page) { + rd_write_short_item(rd_global_usage_page, pp_data->caps[caps_idx].UsagePage, &rpt_desc); + last_usage_page = pp_data->caps[caps_idx].UsagePage; + } + + if (inhibit_write_of_usage) { + // Inhibit only once after Delimiter - Reset flag + inhibit_write_of_usage = FALSE; + } + else { + if (pp_data->caps[caps_idx].IsRange) { + // Write usage range from "Usage Minimum" to "Usage Maximum" + rd_write_short_item(rd_local_usage_minimum, pp_data->caps[caps_idx].Range.UsageMin, &rpt_desc); + rd_write_short_item(rd_local_usage_maximum, pp_data->caps[caps_idx].Range.UsageMax, &rpt_desc); + } + else { + // Write single "Usage" + rd_write_short_item(rd_local_usage, pp_data->caps[caps_idx].NotRange.Usage, &rpt_desc); + } + } + + if (pp_data->caps[caps_idx].IsDesignatorRange) { + // Write physical descriptor indices range from "Designator Minimum" to "Designator Maximum" + rd_write_short_item(rd_local_designator_minimum, pp_data->caps[caps_idx].Range.DesignatorMin, &rpt_desc); + rd_write_short_item(rd_local_designator_maximum, pp_data->caps[caps_idx].Range.DesignatorMax, &rpt_desc); + } + else if (pp_data->caps[caps_idx].NotRange.DesignatorIndex != 0) { + // Designator set 0 is a special descriptor set (of the HID Physical Descriptor), + // that specifies the number of additional descriptor sets. + // Therefore Designator Index 0 can never be a useful reference for a control and we can inhibit it. + // Write single "Designator Index" + rd_write_short_item(rd_local_designator_index, pp_data->caps[caps_idx].NotRange.DesignatorIndex, &rpt_desc); + } + + if (pp_data->caps[caps_idx].IsStringRange) { + // Write range of indices of the USB string descriptor, from "String Minimum" to "String Maximum" + rd_write_short_item(rd_local_string_minimum, pp_data->caps[caps_idx].Range.StringMin, &rpt_desc); + rd_write_short_item(rd_local_string_maximum, pp_data->caps[caps_idx].Range.StringMax, &rpt_desc); + } + else if (pp_data->caps[caps_idx].NotRange.StringIndex != 0) { + // String Index 0 is a special entry of the USB string descriptor, that contains a list of supported languages, + // therefore Designator Index 0 can never be a useful reference for a control and we can inhibit it. + // Write single "String Index" + rd_write_short_item(rd_local_string, pp_data->caps[caps_idx].NotRange.StringIndex, &rpt_desc); + } + + if ((pp_data->caps[caps_idx].BitField & 0x02) != 0x02) { + // In case of an value array overwrite "Report Count" + pp_data->caps[caps_idx].ReportCount = pp_data->caps[caps_idx].Range.DataIndexMax - pp_data->caps[caps_idx].Range.DataIndexMin + 1; + } + + + // Print only local report items for each cap, if ReportCount > 1 + if ((main_item_list->next != NULL) && + ((int) main_item_list->next->MainItemType == rt_idx) && + (main_item_list->next->TypeOfNode == rd_item_node_cap) && + (!pp_data->caps[main_item_list->next->CapsIndex].IsButtonCap) && + (!pp_data->caps[caps_idx].IsRange) && // This node in list is no array + (!pp_data->caps[main_item_list->next->CapsIndex].IsRange) && // Next node in list is no array + (pp_data->caps[main_item_list->next->CapsIndex].UsagePage == pp_data->caps[caps_idx].UsagePage) && + (pp_data->caps[main_item_list->next->CapsIndex].NotButton.LogicalMin == pp_data->caps[caps_idx].NotButton.LogicalMin) && + (pp_data->caps[main_item_list->next->CapsIndex].NotButton.LogicalMax == pp_data->caps[caps_idx].NotButton.LogicalMax) && + (pp_data->caps[main_item_list->next->CapsIndex].NotButton.PhysicalMin == pp_data->caps[caps_idx].NotButton.PhysicalMin) && + (pp_data->caps[main_item_list->next->CapsIndex].NotButton.PhysicalMax == pp_data->caps[caps_idx].NotButton.PhysicalMax) && + (pp_data->caps[main_item_list->next->CapsIndex].UnitsExp == pp_data->caps[caps_idx].UnitsExp) && + (pp_data->caps[main_item_list->next->CapsIndex].Units == pp_data->caps[caps_idx].Units) && + (pp_data->caps[main_item_list->next->CapsIndex].ReportSize == pp_data->caps[caps_idx].ReportSize) && + (pp_data->caps[main_item_list->next->CapsIndex].ReportID == pp_data->caps[caps_idx].ReportID) && + (pp_data->caps[main_item_list->next->CapsIndex].BitField == pp_data->caps[caps_idx].BitField) && + (pp_data->caps[main_item_list->next->CapsIndex].ReportCount == 1) && + (pp_data->caps[caps_idx].ReportCount == 1) + ) { + // Skip global items until any of them changes, than use ReportCount item to write the count of identical report fields + report_count++; + } + else { + // Value + + // Write logical range from "Logical Minimum" to "Logical Maximum" + rd_write_short_item(rd_global_logical_minimum, pp_data->caps[caps_idx].NotButton.LogicalMin, &rpt_desc); + rd_write_short_item(rd_global_logical_maximum, pp_data->caps[caps_idx].NotButton.LogicalMax, &rpt_desc); + + if ((last_physical_min != pp_data->caps[caps_idx].NotButton.PhysicalMin) || + (last_physical_max != pp_data->caps[caps_idx].NotButton.PhysicalMax)) { + // Write range from "Physical Minimum" to " Physical Maximum", but only if one of them changed + rd_write_short_item(rd_global_physical_minimum, pp_data->caps[caps_idx].NotButton.PhysicalMin, &rpt_desc); + last_physical_min = pp_data->caps[caps_idx].NotButton.PhysicalMin; + rd_write_short_item(rd_global_physical_maximum, pp_data->caps[caps_idx].NotButton.PhysicalMax, &rpt_desc); + last_physical_max = pp_data->caps[caps_idx].NotButton.PhysicalMax; + } + + + if (last_unit_exponent != pp_data->caps[caps_idx].UnitsExp) { + // Write "Unit Exponent", but only if changed + rd_write_short_item(rd_global_unit_exponent, pp_data->caps[caps_idx].UnitsExp, &rpt_desc); + last_unit_exponent = pp_data->caps[caps_idx].UnitsExp; + } + + if (last_unit != pp_data->caps[caps_idx].Units) { + // Write physical "Unit", but only if changed + rd_write_short_item(rd_global_unit, pp_data->caps[caps_idx].Units, &rpt_desc); + last_unit = pp_data->caps[caps_idx].Units; + } + + // Write "Report Size" + rd_write_short_item(rd_global_report_size, pp_data->caps[caps_idx].ReportSize, &rpt_desc); + + // Write "Report Count" + rd_write_short_item(rd_global_report_count, pp_data->caps[caps_idx].ReportCount + report_count, &rpt_desc); + + if (rt_idx == HidP_Input) { + // Write "Input" main item + rd_write_short_item(rd_main_input, pp_data->caps[caps_idx].BitField, &rpt_desc); + } + else if (rt_idx == HidP_Output) { + // Write "Output" main item + rd_write_short_item(rd_main_output, pp_data->caps[caps_idx].BitField, &rpt_desc); + } + else if (rt_idx == HidP_Feature) { + // Write "Feature" main item + rd_write_short_item(rd_main_feature, pp_data->caps[caps_idx].BitField, &rpt_desc); + } + report_count = 0; + } + } + + // Go to next item in main_item_list and free the memory of the actual item + struct rd_main_item_node *main_item_list_prev = main_item_list; + main_item_list = main_item_list->next; + free(main_item_list_prev); + } + + // Free multidimensionable array: coll_bit_range[COLLECTION_INDEX][REPORT_ID][INPUT/OUTPUT/FEATURE] + // Free multidimensionable array: coll_child_order[COLLECTION_INDEX][DIRECT_CHILD_INDEX] + for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { + for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { + for (HIDP_REPORT_TYPE rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { + free(coll_bit_range[collection_node_idx][reportid_idx][rt_idx]); + } + free(coll_bit_range[collection_node_idx][reportid_idx]); + } + free(coll_bit_range[collection_node_idx]); + if (coll_number_of_direct_childs[collection_node_idx] != 0) free(coll_child_order[collection_node_idx]); + } + free(coll_bit_range); + free(coll_child_order); + + // Free one dimensional arrays + free(coll_begin_lookup); + free(coll_end_lookup); + free(coll_levels); + free(coll_number_of_direct_childs); + + return (int) rpt_desc.byte_idx; +} diff --git a/thirdparty/sdl/hidapi/windows/hidapi_descriptor_reconstruct.h b/thirdparty/sdl/hidapi/windows/hidapi_descriptor_reconstruct.h new file mode 100644 index 00000000000..0bfe72b2330 --- /dev/null +++ b/thirdparty/sdl/hidapi/windows/hidapi_descriptor_reconstruct.h @@ -0,0 +1,254 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ +#include "SDL_internal.h" + +#ifndef HIDAPI_DESCRIPTOR_RECONSTRUCT_H__ +#define HIDAPI_DESCRIPTOR_RECONSTRUCT_H__ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +/* Do not warn about wcsncpy usage. + https://docs.microsoft.com/cpp/c-runtime-library/security-features-in-the-crt */ +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "hidapi_winapi.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4200) +#pragma warning(disable: 4201) +#pragma warning(disable: 4214) +#endif + +#include + +#include "hidapi_hidsdi.h" +/*#include */ + +#define NUM_OF_HIDP_REPORT_TYPES 3 + +typedef enum rd_items_ { + rd_main_input = 0x80, /* 1000 00 nn */ + rd_main_output = 0x90, /* 1001 00 nn */ + rd_main_feature = 0xB0, /* 1011 00 nn */ + rd_main_collection = 0xA0, /* 1010 00 nn */ + rd_main_collection_end = 0xC0, /* 1100 00 nn */ + rd_global_usage_page = 0x04, /* 0000 01 nn */ + rd_global_logical_minimum = 0x14, /* 0001 01 nn */ + rd_global_logical_maximum = 0x24, /* 0010 01 nn */ + rd_global_physical_minimum = 0x34, /* 0011 01 nn */ + rd_global_physical_maximum = 0x44, /* 0100 01 nn */ + rd_global_unit_exponent = 0x54, /* 0101 01 nn */ + rd_global_unit = 0x64, /* 0110 01 nn */ + rd_global_report_size = 0x74, /* 0111 01 nn */ + rd_global_report_id = 0x84, /* 1000 01 nn */ + rd_global_report_count = 0x94, /* 1001 01 nn */ + rd_global_push = 0xA4, /* 1010 01 nn */ + rd_global_pop = 0xB4, /* 1011 01 nn */ + rd_local_usage = 0x08, /* 0000 10 nn */ + rd_local_usage_minimum = 0x18, /* 0001 10 nn */ + rd_local_usage_maximum = 0x28, /* 0010 10 nn */ + rd_local_designator_index = 0x38, /* 0011 10 nn */ + rd_local_designator_minimum = 0x48, /* 0100 10 nn */ + rd_local_designator_maximum = 0x58, /* 0101 10 nn */ + rd_local_string = 0x78, /* 0111 10 nn */ + rd_local_string_minimum = 0x88, /* 1000 10 nn */ + rd_local_string_maximum = 0x98, /* 1001 10 nn */ + rd_local_delimiter = 0xA8 /* 1010 10 nn */ +} rd_items; + +typedef enum rd_main_items_ { + rd_input = HidP_Input, + rd_output = HidP_Output, + rd_feature = HidP_Feature, + rd_collection, + rd_collection_end, + rd_delimiter_open, + rd_delimiter_usage, + rd_delimiter_close, +} rd_main_items; + +typedef struct rd_bit_range_ { + int FirstBit; + int LastBit; +} rd_bit_range; + +typedef enum rd_item_node_type_ { + rd_item_node_cap, + rd_item_node_padding, + rd_item_node_collection, +} rd_node_type; + +struct rd_main_item_node { + int FirstBit; /* Position of first bit in report (counting from 0) */ + int LastBit; /* Position of last bit in report (counting from 0) */ + rd_node_type TypeOfNode; /* Information if caps index refers to the array of button caps, value caps, + or if the node is just a padding element to fill unused bit positions. + The node can also be a collection node without any bits in the report. */ + int CapsIndex; /* Index in the array of caps */ + int CollectionIndex; /* Index in the array of link collections */ + rd_main_items MainItemType; /* Input, Output, Feature, Collection or Collection End */ + unsigned char ReportID; + struct rd_main_item_node* next; +}; + +typedef struct hid_pp_caps_info_ { + USHORT FirstCap; + USHORT NumberOfCaps; // Includes empty caps after LastCap + USHORT LastCap; + USHORT ReportByteLength; +} hid_pp_caps_info, *phid_pp_caps_info; + +typedef struct hid_pp_link_collection_node_ { + USAGE LinkUsage; + USAGE LinkUsagePage; + USHORT Parent; + USHORT NumberOfChildren; + USHORT NextSibling; + USHORT FirstChild; + ULONG CollectionType : 8; + ULONG IsAlias : 1; + ULONG Reserved : 23; + // Same as the public API structure HIDP_LINK_COLLECTION_NODE, but without PVOID UserContext at the end +} hid_pp_link_collection_node, *phid_pp_link_collection_node; + +// Note: This is risk-reduction-measure for this specific struct, as it has ULONG bit-field. +// Although very unlikely, it might still be possible that the compiler creates a memory layout that is +// not binary compatile. +// Other structs are not checked at the time of writing. +//static_assert(sizeof(struct hid_pp_link_collection_node_) == 16, +// "Size of struct hid_pp_link_collection_node_ not as expected. This might break binary compatibility"); +SDL_COMPILE_TIME_ASSERT(hid_pp_link_collection_node_, sizeof(struct hid_pp_link_collection_node_) == 16); + +typedef struct hidp_unknown_token_ { + UCHAR Token; /* Specifies the one-byte prefix of a global item. */ + UCHAR Reserved[3]; + ULONG BitField; /* Specifies the data part of the global item. */ +} hidp_unknown_token, * phidp_unknown_token; + +typedef struct hid_pp_cap_ { + USAGE UsagePage; + UCHAR ReportID; + UCHAR BitPosition; + USHORT ReportSize; // WIN32 term for this is BitSize + USHORT ReportCount; + USHORT BytePosition; + USHORT BitCount; + ULONG BitField; + USHORT NextBytePosition; + USHORT LinkCollection; + USAGE LinkUsagePage; + USAGE LinkUsage; + + // Start of 8 Flags in one byte + BOOLEAN IsMultipleItemsForArray:1; + + BOOLEAN IsPadding:1; + BOOLEAN IsButtonCap:1; + BOOLEAN IsAbsolute:1; + BOOLEAN IsRange:1; + BOOLEAN IsAlias:1; // IsAlias is set to TRUE in the first n-1 capability structures added to the capability array. IsAlias set to FALSE in the nth capability structure. + BOOLEAN IsStringRange:1; + BOOLEAN IsDesignatorRange:1; + // End of 8 Flags in one byte + BOOLEAN Reserved1[3]; + + hidp_unknown_token UnknownTokens[4]; // 4 x 8 Byte + + union { + struct { + USAGE UsageMin; + USAGE UsageMax; + USHORT StringMin; + USHORT StringMax; + USHORT DesignatorMin; + USHORT DesignatorMax; + USHORT DataIndexMin; + USHORT DataIndexMax; + } Range; + struct { + USAGE Usage; + USAGE Reserved1; + USHORT StringIndex; + USHORT Reserved2; + USHORT DesignatorIndex; + USHORT Reserved3; + USHORT DataIndex; + USHORT Reserved4; + } NotRange; + }; + union { + struct { + LONG LogicalMin; + LONG LogicalMax; + } Button; + struct { + BOOLEAN HasNull; + UCHAR Reserved4[3]; + LONG LogicalMin; + LONG LogicalMax; + LONG PhysicalMin; + LONG PhysicalMax; + } NotButton; + }; + ULONG Units; + ULONG UnitsExp; + +} hid_pp_cap, *phid_pp_cap; + +typedef struct hidp_preparsed_data_ { + UCHAR MagicKey[8]; + USAGE Usage; + USAGE UsagePage; + USHORT Reserved[2]; + + // CAPS structure for Input, Output and Feature + hid_pp_caps_info caps_info[3]; + + USHORT FirstByteOfLinkCollectionArray; + USHORT NumberLinkCollectionNodes; + +#ifndef _MSC_VER + // MINGW fails with: Flexible array member in union not supported + // Solution: https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html + union { +#ifdef HAVE_GCC_DIAGNOSTIC_PRAGMA +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpedantic" +#endif + hid_pp_cap caps[0]; + hid_pp_link_collection_node LinkCollectionArray[0]; +#ifdef HAVE_GCC_DIAGNOSTIC_PRAGMA +#pragma GCC diagnostic pop +#endif + }; +#else + union { + hid_pp_cap caps[]; + hid_pp_link_collection_node LinkCollectionArray[]; + }; +#endif + +} hidp_preparsed_data; + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif diff --git a/thirdparty/sdl/hidapi/windows/hidapi_hidclass.h b/thirdparty/sdl/hidapi/windows/hidapi_hidclass.h new file mode 100644 index 00000000000..8acc52e0adc --- /dev/null +++ b/thirdparty/sdl/hidapi/windows/hidapi_hidclass.h @@ -0,0 +1,40 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +#ifndef HIDAPI_HIDCLASS_H +#define HIDAPI_HIDCLASS_H + +#ifdef HIDAPI_USE_DDK + +#include + +#else + +#include + +/* This part of the header mimics hidclass.h, + but only what is used by HIDAPI */ + +#define HID_OUT_CTL_CODE(id) CTL_CODE(FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS) +#define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100) +#define IOCTL_HID_GET_INPUT_REPORT HID_OUT_CTL_CODE(104) + +#endif + +#endif /* HIDAPI_HIDCLASS_H */ diff --git a/thirdparty/sdl/hidapi/windows/hidapi_hidpi.h b/thirdparty/sdl/hidapi/windows/hidapi_hidpi.h new file mode 100644 index 00000000000..75a5812c943 --- /dev/null +++ b/thirdparty/sdl/hidapi/windows/hidapi_hidpi.h @@ -0,0 +1,72 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +#ifndef HIDAPI_HIDPI_H +#define HIDAPI_HIDPI_H + +#ifdef HIDAPI_USE_DDK + +#include + +#else + +/* This part of the header mimics hidpi.h, + but only what is used by HIDAPI */ + +typedef enum _HIDP_REPORT_TYPE +{ + HidP_Input, + HidP_Output, + HidP_Feature +} HIDP_REPORT_TYPE; + +typedef struct _HIDP_PREPARSED_DATA * PHIDP_PREPARSED_DATA; + +typedef struct _HIDP_CAPS +{ + USAGE Usage; + USAGE UsagePage; + USHORT InputReportByteLength; + USHORT OutputReportByteLength; + USHORT FeatureReportByteLength; + USHORT Reserved[17]; + + USHORT NumberLinkCollectionNodes; + + USHORT NumberInputButtonCaps; + USHORT NumberInputValueCaps; + USHORT NumberInputDataIndices; + + USHORT NumberOutputButtonCaps; + USHORT NumberOutputValueCaps; + USHORT NumberOutputDataIndices; + + USHORT NumberFeatureButtonCaps; + USHORT NumberFeatureValueCaps; + USHORT NumberFeatureDataIndices; +} HIDP_CAPS, *PHIDP_CAPS; + +#define HIDP_STATUS_SUCCESS 0x00110000 +#define HIDP_STATUS_INVALID_PREPARSED_DATA 0xc0110001 + +typedef NTSTATUS (__stdcall *HidP_GetCaps_)(PHIDP_PREPARSED_DATA preparsed_data, PHIDP_CAPS caps); + +#endif + +#endif /* HIDAPI_HIDPI_H */ diff --git a/thirdparty/sdl/hidapi/windows/hidapi_hidsdi.h b/thirdparty/sdl/hidapi/windows/hidapi_hidsdi.h new file mode 100644 index 00000000000..95e2fcb3b80 --- /dev/null +++ b/thirdparty/sdl/hidapi/windows/hidapi_hidsdi.h @@ -0,0 +1,59 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +#ifndef HIDAPI_HIDSDI_H +#define HIDAPI_HIDSDI_H + +#ifdef HIDAPI_USE_DDK + +#include + +#else + +/* This part of the header mimics hidsdi.h, + but only what is used by HIDAPI */ + +typedef USHORT USAGE; + +#include "hidapi_hidpi.h" + +typedef struct _HIDD_ATTRIBUTES{ + ULONG Size; + USHORT VendorID; + USHORT ProductID; + USHORT VersionNumber; +} HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES; + +typedef void (__stdcall *HidD_GetHidGuid_)(LPGUID hid_guid); +typedef BOOLEAN (__stdcall *HidD_GetAttributes_)(HANDLE device, PHIDD_ATTRIBUTES attrib); +typedef BOOLEAN (__stdcall *HidD_GetSerialNumberString_)(HANDLE device, PVOID buffer, ULONG buffer_len); +typedef BOOLEAN (__stdcall *HidD_GetManufacturerString_)(HANDLE handle, PVOID buffer, ULONG buffer_len); +typedef BOOLEAN (__stdcall *HidD_GetProductString_)(HANDLE handle, PVOID buffer, ULONG buffer_len); +typedef BOOLEAN (__stdcall *HidD_SetFeature_)(HANDLE handle, PVOID data, ULONG length); +typedef BOOLEAN (__stdcall *HidD_GetFeature_)(HANDLE handle, PVOID data, ULONG length); +typedef BOOLEAN (__stdcall *HidD_GetInputReport_)(HANDLE handle, PVOID data, ULONG length); +typedef BOOLEAN (__stdcall *HidD_GetIndexedString_)(HANDLE handle, ULONG string_index, PVOID buffer, ULONG buffer_len); +typedef BOOLEAN (__stdcall *HidD_GetPreparsedData_)(HANDLE handle, PHIDP_PREPARSED_DATA *preparsed_data); +typedef BOOLEAN (__stdcall *HidD_FreePreparsedData_)(PHIDP_PREPARSED_DATA preparsed_data); +typedef BOOLEAN (__stdcall *HidD_SetNumInputBuffers_)(HANDLE handle, ULONG number_buffers); +typedef BOOLEAN (__stdcall *HidD_SetOutputReport_)(HANDLE HidDeviceObject, PVOID ReportBuffer, ULONG ReportBufferLength); + +#endif + +#endif /* HIDAPI_HIDSDI_H */ diff --git a/thirdparty/sdl/hidapi/windows/hidapi_winapi.h b/thirdparty/sdl/hidapi/windows/hidapi_winapi.h new file mode 100644 index 00000000000..9c4b5c0b63c --- /dev/null +++ b/thirdparty/sdl/hidapi/windows/hidapi_winapi.h @@ -0,0 +1,74 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2022, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +/** @file + * @defgroup API hidapi API + * + * Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) + */ + +#ifndef HIDAPI_WINAPI_H__ +#define HIDAPI_WINAPI_H__ + +#include + +#include + +#include "../hidapi/hidapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + /** @brief Get the container ID for a HID device. + + Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) + + This function returns the `DEVPKEY_Device_ContainerId` property of + the given device. This can be used to correlate different + interfaces/ports on the same hardware device. + + @ingroup API + @param dev A device handle returned from hid_open(). + @param container_id The device's container ID on return. + + @returns + This function returns 0 on success and -1 on error. + */ + int HID_API_EXPORT_CALL hid_winapi_get_container_id(hid_device *dev, GUID *container_id); + + /** + * @brief Reconstructs a HID Report Descriptor from a Win32 HIDP_PREPARSED_DATA structure. + * This reconstructed report descriptor is logical identical to the real report descriptor, + * but not byte wise identical. + * + * @param[in] hidp_preparsed_data Pointer to the HIDP_PREPARSED_DATA to read, i.e.: the value of PHIDP_PREPARSED_DATA, + * as returned by HidD_GetPreparsedData WinAPI function. + * @param buf Pointer to the buffer where the report descriptor should be stored. + * @param[in] buf_size Size of the buffer. The recommended size for the buffer is @ref HID_API_MAX_REPORT_DESCRIPTOR_SIZE bytes. + * + * @return Returns size of reconstructed report descriptor if successful, -1 for error. + */ + int HID_API_EXPORT_CALL hid_winapi_descriptor_reconstruct_pp_data(void *hidp_preparsed_data, unsigned char *buf, size_t buf_size); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/thirdparty/sdl/include/SDL3/SDL.h b/thirdparty/sdl/include/SDL3/SDL.h new file mode 100644 index 00000000000..f0671c95c32 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL.h @@ -0,0 +1,90 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * Main include header for the SDL library, version 3.2.16 + * + * It is almost always best to include just this one header instead of + * picking out individual headers included here. There are exceptions to + * this rule--SDL_main.h is special and not included here--but usually + * letting SDL.h include the kitchen sink for you is the correct approach. + */ + +#ifndef SDL_h_ +#define SDL_h_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include + +#endif /* SDL_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_assert.h b/thirdparty/sdl/include/SDL3/SDL_assert.h new file mode 100644 index 00000000000..6c90acc0290 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_assert.h @@ -0,0 +1,662 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryAssert + * + * A helpful assertion macro! + * + * SDL assertions operate like your usual `assert` macro, but with some added + * features: + * + * - It uses a trick with the `sizeof` operator, so disabled assertions + * vaporize out of the compiled code, but variables only referenced in the + * assertion won't trigger compiler warnings about being unused. + * - It is safe to use with a dangling-else: `if (x) SDL_assert(y); else + * do_something();` + * - It works the same everywhere, instead of counting on various platforms' + * compiler and C runtime to behave. + * - It provides multiple levels of assertion (SDL_assert, SDL_assert_release, + * SDL_assert_paranoid) instead of a single all-or-nothing option. + * - It offers a variety of responses when an assertion fails (retry, trigger + * the debugger, abort the program, ignore the failure once, ignore it for + * the rest of the program's run). + * - It tries to show the user a dialog by default, if possible, but the app + * can provide a callback to handle assertion failures however they like. + * - It lets failed assertions be retried. Perhaps you had a network failure + * and just want to retry the test after plugging your network cable back + * in? You can. + * - It lets the user ignore an assertion failure, if there's a harmless + * problem that one can continue past. + * - It lets the user mark an assertion as ignored for the rest of the + * program's run; if there's a harmless problem that keeps popping up. + * - It provides statistics and data on all failed assertions to the app. + * - It allows the default assertion handler to be controlled with environment + * variables, in case an automated script needs to control it. + * - It can be used as an aid to Clang's static analysis; it will treat SDL + * assertions as universally true (under the assumption that you are serious + * about the asserted claims and that your debug builds will detect when + * these claims were wrong). This can help the analyzer avoid false + * positives. + * + * To use it: compile a debug build and just sprinkle around tests to check + * your code! + */ + +#ifndef SDL_assert_h_ +#define SDL_assert_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * The level of assertion aggressiveness. + * + * This value changes depending on compiler options and other preprocessor + * defines. + * + * It is currently one of the following values, but future SDL releases might + * add more: + * + * - 0: All SDL assertion macros are disabled. + * - 1: Release settings: SDL_assert disabled, SDL_assert_release enabled. + * - 2: Debug settings: SDL_assert and SDL_assert_release enabled. + * - 3: Paranoid settings: All SDL assertion macros enabled, including + * SDL_assert_paranoid. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ASSERT_LEVEL SomeNumberBasedOnVariousFactors + +#elif !defined(SDL_ASSERT_LEVEL) +#ifdef SDL_DEFAULT_ASSERT_LEVEL +#define SDL_ASSERT_LEVEL SDL_DEFAULT_ASSERT_LEVEL +#elif defined(_DEBUG) || defined(DEBUG) || \ + (defined(__GNUC__) && !defined(__OPTIMIZE__)) +#define SDL_ASSERT_LEVEL 2 +#else +#define SDL_ASSERT_LEVEL 1 +#endif +#endif + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Attempt to tell an attached debugger to pause. + * + * This allows an app to programmatically halt ("break") the debugger as if it + * had hit a breakpoint, allowing the developer to examine program state, etc. + * + * This is a macro--not a function--so that the debugger breaks on the source + * code line that used SDL_TriggerBreakpoint and not in some random guts of + * SDL. SDL_assert uses this macro for the same reason. + * + * If the program is not running under a debugger, SDL_TriggerBreakpoint will + * likely terminate the app, possibly without warning. If the current platform + * isn't supported, this macro is left undefined. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_TriggerBreakpoint() TriggerABreakpointInAPlatformSpecificManner + +#elif defined(_MSC_VER) && _MSC_VER >= 1310 + /* Don't include intrin.h here because it contains C++ code */ + extern void __cdecl __debugbreak(void); + #define SDL_TriggerBreakpoint() __debugbreak() +#elif defined(_MSC_VER) && defined(_M_IX86) + #define SDL_TriggerBreakpoint() { _asm { int 0x03 } } +#elif defined(ANDROID) + #include + #define SDL_TriggerBreakpoint() assert(0) +#elif SDL_HAS_BUILTIN(__builtin_debugtrap) + #define SDL_TriggerBreakpoint() __builtin_debugtrap() +#elif SDL_HAS_BUILTIN(__builtin_trap) + #define SDL_TriggerBreakpoint() __builtin_trap() +#elif (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) + #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "int $3\n\t" ) +#elif (defined(__GNUC__) || defined(__clang__)) && defined(__riscv) + #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "ebreak\n\t" ) +#elif ( defined(SDL_PLATFORM_APPLE) && (defined(__arm64__) || defined(__aarch64__)) ) /* this might work on other ARM targets, but this is a known quantity... */ + #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "brk #22\n\t" ) +#elif defined(SDL_PLATFORM_APPLE) && defined(__arm__) + #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "bkpt #22\n\t" ) +#elif defined(_WIN32) && ((defined(__GNUC__) || defined(__clang__)) && (defined(__arm64__) || defined(__aarch64__)) ) + #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "brk #0xF000\n\t" ) +#elif defined(__GNUC__) || defined(__clang__) + #define SDL_TriggerBreakpoint() __builtin_trap() /* older gcc may not support SDL_HAS_BUILTIN(__builtin_trap) above */ +#elif defined(__386__) && defined(__WATCOMC__) + #define SDL_TriggerBreakpoint() { _asm { int 0x03 } } +#elif defined(HAVE_SIGNAL_H) && !defined(__WATCOMC__) + #include + #define SDL_TriggerBreakpoint() raise(SIGTRAP) +#else + /* SDL_TriggerBreakpoint is intentionally left undefined on unknown platforms. */ +#endif + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A macro that reports the current function being compiled. + * + * If SDL can't figure how the compiler reports this, it will use "???". + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_FUNCTION __FUNCTION__ + +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 supports __func__ as a standard. */ +# define SDL_FUNCTION __func__ +#elif ((defined(__GNUC__) && (__GNUC__ >= 2)) || defined(_MSC_VER) || defined (__WATCOMC__)) +# define SDL_FUNCTION __FUNCTION__ +#else +# define SDL_FUNCTION "???" +#endif + +/** + * A macro that reports the current file being compiled. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_FILE __FILE__ + +/** + * A macro that reports the current line number of the file being compiled. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_LINE __LINE__ + +/* +sizeof (x) makes the compiler still parse the expression even without +assertions enabled, so the code is always checked at compile time, but +doesn't actually generate code for it, so there are no side effects or +expensive checks at run time, just the constant size of what x WOULD be, +which presumably gets optimized out as unused. +This also solves the problem of... + + int somevalue = blah(); + SDL_assert(somevalue == 1); + +...which would cause compiles to complain that somevalue is unused if we +disable assertions. +*/ + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A macro for wrapping code in `do {} while (0);` without compiler warnings. + * + * Visual Studio with really aggressive warnings enabled needs this to avoid + * compiler complaints. + * + * the `do {} while (0);` trick is useful for wrapping code in a macro that + * may or may not be a single statement, to avoid various C language + * accidents. + * + * To use: + * + * ```c + * do { SomethingOnce(); } while (SDL_NULL_WHILE_LOOP_CONDITION (0)); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NULL_WHILE_LOOP_CONDITION (0) + +#elif defined(_MSC_VER) /* Avoid /W4 warnings. */ +/* "while (0,0)" fools Microsoft's compiler's /W4 warning level into thinking + this condition isn't constant. And looks like an owl's face! */ +#define SDL_NULL_WHILE_LOOP_CONDITION (0,0) +#else +#define SDL_NULL_WHILE_LOOP_CONDITION (0) +#endif + +/** + * The macro used when an assertion is disabled. + * + * This isn't for direct use by apps, but this is the code that is inserted + * when an SDL_assert is disabled (perhaps in a release build). + * + * The code does nothing, but wraps `condition` in a sizeof operator, which + * generates no code and has no side effects, but avoid compiler warnings + * about unused variables. + * + * \param condition the condition to assert (but not actually run here). + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_disabled_assert(condition) \ + do { (void) sizeof ((condition)); } while (SDL_NULL_WHILE_LOOP_CONDITION) + +/** + * Possible outcomes from a triggered assertion. + * + * When an enabled assertion triggers, it may call the assertion handler + * (possibly one provided by the app via SDL_SetAssertionHandler), which will + * return one of these values, possibly after asking the user. + * + * Then SDL will respond based on this outcome (loop around to retry the + * condition, try to break in a debugger, kill the program, or ignore the + * problem). + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_AssertState +{ + SDL_ASSERTION_RETRY, /**< Retry the assert immediately. */ + SDL_ASSERTION_BREAK, /**< Make the debugger trigger a breakpoint. */ + SDL_ASSERTION_ABORT, /**< Terminate the program. */ + SDL_ASSERTION_IGNORE, /**< Ignore the assert. */ + SDL_ASSERTION_ALWAYS_IGNORE /**< Ignore the assert from now on. */ +} SDL_AssertState; + +/** + * Information about an assertion failure. + * + * This structure is filled in with information about a triggered assertion, + * used by the assertion handler, then added to the assertion report. This is + * returned as a linked list from SDL_GetAssertionReport(). + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_AssertData +{ + bool always_ignore; /**< true if app should always continue when assertion is triggered. */ + unsigned int trigger_count; /**< Number of times this assertion has been triggered. */ + const char *condition; /**< A string of this assert's test code. */ + const char *filename; /**< The source file where this assert lives. */ + int linenum; /**< The line in `filename` where this assert lives. */ + const char *function; /**< The name of the function where this assert lives. */ + const struct SDL_AssertData *next; /**< next item in the linked list. */ +} SDL_AssertData; + +/** + * Never call this directly. + * + * Use the SDL_assert macros instead. + * + * \param data assert data structure. + * \param func function name. + * \param file file name. + * \param line line number. + * \returns assert state. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_AssertState SDLCALL SDL_ReportAssertion(SDL_AssertData *data, + const char *func, + const char *file, int line) SDL_ANALYZER_NORETURN; + + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * The macro used when an assertion triggers a breakpoint. + * + * This isn't for direct use by apps; use SDL_assert or SDL_TriggerBreakpoint + * instead. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AssertBreakpoint() SDL_TriggerBreakpoint() + +#elif !defined(SDL_AssertBreakpoint) +# if defined(ANDROID) && defined(assert) + /* Define this as empty in case assert() is defined as SDL_assert */ +# define SDL_AssertBreakpoint() +# else +# define SDL_AssertBreakpoint() SDL_TriggerBreakpoint() +# endif +#endif /* !SDL_AssertBreakpoint */ + +/** + * The macro used when an assertion is enabled. + * + * This isn't for direct use by apps, but this is the code that is inserted + * when an SDL_assert is enabled. + * + * The `do {} while(0)` avoids dangling else problems: + * + * ```c + * if (x) SDL_assert(y); else blah(); + * ``` + * + * ... without the do/while, the "else" could attach to this macro's "if". We + * try to handle just the minimum we need here in a macro...the loop, the + * static vars, and break points. The heavy lifting is handled in + * SDL_ReportAssertion(). + * + * \param condition the condition to assert. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_enabled_assert(condition) \ + do { \ + while ( !(condition) ) { \ + static struct SDL_AssertData sdl_assert_data = { 0, 0, #condition, 0, 0, 0, 0 }; \ + const SDL_AssertState sdl_assert_state = SDL_ReportAssertion(&sdl_assert_data, SDL_FUNCTION, SDL_FILE, SDL_LINE); \ + if (sdl_assert_state == SDL_ASSERTION_RETRY) { \ + continue; /* go again. */ \ + } else if (sdl_assert_state == SDL_ASSERTION_BREAK) { \ + SDL_AssertBreakpoint(); \ + } \ + break; /* not retrying. */ \ + } \ + } while (SDL_NULL_WHILE_LOOP_CONDITION) + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * An assertion test that is normally performed only in debug builds. + * + * This macro is enabled when the SDL_ASSERT_LEVEL is >= 2, otherwise it is + * disabled. This is meant to only do these tests in debug builds, so they can + * tend to be more expensive, and they are meant to bring everything to a halt + * when they fail, with the programmer there to assess the problem. + * + * In short: you can sprinkle these around liberally and assume they will + * evaporate out of the build when building for end-users. + * + * When assertions are disabled, this wraps `condition` in a `sizeof` + * operator, which means any function calls and side effects will not run, but + * the compiler will not complain about any otherwise-unused variables that + * are only referenced in the assertion. + * + * One can set the environment variable "SDL_ASSERT" to one of several strings + * ("abort", "break", "retry", "ignore", "always_ignore") to force a default + * behavior, which may be desirable for automation purposes. If your platform + * requires GUI interfaces to happen on the main thread but you're debugging + * an assertion in a background thread, it might be desirable to set this to + * "break" so that your debugger takes control as soon as assert is triggered, + * instead of risking a bad UI interaction (deadlock, etc) in the application. + * + * \param condition boolean value to test. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_assert(condition) if (assertion_enabled && (condition)) { trigger_assertion; } + +/** + * An assertion test that is performed even in release builds. + * + * This macro is enabled when the SDL_ASSERT_LEVEL is >= 1, otherwise it is + * disabled. This is meant to be for tests that are cheap to make and + * extremely unlikely to fail; generally it is frowned upon to have an + * assertion failure in a release build, so these assertions generally need to + * be of more than life-and-death importance if there's a chance they might + * trigger. You should almost always consider handling these cases more + * gracefully than an assert allows. + * + * When assertions are disabled, this wraps `condition` in a `sizeof` + * operator, which means any function calls and side effects will not run, but + * the compiler will not complain about any otherwise-unused variables that + * are only referenced in the assertion. + * + * One can set the environment variable "SDL_ASSERT" to one of several strings + * ("abort", "break", "retry", "ignore", "always_ignore") to force a default + * behavior, which may be desirable for automation purposes. If your platform + * requires GUI interfaces to happen on the main thread but you're debugging + * an assertion in a background thread, it might be desirable to set this to + * "break" so that your debugger takes control as soon as assert is triggered, + * instead of risking a bad UI interaction (deadlock, etc) in the application. + * * + * + * \param condition boolean value to test. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_assert_release(condition) SDL_disabled_assert(condition) + +/** + * An assertion test that is performed only when built with paranoid settings. + * + * This macro is enabled when the SDL_ASSERT_LEVEL is >= 3, otherwise it is + * disabled. This is a higher level than both release and debug, so these + * tests are meant to be expensive and only run when specifically looking for + * extremely unexpected failure cases in a special build. + * + * When assertions are disabled, this wraps `condition` in a `sizeof` + * operator, which means any function calls and side effects will not run, but + * the compiler will not complain about any otherwise-unused variables that + * are only referenced in the assertion. + * + * One can set the environment variable "SDL_ASSERT" to one of several strings + * ("abort", "break", "retry", "ignore", "always_ignore") to force a default + * behavior, which may be desirable for automation purposes. If your platform + * requires GUI interfaces to happen on the main thread but you're debugging + * an assertion in a background thread, it might be desirable to set this to + * "break" so that your debugger takes control as soon as assert is triggered, + * instead of risking a bad UI interaction (deadlock, etc) in the application. + * + * \param condition boolean value to test. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_assert_paranoid(condition) SDL_disabled_assert(condition) + +/* Enable various levels of assertions. */ +#elif SDL_ASSERT_LEVEL == 0 /* assertions disabled */ +# define SDL_assert(condition) SDL_disabled_assert(condition) +# define SDL_assert_release(condition) SDL_disabled_assert(condition) +# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition) +#elif SDL_ASSERT_LEVEL == 1 /* release settings. */ +# define SDL_assert(condition) SDL_disabled_assert(condition) +# define SDL_assert_release(condition) SDL_enabled_assert(condition) +# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition) +#elif SDL_ASSERT_LEVEL == 2 /* debug settings. */ +# define SDL_assert(condition) SDL_enabled_assert(condition) +# define SDL_assert_release(condition) SDL_enabled_assert(condition) +# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition) +#elif SDL_ASSERT_LEVEL == 3 /* paranoid settings. */ +# define SDL_assert(condition) SDL_enabled_assert(condition) +# define SDL_assert_release(condition) SDL_enabled_assert(condition) +# define SDL_assert_paranoid(condition) SDL_enabled_assert(condition) +#else +# error Unknown assertion level. +#endif + +/** + * An assertion test that is always performed. + * + * This macro is always enabled no matter what SDL_ASSERT_LEVEL is set to. You + * almost never want to use this, as it could trigger on an end-user's system, + * crashing your program. + * + * One can set the environment variable "SDL_ASSERT" to one of several strings + * ("abort", "break", "retry", "ignore", "always_ignore") to force a default + * behavior, which may be desirable for automation purposes. If your platform + * requires GUI interfaces to happen on the main thread but you're debugging + * an assertion in a background thread, it might be desirable to set this to + * "break" so that your debugger takes control as soon as assert is triggered, + * instead of risking a bad UI interaction (deadlock, etc) in the application. + * + * \param condition boolean value to test. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_assert_always(condition) SDL_enabled_assert(condition) + + +/** + * A callback that fires when an SDL assertion fails. + * + * \param data a pointer to the SDL_AssertData structure corresponding to the + * current assertion. + * \param userdata what was passed as `userdata` to SDL_SetAssertionHandler(). + * \returns an SDL_AssertState value indicating how to handle the failure. + * + * \threadsafety This callback may be called from any thread that triggers an + * assert at any time. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef SDL_AssertState (SDLCALL *SDL_AssertionHandler)( + const SDL_AssertData *data, void *userdata); + +/** + * Set an application-defined assertion handler. + * + * This function allows an application to show its own assertion UI and/or + * force the response to an assertion failure. If the application doesn't + * provide this, SDL will try to do the right thing, popping up a + * system-specific GUI dialog, and probably minimizing any fullscreen windows. + * + * This callback may fire from any thread, but it runs wrapped in a mutex, so + * it will only fire from one thread at a time. + * + * This callback is NOT reset to SDL's internal handler upon SDL_Quit()! + * + * \param handler the SDL_AssertionHandler function to call when an assertion + * fails or NULL for the default handler. + * \param userdata a pointer that is passed to `handler`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAssertionHandler + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetAssertionHandler( + SDL_AssertionHandler handler, + void *userdata); + +/** + * Get the default assertion handler. + * + * This returns the function pointer that is called by default when an + * assertion is triggered. This is an internal function provided by SDL, that + * is used for assertions when SDL_SetAssertionHandler() hasn't been used to + * provide a different function. + * + * \returns the default SDL_AssertionHandler that is called when an assert + * triggers. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAssertionHandler + */ +extern SDL_DECLSPEC SDL_AssertionHandler SDLCALL SDL_GetDefaultAssertionHandler(void); + +/** + * Get the current assertion handler. + * + * This returns the function pointer that is called when an assertion is + * triggered. This is either the value last passed to + * SDL_SetAssertionHandler(), or if no application-specified function is set, + * is equivalent to calling SDL_GetDefaultAssertionHandler(). + * + * The parameter `puserdata` is a pointer to a void*, which will store the + * "userdata" pointer that was passed to SDL_SetAssertionHandler(). This value + * will always be NULL for the default handler. If you don't care about this + * data, it is safe to pass a NULL pointer to this function to ignore it. + * + * \param puserdata pointer which is filled with the "userdata" pointer that + * was passed to SDL_SetAssertionHandler(). + * \returns the SDL_AssertionHandler that is called when an assert triggers. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAssertionHandler + */ +extern SDL_DECLSPEC SDL_AssertionHandler SDLCALL SDL_GetAssertionHandler(void **puserdata); + +/** + * Get a list of all assertion failures. + * + * This function gets all assertions triggered since the last call to + * SDL_ResetAssertionReport(), or the start of the program. + * + * The proper way to examine this data looks something like this: + * + * ```c + * const SDL_AssertData *item = SDL_GetAssertionReport(); + * while (item) { + * printf("'%s', %s (%s:%d), triggered %u times, always ignore: %s.\\n", + * item->condition, item->function, item->filename, + * item->linenum, item->trigger_count, + * item->always_ignore ? "yes" : "no"); + * item = item->next; + * } + * ``` + * + * \returns a list of all failed assertions or NULL if the list is empty. This + * memory should not be modified or freed by the application. This + * pointer remains valid until the next call to SDL_Quit() or + * SDL_ResetAssertionReport(). + * + * \threadsafety This function is not thread safe. Other threads calling + * SDL_ResetAssertionReport() simultaneously, may render the + * returned pointer invalid. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ResetAssertionReport + */ +extern SDL_DECLSPEC const SDL_AssertData * SDLCALL SDL_GetAssertionReport(void); + +/** + * Clear the list of all assertion failures. + * + * This function will clear the list of all assertions triggered up to that + * point. Immediately following this call, SDL_GetAssertionReport will return + * no items. In addition, any previously-triggered assertions will be reset to + * a trigger_count of zero, and their always_ignore state will be false. + * + * \threadsafety This function is not thread safe. Other threads triggering an + * assertion, or simultaneously calling this function may cause + * memory leaks or crashes. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAssertionReport + */ +extern SDL_DECLSPEC void SDLCALL SDL_ResetAssertionReport(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_assert_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_asyncio.h b/thirdparty/sdl/include/SDL3/SDL_asyncio.h new file mode 100644 index 00000000000..b36cb071bcf --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_asyncio.h @@ -0,0 +1,546 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: AsyncIO */ + +/** + * # CategoryAsyncIO + * + * SDL offers a way to perform I/O asynchronously. This allows an app to read + * or write files without waiting for data to actually transfer; the functions + * that request I/O never block while the request is fulfilled. + * + * Instead, the data moves in the background and the app can check for results + * at their leisure. + * + * This is more complicated than just reading and writing files in a + * synchronous way, but it can allow for more efficiency, and never having + * framerate drops as the hard drive catches up, etc. + * + * The general usage pattern for async I/O is: + * + * - Create one or more SDL_AsyncIOQueue objects. + * - Open files with SDL_AsyncIOFromFile. + * - Start I/O tasks to the files with SDL_ReadAsyncIO or SDL_WriteAsyncIO, + * putting those tasks into one of the queues. + * - Later on, use SDL_GetAsyncIOResult on a queue to see if any task is + * finished without blocking. Tasks might finish in any order with success + * or failure. + * - When all your tasks are done, close the file with SDL_CloseAsyncIO. This + * also generates a task, since it might flush data to disk! + * + * This all works, without blocking, in a single thread, but one can also wait + * on a queue in a background thread, sleeping until new results have arrived: + * + * - Call SDL_WaitAsyncIOResult from one or more threads to efficiently block + * until new tasks complete. + * - When shutting down, call SDL_SignalAsyncIOQueue to unblock any sleeping + * threads despite there being no new tasks completed. + * + * And, of course, to match the synchronous SDL_LoadFile, we offer + * SDL_LoadFileAsync as a convenience function. This will handle allocating a + * buffer, slurping in the file data, and null-terminating it; you still check + * for results later. + * + * Behind the scenes, SDL will use newer, efficient APIs on platforms that + * support them: Linux's io_uring and Windows 11's IoRing, for example. If + * those technologies aren't available, SDL will offload the work to a thread + * pool that will manage otherwise-synchronous loads without blocking the app. + * + * ## Best Practices + * + * Simple non-blocking I/O--for an app that just wants to pick up data + * whenever it's ready without losing framerate waiting on disks to spin--can + * use whatever pattern works well for the program. In this case, simply call + * SDL_ReadAsyncIO, or maybe SDL_LoadFileAsync, as needed. Once a frame, call + * SDL_GetAsyncIOResult to check for any completed tasks and deal with the + * data as it arrives. + * + * If two separate pieces of the same program need their own I/O, it is legal + * for each to create their own queue. This will prevent either piece from + * accidentally consuming the other's completed tasks. Each queue does require + * some amount of resources, but it is not an overwhelming cost. Do not make a + * queue for each task, however. It is better to put many tasks into a single + * queue. They will be reported in order of completion, not in the order they + * were submitted, so it doesn't generally matter what order tasks are + * started. + * + * One async I/O queue can be shared by multiple threads, or one thread can + * have more than one queue, but the most efficient way--if ruthless + * efficiency is the goal--is to have one queue per thread, with multiple + * threads working in parallel, and attempt to keep each queue loaded with + * tasks that are both started by and consumed by the same thread. On modern + * platforms that can use newer interfaces, this can keep data flowing as + * efficiently as possible all the way from storage hardware to the app, with + * no contention between threads for access to the same queue. + * + * Written data is not guaranteed to make it to physical media by the time a + * closing task is completed, unless SDL_CloseAsyncIO is called with its + * `flush` parameter set to true, which is to say that a successful result + * here can still result in lost data during an unfortunately-timed power + * outage if not flushed. However, flushing will take longer and may be + * unnecessary, depending on the app's needs. + */ + +#ifndef SDL_asyncio_h_ +#define SDL_asyncio_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The asynchronous I/O operation structure. + * + * This operates as an opaque handle. One can then request read or write + * operations on it. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_AsyncIOFromFile + */ +typedef struct SDL_AsyncIO SDL_AsyncIO; + +/** + * Types of asynchronous I/O tasks. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_AsyncIOTaskType +{ + SDL_ASYNCIO_TASK_READ, /**< A read operation. */ + SDL_ASYNCIO_TASK_WRITE, /**< A write operation. */ + SDL_ASYNCIO_TASK_CLOSE /**< A close operation. */ +} SDL_AsyncIOTaskType; + +/** + * Possible outcomes of an asynchronous I/O task. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_AsyncIOResult +{ + SDL_ASYNCIO_COMPLETE, /**< request was completed without error */ + SDL_ASYNCIO_FAILURE, /**< request failed for some reason; check SDL_GetError()! */ + SDL_ASYNCIO_CANCELED /**< request was canceled before completing. */ +} SDL_AsyncIOResult; + +/** + * Information about a completed asynchronous I/O request. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_AsyncIOOutcome +{ + SDL_AsyncIO *asyncio; /**< what generated this task. This pointer will be invalid if it was closed! */ + SDL_AsyncIOTaskType type; /**< What sort of task was this? Read, write, etc? */ + SDL_AsyncIOResult result; /**< the result of the work (success, failure, cancellation). */ + void *buffer; /**< buffer where data was read/written. */ + Uint64 offset; /**< offset in the SDL_AsyncIO where data was read/written. */ + Uint64 bytes_requested; /**< number of bytes the task was to read/write. */ + Uint64 bytes_transferred; /**< actual number of bytes that were read/written. */ + void *userdata; /**< pointer provided by the app when starting the task */ +} SDL_AsyncIOOutcome; + +/** + * A queue of completed asynchronous I/O tasks. + * + * When starting an asynchronous operation, you specify a queue for the new + * task. A queue can be asked later if any tasks in it have completed, + * allowing an app to manage multiple pending tasks in one place, in whatever + * order they complete. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_CreateAsyncIOQueue + * \sa SDL_ReadAsyncIO + * \sa SDL_WriteAsyncIO + * \sa SDL_GetAsyncIOResult + * \sa SDL_WaitAsyncIOResult + */ +typedef struct SDL_AsyncIOQueue SDL_AsyncIOQueue; + +/** + * Use this function to create a new SDL_AsyncIO object for reading from + * and/or writing to a named file. + * + * The `mode` string understands the following values: + * + * - "r": Open a file for reading only. It must exist. + * - "w": Open a file for writing only. It will create missing files or + * truncate existing ones. + * - "r+": Open a file for update both reading and writing. The file must + * exist. + * - "w+": Create an empty file for both reading and writing. If a file with + * the same name already exists its content is erased and the file is + * treated as a new empty file. + * + * There is no "b" mode, as there is only "binary" style I/O, and no "a" mode + * for appending, since you specify the position when starting a task. + * + * This function supports Unicode filenames, but they must be encoded in UTF-8 + * format, regardless of the underlying operating system. + * + * This call is _not_ asynchronous; it will open the file before returning, + * under the assumption that doing so is generally a fast operation. Future + * reads and writes to the opened file will be async, however. + * + * \param file a UTF-8 string representing the filename to open. + * \param mode an ASCII string representing the mode to be used for opening + * the file. + * \returns a pointer to the SDL_AsyncIO structure that is created or NULL on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseAsyncIO + * \sa SDL_ReadAsyncIO + * \sa SDL_WriteAsyncIO + */ +extern SDL_DECLSPEC SDL_AsyncIO * SDLCALL SDL_AsyncIOFromFile(const char *file, const char *mode); + +/** + * Use this function to get the size of the data stream in an SDL_AsyncIO. + * + * This call is _not_ asynchronous; it assumes that obtaining this info is a + * non-blocking operation in most reasonable cases. + * + * \param asyncio the SDL_AsyncIO to get the size of the data stream from. + * \returns the size of the data stream in the SDL_IOStream on success or a + * negative error code on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Sint64 SDLCALL SDL_GetAsyncIOSize(SDL_AsyncIO *asyncio); + +/** + * Start an async read. + * + * This function reads up to `size` bytes from `offset` position in the data + * source to the area pointed at by `ptr`. This function may read less bytes + * than requested. + * + * This function returns as quickly as possible; it does not wait for the read + * to complete. On a successful return, this work will continue in the + * background. If the work begins, even failure is asynchronous: a failing + * return value from this function only means the work couldn't start at all. + * + * `ptr` must remain available until the work is done, and may be accessed by + * the system at any time until then. Do not allocate it on the stack, as this + * might take longer than the life of the calling function to complete! + * + * An SDL_AsyncIOQueue must be specified. The newly-created task will be added + * to it when it completes its work. + * + * \param asyncio a pointer to an SDL_AsyncIO structure. + * \param ptr a pointer to a buffer to read data into. + * \param offset the position to start reading in the data source. + * \param size the number of bytes to read from the data source. + * \param queue a queue to add the new SDL_AsyncIO to. + * \param userdata an app-defined pointer that will be provided with the task + * results. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_WriteAsyncIO + * \sa SDL_CreateAsyncIOQueue + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadAsyncIO(SDL_AsyncIO *asyncio, void *ptr, Uint64 offset, Uint64 size, SDL_AsyncIOQueue *queue, void *userdata); + +/** + * Start an async write. + * + * This function writes `size` bytes from `offset` position in the data source + * to the area pointed at by `ptr`. + * + * This function returns as quickly as possible; it does not wait for the + * write to complete. On a successful return, this work will continue in the + * background. If the work begins, even failure is asynchronous: a failing + * return value from this function only means the work couldn't start at all. + * + * `ptr` must remain available until the work is done, and may be accessed by + * the system at any time until then. Do not allocate it on the stack, as this + * might take longer than the life of the calling function to complete! + * + * An SDL_AsyncIOQueue must be specified. The newly-created task will be added + * to it when it completes its work. + * + * \param asyncio a pointer to an SDL_AsyncIO structure. + * \param ptr a pointer to a buffer to write data from. + * \param offset the position to start writing to the data source. + * \param size the number of bytes to write to the data source. + * \param queue a queue to add the new SDL_AsyncIO to. + * \param userdata an app-defined pointer that will be provided with the task + * results. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ReadAsyncIO + * \sa SDL_CreateAsyncIOQueue + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteAsyncIO(SDL_AsyncIO *asyncio, void *ptr, Uint64 offset, Uint64 size, SDL_AsyncIOQueue *queue, void *userdata); + +/** + * Close and free any allocated resources for an async I/O object. + * + * Closing a file is _also_ an asynchronous task! If a write failure were to + * happen during the closing process, for example, the task results will + * report it as usual. + * + * Closing a file that has been written to does not guarantee the data has + * made it to physical media; it may remain in the operating system's file + * cache, for later writing to disk. This means that a successfully-closed + * file can be lost if the system crashes or loses power in this small window. + * To prevent this, call this function with the `flush` parameter set to true. + * This will make the operation take longer, and perhaps increase system load + * in general, but a successful result guarantees that the data has made it to + * physical storage. Don't use this for temporary files, caches, and + * unimportant data, and definitely use it for crucial irreplaceable files, + * like game saves. + * + * This function guarantees that the close will happen after any other pending + * tasks to `asyncio`, so it's safe to open a file, start several operations, + * close the file immediately, then check for all results later. This function + * will not block until the tasks have completed. + * + * Once this function returns true, `asyncio` is no longer valid, regardless + * of any future outcomes. Any completed tasks might still contain this + * pointer in their SDL_AsyncIOOutcome data, in case the app was using this + * value to track information, but it should not be used again. + * + * If this function returns false, the close wasn't started at all, and it's + * safe to attempt to close again later. + * + * An SDL_AsyncIOQueue must be specified. The newly-created task will be added + * to it when it completes its work. + * + * \param asyncio a pointer to an SDL_AsyncIO structure to close. + * \param flush true if data should sync to disk before the task completes. + * \param queue a queue to add the new SDL_AsyncIO to. + * \param userdata an app-defined pointer that will be provided with the task + * results. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, but two + * threads should not attempt to close the same object. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CloseAsyncIO(SDL_AsyncIO *asyncio, bool flush, SDL_AsyncIOQueue *queue, void *userdata); + +/** + * Create a task queue for tracking multiple I/O operations. + * + * Async I/O operations are assigned to a queue when started. The queue can be + * checked for completed tasks thereafter. + * + * \returns a new task queue object or NULL if there was an error; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroyAsyncIOQueue + * \sa SDL_GetAsyncIOResult + * \sa SDL_WaitAsyncIOResult + */ +extern SDL_DECLSPEC SDL_AsyncIOQueue * SDLCALL SDL_CreateAsyncIOQueue(void); + +/** + * Destroy a previously-created async I/O task queue. + * + * If there are still tasks pending for this queue, this call will block until + * those tasks are finished. All those tasks will be deallocated. Their + * results will be lost to the app. + * + * Any pending reads from SDL_LoadFileAsync() that are still in this queue + * will have their buffers deallocated by this function, to prevent a memory + * leak. + * + * Once this function is called, the queue is no longer valid and should not + * be used, including by other threads that might access it while destruction + * is blocking on pending tasks. + * + * Do not destroy a queue that still has threads waiting on it through + * SDL_WaitAsyncIOResult(). You can call SDL_SignalAsyncIOQueue() first to + * unblock those threads, and take measures (such as SDL_WaitThread()) to make + * sure they have finished their wait and won't wait on the queue again. + * + * \param queue the task queue to destroy. + * + * \threadsafety It is safe to call this function from any thread, so long as + * no other thread is waiting on the queue with + * SDL_WaitAsyncIOResult. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyAsyncIOQueue(SDL_AsyncIOQueue *queue); + +/** + * Query an async I/O task queue for completed tasks. + * + * If a task assigned to this queue has finished, this will return true and + * fill in `outcome` with the details of the task. If no task in the queue has + * finished, this function will return false. This function does not block. + * + * If a task has completed, this function will free its resources and the task + * pointer will no longer be valid. The task will be removed from the queue. + * + * It is safe for multiple threads to call this function on the same queue at + * once; a completed task will only go to one of the threads. + * + * \param queue the async I/O task queue to query. + * \param outcome details of a finished task will be written here. May not be + * NULL. + * \returns true if a task has completed, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_WaitAsyncIOResult + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetAsyncIOResult(SDL_AsyncIOQueue *queue, SDL_AsyncIOOutcome *outcome); + +/** + * Block until an async I/O task queue has a completed task. + * + * This function puts the calling thread to sleep until there a task assigned + * to the queue that has finished. + * + * If a task assigned to the queue has finished, this will return true and + * fill in `outcome` with the details of the task. If no task in the queue has + * finished, this function will return false. + * + * If a task has completed, this function will free its resources and the task + * pointer will no longer be valid. The task will be removed from the queue. + * + * It is safe for multiple threads to call this function on the same queue at + * once; a completed task will only go to one of the threads. + * + * Note that by the nature of various platforms, more than one waiting thread + * may wake to handle a single task, but only one will obtain it, so + * `timeoutMS` is a _maximum_ wait time, and this function may return false + * sooner. + * + * This function may return false if there was a system error, the OS + * inadvertently awoke multiple threads, or if SDL_SignalAsyncIOQueue() was + * called to wake up all waiting threads without a finished task. + * + * A timeout can be used to specify a maximum wait time, but rather than + * polling, it is possible to have a timeout of -1 to wait forever, and use + * SDL_SignalAsyncIOQueue() to wake up the waiting threads later. + * + * \param queue the async I/O task queue to wait on. + * \param outcome details of a finished task will be written here. May not be + * NULL. + * \param timeoutMS the maximum time to wait, in milliseconds, or -1 to wait + * indefinitely. + * \returns true if task has completed, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SignalAsyncIOQueue + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WaitAsyncIOResult(SDL_AsyncIOQueue *queue, SDL_AsyncIOOutcome *outcome, Sint32 timeoutMS); + +/** + * Wake up any threads that are blocking in SDL_WaitAsyncIOResult(). + * + * This will unblock any threads that are sleeping in a call to + * SDL_WaitAsyncIOResult for the specified queue, and cause them to return + * from that function. + * + * This can be useful when destroying a queue to make sure nothing is touching + * it indefinitely. In this case, once this call completes, the caller should + * take measures to make sure any previously-blocked threads have returned + * from their wait and will not touch the queue again (perhaps by setting a + * flag to tell the threads to terminate and then using SDL_WaitThread() to + * make sure they've done so). + * + * \param queue the async I/O task queue to signal. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_WaitAsyncIOResult + */ +extern SDL_DECLSPEC void SDLCALL SDL_SignalAsyncIOQueue(SDL_AsyncIOQueue *queue); + +/** + * Load all the data from a file path, asynchronously. + * + * This function returns as quickly as possible; it does not wait for the read + * to complete. On a successful return, this work will continue in the + * background. If the work begins, even failure is asynchronous: a failing + * return value from this function only means the work couldn't start at all. + * + * The data is allocated with a zero byte at the end (null terminated) for + * convenience. This extra byte is not included in SDL_AsyncIOOutcome's + * bytes_transferred value. + * + * This function will allocate the buffer to contain the file. It must be + * deallocated by calling SDL_free() on SDL_AsyncIOOutcome's buffer field + * after completion. + * + * An SDL_AsyncIOQueue must be specified. The newly-created task will be added + * to it when it completes its work. + * + * \param file the path to read all available data from. + * \param queue a queue to add the new SDL_AsyncIO to. + * \param userdata an app-defined pointer that will be provided with the task + * results. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LoadFile_IO + */ +extern SDL_DECLSPEC bool SDLCALL SDL_LoadFileAsync(const char *file, SDL_AsyncIOQueue *queue, void *userdata); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_asyncio_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_atomic.h b/thirdparty/sdl/include/SDL3/SDL_atomic.h new file mode 100644 index 00000000000..78b5e0fa5bf --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_atomic.h @@ -0,0 +1,664 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryAtomic + * + * Atomic operations. + * + * IMPORTANT: If you are not an expert in concurrent lockless programming, you + * should not be using any functions in this file. You should be protecting + * your data structures with full mutexes instead. + * + * ***Seriously, here be dragons!*** + * + * You can find out a little more about lockless programming and the subtle + * issues that can arise here: + * https://learn.microsoft.com/en-us/windows/win32/dxtecharts/lockless-programming + * + * There's also lots of good information here: + * + * - https://www.1024cores.net/home/lock-free-algorithms + * - https://preshing.com/ + * + * These operations may or may not actually be implemented using processor + * specific atomic operations. When possible they are implemented as true + * processor specific atomic operations. When that is not possible the are + * implemented using locks that *do* use the available atomic operations. + * + * All of the atomic operations that modify memory are full memory barriers. + */ + +#ifndef SDL_atomic_h_ +#define SDL_atomic_h_ + +#include +#include + +#include + +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * An atomic spinlock. + * + * The atomic locks are efficient spinlocks using CPU instructions, but are + * vulnerable to starvation and can spin forever if a thread holding a lock + * has been terminated. For this reason you should minimize the code executed + * inside an atomic lock and never do expensive things like API or system + * calls while holding them. + * + * They are also vulnerable to starvation if the thread holding the lock is + * lower priority than other threads and doesn't get scheduled. In general you + * should use mutexes instead, since they have better performance and + * contention behavior. + * + * The atomic locks are not safe to lock recursively. + * + * Porting Note: The spin lock functions and type are required and can not be + * emulated because they are used in the atomic emulation code. + */ +typedef int SDL_SpinLock; + +/** + * Try to lock a spin lock by setting it to a non-zero value. + * + * ***Please note that spinlocks are dangerous if you don't know what you're + * doing. Please be careful using any sort of spinlock!*** + * + * \param lock a pointer to a lock variable. + * \returns true if the lock succeeded, false if the lock is already held. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockSpinlock + * \sa SDL_UnlockSpinlock + */ +extern SDL_DECLSPEC bool SDLCALL SDL_TryLockSpinlock(SDL_SpinLock *lock); + +/** + * Lock a spin lock by setting it to a non-zero value. + * + * ***Please note that spinlocks are dangerous if you don't know what you're + * doing. Please be careful using any sort of spinlock!*** + * + * \param lock a pointer to a lock variable. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_TryLockSpinlock + * \sa SDL_UnlockSpinlock + */ +extern SDL_DECLSPEC void SDLCALL SDL_LockSpinlock(SDL_SpinLock *lock); + +/** + * Unlock a spin lock by setting it to 0. + * + * Always returns immediately. + * + * ***Please note that spinlocks are dangerous if you don't know what you're + * doing. Please be careful using any sort of spinlock!*** + * + * \param lock a pointer to a lock variable. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockSpinlock + * \sa SDL_TryLockSpinlock + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnlockSpinlock(SDL_SpinLock *lock); + + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Mark a compiler barrier. + * + * A compiler barrier prevents the compiler from reordering reads and writes + * to globally visible variables across the call. + * + * This macro only prevents the compiler from reordering reads and writes, it + * does not prevent the CPU from reordering reads and writes. However, all of + * the atomic operations that modify memory are full memory barriers. + * + * \threadsafety Obviously this macro is safe to use from any thread at any + * time, but if you find yourself needing this, you are probably + * dealing with some very sensitive code; be careful! + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_CompilerBarrier() DoCompilerSpecificReadWriteBarrier() + +#elif defined(_MSC_VER) && (_MSC_VER > 1200) && !defined(__clang__) +void _ReadWriteBarrier(void); +#pragma intrinsic(_ReadWriteBarrier) +#define SDL_CompilerBarrier() _ReadWriteBarrier() +#elif (defined(__GNUC__) && !defined(SDL_PLATFORM_EMSCRIPTEN)) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5120)) +/* This is correct for all CPUs when using GCC or Solaris Studio 12.1+. */ +#define SDL_CompilerBarrier() __asm__ __volatile__ ("" : : : "memory") +#elif defined(__WATCOMC__) +extern __inline void SDL_CompilerBarrier(void); +#pragma aux SDL_CompilerBarrier = "" parm [] modify exact []; +#else +#define SDL_CompilerBarrier() \ +{ SDL_SpinLock _tmp = 0; SDL_LockSpinlock(&_tmp); SDL_UnlockSpinlock(&_tmp); } +#endif + +/** + * Insert a memory release barrier (function version). + * + * Please refer to SDL_MemoryBarrierRelease for details. This is a function + * version, which might be useful if you need to use this functionality from a + * scripting language, etc. Also, some of the macro versions call this + * function behind the scenes, where more heavy lifting can happen inside of + * SDL. Generally, though, an app written in C/C++/etc should use the macro + * version, as it will be more efficient. + * + * \threadsafety Obviously this function is safe to use from any thread at any + * time, but if you find yourself needing this, you are probably + * dealing with some very sensitive code; be careful! + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_MemoryBarrierRelease + */ +extern SDL_DECLSPEC void SDLCALL SDL_MemoryBarrierReleaseFunction(void); + +/** + * Insert a memory acquire barrier (function version). + * + * Please refer to SDL_MemoryBarrierRelease for details. This is a function + * version, which might be useful if you need to use this functionality from a + * scripting language, etc. Also, some of the macro versions call this + * function behind the scenes, where more heavy lifting can happen inside of + * SDL. Generally, though, an app written in C/C++/etc should use the macro + * version, as it will be more efficient. + * + * \threadsafety Obviously this function is safe to use from any thread at any + * time, but if you find yourself needing this, you are probably + * dealing with some very sensitive code; be careful! + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_MemoryBarrierAcquire + */ +extern SDL_DECLSPEC void SDLCALL SDL_MemoryBarrierAcquireFunction(void); + + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Insert a memory release barrier (macro version). + * + * Memory barriers are designed to prevent reads and writes from being + * reordered by the compiler and being seen out of order on multi-core CPUs. + * + * A typical pattern would be for thread A to write some data and a flag, and + * for thread B to read the flag and get the data. In this case you would + * insert a release barrier between writing the data and the flag, + * guaranteeing that the data write completes no later than the flag is + * written, and you would insert an acquire barrier between reading the flag + * and reading the data, to ensure that all the reads associated with the flag + * have completed. + * + * In this pattern you should always see a release barrier paired with an + * acquire barrier and you should gate the data reads/writes with a single + * flag variable. + * + * For more information on these semantics, take a look at the blog post: + * http://preshing.com/20120913/acquire-and-release-semantics + * + * This is the macro version of this functionality; if possible, SDL will use + * compiler intrinsics or inline assembly, but some platforms might need to + * call the function version of this, SDL_MemoryBarrierReleaseFunction to do + * the heavy lifting. Apps that can use the macro should favor it over the + * function. + * + * \threadsafety Obviously this macro is safe to use from any thread at any + * time, but if you find yourself needing this, you are probably + * dealing with some very sensitive code; be careful! + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_MemoryBarrierAcquire + * \sa SDL_MemoryBarrierReleaseFunction + */ +#define SDL_MemoryBarrierRelease() SDL_MemoryBarrierReleaseFunction() + +/** + * Insert a memory acquire barrier (macro version). + * + * Please see SDL_MemoryBarrierRelease for the details on what memory barriers + * are and when to use them. + * + * This is the macro version of this functionality; if possible, SDL will use + * compiler intrinsics or inline assembly, but some platforms might need to + * call the function version of this, SDL_MemoryBarrierAcquireFunction, to do + * the heavy lifting. Apps that can use the macro should favor it over the + * function. + * + * \threadsafety Obviously this macro is safe to use from any thread at any + * time, but if you find yourself needing this, you are probably + * dealing with some very sensitive code; be careful! + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_MemoryBarrierRelease + * \sa SDL_MemoryBarrierAcquireFunction + */ +#define SDL_MemoryBarrierAcquire() SDL_MemoryBarrierAcquireFunction() + +#elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__)) +#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("lwsync" : : : "memory") +#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("lwsync" : : : "memory") +#elif defined(__GNUC__) && defined(__aarch64__) +#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("dmb ish" : : : "memory") +#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("dmb ish" : : : "memory") +#elif defined(__GNUC__) && defined(__arm__) +#if 0 /* defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_ANDROID) */ +/* Information from: + https://chromium.googlesource.com/chromium/chromium/+/trunk/base/atomicops_internals_arm_gcc.h#19 + + The Linux kernel provides a helper function which provides the right code for a memory barrier, + hard-coded at address 0xffff0fa0 +*/ +typedef void (*SDL_KernelMemoryBarrierFunc)(); +#define SDL_MemoryBarrierRelease() ((SDL_KernelMemoryBarrierFunc)0xffff0fa0)() +#define SDL_MemoryBarrierAcquire() ((SDL_KernelMemoryBarrierFunc)0xffff0fa0)() +#else +#if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) || defined(__ARM_ARCH_8A__) +#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("dmb ish" : : : "memory") +#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("dmb ish" : : : "memory") +#elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) +#ifdef __thumb__ +/* The mcr instruction isn't available in thumb mode, use real functions */ +#define SDL_MEMORY_BARRIER_USES_FUNCTION +#define SDL_MemoryBarrierRelease() SDL_MemoryBarrierReleaseFunction() +#define SDL_MemoryBarrierAcquire() SDL_MemoryBarrierAcquireFunction() +#else +#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory") +#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory") +#endif /* __thumb__ */ +#else +#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("" : : : "memory") +#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("" : : : "memory") +#endif /* SDL_PLATFORM_LINUX || SDL_PLATFORM_ANDROID */ +#endif /* __GNUC__ && __arm__ */ +#else +#if (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5120)) +/* This is correct for all CPUs on Solaris when using Solaris Studio 12.1+. */ +#include +#define SDL_MemoryBarrierRelease() __machine_rel_barrier() +#define SDL_MemoryBarrierAcquire() __machine_acq_barrier() +#else +/* This is correct for the x86 and x64 CPUs, and we'll expand this over time. */ +#define SDL_MemoryBarrierRelease() SDL_CompilerBarrier() +#define SDL_MemoryBarrierAcquire() SDL_CompilerBarrier() +#endif +#endif + +/* "REP NOP" is PAUSE, coded for tools that don't know it by that name. */ +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A macro to insert a CPU-specific "pause" instruction into the program. + * + * This can be useful in busy-wait loops, as it serves as a hint to the CPU as + * to the program's intent; some CPUs can use this to do more efficient + * processing. On some platforms, this doesn't do anything, so using this + * macro might just be a harmless no-op. + * + * Note that if you are busy-waiting, there are often more-efficient + * approaches with other synchronization primitives: mutexes, semaphores, + * condition variables, etc. + * + * \threadsafety This macro is safe to use from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_CPUPauseInstruction() DoACPUPauseInACompilerAndArchitectureSpecificWay + +#elif (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) + #define SDL_CPUPauseInstruction() __asm__ __volatile__("pause\n") /* Some assemblers can't do REP NOP, so go with PAUSE. */ +#elif (defined(__arm__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7) || defined(__aarch64__) + #define SDL_CPUPauseInstruction() __asm__ __volatile__("yield" ::: "memory") +#elif (defined(__powerpc__) || defined(__powerpc64__)) + #define SDL_CPUPauseInstruction() __asm__ __volatile__("or 27,27,27"); +#elif (defined(__riscv) && __riscv_xlen == 64) + #define SDL_CPUPauseInstruction() __asm__ __volatile__(".insn i 0x0F, 0, x0, x0, 0x010"); +#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) + #define SDL_CPUPauseInstruction() _mm_pause() /* this is actually "rep nop" and not a SIMD instruction. No inline asm in MSVC x86-64! */ +#elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) + #define SDL_CPUPauseInstruction() __yield() +#elif defined(__WATCOMC__) && defined(__386__) + extern __inline void SDL_CPUPauseInstruction(void); + #pragma aux SDL_CPUPauseInstruction = ".686p" ".xmm2" "pause" +#else + #define SDL_CPUPauseInstruction() +#endif + + +/** + * A type representing an atomic integer value. + * + * This can be used to manage a value that is synchronized across multiple + * CPUs without a race condition; when an app sets a value with + * SDL_SetAtomicInt all other threads, regardless of the CPU it is running on, + * will see that value when retrieved with SDL_GetAtomicInt, regardless of CPU + * caches, etc. + * + * This is also useful for atomic compare-and-swap operations: a thread can + * change the value as long as its current value matches expectations. When + * done in a loop, one can guarantee data consistency across threads without a + * lock (but the usual warnings apply: if you don't know what you're doing, or + * you don't do it carefully, you can confidently cause any number of + * disasters with this, so in most cases, you _should_ use a mutex instead of + * this!). + * + * This is a struct so people don't accidentally use numeric operations on it + * directly. You have to use SDL atomic functions. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_CompareAndSwapAtomicInt + * \sa SDL_GetAtomicInt + * \sa SDL_SetAtomicInt + * \sa SDL_AddAtomicInt + */ +typedef struct SDL_AtomicInt { int value; } SDL_AtomicInt; + +/** + * Set an atomic variable to a new value if it is currently an old value. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_AtomicInt variable to be modified. + * \param oldval the old value. + * \param newval the new value. + * \returns true if the atomic variable was set, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAtomicInt + * \sa SDL_SetAtomicInt + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CompareAndSwapAtomicInt(SDL_AtomicInt *a, int oldval, int newval); + +/** + * Set an atomic variable to a value. + * + * This function also acts as a full memory barrier. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_AtomicInt variable to be modified. + * \param v the desired value. + * \returns the previous value of the atomic variable. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAtomicInt + */ +extern SDL_DECLSPEC int SDLCALL SDL_SetAtomicInt(SDL_AtomicInt *a, int v); + +/** + * Get the value of an atomic variable. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_AtomicInt variable. + * \returns the current value of an atomic variable. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAtomicInt + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetAtomicInt(SDL_AtomicInt *a); + +/** + * Add to an atomic variable. + * + * This function also acts as a full memory barrier. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_AtomicInt variable to be modified. + * \param v the desired value to add. + * \returns the previous value of the atomic variable. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AtomicDecRef + * \sa SDL_AtomicIncRef + */ +extern SDL_DECLSPEC int SDLCALL SDL_AddAtomicInt(SDL_AtomicInt *a, int v); + +#ifndef SDL_AtomicIncRef + +/** + * Increment an atomic variable used as a reference count. + * + * ***Note: If you don't know what this macro is for, you shouldn't use it!*** + * + * \param a a pointer to an SDL_AtomicInt to increment. + * \returns the previous value of the atomic variable. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_AtomicDecRef + */ +#define SDL_AtomicIncRef(a) SDL_AddAtomicInt(a, 1) +#endif + +#ifndef SDL_AtomicDecRef + +/** + * Decrement an atomic variable used as a reference count. + * + * ***Note: If you don't know what this macro is for, you shouldn't use it!*** + * + * \param a a pointer to an SDL_AtomicInt to decrement. + * \returns true if the variable reached zero after decrementing, false + * otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_AtomicIncRef + */ +#define SDL_AtomicDecRef(a) (SDL_AddAtomicInt(a, -1) == 1) +#endif + +/** + * A type representing an atomic unsigned 32-bit value. + * + * This can be used to manage a value that is synchronized across multiple + * CPUs without a race condition; when an app sets a value with + * SDL_SetAtomicU32 all other threads, regardless of the CPU it is running on, + * will see that value when retrieved with SDL_GetAtomicU32, regardless of CPU + * caches, etc. + * + * This is also useful for atomic compare-and-swap operations: a thread can + * change the value as long as its current value matches expectations. When + * done in a loop, one can guarantee data consistency across threads without a + * lock (but the usual warnings apply: if you don't know what you're doing, or + * you don't do it carefully, you can confidently cause any number of + * disasters with this, so in most cases, you _should_ use a mutex instead of + * this!). + * + * This is a struct so people don't accidentally use numeric operations on it + * directly. You have to use SDL atomic functions. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_CompareAndSwapAtomicU32 + * \sa SDL_GetAtomicU32 + * \sa SDL_SetAtomicU32 + */ +typedef struct SDL_AtomicU32 { Uint32 value; } SDL_AtomicU32; + +/** + * Set an atomic variable to a new value if it is currently an old value. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_AtomicU32 variable to be modified. + * \param oldval the old value. + * \param newval the new value. + * \returns true if the atomic variable was set, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAtomicU32 + * \sa SDL_SetAtomicU32 + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CompareAndSwapAtomicU32(SDL_AtomicU32 *a, Uint32 oldval, Uint32 newval); + +/** + * Set an atomic variable to a value. + * + * This function also acts as a full memory barrier. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_AtomicU32 variable to be modified. + * \param v the desired value. + * \returns the previous value of the atomic variable. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAtomicU32 + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_SetAtomicU32(SDL_AtomicU32 *a, Uint32 v); + +/** + * Get the value of an atomic variable. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_AtomicU32 variable. + * \returns the current value of an atomic variable. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAtomicU32 + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_GetAtomicU32(SDL_AtomicU32 *a); + +/** + * Set a pointer to a new value if it is currently an old value. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to a pointer. + * \param oldval the old pointer value. + * \param newval the new pointer value. + * \returns true if the pointer was set, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CompareAndSwapAtomicInt + * \sa SDL_GetAtomicPointer + * \sa SDL_SetAtomicPointer + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CompareAndSwapAtomicPointer(void **a, void *oldval, void *newval); + +/** + * Set a pointer to a value atomically. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to a pointer. + * \param v the desired pointer value. + * \returns the previous value of the pointer. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CompareAndSwapAtomicPointer + * \sa SDL_GetAtomicPointer + */ +extern SDL_DECLSPEC void * SDLCALL SDL_SetAtomicPointer(void **a, void *v); + +/** + * Get the value of a pointer atomically. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to a pointer. + * \returns the current value of a pointer. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CompareAndSwapAtomicPointer + * \sa SDL_SetAtomicPointer + */ +extern SDL_DECLSPEC void * SDLCALL SDL_GetAtomicPointer(void **a); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif + +#include + +#endif /* SDL_atomic_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_audio.h b/thirdparty/sdl/include/SDL3/SDL_audio.h new file mode 100644 index 00000000000..c6acf885f42 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_audio.h @@ -0,0 +1,2200 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryAudio + * + * Audio functionality for the SDL library. + * + * All audio in SDL3 revolves around SDL_AudioStream. Whether you want to play + * or record audio, convert it, stream it, buffer it, or mix it, you're going + * to be passing it through an audio stream. + * + * Audio streams are quite flexible; they can accept any amount of data at a + * time, in any supported format, and output it as needed in any other format, + * even if the data format changes on either side halfway through. + * + * An app opens an audio device and binds any number of audio streams to it, + * feeding more data to the streams as available. When the device needs more + * data, it will pull it from all bound streams and mix them together for + * playback. + * + * Audio streams can also use an app-provided callback to supply data + * on-demand, which maps pretty closely to the SDL2 audio model. + * + * SDL also provides a simple .WAV loader in SDL_LoadWAV (and SDL_LoadWAV_IO + * if you aren't reading from a file) as a basic means to load sound data into + * your program. + * + * ## Logical audio devices + * + * In SDL3, opening a physical device (like a SoundBlaster 16 Pro) gives you a + * logical device ID that you can bind audio streams to. In almost all cases, + * logical devices can be used anywhere in the API that a physical device is + * normally used. However, since each device opening generates a new logical + * device, different parts of the program (say, a VoIP library, or + * text-to-speech framework, or maybe some other sort of mixer on top of SDL) + * can have their own device opens that do not interfere with each other; each + * logical device will mix its separate audio down to a single buffer, fed to + * the physical device, behind the scenes. As many logical devices as you like + * can come and go; SDL will only have to open the physical device at the OS + * level once, and will manage all the logical devices on top of it + * internally. + * + * One other benefit of logical devices: if you don't open a specific physical + * device, instead opting for the default, SDL can automatically migrate those + * logical devices to different hardware as circumstances change: a user + * plugged in headphones? The system default changed? SDL can transparently + * migrate the logical devices to the correct physical device seamlessly and + * keep playing; the app doesn't even have to know it happened if it doesn't + * want to. + * + * ## Simplified audio + * + * As a simplified model for when a single source of audio is all that's + * needed, an app can use SDL_OpenAudioDeviceStream, which is a single + * function to open an audio device, create an audio stream, bind that stream + * to the newly-opened device, and (optionally) provide a callback for + * obtaining audio data. When using this function, the primary interface is + * the SDL_AudioStream and the device handle is mostly hidden away; destroying + * a stream created through this function will also close the device, stream + * bindings cannot be changed, etc. One other quirk of this is that the device + * is started in a _paused_ state and must be explicitly resumed; this is + * partially to offer a clean migration for SDL2 apps and partially because + * the app might have to do more setup before playback begins; in the + * non-simplified form, nothing will play until a stream is bound to a device, + * so they start _unpaused_. + * + * ## Channel layouts + * + * Audio data passing through SDL is uncompressed PCM data, interleaved. One + * can provide their own decompression through an MP3, etc, decoder, but SDL + * does not provide this directly. Each interleaved channel of data is meant + * to be in a specific order. + * + * Abbreviations: + * + * - FRONT = single mono speaker + * - FL = front left speaker + * - FR = front right speaker + * - FC = front center speaker + * - BL = back left speaker + * - BR = back right speaker + * - SR = surround right speaker + * - SL = surround left speaker + * - BC = back center speaker + * - LFE = low-frequency speaker + * + * These are listed in the order they are laid out in memory, so "FL, FR" + * means "the front left speaker is laid out in memory first, then the front + * right, then it repeats for the next audio frame". + * + * - 1 channel (mono) layout: FRONT + * - 2 channels (stereo) layout: FL, FR + * - 3 channels (2.1) layout: FL, FR, LFE + * - 4 channels (quad) layout: FL, FR, BL, BR + * - 5 channels (4.1) layout: FL, FR, LFE, BL, BR + * - 6 channels (5.1) layout: FL, FR, FC, LFE, BL, BR (last two can also be + * SL, SR) + * - 7 channels (6.1) layout: FL, FR, FC, LFE, BC, SL, SR + * - 8 channels (7.1) layout: FL, FR, FC, LFE, BL, BR, SL, SR + * + * This is the same order as DirectSound expects, but applied to all + * platforms; SDL will swizzle the channels as necessary if a platform expects + * something different. + * + * SDL_AudioStream can also be provided channel maps to change this ordering + * to whatever is necessary, in other audio processing scenarios. + */ + +#ifndef SDL_audio_h_ +#define SDL_audio_h_ + +#include +#include +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Mask of bits in an SDL_AudioFormat that contains the format bit size. + * + * Generally one should use SDL_AUDIO_BITSIZE instead of this macro directly. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_MASK_BITSIZE (0xFFu) + +/** + * Mask of bits in an SDL_AudioFormat that contain the floating point flag. + * + * Generally one should use SDL_AUDIO_ISFLOAT instead of this macro directly. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_MASK_FLOAT (1u<<8) + +/** + * Mask of bits in an SDL_AudioFormat that contain the bigendian flag. + * + * Generally one should use SDL_AUDIO_ISBIGENDIAN or SDL_AUDIO_ISLITTLEENDIAN + * instead of this macro directly. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_MASK_BIG_ENDIAN (1u<<12) + +/** + * Mask of bits in an SDL_AudioFormat that contain the signed data flag. + * + * Generally one should use SDL_AUDIO_ISSIGNED instead of this macro directly. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_MASK_SIGNED (1u<<15) + +/** + * Define an SDL_AudioFormat value. + * + * SDL does not support custom audio formats, so this macro is not of much use + * externally, but it can be illustrative as to what the various bits of an + * SDL_AudioFormat mean. + * + * For example, SDL_AUDIO_S32LE looks like this: + * + * ```c + * SDL_DEFINE_AUDIO_FORMAT(1, 0, 0, 32) + * ``` + * + * \param signed 1 for signed data, 0 for unsigned data. + * \param bigendian 1 for bigendian data, 0 for littleendian data. + * \param flt 1 for floating point data, 0 for integer data. + * \param size number of bits per sample. + * \returns a format value in the style of SDL_AudioFormat. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_DEFINE_AUDIO_FORMAT(signed, bigendian, flt, size) \ + (((Uint16)(signed) << 15) | ((Uint16)(bigendian) << 12) | ((Uint16)(flt) << 8) | ((size) & SDL_AUDIO_MASK_BITSIZE)) + +/** + * Audio format. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_AUDIO_BITSIZE + * \sa SDL_AUDIO_BYTESIZE + * \sa SDL_AUDIO_ISINT + * \sa SDL_AUDIO_ISFLOAT + * \sa SDL_AUDIO_ISBIGENDIAN + * \sa SDL_AUDIO_ISLITTLEENDIAN + * \sa SDL_AUDIO_ISSIGNED + * \sa SDL_AUDIO_ISUNSIGNED + */ +typedef enum SDL_AudioFormat +{ + SDL_AUDIO_UNKNOWN = 0x0000u, /**< Unspecified audio format */ + SDL_AUDIO_U8 = 0x0008u, /**< Unsigned 8-bit samples */ + /* SDL_DEFINE_AUDIO_FORMAT(0, 0, 0, 8), */ + SDL_AUDIO_S8 = 0x8008u, /**< Signed 8-bit samples */ + /* SDL_DEFINE_AUDIO_FORMAT(1, 0, 0, 8), */ + SDL_AUDIO_S16LE = 0x8010u, /**< Signed 16-bit samples */ + /* SDL_DEFINE_AUDIO_FORMAT(1, 0, 0, 16), */ + SDL_AUDIO_S16BE = 0x9010u, /**< As above, but big-endian byte order */ + /* SDL_DEFINE_AUDIO_FORMAT(1, 1, 0, 16), */ + SDL_AUDIO_S32LE = 0x8020u, /**< 32-bit integer samples */ + /* SDL_DEFINE_AUDIO_FORMAT(1, 0, 0, 32), */ + SDL_AUDIO_S32BE = 0x9020u, /**< As above, but big-endian byte order */ + /* SDL_DEFINE_AUDIO_FORMAT(1, 1, 0, 32), */ + SDL_AUDIO_F32LE = 0x8120u, /**< 32-bit floating point samples */ + /* SDL_DEFINE_AUDIO_FORMAT(1, 0, 1, 32), */ + SDL_AUDIO_F32BE = 0x9120u, /**< As above, but big-endian byte order */ + /* SDL_DEFINE_AUDIO_FORMAT(1, 1, 1, 32), */ + + /* These represent the current system's byteorder. */ + #if SDL_BYTEORDER == SDL_LIL_ENDIAN + SDL_AUDIO_S16 = SDL_AUDIO_S16LE, + SDL_AUDIO_S32 = SDL_AUDIO_S32LE, + SDL_AUDIO_F32 = SDL_AUDIO_F32LE + #else + SDL_AUDIO_S16 = SDL_AUDIO_S16BE, + SDL_AUDIO_S32 = SDL_AUDIO_S32BE, + SDL_AUDIO_F32 = SDL_AUDIO_F32BE + #endif +} SDL_AudioFormat; + + +/** + * Retrieve the size, in bits, from an SDL_AudioFormat. + * + * For example, `SDL_AUDIO_BITSIZE(SDL_AUDIO_S16)` returns 16. + * + * \param x an SDL_AudioFormat value. + * \returns data size in bits. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_BITSIZE(x) ((x) & SDL_AUDIO_MASK_BITSIZE) + +/** + * Retrieve the size, in bytes, from an SDL_AudioFormat. + * + * For example, `SDL_AUDIO_BYTESIZE(SDL_AUDIO_S16)` returns 2. + * + * \param x an SDL_AudioFormat value. + * \returns data size in bytes. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_BYTESIZE(x) (SDL_AUDIO_BITSIZE(x) / 8) + +/** + * Determine if an SDL_AudioFormat represents floating point data. + * + * For example, `SDL_AUDIO_ISFLOAT(SDL_AUDIO_S16)` returns 0. + * + * \param x an SDL_AudioFormat value. + * \returns non-zero if format is floating point, zero otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_ISFLOAT(x) ((x) & SDL_AUDIO_MASK_FLOAT) + +/** + * Determine if an SDL_AudioFormat represents bigendian data. + * + * For example, `SDL_AUDIO_ISBIGENDIAN(SDL_AUDIO_S16LE)` returns 0. + * + * \param x an SDL_AudioFormat value. + * \returns non-zero if format is bigendian, zero otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_ISBIGENDIAN(x) ((x) & SDL_AUDIO_MASK_BIG_ENDIAN) + +/** + * Determine if an SDL_AudioFormat represents littleendian data. + * + * For example, `SDL_AUDIO_ISLITTLEENDIAN(SDL_AUDIO_S16BE)` returns 0. + * + * \param x an SDL_AudioFormat value. + * \returns non-zero if format is littleendian, zero otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_ISLITTLEENDIAN(x) (!SDL_AUDIO_ISBIGENDIAN(x)) + +/** + * Determine if an SDL_AudioFormat represents signed data. + * + * For example, `SDL_AUDIO_ISSIGNED(SDL_AUDIO_U8)` returns 0. + * + * \param x an SDL_AudioFormat value. + * \returns non-zero if format is signed, zero otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_ISSIGNED(x) ((x) & SDL_AUDIO_MASK_SIGNED) + +/** + * Determine if an SDL_AudioFormat represents integer data. + * + * For example, `SDL_AUDIO_ISINT(SDL_AUDIO_F32)` returns 0. + * + * \param x an SDL_AudioFormat value. + * \returns non-zero if format is integer, zero otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_ISINT(x) (!SDL_AUDIO_ISFLOAT(x)) + +/** + * Determine if an SDL_AudioFormat represents unsigned data. + * + * For example, `SDL_AUDIO_ISUNSIGNED(SDL_AUDIO_S16)` returns 0. + * + * \param x an SDL_AudioFormat value. + * \returns non-zero if format is unsigned, zero otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_ISUNSIGNED(x) (!SDL_AUDIO_ISSIGNED(x)) + + +/** + * SDL Audio Device instance IDs. + * + * Zero is used to signify an invalid/null device. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_AudioDeviceID; + +/** + * A value used to request a default playback audio device. + * + * Several functions that require an SDL_AudioDeviceID will accept this value + * to signify the app just wants the system to choose a default device instead + * of the app providing a specific one. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK ((SDL_AudioDeviceID) 0xFFFFFFFFu) + +/** + * A value used to request a default recording audio device. + * + * Several functions that require an SDL_AudioDeviceID will accept this value + * to signify the app just wants the system to choose a default device instead + * of the app providing a specific one. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_DEVICE_DEFAULT_RECORDING ((SDL_AudioDeviceID) 0xFFFFFFFEu) + +/** + * Format specifier for audio data. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_AudioFormat + */ +typedef struct SDL_AudioSpec +{ + SDL_AudioFormat format; /**< Audio data format */ + int channels; /**< Number of channels: 1 mono, 2 stereo, etc */ + int freq; /**< sample rate: sample frames per second */ +} SDL_AudioSpec; + +/** + * Calculate the size of each audio frame (in bytes) from an SDL_AudioSpec. + * + * This reports on the size of an audio sample frame: stereo Sint16 data (2 + * channels of 2 bytes each) would be 4 bytes per frame, for example. + * + * \param x an SDL_AudioSpec to query. + * \returns the number of bytes used per sample frame. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_AUDIO_FRAMESIZE(x) (SDL_AUDIO_BYTESIZE((x).format) * (x).channels) + +/** + * The opaque handle that represents an audio stream. + * + * SDL_AudioStream is an audio conversion interface. + * + * - It can handle resampling data in chunks without generating artifacts, + * when it doesn't have the complete buffer available. + * - It can handle incoming data in any variable size. + * - It can handle input/output format changes on the fly. + * - It can remap audio channels between inputs and outputs. + * - You push data as you have it, and pull it when you need it + * - It can also function as a basic audio data queue even if you just have + * sound that needs to pass from one place to another. + * - You can hook callbacks up to them when more data is added or requested, + * to manage data on-the-fly. + * + * Audio streams are the core of the SDL3 audio interface. You create one or + * more of them, bind them to an opened audio device, and feed data to them + * (or for recording, consume data from them). + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_CreateAudioStream + */ +typedef struct SDL_AudioStream SDL_AudioStream; + + +/* Function prototypes */ + +/** + * Use this function to get the number of built-in audio drivers. + * + * This function returns a hardcoded number. This never returns a negative + * value; if there are no drivers compiled into this build of SDL, this + * function returns zero. The presence of a driver in this list does not mean + * it will function, it just means SDL is capable of interacting with that + * interface. For example, a build of SDL might have esound support, but if + * there's no esound server available, SDL's esound driver would fail if used. + * + * By default, SDL tries all drivers, in its preferred order, until one is + * found to be usable. + * + * \returns the number of built-in audio drivers. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAudioDriver + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumAudioDrivers(void); + +/** + * Use this function to get the name of a built in audio driver. + * + * The list of audio drivers is given in the order that they are normally + * initialized by default; the drivers that seem more reasonable to choose + * first (as far as the SDL developers believe) are earlier in the list. + * + * The names of drivers are all simple, low-ASCII identifiers, like "alsa", + * "coreaudio" or "wasapi". These never have Unicode characters, and are not + * meant to be proper names. + * + * \param index the index of the audio driver; the value ranges from 0 to + * SDL_GetNumAudioDrivers() - 1. + * \returns the name of the audio driver at the requested index, or NULL if an + * invalid index was specified. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumAudioDrivers + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetAudioDriver(int index); + +/** + * Get the name of the current audio driver. + * + * The names of drivers are all simple, low-ASCII identifiers, like "alsa", + * "coreaudio" or "wasapi". These never have Unicode characters, and are not + * meant to be proper names. + * + * \returns the name of the current audio driver or NULL if no driver has been + * initialized. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetCurrentAudioDriver(void); + +/** + * Get a list of currently-connected audio playback devices. + * + * This returns of list of available devices that play sound, perhaps to + * speakers or headphones ("playback" devices). If you want devices that + * record audio, like a microphone ("recording" devices), use + * SDL_GetAudioRecordingDevices() instead. + * + * This only returns a list of physical devices; it will not have any device + * IDs returned by SDL_OpenAudioDevice(). + * + * If this function returns NULL, to signify an error, `*count` will be set to + * zero. + * + * \param count a pointer filled in with the number of devices returned, may + * be NULL. + * \returns a 0 terminated array of device instance IDs or NULL on error; call + * SDL_GetError() for more information. This should be freed with + * SDL_free() when it is no longer needed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenAudioDevice + * \sa SDL_GetAudioRecordingDevices + */ +extern SDL_DECLSPEC SDL_AudioDeviceID * SDLCALL SDL_GetAudioPlaybackDevices(int *count); + +/** + * Get a list of currently-connected audio recording devices. + * + * This returns of list of available devices that record audio, like a + * microphone ("recording" devices). If you want devices that play sound, + * perhaps to speakers or headphones ("playback" devices), use + * SDL_GetAudioPlaybackDevices() instead. + * + * This only returns a list of physical devices; it will not have any device + * IDs returned by SDL_OpenAudioDevice(). + * + * If this function returns NULL, to signify an error, `*count` will be set to + * zero. + * + * \param count a pointer filled in with the number of devices returned, may + * be NULL. + * \returns a 0 terminated array of device instance IDs, or NULL on failure; + * call SDL_GetError() for more information. This should be freed + * with SDL_free() when it is no longer needed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenAudioDevice + * \sa SDL_GetAudioPlaybackDevices + */ +extern SDL_DECLSPEC SDL_AudioDeviceID * SDLCALL SDL_GetAudioRecordingDevices(int *count); + +/** + * Get the human-readable name of a specific audio device. + * + * \param devid the instance ID of the device to query. + * \returns the name of the audio device, or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAudioPlaybackDevices + * \sa SDL_GetAudioRecordingDevices + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetAudioDeviceName(SDL_AudioDeviceID devid); + +/** + * Get the current audio format of a specific audio device. + * + * For an opened device, this will report the format the device is currently + * using. If the device isn't yet opened, this will report the device's + * preferred format (or a reasonable default if this can't be determined). + * + * You may also specify SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK or + * SDL_AUDIO_DEVICE_DEFAULT_RECORDING here, which is useful for getting a + * reasonable recommendation before opening the system-recommended default + * device. + * + * You can also use this to request the current device buffer size. This is + * specified in sample frames and represents the amount of data SDL will feed + * to the physical hardware in each chunk. This can be converted to + * milliseconds of audio with the following equation: + * + * `ms = (int) ((((Sint64) frames) * 1000) / spec.freq);` + * + * Buffer size is only important if you need low-level control over the audio + * playback timing. Most apps do not need this. + * + * \param devid the instance ID of the device to query. + * \param spec on return, will be filled with device details. + * \param sample_frames pointer to store device buffer size, in sample frames. + * Can be NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetAudioDeviceFormat(SDL_AudioDeviceID devid, SDL_AudioSpec *spec, int *sample_frames); + +/** + * Get the current channel map of an audio device. + * + * Channel maps are optional; most things do not need them, instead passing + * data in the [order that SDL expects](CategoryAudio#channel-layouts). + * + * Audio devices usually have no remapping applied. This is represented by + * returning NULL, and does not signify an error. + * + * \param devid the instance ID of the device to query. + * \param count On output, set to number of channels in the map. Can be NULL. + * \returns an array of the current channel mapping, with as many elements as + * the current output spec's channels, or NULL if default. This + * should be freed with SDL_free() when it is no longer needed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamInputChannelMap + */ +extern SDL_DECLSPEC int * SDLCALL SDL_GetAudioDeviceChannelMap(SDL_AudioDeviceID devid, int *count); + +/** + * Open a specific audio device. + * + * You can open both playback and recording devices through this function. + * Playback devices will take data from bound audio streams, mix it, and send + * it to the hardware. Recording devices will feed any bound audio streams + * with a copy of any incoming data. + * + * An opened audio device starts out with no audio streams bound. To start + * audio playing, bind a stream and supply audio data to it. Unlike SDL2, + * there is no audio callback; you only bind audio streams and make sure they + * have data flowing into them (however, you can simulate SDL2's semantics + * fairly closely by using SDL_OpenAudioDeviceStream instead of this + * function). + * + * If you don't care about opening a specific device, pass a `devid` of either + * `SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK` or + * `SDL_AUDIO_DEVICE_DEFAULT_RECORDING`. In this case, SDL will try to pick + * the most reasonable default, and may also switch between physical devices + * seamlessly later, if the most reasonable default changes during the + * lifetime of this opened device (user changed the default in the OS's system + * preferences, the default got unplugged so the system jumped to a new + * default, the user plugged in headphones on a mobile device, etc). Unless + * you have a good reason to choose a specific device, this is probably what + * you want. + * + * You may request a specific format for the audio device, but there is no + * promise the device will honor that request for several reasons. As such, + * it's only meant to be a hint as to what data your app will provide. Audio + * streams will accept data in whatever format you specify and manage + * conversion for you as appropriate. SDL_GetAudioDeviceFormat can tell you + * the preferred format for the device before opening and the actual format + * the device is using after opening. + * + * It's legal to open the same device ID more than once; each successful open + * will generate a new logical SDL_AudioDeviceID that is managed separately + * from others on the same physical device. This allows libraries to open a + * device separately from the main app and bind its own streams without + * conflicting. + * + * It is also legal to open a device ID returned by a previous call to this + * function; doing so just creates another logical device on the same physical + * device. This may be useful for making logical groupings of audio streams. + * + * This function returns the opened device ID on success. This is a new, + * unique SDL_AudioDeviceID that represents a logical device. + * + * Some backends might offer arbitrary devices (for example, a networked audio + * protocol that can connect to an arbitrary server). For these, as a change + * from SDL2, you should open a default device ID and use an SDL hint to + * specify the target if you care, or otherwise let the backend figure out a + * reasonable default. Most backends don't offer anything like this, and often + * this would be an end user setting an environment variable for their custom + * need, and not something an application should specifically manage. + * + * When done with an audio device, possibly at the end of the app's life, one + * should call SDL_CloseAudioDevice() on the returned device id. + * + * \param devid the device instance id to open, or + * SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK or + * SDL_AUDIO_DEVICE_DEFAULT_RECORDING for the most reasonable + * default device. + * \param spec the requested device configuration. Can be NULL to use + * reasonable defaults. + * \returns the device ID on success or 0 on failure; call SDL_GetError() for + * more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseAudioDevice + * \sa SDL_GetAudioDeviceFormat + */ +extern SDL_DECLSPEC SDL_AudioDeviceID SDLCALL SDL_OpenAudioDevice(SDL_AudioDeviceID devid, const SDL_AudioSpec *spec); + +/** + * Determine if an audio device is physical (instead of logical). + * + * An SDL_AudioDeviceID that represents physical hardware is a physical + * device; there is one for each piece of hardware that SDL can see. Logical + * devices are created by calling SDL_OpenAudioDevice or + * SDL_OpenAudioDeviceStream, and while each is associated with a physical + * device, there can be any number of logical devices on one physical device. + * + * For the most part, logical and physical IDs are interchangeable--if you try + * to open a logical device, SDL understands to assign that effort to the + * underlying physical device, etc. However, it might be useful to know if an + * arbitrary device ID is physical or logical. This function reports which. + * + * This function may return either true or false for invalid device IDs. + * + * \param devid the device ID to query. + * \returns true if devid is a physical device, false if it is logical. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsAudioDevicePhysical(SDL_AudioDeviceID devid); + +/** + * Determine if an audio device is a playback device (instead of recording). + * + * This function may return either true or false for invalid device IDs. + * + * \param devid the device ID to query. + * \returns true if devid is a playback device, false if it is recording. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsAudioDevicePlayback(SDL_AudioDeviceID devid); + +/** + * Use this function to pause audio playback on a specified device. + * + * This function pauses audio processing for a given device. Any bound audio + * streams will not progress, and no audio will be generated. Pausing one + * device does not prevent other unpaused devices from running. + * + * Unlike in SDL2, audio devices start in an _unpaused_ state, since an app + * has to bind a stream before any audio will flow. Pausing a paused device is + * a legal no-op. + * + * Pausing a device can be useful to halt all audio without unbinding all the + * audio streams. This might be useful while a game is paused, or a level is + * loading, etc. + * + * Physical devices can not be paused or unpaused, only logical devices + * created through SDL_OpenAudioDevice() can be. + * + * \param devid a device opened by SDL_OpenAudioDevice(). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ResumeAudioDevice + * \sa SDL_AudioDevicePaused + */ +extern SDL_DECLSPEC bool SDLCALL SDL_PauseAudioDevice(SDL_AudioDeviceID devid); + +/** + * Use this function to unpause audio playback on a specified device. + * + * This function unpauses audio processing for a given device that has + * previously been paused with SDL_PauseAudioDevice(). Once unpaused, any + * bound audio streams will begin to progress again, and audio can be + * generated. + * + * Unlike in SDL2, audio devices start in an _unpaused_ state, since an app + * has to bind a stream before any audio will flow. Unpausing an unpaused + * device is a legal no-op. + * + * Physical devices can not be paused or unpaused, only logical devices + * created through SDL_OpenAudioDevice() can be. + * + * \param devid a device opened by SDL_OpenAudioDevice(). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AudioDevicePaused + * \sa SDL_PauseAudioDevice + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ResumeAudioDevice(SDL_AudioDeviceID devid); + +/** + * Use this function to query if an audio device is paused. + * + * Unlike in SDL2, audio devices start in an _unpaused_ state, since an app + * has to bind a stream before any audio will flow. + * + * Physical devices can not be paused or unpaused, only logical devices + * created through SDL_OpenAudioDevice() can be. Physical and invalid device + * IDs will report themselves as unpaused here. + * + * \param devid a device opened by SDL_OpenAudioDevice(). + * \returns true if device is valid and paused, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PauseAudioDevice + * \sa SDL_ResumeAudioDevice + */ +extern SDL_DECLSPEC bool SDLCALL SDL_AudioDevicePaused(SDL_AudioDeviceID devid); + +/** + * Get the gain of an audio device. + * + * The gain of a device is its volume; a larger gain means a louder output, + * with a gain of zero being silence. + * + * Audio devices default to a gain of 1.0f (no change in output). + * + * Physical devices may not have their gain changed, only logical devices, and + * this function will always return -1.0f when used on physical devices. + * + * \param devid the audio device to query. + * \returns the gain of the device or -1.0f on failure; call SDL_GetError() + * for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioDeviceGain + */ +extern SDL_DECLSPEC float SDLCALL SDL_GetAudioDeviceGain(SDL_AudioDeviceID devid); + +/** + * Change the gain of an audio device. + * + * The gain of a device is its volume; a larger gain means a louder output, + * with a gain of zero being silence. + * + * Audio devices default to a gain of 1.0f (no change in output). + * + * Physical devices may not have their gain changed, only logical devices, and + * this function will always return false when used on physical devices. While + * it might seem attractive to adjust several logical devices at once in this + * way, it would allow an app or library to interfere with another portion of + * the program's otherwise-isolated devices. + * + * This is applied, along with any per-audiostream gain, during playback to + * the hardware, and can be continuously changed to create various effects. On + * recording devices, this will adjust the gain before passing the data into + * an audiostream; that recording audiostream can then adjust its gain further + * when outputting the data elsewhere, if it likes, but that second gain is + * not applied until the data leaves the audiostream again. + * + * \param devid the audio device on which to change gain. + * \param gain the gain. 1.0f is no change, 0.0f is silence. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAudioDeviceGain + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioDeviceGain(SDL_AudioDeviceID devid, float gain); + +/** + * Close a previously-opened audio device. + * + * The application should close open audio devices once they are no longer + * needed. + * + * This function may block briefly while pending audio data is played by the + * hardware, so that applications don't drop the last buffer of data they + * supplied if terminating immediately afterwards. + * + * \param devid an audio device id previously returned by + * SDL_OpenAudioDevice(). + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenAudioDevice + */ +extern SDL_DECLSPEC void SDLCALL SDL_CloseAudioDevice(SDL_AudioDeviceID devid); + +/** + * Bind a list of audio streams to an audio device. + * + * Audio data will flow through any bound streams. For a playback device, data + * for all bound streams will be mixed together and fed to the device. For a + * recording device, a copy of recorded data will be provided to each bound + * stream. + * + * Audio streams can only be bound to an open device. This operation is + * atomic--all streams bound in the same call will start processing at the + * same time, so they can stay in sync. Also: either all streams will be bound + * or none of them will be. + * + * It is an error to bind an already-bound stream; it must be explicitly + * unbound first. + * + * Binding a stream to a device will set its output format for playback + * devices, and its input format for recording devices, so they match the + * device's settings. The caller is welcome to change the other end of the + * stream's format at any time with SDL_SetAudioStreamFormat(). + * + * \param devid an audio device to bind a stream to. + * \param streams an array of audio streams to bind. + * \param num_streams number streams listed in the `streams` array. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BindAudioStreams + * \sa SDL_UnbindAudioStream + * \sa SDL_GetAudioStreamDevice + */ +extern SDL_DECLSPEC bool SDLCALL SDL_BindAudioStreams(SDL_AudioDeviceID devid, SDL_AudioStream * const *streams, int num_streams); + +/** + * Bind a single audio stream to an audio device. + * + * This is a convenience function, equivalent to calling + * `SDL_BindAudioStreams(devid, &stream, 1)`. + * + * \param devid an audio device to bind a stream to. + * \param stream an audio stream to bind to a device. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BindAudioStreams + * \sa SDL_UnbindAudioStream + * \sa SDL_GetAudioStreamDevice + */ +extern SDL_DECLSPEC bool SDLCALL SDL_BindAudioStream(SDL_AudioDeviceID devid, SDL_AudioStream *stream); + +/** + * Unbind a list of audio streams from their audio devices. + * + * The streams being unbound do not all have to be on the same device. All + * streams on the same device will be unbound atomically (data will stop + * flowing through all unbound streams on the same device at the same time). + * + * Unbinding a stream that isn't bound to a device is a legal no-op. + * + * \param streams an array of audio streams to unbind. Can be NULL or contain + * NULL. + * \param num_streams number streams listed in the `streams` array. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BindAudioStreams + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnbindAudioStreams(SDL_AudioStream * const *streams, int num_streams); + +/** + * Unbind a single audio stream from its audio device. + * + * This is a convenience function, equivalent to calling + * `SDL_UnbindAudioStreams(&stream, 1)`. + * + * \param stream an audio stream to unbind from a device. Can be NULL. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BindAudioStream + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnbindAudioStream(SDL_AudioStream *stream); + +/** + * Query an audio stream for its currently-bound device. + * + * This reports the audio device that an audio stream is currently bound to. + * + * If not bound, or invalid, this returns zero, which is not a valid device + * ID. + * + * \param stream the audio stream to query. + * \returns the bound audio device, or 0 if not bound or invalid. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BindAudioStream + * \sa SDL_BindAudioStreams + */ +extern SDL_DECLSPEC SDL_AudioDeviceID SDLCALL SDL_GetAudioStreamDevice(SDL_AudioStream *stream); + +/** + * Create a new audio stream. + * + * \param src_spec the format details of the input audio. + * \param dst_spec the format details of the output audio. + * \returns a new audio stream on success or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PutAudioStreamData + * \sa SDL_GetAudioStreamData + * \sa SDL_GetAudioStreamAvailable + * \sa SDL_FlushAudioStream + * \sa SDL_ClearAudioStream + * \sa SDL_SetAudioStreamFormat + * \sa SDL_DestroyAudioStream + */ +extern SDL_DECLSPEC SDL_AudioStream * SDLCALL SDL_CreateAudioStream(const SDL_AudioSpec *src_spec, const SDL_AudioSpec *dst_spec); + +/** + * Get the properties associated with an audio stream. + * + * \param stream the SDL_AudioStream to query. + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetAudioStreamProperties(SDL_AudioStream *stream); + +/** + * Query the current format of an audio stream. + * + * \param stream the SDL_AudioStream to query. + * \param src_spec where to store the input audio format; ignored if NULL. + * \param dst_spec where to store the output audio format; ignored if NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamFormat + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetAudioStreamFormat(SDL_AudioStream *stream, SDL_AudioSpec *src_spec, SDL_AudioSpec *dst_spec); + +/** + * Change the input and output formats of an audio stream. + * + * Future calls to and SDL_GetAudioStreamAvailable and SDL_GetAudioStreamData + * will reflect the new format, and future calls to SDL_PutAudioStreamData + * must provide data in the new input formats. + * + * Data that was previously queued in the stream will still be operated on in + * the format that was current when it was added, which is to say you can put + * the end of a sound file in one format to a stream, change formats for the + * next sound file, and start putting that new data while the previous sound + * file is still queued, and everything will still play back correctly. + * + * If a stream is bound to a device, then the format of the side of the stream + * bound to a device cannot be changed (src_spec for recording devices, + * dst_spec for playback devices). Attempts to make a change to this side will + * be ignored, but this will not report an error. The other side's format can + * be changed. + * + * \param stream the stream the format is being changed. + * \param src_spec the new format of the audio input; if NULL, it is not + * changed. + * \param dst_spec the new format of the audio output; if NULL, it is not + * changed. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAudioStreamFormat + * \sa SDL_SetAudioStreamFrequencyRatio + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioStreamFormat(SDL_AudioStream *stream, const SDL_AudioSpec *src_spec, const SDL_AudioSpec *dst_spec); + +/** + * Get the frequency ratio of an audio stream. + * + * \param stream the SDL_AudioStream to query. + * \returns the frequency ratio of the stream or 0.0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamFrequencyRatio + */ +extern SDL_DECLSPEC float SDLCALL SDL_GetAudioStreamFrequencyRatio(SDL_AudioStream *stream); + +/** + * Change the frequency ratio of an audio stream. + * + * The frequency ratio is used to adjust the rate at which input data is + * consumed. Changing this effectively modifies the speed and pitch of the + * audio. A value greater than 1.0 will play the audio faster, and at a higher + * pitch. A value less than 1.0 will play the audio slower, and at a lower + * pitch. + * + * This is applied during SDL_GetAudioStreamData, and can be continuously + * changed to create various effects. + * + * \param stream the stream the frequency ratio is being changed. + * \param ratio the frequency ratio. 1.0 is normal speed. Must be between 0.01 + * and 100. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAudioStreamFrequencyRatio + * \sa SDL_SetAudioStreamFormat + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioStreamFrequencyRatio(SDL_AudioStream *stream, float ratio); + +/** + * Get the gain of an audio stream. + * + * The gain of a stream is its volume; a larger gain means a louder output, + * with a gain of zero being silence. + * + * Audio streams default to a gain of 1.0f (no change in output). + * + * \param stream the SDL_AudioStream to query. + * \returns the gain of the stream or -1.0f on failure; call SDL_GetError() + * for more information. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamGain + */ +extern SDL_DECLSPEC float SDLCALL SDL_GetAudioStreamGain(SDL_AudioStream *stream); + +/** + * Change the gain of an audio stream. + * + * The gain of a stream is its volume; a larger gain means a louder output, + * with a gain of zero being silence. + * + * Audio streams default to a gain of 1.0f (no change in output). + * + * This is applied during SDL_GetAudioStreamData, and can be continuously + * changed to create various effects. + * + * \param stream the stream on which the gain is being changed. + * \param gain the gain. 1.0f is no change, 0.0f is silence. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAudioStreamGain + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioStreamGain(SDL_AudioStream *stream, float gain); + +/** + * Get the current input channel map of an audio stream. + * + * Channel maps are optional; most things do not need them, instead passing + * data in the [order that SDL expects](CategoryAudio#channel-layouts). + * + * Audio streams default to no remapping applied. This is represented by + * returning NULL, and does not signify an error. + * + * \param stream the SDL_AudioStream to query. + * \param count On output, set to number of channels in the map. Can be NULL. + * \returns an array of the current channel mapping, with as many elements as + * the current output spec's channels, or NULL if default. This + * should be freed with SDL_free() when it is no longer needed. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamInputChannelMap + */ +extern SDL_DECLSPEC int * SDLCALL SDL_GetAudioStreamInputChannelMap(SDL_AudioStream *stream, int *count); + +/** + * Get the current output channel map of an audio stream. + * + * Channel maps are optional; most things do not need them, instead passing + * data in the [order that SDL expects](CategoryAudio#channel-layouts). + * + * Audio streams default to no remapping applied. This is represented by + * returning NULL, and does not signify an error. + * + * \param stream the SDL_AudioStream to query. + * \param count On output, set to number of channels in the map. Can be NULL. + * \returns an array of the current channel mapping, with as many elements as + * the current output spec's channels, or NULL if default. This + * should be freed with SDL_free() when it is no longer needed. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamInputChannelMap + */ +extern SDL_DECLSPEC int * SDLCALL SDL_GetAudioStreamOutputChannelMap(SDL_AudioStream *stream, int *count); + +/** + * Set the current input channel map of an audio stream. + * + * Channel maps are optional; most things do not need them, instead passing + * data in the [order that SDL expects](CategoryAudio#channel-layouts). + * + * The input channel map reorders data that is added to a stream via + * SDL_PutAudioStreamData. Future calls to SDL_PutAudioStreamData must provide + * data in the new channel order. + * + * Each item in the array represents an input channel, and its value is the + * channel that it should be remapped to. To reverse a stereo signal's left + * and right values, you'd have an array of `{ 1, 0 }`. It is legal to remap + * multiple channels to the same thing, so `{ 1, 1 }` would duplicate the + * right channel to both channels of a stereo signal. An element in the + * channel map set to -1 instead of a valid channel will mute that channel, + * setting it to a silence value. + * + * You cannot change the number of channels through a channel map, just + * reorder/mute them. + * + * Data that was previously queued in the stream will still be operated on in + * the order that was current when it was added, which is to say you can put + * the end of a sound file in one order to a stream, change orders for the + * next sound file, and start putting that new data while the previous sound + * file is still queued, and everything will still play back correctly. + * + * Audio streams default to no remapping applied. Passing a NULL channel map + * is legal, and turns off remapping. + * + * SDL will copy the channel map; the caller does not have to save this array + * after this call. + * + * If `count` is not equal to the current number of channels in the audio + * stream's format, this will fail. This is a safety measure to make sure a + * race condition hasn't changed the format while this call is setting the + * channel map. + * + * Unlike attempting to change the stream's format, the input channel map on a + * stream bound to a recording device is permitted to change at any time; any + * data added to the stream from the device after this call will have the new + * mapping, but previously-added data will still have the prior mapping. + * + * \param stream the SDL_AudioStream to change. + * \param chmap the new channel map, NULL to reset to default. + * \param count The number of channels in the map. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. Don't change the + * stream's format to have a different number of channels from a + * a different thread at the same time, though! + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamInputChannelMap + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioStreamInputChannelMap(SDL_AudioStream *stream, const int *chmap, int count); + +/** + * Set the current output channel map of an audio stream. + * + * Channel maps are optional; most things do not need them, instead passing + * data in the [order that SDL expects](CategoryAudio#channel-layouts). + * + * The output channel map reorders data that leaving a stream via + * SDL_GetAudioStreamData. + * + * Each item in the array represents an input channel, and its value is the + * channel that it should be remapped to. To reverse a stereo signal's left + * and right values, you'd have an array of `{ 1, 0 }`. It is legal to remap + * multiple channels to the same thing, so `{ 1, 1 }` would duplicate the + * right channel to both channels of a stereo signal. An element in the + * channel map set to -1 instead of a valid channel will mute that channel, + * setting it to a silence value. + * + * You cannot change the number of channels through a channel map, just + * reorder/mute them. + * + * The output channel map can be changed at any time, as output remapping is + * applied during SDL_GetAudioStreamData. + * + * Audio streams default to no remapping applied. Passing a NULL channel map + * is legal, and turns off remapping. + * + * SDL will copy the channel map; the caller does not have to save this array + * after this call. + * + * If `count` is not equal to the current number of channels in the audio + * stream's format, this will fail. This is a safety measure to make sure a + * race condition hasn't changed the format while this call is setting the + * channel map. + * + * Unlike attempting to change the stream's format, the output channel map on + * a stream bound to a recording device is permitted to change at any time; + * any data added to the stream after this call will have the new mapping, but + * previously-added data will still have the prior mapping. When the channel + * map doesn't match the hardware's channel layout, SDL will convert the data + * before feeding it to the device for playback. + * + * \param stream the SDL_AudioStream to change. + * \param chmap the new channel map, NULL to reset to default. + * \param count The number of channels in the map. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, as it holds + * a stream-specific mutex while running. Don't change the + * stream's format to have a different number of channels from a + * a different thread at the same time, though! + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamInputChannelMap + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioStreamOutputChannelMap(SDL_AudioStream *stream, const int *chmap, int count); + +/** + * Add data to the stream. + * + * This data must match the format/channels/samplerate specified in the latest + * call to SDL_SetAudioStreamFormat, or the format specified when creating the + * stream if it hasn't been changed. + * + * Note that this call simply copies the unconverted data for later. This is + * different than SDL2, where data was converted during the Put call and the + * Get call would just dequeue the previously-converted data. + * + * \param stream the stream the audio data is being added to. + * \param buf a pointer to the audio data to add. + * \param len the number of bytes to write to the stream. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, but if the + * stream has a callback set, the caller might need to manage + * extra locking. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ClearAudioStream + * \sa SDL_FlushAudioStream + * \sa SDL_GetAudioStreamData + * \sa SDL_GetAudioStreamQueued + */ +extern SDL_DECLSPEC bool SDLCALL SDL_PutAudioStreamData(SDL_AudioStream *stream, const void *buf, int len); + +/** + * Get converted/resampled data from the stream. + * + * The input/output data format/channels/samplerate is specified when creating + * the stream, and can be changed after creation by calling + * SDL_SetAudioStreamFormat. + * + * Note that any conversion and resampling necessary is done during this call, + * and SDL_PutAudioStreamData simply queues unconverted data for later. This + * is different than SDL2, where that work was done while inputting new data + * to the stream and requesting the output just copied the converted data. + * + * \param stream the stream the audio is being requested from. + * \param buf a buffer to fill with audio data. + * \param len the maximum number of bytes to fill. + * \returns the number of bytes read from the stream or -1 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread, but if the + * stream has a callback set, the caller might need to manage + * extra locking. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ClearAudioStream + * \sa SDL_GetAudioStreamAvailable + * \sa SDL_PutAudioStreamData + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetAudioStreamData(SDL_AudioStream *stream, void *buf, int len); + +/** + * Get the number of converted/resampled bytes available. + * + * The stream may be buffering data behind the scenes until it has enough to + * resample correctly, so this number might be lower than what you expect, or + * even be zero. Add more data or flush the stream if you need the data now. + * + * If the stream has so much data that it would overflow an int, the return + * value is clamped to a maximum value, but no queued data is lost; if there + * are gigabytes of data queued, the app might need to read some of it with + * SDL_GetAudioStreamData before this function's return value is no longer + * clamped. + * + * \param stream the audio stream to query. + * \returns the number of converted/resampled bytes available or -1 on + * failure; call SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAudioStreamData + * \sa SDL_PutAudioStreamData + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetAudioStreamAvailable(SDL_AudioStream *stream); + + +/** + * Get the number of bytes currently queued. + * + * This is the number of bytes put into a stream as input, not the number that + * can be retrieved as output. Because of several details, it's not possible + * to calculate one number directly from the other. If you need to know how + * much usable data can be retrieved right now, you should use + * SDL_GetAudioStreamAvailable() and not this function. + * + * Note that audio streams can change their input format at any time, even if + * there is still data queued in a different format, so the returned byte + * count will not necessarily match the number of _sample frames_ available. + * Users of this API should be aware of format changes they make when feeding + * a stream and plan accordingly. + * + * Queued data is not converted until it is consumed by + * SDL_GetAudioStreamData, so this value should be representative of the exact + * data that was put into the stream. + * + * If the stream has so much data that it would overflow an int, the return + * value is clamped to a maximum value, but no queued data is lost; if there + * are gigabytes of data queued, the app might need to read some of it with + * SDL_GetAudioStreamData before this function's return value is no longer + * clamped. + * + * \param stream the audio stream to query. + * \returns the number of bytes queued or -1 on failure; call SDL_GetError() + * for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PutAudioStreamData + * \sa SDL_ClearAudioStream + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetAudioStreamQueued(SDL_AudioStream *stream); + + +/** + * Tell the stream that you're done sending data, and anything being buffered + * should be converted/resampled and made available immediately. + * + * It is legal to add more data to a stream after flushing, but there may be + * audio gaps in the output. Generally this is intended to signal the end of + * input, so the complete output becomes available. + * + * \param stream the audio stream to flush. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PutAudioStreamData + */ +extern SDL_DECLSPEC bool SDLCALL SDL_FlushAudioStream(SDL_AudioStream *stream); + +/** + * Clear any pending data in the stream. + * + * This drops any queued data, so there will be nothing to read from the + * stream until more is added. + * + * \param stream the audio stream to clear. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAudioStreamAvailable + * \sa SDL_GetAudioStreamData + * \sa SDL_GetAudioStreamQueued + * \sa SDL_PutAudioStreamData + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ClearAudioStream(SDL_AudioStream *stream); + +/** + * Use this function to pause audio playback on the audio device associated + * with an audio stream. + * + * This function pauses audio processing for a given device. Any bound audio + * streams will not progress, and no audio will be generated. Pausing one + * device does not prevent other unpaused devices from running. + * + * Pausing a device can be useful to halt all audio without unbinding all the + * audio streams. This might be useful while a game is paused, or a level is + * loading, etc. + * + * \param stream the audio stream associated with the audio device to pause. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ResumeAudioStreamDevice + */ +extern SDL_DECLSPEC bool SDLCALL SDL_PauseAudioStreamDevice(SDL_AudioStream *stream); + +/** + * Use this function to unpause audio playback on the audio device associated + * with an audio stream. + * + * This function unpauses audio processing for a given device that has + * previously been paused. Once unpaused, any bound audio streams will begin + * to progress again, and audio can be generated. + * + * Remember, SDL_OpenAudioDeviceStream opens device in a paused state, so this + * function call is required for audio playback to begin on such device. + * + * \param stream the audio stream associated with the audio device to resume. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PauseAudioStreamDevice + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ResumeAudioStreamDevice(SDL_AudioStream *stream); + +/** + * Use this function to query if an audio device associated with a stream is + * paused. + * + * Unlike in SDL2, audio devices start in an _unpaused_ state, since an app + * has to bind a stream before any audio will flow. + * + * \param stream the audio stream associated with the audio device to query. + * \returns true if device is valid and paused, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PauseAudioStreamDevice + * \sa SDL_ResumeAudioStreamDevice + */ +extern SDL_DECLSPEC bool SDLCALL SDL_AudioStreamDevicePaused(SDL_AudioStream *stream); + + +/** + * Lock an audio stream for serialized access. + * + * Each SDL_AudioStream has an internal mutex it uses to protect its data + * structures from threading conflicts. This function allows an app to lock + * that mutex, which could be useful if registering callbacks on this stream. + * + * One does not need to lock a stream to use in it most cases, as the stream + * manages this lock internally. However, this lock is held during callbacks, + * which may run from arbitrary threads at any time, so if an app needs to + * protect shared data during those callbacks, locking the stream guarantees + * that the callback is not running while the lock is held. + * + * As this is just a wrapper over SDL_LockMutex for an internal lock; it has + * all the same attributes (recursive locks are allowed, etc). + * + * \param stream the audio stream to lock. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_UnlockAudioStream + */ +extern SDL_DECLSPEC bool SDLCALL SDL_LockAudioStream(SDL_AudioStream *stream); + + +/** + * Unlock an audio stream for serialized access. + * + * This unlocks an audio stream after a call to SDL_LockAudioStream. + * + * \param stream the audio stream to unlock. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety You should only call this from the same thread that + * previously called SDL_LockAudioStream. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockAudioStream + */ +extern SDL_DECLSPEC bool SDLCALL SDL_UnlockAudioStream(SDL_AudioStream *stream); + +/** + * A callback that fires when data passes through an SDL_AudioStream. + * + * Apps can (optionally) register a callback with an audio stream that is + * called when data is added with SDL_PutAudioStreamData, or requested with + * SDL_GetAudioStreamData. + * + * Two values are offered here: one is the amount of additional data needed to + * satisfy the immediate request (which might be zero if the stream already + * has enough data queued) and the other is the total amount being requested. + * In a Get call triggering a Put callback, these values can be different. In + * a Put call triggering a Get callback, these values are always the same. + * + * Byte counts might be slightly overestimated due to buffering or resampling, + * and may change from call to call. + * + * This callback is not required to do anything. Generally this is useful for + * adding/reading data on demand, and the app will often put/get data as + * appropriate, but the system goes on with the data currently available to it + * if this callback does nothing. + * + * \param stream the SDL audio stream associated with this callback. + * \param additional_amount the amount of data, in bytes, that is needed right + * now. + * \param total_amount the total amount of data requested, in bytes, that is + * requested or available. + * \param userdata an opaque pointer provided by the app for their personal + * use. + * + * \threadsafety This callbacks may run from any thread, so if you need to + * protect shared data, you should use SDL_LockAudioStream to + * serialize access; this lock will be held before your callback + * is called, so your callback does not need to manage the lock + * explicitly. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamGetCallback + * \sa SDL_SetAudioStreamPutCallback + */ +typedef void (SDLCALL *SDL_AudioStreamCallback)(void *userdata, SDL_AudioStream *stream, int additional_amount, int total_amount); + +/** + * Set a callback that runs when data is requested from an audio stream. + * + * This callback is called _before_ data is obtained from the stream, giving + * the callback the chance to add more on-demand. + * + * The callback can (optionally) call SDL_PutAudioStreamData() to add more + * audio to the stream during this call; if needed, the request that triggered + * this callback will obtain the new data immediately. + * + * The callback's `additional_amount` argument is roughly how many bytes of + * _unconverted_ data (in the stream's input format) is needed by the caller, + * although this may overestimate a little for safety. This takes into account + * how much is already in the stream and only asks for any extra necessary to + * resolve the request, which means the callback may be asked for zero bytes, + * and a different amount on each call. + * + * The callback is not required to supply exact amounts; it is allowed to + * supply too much or too little or none at all. The caller will get what's + * available, up to the amount they requested, regardless of this callback's + * outcome. + * + * Clearing or flushing an audio stream does not call this callback. + * + * This function obtains the stream's lock, which means any existing callback + * (get or put) in progress will finish running before setting the new + * callback. + * + * Setting a NULL function turns off the callback. + * + * \param stream the audio stream to set the new callback on. + * \param callback the new callback function to call when data is requested + * from the stream. + * \param userdata an opaque pointer provided to the callback for its own + * personal use. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. This only fails if `stream` is NULL. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamPutCallback + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioStreamGetCallback(SDL_AudioStream *stream, SDL_AudioStreamCallback callback, void *userdata); + +/** + * Set a callback that runs when data is added to an audio stream. + * + * This callback is called _after_ the data is added to the stream, giving the + * callback the chance to obtain it immediately. + * + * The callback can (optionally) call SDL_GetAudioStreamData() to obtain audio + * from the stream during this call. + * + * The callback's `additional_amount` argument is how many bytes of + * _converted_ data (in the stream's output format) was provided by the + * caller, although this may underestimate a little for safety. This value + * might be less than what is currently available in the stream, if data was + * already there, and might be less than the caller provided if the stream + * needs to keep a buffer to aid in resampling. Which means the callback may + * be provided with zero bytes, and a different amount on each call. + * + * The callback may call SDL_GetAudioStreamAvailable to see the total amount + * currently available to read from the stream, instead of the total provided + * by the current call. + * + * The callback is not required to obtain all data. It is allowed to read less + * or none at all. Anything not read now simply remains in the stream for + * later access. + * + * Clearing or flushing an audio stream does not call this callback. + * + * This function obtains the stream's lock, which means any existing callback + * (get or put) in progress will finish running before setting the new + * callback. + * + * Setting a NULL function turns off the callback. + * + * \param stream the audio stream to set the new callback on. + * \param callback the new callback function to call when data is added to the + * stream. + * \param userdata an opaque pointer provided to the callback for its own + * personal use. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. This only fails if `stream` is NULL. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAudioStreamGetCallback + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioStreamPutCallback(SDL_AudioStream *stream, SDL_AudioStreamCallback callback, void *userdata); + + +/** + * Free an audio stream. + * + * This will release all allocated data, including any audio that is still + * queued. You do not need to manually clear the stream first. + * + * If this stream was bound to an audio device, it is unbound during this + * call. If this stream was created with SDL_OpenAudioDeviceStream, the audio + * device that was opened alongside this stream's creation will be closed, + * too. + * + * \param stream the audio stream to destroy. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateAudioStream + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyAudioStream(SDL_AudioStream *stream); + + +/** + * Convenience function for straightforward audio init for the common case. + * + * If all your app intends to do is provide a single source of PCM audio, this + * function allows you to do all your audio setup in a single call. + * + * This is also intended to be a clean means to migrate apps from SDL2. + * + * This function will open an audio device, create a stream and bind it. + * Unlike other methods of setup, the audio device will be closed when this + * stream is destroyed, so the app can treat the returned SDL_AudioStream as + * the only object needed to manage audio playback. + * + * Also unlike other functions, the audio device begins paused. This is to map + * more closely to SDL2-style behavior, since there is no extra step here to + * bind a stream to begin audio flowing. The audio device should be resumed + * with `SDL_ResumeAudioStreamDevice(stream);` + * + * This function works with both playback and recording devices. + * + * The `spec` parameter represents the app's side of the audio stream. That + * is, for recording audio, this will be the output format, and for playing + * audio, this will be the input format. If spec is NULL, the system will + * choose the format, and the app can use SDL_GetAudioStreamFormat() to obtain + * this information later. + * + * If you don't care about opening a specific audio device, you can (and + * probably _should_), use SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK for playback and + * SDL_AUDIO_DEVICE_DEFAULT_RECORDING for recording. + * + * One can optionally provide a callback function; if NULL, the app is + * expected to queue audio data for playback (or unqueue audio data if + * capturing). Otherwise, the callback will begin to fire once the device is + * unpaused. + * + * Destroying the returned stream with SDL_DestroyAudioStream will also close + * the audio device associated with this stream. + * + * \param devid an audio device to open, or SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK + * or SDL_AUDIO_DEVICE_DEFAULT_RECORDING. + * \param spec the audio stream's data format. Can be NULL. + * \param callback a callback where the app will provide new data for + * playback, or receive new data for recording. Can be NULL, + * in which case the app will need to call + * SDL_PutAudioStreamData or SDL_GetAudioStreamData as + * necessary. + * \param userdata app-controlled pointer passed to callback. Can be NULL. + * Ignored if callback is NULL. + * \returns an audio stream on success, ready to use, or NULL on failure; call + * SDL_GetError() for more information. When done with this stream, + * call SDL_DestroyAudioStream to free resources and close the + * device. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAudioStreamDevice + * \sa SDL_ResumeAudioStreamDevice + */ +extern SDL_DECLSPEC SDL_AudioStream * SDLCALL SDL_OpenAudioDeviceStream(SDL_AudioDeviceID devid, const SDL_AudioSpec *spec, SDL_AudioStreamCallback callback, void *userdata); + +/** + * A callback that fires when data is about to be fed to an audio device. + * + * This is useful for accessing the final mix, perhaps for writing a + * visualizer or applying a final effect to the audio data before playback. + * + * This callback should run as quickly as possible and not block for any + * significant time, as this callback delays submission of data to the audio + * device, which can cause audio playback problems. + * + * The postmix callback _must_ be able to handle any audio data format + * specified in `spec`, which can change between callbacks if the audio device + * changed. However, this only covers frequency and channel count; data is + * always provided here in SDL_AUDIO_F32 format. + * + * The postmix callback runs _after_ logical device gain and audiostream gain + * have been applied, which is to say you can make the output data louder at + * this point than the gain settings would suggest. + * + * \param userdata a pointer provided by the app through + * SDL_SetAudioPostmixCallback, for its own use. + * \param spec the current format of audio that is to be submitted to the + * audio device. + * \param buffer the buffer of audio samples to be submitted. The callback can + * inspect and/or modify this data. + * \param buflen the size of `buffer` in bytes. + * + * \threadsafety This will run from a background thread owned by SDL. The + * application is responsible for locking resources the callback + * touches that need to be protected. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_SetAudioPostmixCallback + */ +typedef void (SDLCALL *SDL_AudioPostmixCallback)(void *userdata, const SDL_AudioSpec *spec, float *buffer, int buflen); + +/** + * Set a callback that fires when data is about to be fed to an audio device. + * + * This is useful for accessing the final mix, perhaps for writing a + * visualizer or applying a final effect to the audio data before playback. + * + * The buffer is the final mix of all bound audio streams on an opened device; + * this callback will fire regularly for any device that is both opened and + * unpaused. If there is no new data to mix, either because no streams are + * bound to the device or all the streams are empty, this callback will still + * fire with the entire buffer set to silence. + * + * This callback is allowed to make changes to the data; the contents of the + * buffer after this call is what is ultimately passed along to the hardware. + * + * The callback is always provided the data in float format (values from -1.0f + * to 1.0f), but the number of channels or sample rate may be different than + * the format the app requested when opening the device; SDL might have had to + * manage a conversion behind the scenes, or the playback might have jumped to + * new physical hardware when a system default changed, etc. These details may + * change between calls. Accordingly, the size of the buffer might change + * between calls as well. + * + * This callback can run at any time, and from any thread; if you need to + * serialize access to your app's data, you should provide and use a mutex or + * other synchronization device. + * + * All of this to say: there are specific needs this callback can fulfill, but + * it is not the simplest interface. Apps should generally provide audio in + * their preferred format through an SDL_AudioStream and let SDL handle the + * difference. + * + * This function is extremely time-sensitive; the callback should do the least + * amount of work possible and return as quickly as it can. The longer the + * callback runs, the higher the risk of audio dropouts or other problems. + * + * This function will block until the audio device is in between iterations, + * so any existing callback that might be running will finish before this + * function sets the new callback and returns. + * + * Setting a NULL callback function disables any previously-set callback. + * + * \param devid the ID of an opened audio device. + * \param callback a callback function to be called. Can be NULL. + * \param userdata app-controlled pointer passed to callback. Can be NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioPostmixCallback(SDL_AudioDeviceID devid, SDL_AudioPostmixCallback callback, void *userdata); + + +/** + * Load the audio data of a WAVE file into memory. + * + * Loading a WAVE file requires `src`, `spec`, `audio_buf` and `audio_len` to + * be valid pointers. The entire data portion of the file is then loaded into + * memory and decoded if necessary. + * + * Supported formats are RIFF WAVE files with the formats PCM (8, 16, 24, and + * 32 bits), IEEE Float (32 bits), Microsoft ADPCM and IMA ADPCM (4 bits), and + * A-law and mu-law (8 bits). Other formats are currently unsupported and + * cause an error. + * + * If this function succeeds, the return value is zero and the pointer to the + * audio data allocated by the function is written to `audio_buf` and its + * length in bytes to `audio_len`. The SDL_AudioSpec members `freq`, + * `channels`, and `format` are set to the values of the audio data in the + * buffer. + * + * It's necessary to use SDL_free() to free the audio data returned in + * `audio_buf` when it is no longer used. + * + * Because of the underspecification of the .WAV format, there are many + * problematic files in the wild that cause issues with strict decoders. To + * provide compatibility with these files, this decoder is lenient in regards + * to the truncation of the file, the fact chunk, and the size of the RIFF + * chunk. The hints `SDL_HINT_WAVE_RIFF_CHUNK_SIZE`, + * `SDL_HINT_WAVE_TRUNCATION`, and `SDL_HINT_WAVE_FACT_CHUNK` can be used to + * tune the behavior of the loading process. + * + * Any file that is invalid (due to truncation, corruption, or wrong values in + * the headers), too big, or unsupported causes an error. Additionally, any + * critical I/O error from the data source will terminate the loading process + * with an error. The function returns NULL on error and in all cases (with + * the exception of `src` being NULL), an appropriate error message will be + * set. + * + * It is required that the data source supports seeking. + * + * Example: + * + * ```c + * SDL_LoadWAV_IO(SDL_IOFromFile("sample.wav", "rb"), true, &spec, &buf, &len); + * ``` + * + * Note that the SDL_LoadWAV function does this same thing for you, but in a + * less messy way: + * + * ```c + * SDL_LoadWAV("sample.wav", &spec, &buf, &len); + * ``` + * + * \param src the data source for the WAVE data. + * \param closeio if true, calls SDL_CloseIO() on `src` before returning, even + * in the case of an error. + * \param spec a pointer to an SDL_AudioSpec that will be set to the WAVE + * data's format details on successful return. + * \param audio_buf a pointer filled with the audio data, allocated by the + * function. + * \param audio_len a pointer filled with the length of the audio data buffer + * in bytes. + * \returns true on success. `audio_buf` will be filled with a pointer to an + * allocated buffer containing the audio data, and `audio_len` is + * filled with the length of that audio buffer in bytes. + * + * This function returns false if the .WAV file cannot be opened, + * uses an unknown data format, or is corrupt; call SDL_GetError() + * for more information. + * + * When the application is done with the data returned in + * `audio_buf`, it should call SDL_free() to dispose of it. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_free + * \sa SDL_LoadWAV + */ +extern SDL_DECLSPEC bool SDLCALL SDL_LoadWAV_IO(SDL_IOStream *src, bool closeio, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len); + +/** + * Loads a WAV from a file path. + * + * This is a convenience function that is effectively the same as: + * + * ```c + * SDL_LoadWAV_IO(SDL_IOFromFile(path, "rb"), true, spec, audio_buf, audio_len); + * ``` + * + * \param path the file path of the WAV file to open. + * \param spec a pointer to an SDL_AudioSpec that will be set to the WAVE + * data's format details on successful return. + * \param audio_buf a pointer filled with the audio data, allocated by the + * function. + * \param audio_len a pointer filled with the length of the audio data buffer + * in bytes. + * \returns true on success. `audio_buf` will be filled with a pointer to an + * allocated buffer containing the audio data, and `audio_len` is + * filled with the length of that audio buffer in bytes. + * + * This function returns false if the .WAV file cannot be opened, + * uses an unknown data format, or is corrupt; call SDL_GetError() + * for more information. + * + * When the application is done with the data returned in + * `audio_buf`, it should call SDL_free() to dispose of it. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_free + * \sa SDL_LoadWAV_IO + */ +extern SDL_DECLSPEC bool SDLCALL SDL_LoadWAV(const char *path, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len); + +/** + * Mix audio data in a specified format. + * + * This takes an audio buffer `src` of `len` bytes of `format` data and mixes + * it into `dst`, performing addition, volume adjustment, and overflow + * clipping. The buffer pointed to by `dst` must also be `len` bytes of + * `format` data. + * + * This is provided for convenience -- you can mix your own audio data. + * + * Do not use this function for mixing together more than two streams of + * sample data. The output from repeated application of this function may be + * distorted by clipping, because there is no accumulator with greater range + * than the input (not to mention this being an inefficient way of doing it). + * + * It is a common misconception that this function is required to write audio + * data to an output stream in an audio callback. While you can do that, + * SDL_MixAudio() is really only needed when you're mixing a single audio + * stream with a volume adjustment. + * + * \param dst the destination for the mixed audio. + * \param src the source audio buffer to be mixed. + * \param format the SDL_AudioFormat structure representing the desired audio + * format. + * \param len the length of the audio buffer in bytes. + * \param volume ranges from 0.0 - 1.0, and should be set to 1.0 for full + * audio volume. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_MixAudio(Uint8 *dst, const Uint8 *src, SDL_AudioFormat format, Uint32 len, float volume); + +/** + * Convert some audio data of one format to another format. + * + * Please note that this function is for convenience, but should not be used + * to resample audio in blocks, as it will introduce audio artifacts on the + * boundaries. You should only use this function if you are converting audio + * data in its entirety in one call. If you want to convert audio in smaller + * chunks, use an SDL_AudioStream, which is designed for this situation. + * + * Internally, this function creates and destroys an SDL_AudioStream on each + * use, so it's also less efficient than using one directly, if you need to + * convert multiple times. + * + * \param src_spec the format details of the input audio. + * \param src_data the audio data to be converted. + * \param src_len the len of src_data. + * \param dst_spec the format details of the output audio. + * \param dst_data will be filled with a pointer to converted audio data, + * which should be freed with SDL_free(). On error, it will be + * NULL. + * \param dst_len will be filled with the len of dst_data. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ConvertAudioSamples(const SDL_AudioSpec *src_spec, const Uint8 *src_data, int src_len, const SDL_AudioSpec *dst_spec, Uint8 **dst_data, int *dst_len); + +/** + * Get the human readable name of an audio format. + * + * \param format the audio format to query. + * \returns the human readable name of the specified audio format or + * "SDL_AUDIO_UNKNOWN" if the format isn't recognized. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetAudioFormatName(SDL_AudioFormat format); + +/** + * Get the appropriate memset value for silencing an audio format. + * + * The value returned by this function can be used as the second argument to + * memset (or SDL_memset) to set an audio buffer in a specific format to + * silence. + * + * \param format the audio data format to query. + * \returns a byte value that can be passed to memset. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetSilenceValueForFormat(SDL_AudioFormat format); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_audio_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_begin_code.h b/thirdparty/sdl/include/SDL3/SDL_begin_code.h new file mode 100644 index 00000000000..a6b47cf4b91 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_begin_code.h @@ -0,0 +1,486 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: BeginCode */ + +/** + * # CategoryBeginCode + * + * `SDL_begin_code.h` sets things up for C dynamic library function + * definitions, static inlined functions, and structures aligned at 4-byte + * alignment. If you don't like ugly C preprocessor code, don't look at this + * file. :) + * + * SDL's headers use this; applications generally should not include this + * header directly. + */ + +/* This shouldn't be nested -- included it around code only. */ +#ifdef SDL_begin_code_h +#error Nested inclusion of SDL_begin_code.h +#endif +#define SDL_begin_code_h + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A macro to tag a symbol as deprecated. + * + * A function is marked deprecated by adding this macro to its declaration: + * + * ```c + * extern SDL_DEPRECATED int ThisFunctionWasABadIdea(void); + * ``` + * + * Compilers with deprecation support can give a warning when a deprecated + * function is used. This symbol may be used in SDL's headers, but apps are + * welcome to use it for their own interfaces as well. + * + * SDL, on occasion, might deprecate a function for various reasons. However, + * SDL never removes symbols before major versions, so deprecated interfaces + * in SDL3 will remain available until SDL4, where it would be expected an app + * would have to take steps to migrate anyhow. + * + * On compilers without a deprecation mechanism, this is defined to nothing, + * and using a deprecated function will not generate a warning. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_DEPRECATED __attribute__((deprecated)) + +/** + * A macro to tag a symbol as a public API. + * + * SDL uses this macro for all its public functions. On some targets, it is + * used to signal to the compiler that this function needs to be exported from + * a shared library, but it might have other side effects. + * + * This symbol is used in SDL's headers, but apps and other libraries are + * welcome to use it for their own interfaces as well. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_DECLSPEC __attribute__ ((visibility("default"))) + +/** + * A macro to set a function's calling conventions. + * + * SDL uses this macro for all its public functions, and any callbacks it + * defines. This macro guarantees that calling conventions match between SDL + * and the app, even if the two were built with different compilers or + * optimization settings. + * + * When writing a callback function, it is very important for it to be + * correctly tagged with SDLCALL, as mismatched calling conventions can cause + * strange behaviors and can be difficult to diagnose. Plus, on many + * platforms, SDLCALL is defined to nothing, so compilers won't be able to + * warn that the tag is missing. + * + * This symbol is used in SDL's headers, but apps and other libraries are + * welcome to use it for their own interfaces as well. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDLCALL __cdecl + +/** + * A macro to request a function be inlined. + * + * This is a hint to the compiler to inline a function. The compiler is free + * to ignore this request. On compilers without inline support, this is + * defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_INLINE __inline + +/** + * A macro to demand a function be inlined. + * + * This is a command to the compiler to inline a function. SDL uses this macro + * in its public headers for a handful of simple functions. On compilers + * without forceinline support, this is defined to `static SDL_INLINE`, which + * is often good enough. + * + * This symbol is used in SDL's headers, but apps and other libraries are + * welcome to use it for their own interfaces as well. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_FORCE_INLINE __forceinline + +/** + * A macro to tag a function as never-returning. + * + * This is a hint to the compiler that a function does not return. An example + * of a function like this is the C runtime's exit() function. + * + * This hint can lead to code optimizations, and help analyzers understand + * code flow better. On compilers without noreturn support, this is defined to + * nothing. + * + * This symbol is used in SDL's headers, but apps and other libraries are + * welcome to use it for their own interfaces as well. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NORETURN __attribute__((noreturn)) + +/** + * A macro to tag a function as never-returning (for analysis purposes). + * + * This is almost identical to SDL_NORETURN, except functions marked with this + * _can_ actually return. The difference is that this isn't used for code + * generation, but rather static analyzers use this information to assume + * truths about program state and available code paths. Specifically, this tag + * is useful for writing an assertion mechanism. Indeed, SDL_assert uses this + * tag behind the scenes. Generally, apps that don't understand the specific + * use-case for this tag should avoid using it directly. + * + * On compilers without analyzer_noreturn support, this is defined to nothing. + * + * This symbol is used in SDL's headers, but apps and other libraries are + * welcome to use it for their own interfaces as well. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ANALYZER_NORETURN __attribute__((analyzer_noreturn)) + + +/** + * A macro to signal that a case statement without a `break` is intentional. + * + * C compilers have gotten more aggressive about warning when a switch's + * `case` block does not end with a `break` or other flow control statement, + * flowing into the next case's code, as this is a common accident that leads + * to strange bugs. But sometimes falling through to the next case is the + * correct and desired behavior. This symbol lets an app communicate this + * intention to the compiler, so it doesn't generate a warning. + * + * It is used like this: + * + * ```c + * switch (x) { + * case 1: + * DoSomethingOnlyForOne(); + * SDL_FALLTHROUGH; // tell the compiler this was intentional. + * case 2: + * DoSomethingForOneAndTwo(); + * break; + * } + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_FALLTHROUGH [[fallthrough]] + +/** + * A macro to tag a function's return value as critical. + * + * This is a hint to the compiler that a function's return value should not be + * ignored. + * + * If an NODISCARD function's return value is thrown away (the function is + * called as if it returns `void`), the compiler will issue a warning. + * + * While it's generally good practice to check return values for errors, often + * times legitimate programs do not for good reasons. Be careful about what + * functions are tagged as NODISCARD. It operates best when used on a function + * that's failure is surprising and catastrophic; a good example would be a + * program that checks the return values of all its file write function calls + * but not the call to close the file, which it assumes incorrectly never + * fails. + * + * Function callers that want to throw away a NODISCARD return value can call + * the function with a `(void)` cast, which informs the compiler the act is + * intentional. + * + * On compilers without nodiscard support, this is defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NODISCARD [[nodiscard]] + +/** + * A macro to tag a function as an allocator. + * + * This is a hint to the compiler that a function is an allocator, like + * malloc(), with certain rules. A description of how GCC treats this hint is + * here: + * + * https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-malloc-function-attribute + * + * On compilers without allocator tag support, this is defined to nothing. + * + * Most apps don't need to, and should not, use this directly. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_MALLOC __declspec(allocator) __desclspec(restrict) + +/** + * A macro to tag a function as returning a certain allocation. + * + * This is a hint to the compiler that a function allocates and returns a + * specific amount of memory based on one of its arguments. For example, the C + * runtime's malloc() function could use this macro with an argument of 1 + * (first argument to malloc is the size of the allocation). + * + * On compilers without alloc_size support, this is defined to nothing. + * + * Most apps don't need to, and should not, use this directly. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ALLOC_SIZE(p) __attribute__((alloc_size(p))) + +/** + * A macro to tag a pointer variable, to help with pointer aliasing. + * + * A good explanation of the restrict keyword is here: + * + * https://en.wikipedia.org/wiki/Restrict + * + * On compilers without restrict support, this is defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_RESTRICT __restrict__ + +/** + * Check if the compiler supports a given builtin functionality. + * + * This allows preprocessor checks for things that otherwise might fail to + * compile. + * + * Supported by virtually all clang versions and more-recent GCCs. Use this + * instead of checking the clang version if possible. + * + * On compilers without has_builtin support, this is defined to 0 (always + * false). + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_HAS_BUILTIN(x) __has_builtin(x) + +/* end of wiki documentation section. */ +#endif + +#ifndef SDL_HAS_BUILTIN +#ifdef __has_builtin +#define SDL_HAS_BUILTIN(x) __has_builtin(x) +#else +#define SDL_HAS_BUILTIN(x) 0 +#endif +#endif + +#ifndef SDL_DEPRECATED +# if defined(__GNUC__) && (__GNUC__ >= 4) /* technically, this arrived in gcc 3.1, but oh well. */ +# define SDL_DEPRECATED __attribute__((deprecated)) +# elif defined(_MSC_VER) +# define SDL_DEPRECATED __declspec(deprecated) +# else +# define SDL_DEPRECATED +# endif +#endif + +#ifndef SDL_UNUSED +# ifdef __GNUC__ +# define SDL_UNUSED __attribute__((unused)) +# else +# define SDL_UNUSED +# endif +#endif + +/* Some compilers use a special export keyword */ +#ifndef SDL_DECLSPEC +# if defined(SDL_PLATFORM_WINDOWS) +# ifdef DLL_EXPORT +# define SDL_DECLSPEC __declspec(dllexport) +# else +# define SDL_DECLSPEC +# endif +# else +# if defined(__GNUC__) && __GNUC__ >= 4 +# define SDL_DECLSPEC __attribute__ ((visibility("default"))) +# else +# define SDL_DECLSPEC +# endif +# endif +#endif + +/* By default SDL uses the C calling convention */ +#ifndef SDLCALL +#if defined(SDL_PLATFORM_WINDOWS) && !defined(__GNUC__) +#define SDLCALL __cdecl +#else +#define SDLCALL +#endif +#endif /* SDLCALL */ + +/* Force structure packing at 4 byte alignment. + This is necessary if the header is included in code which has structure + packing set to an alternate value, say for loading structures from disk. + The packing is reset to the previous value in SDL_close_code.h + */ +#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__) +#ifdef _MSC_VER +#pragma warning(disable: 4103) +#endif +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wpragma-pack" +#endif +#ifdef __BORLANDC__ +#pragma nopackwarning +#endif +#ifdef _WIN64 +/* Use 8-byte alignment on 64-bit architectures, so pointers are aligned */ +#pragma pack(push,8) +#else +#pragma pack(push,4) +#endif +#endif /* Compiler needs structure packing set */ + +#ifndef SDL_INLINE +#ifdef __GNUC__ +#define SDL_INLINE __inline__ +#elif defined(_MSC_VER) || defined(__BORLANDC__) || \ + defined(__DMC__) || defined(__SC__) || \ + defined(__WATCOMC__) || defined(__LCC__) || \ + defined(__DECC) || defined(__CC_ARM) +#define SDL_INLINE __inline +#ifndef __inline__ +#define __inline__ __inline +#endif +#else +#define SDL_INLINE inline +#ifndef __inline__ +#define __inline__ inline +#endif +#endif +#endif /* SDL_INLINE not defined */ + +#ifndef SDL_FORCE_INLINE +#ifdef _MSC_VER +#define SDL_FORCE_INLINE __forceinline +#elif ( (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) ) +#define SDL_FORCE_INLINE __attribute__((always_inline)) static __inline__ +#else +#define SDL_FORCE_INLINE static SDL_INLINE +#endif +#endif /* SDL_FORCE_INLINE not defined */ + +#ifndef SDL_NORETURN +#ifdef __GNUC__ +#define SDL_NORETURN __attribute__((noreturn)) +#elif defined(_MSC_VER) +#define SDL_NORETURN __declspec(noreturn) +#else +#define SDL_NORETURN +#endif +#endif /* SDL_NORETURN not defined */ + +#ifdef __clang__ +#if __has_feature(attribute_analyzer_noreturn) +#define SDL_ANALYZER_NORETURN __attribute__((analyzer_noreturn)) +#endif +#endif + +#ifndef SDL_ANALYZER_NORETURN +#define SDL_ANALYZER_NORETURN +#endif + +/* Apparently this is needed by several Windows compilers */ +#ifndef __MACH__ +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif /* NULL */ +#endif /* ! macOS - breaks precompiled headers */ + +#ifndef SDL_FALLTHROUGH +#if (defined(__cplusplus) && __cplusplus >= 201703L) || \ + (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202000L) +#define SDL_FALLTHROUGH [[fallthrough]] +#else +#if defined(__has_attribute) && !defined(__SUNPRO_C) && !defined(__SUNPRO_CC) +#define SDL_HAS_FALLTHROUGH __has_attribute(__fallthrough__) +#else +#define SDL_HAS_FALLTHROUGH 0 +#endif /* __has_attribute */ +#if SDL_HAS_FALLTHROUGH && \ + ((defined(__GNUC__) && __GNUC__ >= 7) || \ + (defined(__clang_major__) && __clang_major__ >= 10)) +#define SDL_FALLTHROUGH __attribute__((__fallthrough__)) +#else +#define SDL_FALLTHROUGH do {} while (0) /* fallthrough */ +#endif /* SDL_HAS_FALLTHROUGH */ +#undef SDL_HAS_FALLTHROUGH +#endif /* C++17 or C2x */ +#endif /* SDL_FALLTHROUGH not defined */ + +#ifndef SDL_NODISCARD +#if (defined(__cplusplus) && __cplusplus >= 201703L) || \ + (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) +#define SDL_NODISCARD [[nodiscard]] +#elif ( (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) ) +#define SDL_NODISCARD __attribute__((warn_unused_result)) +#elif defined(_MSC_VER) && (_MSC_VER >= 1700) +#define SDL_NODISCARD _Check_return_ +#else +#define SDL_NODISCARD +#endif /* C++17 or C23 */ +#endif /* SDL_NODISCARD not defined */ + +#ifndef SDL_MALLOC +#if defined(__GNUC__) && (__GNUC__ >= 3) +#define SDL_MALLOC __attribute__((malloc)) +/** FIXME +#elif defined(_MSC_VER) +#define SDL_MALLOC __declspec(allocator) __desclspec(restrict) +**/ +#else +#define SDL_MALLOC +#endif +#endif /* SDL_MALLOC not defined */ + +#ifndef SDL_ALLOC_SIZE +#if (defined(__clang__) && __clang_major__ >= 4) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) +#define SDL_ALLOC_SIZE(p) __attribute__((alloc_size(p))) +#elif defined(_MSC_VER) +#define SDL_ALLOC_SIZE(p) +#else +#define SDL_ALLOC_SIZE(p) +#endif +#endif /* SDL_ALLOC_SIZE not defined */ + +#ifndef SDL_ALLOC_SIZE2 +#if (defined(__clang__) && __clang_major__ >= 4) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) +#define SDL_ALLOC_SIZE2(p1, p2) __attribute__((alloc_size(p1, p2))) +#elif defined(_MSC_VER) +#define SDL_ALLOC_SIZE2(p1, p2) +#else +#define SDL_ALLOC_SIZE2(p1, p2) +#endif +#endif /* SDL_ALLOC_SIZE2 not defined */ diff --git a/thirdparty/sdl/include/SDL3/SDL_bits.h b/thirdparty/sdl/include/SDL3/SDL_bits.h new file mode 100644 index 00000000000..7435ce6d939 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_bits.h @@ -0,0 +1,147 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryBits + * + * Functions for fiddling with bits and bitmasks. + */ + +#ifndef SDL_bits_h_ +#define SDL_bits_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(__WATCOMC__) && defined(__386__) +extern __inline int _SDL_bsr_watcom(Uint32); +#pragma aux _SDL_bsr_watcom = \ + "bsr eax, eax" \ + parm [eax] nomemory \ + value [eax] \ + modify exact [eax] nomemory; +#endif + +/** + * Get the index of the most significant (set) bit in a 32-bit number. + * + * Result is undefined when called with 0. This operation can also be stated + * as "count leading zeroes" and "log base 2". + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param x the 32-bit value to examine. + * \returns the index of the most significant bit, or -1 if the value is 0. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE int SDL_MostSignificantBitIndex32(Uint32 x) +{ +#if defined(__GNUC__) && (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) + /* Count Leading Zeroes builtin in GCC. + * http://gcc.gnu.org/onlinedocs/gcc-4.3.4/gcc/Other-Builtins.html + */ + if (x == 0) { + return -1; + } + return 31 - __builtin_clz(x); +#elif defined(__WATCOMC__) && defined(__386__) + if (x == 0) { + return -1; + } + return _SDL_bsr_watcom(x); +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + unsigned long index; + if (_BitScanReverse(&index, x)) { + return (int)index; + } + return -1; +#else + /* Based off of Bit Twiddling Hacks by Sean Eron Anderson + * , released in the public domain. + * http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog + */ + const Uint32 b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000}; + const int S[] = {1, 2, 4, 8, 16}; + + int msbIndex = 0; + int i; + + if (x == 0) { + return -1; + } + + for (i = 4; i >= 0; i--) + { + if (x & b[i]) + { + x >>= S[i]; + msbIndex |= S[i]; + } + } + + return msbIndex; +#endif +} + +/** + * Determine if a unsigned 32-bit value has exactly one bit set. + * + * If there are no bits set (`x` is zero), or more than one bit set, this + * returns false. If any one bit is exclusively set, this returns true. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param x the 32-bit value to examine. + * \returns true if exactly one bit is set in `x`, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE bool SDL_HasExactlyOneBitSet32(Uint32 x) +{ + if (x && !(x & (x - 1))) { + return true; + } + return false; +} + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_bits_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_blendmode.h b/thirdparty/sdl/include/SDL3/SDL_blendmode.h new file mode 100644 index 00000000000..8f00cbcafb0 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_blendmode.h @@ -0,0 +1,202 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryBlendmode + * + * Blend modes decide how two colors will mix together. There are both + * standard modes for basic needs and a means to create custom modes, + * dictating what sort of math to do on what color components. + */ + +#ifndef SDL_blendmode_h_ +#define SDL_blendmode_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A set of blend modes used in drawing operations. + * + * These predefined blend modes are supported everywhere. + * + * Additional values may be obtained from SDL_ComposeCustomBlendMode. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_ComposeCustomBlendMode + */ +typedef Uint32 SDL_BlendMode; + +#define SDL_BLENDMODE_NONE 0x00000000u /**< no blending: dstRGBA = srcRGBA */ +#define SDL_BLENDMODE_BLEND 0x00000001u /**< alpha blending: dstRGB = (srcRGB * srcA) + (dstRGB * (1-srcA)), dstA = srcA + (dstA * (1-srcA)) */ +#define SDL_BLENDMODE_BLEND_PREMULTIPLIED 0x00000010u /**< pre-multiplied alpha blending: dstRGBA = srcRGBA + (dstRGBA * (1-srcA)) */ +#define SDL_BLENDMODE_ADD 0x00000002u /**< additive blending: dstRGB = (srcRGB * srcA) + dstRGB, dstA = dstA */ +#define SDL_BLENDMODE_ADD_PREMULTIPLIED 0x00000020u /**< pre-multiplied additive blending: dstRGB = srcRGB + dstRGB, dstA = dstA */ +#define SDL_BLENDMODE_MOD 0x00000004u /**< color modulate: dstRGB = srcRGB * dstRGB, dstA = dstA */ +#define SDL_BLENDMODE_MUL 0x00000008u /**< color multiply: dstRGB = (srcRGB * dstRGB) + (dstRGB * (1-srcA)), dstA = dstA */ +#define SDL_BLENDMODE_INVALID 0x7FFFFFFFu + +/** + * The blend operation used when combining source and destination pixel + * components. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_BlendOperation +{ + SDL_BLENDOPERATION_ADD = 0x1, /**< dst + src: supported by all renderers */ + SDL_BLENDOPERATION_SUBTRACT = 0x2, /**< src - dst : supported by D3D, OpenGL, OpenGLES, and Vulkan */ + SDL_BLENDOPERATION_REV_SUBTRACT = 0x3, /**< dst - src : supported by D3D, OpenGL, OpenGLES, and Vulkan */ + SDL_BLENDOPERATION_MINIMUM = 0x4, /**< min(dst, src) : supported by D3D, OpenGL, OpenGLES, and Vulkan */ + SDL_BLENDOPERATION_MAXIMUM = 0x5 /**< max(dst, src) : supported by D3D, OpenGL, OpenGLES, and Vulkan */ +} SDL_BlendOperation; + +/** + * The normalized factor used to multiply pixel components. + * + * The blend factors are multiplied with the pixels from a drawing operation + * (src) and the pixels from the render target (dst) before the blend + * operation. The comma-separated factors listed above are always applied in + * the component order red, green, blue, and alpha. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_BlendFactor +{ + SDL_BLENDFACTOR_ZERO = 0x1, /**< 0, 0, 0, 0 */ + SDL_BLENDFACTOR_ONE = 0x2, /**< 1, 1, 1, 1 */ + SDL_BLENDFACTOR_SRC_COLOR = 0x3, /**< srcR, srcG, srcB, srcA */ + SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = 0x4, /**< 1-srcR, 1-srcG, 1-srcB, 1-srcA */ + SDL_BLENDFACTOR_SRC_ALPHA = 0x5, /**< srcA, srcA, srcA, srcA */ + SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = 0x6, /**< 1-srcA, 1-srcA, 1-srcA, 1-srcA */ + SDL_BLENDFACTOR_DST_COLOR = 0x7, /**< dstR, dstG, dstB, dstA */ + SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = 0x8, /**< 1-dstR, 1-dstG, 1-dstB, 1-dstA */ + SDL_BLENDFACTOR_DST_ALPHA = 0x9, /**< dstA, dstA, dstA, dstA */ + SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = 0xA /**< 1-dstA, 1-dstA, 1-dstA, 1-dstA */ +} SDL_BlendFactor; + +/** + * Compose a custom blend mode for renderers. + * + * The functions SDL_SetRenderDrawBlendMode and SDL_SetTextureBlendMode accept + * the SDL_BlendMode returned by this function if the renderer supports it. + * + * A blend mode controls how the pixels from a drawing operation (source) get + * combined with the pixels from the render target (destination). First, the + * components of the source and destination pixels get multiplied with their + * blend factors. Then, the blend operation takes the two products and + * calculates the result that will get stored in the render target. + * + * Expressed in pseudocode, it would look like this: + * + * ```c + * dstRGB = colorOperation(srcRGB * srcColorFactor, dstRGB * dstColorFactor); + * dstA = alphaOperation(srcA * srcAlphaFactor, dstA * dstAlphaFactor); + * ``` + * + * Where the functions `colorOperation(src, dst)` and `alphaOperation(src, + * dst)` can return one of the following: + * + * - `src + dst` + * - `src - dst` + * - `dst - src` + * - `min(src, dst)` + * - `max(src, dst)` + * + * The red, green, and blue components are always multiplied with the first, + * second, and third components of the SDL_BlendFactor, respectively. The + * fourth component is not used. + * + * The alpha component is always multiplied with the fourth component of the + * SDL_BlendFactor. The other components are not used in the alpha + * calculation. + * + * Support for these blend modes varies for each renderer. To check if a + * specific SDL_BlendMode is supported, create a renderer and pass it to + * either SDL_SetRenderDrawBlendMode or SDL_SetTextureBlendMode. They will + * return with an error if the blend mode is not supported. + * + * This list describes the support of custom blend modes for each renderer. + * All renderers support the four blend modes listed in the SDL_BlendMode + * enumeration. + * + * - **direct3d**: Supports all operations with all factors. However, some + * factors produce unexpected results with `SDL_BLENDOPERATION_MINIMUM` and + * `SDL_BLENDOPERATION_MAXIMUM`. + * - **direct3d11**: Same as Direct3D 9. + * - **opengl**: Supports the `SDL_BLENDOPERATION_ADD` operation with all + * factors. OpenGL versions 1.1, 1.2, and 1.3 do not work correctly here. + * - **opengles2**: Supports the `SDL_BLENDOPERATION_ADD`, + * `SDL_BLENDOPERATION_SUBTRACT`, `SDL_BLENDOPERATION_REV_SUBTRACT` + * operations with all factors. + * - **psp**: No custom blend mode support. + * - **software**: No custom blend mode support. + * + * Some renderers do not provide an alpha component for the default render + * target. The `SDL_BLENDFACTOR_DST_ALPHA` and + * `SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA` factors do not have an effect in this + * case. + * + * \param srcColorFactor the SDL_BlendFactor applied to the red, green, and + * blue components of the source pixels. + * \param dstColorFactor the SDL_BlendFactor applied to the red, green, and + * blue components of the destination pixels. + * \param colorOperation the SDL_BlendOperation used to combine the red, + * green, and blue components of the source and + * destination pixels. + * \param srcAlphaFactor the SDL_BlendFactor applied to the alpha component of + * the source pixels. + * \param dstAlphaFactor the SDL_BlendFactor applied to the alpha component of + * the destination pixels. + * \param alphaOperation the SDL_BlendOperation used to combine the alpha + * component of the source and destination pixels. + * \returns an SDL_BlendMode that represents the chosen factors and + * operations. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_GetRenderDrawBlendMode + * \sa SDL_SetTextureBlendMode + * \sa SDL_GetTextureBlendMode + */ +extern SDL_DECLSPEC SDL_BlendMode SDLCALL SDL_ComposeCustomBlendMode(SDL_BlendFactor srcColorFactor, + SDL_BlendFactor dstColorFactor, + SDL_BlendOperation colorOperation, + SDL_BlendFactor srcAlphaFactor, + SDL_BlendFactor dstAlphaFactor, + SDL_BlendOperation alphaOperation); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_blendmode_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_camera.h b/thirdparty/sdl/include/SDL3/SDL_camera.h new file mode 100644 index 00000000000..5f3911fdf96 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_camera.h @@ -0,0 +1,519 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryCamera + * + * Video capture for the SDL library. + * + * This API lets apps read input from video sources, like webcams. Camera + * devices can be enumerated, queried, and opened. Once opened, it will + * provide SDL_Surface objects as new frames of video come in. These surfaces + * can be uploaded to an SDL_Texture or processed as pixels in memory. + * + * Several platforms will alert the user if an app tries to access a camera, + * and some will present a UI asking the user if your application should be + * allowed to obtain images at all, which they can deny. A successfully opened + * camera will not provide images until permission is granted. Applications, + * after opening a camera device, can see if they were granted access by + * either polling with the SDL_GetCameraPermissionState() function, or waiting + * for an SDL_EVENT_CAMERA_DEVICE_APPROVED or SDL_EVENT_CAMERA_DEVICE_DENIED + * event. Platforms that don't have any user approval process will report + * approval immediately. + * + * Note that SDL cameras only provide video as individual frames; they will + * not provide full-motion video encoded in a movie file format, although an + * app is free to encode the acquired frames into any format it likes. It also + * does not provide audio from the camera hardware through this API; not only + * do many webcams not have microphones at all, many people--from streamers to + * people on Zoom calls--will want to use a separate microphone regardless of + * the camera. In any case, recorded audio will be available through SDL's + * audio API no matter what hardware provides the microphone. + * + * ## Camera gotchas + * + * Consumer-level camera hardware tends to take a little while to warm up, + * once the device has been opened. Generally most camera apps have some sort + * of UI to take a picture (a button to snap a pic while a preview is showing, + * some sort of multi-second countdown for the user to pose, like a photo + * booth), which puts control in the users' hands, or they are intended to + * stay on for long times (Pokemon Go, etc). + * + * It's not uncommon that a newly-opened camera will provide a couple of + * completely black frames, maybe followed by some under-exposed images. If + * taking a single frame automatically, or recording video from a camera's + * input without the user initiating it from a preview, it could be wise to + * drop the first several frames (if not the first several _seconds_ worth of + * frames!) before using images from a camera. + */ + +#ifndef SDL_camera_h_ +#define SDL_camera_h_ + +#include +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * This is a unique ID for a camera device for the time it is connected to the + * system, and is never reused for the lifetime of the application. + * + * If the device is disconnected and reconnected, it will get a new ID. + * + * The value 0 is an invalid ID. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_GetCameras + */ +typedef Uint32 SDL_CameraID; + +/** + * The opaque structure used to identify an opened SDL camera. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Camera SDL_Camera; + +/** + * The details of an output format for a camera device. + * + * Cameras often support multiple formats; each one will be encapsulated in + * this struct. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_GetCameraSupportedFormats + * \sa SDL_GetCameraFormat + */ +typedef struct SDL_CameraSpec +{ + SDL_PixelFormat format; /**< Frame format */ + SDL_Colorspace colorspace; /**< Frame colorspace */ + int width; /**< Frame width */ + int height; /**< Frame height */ + int framerate_numerator; /**< Frame rate numerator ((num / denom) == FPS, (denom / num) == duration in seconds) */ + int framerate_denominator; /**< Frame rate demoninator ((num / denom) == FPS, (denom / num) == duration in seconds) */ +} SDL_CameraSpec; + +/** + * The position of camera in relation to system device. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_GetCameraPosition + */ +typedef enum SDL_CameraPosition +{ + SDL_CAMERA_POSITION_UNKNOWN, + SDL_CAMERA_POSITION_FRONT_FACING, + SDL_CAMERA_POSITION_BACK_FACING +} SDL_CameraPosition; + + +/** + * Use this function to get the number of built-in camera drivers. + * + * This function returns a hardcoded number. This never returns a negative + * value; if there are no drivers compiled into this build of SDL, this + * function returns zero. The presence of a driver in this list does not mean + * it will function, it just means SDL is capable of interacting with that + * interface. For example, a build of SDL might have v4l2 support, but if + * there's no kernel support available, SDL's v4l2 driver would fail if used. + * + * By default, SDL tries all drivers, in its preferred order, until one is + * found to be usable. + * + * \returns the number of built-in camera drivers. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetCameraDriver + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumCameraDrivers(void); + +/** + * Use this function to get the name of a built in camera driver. + * + * The list of camera drivers is given in the order that they are normally + * initialized by default; the drivers that seem more reasonable to choose + * first (as far as the SDL developers believe) are earlier in the list. + * + * The names of drivers are all simple, low-ASCII identifiers, like "v4l2", + * "coremedia" or "android". These never have Unicode characters, and are not + * meant to be proper names. + * + * \param index the index of the camera driver; the value ranges from 0 to + * SDL_GetNumCameraDrivers() - 1. + * \returns the name of the camera driver at the requested index, or NULL if + * an invalid index was specified. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumCameraDrivers + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetCameraDriver(int index); + +/** + * Get the name of the current camera driver. + * + * The names of drivers are all simple, low-ASCII identifiers, like "v4l2", + * "coremedia" or "android". These never have Unicode characters, and are not + * meant to be proper names. + * + * \returns the name of the current camera driver or NULL if no driver has + * been initialized. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetCurrentCameraDriver(void); + +/** + * Get a list of currently connected camera devices. + * + * \param count a pointer filled in with the number of cameras returned, may + * be NULL. + * \returns a 0 terminated array of camera instance IDs or NULL on failure; + * call SDL_GetError() for more information. This should be freed + * with SDL_free() when it is no longer needed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenCamera + */ +extern SDL_DECLSPEC SDL_CameraID * SDLCALL SDL_GetCameras(int *count); + +/** + * Get the list of native formats/sizes a camera supports. + * + * This returns a list of all formats and frame sizes that a specific camera + * can offer. This is useful if your app can accept a variety of image formats + * and sizes and so want to find the optimal spec that doesn't require + * conversion. + * + * This function isn't strictly required; if you call SDL_OpenCamera with a + * NULL spec, SDL will choose a native format for you, and if you instead + * specify a desired format, it will transparently convert to the requested + * format on your behalf. + * + * If `count` is not NULL, it will be filled with the number of elements in + * the returned array. + * + * Note that it's legal for a camera to supply an empty list. This is what + * will happen on Emscripten builds, since that platform won't tell _anything_ + * about available cameras until you've opened one, and won't even tell if + * there _is_ a camera until the user has given you permission to check + * through a scary warning popup. + * + * \param instance_id the camera device instance ID. + * \param count a pointer filled in with the number of elements in the list, + * may be NULL. + * \returns a NULL terminated array of pointers to SDL_CameraSpec or NULL on + * failure; call SDL_GetError() for more information. This is a + * single allocation that should be freed with SDL_free() when it is + * no longer needed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetCameras + * \sa SDL_OpenCamera + */ +extern SDL_DECLSPEC SDL_CameraSpec ** SDLCALL SDL_GetCameraSupportedFormats(SDL_CameraID instance_id, int *count); + +/** + * Get the human-readable device name for a camera. + * + * \param instance_id the camera device instance ID. + * \returns a human-readable device name or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetCameras + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetCameraName(SDL_CameraID instance_id); + +/** + * Get the position of the camera in relation to the system. + * + * Most platforms will report UNKNOWN, but mobile devices, like phones, can + * often make a distinction between cameras on the front of the device (that + * points towards the user, for taking "selfies") and cameras on the back (for + * filming in the direction the user is facing). + * + * \param instance_id the camera device instance ID. + * \returns the position of the camera on the system hardware. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetCameras + */ +extern SDL_DECLSPEC SDL_CameraPosition SDLCALL SDL_GetCameraPosition(SDL_CameraID instance_id); + +/** + * Open a video recording device (a "camera"). + * + * You can open the device with any reasonable spec, and if the hardware can't + * directly support it, it will convert data seamlessly to the requested + * format. This might incur overhead, including scaling of image data. + * + * If you would rather accept whatever format the device offers, you can pass + * a NULL spec here and it will choose one for you (and you can use + * SDL_Surface's conversion/scaling functions directly if necessary). + * + * You can call SDL_GetCameraFormat() to get the actual data format if passing + * a NULL spec here. You can see the exact specs a device can support without + * conversion with SDL_GetCameraSupportedFormats(). + * + * SDL will not attempt to emulate framerate; it will try to set the hardware + * to the rate closest to the requested speed, but it won't attempt to limit + * or duplicate frames artificially; call SDL_GetCameraFormat() to see the + * actual framerate of the opened the device, and check your timestamps if + * this is crucial to your app! + * + * Note that the camera is not usable until the user approves its use! On some + * platforms, the operating system will prompt the user to permit access to + * the camera, and they can choose Yes or No at that point. Until they do, the + * camera will not be usable. The app should either wait for an + * SDL_EVENT_CAMERA_DEVICE_APPROVED (or SDL_EVENT_CAMERA_DEVICE_DENIED) event, + * or poll SDL_GetCameraPermissionState() occasionally until it returns + * non-zero. On platforms that don't require explicit user approval (and + * perhaps in places where the user previously permitted access), the approval + * event might come immediately, but it might come seconds, minutes, or hours + * later! + * + * \param instance_id the camera device instance ID. + * \param spec the desired format for data the device will provide. Can be + * NULL. + * \returns an SDL_Camera object or NULL on failure; call SDL_GetError() for + * more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetCameras + * \sa SDL_GetCameraFormat + */ +extern SDL_DECLSPEC SDL_Camera * SDLCALL SDL_OpenCamera(SDL_CameraID instance_id, const SDL_CameraSpec *spec); + +/** + * Query if camera access has been approved by the user. + * + * Cameras will not function between when the device is opened by the app and + * when the user permits access to the hardware. On some platforms, this + * presents as a popup dialog where the user has to explicitly approve access; + * on others the approval might be implicit and not alert the user at all. + * + * This function can be used to check the status of that approval. It will + * return 0 if still waiting for user response, 1 if the camera is approved + * for use, and -1 if the user denied access. + * + * Instead of polling with this function, you can wait for a + * SDL_EVENT_CAMERA_DEVICE_APPROVED (or SDL_EVENT_CAMERA_DEVICE_DENIED) event + * in the standard SDL event loop, which is guaranteed to be sent once when + * permission to use the camera is decided. + * + * If a camera is declined, there's nothing to be done but call + * SDL_CloseCamera() to dispose of it. + * + * \param camera the opened camera device to query. + * \returns -1 if user denied access to the camera, 1 if user approved access, + * 0 if no decision has been made yet. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenCamera + * \sa SDL_CloseCamera + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetCameraPermissionState(SDL_Camera *camera); + +/** + * Get the instance ID of an opened camera. + * + * \param camera an SDL_Camera to query. + * \returns the instance ID of the specified camera on success or 0 on + * failure; call SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenCamera + */ +extern SDL_DECLSPEC SDL_CameraID SDLCALL SDL_GetCameraID(SDL_Camera *camera); + +/** + * Get the properties associated with an opened camera. + * + * \param camera the SDL_Camera obtained from SDL_OpenCamera(). + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetCameraProperties(SDL_Camera *camera); + +/** + * Get the spec that a camera is using when generating images. + * + * Note that this might not be the native format of the hardware, as SDL might + * be converting to this format behind the scenes. + * + * If the system is waiting for the user to approve access to the camera, as + * some platforms require, this will return false, but this isn't necessarily + * a fatal error; you should either wait for an + * SDL_EVENT_CAMERA_DEVICE_APPROVED (or SDL_EVENT_CAMERA_DEVICE_DENIED) event, + * or poll SDL_GetCameraPermissionState() occasionally until it returns + * non-zero. + * + * \param camera opened camera device. + * \param spec the SDL_CameraSpec to be initialized by this function. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenCamera + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetCameraFormat(SDL_Camera *camera, SDL_CameraSpec *spec); + +/** + * Acquire a frame. + * + * The frame is a memory pointer to the image data, whose size and format are + * given by the spec requested when opening the device. + * + * This is a non blocking API. If there is a frame available, a non-NULL + * surface is returned, and timestampNS will be filled with a non-zero value. + * + * Note that an error case can also return NULL, but a NULL by itself is + * normal and just signifies that a new frame is not yet available. Note that + * even if a camera device fails outright (a USB camera is unplugged while in + * use, etc), SDL will send an event separately to notify the app, but + * continue to provide blank frames at ongoing intervals until + * SDL_CloseCamera() is called, so real failure here is almost always an out + * of memory condition. + * + * After use, the frame should be released with SDL_ReleaseCameraFrame(). If + * you don't do this, the system may stop providing more video! + * + * Do not call SDL_DestroySurface() on the returned surface! It must be given + * back to the camera subsystem with SDL_ReleaseCameraFrame! + * + * If the system is waiting for the user to approve access to the camera, as + * some platforms require, this will return NULL (no frames available); you + * should either wait for an SDL_EVENT_CAMERA_DEVICE_APPROVED (or + * SDL_EVENT_CAMERA_DEVICE_DENIED) event, or poll + * SDL_GetCameraPermissionState() occasionally until it returns non-zero. + * + * \param camera opened camera device. + * \param timestampNS a pointer filled in with the frame's timestamp, or 0 on + * error. Can be NULL. + * \returns a new frame of video on success, NULL if none is currently + * available. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ReleaseCameraFrame + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_AcquireCameraFrame(SDL_Camera *camera, Uint64 *timestampNS); + +/** + * Release a frame of video acquired from a camera. + * + * Let the back-end re-use the internal buffer for camera. + * + * This function _must_ be called only on surface objects returned by + * SDL_AcquireCameraFrame(). This function should be called as quickly as + * possible after acquisition, as SDL keeps a small FIFO queue of surfaces for + * video frames; if surfaces aren't released in a timely manner, SDL may drop + * upcoming video frames from the camera. + * + * If the app needs to keep the surface for a significant time, they should + * make a copy of it and release the original. + * + * The app should not use the surface again after calling this function; + * assume the surface is freed and the pointer is invalid. + * + * \param camera opened camera device. + * \param frame the video frame surface to release. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AcquireCameraFrame + */ +extern SDL_DECLSPEC void SDLCALL SDL_ReleaseCameraFrame(SDL_Camera *camera, SDL_Surface *frame); + +/** + * Use this function to shut down camera processing and close the camera + * device. + * + * \param camera opened camera device. + * + * \threadsafety It is safe to call this function from any thread, but no + * thread may reference `device` once this function is called. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenCamera + */ +extern SDL_DECLSPEC void SDLCALL SDL_CloseCamera(SDL_Camera *camera); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_camera_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_clipboard.h b/thirdparty/sdl/include/SDL3/SDL_clipboard.h new file mode 100644 index 00000000000..0d3cbb499b1 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_clipboard.h @@ -0,0 +1,331 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryClipboard + * + * SDL provides access to the system clipboard, both for reading information + * from other processes and publishing information of its own. + * + * This is not just text! SDL apps can access and publish data by mimetype. + * + * ## Basic use (text) + * + * Obtaining and publishing simple text to the system clipboard is as easy as + * calling SDL_GetClipboardText() and SDL_SetClipboardText(), respectively. + * These deal with C strings in UTF-8 encoding. Data transmission and encoding + * conversion is completely managed by SDL. + * + * ## Clipboard callbacks (data other than text) + * + * Things get more complicated when the clipboard contains something other + * than text. Not only can the system clipboard contain data of any type, in + * some cases it can contain the same data in different formats! For example, + * an image painting app might let the user copy a graphic to the clipboard, + * and offers it in .BMP, .JPG, or .PNG format for other apps to consume. + * + * Obtaining clipboard data ("pasting") like this is a matter of calling + * SDL_GetClipboardData() and telling it the mimetype of the data you want. + * But how does one know if that format is available? SDL_HasClipboardData() + * can report if a specific mimetype is offered, and + * SDL_GetClipboardMimeTypes() can provide the entire list of mimetypes + * available, so the app can decide what to do with the data and what formats + * it can support. + * + * Setting the clipboard ("copying") to arbitrary data is done with + * SDL_SetClipboardData. The app does not provide the data in this call, but + * rather the mimetypes it is willing to provide and a callback function. + * During the callback, the app will generate the data. This allows massive + * data sets to be provided to the clipboard, without any data being copied + * before it is explicitly requested. More specifically, it allows an app to + * offer data in multiple formats without providing a copy of all of them + * upfront. If the app has an image that it could provide in PNG or JPG + * format, it doesn't have to encode it to either of those unless and until + * something tries to paste it. + * + * ## Primary Selection + * + * The X11 and Wayland video targets have a concept of the "primary selection" + * in addition to the usual clipboard. This is generally highlighted (but not + * explicitly copied) text from various apps. SDL offers APIs for this through + * SDL_GetPrimarySelectionText() and SDL_SetPrimarySelectionText(). SDL offers + * these APIs on platforms without this concept, too, but only so far that it + * will keep a copy of a string that the app sets for later retrieval; the + * operating system will not ever attempt to change the string externally if + * it doesn't support a primary selection. + */ + +#ifndef SDL_clipboard_h_ +#define SDL_clipboard_h_ + +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* Function prototypes */ + +/** + * Put UTF-8 text into the clipboard. + * + * \param text the text to store in the clipboard. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetClipboardText + * \sa SDL_HasClipboardText + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetClipboardText(const char *text); + +/** + * Get UTF-8 text from the clipboard. + * + * This functions returns an empty string if there was not enough memory left + * for a copy of the clipboard's content. + * + * \returns the clipboard text on success or an empty string on failure; call + * SDL_GetError() for more information. This should be freed with + * SDL_free() when it is no longer needed. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasClipboardText + * \sa SDL_SetClipboardText + */ +extern SDL_DECLSPEC char * SDLCALL SDL_GetClipboardText(void); + +/** + * Query whether the clipboard exists and contains a non-empty text string. + * + * \returns true if the clipboard has text, or false if it does not. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetClipboardText + * \sa SDL_SetClipboardText + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasClipboardText(void); + +/** + * Put UTF-8 text into the primary selection. + * + * \param text the text to store in the primary selection. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPrimarySelectionText + * \sa SDL_HasPrimarySelectionText + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetPrimarySelectionText(const char *text); + +/** + * Get UTF-8 text from the primary selection. + * + * This functions returns an empty string if there was not enough memory left + * for a copy of the primary selection's content. + * + * \returns the primary selection text on success or an empty string on + * failure; call SDL_GetError() for more information. This should be + * freed with SDL_free() when it is no longer needed. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasPrimarySelectionText + * \sa SDL_SetPrimarySelectionText + */ +extern SDL_DECLSPEC char * SDLCALL SDL_GetPrimarySelectionText(void); + +/** + * Query whether the primary selection exists and contains a non-empty text + * string. + * + * \returns true if the primary selection has text, or false if it does not. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPrimarySelectionText + * \sa SDL_SetPrimarySelectionText + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasPrimarySelectionText(void); + +/** + * Callback function that will be called when data for the specified mime-type + * is requested by the OS. + * + * The callback function is called with NULL as the mime_type when the + * clipboard is cleared or new data is set. The clipboard is automatically + * cleared in SDL_Quit(). + * + * \param userdata a pointer to provided user data. + * \param mime_type the requested mime-type. + * \param size a pointer filled in with the length of the returned data. + * \returns a pointer to the data for the provided mime-type. Returning NULL + * or setting length to 0 will cause no data to be sent to the + * "receiver". It is up to the receiver to handle this. Essentially + * returning no data is more or less undefined behavior and may cause + * breakage in receiving applications. The returned data will not be + * freed so it needs to be retained and dealt with internally. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetClipboardData + */ +typedef const void *(SDLCALL *SDL_ClipboardDataCallback)(void *userdata, const char *mime_type, size_t *size); + +/** + * Callback function that will be called when the clipboard is cleared, or new + * data is set. + * + * \param userdata a pointer to provided user data. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetClipboardData + */ +typedef void (SDLCALL *SDL_ClipboardCleanupCallback)(void *userdata); + +/** + * Offer clipboard data to the OS. + * + * Tell the operating system that the application is offering clipboard data + * for each of the provided mime-types. Once another application requests the + * data the callback function will be called, allowing it to generate and + * respond with the data for the requested mime-type. + * + * The size of text data does not include any terminator, and the text does + * not need to be null terminated (e.g. you can directly copy a portion of a + * document). + * + * \param callback a function pointer to the function that provides the + * clipboard data. + * \param cleanup a function pointer to the function that cleans up the + * clipboard data. + * \param userdata an opaque pointer that will be forwarded to the callbacks. + * \param mime_types a list of mime-types that are being offered. + * \param num_mime_types the number of mime-types in the mime_types list. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ClearClipboardData + * \sa SDL_GetClipboardData + * \sa SDL_HasClipboardData + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetClipboardData(SDL_ClipboardDataCallback callback, SDL_ClipboardCleanupCallback cleanup, void *userdata, const char **mime_types, size_t num_mime_types); + +/** + * Clear the clipboard data. + * + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetClipboardData + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ClearClipboardData(void); + +/** + * Get the data from clipboard for a given mime type. + * + * The size of text data does not include the terminator, but the text is + * guaranteed to be null terminated. + * + * \param mime_type the mime type to read from the clipboard. + * \param size a pointer filled in with the length of the returned data. + * \returns the retrieved data buffer or NULL on failure; call SDL_GetError() + * for more information. This should be freed with SDL_free() when it + * is no longer needed. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasClipboardData + * \sa SDL_SetClipboardData + */ +extern SDL_DECLSPEC void * SDLCALL SDL_GetClipboardData(const char *mime_type, size_t *size); + +/** + * Query whether there is data in the clipboard for the provided mime type. + * + * \param mime_type the mime type to check for data for. + * \returns true if there exists data in clipboard for the provided mime type, + * false if it does not. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetClipboardData + * \sa SDL_GetClipboardData + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasClipboardData(const char *mime_type); + +/** + * Retrieve the list of mime types available in the clipboard. + * + * \param num_mime_types a pointer filled with the number of mime types, may + * be NULL. + * \returns a null terminated array of strings with mime types, or NULL on + * failure; call SDL_GetError() for more information. This should be + * freed with SDL_free() when it is no longer needed. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetClipboardData + */ +extern SDL_DECLSPEC char ** SDLCALL SDL_GetClipboardMimeTypes(size_t *num_mime_types); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_clipboard_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_close_code.h b/thirdparty/sdl/include/SDL3/SDL_close_code.h new file mode 100644 index 00000000000..da1dea7fac0 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_close_code.h @@ -0,0 +1,41 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * This file reverses the effects of SDL_begin_code.h and should be included + * after you finish any function and structure declarations in your headers. + * + * SDL's headers use this; applications generally should not include this + * header directly. + */ + +#ifndef SDL_begin_code_h +#error SDL_close_code.h included without matching SDL_begin_code.h +#endif +#undef SDL_begin_code_h + +/* Reset structure packing at previous byte alignment */ +#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__) +#ifdef __BORLANDC__ +#pragma nopackwarning +#endif +#pragma pack(pop) +#endif /* Compiler needs structure packing set */ diff --git a/thirdparty/sdl/include/SDL3/SDL_copying.h b/thirdparty/sdl/include/SDL3/SDL_copying.h new file mode 100644 index 00000000000..747bd357008 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_copying.h @@ -0,0 +1,22 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* Header file containing SDL's license. */ diff --git a/thirdparty/sdl/include/SDL3/SDL_cpuinfo.h b/thirdparty/sdl/include/SDL3/SDL_cpuinfo.h new file mode 100644 index 00000000000..1745bd93490 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_cpuinfo.h @@ -0,0 +1,353 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: CPUInfo */ + +/** + * # CategoryCPUInfo + * + * CPU feature detection for SDL. + * + * These functions are largely concerned with reporting if the system has + * access to various SIMD instruction sets, but also has other important info + * to share, such as system RAM size and number of logical CPU cores. + * + * CPU instruction set checks, like SDL_HasSSE() and SDL_HasNEON(), are + * available on all platforms, even if they don't make sense (an ARM processor + * will never have SSE and an x86 processor will never have NEON, for example, + * but these functions still exist and will simply return false in these + * cases). + */ + +#ifndef SDL_cpuinfo_h_ +#define SDL_cpuinfo_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A guess for the cacheline size used for padding. + * + * Most x86 processors have a 64 byte cache line. The 64-bit PowerPC + * processors have a 128 byte cache line. We use the larger value to be + * generally safe. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_CACHELINE_SIZE 128 + +/** + * Get the number of logical CPU cores available. + * + * \returns the total number of logical CPU cores. On CPUs that include + * technologies such as hyperthreading, the number of logical cores + * may be more than the number of physical cores. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumLogicalCPUCores(void); + +/** + * Determine the L1 cache line size of the CPU. + * + * This is useful for determining multi-threaded structure padding or SIMD + * prefetch sizes. + * + * \returns the L1 cache line size of the CPU, in bytes. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetCPUCacheLineSize(void); + +/** + * Determine whether the CPU has AltiVec features. + * + * This always returns false on CPUs that aren't using PowerPC instruction + * sets. + * + * \returns true if the CPU has AltiVec features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasAltiVec(void); + +/** + * Determine whether the CPU has MMX features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns true if the CPU has MMX features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasMMX(void); + +/** + * Determine whether the CPU has SSE features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns true if the CPU has SSE features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasSSE(void); + +/** + * Determine whether the CPU has SSE2 features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns true if the CPU has SSE2 features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasSSE + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasSSE2(void); + +/** + * Determine whether the CPU has SSE3 features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns true if the CPU has SSE3 features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasSSE3(void); + +/** + * Determine whether the CPU has SSE4.1 features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns true if the CPU has SSE4.1 features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE42 + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasSSE41(void); + +/** + * Determine whether the CPU has SSE4.2 features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns true if the CPU has SSE4.2 features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasSSE42(void); + +/** + * Determine whether the CPU has AVX features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns true if the CPU has AVX features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasAVX2 + * \sa SDL_HasAVX512F + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasAVX(void); + +/** + * Determine whether the CPU has AVX2 features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns true if the CPU has AVX2 features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasAVX + * \sa SDL_HasAVX512F + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasAVX2(void); + +/** + * Determine whether the CPU has AVX-512F (foundation) features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns true if the CPU has AVX-512F features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasAVX + * \sa SDL_HasAVX2 + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasAVX512F(void); + +/** + * Determine whether the CPU has ARM SIMD (ARMv6) features. + * + * This is different from ARM NEON, which is a different instruction set. + * + * This always returns false on CPUs that aren't using ARM instruction sets. + * + * \returns true if the CPU has ARM SIMD features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasNEON + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasARMSIMD(void); + +/** + * Determine whether the CPU has NEON (ARM SIMD) features. + * + * This always returns false on CPUs that aren't using ARM instruction sets. + * + * \returns true if the CPU has ARM NEON features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasNEON(void); + +/** + * Determine whether the CPU has LSX (LOONGARCH SIMD) features. + * + * This always returns false on CPUs that aren't using LOONGARCH instruction + * sets. + * + * \returns true if the CPU has LOONGARCH LSX features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasLSX(void); + +/** + * Determine whether the CPU has LASX (LOONGARCH SIMD) features. + * + * This always returns false on CPUs that aren't using LOONGARCH instruction + * sets. + * + * \returns true if the CPU has LOONGARCH LASX features or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasLASX(void); + +/** + * Get the amount of RAM configured in the system. + * + * \returns the amount of RAM configured in the system in MiB. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetSystemRAM(void); + +/** + * Report the alignment this system needs for SIMD allocations. + * + * This will return the minimum number of bytes to which a pointer must be + * aligned to be compatible with SIMD instructions on the current machine. For + * example, if the machine supports SSE only, it will return 16, but if it + * supports AVX-512F, it'll return 64 (etc). This only reports values for + * instruction sets SDL knows about, so if your SDL build doesn't have + * SDL_HasAVX512F(), then it might return 16 for the SSE support it sees and + * not 64 for the AVX-512 instructions that exist but SDL doesn't know about. + * Plan accordingly. + * + * \returns the alignment in bytes needed for available, known SIMD + * instructions. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_aligned_alloc + * \sa SDL_aligned_free + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_GetSIMDAlignment(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_cpuinfo_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_dialog.h b/thirdparty/sdl/include/SDL3/SDL_dialog.h new file mode 100644 index 00000000000..ddb9e24d5fe --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_dialog.h @@ -0,0 +1,341 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryDialog + * + * File dialog support. + * + * SDL offers file dialogs, to let users select files with native GUI + * interfaces. There are "open" dialogs, "save" dialogs, and folder selection + * dialogs. The app can control some details, such as filtering to specific + * files, or whether multiple files can be selected by the user. + * + * Note that launching a file dialog is a non-blocking operation; control + * returns to the app immediately, and a callback is called later (possibly in + * another thread) when the user makes a choice. + */ + +#ifndef SDL_dialog_h_ +#define SDL_dialog_h_ + +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * An entry for filters for file dialogs. + * + * `name` is a user-readable label for the filter (for example, "Office + * document"). + * + * `pattern` is a semicolon-separated list of file extensions (for example, + * "doc;docx"). File extensions may only contain alphanumeric characters, + * hyphens, underscores and periods. Alternatively, the whole string can be a + * single asterisk ("*"), which serves as an "All files" filter. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_DialogFileCallback + * \sa SDL_ShowOpenFileDialog + * \sa SDL_ShowSaveFileDialog + * \sa SDL_ShowOpenFolderDialog + * \sa SDL_ShowFileDialogWithProperties + */ +typedef struct SDL_DialogFileFilter +{ + const char *name; + const char *pattern; +} SDL_DialogFileFilter; + +/** + * Callback used by file dialog functions. + * + * The specific usage is described in each function. + * + * If `filelist` is: + * + * - NULL, an error occurred. Details can be obtained with SDL_GetError(). + * - A pointer to NULL, the user either didn't choose any file or canceled the + * dialog. + * - A pointer to non-`NULL`, the user chose one or more files. The argument + * is a null-terminated array of pointers to UTF-8 encoded strings, each + * containing a path. + * + * The filelist argument should not be freed; it will automatically be freed + * when the callback returns. + * + * The filter argument is the index of the filter that was selected, or -1 if + * no filter was selected or if the platform or method doesn't support + * fetching the selected filter. + * + * In Android, the `filelist` are `content://` URIs. They should be opened + * using SDL_IOFromFile() with appropriate modes. This applies both to open + * and save file dialog. + * + * \param userdata an app-provided pointer, for the callback's use. + * \param filelist the file(s) chosen by the user. + * \param filter index of the selected filter. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_DialogFileFilter + * \sa SDL_ShowOpenFileDialog + * \sa SDL_ShowSaveFileDialog + * \sa SDL_ShowOpenFolderDialog + * \sa SDL_ShowFileDialogWithProperties + */ +typedef void (SDLCALL *SDL_DialogFileCallback)(void *userdata, const char * const *filelist, int filter); + +/** + * Displays a dialog that lets the user select a file on their filesystem. + * + * This is an asynchronous function; it will return immediately, and the + * result will be passed to the callback. + * + * The callback will be invoked with a null-terminated list of files the user + * chose. The list will be empty if the user canceled the dialog, and it will + * be NULL if an error occurred. + * + * Note that the callback may be called from a different thread than the one + * the function was invoked on. + * + * Depending on the platform, the user may be allowed to input paths that + * don't yet exist. + * + * On Linux, dialogs may require XDG Portals, which requires DBus, which + * requires an event-handling loop. Apps that do not use SDL to handle events + * should add a call to SDL_PumpEvents in their main loop. + * + * \param callback a function pointer to be invoked when the user selects a + * file and accepts, or cancels the dialog, or an error + * occurs. + * \param userdata an optional pointer to pass extra data to the callback when + * it will be invoked. + * \param window the window that the dialog should be modal for, may be NULL. + * Not all platforms support this option. + * \param filters a list of filters, may be NULL. Not all platforms support + * this option, and platforms that do support it may allow the + * user to ignore the filters. If non-NULL, it must remain + * valid at least until the callback is invoked. + * \param nfilters the number of filters. Ignored if filters is NULL. + * \param default_location the default folder or file to start the dialog at, + * may be NULL. Not all platforms support this option. + * \param allow_many if non-zero, the user will be allowed to select multiple + * entries. Not all platforms support this option. + * + * \threadsafety This function should be called only from the main thread. The + * callback may be invoked from the same thread or from a + * different one, depending on the OS's constraints. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DialogFileCallback + * \sa SDL_DialogFileFilter + * \sa SDL_ShowSaveFileDialog + * \sa SDL_ShowOpenFolderDialog + * \sa SDL_ShowFileDialogWithProperties + */ +extern SDL_DECLSPEC void SDLCALL SDL_ShowOpenFileDialog(SDL_DialogFileCallback callback, void *userdata, SDL_Window *window, const SDL_DialogFileFilter *filters, int nfilters, const char *default_location, bool allow_many); + +/** + * Displays a dialog that lets the user choose a new or existing file on their + * filesystem. + * + * This is an asynchronous function; it will return immediately, and the + * result will be passed to the callback. + * + * The callback will be invoked with a null-terminated list of files the user + * chose. The list will be empty if the user canceled the dialog, and it will + * be NULL if an error occurred. + * + * Note that the callback may be called from a different thread than the one + * the function was invoked on. + * + * The chosen file may or may not already exist. + * + * On Linux, dialogs may require XDG Portals, which requires DBus, which + * requires an event-handling loop. Apps that do not use SDL to handle events + * should add a call to SDL_PumpEvents in their main loop. + * + * \param callback a function pointer to be invoked when the user selects a + * file and accepts, or cancels the dialog, or an error + * occurs. + * \param userdata an optional pointer to pass extra data to the callback when + * it will be invoked. + * \param window the window that the dialog should be modal for, may be NULL. + * Not all platforms support this option. + * \param filters a list of filters, may be NULL. Not all platforms support + * this option, and platforms that do support it may allow the + * user to ignore the filters. If non-NULL, it must remain + * valid at least until the callback is invoked. + * \param nfilters the number of filters. Ignored if filters is NULL. + * \param default_location the default folder or file to start the dialog at, + * may be NULL. Not all platforms support this option. + * + * \threadsafety This function should be called only from the main thread. The + * callback may be invoked from the same thread or from a + * different one, depending on the OS's constraints. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DialogFileCallback + * \sa SDL_DialogFileFilter + * \sa SDL_ShowOpenFileDialog + * \sa SDL_ShowOpenFolderDialog + * \sa SDL_ShowFileDialogWithProperties + */ +extern SDL_DECLSPEC void SDLCALL SDL_ShowSaveFileDialog(SDL_DialogFileCallback callback, void *userdata, SDL_Window *window, const SDL_DialogFileFilter *filters, int nfilters, const char *default_location); + +/** + * Displays a dialog that lets the user select a folder on their filesystem. + * + * This is an asynchronous function; it will return immediately, and the + * result will be passed to the callback. + * + * The callback will be invoked with a null-terminated list of files the user + * chose. The list will be empty if the user canceled the dialog, and it will + * be NULL if an error occurred. + * + * Note that the callback may be called from a different thread than the one + * the function was invoked on. + * + * Depending on the platform, the user may be allowed to input paths that + * don't yet exist. + * + * On Linux, dialogs may require XDG Portals, which requires DBus, which + * requires an event-handling loop. Apps that do not use SDL to handle events + * should add a call to SDL_PumpEvents in their main loop. + * + * \param callback a function pointer to be invoked when the user selects a + * file and accepts, or cancels the dialog, or an error + * occurs. + * \param userdata an optional pointer to pass extra data to the callback when + * it will be invoked. + * \param window the window that the dialog should be modal for, may be NULL. + * Not all platforms support this option. + * \param default_location the default folder or file to start the dialog at, + * may be NULL. Not all platforms support this option. + * \param allow_many if non-zero, the user will be allowed to select multiple + * entries. Not all platforms support this option. + * + * \threadsafety This function should be called only from the main thread. The + * callback may be invoked from the same thread or from a + * different one, depending on the OS's constraints. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DialogFileCallback + * \sa SDL_ShowOpenFileDialog + * \sa SDL_ShowSaveFileDialog + * \sa SDL_ShowFileDialogWithProperties + */ +extern SDL_DECLSPEC void SDLCALL SDL_ShowOpenFolderDialog(SDL_DialogFileCallback callback, void *userdata, SDL_Window *window, const char *default_location, bool allow_many); + +/** + * Various types of file dialogs. + * + * This is used by SDL_ShowFileDialogWithProperties() to decide what kind of + * dialog to present to the user. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_ShowFileDialogWithProperties + */ +typedef enum SDL_FileDialogType +{ + SDL_FILEDIALOG_OPENFILE, + SDL_FILEDIALOG_SAVEFILE, + SDL_FILEDIALOG_OPENFOLDER +} SDL_FileDialogType; + +/** + * Create and launch a file dialog with the specified properties. + * + * These are the supported properties: + * + * - `SDL_PROP_FILE_DIALOG_FILTERS_POINTER`: a pointer to a list of + * SDL_DialogFileFilter structs, which will be used as filters for + * file-based selections. Ignored if the dialog is an "Open Folder" dialog. + * If non-NULL, the array of filters must remain valid at least until the + * callback is invoked. + * - `SDL_PROP_FILE_DIALOG_NFILTERS_NUMBER`: the number of filters in the + * array of filters, if it exists. + * - `SDL_PROP_FILE_DIALOG_WINDOW_POINTER`: the window that the dialog should + * be modal for. + * - `SDL_PROP_FILE_DIALOG_LOCATION_STRING`: the default folder or file to + * start the dialog at. + * - `SDL_PROP_FILE_DIALOG_MANY_BOOLEAN`: true to allow the user to select + * more than one entry. + * - `SDL_PROP_FILE_DIALOG_TITLE_STRING`: the title for the dialog. + * - `SDL_PROP_FILE_DIALOG_ACCEPT_STRING`: the label that the accept button + * should have. + * - `SDL_PROP_FILE_DIALOG_CANCEL_STRING`: the label that the cancel button + * should have. + * + * Note that each platform may or may not support any of the properties. + * + * \param type the type of file dialog. + * \param callback a function pointer to be invoked when the user selects a + * file and accepts, or cancels the dialog, or an error + * occurs. + * \param userdata an optional pointer to pass extra data to the callback when + * it will be invoked. + * \param props the properties to use. + * + * \threadsafety This function should be called only from the main thread. The + * callback may be invoked from the same thread or from a + * different one, depending on the OS's constraints. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_FileDialogType + * \sa SDL_DialogFileCallback + * \sa SDL_DialogFileFilter + * \sa SDL_ShowOpenFileDialog + * \sa SDL_ShowSaveFileDialog + * \sa SDL_ShowOpenFolderDialog + */ +extern SDL_DECLSPEC void SDLCALL SDL_ShowFileDialogWithProperties(SDL_FileDialogType type, SDL_DialogFileCallback callback, void *userdata, SDL_PropertiesID props); + +#define SDL_PROP_FILE_DIALOG_FILTERS_POINTER "SDL.filedialog.filters" +#define SDL_PROP_FILE_DIALOG_NFILTERS_NUMBER "SDL.filedialog.nfilters" +#define SDL_PROP_FILE_DIALOG_WINDOW_POINTER "SDL.filedialog.window" +#define SDL_PROP_FILE_DIALOG_LOCATION_STRING "SDL.filedialog.location" +#define SDL_PROP_FILE_DIALOG_MANY_BOOLEAN "SDL.filedialog.many" +#define SDL_PROP_FILE_DIALOG_TITLE_STRING "SDL.filedialog.title" +#define SDL_PROP_FILE_DIALOG_ACCEPT_STRING "SDL.filedialog.accept" +#define SDL_PROP_FILE_DIALOG_CANCEL_STRING "SDL.filedialog.cancel" + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_dialog_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_endian.h b/thirdparty/sdl/include/SDL3/SDL_endian.h new file mode 100644 index 00000000000..a34e9d4b09c --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_endian.h @@ -0,0 +1,645 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryEndian + * + * Functions converting endian-specific values to different byte orders. + * + * These functions either unconditionally swap byte order (SDL_Swap16, + * SDL_Swap32, SDL_Swap64, SDL_SwapFloat), or they swap to/from the system's + * native byte order (SDL_Swap16LE, SDL_Swap16BE, SDL_Swap32LE, SDL_Swap32BE, + * SDL_Swap32LE, SDL_Swap32BE, SDL_SwapFloatLE, SDL_SwapFloatBE). In the + * latter case, the functionality is provided by macros that become no-ops if + * a swap isn't necessary: on an x86 (littleendian) processor, SDL_Swap32LE + * does nothing, but SDL_Swap32BE reverses the bytes of the data. On a PowerPC + * processor (bigendian), the macros behavior is reversed. + * + * The swap routines are inline functions, and attempt to use compiler + * intrinsics, inline assembly, and other magic to make byteswapping + * efficient. + */ + +#ifndef SDL_endian_h_ +#define SDL_endian_h_ + +#include + +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +/* As of Clang 11, '_m_prefetchw' is conflicting with the winnt.h's version, + so we define the needed '_m_prefetch' here as a pseudo-header, until the issue is fixed. */ +#ifdef __clang__ +#ifndef __PRFCHWINTRIN_H +#define __PRFCHWINTRIN_H +static __inline__ void __attribute__((__always_inline__, __nodebug__)) +_m_prefetch(void *__P) +{ + __builtin_prefetch(__P, 0, 3 /* _MM_HINT_T0 */); +} +#endif /* __PRFCHWINTRIN_H */ +#endif /* __clang__ */ + +#include +#endif + +/** + * \name The two types of endianness + */ +/* @{ */ + + +/** + * A value to represent littleendian byteorder. + * + * This is used with the preprocessor macro SDL_BYTEORDER, to determine a + * platform's byte ordering: + * + * ```c + * #if SDL_BYTEORDER == SDL_LIL_ENDIAN + * SDL_Log("This system is littleendian."); + * #endif + * ``` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_BYTEORDER + * \sa SDL_BIG_ENDIAN + */ +#define SDL_LIL_ENDIAN 1234 + +/** + * A value to represent bigendian byteorder. + * + * This is used with the preprocessor macro SDL_BYTEORDER, to determine a + * platform's byte ordering: + * + * ```c + * #if SDL_BYTEORDER == SDL_BIG_ENDIAN + * SDL_Log("This system is bigendian."); + * #endif + * ``` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_BYTEORDER + * \sa SDL_LIL_ENDIAN + */ +#define SDL_BIG_ENDIAN 4321 + +/* @} */ + +#ifndef SDL_BYTEORDER +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A macro that reports the target system's byte order. + * + * This is set to either SDL_LIL_ENDIAN or SDL_BIG_ENDIAN (and maybe other + * values in the future, if something else becomes popular). This can be + * tested with the preprocessor, so decisions can be made at compile time. + * + * ```c + * #if SDL_BYTEORDER == SDL_BIG_ENDIAN + * SDL_Log("This system is bigendian."); + * #endif + * ``` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_LIL_ENDIAN + * \sa SDL_BIG_ENDIAN + */ +#define SDL_BYTEORDER SDL_LIL_ENDIAN___or_maybe___SDL_BIG_ENDIAN +#elif defined(SDL_PLATFORM_LINUX) +#include +#define SDL_BYTEORDER __BYTE_ORDER +#elif defined(SDL_PLATFORM_SOLARIS) +#include +#if defined(_LITTLE_ENDIAN) +#define SDL_BYTEORDER SDL_LIL_ENDIAN +#elif defined(_BIG_ENDIAN) +#define SDL_BYTEORDER SDL_BIG_ENDIAN +#else +#error Unsupported endianness +#endif +#elif defined(SDL_PLATFORM_OPENBSD) || defined(__DragonFly__) +#include +#define SDL_BYTEORDER BYTE_ORDER +#elif defined(SDL_PLATFORM_FREEBSD) || defined(SDL_PLATFORM_NETBSD) +#include +#define SDL_BYTEORDER BYTE_ORDER +/* predefs from newer gcc and clang versions: */ +#elif defined(__ORDER_LITTLE_ENDIAN__) && defined(__ORDER_BIG_ENDIAN__) && defined(__BYTE_ORDER__) +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) +#define SDL_BYTEORDER SDL_LIL_ENDIAN +#elif (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) +#define SDL_BYTEORDER SDL_BIG_ENDIAN +#else +#error Unsupported endianness +#endif /**/ +#else +#if defined(__hppa__) || \ + defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \ + (defined(__MIPS__) && defined(__MIPSEB__)) || \ + defined(__ppc__) || defined(__POWERPC__) || defined(__powerpc__) || defined(__PPC__) || \ + defined(__sparc__) || defined(__sparc) +#define SDL_BYTEORDER SDL_BIG_ENDIAN +#else +#define SDL_BYTEORDER SDL_LIL_ENDIAN +#endif +#endif /* SDL_PLATFORM_LINUX */ +#endif /* !SDL_BYTEORDER */ + +#ifndef SDL_FLOATWORDORDER +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A macro that reports the target system's floating point word order. + * + * This is set to either SDL_LIL_ENDIAN or SDL_BIG_ENDIAN (and maybe other + * values in the future, if something else becomes popular). This can be + * tested with the preprocessor, so decisions can be made at compile time. + * + * ```c + * #if SDL_FLOATWORDORDER == SDL_BIG_ENDIAN + * SDL_Log("This system's floats are bigendian."); + * #endif + * ``` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_LIL_ENDIAN + * \sa SDL_BIG_ENDIAN + */ +#define SDL_FLOATWORDORDER SDL_LIL_ENDIAN___or_maybe___SDL_BIG_ENDIAN +/* predefs from newer gcc versions: */ +#elif defined(__ORDER_LITTLE_ENDIAN__) && defined(__ORDER_BIG_ENDIAN__) && defined(__FLOAT_WORD_ORDER__) +#if (__FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__) +#define SDL_FLOATWORDORDER SDL_LIL_ENDIAN +#elif (__FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__) +#define SDL_FLOATWORDORDER SDL_BIG_ENDIAN +#else +#error Unsupported endianness +#endif /**/ +#elif defined(__MAVERICK__) +/* For Maverick, float words are always little-endian. */ +#define SDL_FLOATWORDORDER SDL_LIL_ENDIAN +#elif (defined(__arm__) || defined(__thumb__)) && !defined(__VFP_FP__) && !defined(__ARM_EABI__) +/* For FPA, float words are always big-endian. */ +#define SDL_FLOATWORDORDER SDL_BIG_ENDIAN +#else +/* By default, assume that floats words follow the memory system mode. */ +#define SDL_FLOATWORDORDER SDL_BYTEORDER +#endif /* __FLOAT_WORD_ORDER__ */ +#endif /* !SDL_FLOATWORDORDER */ + + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* various modern compilers may have builtin swap */ +#if defined(__GNUC__) || defined(__clang__) +# define HAS_BUILTIN_BSWAP16 (SDL_HAS_BUILTIN(__builtin_bswap16)) || \ + (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) +# define HAS_BUILTIN_BSWAP32 (SDL_HAS_BUILTIN(__builtin_bswap32)) || \ + (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) +# define HAS_BUILTIN_BSWAP64 (SDL_HAS_BUILTIN(__builtin_bswap64)) || \ + (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + + /* this one is broken */ +# define HAS_BROKEN_BSWAP (__GNUC__ == 2 && __GNUC_MINOR__ <= 95) +#else +# define HAS_BUILTIN_BSWAP16 0 +# define HAS_BUILTIN_BSWAP32 0 +# define HAS_BUILTIN_BSWAP64 0 +# define HAS_BROKEN_BSWAP 0 +#endif + +/* Byte swap 16-bit integer. */ +#ifndef SDL_WIKI_DOCUMENTATION_SECTION +#if HAS_BUILTIN_BSWAP16 +#define SDL_Swap16(x) __builtin_bswap16(x) +#elif (defined(_MSC_VER) && (_MSC_VER >= 1400)) && !defined(__ICL) +#pragma intrinsic(_byteswap_ushort) +#define SDL_Swap16(x) _byteswap_ushort(x) +#elif defined(__i386__) && !HAS_BROKEN_BSWAP +SDL_FORCE_INLINE Uint16 SDL_Swap16(Uint16 x) +{ + __asm__("xchgb %b0,%h0": "=q"(x):"0"(x)); + return x; +} +#elif defined(__x86_64__) +SDL_FORCE_INLINE Uint16 SDL_Swap16(Uint16 x) +{ + __asm__("xchgb %b0,%h0": "=Q"(x):"0"(x)); + return x; +} +#elif (defined(__powerpc__) || defined(__ppc__)) +SDL_FORCE_INLINE Uint16 SDL_Swap16(Uint16 x) +{ + int result; + + __asm__("rlwimi %0,%2,8,16,23": "=&r"(result):"0"(x >> 8), "r"(x)); + return (Uint16)result; +} +#elif (defined(__m68k__) && !defined(__mcoldfire__)) +SDL_FORCE_INLINE Uint16 SDL_Swap16(Uint16 x) +{ + __asm__("rorw #8,%0": "=d"(x): "0"(x):"cc"); + return x; +} +#elif defined(__WATCOMC__) && defined(__386__) +extern __inline Uint16 SDL_Swap16(Uint16); +#pragma aux SDL_Swap16 = \ + "xchg al, ah" \ + parm [ax] \ + modify [ax]; +#else +SDL_FORCE_INLINE Uint16 SDL_Swap16(Uint16 x) +{ + return SDL_static_cast(Uint16, ((x << 8) | (x >> 8))); +} +#endif +#endif + +/* Byte swap 32-bit integer. */ +#ifndef SDL_WIKI_DOCUMENTATION_SECTION +#if HAS_BUILTIN_BSWAP32 +#define SDL_Swap32(x) __builtin_bswap32(x) +#elif (defined(_MSC_VER) && (_MSC_VER >= 1400)) && !defined(__ICL) +#pragma intrinsic(_byteswap_ulong) +#define SDL_Swap32(x) _byteswap_ulong(x) +#elif defined(__i386__) && !HAS_BROKEN_BSWAP +SDL_FORCE_INLINE Uint32 SDL_Swap32(Uint32 x) +{ + __asm__("bswap %0": "=r"(x):"0"(x)); + return x; +} +#elif defined(__x86_64__) +SDL_FORCE_INLINE Uint32 SDL_Swap32(Uint32 x) +{ + __asm__("bswapl %0": "=r"(x):"0"(x)); + return x; +} +#elif (defined(__powerpc__) || defined(__ppc__)) +SDL_FORCE_INLINE Uint32 SDL_Swap32(Uint32 x) +{ + Uint32 result; + + __asm__("rlwimi %0,%2,24,16,23": "=&r"(result): "0" (x>>24), "r"(x)); + __asm__("rlwimi %0,%2,8,8,15" : "=&r"(result): "0" (result), "r"(x)); + __asm__("rlwimi %0,%2,24,0,7" : "=&r"(result): "0" (result), "r"(x)); + return result; +} +#elif (defined(__m68k__) && !defined(__mcoldfire__)) +SDL_FORCE_INLINE Uint32 SDL_Swap32(Uint32 x) +{ + __asm__("rorw #8,%0\n\tswap %0\n\trorw #8,%0": "=d"(x): "0"(x):"cc"); + return x; +} +#elif defined(__WATCOMC__) && defined(__386__) +extern __inline Uint32 SDL_Swap32(Uint32); +#pragma aux SDL_Swap32 = \ + "bswap eax" \ + parm [eax] \ + modify [eax]; +#else +SDL_FORCE_INLINE Uint32 SDL_Swap32(Uint32 x) +{ + return SDL_static_cast(Uint32, ((x << 24) | ((x << 8) & 0x00FF0000) | + ((x >> 8) & 0x0000FF00) | (x >> 24))); +} +#endif +#endif + +/* Byte swap 64-bit integer. */ +#ifndef SDL_WIKI_DOCUMENTATION_SECTION +#if HAS_BUILTIN_BSWAP64 +#define SDL_Swap64(x) __builtin_bswap64(x) +#elif (defined(_MSC_VER) && (_MSC_VER >= 1400)) && !defined(__ICL) +#pragma intrinsic(_byteswap_uint64) +#define SDL_Swap64(x) _byteswap_uint64(x) +#elif defined(__i386__) && !HAS_BROKEN_BSWAP +SDL_FORCE_INLINE Uint64 SDL_Swap64(Uint64 x) +{ + union { + struct { + Uint32 a, b; + } s; + Uint64 u; + } v; + v.u = x; + __asm__("bswapl %0 ; bswapl %1 ; xchgl %0,%1" + : "=r"(v.s.a), "=r"(v.s.b) + : "0" (v.s.a), "1"(v.s.b)); + return v.u; +} +#elif defined(__x86_64__) +SDL_FORCE_INLINE Uint64 SDL_Swap64(Uint64 x) +{ + __asm__("bswapq %0": "=r"(x):"0"(x)); + return x; +} +#elif defined(__WATCOMC__) && defined(__386__) +extern __inline Uint64 SDL_Swap64(Uint64); +#pragma aux SDL_Swap64 = \ + "bswap eax" \ + "bswap edx" \ + "xchg eax,edx" \ + parm [eax edx] \ + modify [eax edx]; +#else +SDL_FORCE_INLINE Uint64 SDL_Swap64(Uint64 x) +{ + Uint32 hi, lo; + + /* Separate into high and low 32-bit values and swap them */ + lo = SDL_static_cast(Uint32, x & 0xFFFFFFFF); + x >>= 32; + hi = SDL_static_cast(Uint32, x & 0xFFFFFFFF); + x = SDL_Swap32(lo); + x <<= 32; + x |= SDL_Swap32(hi); + return (x); +} +#endif +#endif + +/** + * Byte-swap a floating point number. + * + * This will always byte-swap the value, whether it's currently in the native + * byteorder of the system or not. You should use SDL_SwapFloatLE or + * SDL_SwapFloatBE instead, in most cases. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param x the value to byte-swap. + * \returns x, with its bytes in the opposite endian order. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE float SDL_SwapFloat(float x) +{ + union { + float f; + Uint32 ui32; + } swapper; + swapper.f = x; + swapper.ui32 = SDL_Swap32(swapper.ui32); + return swapper.f; +} + +/* remove extra macros */ +#undef HAS_BROKEN_BSWAP +#undef HAS_BUILTIN_BSWAP16 +#undef HAS_BUILTIN_BSWAP32 +#undef HAS_BUILTIN_BSWAP64 + + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Byte-swap an unsigned 16-bit number. + * + * This will always byte-swap the value, whether it's currently in the native + * byteorder of the system or not. You should use SDL_Swap16LE or SDL_Swap16BE + * instead, in most cases. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param x the value to byte-swap. + * \returns `x`, with its bytes in the opposite endian order. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE Uint16 SDL_Swap16(Uint16 x) { return x_but_byteswapped; } + +/** + * Byte-swap an unsigned 32-bit number. + * + * This will always byte-swap the value, whether it's currently in the native + * byteorder of the system or not. You should use SDL_Swap32LE or SDL_Swap32BE + * instead, in most cases. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param x the value to byte-swap. + * \returns `x`, with its bytes in the opposite endian order. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE Uint32 SDL_Swap32(Uint32 x) { return x_but_byteswapped; } + +/** + * Byte-swap an unsigned 64-bit number. + * + * This will always byte-swap the value, whether it's currently in the native + * byteorder of the system or not. You should use SDL_Swap64LE or SDL_Swap64BE + * instead, in most cases. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param x the value to byte-swap. + * \returns `x`, with its bytes in the opposite endian order. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE Uint32 SDL_Swap64(Uint64 x) { return x_but_byteswapped; } + +/** + * Swap a 16-bit value from littleendian to native byte order. + * + * If this is running on a littleendian system, `x` is returned unchanged. + * + * This macro never references `x` more than once, avoiding side effects. + * + * \param x the value to swap, in littleendian byte order. + * \returns `x` in native byte order. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_Swap16LE(x) SwapOnlyIfNecessary(x) + +/** + * Swap a 32-bit value from littleendian to native byte order. + * + * If this is running on a littleendian system, `x` is returned unchanged. + * + * This macro never references `x` more than once, avoiding side effects. + * + * \param x the value to swap, in littleendian byte order. + * \returns `x` in native byte order. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_Swap32LE(x) SwapOnlyIfNecessary(x) + +/** + * Swap a 64-bit value from littleendian to native byte order. + * + * If this is running on a littleendian system, `x` is returned unchanged. + * + * This macro never references `x` more than once, avoiding side effects. + * + * \param x the value to swap, in littleendian byte order. + * \returns `x` in native byte order. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_Swap64LE(x) SwapOnlyIfNecessary(x) + +/** + * Swap a floating point value from littleendian to native byte order. + * + * If this is running on a littleendian system, `x` is returned unchanged. + * + * This macro never references `x` more than once, avoiding side effects. + * + * \param x the value to swap, in littleendian byte order. + * \returns `x` in native byte order. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_SwapFloatLE(x) SwapOnlyIfNecessary(x) + +/** + * Swap a 16-bit value from bigendian to native byte order. + * + * If this is running on a bigendian system, `x` is returned unchanged. + * + * This macro never references `x` more than once, avoiding side effects. + * + * \param x the value to swap, in bigendian byte order. + * \returns `x` in native byte order. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_Swap16BE(x) SwapOnlyIfNecessary(x) + +/** + * Swap a 32-bit value from bigendian to native byte order. + * + * If this is running on a bigendian system, `x` is returned unchanged. + * + * This macro never references `x` more than once, avoiding side effects. + * + * \param x the value to swap, in bigendian byte order. + * \returns `x` in native byte order. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_Swap32BE(x) SwapOnlyIfNecessary(x) + +/** + * Swap a 64-bit value from bigendian to native byte order. + * + * If this is running on a bigendian system, `x` is returned unchanged. + * + * This macro never references `x` more than once, avoiding side effects. + * + * \param x the value to swap, in bigendian byte order. + * \returns `x` in native byte order. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_Swap64BE(x) SwapOnlyIfNecessary(x) + +/** + * Swap a floating point value from bigendian to native byte order. + * + * If this is running on a bigendian system, `x` is returned unchanged. + * + * This macro never references `x` more than once, avoiding side effects. + * + * \param x the value to swap, in bigendian byte order. + * \returns `x` in native byte order. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_SwapFloatBE(x) SwapOnlyIfNecessary(x) + +#elif SDL_BYTEORDER == SDL_LIL_ENDIAN +#define SDL_Swap16LE(x) (x) +#define SDL_Swap32LE(x) (x) +#define SDL_Swap64LE(x) (x) +#define SDL_SwapFloatLE(x) (x) +#define SDL_Swap16BE(x) SDL_Swap16(x) +#define SDL_Swap32BE(x) SDL_Swap32(x) +#define SDL_Swap64BE(x) SDL_Swap64(x) +#define SDL_SwapFloatBE(x) SDL_SwapFloat(x) +#else +#define SDL_Swap16LE(x) SDL_Swap16(x) +#define SDL_Swap32LE(x) SDL_Swap32(x) +#define SDL_Swap64LE(x) SDL_Swap64(x) +#define SDL_SwapFloatLE(x) SDL_SwapFloat(x) +#define SDL_Swap16BE(x) (x) +#define SDL_Swap32BE(x) (x) +#define SDL_Swap64BE(x) (x) +#define SDL_SwapFloatBE(x) (x) +#endif + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_endian_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_error.h b/thirdparty/sdl/include/SDL3/SDL_error.h new file mode 100644 index 00000000000..934967c1cf0 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_error.h @@ -0,0 +1,226 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryError + * + * Simple error message routines for SDL. + * + * Most apps will interface with these APIs in exactly one function: when + * almost any SDL function call reports failure, you can get a human-readable + * string of the problem from SDL_GetError(). + * + * These strings are maintained per-thread, and apps are welcome to set their + * own errors, which is popular when building libraries on top of SDL for + * other apps to consume. These strings are set by calling SDL_SetError(). + * + * A common usage pattern is to have a function that returns true for success + * and false for failure, and do this when something fails: + * + * ```c + * if (something_went_wrong) { + * return SDL_SetError("The thing broke in this specific way: %d", errcode); + * } + * ``` + * + * It's also common to just return `false` in this case if the failing thing + * is known to call SDL_SetError(), so errors simply propagate through. + */ + +#ifndef SDL_error_h_ +#define SDL_error_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* Public functions */ + + +/** + * Set the SDL error message for the current thread. + * + * Calling this function will replace any previous error message that was set. + * + * This function always returns false, since SDL frequently uses false to + * signify a failing result, leading to this idiom: + * + * ```c + * if (error_code) { + * return SDL_SetError("This operation has failed: %d", error_code); + * } + * ``` + * + * \param fmt a printf()-style message format string. + * \param ... additional parameters matching % tokens in the `fmt` string, if + * any. + * \returns false. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ClearError + * \sa SDL_GetError + * \sa SDL_SetErrorV + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1); + +/** + * Set the SDL error message for the current thread. + * + * Calling this function will replace any previous error message that was set. + * + * \param fmt a printf()-style message format string. + * \param ap a variable argument list. + * \returns false. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ClearError + * \sa SDL_GetError + * \sa SDL_SetError + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetErrorV(SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(1); + +/** + * Set an error indicating that memory allocation failed. + * + * This function does not do any memory allocation. + * + * \returns false. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_OutOfMemory(void); + +/** + * Retrieve a message about the last error that occurred on the current + * thread. + * + * It is possible for multiple errors to occur before calling SDL_GetError(). + * Only the last error is returned. + * + * The message is only applicable when an SDL function has signaled an error. + * You must check the return values of SDL function calls to determine when to + * appropriately call SDL_GetError(). You should *not* use the results of + * SDL_GetError() to decide if an error has occurred! Sometimes SDL will set + * an error string even when reporting success. + * + * SDL will *not* clear the error string for successful API calls. You *must* + * check return values for failure cases before you can assume the error + * string applies. + * + * Error strings are set per-thread, so an error set in a different thread + * will not interfere with the current thread's operation. + * + * The returned value is a thread-local string which will remain valid until + * the current thread's error string is changed. The caller should make a copy + * if the value is needed after the next SDL API call. + * + * \returns a message with information about the specific error that occurred, + * or an empty string if there hasn't been an error message set since + * the last call to SDL_ClearError(). + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ClearError + * \sa SDL_SetError + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetError(void); + +/** + * Clear any previous error message for this thread. + * + * \returns true. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetError + * \sa SDL_SetError + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ClearError(void); + +/** + * \name Internal error functions + * + * \internal + * Private error reporting function - used internally. + */ +/* @{ */ + +/** + * A macro to standardize error reporting on unsupported operations. + * + * This simply calls SDL_SetError() with a standardized error string, for + * convenience, consistency, and clarity. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_Unsupported() SDL_SetError("That operation is not supported") + +/** + * A macro to standardize error reporting on unsupported operations. + * + * This simply calls SDL_SetError() with a standardized error string, for + * convenience, consistency, and clarity. + * + * A common usage pattern inside SDL is this: + * + * ```c + * bool MyFunction(const char *str) { + * if (!str) { + * return SDL_InvalidParamError("str"); // returns false. + * } + * DoSomething(str); + * return true; + * } + * ``` + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_InvalidParamError(param) SDL_SetError("Parameter '%s' is invalid", (param)) + +/* @} *//* Internal error functions */ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_error_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_events.h b/thirdparty/sdl/include/SDL3/SDL_events.h new file mode 100644 index 00000000000..d267f051f8d --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_events.h @@ -0,0 +1,1576 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryEvents + * + * Event queue management. + * + * It's extremely common--often required--that an app deal with SDL's event + * queue. Almost all useful information about interactions with the real world + * flow through here: the user interacting with the computer and app, hardware + * coming and going, the system changing in some way, etc. + * + * An app generally takes a moment, perhaps at the start of a new frame, to + * examine any events that have occured since the last time and process or + * ignore them. This is generally done by calling SDL_PollEvent() in a loop + * until it returns false (or, if using the main callbacks, events are + * provided one at a time in calls to SDL_AppEvent() before the next call to + * SDL_AppIterate(); in this scenario, the app does not call SDL_PollEvent() + * at all). + * + * There is other forms of control, too: SDL_PeepEvents() has more + * functionality at the cost of more complexity, and SDL_WaitEvent() can block + * the process until something interesting happens, which might be beneficial + * for certain types of programs on low-power hardware. One may also call + * SDL_AddEventWatch() to set a callback when new events arrive. + * + * The app is free to generate their own events, too: SDL_PushEvent allows the + * app to put events onto the queue for later retrieval; SDL_RegisterEvents + * can guarantee that these events have a type that isn't in use by other + * parts of the system. + */ + +#ifndef SDL_events_h_ +#define SDL_events_h_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* General keyboard/mouse/pen state definitions */ + +/** + * The types of events that can be delivered. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_EventType +{ + SDL_EVENT_FIRST = 0, /**< Unused (do not remove) */ + + /* Application events */ + SDL_EVENT_QUIT = 0x100, /**< User-requested quit */ + + /* These application events have special meaning on iOS and Android, see README-ios.md and README-android.md for details */ + SDL_EVENT_TERMINATING, /**< The application is being terminated by the OS. This event must be handled in a callback set with SDL_AddEventWatch(). + Called on iOS in applicationWillTerminate() + Called on Android in onDestroy() + */ + SDL_EVENT_LOW_MEMORY, /**< The application is low on memory, free memory if possible. This event must be handled in a callback set with SDL_AddEventWatch(). + Called on iOS in applicationDidReceiveMemoryWarning() + Called on Android in onTrimMemory() + */ + SDL_EVENT_WILL_ENTER_BACKGROUND, /**< The application is about to enter the background. This event must be handled in a callback set with SDL_AddEventWatch(). + Called on iOS in applicationWillResignActive() + Called on Android in onPause() + */ + SDL_EVENT_DID_ENTER_BACKGROUND, /**< The application did enter the background and may not get CPU for some time. This event must be handled in a callback set with SDL_AddEventWatch(). + Called on iOS in applicationDidEnterBackground() + Called on Android in onPause() + */ + SDL_EVENT_WILL_ENTER_FOREGROUND, /**< The application is about to enter the foreground. This event must be handled in a callback set with SDL_AddEventWatch(). + Called on iOS in applicationWillEnterForeground() + Called on Android in onResume() + */ + SDL_EVENT_DID_ENTER_FOREGROUND, /**< The application is now interactive. This event must be handled in a callback set with SDL_AddEventWatch(). + Called on iOS in applicationDidBecomeActive() + Called on Android in onResume() + */ + + SDL_EVENT_LOCALE_CHANGED, /**< The user's locale preferences have changed. */ + + SDL_EVENT_SYSTEM_THEME_CHANGED, /**< The system theme changed */ + + /* Display events */ + /* 0x150 was SDL_DISPLAYEVENT, reserve the number for sdl2-compat */ + SDL_EVENT_DISPLAY_ORIENTATION = 0x151, /**< Display orientation has changed to data1 */ + SDL_EVENT_DISPLAY_ADDED, /**< Display has been added to the system */ + SDL_EVENT_DISPLAY_REMOVED, /**< Display has been removed from the system */ + SDL_EVENT_DISPLAY_MOVED, /**< Display has changed position */ + SDL_EVENT_DISPLAY_DESKTOP_MODE_CHANGED, /**< Display has changed desktop mode */ + SDL_EVENT_DISPLAY_CURRENT_MODE_CHANGED, /**< Display has changed current mode */ + SDL_EVENT_DISPLAY_CONTENT_SCALE_CHANGED, /**< Display has changed content scale */ + SDL_EVENT_DISPLAY_FIRST = SDL_EVENT_DISPLAY_ORIENTATION, + SDL_EVENT_DISPLAY_LAST = SDL_EVENT_DISPLAY_CONTENT_SCALE_CHANGED, + + /* Window events */ + /* 0x200 was SDL_WINDOWEVENT, reserve the number for sdl2-compat */ + /* 0x201 was SDL_SYSWMEVENT, reserve the number for sdl2-compat */ + SDL_EVENT_WINDOW_SHOWN = 0x202, /**< Window has been shown */ + SDL_EVENT_WINDOW_HIDDEN, /**< Window has been hidden */ + SDL_EVENT_WINDOW_EXPOSED, /**< Window has been exposed and should be redrawn, and can be redrawn directly from event watchers for this event */ + SDL_EVENT_WINDOW_MOVED, /**< Window has been moved to data1, data2 */ + SDL_EVENT_WINDOW_RESIZED, /**< Window has been resized to data1xdata2 */ + SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED,/**< The pixel size of the window has changed to data1xdata2 */ + SDL_EVENT_WINDOW_METAL_VIEW_RESIZED,/**< The pixel size of a Metal view associated with the window has changed */ + SDL_EVENT_WINDOW_MINIMIZED, /**< Window has been minimized */ + SDL_EVENT_WINDOW_MAXIMIZED, /**< Window has been maximized */ + SDL_EVENT_WINDOW_RESTORED, /**< Window has been restored to normal size and position */ + SDL_EVENT_WINDOW_MOUSE_ENTER, /**< Window has gained mouse focus */ + SDL_EVENT_WINDOW_MOUSE_LEAVE, /**< Window has lost mouse focus */ + SDL_EVENT_WINDOW_FOCUS_GAINED, /**< Window has gained keyboard focus */ + SDL_EVENT_WINDOW_FOCUS_LOST, /**< Window has lost keyboard focus */ + SDL_EVENT_WINDOW_CLOSE_REQUESTED, /**< The window manager requests that the window be closed */ + SDL_EVENT_WINDOW_HIT_TEST, /**< Window had a hit test that wasn't SDL_HITTEST_NORMAL */ + SDL_EVENT_WINDOW_ICCPROF_CHANGED, /**< The ICC profile of the window's display has changed */ + SDL_EVENT_WINDOW_DISPLAY_CHANGED, /**< Window has been moved to display data1 */ + SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED, /**< Window display scale has been changed */ + SDL_EVENT_WINDOW_SAFE_AREA_CHANGED, /**< The window safe area has been changed */ + SDL_EVENT_WINDOW_OCCLUDED, /**< The window has been occluded */ + SDL_EVENT_WINDOW_ENTER_FULLSCREEN, /**< The window has entered fullscreen mode */ + SDL_EVENT_WINDOW_LEAVE_FULLSCREEN, /**< The window has left fullscreen mode */ + SDL_EVENT_WINDOW_DESTROYED, /**< The window with the associated ID is being or has been destroyed. If this message is being handled + in an event watcher, the window handle is still valid and can still be used to retrieve any properties + associated with the window. Otherwise, the handle has already been destroyed and all resources + associated with it are invalid */ + SDL_EVENT_WINDOW_HDR_STATE_CHANGED, /**< Window HDR properties have changed */ + SDL_EVENT_WINDOW_FIRST = SDL_EVENT_WINDOW_SHOWN, + SDL_EVENT_WINDOW_LAST = SDL_EVENT_WINDOW_HDR_STATE_CHANGED, + + /* Keyboard events */ + SDL_EVENT_KEY_DOWN = 0x300, /**< Key pressed */ + SDL_EVENT_KEY_UP, /**< Key released */ + SDL_EVENT_TEXT_EDITING, /**< Keyboard text editing (composition) */ + SDL_EVENT_TEXT_INPUT, /**< Keyboard text input */ + SDL_EVENT_KEYMAP_CHANGED, /**< Keymap changed due to a system event such as an + input language or keyboard layout change. */ + SDL_EVENT_KEYBOARD_ADDED, /**< A new keyboard has been inserted into the system */ + SDL_EVENT_KEYBOARD_REMOVED, /**< A keyboard has been removed */ + SDL_EVENT_TEXT_EDITING_CANDIDATES, /**< Keyboard text editing candidates */ + + /* Mouse events */ + SDL_EVENT_MOUSE_MOTION = 0x400, /**< Mouse moved */ + SDL_EVENT_MOUSE_BUTTON_DOWN, /**< Mouse button pressed */ + SDL_EVENT_MOUSE_BUTTON_UP, /**< Mouse button released */ + SDL_EVENT_MOUSE_WHEEL, /**< Mouse wheel motion */ + SDL_EVENT_MOUSE_ADDED, /**< A new mouse has been inserted into the system */ + SDL_EVENT_MOUSE_REMOVED, /**< A mouse has been removed */ + + /* Joystick events */ + SDL_EVENT_JOYSTICK_AXIS_MOTION = 0x600, /**< Joystick axis motion */ + SDL_EVENT_JOYSTICK_BALL_MOTION, /**< Joystick trackball motion */ + SDL_EVENT_JOYSTICK_HAT_MOTION, /**< Joystick hat position change */ + SDL_EVENT_JOYSTICK_BUTTON_DOWN, /**< Joystick button pressed */ + SDL_EVENT_JOYSTICK_BUTTON_UP, /**< Joystick button released */ + SDL_EVENT_JOYSTICK_ADDED, /**< A new joystick has been inserted into the system */ + SDL_EVENT_JOYSTICK_REMOVED, /**< An opened joystick has been removed */ + SDL_EVENT_JOYSTICK_BATTERY_UPDATED, /**< Joystick battery level change */ + SDL_EVENT_JOYSTICK_UPDATE_COMPLETE, /**< Joystick update is complete */ + + /* Gamepad events */ + SDL_EVENT_GAMEPAD_AXIS_MOTION = 0x650, /**< Gamepad axis motion */ + SDL_EVENT_GAMEPAD_BUTTON_DOWN, /**< Gamepad button pressed */ + SDL_EVENT_GAMEPAD_BUTTON_UP, /**< Gamepad button released */ + SDL_EVENT_GAMEPAD_ADDED, /**< A new gamepad has been inserted into the system */ + SDL_EVENT_GAMEPAD_REMOVED, /**< A gamepad has been removed */ + SDL_EVENT_GAMEPAD_REMAPPED, /**< The gamepad mapping was updated */ + SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN, /**< Gamepad touchpad was touched */ + SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION, /**< Gamepad touchpad finger was moved */ + SDL_EVENT_GAMEPAD_TOUCHPAD_UP, /**< Gamepad touchpad finger was lifted */ + SDL_EVENT_GAMEPAD_SENSOR_UPDATE, /**< Gamepad sensor was updated */ + SDL_EVENT_GAMEPAD_UPDATE_COMPLETE, /**< Gamepad update is complete */ + SDL_EVENT_GAMEPAD_STEAM_HANDLE_UPDATED, /**< Gamepad Steam handle has changed */ + + /* Touch events */ + SDL_EVENT_FINGER_DOWN = 0x700, + SDL_EVENT_FINGER_UP, + SDL_EVENT_FINGER_MOTION, + SDL_EVENT_FINGER_CANCELED, + + /* 0x800, 0x801, and 0x802 were the Gesture events from SDL2. Do not reuse these values! sdl2-compat needs them! */ + + /* Clipboard events */ + SDL_EVENT_CLIPBOARD_UPDATE = 0x900, /**< The clipboard or primary selection changed */ + + /* Drag and drop events */ + SDL_EVENT_DROP_FILE = 0x1000, /**< The system requests a file open */ + SDL_EVENT_DROP_TEXT, /**< text/plain drag-and-drop event */ + SDL_EVENT_DROP_BEGIN, /**< A new set of drops is beginning (NULL filename) */ + SDL_EVENT_DROP_COMPLETE, /**< Current set of drops is now complete (NULL filename) */ + SDL_EVENT_DROP_POSITION, /**< Position while moving over the window */ + + /* Audio hotplug events */ + SDL_EVENT_AUDIO_DEVICE_ADDED = 0x1100, /**< A new audio device is available */ + SDL_EVENT_AUDIO_DEVICE_REMOVED, /**< An audio device has been removed. */ + SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED, /**< An audio device's format has been changed by the system. */ + + /* Sensor events */ + SDL_EVENT_SENSOR_UPDATE = 0x1200, /**< A sensor was updated */ + + /* Pressure-sensitive pen events */ + SDL_EVENT_PEN_PROXIMITY_IN = 0x1300, /**< Pressure-sensitive pen has become available */ + SDL_EVENT_PEN_PROXIMITY_OUT, /**< Pressure-sensitive pen has become unavailable */ + SDL_EVENT_PEN_DOWN, /**< Pressure-sensitive pen touched drawing surface */ + SDL_EVENT_PEN_UP, /**< Pressure-sensitive pen stopped touching drawing surface */ + SDL_EVENT_PEN_BUTTON_DOWN, /**< Pressure-sensitive pen button pressed */ + SDL_EVENT_PEN_BUTTON_UP, /**< Pressure-sensitive pen button released */ + SDL_EVENT_PEN_MOTION, /**< Pressure-sensitive pen is moving on the tablet */ + SDL_EVENT_PEN_AXIS, /**< Pressure-sensitive pen angle/pressure/etc changed */ + + /* Camera hotplug events */ + SDL_EVENT_CAMERA_DEVICE_ADDED = 0x1400, /**< A new camera device is available */ + SDL_EVENT_CAMERA_DEVICE_REMOVED, /**< A camera device has been removed. */ + SDL_EVENT_CAMERA_DEVICE_APPROVED, /**< A camera device has been approved for use by the user. */ + SDL_EVENT_CAMERA_DEVICE_DENIED, /**< A camera device has been denied for use by the user. */ + + /* Render events */ + SDL_EVENT_RENDER_TARGETS_RESET = 0x2000, /**< The render targets have been reset and their contents need to be updated */ + SDL_EVENT_RENDER_DEVICE_RESET, /**< The device has been reset and all textures need to be recreated */ + SDL_EVENT_RENDER_DEVICE_LOST, /**< The device has been lost and can't be recovered. */ + + /* Reserved events for private platforms */ + SDL_EVENT_PRIVATE0 = 0x4000, + SDL_EVENT_PRIVATE1, + SDL_EVENT_PRIVATE2, + SDL_EVENT_PRIVATE3, + + /* Internal events */ + SDL_EVENT_POLL_SENTINEL = 0x7F00, /**< Signals the end of an event poll cycle */ + + /** Events SDL_EVENT_USER through SDL_EVENT_LAST are for your use, + * and should be allocated with SDL_RegisterEvents() + */ + SDL_EVENT_USER = 0x8000, + + /** + * This last event is only for bounding internal arrays + */ + SDL_EVENT_LAST = 0xFFFF, + + /* This just makes sure the enum is the size of Uint32 */ + SDL_EVENT_ENUM_PADDING = 0x7FFFFFFF + +} SDL_EventType; + +/** + * Fields shared by every event + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_CommonEvent +{ + Uint32 type; /**< Event type, shared with all events, Uint32 to cover user events which are not in the SDL_EventType enumeration */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ +} SDL_CommonEvent; + +/** + * Display state change event data (event.display.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_DisplayEvent +{ + SDL_EventType type; /**< SDL_DISPLAYEVENT_* */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_DisplayID displayID;/**< The associated display */ + Sint32 data1; /**< event dependent data */ + Sint32 data2; /**< event dependent data */ +} SDL_DisplayEvent; + +/** + * Window state change event data (event.window.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_WindowEvent +{ + SDL_EventType type; /**< SDL_EVENT_WINDOW_* */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The associated window */ + Sint32 data1; /**< event dependent data */ + Sint32 data2; /**< event dependent data */ +} SDL_WindowEvent; + +/** + * Keyboard device event structure (event.kdevice.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_KeyboardDeviceEvent +{ + SDL_EventType type; /**< SDL_EVENT_KEYBOARD_ADDED or SDL_EVENT_KEYBOARD_REMOVED */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_KeyboardID which; /**< The keyboard instance id */ +} SDL_KeyboardDeviceEvent; + +/** + * Keyboard button event structure (event.key.*) + * + * The `key` is the base SDL_Keycode generated by pressing the `scancode` + * using the current keyboard layout, applying any options specified in + * SDL_HINT_KEYCODE_OPTIONS. You can get the SDL_Keycode corresponding to the + * event scancode and modifiers directly from the keyboard layout, bypassing + * SDL_HINT_KEYCODE_OPTIONS, by calling SDL_GetKeyFromScancode(). + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_GetKeyFromScancode + * \sa SDL_HINT_KEYCODE_OPTIONS + */ +typedef struct SDL_KeyboardEvent +{ + SDL_EventType type; /**< SDL_EVENT_KEY_DOWN or SDL_EVENT_KEY_UP */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with keyboard focus, if any */ + SDL_KeyboardID which; /**< The keyboard instance id, or 0 if unknown or virtual */ + SDL_Scancode scancode; /**< SDL physical key code */ + SDL_Keycode key; /**< SDL virtual key code */ + SDL_Keymod mod; /**< current key modifiers */ + Uint16 raw; /**< The platform dependent scancode for this event */ + bool down; /**< true if the key is pressed */ + bool repeat; /**< true if this is a key repeat */ +} SDL_KeyboardEvent; + +/** + * Keyboard text editing event structure (event.edit.*) + * + * The start cursor is the position, in UTF-8 characters, where new typing + * will be inserted into the editing text. The length is the number of UTF-8 + * characters that will be replaced by new typing. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_TextEditingEvent +{ + SDL_EventType type; /**< SDL_EVENT_TEXT_EDITING */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with keyboard focus, if any */ + const char *text; /**< The editing text */ + Sint32 start; /**< The start cursor of selected editing text, or -1 if not set */ + Sint32 length; /**< The length of selected editing text, or -1 if not set */ +} SDL_TextEditingEvent; + +/** + * Keyboard IME candidates event structure (event.edit_candidates.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_TextEditingCandidatesEvent +{ + SDL_EventType type; /**< SDL_EVENT_TEXT_EDITING_CANDIDATES */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with keyboard focus, if any */ + const char * const *candidates; /**< The list of candidates, or NULL if there are no candidates available */ + Sint32 num_candidates; /**< The number of strings in `candidates` */ + Sint32 selected_candidate; /**< The index of the selected candidate, or -1 if no candidate is selected */ + bool horizontal; /**< true if the list is horizontal, false if it's vertical */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; +} SDL_TextEditingCandidatesEvent; + +/** + * Keyboard text input event structure (event.text.*) + * + * This event will never be delivered unless text input is enabled by calling + * SDL_StartTextInput(). Text input is disabled by default! + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_StartTextInput + * \sa SDL_StopTextInput + */ +typedef struct SDL_TextInputEvent +{ + SDL_EventType type; /**< SDL_EVENT_TEXT_INPUT */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with keyboard focus, if any */ + const char *text; /**< The input text, UTF-8 encoded */ +} SDL_TextInputEvent; + +/** + * Mouse device event structure (event.mdevice.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_MouseDeviceEvent +{ + SDL_EventType type; /**< SDL_EVENT_MOUSE_ADDED or SDL_EVENT_MOUSE_REMOVED */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_MouseID which; /**< The mouse instance id */ +} SDL_MouseDeviceEvent; + +/** + * Mouse motion event structure (event.motion.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_MouseMotionEvent +{ + SDL_EventType type; /**< SDL_EVENT_MOUSE_MOTION */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with mouse focus, if any */ + SDL_MouseID which; /**< The mouse instance id in relative mode, SDL_TOUCH_MOUSEID for touch events, or 0 */ + SDL_MouseButtonFlags state; /**< The current button state */ + float x; /**< X coordinate, relative to window */ + float y; /**< Y coordinate, relative to window */ + float xrel; /**< The relative motion in the X direction */ + float yrel; /**< The relative motion in the Y direction */ +} SDL_MouseMotionEvent; + +/** + * Mouse button event structure (event.button.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_MouseButtonEvent +{ + SDL_EventType type; /**< SDL_EVENT_MOUSE_BUTTON_DOWN or SDL_EVENT_MOUSE_BUTTON_UP */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with mouse focus, if any */ + SDL_MouseID which; /**< The mouse instance id in relative mode, SDL_TOUCH_MOUSEID for touch events, or 0 */ + Uint8 button; /**< The mouse button index */ + bool down; /**< true if the button is pressed */ + Uint8 clicks; /**< 1 for single-click, 2 for double-click, etc. */ + Uint8 padding; + float x; /**< X coordinate, relative to window */ + float y; /**< Y coordinate, relative to window */ +} SDL_MouseButtonEvent; + +/** + * Mouse wheel event structure (event.wheel.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_MouseWheelEvent +{ + SDL_EventType type; /**< SDL_EVENT_MOUSE_WHEEL */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with mouse focus, if any */ + SDL_MouseID which; /**< The mouse instance id in relative mode or 0 */ + float x; /**< The amount scrolled horizontally, positive to the right and negative to the left */ + float y; /**< The amount scrolled vertically, positive away from the user and negative toward the user */ + SDL_MouseWheelDirection direction; /**< Set to one of the SDL_MOUSEWHEEL_* defines. When FLIPPED the values in X and Y will be opposite. Multiply by -1 to change them back */ + float mouse_x; /**< X coordinate, relative to window */ + float mouse_y; /**< Y coordinate, relative to window */ + Sint32 integer_x; /**< The amount scrolled horizontally, accumulated to whole scroll "ticks" (added in 3.2.12) */ + Sint32 integer_y; /**< The amount scrolled vertically, accumulated to whole scroll "ticks" (added in 3.2.12) */ +} SDL_MouseWheelEvent; + +/** + * Joystick axis motion event structure (event.jaxis.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_JoyAxisEvent +{ + SDL_EventType type; /**< SDL_EVENT_JOYSTICK_AXIS_MOTION */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 axis; /**< The joystick axis index */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; + Sint16 value; /**< The axis value (range: -32768 to 32767) */ + Uint16 padding4; +} SDL_JoyAxisEvent; + +/** + * Joystick trackball motion event structure (event.jball.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_JoyBallEvent +{ + SDL_EventType type; /**< SDL_EVENT_JOYSTICK_BALL_MOTION */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 ball; /**< The joystick trackball index */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; + Sint16 xrel; /**< The relative motion in the X direction */ + Sint16 yrel; /**< The relative motion in the Y direction */ +} SDL_JoyBallEvent; + +/** + * Joystick hat position change event structure (event.jhat.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_JoyHatEvent +{ + SDL_EventType type; /**< SDL_EVENT_JOYSTICK_HAT_MOTION */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 hat; /**< The joystick hat index */ + Uint8 value; /**< The hat position value. + * \sa SDL_HAT_LEFTUP SDL_HAT_UP SDL_HAT_RIGHTUP + * \sa SDL_HAT_LEFT SDL_HAT_CENTERED SDL_HAT_RIGHT + * \sa SDL_HAT_LEFTDOWN SDL_HAT_DOWN SDL_HAT_RIGHTDOWN + * + * Note that zero means the POV is centered. + */ + Uint8 padding1; + Uint8 padding2; +} SDL_JoyHatEvent; + +/** + * Joystick button event structure (event.jbutton.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_JoyButtonEvent +{ + SDL_EventType type; /**< SDL_EVENT_JOYSTICK_BUTTON_DOWN or SDL_EVENT_JOYSTICK_BUTTON_UP */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 button; /**< The joystick button index */ + bool down; /**< true if the button is pressed */ + Uint8 padding1; + Uint8 padding2; +} SDL_JoyButtonEvent; + +/** + * Joystick device event structure (event.jdevice.*) + * + * SDL will send JOYSTICK_ADDED events for devices that are already plugged in + * during SDL_Init. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_GamepadDeviceEvent + */ +typedef struct SDL_JoyDeviceEvent +{ + SDL_EventType type; /**< SDL_EVENT_JOYSTICK_ADDED or SDL_EVENT_JOYSTICK_REMOVED or SDL_EVENT_JOYSTICK_UPDATE_COMPLETE */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ +} SDL_JoyDeviceEvent; + +/** + * Joystick battery level change event structure (event.jbattery.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_JoyBatteryEvent +{ + SDL_EventType type; /**< SDL_EVENT_JOYSTICK_BATTERY_UPDATED */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ + SDL_PowerState state; /**< The joystick battery state */ + int percent; /**< The joystick battery percent charge remaining */ +} SDL_JoyBatteryEvent; + +/** + * Gamepad axis motion event structure (event.gaxis.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_GamepadAxisEvent +{ + SDL_EventType type; /**< SDL_EVENT_GAMEPAD_AXIS_MOTION */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 axis; /**< The gamepad axis (SDL_GamepadAxis) */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; + Sint16 value; /**< The axis value (range: -32768 to 32767) */ + Uint16 padding4; +} SDL_GamepadAxisEvent; + + +/** + * Gamepad button event structure (event.gbutton.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_GamepadButtonEvent +{ + SDL_EventType type; /**< SDL_EVENT_GAMEPAD_BUTTON_DOWN or SDL_EVENT_GAMEPAD_BUTTON_UP */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 button; /**< The gamepad button (SDL_GamepadButton) */ + bool down; /**< true if the button is pressed */ + Uint8 padding1; + Uint8 padding2; +} SDL_GamepadButtonEvent; + + +/** + * Gamepad device event structure (event.gdevice.*) + * + * Joysticks that are supported gamepads receive both an SDL_JoyDeviceEvent + * and an SDL_GamepadDeviceEvent. + * + * SDL will send GAMEPAD_ADDED events for joysticks that are already plugged + * in during SDL_Init() and are recognized as gamepads. It will also send + * events for joysticks that get gamepad mappings at runtime. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_JoyDeviceEvent + */ +typedef struct SDL_GamepadDeviceEvent +{ + SDL_EventType type; /**< SDL_EVENT_GAMEPAD_ADDED, SDL_EVENT_GAMEPAD_REMOVED, or SDL_EVENT_GAMEPAD_REMAPPED, SDL_EVENT_GAMEPAD_UPDATE_COMPLETE or SDL_EVENT_GAMEPAD_STEAM_HANDLE_UPDATED */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ +} SDL_GamepadDeviceEvent; + +/** + * Gamepad touchpad event structure (event.gtouchpad.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_GamepadTouchpadEvent +{ + SDL_EventType type; /**< SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN or SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION or SDL_EVENT_GAMEPAD_TOUCHPAD_UP */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ + Sint32 touchpad; /**< The index of the touchpad */ + Sint32 finger; /**< The index of the finger on the touchpad */ + float x; /**< Normalized in the range 0...1 with 0 being on the left */ + float y; /**< Normalized in the range 0...1 with 0 being at the top */ + float pressure; /**< Normalized in the range 0...1 */ +} SDL_GamepadTouchpadEvent; + +/** + * Gamepad sensor event structure (event.gsensor.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_GamepadSensorEvent +{ + SDL_EventType type; /**< SDL_EVENT_GAMEPAD_SENSOR_UPDATE */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_JoystickID which; /**< The joystick instance id */ + Sint32 sensor; /**< The type of the sensor, one of the values of SDL_SensorType */ + float data[3]; /**< Up to 3 values from the sensor, as defined in SDL_sensor.h */ + Uint64 sensor_timestamp; /**< The timestamp of the sensor reading in nanoseconds, not necessarily synchronized with the system clock */ +} SDL_GamepadSensorEvent; + +/** + * Audio device event structure (event.adevice.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_AudioDeviceEvent +{ + SDL_EventType type; /**< SDL_EVENT_AUDIO_DEVICE_ADDED, or SDL_EVENT_AUDIO_DEVICE_REMOVED, or SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_AudioDeviceID which; /**< SDL_AudioDeviceID for the device being added or removed or changing */ + bool recording; /**< false if a playback device, true if a recording device. */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; +} SDL_AudioDeviceEvent; + +/** + * Camera device event structure (event.cdevice.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_CameraDeviceEvent +{ + SDL_EventType type; /**< SDL_EVENT_CAMERA_DEVICE_ADDED, SDL_EVENT_CAMERA_DEVICE_REMOVED, SDL_EVENT_CAMERA_DEVICE_APPROVED, SDL_EVENT_CAMERA_DEVICE_DENIED */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_CameraID which; /**< SDL_CameraID for the device being added or removed or changing */ +} SDL_CameraDeviceEvent; + + +/** + * Renderer event structure (event.render.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_RenderEvent +{ + SDL_EventType type; /**< SDL_EVENT_RENDER_TARGETS_RESET, SDL_EVENT_RENDER_DEVICE_RESET, SDL_EVENT_RENDER_DEVICE_LOST */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window containing the renderer in question. */ +} SDL_RenderEvent; + + +/** + * Touch finger event structure (event.tfinger.*) + * + * Coordinates in this event are normalized. `x` and `y` are normalized to a + * range between 0.0f and 1.0f, relative to the window, so (0,0) is the top + * left and (1,1) is the bottom right. Delta coordinates `dx` and `dy` are + * normalized in the ranges of -1.0f (traversed all the way from the bottom or + * right to all the way up or left) to 1.0f (traversed all the way from the + * top or left to all the way down or right). + * + * Note that while the coordinates are _normalized_, they are not _clamped_, + * which means in some circumstances you can get a value outside of this + * range. For example, a renderer using logical presentation might give a + * negative value when the touch is in the letterboxing. Some platforms might + * report a touch outside of the window, which will also be outside of the + * range. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_TouchFingerEvent +{ + SDL_EventType type; /**< SDL_EVENT_FINGER_DOWN, SDL_EVENT_FINGER_UP, SDL_EVENT_FINGER_MOTION, or SDL_EVENT_FINGER_CANCELED */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_TouchID touchID; /**< The touch device id */ + SDL_FingerID fingerID; + float x; /**< Normalized in the range 0...1 */ + float y; /**< Normalized in the range 0...1 */ + float dx; /**< Normalized in the range -1...1 */ + float dy; /**< Normalized in the range -1...1 */ + float pressure; /**< Normalized in the range 0...1 */ + SDL_WindowID windowID; /**< The window underneath the finger, if any */ +} SDL_TouchFingerEvent; + +/** + * Pressure-sensitive pen proximity event structure (event.pmotion.*) + * + * When a pen becomes visible to the system (it is close enough to a tablet, + * etc), SDL will send an SDL_EVENT_PEN_PROXIMITY_IN event with the new pen's + * ID. This ID is valid until the pen leaves proximity again (has been removed + * from the tablet's area, the tablet has been unplugged, etc). If the same + * pen reenters proximity again, it will be given a new ID. + * + * Note that "proximity" means "close enough for the tablet to know the tool + * is there." The pen touching and lifting off from the tablet while not + * leaving the area are handled by SDL_EVENT_PEN_DOWN and SDL_EVENT_PEN_UP. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_PenProximityEvent +{ + SDL_EventType type; /**< SDL_EVENT_PEN_PROXIMITY_IN or SDL_EVENT_PEN_PROXIMITY_OUT */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with pen focus, if any */ + SDL_PenID which; /**< The pen instance id */ +} SDL_PenProximityEvent; + +/** + * Pressure-sensitive pen motion event structure (event.pmotion.*) + * + * Depending on the hardware, you may get motion events when the pen is not + * touching a tablet, for tracking a pen even when it isn't drawing. You + * should listen for SDL_EVENT_PEN_DOWN and SDL_EVENT_PEN_UP events, or check + * `pen_state & SDL_PEN_INPUT_DOWN` to decide if a pen is "drawing" when + * dealing with pen motion. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_PenMotionEvent +{ + SDL_EventType type; /**< SDL_EVENT_PEN_MOTION */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with pen focus, if any */ + SDL_PenID which; /**< The pen instance id */ + SDL_PenInputFlags pen_state; /**< Complete pen input state at time of event */ + float x; /**< X coordinate, relative to window */ + float y; /**< Y coordinate, relative to window */ +} SDL_PenMotionEvent; + +/** + * Pressure-sensitive pen touched event structure (event.ptouch.*) + * + * These events come when a pen touches a surface (a tablet, etc), or lifts + * off from one. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_PenTouchEvent +{ + SDL_EventType type; /**< SDL_EVENT_PEN_DOWN or SDL_EVENT_PEN_UP */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with pen focus, if any */ + SDL_PenID which; /**< The pen instance id */ + SDL_PenInputFlags pen_state; /**< Complete pen input state at time of event */ + float x; /**< X coordinate, relative to window */ + float y; /**< Y coordinate, relative to window */ + bool eraser; /**< true if eraser end is used (not all pens support this). */ + bool down; /**< true if the pen is touching or false if the pen is lifted off */ +} SDL_PenTouchEvent; + +/** + * Pressure-sensitive pen button event structure (event.pbutton.*) + * + * This is for buttons on the pen itself that the user might click. The pen + * itself pressing down to draw triggers a SDL_EVENT_PEN_DOWN event instead. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_PenButtonEvent +{ + SDL_EventType type; /**< SDL_EVENT_PEN_BUTTON_DOWN or SDL_EVENT_PEN_BUTTON_UP */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with mouse focus, if any */ + SDL_PenID which; /**< The pen instance id */ + SDL_PenInputFlags pen_state; /**< Complete pen input state at time of event */ + float x; /**< X coordinate, relative to window */ + float y; /**< Y coordinate, relative to window */ + Uint8 button; /**< The pen button index (first button is 1). */ + bool down; /**< true if the button is pressed */ +} SDL_PenButtonEvent; + +/** + * Pressure-sensitive pen pressure / angle event structure (event.paxis.*) + * + * You might get some of these events even if the pen isn't touching the + * tablet. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_PenAxisEvent +{ + SDL_EventType type; /**< SDL_EVENT_PEN_AXIS */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window with pen focus, if any */ + SDL_PenID which; /**< The pen instance id */ + SDL_PenInputFlags pen_state; /**< Complete pen input state at time of event */ + float x; /**< X coordinate, relative to window */ + float y; /**< Y coordinate, relative to window */ + SDL_PenAxis axis; /**< Axis that has changed */ + float value; /**< New value of axis */ +} SDL_PenAxisEvent; + +/** + * An event used to drop text or request a file open by the system + * (event.drop.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_DropEvent +{ + SDL_EventType type; /**< SDL_EVENT_DROP_BEGIN or SDL_EVENT_DROP_FILE or SDL_EVENT_DROP_TEXT or SDL_EVENT_DROP_COMPLETE or SDL_EVENT_DROP_POSITION */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The window that was dropped on, if any */ + float x; /**< X coordinate, relative to window (not on begin) */ + float y; /**< Y coordinate, relative to window (not on begin) */ + const char *source; /**< The source app that sent this drop event, or NULL if that isn't available */ + const char *data; /**< The text for SDL_EVENT_DROP_TEXT and the file name for SDL_EVENT_DROP_FILE, NULL for other events */ +} SDL_DropEvent; + +/** + * An event triggered when the clipboard contents have changed + * (event.clipboard.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_ClipboardEvent +{ + SDL_EventType type; /**< SDL_EVENT_CLIPBOARD_UPDATE */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + bool owner; /**< are we owning the clipboard (internal update) */ + Sint32 num_mime_types; /**< number of mime types */ + const char **mime_types; /**< current mime types */ +} SDL_ClipboardEvent; + +/** + * Sensor event structure (event.sensor.*) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_SensorEvent +{ + SDL_EventType type; /**< SDL_EVENT_SENSOR_UPDATE */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_SensorID which; /**< The instance ID of the sensor */ + float data[6]; /**< Up to 6 values from the sensor - additional values can be queried using SDL_GetSensorData() */ + Uint64 sensor_timestamp; /**< The timestamp of the sensor reading in nanoseconds, not necessarily synchronized with the system clock */ +} SDL_SensorEvent; + +/** + * The "quit requested" event + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_QuitEvent +{ + SDL_EventType type; /**< SDL_EVENT_QUIT */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ +} SDL_QuitEvent; + +/** + * A user-defined event type (event.user.*) + * + * This event is unique; it is never created by SDL, but only by the + * application. The event can be pushed onto the event queue using + * SDL_PushEvent(). The contents of the structure members are completely up to + * the programmer; the only requirement is that '''type''' is a value obtained + * from SDL_RegisterEvents(). + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_UserEvent +{ + Uint32 type; /**< SDL_EVENT_USER through SDL_EVENT_LAST-1, Uint32 because these are not in the SDL_EventType enumeration */ + Uint32 reserved; + Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */ + SDL_WindowID windowID; /**< The associated window if any */ + Sint32 code; /**< User defined event code */ + void *data1; /**< User defined data pointer */ + void *data2; /**< User defined data pointer */ +} SDL_UserEvent; + + +/** + * The structure for all events in SDL. + * + * The SDL_Event structure is the core of all event handling in SDL. SDL_Event + * is a union of all event structures used in SDL. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef union SDL_Event +{ + Uint32 type; /**< Event type, shared with all events, Uint32 to cover user events which are not in the SDL_EventType enumeration */ + SDL_CommonEvent common; /**< Common event data */ + SDL_DisplayEvent display; /**< Display event data */ + SDL_WindowEvent window; /**< Window event data */ + SDL_KeyboardDeviceEvent kdevice; /**< Keyboard device change event data */ + SDL_KeyboardEvent key; /**< Keyboard event data */ + SDL_TextEditingEvent edit; /**< Text editing event data */ + SDL_TextEditingCandidatesEvent edit_candidates; /**< Text editing candidates event data */ + SDL_TextInputEvent text; /**< Text input event data */ + SDL_MouseDeviceEvent mdevice; /**< Mouse device change event data */ + SDL_MouseMotionEvent motion; /**< Mouse motion event data */ + SDL_MouseButtonEvent button; /**< Mouse button event data */ + SDL_MouseWheelEvent wheel; /**< Mouse wheel event data */ + SDL_JoyDeviceEvent jdevice; /**< Joystick device change event data */ + SDL_JoyAxisEvent jaxis; /**< Joystick axis event data */ + SDL_JoyBallEvent jball; /**< Joystick ball event data */ + SDL_JoyHatEvent jhat; /**< Joystick hat event data */ + SDL_JoyButtonEvent jbutton; /**< Joystick button event data */ + SDL_JoyBatteryEvent jbattery; /**< Joystick battery event data */ + SDL_GamepadDeviceEvent gdevice; /**< Gamepad device event data */ + SDL_GamepadAxisEvent gaxis; /**< Gamepad axis event data */ + SDL_GamepadButtonEvent gbutton; /**< Gamepad button event data */ + SDL_GamepadTouchpadEvent gtouchpad; /**< Gamepad touchpad event data */ + SDL_GamepadSensorEvent gsensor; /**< Gamepad sensor event data */ + SDL_AudioDeviceEvent adevice; /**< Audio device event data */ + SDL_CameraDeviceEvent cdevice; /**< Camera device event data */ + SDL_SensorEvent sensor; /**< Sensor event data */ + SDL_QuitEvent quit; /**< Quit request event data */ + SDL_UserEvent user; /**< Custom event data */ + SDL_TouchFingerEvent tfinger; /**< Touch finger event data */ + SDL_PenProximityEvent pproximity; /**< Pen proximity event data */ + SDL_PenTouchEvent ptouch; /**< Pen tip touching event data */ + SDL_PenMotionEvent pmotion; /**< Pen motion event data */ + SDL_PenButtonEvent pbutton; /**< Pen button event data */ + SDL_PenAxisEvent paxis; /**< Pen axis event data */ + SDL_RenderEvent render; /**< Render event data */ + SDL_DropEvent drop; /**< Drag and drop event data */ + SDL_ClipboardEvent clipboard; /**< Clipboard event data */ + + /* This is necessary for ABI compatibility between Visual C++ and GCC. + Visual C++ will respect the push pack pragma and use 52 bytes (size of + SDL_TextEditingEvent, the largest structure for 32-bit and 64-bit + architectures) for this union, and GCC will use the alignment of the + largest datatype within the union, which is 8 bytes on 64-bit + architectures. + + So... we'll add padding to force the size to be the same for both. + + On architectures where pointers are 16 bytes, this needs rounding up to + the next multiple of 16, 64, and on architectures where pointers are + even larger the size of SDL_UserEvent will dominate as being 3 pointers. + */ + Uint8 padding[128]; +} SDL_Event; + +/* Make sure we haven't broken binary compatibility */ +SDL_COMPILE_TIME_ASSERT(SDL_Event, sizeof(SDL_Event) == sizeof(((SDL_Event *)NULL)->padding)); + + +/* Function prototypes */ + +/** + * Pump the event loop, gathering events from the input devices. + * + * This function updates the event queue and internal input device state. + * + * SDL_PumpEvents() gathers all the pending input information from devices and + * places it in the event queue. Without calls to SDL_PumpEvents() no events + * would ever be placed on the queue. Often the need for calls to + * SDL_PumpEvents() is hidden from the user since SDL_PollEvent() and + * SDL_WaitEvent() implicitly call SDL_PumpEvents(). However, if you are not + * polling or waiting for events (e.g. you are filtering them), then you must + * call SDL_PumpEvents() to force an event queue update. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PollEvent + * \sa SDL_WaitEvent + */ +extern SDL_DECLSPEC void SDLCALL SDL_PumpEvents(void); + +/* @{ */ + +/** + * The type of action to request from SDL_PeepEvents(). + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_EventAction +{ + SDL_ADDEVENT, /**< Add events to the back of the queue. */ + SDL_PEEKEVENT, /**< Check but don't remove events from the queue front. */ + SDL_GETEVENT /**< Retrieve/remove events from the front of the queue. */ +} SDL_EventAction; + +/** + * Check the event queue for messages and optionally return them. + * + * `action` may be any of the following: + * + * - `SDL_ADDEVENT`: up to `numevents` events will be added to the back of the + * event queue. + * - `SDL_PEEKEVENT`: `numevents` events at the front of the event queue, + * within the specified minimum and maximum type, will be returned to the + * caller and will _not_ be removed from the queue. If you pass NULL for + * `events`, then `numevents` is ignored and the total number of matching + * events will be returned. + * - `SDL_GETEVENT`: up to `numevents` events at the front of the event queue, + * within the specified minimum and maximum type, will be returned to the + * caller and will be removed from the queue. + * + * You may have to call SDL_PumpEvents() before calling this function. + * Otherwise, the events may not be ready to be filtered when you call + * SDL_PeepEvents(). + * + * \param events destination buffer for the retrieved events, may be NULL to + * leave the events in the queue and return the number of events + * that would have been stored. + * \param numevents if action is SDL_ADDEVENT, the number of events to add + * back to the event queue; if action is SDL_PEEKEVENT or + * SDL_GETEVENT, the maximum number of events to retrieve. + * \param action action to take; see [Remarks](#remarks) for details. + * \param minType minimum value of the event type to be considered; + * SDL_EVENT_FIRST is a safe choice. + * \param maxType maximum value of the event type to be considered; + * SDL_EVENT_LAST is a safe choice. + * \returns the number of events actually stored or -1 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PollEvent + * \sa SDL_PumpEvents + * \sa SDL_PushEvent + */ +extern SDL_DECLSPEC int SDLCALL SDL_PeepEvents(SDL_Event *events, int numevents, SDL_EventAction action, Uint32 minType, Uint32 maxType); +/* @} */ + +/** + * Check for the existence of a certain event type in the event queue. + * + * If you need to check for a range of event types, use SDL_HasEvents() + * instead. + * + * \param type the type of event to be queried; see SDL_EventType for details. + * \returns true if events matching `type` are present, or false if events + * matching `type` are not present. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasEvents + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasEvent(Uint32 type); + + +/** + * Check for the existence of certain event types in the event queue. + * + * If you need to check for a single event type, use SDL_HasEvent() instead. + * + * \param minType the low end of event type to be queried, inclusive; see + * SDL_EventType for details. + * \param maxType the high end of event type to be queried, inclusive; see + * SDL_EventType for details. + * \returns true if events with type >= `minType` and <= `maxType` are + * present, or false if not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasEvents + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasEvents(Uint32 minType, Uint32 maxType); + +/** + * Clear events of a specific type from the event queue. + * + * This will unconditionally remove any events from the queue that match + * `type`. If you need to remove a range of event types, use SDL_FlushEvents() + * instead. + * + * It's also normal to just ignore events you don't care about in your event + * loop without calling this function. + * + * This function only affects currently queued events. If you want to make + * sure that all pending OS events are flushed, you can call SDL_PumpEvents() + * on the main thread immediately before the flush call. + * + * If you have user events with custom data that needs to be freed, you should + * use SDL_PeepEvents() to remove and clean up those events before calling + * this function. + * + * \param type the type of event to be cleared; see SDL_EventType for details. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_FlushEvents + */ +extern SDL_DECLSPEC void SDLCALL SDL_FlushEvent(Uint32 type); + +/** + * Clear events of a range of types from the event queue. + * + * This will unconditionally remove any events from the queue that are in the + * range of `minType` to `maxType`, inclusive. If you need to remove a single + * event type, use SDL_FlushEvent() instead. + * + * It's also normal to just ignore events you don't care about in your event + * loop without calling this function. + * + * This function only affects currently queued events. If you want to make + * sure that all pending OS events are flushed, you can call SDL_PumpEvents() + * on the main thread immediately before the flush call. + * + * \param minType the low end of event type to be cleared, inclusive; see + * SDL_EventType for details. + * \param maxType the high end of event type to be cleared, inclusive; see + * SDL_EventType for details. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_FlushEvent + */ +extern SDL_DECLSPEC void SDLCALL SDL_FlushEvents(Uint32 minType, Uint32 maxType); + +/** + * Poll for currently pending events. + * + * If `event` is not NULL, the next event is removed from the queue and stored + * in the SDL_Event structure pointed to by `event`. The 1 returned refers to + * this event, immediately stored in the SDL Event structure -- not an event + * to follow. + * + * If `event` is NULL, it simply returns 1 if there is an event in the queue, + * but will not remove it from the queue. + * + * As this function may implicitly call SDL_PumpEvents(), you can only call + * this function in the thread that set the video mode. + * + * SDL_PollEvent() is the favored way of receiving system events since it can + * be done from the main loop and does not suspend the main loop while waiting + * on an event to be posted. + * + * The common practice is to fully process the event queue once every frame, + * usually as a first step before updating the game's state: + * + * ```c + * while (game_is_still_running) { + * SDL_Event event; + * while (SDL_PollEvent(&event)) { // poll until all events are handled! + * // decide what to do with this event. + * } + * + * // update game state, draw the current frame + * } + * ``` + * + * \param event the SDL_Event structure to be filled with the next event from + * the queue, or NULL. + * \returns true if this got an event or false if there are none available. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PushEvent + * \sa SDL_WaitEvent + * \sa SDL_WaitEventTimeout + */ +extern SDL_DECLSPEC bool SDLCALL SDL_PollEvent(SDL_Event *event); + +/** + * Wait indefinitely for the next available event. + * + * If `event` is not NULL, the next event is removed from the queue and stored + * in the SDL_Event structure pointed to by `event`. + * + * As this function may implicitly call SDL_PumpEvents(), you can only call + * this function in the thread that initialized the video subsystem. + * + * \param event the SDL_Event structure to be filled in with the next event + * from the queue, or NULL. + * \returns true on success or false if there was an error while waiting for + * events; call SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PollEvent + * \sa SDL_PushEvent + * \sa SDL_WaitEventTimeout + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WaitEvent(SDL_Event *event); + +/** + * Wait until the specified timeout (in milliseconds) for the next available + * event. + * + * If `event` is not NULL, the next event is removed from the queue and stored + * in the SDL_Event structure pointed to by `event`. + * + * As this function may implicitly call SDL_PumpEvents(), you can only call + * this function in the thread that initialized the video subsystem. + * + * The timeout is not guaranteed, the actual wait time could be longer due to + * system scheduling. + * + * \param event the SDL_Event structure to be filled in with the next event + * from the queue, or NULL. + * \param timeoutMS the maximum number of milliseconds to wait for the next + * available event. + * \returns true if this got an event or false if the timeout elapsed without + * any events available. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PollEvent + * \sa SDL_PushEvent + * \sa SDL_WaitEvent + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WaitEventTimeout(SDL_Event *event, Sint32 timeoutMS); + +/** + * Add an event to the event queue. + * + * The event queue can actually be used as a two way communication channel. + * Not only can events be read from the queue, but the user can also push + * their own events onto it. `event` is a pointer to the event structure you + * wish to push onto the queue. The event is copied into the queue, and the + * caller may dispose of the memory pointed to after SDL_PushEvent() returns. + * + * Note: Pushing device input events onto the queue doesn't modify the state + * of the device within SDL. + * + * Note: Events pushed onto the queue with SDL_PushEvent() get passed through + * the event filter but events added with SDL_PeepEvents() do not. + * + * For pushing application-specific events, please use SDL_RegisterEvents() to + * get an event type that does not conflict with other code that also wants + * its own custom event types. + * + * \param event the SDL_Event to be added to the queue. + * \returns true on success, false if the event was filtered or on failure; + * call SDL_GetError() for more information. A common reason for + * error is the event queue being full. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PeepEvents + * \sa SDL_PollEvent + * \sa SDL_RegisterEvents + */ +extern SDL_DECLSPEC bool SDLCALL SDL_PushEvent(SDL_Event *event); + +/** + * A function pointer used for callbacks that watch the event queue. + * + * \param userdata what was passed as `userdata` to SDL_SetEventFilter() or + * SDL_AddEventWatch, etc. + * \param event the event that triggered the callback. + * \returns true to permit event to be added to the queue, and false to + * disallow it. When used with SDL_AddEventWatch, the return value is + * ignored. + * + * \threadsafety SDL may call this callback at any time from any thread; the + * application is responsible for locking resources the callback + * touches that need to be protected. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_SetEventFilter + * \sa SDL_AddEventWatch + */ +typedef bool (SDLCALL *SDL_EventFilter)(void *userdata, SDL_Event *event); + +/** + * Set up a filter to process all events before they are added to the internal + * event queue. + * + * If you just want to see events without modifying them or preventing them + * from being queued, you should use SDL_AddEventWatch() instead. + * + * If the filter function returns true when called, then the event will be + * added to the internal queue. If it returns false, then the event will be + * dropped from the queue, but the internal state will still be updated. This + * allows selective filtering of dynamically arriving events. + * + * **WARNING**: Be very careful of what you do in the event filter function, + * as it may run in a different thread! + * + * On platforms that support it, if the quit event is generated by an + * interrupt signal (e.g. pressing Ctrl-C), it will be delivered to the + * application at the next event poll. + * + * Note: Disabled events never make it to the event filter function; see + * SDL_SetEventEnabled(). + * + * Note: Events pushed onto the queue with SDL_PushEvent() get passed through + * the event filter, but events pushed onto the queue with SDL_PeepEvents() do + * not. + * + * \param filter an SDL_EventFilter function to call when an event happens. + * \param userdata a pointer that is passed to `filter`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddEventWatch + * \sa SDL_SetEventEnabled + * \sa SDL_GetEventFilter + * \sa SDL_PeepEvents + * \sa SDL_PushEvent + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetEventFilter(SDL_EventFilter filter, void *userdata); + +/** + * Query the current event filter. + * + * This function can be used to "chain" filters, by saving the existing filter + * before replacing it with a function that will call that saved filter. + * + * \param filter the current callback function will be stored here. + * \param userdata the pointer that is passed to the current event filter will + * be stored here. + * \returns true on success or false if there is no event filter set. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetEventFilter + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetEventFilter(SDL_EventFilter *filter, void **userdata); + +/** + * Add a callback to be triggered when an event is added to the event queue. + * + * `filter` will be called when an event happens, and its return value is + * ignored. + * + * **WARNING**: Be very careful of what you do in the event filter function, + * as it may run in a different thread! + * + * If the quit event is generated by a signal (e.g. SIGINT), it will bypass + * the internal queue and be delivered to the watch callback immediately, and + * arrive at the next event poll. + * + * Note: the callback is called for events posted by the user through + * SDL_PushEvent(), but not for disabled events, nor for events by a filter + * callback set with SDL_SetEventFilter(), nor for events posted by the user + * through SDL_PeepEvents(). + * + * \param filter an SDL_EventFilter function to call when an event happens. + * \param userdata a pointer that is passed to `filter`. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RemoveEventWatch + * \sa SDL_SetEventFilter + */ +extern SDL_DECLSPEC bool SDLCALL SDL_AddEventWatch(SDL_EventFilter filter, void *userdata); + +/** + * Remove an event watch callback added with SDL_AddEventWatch(). + * + * This function takes the same input as SDL_AddEventWatch() to identify and + * delete the corresponding callback. + * + * \param filter the function originally passed to SDL_AddEventWatch(). + * \param userdata the pointer originally passed to SDL_AddEventWatch(). + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddEventWatch + */ +extern SDL_DECLSPEC void SDLCALL SDL_RemoveEventWatch(SDL_EventFilter filter, void *userdata); + +/** + * Run a specific filter function on the current event queue, removing any + * events for which the filter returns false. + * + * See SDL_SetEventFilter() for more information. Unlike SDL_SetEventFilter(), + * this function does not change the filter permanently, it only uses the + * supplied filter until this function returns. + * + * \param filter the SDL_EventFilter function to call when an event happens. + * \param userdata a pointer that is passed to `filter`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetEventFilter + * \sa SDL_SetEventFilter + */ +extern SDL_DECLSPEC void SDLCALL SDL_FilterEvents(SDL_EventFilter filter, void *userdata); + +/** + * Set the state of processing events by type. + * + * \param type the type of event; see SDL_EventType for details. + * \param enabled whether to process the event or not. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_EventEnabled + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetEventEnabled(Uint32 type, bool enabled); + +/** + * Query the state of processing events by type. + * + * \param type the type of event; see SDL_EventType for details. + * \returns true if the event is being processed, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetEventEnabled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_EventEnabled(Uint32 type); + +/** + * Allocate a set of user-defined events, and return the beginning event + * number for that set of events. + * + * \param numevents the number of events to be allocated. + * \returns the beginning event number, or 0 if numevents is invalid or if + * there are not enough user-defined events left. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PushEvent + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_RegisterEvents(int numevents); + +/** + * Get window associated with an event. + * + * \param event an event containing a `windowID`. + * \returns the associated window on success or NULL if there is none. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PollEvent + * \sa SDL_WaitEvent + * \sa SDL_WaitEventTimeout + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GetWindowFromEvent(const SDL_Event *event); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_events_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_filesystem.h b/thirdparty/sdl/include/SDL3/SDL_filesystem.h new file mode 100644 index 00000000000..af3ca27e021 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_filesystem.h @@ -0,0 +1,503 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryFilesystem + * + * SDL offers an API for examining and manipulating the system's filesystem. + * This covers most things one would need to do with directories, except for + * actual file I/O (which is covered by [CategoryIOStream](CategoryIOStream) + * and [CategoryAsyncIO](CategoryAsyncIO) instead). + * + * There are functions to answer necessary path questions: + * + * - Where is my app's data? SDL_GetBasePath(). + * - Where can I safely write files? SDL_GetPrefPath(). + * - Where are paths like Downloads, Desktop, Music? SDL_GetUserFolder(). + * - What is this thing at this location? SDL_GetPathInfo(). + * - What items live in this folder? SDL_EnumerateDirectory(). + * - What items live in this folder by wildcard? SDL_GlobDirectory(). + * - What is my current working directory? SDL_GetCurrentDirectory(). + * + * SDL also offers functions to manipulate the directory tree: renaming, + * removing, copying files. + */ + +#ifndef SDL_filesystem_h_ +#define SDL_filesystem_h_ + +#include +#include + +#include + +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Get the directory where the application was run from. + * + * SDL caches the result of this call internally, but the first call to this + * function is not necessarily fast, so plan accordingly. + * + * **macOS and iOS Specific Functionality**: If the application is in a ".app" + * bundle, this function returns the Resource directory (e.g. + * MyApp.app/Contents/Resources/). This behaviour can be overridden by adding + * a property to the Info.plist file. Adding a string key with the name + * SDL_FILESYSTEM_BASE_DIR_TYPE with a supported value will change the + * behaviour. + * + * Supported values for the SDL_FILESYSTEM_BASE_DIR_TYPE property (Given an + * application in /Applications/SDLApp/MyApp.app): + * + * - `resource`: bundle resource directory (the default). For example: + * `/Applications/SDLApp/MyApp.app/Contents/Resources` + * - `bundle`: the Bundle directory. For example: + * `/Applications/SDLApp/MyApp.app/` + * - `parent`: the containing directory of the bundle. For example: + * `/Applications/SDLApp/` + * + * **Nintendo 3DS Specific Functionality**: This function returns "romfs" + * directory of the application as it is uncommon to store resources outside + * the executable. As such it is not a writable directory. + * + * The returned path is guaranteed to end with a path separator ('\\' on + * Windows, '/' on most other platforms). + * + * \returns an absolute path in UTF-8 encoding to the application data + * directory. NULL will be returned on error or when the platform + * doesn't implement this functionality, call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPrefPath + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetBasePath(void); + +/** + * Get the user-and-app-specific path where files can be written. + * + * Get the "pref dir". This is meant to be where users can write personal + * files (preferences and save games, etc) that are specific to your + * application. This directory is unique per user, per application. + * + * This function will decide the appropriate location in the native + * filesystem, create the directory if necessary, and return a string of the + * absolute path to the directory in UTF-8 encoding. + * + * On Windows, the string might look like: + * + * `C:\\Users\\bob\\AppData\\Roaming\\My Company\\My Program Name\\` + * + * On Linux, the string might look like: + * + * `/home/bob/.local/share/My Program Name/` + * + * On macOS, the string might look like: + * + * `/Users/bob/Library/Application Support/My Program Name/` + * + * You should assume the path returned by this function is the only safe place + * to write files (and that SDL_GetBasePath(), while it might be writable, or + * even the parent of the returned path, isn't where you should be writing + * things). + * + * Both the org and app strings may become part of a directory name, so please + * follow these rules: + * + * - Try to use the same org string (_including case-sensitivity_) for all + * your applications that use this function. + * - Always use a unique app string for each one, and make sure it never + * changes for an app once you've decided on it. + * - Unicode characters are legal, as long as they are UTF-8 encoded, but... + * - ...only use letters, numbers, and spaces. Avoid punctuation like "Game + * Name 2: Bad Guy's Revenge!" ... "Game Name 2" is sufficient. + * + * The returned path is guaranteed to end with a path separator ('\\' on + * Windows, '/' on most other platforms). + * + * \param org the name of your organization. + * \param app the name of your application. + * \returns a UTF-8 string of the user directory in platform-dependent + * notation. NULL if there's a problem (creating directory failed, + * etc.). This should be freed with SDL_free() when it is no longer + * needed. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetBasePath + */ +extern SDL_DECLSPEC char * SDLCALL SDL_GetPrefPath(const char *org, const char *app); + +/** + * The type of the OS-provided default folder for a specific purpose. + * + * Note that the Trash folder isn't included here, because trashing files + * usually involves extra OS-specific functionality to remember the file's + * original location. + * + * The folders supported per platform are: + * + * | | Windows | macOS/iOS | tvOS | Unix (XDG) | Haiku | Emscripten | + * | ----------- | ------- | --------- | ---- | ---------- | ----- | ---------- | + * | HOME | X | X | | X | X | X | + * | DESKTOP | X | X | | X | X | | + * | DOCUMENTS | X | X | | X | | | + * | DOWNLOADS | Vista+ | X | | X | | | + * | MUSIC | X | X | | X | | | + * | PICTURES | X | X | | X | | | + * | PUBLICSHARE | | X | | X | | | + * | SAVEDGAMES | Vista+ | | | | | | + * | SCREENSHOTS | Vista+ | | | | | | + * | TEMPLATES | X | X | | X | | | + * | VIDEOS | X | X* | | X | | | + * + * Note that on macOS/iOS, the Videos folder is called "Movies". + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_GetUserFolder + */ +typedef enum SDL_Folder +{ + SDL_FOLDER_HOME, /**< The folder which contains all of the current user's data, preferences, and documents. It usually contains most of the other folders. If a requested folder does not exist, the home folder can be considered a safe fallback to store a user's documents. */ + SDL_FOLDER_DESKTOP, /**< The folder of files that are displayed on the desktop. Note that the existence of a desktop folder does not guarantee that the system does show icons on its desktop; certain GNU/Linux distros with a graphical environment may not have desktop icons. */ + SDL_FOLDER_DOCUMENTS, /**< User document files, possibly application-specific. This is a good place to save a user's projects. */ + SDL_FOLDER_DOWNLOADS, /**< Standard folder for user files downloaded from the internet. */ + SDL_FOLDER_MUSIC, /**< Music files that can be played using a standard music player (mp3, ogg...). */ + SDL_FOLDER_PICTURES, /**< Image files that can be displayed using a standard viewer (png, jpg...). */ + SDL_FOLDER_PUBLICSHARE, /**< Files that are meant to be shared with other users on the same computer. */ + SDL_FOLDER_SAVEDGAMES, /**< Save files for games. */ + SDL_FOLDER_SCREENSHOTS, /**< Application screenshots. */ + SDL_FOLDER_TEMPLATES, /**< Template files to be used when the user requests the desktop environment to create a new file in a certain folder, such as "New Text File.txt". Any file in the Templates folder can be used as a starting point for a new file. */ + SDL_FOLDER_VIDEOS, /**< Video files that can be played using a standard video player (mp4, webm...). */ + SDL_FOLDER_COUNT /**< Total number of types in this enum, not a folder type by itself. */ +} SDL_Folder; + +/** + * Finds the most suitable user folder for a specific purpose. + * + * Many OSes provide certain standard folders for certain purposes, such as + * storing pictures, music or videos for a certain user. This function gives + * the path for many of those special locations. + * + * This function is specifically for _user_ folders, which are meant for the + * user to access and manage. For application-specific folders, meant to hold + * data for the application to manage, see SDL_GetBasePath() and + * SDL_GetPrefPath(). + * + * The returned path is guaranteed to end with a path separator ('\\' on + * Windows, '/' on most other platforms). + * + * If NULL is returned, the error may be obtained with SDL_GetError(). + * + * \param folder the type of folder to find. + * \returns either a null-terminated C string containing the full path to the + * folder, or NULL if an error happened. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetUserFolder(SDL_Folder folder); + + +/* Abstract filesystem interface */ + +/** + * Types of filesystem entries. + * + * Note that there may be other sorts of items on a filesystem: devices, + * symlinks, named pipes, etc. They are currently reported as + * SDL_PATHTYPE_OTHER. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_PathInfo + */ +typedef enum SDL_PathType +{ + SDL_PATHTYPE_NONE, /**< path does not exist */ + SDL_PATHTYPE_FILE, /**< a normal file */ + SDL_PATHTYPE_DIRECTORY, /**< a directory */ + SDL_PATHTYPE_OTHER /**< something completely different like a device node (not a symlink, those are always followed) */ +} SDL_PathType; + +/** + * Information about a path on the filesystem. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_GetPathInfo + * \sa SDL_GetStoragePathInfo + */ +typedef struct SDL_PathInfo +{ + SDL_PathType type; /**< the path type */ + Uint64 size; /**< the file size in bytes */ + SDL_Time create_time; /**< the time when the path was created */ + SDL_Time modify_time; /**< the last time the path was modified */ + SDL_Time access_time; /**< the last time the path was read */ +} SDL_PathInfo; + +/** + * Flags for path matching. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_GlobDirectory + * \sa SDL_GlobStorageDirectory + */ +typedef Uint32 SDL_GlobFlags; + +#define SDL_GLOB_CASEINSENSITIVE (1u << 0) + +/** + * Create a directory, and any missing parent directories. + * + * This reports success if `path` already exists as a directory. + * + * If parent directories are missing, it will also create them. Note that if + * this fails, it will not remove any parent directories it already made. + * + * \param path the path of the directory to create. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CreateDirectory(const char *path); + +/** + * Possible results from an enumeration callback. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_EnumerateDirectoryCallback + */ +typedef enum SDL_EnumerationResult +{ + SDL_ENUM_CONTINUE, /**< Value that requests that enumeration continue. */ + SDL_ENUM_SUCCESS, /**< Value that requests that enumeration stop, successfully. */ + SDL_ENUM_FAILURE /**< Value that requests that enumeration stop, as a failure. */ +} SDL_EnumerationResult; + +/** + * Callback for directory enumeration. + * + * Enumeration of directory entries will continue until either all entries + * have been provided to the callback, or the callback has requested a stop + * through its return value. + * + * Returning SDL_ENUM_CONTINUE will let enumeration proceed, calling the + * callback with further entries. SDL_ENUM_SUCCESS and SDL_ENUM_FAILURE will + * terminate the enumeration early, and dictate the return value of the + * enumeration function itself. + * + * `dirname` is guaranteed to end with a path separator ('\\' on Windows, '/' + * on most other platforms). + * + * \param userdata an app-controlled pointer that is passed to the callback. + * \param dirname the directory that is being enumerated. + * \param fname the next entry in the enumeration. + * \returns how the enumeration should proceed. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_EnumerateDirectory + */ +typedef SDL_EnumerationResult (SDLCALL *SDL_EnumerateDirectoryCallback)(void *userdata, const char *dirname, const char *fname); + +/** + * Enumerate a directory through a callback function. + * + * This function provides every directory entry through an app-provided + * callback, called once for each directory entry, until all results have been + * provided or the callback returns either SDL_ENUM_SUCCESS or + * SDL_ENUM_FAILURE. + * + * This will return false if there was a system problem in general, or if a + * callback returns SDL_ENUM_FAILURE. A successful return means a callback + * returned SDL_ENUM_SUCCESS to halt enumeration, or all directory entries + * were enumerated. + * + * \param path the path of the directory to enumerate. + * \param callback a function that is called for each entry in the directory. + * \param userdata a pointer that is passed to `callback`. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_EnumerateDirectory(const char *path, SDL_EnumerateDirectoryCallback callback, void *userdata); + +/** + * Remove a file or an empty directory. + * + * Directories that are not empty will fail; this function will not recursely + * delete directory trees. + * + * \param path the path to remove from the filesystem. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RemovePath(const char *path); + +/** + * Rename a file or directory. + * + * If the file at `newpath` already exists, it will replaced. + * + * Note that this will not copy files across filesystems/drives/volumes, as + * that is a much more complicated (and possibly time-consuming) operation. + * + * Which is to say, if this function fails, SDL_CopyFile() to a temporary file + * in the same directory as `newpath`, then SDL_RenamePath() from the + * temporary file to `newpath` and SDL_RemovePath() on `oldpath` might work + * for files. Renaming a non-empty directory across filesystems is + * dramatically more complex, however. + * + * \param oldpath the old path. + * \param newpath the new path. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenamePath(const char *oldpath, const char *newpath); + +/** + * Copy a file. + * + * If the file at `newpath` already exists, it will be overwritten with the + * contents of the file at `oldpath`. + * + * This function will block until the copy is complete, which might be a + * significant time for large files on slow disks. On some platforms, the copy + * can be handed off to the OS itself, but on others SDL might just open both + * paths, and read from one and write to the other. + * + * Note that this is not an atomic operation! If something tries to read from + * `newpath` while the copy is in progress, it will see an incomplete copy of + * the data, and if the calling thread terminates (or the power goes out) + * during the copy, `newpath`'s previous contents will be gone, replaced with + * an incomplete copy of the data. To avoid this risk, it is recommended that + * the app copy to a temporary file in the same directory as `newpath`, and if + * the copy is successful, use SDL_RenamePath() to replace `newpath` with the + * temporary file. This will ensure that reads of `newpath` will either see a + * complete copy of the data, or it will see the pre-copy state of `newpath`. + * + * This function attempts to synchronize the newly-copied data to disk before + * returning, if the platform allows it, so that the renaming trick will not + * have a problem in a system crash or power failure, where the file could be + * renamed but the contents never made it from the system file cache to the + * physical disk. + * + * If the copy fails for any reason, the state of `newpath` is undefined. It + * might be half a copy, it might be the untouched data of what was already + * there, or it might be a zero-byte file, etc. + * + * \param oldpath the old path. + * \param newpath the new path. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CopyFile(const char *oldpath, const char *newpath); + +/** + * Get information about a filesystem path. + * + * \param path the path to query. + * \param info a pointer filled in with information about the path, or NULL to + * check for the existence of a file. + * \returns true on success or false if the file doesn't exist, or another + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetPathInfo(const char *path, SDL_PathInfo *info); + +/** + * Enumerate a directory tree, filtered by pattern, and return a list. + * + * Files are filtered out if they don't match the string in `pattern`, which + * may contain wildcard characters '\*' (match everything) and '?' (match one + * character). If pattern is NULL, no filtering is done and all results are + * returned. Subdirectories are permitted, and are specified with a path + * separator of '/'. Wildcard characters '\*' and '?' never match a path + * separator. + * + * `flags` may be set to SDL_GLOB_CASEINSENSITIVE to make the pattern matching + * case-insensitive. + * + * The returned array is always NULL-terminated, for your iterating + * convenience, but if `count` is non-NULL, on return it will contain the + * number of items in the array, not counting the NULL terminator. + * + * \param path the path of the directory to enumerate. + * \param pattern the pattern that files in the directory must match. Can be + * NULL. + * \param flags `SDL_GLOB_*` bitflags that affect this search. + * \param count on return, will be set to the number of items in the returned + * array. Can be NULL. + * \returns an array of strings on success or NULL on failure; call + * SDL_GetError() for more information. This is a single allocation + * that should be freed with SDL_free() when it is no longer needed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char ** SDLCALL SDL_GlobDirectory(const char *path, const char *pattern, SDL_GlobFlags flags, int *count); + +/** + * Get what the system believes is the "current working directory." + * + * For systems without a concept of a current working directory, this will + * still attempt to provide something reasonable. + * + * SDL does not provide a means to _change_ the current working directory; for + * platforms without this concept, this would cause surprises with file access + * outside of SDL. + * + * The returned path is guaranteed to end with a path separator ('\\' on + * Windows, '/' on most other platforms). + * + * \returns a UTF-8 string of the current working directory in + * platform-dependent notation. NULL if there's a problem. This + * should be freed with SDL_free() when it is no longer needed. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char * SDLCALL SDL_GetCurrentDirectory(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_filesystem_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_gamepad.h b/thirdparty/sdl/include/SDL3/SDL_gamepad.h new file mode 100644 index 00000000000..99f8b6593fa --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_gamepad.h @@ -0,0 +1,1509 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryGamepad + * + * SDL provides a low-level joystick API, which just treats joysticks as an + * arbitrary pile of buttons, axes, and hat switches. If you're planning to + * write your own control configuration screen, this can give you a lot of + * flexibility, but that's a lot of work, and most things that we consider + * "joysticks" now are actually console-style gamepads. So SDL provides the + * gamepad API on top of the lower-level joystick functionality. + * + * The difference between a joystick and a gamepad is that a gamepad tells you + * _where_ a button or axis is on the device. You don't speak to gamepads in + * terms of arbitrary numbers like "button 3" or "axis 2" but in standard + * locations: the d-pad, the shoulder buttons, triggers, A/B/X/Y (or + * X/O/Square/Triangle, if you will). + * + * One turns a joystick into a gamepad by providing a magic configuration + * string, which tells SDL the details of a specific device: when you see this + * specific hardware, if button 2 gets pressed, this is actually D-Pad Up, + * etc. + * + * SDL has many popular controllers configured out of the box, and users can + * add their own controller details through an environment variable if it's + * otherwise unknown to SDL. + * + * In order to use these functions, SDL_Init() must have been called with the + * SDL_INIT_GAMEPAD flag. This causes SDL to scan the system for gamepads, and + * load appropriate drivers. + * + * If you would like to receive gamepad updates while the application is in + * the background, you should set the following hint before calling + * SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS + * + * Gamepads support various optional features such as rumble, color LEDs, + * touchpad, gyro, etc. The support for these features varies depending on the + * controller and OS support available. You can check for LED and rumble + * capabilities at runtime by calling SDL_GetGamepadProperties() and checking + * the various capability properties. You can check for touchpad by calling + * SDL_GetNumGamepadTouchpads() and check for gyro and accelerometer by + * calling SDL_GamepadHasSensor(). + * + * By default SDL will try to use the most capable driver available, but you + * can tune which OS drivers to use with the various joystick hints in + * SDL_hints.h. + * + * Your application should always support gamepad hotplugging. On some + * platforms like Xbox, Steam Deck, etc., this is a requirement for + * certification. On other platforms, like macOS and Windows when using + * Windows.Gaming.Input, controllers may not be available at startup and will + * come in at some point after you've started processing events. + */ + +#ifndef SDL_gamepad_h_ +#define SDL_gamepad_h_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The structure used to identify an SDL gamepad + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Gamepad SDL_Gamepad; + +/** + * Standard gamepad types. + * + * This type does not necessarily map to first-party controllers from + * Microsoft/Sony/Nintendo; in many cases, third-party controllers can report + * as these, either because they were designed for a specific console, or they + * simply most closely match that console's controllers (does it have A/B/X/Y + * buttons or X/O/Square/Triangle? Does it have a touchpad? etc). + */ +typedef enum SDL_GamepadType +{ + SDL_GAMEPAD_TYPE_UNKNOWN = 0, + SDL_GAMEPAD_TYPE_STANDARD, + SDL_GAMEPAD_TYPE_XBOX360, + SDL_GAMEPAD_TYPE_XBOXONE, + SDL_GAMEPAD_TYPE_PS3, + SDL_GAMEPAD_TYPE_PS4, + SDL_GAMEPAD_TYPE_PS5, + SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO, + SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT, + SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT, + SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR, + SDL_GAMEPAD_TYPE_COUNT +} SDL_GamepadType; + +/** + * The list of buttons available on a gamepad + * + * For controllers that use a diamond pattern for the face buttons, the + * south/east/west/north buttons below correspond to the locations in the + * diamond pattern. For Xbox controllers, this would be A/B/X/Y, for Nintendo + * Switch controllers, this would be B/A/Y/X, for PlayStation controllers this + * would be Cross/Circle/Square/Triangle. + * + * For controllers that don't use a diamond pattern for the face buttons, the + * south/east/west/north buttons indicate the buttons labeled A, B, C, D, or + * 1, 2, 3, 4, or for controllers that aren't labeled, they are the primary, + * secondary, etc. buttons. + * + * The activate action is often the south button and the cancel action is + * often the east button, but in some regions this is reversed, so your game + * should allow remapping actions based on user preferences. + * + * You can query the labels for the face buttons using + * SDL_GetGamepadButtonLabel() + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_GamepadButton +{ + SDL_GAMEPAD_BUTTON_INVALID = -1, + SDL_GAMEPAD_BUTTON_SOUTH, /**< Bottom face button (e.g. Xbox A button) */ + SDL_GAMEPAD_BUTTON_EAST, /**< Right face button (e.g. Xbox B button) */ + SDL_GAMEPAD_BUTTON_WEST, /**< Left face button (e.g. Xbox X button) */ + SDL_GAMEPAD_BUTTON_NORTH, /**< Top face button (e.g. Xbox Y button) */ + SDL_GAMEPAD_BUTTON_BACK, + SDL_GAMEPAD_BUTTON_GUIDE, + SDL_GAMEPAD_BUTTON_START, + SDL_GAMEPAD_BUTTON_LEFT_STICK, + SDL_GAMEPAD_BUTTON_RIGHT_STICK, + SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, + SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, + SDL_GAMEPAD_BUTTON_DPAD_UP, + SDL_GAMEPAD_BUTTON_DPAD_DOWN, + SDL_GAMEPAD_BUTTON_DPAD_LEFT, + SDL_GAMEPAD_BUTTON_DPAD_RIGHT, + SDL_GAMEPAD_BUTTON_MISC1, /**< Additional button (e.g. Xbox Series X share button, PS5 microphone button, Nintendo Switch Pro capture button, Amazon Luna microphone button, Google Stadia capture button) */ + SDL_GAMEPAD_BUTTON_RIGHT_PADDLE1, /**< Upper or primary paddle, under your right hand (e.g. Xbox Elite paddle P1) */ + SDL_GAMEPAD_BUTTON_LEFT_PADDLE1, /**< Upper or primary paddle, under your left hand (e.g. Xbox Elite paddle P3) */ + SDL_GAMEPAD_BUTTON_RIGHT_PADDLE2, /**< Lower or secondary paddle, under your right hand (e.g. Xbox Elite paddle P2) */ + SDL_GAMEPAD_BUTTON_LEFT_PADDLE2, /**< Lower or secondary paddle, under your left hand (e.g. Xbox Elite paddle P4) */ + SDL_GAMEPAD_BUTTON_TOUCHPAD, /**< PS4/PS5 touchpad button */ + SDL_GAMEPAD_BUTTON_MISC2, /**< Additional button */ + SDL_GAMEPAD_BUTTON_MISC3, /**< Additional button */ + SDL_GAMEPAD_BUTTON_MISC4, /**< Additional button */ + SDL_GAMEPAD_BUTTON_MISC5, /**< Additional button */ + SDL_GAMEPAD_BUTTON_MISC6, /**< Additional button */ + SDL_GAMEPAD_BUTTON_COUNT +} SDL_GamepadButton; + +/** + * The set of gamepad button labels + * + * This isn't a complete set, just the face buttons to make it easy to show + * button prompts. + * + * For a complete set, you should look at the button and gamepad type and have + * a set of symbols that work well with your art style. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_GamepadButtonLabel +{ + SDL_GAMEPAD_BUTTON_LABEL_UNKNOWN, + SDL_GAMEPAD_BUTTON_LABEL_A, + SDL_GAMEPAD_BUTTON_LABEL_B, + SDL_GAMEPAD_BUTTON_LABEL_X, + SDL_GAMEPAD_BUTTON_LABEL_Y, + SDL_GAMEPAD_BUTTON_LABEL_CROSS, + SDL_GAMEPAD_BUTTON_LABEL_CIRCLE, + SDL_GAMEPAD_BUTTON_LABEL_SQUARE, + SDL_GAMEPAD_BUTTON_LABEL_TRIANGLE +} SDL_GamepadButtonLabel; + +/** + * The list of axes available on a gamepad + * + * Thumbstick axis values range from SDL_JOYSTICK_AXIS_MIN to + * SDL_JOYSTICK_AXIS_MAX, and are centered within ~8000 of zero, though + * advanced UI will allow users to set or autodetect the dead zone, which + * varies between gamepads. + * + * Trigger axis values range from 0 (released) to SDL_JOYSTICK_AXIS_MAX (fully + * pressed) when reported by SDL_GetGamepadAxis(). Note that this is not the + * same range that will be reported by the lower-level SDL_GetJoystickAxis(). + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_GamepadAxis +{ + SDL_GAMEPAD_AXIS_INVALID = -1, + SDL_GAMEPAD_AXIS_LEFTX, + SDL_GAMEPAD_AXIS_LEFTY, + SDL_GAMEPAD_AXIS_RIGHTX, + SDL_GAMEPAD_AXIS_RIGHTY, + SDL_GAMEPAD_AXIS_LEFT_TRIGGER, + SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, + SDL_GAMEPAD_AXIS_COUNT +} SDL_GamepadAxis; + +/** + * Types of gamepad control bindings. + * + * A gamepad is a collection of bindings that map arbitrary joystick buttons, + * axes and hat switches to specific positions on a generic console-style + * gamepad. This enum is used as part of SDL_GamepadBinding to specify those + * mappings. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_GamepadBindingType +{ + SDL_GAMEPAD_BINDTYPE_NONE = 0, + SDL_GAMEPAD_BINDTYPE_BUTTON, + SDL_GAMEPAD_BINDTYPE_AXIS, + SDL_GAMEPAD_BINDTYPE_HAT +} SDL_GamepadBindingType; + +/** + * A mapping between one joystick input to a gamepad control. + * + * A gamepad has a collection of several bindings, to say, for example, when + * joystick button number 5 is pressed, that should be treated like the + * gamepad's "start" button. + * + * SDL has these bindings built-in for many popular controllers, and can add + * more with a simple text string. Those strings are parsed into a collection + * of these structs to make it easier to operate on the data. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadBindings + */ +typedef struct SDL_GamepadBinding +{ + SDL_GamepadBindingType input_type; + union + { + int button; + + struct + { + int axis; + int axis_min; + int axis_max; + } axis; + + struct + { + int hat; + int hat_mask; + } hat; + + } input; + + SDL_GamepadBindingType output_type; + union + { + SDL_GamepadButton button; + + struct + { + SDL_GamepadAxis axis; + int axis_min; + int axis_max; + } axis; + + } output; +} SDL_GamepadBinding; + + +/** + * Add support for gamepads that SDL is unaware of or change the binding of an + * existing gamepad. + * + * The mapping string has the format "GUID,name,mapping", where GUID is the + * string value from SDL_GUIDToString(), name is the human readable string for + * the device and mappings are gamepad mappings to joystick ones. Under + * Windows there is a reserved GUID of "xinput" that covers all XInput + * devices. The mapping format for joystick is: + * + * - `bX`: a joystick button, index X + * - `hX.Y`: hat X with value Y + * - `aX`: axis X of the joystick + * + * Buttons can be used as a gamepad axes and vice versa. + * + * If a device with this GUID is already plugged in, SDL will generate an + * SDL_EVENT_GAMEPAD_ADDED event. + * + * This string shows an example of a valid mapping for a gamepad: + * + * ```c + * "341a3608000000000000504944564944,Afterglow PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7" + * ``` + * + * \param mapping the mapping string. + * \returns 1 if a new mapping is added, 0 if an existing mapping is updated, + * -1 on failure; call SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddGamepadMappingsFromFile + * \sa SDL_AddGamepadMappingsFromIO + * \sa SDL_GetGamepadMapping + * \sa SDL_GetGamepadMappingForGUID + * \sa SDL_HINT_GAMECONTROLLERCONFIG + * \sa SDL_HINT_GAMECONTROLLERCONFIG_FILE + * \sa SDL_EVENT_GAMEPAD_ADDED + */ +extern SDL_DECLSPEC int SDLCALL SDL_AddGamepadMapping(const char *mapping); + +/** + * Load a set of gamepad mappings from an SDL_IOStream. + * + * You can call this function several times, if needed, to load different + * database files. + * + * If a new mapping is loaded for an already known gamepad GUID, the later + * version will overwrite the one currently loaded. + * + * Any new mappings for already plugged in controllers will generate + * SDL_EVENT_GAMEPAD_ADDED events. + * + * Mappings not belonging to the current platform or with no platform field + * specified will be ignored (i.e. mappings for Linux will be ignored in + * Windows, etc). + * + * This function will load the text database entirely in memory before + * processing it, so take this into consideration if you are in a memory + * constrained environment. + * + * \param src the data stream for the mappings to be added. + * \param closeio if true, calls SDL_CloseIO() on `src` before returning, even + * in the case of an error. + * \returns the number of mappings added or -1 on failure; call SDL_GetError() + * for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddGamepadMapping + * \sa SDL_AddGamepadMappingsFromFile + * \sa SDL_GetGamepadMapping + * \sa SDL_GetGamepadMappingForGUID + * \sa SDL_HINT_GAMECONTROLLERCONFIG + * \sa SDL_HINT_GAMECONTROLLERCONFIG_FILE + * \sa SDL_EVENT_GAMEPAD_ADDED + */ +extern SDL_DECLSPEC int SDLCALL SDL_AddGamepadMappingsFromIO(SDL_IOStream *src, bool closeio); + +/** + * Load a set of gamepad mappings from a file. + * + * You can call this function several times, if needed, to load different + * database files. + * + * If a new mapping is loaded for an already known gamepad GUID, the later + * version will overwrite the one currently loaded. + * + * Any new mappings for already plugged in controllers will generate + * SDL_EVENT_GAMEPAD_ADDED events. + * + * Mappings not belonging to the current platform or with no platform field + * specified will be ignored (i.e. mappings for Linux will be ignored in + * Windows, etc). + * + * \param file the mappings file to load. + * \returns the number of mappings added or -1 on failure; call SDL_GetError() + * for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddGamepadMapping + * \sa SDL_AddGamepadMappingsFromIO + * \sa SDL_GetGamepadMapping + * \sa SDL_GetGamepadMappingForGUID + * \sa SDL_HINT_GAMECONTROLLERCONFIG + * \sa SDL_HINT_GAMECONTROLLERCONFIG_FILE + * \sa SDL_EVENT_GAMEPAD_ADDED + */ +extern SDL_DECLSPEC int SDLCALL SDL_AddGamepadMappingsFromFile(const char *file); + +/** + * Reinitialize the SDL mapping database to its initial state. + * + * This will generate gamepad events as needed if device mappings change. + * + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReloadGamepadMappings(void); + +/** + * Get the current gamepad mappings. + * + * \param count a pointer filled in with the number of mappings returned, can + * be NULL. + * \returns an array of the mapping strings, NULL-terminated, or NULL on + * failure; call SDL_GetError() for more information. This is a + * single allocation that should be freed with SDL_free() when it is + * no longer needed. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char ** SDLCALL SDL_GetGamepadMappings(int *count); + +/** + * Get the gamepad mapping string for a given GUID. + * + * \param guid a structure containing the GUID for which a mapping is desired. + * \returns a mapping string or NULL on failure; call SDL_GetError() for more + * information. This should be freed with SDL_free() when it is no + * longer needed. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickGUIDForID + * \sa SDL_GetJoystickGUID + */ +extern SDL_DECLSPEC char * SDLCALL SDL_GetGamepadMappingForGUID(SDL_GUID guid); + +/** + * Get the current mapping of a gamepad. + * + * Details about mappings are discussed with SDL_AddGamepadMapping(). + * + * \param gamepad the gamepad you want to get the current mapping for. + * \returns a string that has the gamepad's mapping or NULL if no mapping is + * available; call SDL_GetError() for more information. This should + * be freed with SDL_free() when it is no longer needed. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddGamepadMapping + * \sa SDL_GetGamepadMappingForID + * \sa SDL_GetGamepadMappingForGUID + * \sa SDL_SetGamepadMapping + */ +extern SDL_DECLSPEC char * SDLCALL SDL_GetGamepadMapping(SDL_Gamepad *gamepad); + +/** + * Set the current mapping of a joystick or gamepad. + * + * Details about mappings are discussed with SDL_AddGamepadMapping(). + * + * \param instance_id the joystick instance ID. + * \param mapping the mapping to use for this device, or NULL to clear the + * mapping. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddGamepadMapping + * \sa SDL_GetGamepadMapping + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetGamepadMapping(SDL_JoystickID instance_id, const char *mapping); + +/** + * Return whether a gamepad is currently connected. + * + * \returns true if a gamepad is connected, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepads + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasGamepad(void); + +/** + * Get a list of currently connected gamepads. + * + * \param count a pointer filled in with the number of gamepads returned, may + * be NULL. + * \returns a 0 terminated array of joystick instance IDs or NULL on failure; + * call SDL_GetError() for more information. This should be freed + * with SDL_free() when it is no longer needed. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasGamepad + * \sa SDL_OpenGamepad + */ +extern SDL_DECLSPEC SDL_JoystickID * SDLCALL SDL_GetGamepads(int *count); + +/** + * Check if the given joystick is supported by the gamepad interface. + * + * \param instance_id the joystick instance ID. + * \returns true if the given joystick is supported by the gamepad interface, + * false if it isn't or it's an invalid index. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoysticks + * \sa SDL_OpenGamepad + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsGamepad(SDL_JoystickID instance_id); + +/** + * Get the implementation dependent name of a gamepad. + * + * This can be called before any gamepads are opened. + * + * \param instance_id the joystick instance ID. + * \returns the name of the selected gamepad. If no name can be found, this + * function returns NULL; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadName + * \sa SDL_GetGamepads + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetGamepadNameForID(SDL_JoystickID instance_id); + +/** + * Get the implementation dependent path of a gamepad. + * + * This can be called before any gamepads are opened. + * + * \param instance_id the joystick instance ID. + * \returns the path of the selected gamepad. If no path can be found, this + * function returns NULL; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadPath + * \sa SDL_GetGamepads + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetGamepadPathForID(SDL_JoystickID instance_id); + +/** + * Get the player index of a gamepad. + * + * This can be called before any gamepads are opened. + * + * \param instance_id the joystick instance ID. + * \returns the player index of a gamepad, or -1 if it's not available. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadPlayerIndex + * \sa SDL_GetGamepads + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetGamepadPlayerIndexForID(SDL_JoystickID instance_id); + +/** + * Get the implementation-dependent GUID of a gamepad. + * + * This can be called before any gamepads are opened. + * + * \param instance_id the joystick instance ID. + * \returns the GUID of the selected gamepad. If called on an invalid index, + * this function returns a zero GUID. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GUIDToString + * \sa SDL_GetGamepads + */ +extern SDL_DECLSPEC SDL_GUID SDLCALL SDL_GetGamepadGUIDForID(SDL_JoystickID instance_id); + +/** + * Get the USB vendor ID of a gamepad, if available. + * + * This can be called before any gamepads are opened. If the vendor ID isn't + * available this function returns 0. + * + * \param instance_id the joystick instance ID. + * \returns the USB vendor ID of the selected gamepad. If called on an invalid + * index, this function returns zero. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadVendor + * \sa SDL_GetGamepads + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetGamepadVendorForID(SDL_JoystickID instance_id); + +/** + * Get the USB product ID of a gamepad, if available. + * + * This can be called before any gamepads are opened. If the product ID isn't + * available this function returns 0. + * + * \param instance_id the joystick instance ID. + * \returns the USB product ID of the selected gamepad. If called on an + * invalid index, this function returns zero. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadProduct + * \sa SDL_GetGamepads + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetGamepadProductForID(SDL_JoystickID instance_id); + +/** + * Get the product version of a gamepad, if available. + * + * This can be called before any gamepads are opened. If the product version + * isn't available this function returns 0. + * + * \param instance_id the joystick instance ID. + * \returns the product version of the selected gamepad. If called on an + * invalid index, this function returns zero. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadProductVersion + * \sa SDL_GetGamepads + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetGamepadProductVersionForID(SDL_JoystickID instance_id); + +/** + * Get the type of a gamepad. + * + * This can be called before any gamepads are opened. + * + * \param instance_id the joystick instance ID. + * \returns the gamepad type. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadType + * \sa SDL_GetGamepads + * \sa SDL_GetRealGamepadTypeForID + */ +extern SDL_DECLSPEC SDL_GamepadType SDLCALL SDL_GetGamepadTypeForID(SDL_JoystickID instance_id); + +/** + * Get the type of a gamepad, ignoring any mapping override. + * + * This can be called before any gamepads are opened. + * + * \param instance_id the joystick instance ID. + * \returns the gamepad type. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadTypeForID + * \sa SDL_GetGamepads + * \sa SDL_GetRealGamepadType + */ +extern SDL_DECLSPEC SDL_GamepadType SDLCALL SDL_GetRealGamepadTypeForID(SDL_JoystickID instance_id); + +/** + * Get the mapping of a gamepad. + * + * This can be called before any gamepads are opened. + * + * \param instance_id the joystick instance ID. + * \returns the mapping string. Returns NULL if no mapping is available. This + * should be freed with SDL_free() when it is no longer needed. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepads + * \sa SDL_GetGamepadMapping + */ +extern SDL_DECLSPEC char * SDLCALL SDL_GetGamepadMappingForID(SDL_JoystickID instance_id); + +/** + * Open a gamepad for use. + * + * \param instance_id the joystick instance ID. + * \returns a gamepad identifier or NULL if an error occurred; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseGamepad + * \sa SDL_IsGamepad + */ +extern SDL_DECLSPEC SDL_Gamepad * SDLCALL SDL_OpenGamepad(SDL_JoystickID instance_id); + +/** + * Get the SDL_Gamepad associated with a joystick instance ID, if it has been + * opened. + * + * \param instance_id the joystick instance ID of the gamepad. + * \returns an SDL_Gamepad on success or NULL on failure or if it hasn't been + * opened yet; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Gamepad * SDLCALL SDL_GetGamepadFromID(SDL_JoystickID instance_id); + +/** + * Get the SDL_Gamepad associated with a player index. + * + * \param player_index the player index, which different from the instance ID. + * \returns the SDL_Gamepad associated with a player index. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadPlayerIndex + * \sa SDL_SetGamepadPlayerIndex + */ +extern SDL_DECLSPEC SDL_Gamepad * SDLCALL SDL_GetGamepadFromPlayerIndex(int player_index); + +/** + * Get the properties associated with an opened gamepad. + * + * These properties are shared with the underlying joystick object. + * + * The following read-only properties are provided by SDL: + * + * - `SDL_PROP_GAMEPAD_CAP_MONO_LED_BOOLEAN`: true if this gamepad has an LED + * that has adjustable brightness + * - `SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN`: true if this gamepad has an LED + * that has adjustable color + * - `SDL_PROP_GAMEPAD_CAP_PLAYER_LED_BOOLEAN`: true if this gamepad has a + * player LED + * - `SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN`: true if this gamepad has + * left/right rumble + * - `SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN`: true if this gamepad has + * simple trigger rumble + * + * \param gamepad a gamepad identifier previously returned by + * SDL_OpenGamepad(). + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetGamepadProperties(SDL_Gamepad *gamepad); + +#define SDL_PROP_GAMEPAD_CAP_MONO_LED_BOOLEAN SDL_PROP_JOYSTICK_CAP_MONO_LED_BOOLEAN +#define SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN +#define SDL_PROP_GAMEPAD_CAP_PLAYER_LED_BOOLEAN SDL_PROP_JOYSTICK_CAP_PLAYER_LED_BOOLEAN +#define SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN +#define SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN + +/** + * Get the instance ID of an opened gamepad. + * + * \param gamepad a gamepad identifier previously returned by + * SDL_OpenGamepad(). + * \returns the instance ID of the specified gamepad on success or 0 on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_JoystickID SDLCALL SDL_GetGamepadID(SDL_Gamepad *gamepad); + +/** + * Get the implementation-dependent name for an opened gamepad. + * + * \param gamepad a gamepad identifier previously returned by + * SDL_OpenGamepad(). + * \returns the implementation dependent name for the gamepad, or NULL if + * there is no name or the identifier passed is invalid. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadNameForID + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetGamepadName(SDL_Gamepad *gamepad); + +/** + * Get the implementation-dependent path for an opened gamepad. + * + * \param gamepad a gamepad identifier previously returned by + * SDL_OpenGamepad(). + * \returns the implementation dependent path for the gamepad, or NULL if + * there is no path or the identifier passed is invalid. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadPathForID + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetGamepadPath(SDL_Gamepad *gamepad); + +/** + * Get the type of an opened gamepad. + * + * \param gamepad the gamepad object to query. + * \returns the gamepad type, or SDL_GAMEPAD_TYPE_UNKNOWN if it's not + * available. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadTypeForID + */ +extern SDL_DECLSPEC SDL_GamepadType SDLCALL SDL_GetGamepadType(SDL_Gamepad *gamepad); + +/** + * Get the type of an opened gamepad, ignoring any mapping override. + * + * \param gamepad the gamepad object to query. + * \returns the gamepad type, or SDL_GAMEPAD_TYPE_UNKNOWN if it's not + * available. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRealGamepadTypeForID + */ +extern SDL_DECLSPEC SDL_GamepadType SDLCALL SDL_GetRealGamepadType(SDL_Gamepad *gamepad); + +/** + * Get the player index of an opened gamepad. + * + * For XInput gamepads this returns the XInput user index. + * + * \param gamepad the gamepad object to query. + * \returns the player index for gamepad, or -1 if it's not available. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetGamepadPlayerIndex + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetGamepadPlayerIndex(SDL_Gamepad *gamepad); + +/** + * Set the player index of an opened gamepad. + * + * \param gamepad the gamepad object to adjust. + * \param player_index player index to assign to this gamepad, or -1 to clear + * the player index and turn off player LEDs. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadPlayerIndex + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetGamepadPlayerIndex(SDL_Gamepad *gamepad, int player_index); + +/** + * Get the USB vendor ID of an opened gamepad, if available. + * + * If the vendor ID isn't available this function returns 0. + * + * \param gamepad the gamepad object to query. + * \returns the USB vendor ID, or zero if unavailable. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadVendorForID + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetGamepadVendor(SDL_Gamepad *gamepad); + +/** + * Get the USB product ID of an opened gamepad, if available. + * + * If the product ID isn't available this function returns 0. + * + * \param gamepad the gamepad object to query. + * \returns the USB product ID, or zero if unavailable. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadProductForID + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetGamepadProduct(SDL_Gamepad *gamepad); + +/** + * Get the product version of an opened gamepad, if available. + * + * If the product version isn't available this function returns 0. + * + * \param gamepad the gamepad object to query. + * \returns the USB product version, or zero if unavailable. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadProductVersionForID + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetGamepadProductVersion(SDL_Gamepad *gamepad); + +/** + * Get the firmware version of an opened gamepad, if available. + * + * If the firmware version isn't available this function returns 0. + * + * \param gamepad the gamepad object to query. + * \returns the gamepad firmware version, or zero if unavailable. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetGamepadFirmwareVersion(SDL_Gamepad *gamepad); + +/** + * Get the serial number of an opened gamepad, if available. + * + * Returns the serial number of the gamepad, or NULL if it is not available. + * + * \param gamepad the gamepad object to query. + * \returns the serial number, or NULL if unavailable. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetGamepadSerial(SDL_Gamepad *gamepad); + +/** + * Get the Steam Input handle of an opened gamepad, if available. + * + * Returns an InputHandle_t for the gamepad that can be used with Steam Input + * API: https://partner.steamgames.com/doc/api/ISteamInput + * + * \param gamepad the gamepad object to query. + * \returns the gamepad handle, or 0 if unavailable. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint64 SDLCALL SDL_GetGamepadSteamHandle(SDL_Gamepad *gamepad); + +/** + * Get the connection state of a gamepad. + * + * \param gamepad the gamepad object to query. + * \returns the connection state on success or + * `SDL_JOYSTICK_CONNECTION_INVALID` on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_JoystickConnectionState SDLCALL SDL_GetGamepadConnectionState(SDL_Gamepad *gamepad); + +/** + * Get the battery state of a gamepad. + * + * You should never take a battery status as absolute truth. Batteries + * (especially failing batteries) are delicate hardware, and the values + * reported here are best estimates based on what that hardware reports. It's + * not uncommon for older batteries to lose stored power much faster than it + * reports, or completely drain when reporting it has 20 percent left, etc. + * + * \param gamepad the gamepad object to query. + * \param percent a pointer filled in with the percentage of battery life + * left, between 0 and 100, or NULL to ignore. This will be + * filled in with -1 we can't determine a value or there is no + * battery. + * \returns the current battery state. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PowerState SDLCALL SDL_GetGamepadPowerInfo(SDL_Gamepad *gamepad, int *percent); + +/** + * Check if a gamepad has been opened and is currently connected. + * + * \param gamepad a gamepad identifier previously returned by + * SDL_OpenGamepad(). + * \returns true if the gamepad has been opened and is currently connected, or + * false if not. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GamepadConnected(SDL_Gamepad *gamepad); + +/** + * Get the underlying joystick from a gamepad. + * + * This function will give you a SDL_Joystick object, which allows you to use + * the SDL_Joystick functions with a SDL_Gamepad object. This would be useful + * for getting a joystick's position at any given time, even if it hasn't + * moved (moving it would produce an event, which would have the axis' value). + * + * The pointer returned is owned by the SDL_Gamepad. You should not call + * SDL_CloseJoystick() on it, for example, since doing so will likely cause + * SDL to crash. + * + * \param gamepad the gamepad object that you want to get a joystick from. + * \returns an SDL_Joystick object, or NULL on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Joystick * SDLCALL SDL_GetGamepadJoystick(SDL_Gamepad *gamepad); + +/** + * Set the state of gamepad event processing. + * + * If gamepad events are disabled, you must call SDL_UpdateGamepads() yourself + * and check the state of the gamepad when you want gamepad information. + * + * \param enabled whether to process gamepad events or not. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GamepadEventsEnabled + * \sa SDL_UpdateGamepads + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetGamepadEventsEnabled(bool enabled); + +/** + * Query the state of gamepad event processing. + * + * If gamepad events are disabled, you must call SDL_UpdateGamepads() yourself + * and check the state of the gamepad when you want gamepad information. + * + * \returns true if gamepad events are being processed, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetGamepadEventsEnabled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GamepadEventsEnabled(void); + +/** + * Get the SDL joystick layer bindings for a gamepad. + * + * \param gamepad a gamepad. + * \param count a pointer filled in with the number of bindings returned. + * \returns a NULL terminated array of pointers to bindings or NULL on + * failure; call SDL_GetError() for more information. This is a + * single allocation that should be freed with SDL_free() when it is + * no longer needed. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_GamepadBinding ** SDLCALL SDL_GetGamepadBindings(SDL_Gamepad *gamepad, int *count); + +/** + * Manually pump gamepad updates if not using the loop. + * + * This function is called automatically by the event loop if events are + * enabled. Under such circumstances, it will not be necessary to call this + * function. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_UpdateGamepads(void); + +/** + * Convert a string into SDL_GamepadType enum. + * + * This function is called internally to translate SDL_Gamepad mapping strings + * for the underlying joystick device into the consistent SDL_Gamepad mapping. + * You do not normally need to call this function unless you are parsing + * SDL_Gamepad mappings in your own code. + * + * \param str string representing a SDL_GamepadType type. + * \returns the SDL_GamepadType enum corresponding to the input string, or + * `SDL_GAMEPAD_TYPE_UNKNOWN` if no match was found. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadStringForType + */ +extern SDL_DECLSPEC SDL_GamepadType SDLCALL SDL_GetGamepadTypeFromString(const char *str); + +/** + * Convert from an SDL_GamepadType enum to a string. + * + * \param type an enum value for a given SDL_GamepadType. + * \returns a string for the given type, or NULL if an invalid type is + * specified. The string returned is of the format used by + * SDL_Gamepad mapping strings. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadTypeFromString + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetGamepadStringForType(SDL_GamepadType type); + +/** + * Convert a string into SDL_GamepadAxis enum. + * + * This function is called internally to translate SDL_Gamepad mapping strings + * for the underlying joystick device into the consistent SDL_Gamepad mapping. + * You do not normally need to call this function unless you are parsing + * SDL_Gamepad mappings in your own code. + * + * Note specially that "righttrigger" and "lefttrigger" map to + * `SDL_GAMEPAD_AXIS_RIGHT_TRIGGER` and `SDL_GAMEPAD_AXIS_LEFT_TRIGGER`, + * respectively. + * + * \param str string representing a SDL_Gamepad axis. + * \returns the SDL_GamepadAxis enum corresponding to the input string, or + * `SDL_GAMEPAD_AXIS_INVALID` if no match was found. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadStringForAxis + */ +extern SDL_DECLSPEC SDL_GamepadAxis SDLCALL SDL_GetGamepadAxisFromString(const char *str); + +/** + * Convert from an SDL_GamepadAxis enum to a string. + * + * \param axis an enum value for a given SDL_GamepadAxis. + * \returns a string for the given axis, or NULL if an invalid axis is + * specified. The string returned is of the format used by + * SDL_Gamepad mapping strings. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadAxisFromString + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetGamepadStringForAxis(SDL_GamepadAxis axis); + +/** + * Query whether a gamepad has a given axis. + * + * This merely reports whether the gamepad's mapping defined this axis, as + * that is all the information SDL has about the physical device. + * + * \param gamepad a gamepad. + * \param axis an axis enum value (an SDL_GamepadAxis value). + * \returns true if the gamepad has this axis, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GamepadHasButton + * \sa SDL_GetGamepadAxis + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GamepadHasAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis); + +/** + * Get the current state of an axis control on a gamepad. + * + * The axis indices start at index 0. + * + * For thumbsticks, the state is a value ranging from -32768 (up/left) to + * 32767 (down/right). + * + * Triggers range from 0 when released to 32767 when fully pressed, and never + * return a negative value. Note that this differs from the value reported by + * the lower-level SDL_GetJoystickAxis(), which normally uses the full range. + * + * \param gamepad a gamepad. + * \param axis an axis index (one of the SDL_GamepadAxis values). + * \returns axis state (including 0) on success or 0 (also) on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GamepadHasAxis + * \sa SDL_GetGamepadButton + */ +extern SDL_DECLSPEC Sint16 SDLCALL SDL_GetGamepadAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis); + +/** + * Convert a string into an SDL_GamepadButton enum. + * + * This function is called internally to translate SDL_Gamepad mapping strings + * for the underlying joystick device into the consistent SDL_Gamepad mapping. + * You do not normally need to call this function unless you are parsing + * SDL_Gamepad mappings in your own code. + * + * \param str string representing a SDL_Gamepad axis. + * \returns the SDL_GamepadButton enum corresponding to the input string, or + * `SDL_GAMEPAD_BUTTON_INVALID` if no match was found. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadStringForButton + */ +extern SDL_DECLSPEC SDL_GamepadButton SDLCALL SDL_GetGamepadButtonFromString(const char *str); + +/** + * Convert from an SDL_GamepadButton enum to a string. + * + * \param button an enum value for a given SDL_GamepadButton. + * \returns a string for the given button, or NULL if an invalid button is + * specified. The string returned is of the format used by + * SDL_Gamepad mapping strings. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadButtonFromString + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetGamepadStringForButton(SDL_GamepadButton button); + +/** + * Query whether a gamepad has a given button. + * + * This merely reports whether the gamepad's mapping defined this button, as + * that is all the information SDL has about the physical device. + * + * \param gamepad a gamepad. + * \param button a button enum value (an SDL_GamepadButton value). + * \returns true if the gamepad has this button, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GamepadHasAxis + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GamepadHasButton(SDL_Gamepad *gamepad, SDL_GamepadButton button); + +/** + * Get the current state of a button on a gamepad. + * + * \param gamepad a gamepad. + * \param button a button index (one of the SDL_GamepadButton values). + * \returns true if the button is pressed, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GamepadHasButton + * \sa SDL_GetGamepadAxis + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetGamepadButton(SDL_Gamepad *gamepad, SDL_GamepadButton button); + +/** + * Get the label of a button on a gamepad. + * + * \param type the type of gamepad to check. + * \param button a button index (one of the SDL_GamepadButton values). + * \returns the SDL_GamepadButtonLabel enum corresponding to the button label. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadButtonLabel + */ +extern SDL_DECLSPEC SDL_GamepadButtonLabel SDLCALL SDL_GetGamepadButtonLabelForType(SDL_GamepadType type, SDL_GamepadButton button); + +/** + * Get the label of a button on a gamepad. + * + * \param gamepad a gamepad. + * \param button a button index (one of the SDL_GamepadButton values). + * \returns the SDL_GamepadButtonLabel enum corresponding to the button label. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadButtonLabelForType + */ +extern SDL_DECLSPEC SDL_GamepadButtonLabel SDLCALL SDL_GetGamepadButtonLabel(SDL_Gamepad *gamepad, SDL_GamepadButton button); + +/** + * Get the number of touchpads on a gamepad. + * + * \param gamepad a gamepad. + * \returns number of touchpads. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumGamepadTouchpadFingers + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumGamepadTouchpads(SDL_Gamepad *gamepad); + +/** + * Get the number of supported simultaneous fingers on a touchpad on a game + * gamepad. + * + * \param gamepad a gamepad. + * \param touchpad a touchpad. + * \returns number of supported simultaneous fingers. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadTouchpadFinger + * \sa SDL_GetNumGamepadTouchpads + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumGamepadTouchpadFingers(SDL_Gamepad *gamepad, int touchpad); + +/** + * Get the current state of a finger on a touchpad on a gamepad. + * + * \param gamepad a gamepad. + * \param touchpad a touchpad. + * \param finger a finger. + * \param down a pointer filled with true if the finger is down, false + * otherwise, may be NULL. + * \param x a pointer filled with the x position, normalized 0 to 1, with the + * origin in the upper left, may be NULL. + * \param y a pointer filled with the y position, normalized 0 to 1, with the + * origin in the upper left, may be NULL. + * \param pressure a pointer filled with pressure value, may be NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumGamepadTouchpadFingers + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetGamepadTouchpadFinger(SDL_Gamepad *gamepad, int touchpad, int finger, bool *down, float *x, float *y, float *pressure); + +/** + * Return whether a gamepad has a particular sensor. + * + * \param gamepad the gamepad to query. + * \param type the type of sensor to query. + * \returns true if the sensor exists, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadSensorData + * \sa SDL_GetGamepadSensorDataRate + * \sa SDL_SetGamepadSensorEnabled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GamepadHasSensor(SDL_Gamepad *gamepad, SDL_SensorType type); + +/** + * Set whether data reporting for a gamepad sensor is enabled. + * + * \param gamepad the gamepad to update. + * \param type the type of sensor to enable/disable. + * \param enabled whether data reporting should be enabled. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GamepadHasSensor + * \sa SDL_GamepadSensorEnabled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetGamepadSensorEnabled(SDL_Gamepad *gamepad, SDL_SensorType type, bool enabled); + +/** + * Query whether sensor data reporting is enabled for a gamepad. + * + * \param gamepad the gamepad to query. + * \param type the type of sensor to query. + * \returns true if the sensor is enabled, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetGamepadSensorEnabled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GamepadSensorEnabled(SDL_Gamepad *gamepad, SDL_SensorType type); + +/** + * Get the data rate (number of events per second) of a gamepad sensor. + * + * \param gamepad the gamepad to query. + * \param type the type of sensor to query. + * \returns the data rate, or 0.0f if the data rate is not available. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC float SDLCALL SDL_GetGamepadSensorDataRate(SDL_Gamepad *gamepad, SDL_SensorType type); + +/** + * Get the current state of a gamepad sensor. + * + * The number of values and interpretation of the data is sensor dependent. + * See SDL_sensor.h for the details for each type of sensor. + * + * \param gamepad the gamepad to query. + * \param type the type of sensor to query. + * \param data a pointer filled with the current sensor state. + * \param num_values the number of values to write to data. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetGamepadSensorData(SDL_Gamepad *gamepad, SDL_SensorType type, float *data, int num_values); + +/** + * Start a rumble effect on a gamepad. + * + * Each call to this function cancels any previous rumble effect, and calling + * it with 0 intensity stops any rumbling. + * + * This function requires you to process SDL events or call + * SDL_UpdateJoysticks() to update rumble state. + * + * \param gamepad the gamepad to vibrate. + * \param low_frequency_rumble the intensity of the low frequency (left) + * rumble motor, from 0 to 0xFFFF. + * \param high_frequency_rumble the intensity of the high frequency (right) + * rumble motor, from 0 to 0xFFFF. + * \param duration_ms the duration of the rumble effect, in milliseconds. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RumbleGamepad(SDL_Gamepad *gamepad, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms); + +/** + * Start a rumble effect in the gamepad's triggers. + * + * Each call to this function cancels any previous trigger rumble effect, and + * calling it with 0 intensity stops any rumbling. + * + * Note that this is rumbling of the _triggers_ and not the gamepad as a + * whole. This is currently only supported on Xbox One gamepads. If you want + * the (more common) whole-gamepad rumble, use SDL_RumbleGamepad() instead. + * + * This function requires you to process SDL events or call + * SDL_UpdateJoysticks() to update rumble state. + * + * \param gamepad the gamepad to vibrate. + * \param left_rumble the intensity of the left trigger rumble motor, from 0 + * to 0xFFFF. + * \param right_rumble the intensity of the right trigger rumble motor, from 0 + * to 0xFFFF. + * \param duration_ms the duration of the rumble effect, in milliseconds. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RumbleGamepad + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RumbleGamepadTriggers(SDL_Gamepad *gamepad, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms); + +/** + * Update a gamepad's LED color. + * + * An example of a joystick LED is the light on the back of a PlayStation 4's + * DualShock 4 controller. + * + * For gamepads with a single color LED, the maximum of the RGB values will be + * used as the LED brightness. + * + * \param gamepad the gamepad to update. + * \param red the intensity of the red LED. + * \param green the intensity of the green LED. + * \param blue the intensity of the blue LED. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetGamepadLED(SDL_Gamepad *gamepad, Uint8 red, Uint8 green, Uint8 blue); + +/** + * Send a gamepad specific effect packet. + * + * \param gamepad the gamepad to affect. + * \param data the data to send to the gamepad. + * \param size the size of the data to send to the gamepad. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SendGamepadEffect(SDL_Gamepad *gamepad, const void *data, int size); + +/** + * Close a gamepad previously opened with SDL_OpenGamepad(). + * + * \param gamepad a gamepad identifier previously returned by + * SDL_OpenGamepad(). + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenGamepad + */ +extern SDL_DECLSPEC void SDLCALL SDL_CloseGamepad(SDL_Gamepad *gamepad); + +/** + * Return the sfSymbolsName for a given button on a gamepad on Apple + * platforms. + * + * \param gamepad the gamepad to query. + * \param button a button on the gamepad. + * \returns the sfSymbolsName or NULL if the name can't be found. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadAppleSFSymbolsNameForAxis + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetGamepadAppleSFSymbolsNameForButton(SDL_Gamepad *gamepad, SDL_GamepadButton button); + +/** + * Return the sfSymbolsName for a given axis on a gamepad on Apple platforms. + * + * \param gamepad the gamepad to query. + * \param axis an axis on the gamepad. + * \returns the sfSymbolsName or NULL if the name can't be found. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGamepadAppleSFSymbolsNameForButton + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetGamepadAppleSFSymbolsNameForAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_gamepad_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_guid.h b/thirdparty/sdl/include/SDL3/SDL_guid.h new file mode 100644 index 00000000000..312c42c0316 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_guid.h @@ -0,0 +1,106 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: GUID */ + +/** + * # CategoryGUID + * + * A GUID is a 128-bit value that represents something that is uniquely + * identifiable by this value: "globally unique." + * + * SDL provides functions to convert a GUID to/from a string. + */ + +#ifndef SDL_guid_h_ +#define SDL_guid_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * An SDL_GUID is a 128-bit identifier for an input device that identifies + * that device across runs of SDL programs on the same platform. + * + * If the device is detached and then re-attached to a different port, or if + * the base system is rebooted, the device should still report the same GUID. + * + * GUIDs are as precise as possible but are not guaranteed to distinguish + * physically distinct but equivalent devices. For example, two game + * controllers from the same vendor with the same product ID and revision may + * have the same GUID. + * + * GUIDs may be platform-dependent (i.e., the same device may report different + * GUIDs on different operating systems). + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_GUID { + Uint8 data[16]; +} SDL_GUID; + +/* Function prototypes */ + +/** + * Get an ASCII string representation for a given SDL_GUID. + * + * \param guid the SDL_GUID you wish to convert to string. + * \param pszGUID buffer in which to write the ASCII string. + * \param cbGUID the size of pszGUID, should be at least 33 bytes. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StringToGUID + */ +extern SDL_DECLSPEC void SDLCALL SDL_GUIDToString(SDL_GUID guid, char *pszGUID, int cbGUID); + +/** + * Convert a GUID string into a SDL_GUID structure. + * + * Performs no error checking. If this function is given a string containing + * an invalid GUID, the function will silently succeed, but the GUID generated + * will not be useful. + * + * \param pchGUID string containing an ASCII representation of a GUID. + * \returns a SDL_GUID structure. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GUIDToString + */ +extern SDL_DECLSPEC SDL_GUID SDLCALL SDL_StringToGUID(const char *pchGUID); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_guid_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_haptic.h b/thirdparty/sdl/include/SDL3/SDL_haptic.h new file mode 100644 index 00000000000..a45335b2858 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_haptic.h @@ -0,0 +1,1441 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryHaptic + * + * The SDL haptic subsystem manages haptic (force feedback) devices. + * + * The basic usage is as follows: + * + * - Initialize the subsystem (SDL_INIT_HAPTIC). + * - Open a haptic device. + * - SDL_OpenHaptic() to open from index. + * - SDL_OpenHapticFromJoystick() to open from an existing joystick. + * - Create an effect (SDL_HapticEffect). + * - Upload the effect with SDL_CreateHapticEffect(). + * - Run the effect with SDL_RunHapticEffect(). + * - (optional) Free the effect with SDL_DestroyHapticEffect(). + * - Close the haptic device with SDL_CloseHaptic(). + * + * Simple rumble example: + * + * ```c + * SDL_Haptic *haptic = NULL; + * + * // Open the device + * SDL_HapticID *haptics = SDL_GetHaptics(NULL); + * if (haptics) { + * haptic = SDL_OpenHaptic(haptics[0]); + * SDL_free(haptics); + * } + * if (haptic == NULL) + * return; + * + * // Initialize simple rumble + * if (!SDL_InitHapticRumble(haptic)) + * return; + * + * // Play effect at 50% strength for 2 seconds + * if (!SDL_PlayHapticRumble(haptic, 0.5, 2000)) + * return; + * SDL_Delay(2000); + * + * // Clean up + * SDL_CloseHaptic(haptic); + * ``` + * + * Complete example: + * + * ```c + * bool test_haptic(SDL_Joystick *joystick) + * { + * SDL_Haptic *haptic; + * SDL_HapticEffect effect; + * int effect_id; + * + * // Open the device + * haptic = SDL_OpenHapticFromJoystick(joystick); + * if (haptic == NULL) return false; // Most likely joystick isn't haptic + * + * // See if it can do sine waves + * if ((SDL_GetHapticFeatures(haptic) & SDL_HAPTIC_SINE)==0) { + * SDL_CloseHaptic(haptic); // No sine effect + * return false; + * } + * + * // Create the effect + * SDL_memset(&effect, 0, sizeof(SDL_HapticEffect)); // 0 is safe default + * effect.type = SDL_HAPTIC_SINE; + * effect.periodic.direction.type = SDL_HAPTIC_POLAR; // Polar coordinates + * effect.periodic.direction.dir[0] = 18000; // Force comes from south + * effect.periodic.period = 1000; // 1000 ms + * effect.periodic.magnitude = 20000; // 20000/32767 strength + * effect.periodic.length = 5000; // 5 seconds long + * effect.periodic.attack_length = 1000; // Takes 1 second to get max strength + * effect.periodic.fade_length = 1000; // Takes 1 second to fade away + * + * // Upload the effect + * effect_id = SDL_CreateHapticEffect(haptic, &effect); + * + * // Test the effect + * SDL_RunHapticEffect(haptic, effect_id, 1); + * SDL_Delay(5000); // Wait for the effect to finish + * + * // We destroy the effect, although closing the device also does this + * SDL_DestroyHapticEffect(haptic, effect_id); + * + * // Close the device + * SDL_CloseHaptic(haptic); + * + * return true; // Success + * } + * ``` + * + * Note that the SDL haptic subsystem is not thread-safe. + */ + + +#ifndef SDL_haptic_h_ +#define SDL_haptic_h_ + +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* FIXME: + * + * At the moment the magnitude variables are mixed between signed/unsigned, and + * it is also not made clear that ALL of those variables expect a max of 0x7FFF. + * + * Some platforms may have higher precision than that (Linux FF, Windows XInput) + * so we should fix the inconsistency in favor of higher possible precision, + * adjusting for platforms that use different scales. + * -flibit + */ + +/** + * The haptic structure used to identify an SDL haptic. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_OpenHaptic + * \sa SDL_OpenHapticFromJoystick + * \sa SDL_CloseHaptic + */ +typedef struct SDL_Haptic SDL_Haptic; + + +/** + * \name Haptic features + * + * Different haptic features a device can have. + */ +/* @{ */ + +/** + * \name Haptic effects + */ +/* @{ */ + +/** + * Constant effect supported. + * + * Constant haptic effect. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticCondition + */ +#define SDL_HAPTIC_CONSTANT (1u<<0) + +/** + * Sine wave effect supported. + * + * Periodic haptic effect that simulates sine waves. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticPeriodic + */ +#define SDL_HAPTIC_SINE (1u<<1) + +/** + * Square wave effect supported. + * + * Periodic haptic effect that simulates square waves. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticPeriodic + */ +#define SDL_HAPTIC_SQUARE (1u<<2) + +/** + * Triangle wave effect supported. + * + * Periodic haptic effect that simulates triangular waves. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticPeriodic + */ +#define SDL_HAPTIC_TRIANGLE (1u<<3) + +/** + * Sawtoothup wave effect supported. + * + * Periodic haptic effect that simulates saw tooth up waves. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticPeriodic + */ +#define SDL_HAPTIC_SAWTOOTHUP (1u<<4) + +/** + * Sawtoothdown wave effect supported. + * + * Periodic haptic effect that simulates saw tooth down waves. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticPeriodic + */ +#define SDL_HAPTIC_SAWTOOTHDOWN (1u<<5) + +/** + * Ramp effect supported. + * + * Ramp haptic effect. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticRamp + */ +#define SDL_HAPTIC_RAMP (1u<<6) + +/** + * Spring effect supported - uses axes position. + * + * Condition haptic effect that simulates a spring. Effect is based on the + * axes position. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticCondition + */ +#define SDL_HAPTIC_SPRING (1u<<7) + +/** + * Damper effect supported - uses axes velocity. + * + * Condition haptic effect that simulates dampening. Effect is based on the + * axes velocity. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticCondition + */ +#define SDL_HAPTIC_DAMPER (1u<<8) + +/** + * Inertia effect supported - uses axes acceleration. + * + * Condition haptic effect that simulates inertia. Effect is based on the axes + * acceleration. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticCondition + */ +#define SDL_HAPTIC_INERTIA (1u<<9) + +/** + * Friction effect supported - uses axes movement. + * + * Condition haptic effect that simulates friction. Effect is based on the + * axes movement. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticCondition + */ +#define SDL_HAPTIC_FRICTION (1u<<10) + +/** + * Left/Right effect supported. + * + * Haptic effect for direct control over high/low frequency motors. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticLeftRight + */ +#define SDL_HAPTIC_LEFTRIGHT (1u<<11) + +/** + * Reserved for future use. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_HAPTIC_RESERVED1 (1u<<12) + +/** + * Reserved for future use. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_HAPTIC_RESERVED2 (1u<<13) + +/** + * Reserved for future use. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_HAPTIC_RESERVED3 (1u<<14) + +/** + * Custom effect is supported. + * + * User defined custom haptic effect. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_HAPTIC_CUSTOM (1u<<15) + +/* @} *//* Haptic effects */ + +/* These last few are features the device has, not effects */ + +/** + * Device can set global gain. + * + * Device supports setting the global gain. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_SetHapticGain + */ +#define SDL_HAPTIC_GAIN (1u<<16) + +/** + * Device can set autocenter. + * + * Device supports setting autocenter. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_SetHapticAutocenter + */ +#define SDL_HAPTIC_AUTOCENTER (1u<<17) + +/** + * Device can be queried for effect status. + * + * Device supports querying effect status. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_GetHapticEffectStatus + */ +#define SDL_HAPTIC_STATUS (1u<<18) + +/** + * Device can be paused. + * + * Devices supports being paused. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_PauseHaptic + * \sa SDL_ResumeHaptic + */ +#define SDL_HAPTIC_PAUSE (1u<<19) + + +/** + * \name Direction encodings + */ +/* @{ */ + +/** + * Uses polar coordinates for the direction. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticDirection + */ +#define SDL_HAPTIC_POLAR 0 + +/** + * Uses cartesian coordinates for the direction. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticDirection + */ +#define SDL_HAPTIC_CARTESIAN 1 + +/** + * Uses spherical coordinates for the direction. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticDirection + */ +#define SDL_HAPTIC_SPHERICAL 2 + +/** + * Use this value to play an effect on the steering wheel axis. + * + * This provides better compatibility across platforms and devices as SDL will + * guess the correct axis. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_HapticDirection + */ +#define SDL_HAPTIC_STEERING_AXIS 3 + +/* @} *//* Direction encodings */ + +/* @} *//* Haptic features */ + +/* + * Misc defines. + */ + +/** + * Used to play a device an infinite number of times. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_RunHapticEffect + */ +#define SDL_HAPTIC_INFINITY 4294967295U + + +/** + * Structure that represents a haptic direction. + * + * This is the direction where the force comes from, instead of the direction + * in which the force is exerted. + * + * Directions can be specified by: + * + * - SDL_HAPTIC_POLAR : Specified by polar coordinates. + * - SDL_HAPTIC_CARTESIAN : Specified by cartesian coordinates. + * - SDL_HAPTIC_SPHERICAL : Specified by spherical coordinates. + * + * Cardinal directions of the haptic device are relative to the positioning of + * the device. North is considered to be away from the user. + * + * The following diagram represents the cardinal directions: + * + * ``` + * .--. + * |__| .-------. + * |=.| |.-----.| + * |--| || || + * | | |'-----'| + * |__|~')_____(' + * [ COMPUTER ] + * + * + * North (0,-1) + * ^ + * | + * | + * (-1,0) West <----[ HAPTIC ]----> East (1,0) + * | + * | + * v + * South (0,1) + * + * + * [ USER ] + * \|||/ + * (o o) + * ---ooO-(_)-Ooo--- + * ``` + * + * If type is SDL_HAPTIC_POLAR, direction is encoded by hundredths of a degree + * starting north and turning clockwise. SDL_HAPTIC_POLAR only uses the first + * `dir` parameter. The cardinal directions would be: + * + * - North: 0 (0 degrees) + * - East: 9000 (90 degrees) + * - South: 18000 (180 degrees) + * - West: 27000 (270 degrees) + * + * If type is SDL_HAPTIC_CARTESIAN, direction is encoded by three positions (X + * axis, Y axis and Z axis (with 3 axes)). SDL_HAPTIC_CARTESIAN uses the first + * three `dir` parameters. The cardinal directions would be: + * + * - North: 0,-1, 0 + * - East: 1, 0, 0 + * - South: 0, 1, 0 + * - West: -1, 0, 0 + * + * The Z axis represents the height of the effect if supported, otherwise it's + * unused. In cartesian encoding (1, 2) would be the same as (2, 4), you can + * use any multiple you want, only the direction matters. + * + * If type is SDL_HAPTIC_SPHERICAL, direction is encoded by two rotations. The + * first two `dir` parameters are used. The `dir` parameters are as follows + * (all values are in hundredths of degrees): + * + * - Degrees from (1, 0) rotated towards (0, 1). + * - Degrees towards (0, 0, 1) (device needs at least 3 axes). + * + * Example of force coming from the south with all encodings (force coming + * from the south means the user will have to pull the stick to counteract): + * + * ```c + * SDL_HapticDirection direction; + * + * // Cartesian directions + * direction.type = SDL_HAPTIC_CARTESIAN; // Using cartesian direction encoding. + * direction.dir[0] = 0; // X position + * direction.dir[1] = 1; // Y position + * // Assuming the device has 2 axes, we don't need to specify third parameter. + * + * // Polar directions + * direction.type = SDL_HAPTIC_POLAR; // We'll be using polar direction encoding. + * direction.dir[0] = 18000; // Polar only uses first parameter + * + * // Spherical coordinates + * direction.type = SDL_HAPTIC_SPHERICAL; // Spherical encoding + * direction.dir[0] = 9000; // Since we only have two axes we don't need more parameters. + * ``` + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_HAPTIC_POLAR + * \sa SDL_HAPTIC_CARTESIAN + * \sa SDL_HAPTIC_SPHERICAL + * \sa SDL_HAPTIC_STEERING_AXIS + * \sa SDL_HapticEffect + * \sa SDL_GetNumHapticAxes + */ +typedef struct SDL_HapticDirection +{ + Uint8 type; /**< The type of encoding. */ + Sint32 dir[3]; /**< The encoded direction. */ +} SDL_HapticDirection; + + +/** + * A structure containing a template for a Constant effect. + * + * This struct is exclusively for the SDL_HAPTIC_CONSTANT effect. + * + * A constant effect applies a constant force in the specified direction to + * the joystick. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_HAPTIC_CONSTANT + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticConstant +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_CONSTANT */ + SDL_HapticDirection direction; /**< Direction of the effect. */ + + /* Replay */ + Uint32 length; /**< Duration of the effect. */ + Uint16 delay; /**< Delay before starting the effect. */ + + /* Trigger */ + Uint16 button; /**< Button that triggers the effect. */ + Uint16 interval; /**< How soon it can be triggered again after button. */ + + /* Constant */ + Sint16 level; /**< Strength of the constant effect. */ + + /* Envelope */ + Uint16 attack_length; /**< Duration of the attack. */ + Uint16 attack_level; /**< Level at the start of the attack. */ + Uint16 fade_length; /**< Duration of the fade. */ + Uint16 fade_level; /**< Level at the end of the fade. */ +} SDL_HapticConstant; + +/** + * A structure containing a template for a Periodic effect. + * + * The struct handles the following effects: + * + * - SDL_HAPTIC_SINE + * - SDL_HAPTIC_SQUARE + * - SDL_HAPTIC_TRIANGLE + * - SDL_HAPTIC_SAWTOOTHUP + * - SDL_HAPTIC_SAWTOOTHDOWN + * + * A periodic effect consists in a wave-shaped effect that repeats itself over + * time. The type determines the shape of the wave and the parameters + * determine the dimensions of the wave. + * + * Phase is given by hundredth of a degree meaning that giving the phase a + * value of 9000 will displace it 25% of its period. Here are sample values: + * + * - 0: No phase displacement. + * - 9000: Displaced 25% of its period. + * - 18000: Displaced 50% of its period. + * - 27000: Displaced 75% of its period. + * - 36000: Displaced 100% of its period, same as 0, but 0 is preferred. + * + * Examples: + * + * ``` + * SDL_HAPTIC_SINE + * __ __ __ __ + * / \ / \ / \ / + * / \__/ \__/ \__/ + * + * SDL_HAPTIC_SQUARE + * __ __ __ __ __ + * | | | | | | | | | | + * | |__| |__| |__| |__| | + * + * SDL_HAPTIC_TRIANGLE + * /\ /\ /\ /\ /\ + * / \ / \ / \ / \ / + * / \/ \/ \/ \/ + * + * SDL_HAPTIC_SAWTOOTHUP + * /| /| /| /| /| /| /| + * / | / | / | / | / | / | / | + * / |/ |/ |/ |/ |/ |/ | + * + * SDL_HAPTIC_SAWTOOTHDOWN + * \ |\ |\ |\ |\ |\ |\ | + * \ | \ | \ | \ | \ | \ | \ | + * \| \| \| \| \| \| \| + * ``` + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_HAPTIC_SINE + * \sa SDL_HAPTIC_SQUARE + * \sa SDL_HAPTIC_TRIANGLE + * \sa SDL_HAPTIC_SAWTOOTHUP + * \sa SDL_HAPTIC_SAWTOOTHDOWN + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticPeriodic +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_SINE, SDL_HAPTIC_SQUARE + SDL_HAPTIC_TRIANGLE, SDL_HAPTIC_SAWTOOTHUP or + SDL_HAPTIC_SAWTOOTHDOWN */ + SDL_HapticDirection direction; /**< Direction of the effect. */ + + /* Replay */ + Uint32 length; /**< Duration of the effect. */ + Uint16 delay; /**< Delay before starting the effect. */ + + /* Trigger */ + Uint16 button; /**< Button that triggers the effect. */ + Uint16 interval; /**< How soon it can be triggered again after button. */ + + /* Periodic */ + Uint16 period; /**< Period of the wave. */ + Sint16 magnitude; /**< Peak value; if negative, equivalent to 180 degrees extra phase shift. */ + Sint16 offset; /**< Mean value of the wave. */ + Uint16 phase; /**< Positive phase shift given by hundredth of a degree. */ + + /* Envelope */ + Uint16 attack_length; /**< Duration of the attack. */ + Uint16 attack_level; /**< Level at the start of the attack. */ + Uint16 fade_length; /**< Duration of the fade. */ + Uint16 fade_level; /**< Level at the end of the fade. */ +} SDL_HapticPeriodic; + +/** + * A structure containing a template for a Condition effect. + * + * The struct handles the following effects: + * + * - SDL_HAPTIC_SPRING: Effect based on axes position. + * - SDL_HAPTIC_DAMPER: Effect based on axes velocity. + * - SDL_HAPTIC_INERTIA: Effect based on axes acceleration. + * - SDL_HAPTIC_FRICTION: Effect based on axes movement. + * + * Direction is handled by condition internals instead of a direction member. + * The condition effect specific members have three parameters. The first + * refers to the X axis, the second refers to the Y axis and the third refers + * to the Z axis. The right terms refer to the positive side of the axis and + * the left terms refer to the negative side of the axis. Please refer to the + * SDL_HapticDirection diagram for which side is positive and which is + * negative. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_HapticDirection + * \sa SDL_HAPTIC_SPRING + * \sa SDL_HAPTIC_DAMPER + * \sa SDL_HAPTIC_INERTIA + * \sa SDL_HAPTIC_FRICTION + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticCondition +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_SPRING, SDL_HAPTIC_DAMPER, + SDL_HAPTIC_INERTIA or SDL_HAPTIC_FRICTION */ + SDL_HapticDirection direction; /**< Direction of the effect. */ + + /* Replay */ + Uint32 length; /**< Duration of the effect. */ + Uint16 delay; /**< Delay before starting the effect. */ + + /* Trigger */ + Uint16 button; /**< Button that triggers the effect. */ + Uint16 interval; /**< How soon it can be triggered again after button. */ + + /* Condition */ + Uint16 right_sat[3]; /**< Level when joystick is to the positive side; max 0xFFFF. */ + Uint16 left_sat[3]; /**< Level when joystick is to the negative side; max 0xFFFF. */ + Sint16 right_coeff[3]; /**< How fast to increase the force towards the positive side. */ + Sint16 left_coeff[3]; /**< How fast to increase the force towards the negative side. */ + Uint16 deadband[3]; /**< Size of the dead zone; max 0xFFFF: whole axis-range when 0-centered. */ + Sint16 center[3]; /**< Position of the dead zone. */ +} SDL_HapticCondition; + +/** + * A structure containing a template for a Ramp effect. + * + * This struct is exclusively for the SDL_HAPTIC_RAMP effect. + * + * The ramp effect starts at start strength and ends at end strength. It + * augments in linear fashion. If you use attack and fade with a ramp the + * effects get added to the ramp effect making the effect become quadratic + * instead of linear. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_HAPTIC_RAMP + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticRamp +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_RAMP */ + SDL_HapticDirection direction; /**< Direction of the effect. */ + + /* Replay */ + Uint32 length; /**< Duration of the effect. */ + Uint16 delay; /**< Delay before starting the effect. */ + + /* Trigger */ + Uint16 button; /**< Button that triggers the effect. */ + Uint16 interval; /**< How soon it can be triggered again after button. */ + + /* Ramp */ + Sint16 start; /**< Beginning strength level. */ + Sint16 end; /**< Ending strength level. */ + + /* Envelope */ + Uint16 attack_length; /**< Duration of the attack. */ + Uint16 attack_level; /**< Level at the start of the attack. */ + Uint16 fade_length; /**< Duration of the fade. */ + Uint16 fade_level; /**< Level at the end of the fade. */ +} SDL_HapticRamp; + +/** + * A structure containing a template for a Left/Right effect. + * + * This struct is exclusively for the SDL_HAPTIC_LEFTRIGHT effect. + * + * The Left/Right effect is used to explicitly control the large and small + * motors, commonly found in modern game controllers. The small (right) motor + * is high frequency, and the large (left) motor is low frequency. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_HAPTIC_LEFTRIGHT + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticLeftRight +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_LEFTRIGHT */ + + /* Replay */ + Uint32 length; /**< Duration of the effect in milliseconds. */ + + /* Rumble */ + Uint16 large_magnitude; /**< Control of the large controller motor. */ + Uint16 small_magnitude; /**< Control of the small controller motor. */ +} SDL_HapticLeftRight; + +/** + * A structure containing a template for the SDL_HAPTIC_CUSTOM effect. + * + * This struct is exclusively for the SDL_HAPTIC_CUSTOM effect. + * + * A custom force feedback effect is much like a periodic effect, where the + * application can define its exact shape. You will have to allocate the data + * yourself. Data should consist of channels * samples Uint16 samples. + * + * If channels is one, the effect is rotated using the defined direction. + * Otherwise it uses the samples in data for the different axes. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_HAPTIC_CUSTOM + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticCustom +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_CUSTOM */ + SDL_HapticDirection direction; /**< Direction of the effect. */ + + /* Replay */ + Uint32 length; /**< Duration of the effect. */ + Uint16 delay; /**< Delay before starting the effect. */ + + /* Trigger */ + Uint16 button; /**< Button that triggers the effect. */ + Uint16 interval; /**< How soon it can be triggered again after button. */ + + /* Custom */ + Uint8 channels; /**< Axes to use, minimum of one. */ + Uint16 period; /**< Sample periods. */ + Uint16 samples; /**< Amount of samples. */ + Uint16 *data; /**< Should contain channels*samples items. */ + + /* Envelope */ + Uint16 attack_length; /**< Duration of the attack. */ + Uint16 attack_level; /**< Level at the start of the attack. */ + Uint16 fade_length; /**< Duration of the fade. */ + Uint16 fade_level; /**< Level at the end of the fade. */ +} SDL_HapticCustom; + +/** + * The generic template for any haptic effect. + * + * All values max at 32767 (0x7FFF). Signed values also can be negative. Time + * values unless specified otherwise are in milliseconds. + * + * You can also pass SDL_HAPTIC_INFINITY to length instead of a 0-32767 value. + * Neither delay, interval, attack_length nor fade_length support + * SDL_HAPTIC_INFINITY. Fade will also not be used since effect never ends. + * + * Additionally, the SDL_HAPTIC_RAMP effect does not support a duration of + * SDL_HAPTIC_INFINITY. + * + * Button triggers may not be supported on all devices, it is advised to not + * use them if possible. Buttons start at index 1 instead of index 0 like the + * joystick. + * + * If both attack_length and fade_level are 0, the envelope is not used, + * otherwise both values are used. + * + * Common parts: + * + * ```c + * // Replay - All effects have this + * Uint32 length; // Duration of effect (ms). + * Uint16 delay; // Delay before starting effect. + * + * // Trigger - All effects have this + * Uint16 button; // Button that triggers effect. + * Uint16 interval; // How soon before effect can be triggered again. + * + * // Envelope - All effects except condition effects have this + * Uint16 attack_length; // Duration of the attack (ms). + * Uint16 attack_level; // Level at the start of the attack. + * Uint16 fade_length; // Duration of the fade out (ms). + * Uint16 fade_level; // Level at the end of the fade. + * ``` + * + * Here we have an example of a constant effect evolution in time: + * + * ``` + * Strength + * ^ + * | + * | effect level --> _________________ + * | / \ + * | / \ + * | / \ + * | / \ + * | attack_level --> | \ + * | | | <--- fade_level + * | + * +--------------------------------------------------> Time + * [--] [---] + * attack_length fade_length + * + * [------------------][-----------------------] + * delay length + * ``` + * + * Note either the attack_level or the fade_level may be above the actual + * effect level. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_HapticConstant + * \sa SDL_HapticPeriodic + * \sa SDL_HapticCondition + * \sa SDL_HapticRamp + * \sa SDL_HapticLeftRight + * \sa SDL_HapticCustom + */ +typedef union SDL_HapticEffect +{ + /* Common for all force feedback effects */ + Uint16 type; /**< Effect type. */ + SDL_HapticConstant constant; /**< Constant effect. */ + SDL_HapticPeriodic periodic; /**< Periodic effect. */ + SDL_HapticCondition condition; /**< Condition effect. */ + SDL_HapticRamp ramp; /**< Ramp effect. */ + SDL_HapticLeftRight leftright; /**< Left/Right effect. */ + SDL_HapticCustom custom; /**< Custom effect. */ +} SDL_HapticEffect; + +/** + * This is a unique ID for a haptic device for the time it is connected to the + * system, and is never reused for the lifetime of the application. + * + * If the haptic device is disconnected and reconnected, it will get a new ID. + * + * The value 0 is an invalid ID. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_HapticID; + + +/* Function prototypes */ + +/** + * Get a list of currently connected haptic devices. + * + * \param count a pointer filled in with the number of haptic devices + * returned, may be NULL. + * \returns a 0 terminated array of haptic device instance IDs or NULL on + * failure; call SDL_GetError() for more information. This should be + * freed with SDL_free() when it is no longer needed. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenHaptic + */ +extern SDL_DECLSPEC SDL_HapticID * SDLCALL SDL_GetHaptics(int *count); + +/** + * Get the implementation dependent name of a haptic device. + * + * This can be called before any haptic devices are opened. + * + * \param instance_id the haptic device instance ID. + * \returns the name of the selected haptic device. If no name can be found, + * this function returns NULL; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetHapticName + * \sa SDL_OpenHaptic + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetHapticNameForID(SDL_HapticID instance_id); + +/** + * Open a haptic device for use. + * + * The index passed as an argument refers to the N'th haptic device on this + * system. + * + * When opening a haptic device, its gain will be set to maximum and + * autocenter will be disabled. To modify these values use SDL_SetHapticGain() + * and SDL_SetHapticAutocenter(). + * + * \param instance_id the haptic device instance ID. + * \returns the device identifier or NULL on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseHaptic + * \sa SDL_GetHaptics + * \sa SDL_OpenHapticFromJoystick + * \sa SDL_OpenHapticFromMouse + * \sa SDL_SetHapticAutocenter + * \sa SDL_SetHapticGain + */ +extern SDL_DECLSPEC SDL_Haptic * SDLCALL SDL_OpenHaptic(SDL_HapticID instance_id); + + +/** + * Get the SDL_Haptic associated with an instance ID, if it has been opened. + * + * \param instance_id the instance ID to get the SDL_Haptic for. + * \returns an SDL_Haptic on success or NULL on failure or if it hasn't been + * opened yet; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Haptic * SDLCALL SDL_GetHapticFromID(SDL_HapticID instance_id); + +/** + * Get the instance ID of an opened haptic device. + * + * \param haptic the SDL_Haptic device to query. + * \returns the instance ID of the specified haptic device on success or 0 on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_HapticID SDLCALL SDL_GetHapticID(SDL_Haptic *haptic); + +/** + * Get the implementation dependent name of a haptic device. + * + * \param haptic the SDL_Haptic obtained from SDL_OpenJoystick(). + * \returns the name of the selected haptic device. If no name can be found, + * this function returns NULL; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetHapticNameForID + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetHapticName(SDL_Haptic *haptic); + +/** + * Query whether or not the current mouse has haptic capabilities. + * + * \returns true if the mouse is haptic or false if it isn't. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenHapticFromMouse + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsMouseHaptic(void); + +/** + * Try to open a haptic device from the current mouse. + * + * \returns the haptic device identifier or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseHaptic + * \sa SDL_IsMouseHaptic + */ +extern SDL_DECLSPEC SDL_Haptic * SDLCALL SDL_OpenHapticFromMouse(void); + +/** + * Query if a joystick has haptic features. + * + * \param joystick the SDL_Joystick to test for haptic capabilities. + * \returns true if the joystick is haptic or false if it isn't. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenHapticFromJoystick + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsJoystickHaptic(SDL_Joystick *joystick); + +/** + * Open a haptic device for use from a joystick device. + * + * You must still close the haptic device separately. It will not be closed + * with the joystick. + * + * When opened from a joystick you should first close the haptic device before + * closing the joystick device. If not, on some implementations the haptic + * device will also get unallocated and you'll be unable to use force feedback + * on that device. + * + * \param joystick the SDL_Joystick to create a haptic device from. + * \returns a valid haptic device identifier on success or NULL on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseHaptic + * \sa SDL_IsJoystickHaptic + */ +extern SDL_DECLSPEC SDL_Haptic * SDLCALL SDL_OpenHapticFromJoystick(SDL_Joystick *joystick); + +/** + * Close a haptic device previously opened with SDL_OpenHaptic(). + * + * \param haptic the SDL_Haptic device to close. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenHaptic + */ +extern SDL_DECLSPEC void SDLCALL SDL_CloseHaptic(SDL_Haptic *haptic); + +/** + * Get the number of effects a haptic device can store. + * + * On some platforms this isn't fully supported, and therefore is an + * approximation. Always check to see if your created effect was actually + * created and do not rely solely on SDL_GetMaxHapticEffects(). + * + * \param haptic the SDL_Haptic device to query. + * \returns the number of effects the haptic device can store or a negative + * error code on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetMaxHapticEffectsPlaying + * \sa SDL_GetHapticFeatures + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetMaxHapticEffects(SDL_Haptic *haptic); + +/** + * Get the number of effects a haptic device can play at the same time. + * + * This is not supported on all platforms, but will always return a value. + * + * \param haptic the SDL_Haptic device to query maximum playing effects. + * \returns the number of effects the haptic device can play at the same time + * or -1 on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetMaxHapticEffects + * \sa SDL_GetHapticFeatures + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetMaxHapticEffectsPlaying(SDL_Haptic *haptic); + +/** + * Get the haptic device's supported features in bitwise manner. + * + * \param haptic the SDL_Haptic device to query. + * \returns a list of supported haptic features in bitwise manner (OR'd), or 0 + * on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HapticEffectSupported + * \sa SDL_GetMaxHapticEffects + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_GetHapticFeatures(SDL_Haptic *haptic); + +/** + * Get the number of haptic axes the device has. + * + * The number of haptic axes might be useful if working with the + * SDL_HapticDirection effect. + * + * \param haptic the SDL_Haptic device to query. + * \returns the number of axes on success or -1 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumHapticAxes(SDL_Haptic *haptic); + +/** + * Check to see if an effect is supported by a haptic device. + * + * \param haptic the SDL_Haptic device to query. + * \param effect the desired effect to query. + * \returns true if the effect is supported or false if it isn't. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateHapticEffect + * \sa SDL_GetHapticFeatures + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HapticEffectSupported(SDL_Haptic *haptic, const SDL_HapticEffect *effect); + +/** + * Create a new haptic effect on a specified device. + * + * \param haptic an SDL_Haptic device to create the effect on. + * \param effect an SDL_HapticEffect structure containing the properties of + * the effect to create. + * \returns the ID of the effect on success or -1 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroyHapticEffect + * \sa SDL_RunHapticEffect + * \sa SDL_UpdateHapticEffect + */ +extern SDL_DECLSPEC int SDLCALL SDL_CreateHapticEffect(SDL_Haptic *haptic, const SDL_HapticEffect *effect); + +/** + * Update the properties of an effect. + * + * Can be used dynamically, although behavior when dynamically changing + * direction may be strange. Specifically the effect may re-upload itself and + * start playing from the start. You also cannot change the type either when + * running SDL_UpdateHapticEffect(). + * + * \param haptic the SDL_Haptic device that has the effect. + * \param effect the identifier of the effect to update. + * \param data an SDL_HapticEffect structure containing the new effect + * properties to use. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateHapticEffect + * \sa SDL_RunHapticEffect + */ +extern SDL_DECLSPEC bool SDLCALL SDL_UpdateHapticEffect(SDL_Haptic *haptic, int effect, const SDL_HapticEffect *data); + +/** + * Run the haptic effect on its associated haptic device. + * + * To repeat the effect over and over indefinitely, set `iterations` to + * `SDL_HAPTIC_INFINITY`. (Repeats the envelope - attack and fade.) To make + * one instance of the effect last indefinitely (so the effect does not fade), + * set the effect's `length` in its structure/union to `SDL_HAPTIC_INFINITY` + * instead. + * + * \param haptic the SDL_Haptic device to run the effect on. + * \param effect the ID of the haptic effect to run. + * \param iterations the number of iterations to run the effect; use + * `SDL_HAPTIC_INFINITY` to repeat forever. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetHapticEffectStatus + * \sa SDL_StopHapticEffect + * \sa SDL_StopHapticEffects + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RunHapticEffect(SDL_Haptic *haptic, int effect, Uint32 iterations); + +/** + * Stop the haptic effect on its associated haptic device. + * + * \param haptic the SDL_Haptic device to stop the effect on. + * \param effect the ID of the haptic effect to stop. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RunHapticEffect + * \sa SDL_StopHapticEffects + */ +extern SDL_DECLSPEC bool SDLCALL SDL_StopHapticEffect(SDL_Haptic *haptic, int effect); + +/** + * Destroy a haptic effect on the device. + * + * This will stop the effect if it's running. Effects are automatically + * destroyed when the device is closed. + * + * \param haptic the SDL_Haptic device to destroy the effect on. + * \param effect the ID of the haptic effect to destroy. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateHapticEffect + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyHapticEffect(SDL_Haptic *haptic, int effect); + +/** + * Get the status of the current effect on the specified haptic device. + * + * Device must support the SDL_HAPTIC_STATUS feature. + * + * \param haptic the SDL_Haptic device to query for the effect status on. + * \param effect the ID of the haptic effect to query its status. + * \returns true if it is playing, false if it isn't playing or haptic status + * isn't supported. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetHapticFeatures + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetHapticEffectStatus(SDL_Haptic *haptic, int effect); + +/** + * Set the global gain of the specified haptic device. + * + * Device must support the SDL_HAPTIC_GAIN feature. + * + * The user may specify the maximum gain by setting the environment variable + * `SDL_HAPTIC_GAIN_MAX` which should be between 0 and 100. All calls to + * SDL_SetHapticGain() will scale linearly using `SDL_HAPTIC_GAIN_MAX` as the + * maximum. + * + * \param haptic the SDL_Haptic device to set the gain on. + * \param gain value to set the gain to, should be between 0 and 100 (0 - + * 100). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetHapticFeatures + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetHapticGain(SDL_Haptic *haptic, int gain); + +/** + * Set the global autocenter of the device. + * + * Autocenter should be between 0 and 100. Setting it to 0 will disable + * autocentering. + * + * Device must support the SDL_HAPTIC_AUTOCENTER feature. + * + * \param haptic the SDL_Haptic device to set autocentering on. + * \param autocenter value to set autocenter to (0-100). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetHapticFeatures + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetHapticAutocenter(SDL_Haptic *haptic, int autocenter); + +/** + * Pause a haptic device. + * + * Device must support the `SDL_HAPTIC_PAUSE` feature. Call SDL_ResumeHaptic() + * to resume playback. + * + * Do not modify the effects nor add new ones while the device is paused. That + * can cause all sorts of weird errors. + * + * \param haptic the SDL_Haptic device to pause. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ResumeHaptic + */ +extern SDL_DECLSPEC bool SDLCALL SDL_PauseHaptic(SDL_Haptic *haptic); + +/** + * Resume a haptic device. + * + * Call to unpause after SDL_PauseHaptic(). + * + * \param haptic the SDL_Haptic device to unpause. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PauseHaptic + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ResumeHaptic(SDL_Haptic *haptic); + +/** + * Stop all the currently playing effects on a haptic device. + * + * \param haptic the SDL_Haptic device to stop. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RunHapticEffect + * \sa SDL_StopHapticEffects + */ +extern SDL_DECLSPEC bool SDLCALL SDL_StopHapticEffects(SDL_Haptic *haptic); + +/** + * Check whether rumble is supported on a haptic device. + * + * \param haptic haptic device to check for rumble support. + * \returns true if the effect is supported or false if it isn't. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_InitHapticRumble + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HapticRumbleSupported(SDL_Haptic *haptic); + +/** + * Initialize a haptic device for simple rumble playback. + * + * \param haptic the haptic device to initialize for simple rumble playback. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PlayHapticRumble + * \sa SDL_StopHapticRumble + * \sa SDL_HapticRumbleSupported + */ +extern SDL_DECLSPEC bool SDLCALL SDL_InitHapticRumble(SDL_Haptic *haptic); + +/** + * Run a simple rumble effect on a haptic device. + * + * \param haptic the haptic device to play the rumble effect on. + * \param strength strength of the rumble to play as a 0-1 float value. + * \param length length of the rumble to play in milliseconds. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_InitHapticRumble + * \sa SDL_StopHapticRumble + */ +extern SDL_DECLSPEC bool SDLCALL SDL_PlayHapticRumble(SDL_Haptic *haptic, float strength, Uint32 length); + +/** + * Stop the simple rumble on a haptic device. + * + * \param haptic the haptic device to stop the rumble effect on. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PlayHapticRumble + */ +extern SDL_DECLSPEC bool SDLCALL SDL_StopHapticRumble(SDL_Haptic *haptic); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_haptic_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_hidapi.h b/thirdparty/sdl/include/SDL3/SDL_hidapi.h new file mode 100644 index 00000000000..131b03723a5 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_hidapi.h @@ -0,0 +1,552 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: HIDAPI */ + +/** + * # CategoryHIDAPI + * + * Header file for SDL HIDAPI functions. + * + * This is an adaptation of the original HIDAPI interface by Alan Ott, and + * includes source code licensed under the following license: + * + * ``` + * HIDAPI - Multi-Platform library for + * communication with HID devices. + * + * Copyright 2009, Alan Ott, Signal 11 Software. + * All Rights Reserved. + * + * This software may be used by anyone for any reason so + * long as the copyright notice in the source files + * remains intact. + * ``` + * + * (Note that this license is the same as item three of SDL's zlib license, so + * it adds no new requirements on the user.) + * + * If you would like a version of SDL without this code, you can build SDL + * with SDL_HIDAPI_DISABLED defined to 1. You might want to do this for + * example on iOS or tvOS to avoid a dependency on the CoreBluetooth + * framework. + */ + +#ifndef SDL_hidapi_h_ +#define SDL_hidapi_h_ + +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * An opaque handle representing an open HID device. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_hid_device SDL_hid_device; + +/** + * HID underlying bus types. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_hid_bus_type { + /** Unknown bus type */ + SDL_HID_API_BUS_UNKNOWN = 0x00, + + /** USB bus + Specifications: + https://usb.org/hid */ + SDL_HID_API_BUS_USB = 0x01, + + /** Bluetooth or Bluetooth LE bus + Specifications: + https://www.bluetooth.com/specifications/specs/human-interface-device-profile-1-1-1/ + https://www.bluetooth.com/specifications/specs/hid-service-1-0/ + https://www.bluetooth.com/specifications/specs/hid-over-gatt-profile-1-0/ */ + SDL_HID_API_BUS_BLUETOOTH = 0x02, + + /** I2C bus + Specifications: + https://docs.microsoft.com/previous-versions/windows/hardware/design/dn642101(v=vs.85) */ + SDL_HID_API_BUS_I2C = 0x03, + + /** SPI bus + Specifications: + https://www.microsoft.com/download/details.aspx?id=103325 */ + SDL_HID_API_BUS_SPI = 0x04 + +} SDL_hid_bus_type; + +/** hidapi info structure */ + +/** + * Information about a connected HID device + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_hid_device_info +{ + /** Platform-specific device path */ + char *path; + /** Device Vendor ID */ + unsigned short vendor_id; + /** Device Product ID */ + unsigned short product_id; + /** Serial Number */ + wchar_t *serial_number; + /** Device Release Number in binary-coded decimal, + also known as Device Version Number */ + unsigned short release_number; + /** Manufacturer String */ + wchar_t *manufacturer_string; + /** Product string */ + wchar_t *product_string; + /** Usage Page for this Device/Interface + (Windows/Mac/hidraw only) */ + unsigned short usage_page; + /** Usage for this Device/Interface + (Windows/Mac/hidraw only) */ + unsigned short usage; + /** The USB interface which this logical device + represents. + + Valid only if the device is a USB HID device. + Set to -1 in all other cases. + */ + int interface_number; + + /** Additional information about the USB interface. + Valid on libusb and Android implementations. */ + int interface_class; + int interface_subclass; + int interface_protocol; + + /** Underlying bus type */ + SDL_hid_bus_type bus_type; + + /** Pointer to the next device */ + struct SDL_hid_device_info *next; + +} SDL_hid_device_info; + + +/** + * Initialize the HIDAPI library. + * + * This function initializes the HIDAPI library. Calling it is not strictly + * necessary, as it will be called automatically by SDL_hid_enumerate() and + * any of the SDL_hid_open_*() functions if it is needed. This function should + * be called at the beginning of execution however, if there is a chance of + * HIDAPI handles being opened by different threads simultaneously. + * + * Each call to this function should have a matching call to SDL_hid_exit() + * + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_hid_exit + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_init(void); + +/** + * Finalize the HIDAPI library. + * + * This function frees all of the static data associated with HIDAPI. It + * should be called at the end of execution to avoid memory leaks. + * + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_hid_init + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_exit(void); + +/** + * Check to see if devices may have been added or removed. + * + * Enumerating the HID devices is an expensive operation, so you can call this + * to see if there have been any system device changes since the last call to + * this function. A change in the counter returned doesn't necessarily mean + * that anything has changed, but you can call SDL_hid_enumerate() to get an + * updated device list. + * + * Calling this function for the first time may cause a thread or other system + * resource to be allocated to track device change notifications. + * + * \returns a change counter that is incremented with each potential device + * change, or 0 if device change detection isn't available. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_hid_enumerate + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_hid_device_change_count(void); + +/** + * Enumerate the HID Devices. + * + * This function returns a linked list of all the HID devices attached to the + * system which match vendor_id and product_id. If `vendor_id` is set to 0 + * then any vendor matches. If `product_id` is set to 0 then any product + * matches. If `vendor_id` and `product_id` are both set to 0, then all HID + * devices will be returned. + * + * By default SDL will only enumerate controllers, to reduce risk of hanging + * or crashing on bad drivers, but SDL_HINT_HIDAPI_ENUMERATE_ONLY_CONTROLLERS + * can be set to "0" to enumerate all HID devices. + * + * \param vendor_id the Vendor ID (VID) of the types of device to open, or 0 + * to match any vendor. + * \param product_id the Product ID (PID) of the types of device to open, or 0 + * to match any product. + * \returns a pointer to a linked list of type SDL_hid_device_info, containing + * information about the HID devices attached to the system, or NULL + * in the case of failure. Free this linked list by calling + * SDL_hid_free_enumeration(). + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_hid_device_change_count + */ +extern SDL_DECLSPEC SDL_hid_device_info * SDLCALL SDL_hid_enumerate(unsigned short vendor_id, unsigned short product_id); + +/** + * Free an enumeration linked list. + * + * This function frees a linked list created by SDL_hid_enumerate(). + * + * \param devs pointer to a list of struct_device returned from + * SDL_hid_enumerate(). + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_hid_free_enumeration(SDL_hid_device_info *devs); + +/** + * Open a HID device using a Vendor ID (VID), Product ID (PID) and optionally + * a serial number. + * + * If `serial_number` is NULL, the first device with the specified VID and PID + * is opened. + * + * \param vendor_id the Vendor ID (VID) of the device to open. + * \param product_id the Product ID (PID) of the device to open. + * \param serial_number the Serial Number of the device to open (Optionally + * NULL). + * \returns a pointer to a SDL_hid_device object on success or NULL on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_hid_device * SDLCALL SDL_hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number); + +/** + * Open a HID device by its path name. + * + * The path name be determined by calling SDL_hid_enumerate(), or a + * platform-specific path name can be used (eg: /dev/hidraw0 on Linux). + * + * \param path the path name of the device to open. + * \returns a pointer to a SDL_hid_device object on success or NULL on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_hid_device * SDLCALL SDL_hid_open_path(const char *path); + +/** + * Write an Output report to a HID device. + * + * The first byte of `data` must contain the Report ID. For devices which only + * support a single report, this must be set to 0x0. The remaining bytes + * contain the report data. Since the Report ID is mandatory, calls to + * SDL_hid_write() will always contain one more byte than the report contains. + * For example, if a hid report is 16 bytes long, 17 bytes must be passed to + * SDL_hid_write(), the Report ID (or 0x0, for devices with a single report), + * followed by the report data (16 bytes). In this example, the length passed + * in would be 17. + * + * SDL_hid_write() will send the data on the first OUT endpoint, if one + * exists. If it does not, it will send the data through the Control Endpoint + * (Endpoint 0). + * + * \param dev a device handle returned from SDL_hid_open(). + * \param data the data to send, including the report number as the first + * byte. + * \param length the length in bytes of the data to send. + * \returns the actual number of bytes written and -1 on on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_write(SDL_hid_device *dev, const unsigned char *data, size_t length); + +/** + * Read an Input report from a HID device with timeout. + * + * Input reports are returned to the host through the INTERRUPT IN endpoint. + * The first byte will contain the Report number if the device uses numbered + * reports. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param data a buffer to put the read data into. + * \param length the number of bytes to read. For devices with multiple + * reports, make sure to read an extra byte for the report + * number. + * \param milliseconds timeout in milliseconds or -1 for blocking wait. + * \returns the actual number of bytes read and -1 on on failure; call + * SDL_GetError() for more information. If no packet was available to + * be read within the timeout period, this function returns 0. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_read_timeout(SDL_hid_device *dev, unsigned char *data, size_t length, int milliseconds); + +/** + * Read an Input report from a HID device. + * + * Input reports are returned to the host through the INTERRUPT IN endpoint. + * The first byte will contain the Report number if the device uses numbered + * reports. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param data a buffer to put the read data into. + * \param length the number of bytes to read. For devices with multiple + * reports, make sure to read an extra byte for the report + * number. + * \returns the actual number of bytes read and -1 on failure; call + * SDL_GetError() for more information. If no packet was available to + * be read and the handle is in non-blocking mode, this function + * returns 0. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_read(SDL_hid_device *dev, unsigned char *data, size_t length); + +/** + * Set the device handle to be non-blocking. + * + * In non-blocking mode calls to SDL_hid_read() will return immediately with a + * value of 0 if there is no data to be read. In blocking mode, SDL_hid_read() + * will wait (block) until there is data to read before returning. + * + * Nonblocking can be turned on and off at any time. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param nonblock enable or not the nonblocking reads - 1 to enable + * nonblocking - 0 to disable nonblocking. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_set_nonblocking(SDL_hid_device *dev, int nonblock); + +/** + * Send a Feature report to the device. + * + * Feature reports are sent over the Control endpoint as a Set_Report + * transfer. The first byte of `data` must contain the Report ID. For devices + * which only support a single report, this must be set to 0x0. The remaining + * bytes contain the report data. Since the Report ID is mandatory, calls to + * SDL_hid_send_feature_report() will always contain one more byte than the + * report contains. For example, if a hid report is 16 bytes long, 17 bytes + * must be passed to SDL_hid_send_feature_report(): the Report ID (or 0x0, for + * devices which do not use numbered reports), followed by the report data (16 + * bytes). In this example, the length passed in would be 17. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param data the data to send, including the report number as the first + * byte. + * \param length the length in bytes of the data to send, including the report + * number. + * \returns the actual number of bytes written and -1 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_send_feature_report(SDL_hid_device *dev, const unsigned char *data, size_t length); + +/** + * Get a feature report from a HID device. + * + * Set the first byte of `data` to the Report ID of the report to be read. + * Make sure to allow space for this extra byte in `data`. Upon return, the + * first byte will still contain the Report ID, and the report data will start + * in data[1]. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param data a buffer to put the read data into, including the Report ID. + * Set the first byte of `data` to the Report ID of the report to + * be read, or set it to zero if your device does not use numbered + * reports. + * \param length the number of bytes to read, including an extra byte for the + * report ID. The buffer can be longer than the actual report. + * \returns the number of bytes read plus one for the report ID (which is + * still in the first byte), or -1 on on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_get_feature_report(SDL_hid_device *dev, unsigned char *data, size_t length); + +/** + * Get an input report from a HID device. + * + * Set the first byte of `data` to the Report ID of the report to be read. + * Make sure to allow space for this extra byte in `data`. Upon return, the + * first byte will still contain the Report ID, and the report data will start + * in data[1]. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param data a buffer to put the read data into, including the Report ID. + * Set the first byte of `data` to the Report ID of the report to + * be read, or set it to zero if your device does not use numbered + * reports. + * \param length the number of bytes to read, including an extra byte for the + * report ID. The buffer can be longer than the actual report. + * \returns the number of bytes read plus one for the report ID (which is + * still in the first byte), or -1 on on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_get_input_report(SDL_hid_device *dev, unsigned char *data, size_t length); + +/** + * Close a HID device. + * + * \param dev a device handle returned from SDL_hid_open(). + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_close(SDL_hid_device *dev); + +/** + * Get The Manufacturer String from a HID device. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param string a wide string buffer to put the data into. + * \param maxlen the length of the buffer in multiples of wchar_t. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_get_manufacturer_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen); + +/** + * Get The Product String from a HID device. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param string a wide string buffer to put the data into. + * \param maxlen the length of the buffer in multiples of wchar_t. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_get_product_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen); + +/** + * Get The Serial Number String from a HID device. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param string a wide string buffer to put the data into. + * \param maxlen the length of the buffer in multiples of wchar_t. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_get_serial_number_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen); + +/** + * Get a string from a HID device, based on its string index. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param string_index the index of the string to get. + * \param string a wide string buffer to put the data into. + * \param maxlen the length of the buffer in multiples of wchar_t. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_get_indexed_string(SDL_hid_device *dev, int string_index, wchar_t *string, size_t maxlen); + +/** + * Get the device info from a HID device. + * + * \param dev a device handle returned from SDL_hid_open(). + * \returns a pointer to the SDL_hid_device_info for this hid_device or NULL + * on failure; call SDL_GetError() for more information. This struct + * is valid until the device is closed with SDL_hid_close(). + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_hid_device_info * SDLCALL SDL_hid_get_device_info(SDL_hid_device *dev); + +/** + * Get a report descriptor from a HID device. + * + * User has to provide a preallocated buffer where descriptor will be copied + * to. The recommended size for a preallocated buffer is 4096 bytes. + * + * \param dev a device handle returned from SDL_hid_open(). + * \param buf the buffer to copy descriptor into. + * \param buf_size the size of the buffer in bytes. + * \returns the number of bytes actually copied or -1 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_hid_get_report_descriptor(SDL_hid_device *dev, unsigned char *buf, size_t buf_size); + +/** + * Start or stop a BLE scan on iOS and tvOS to pair Steam Controllers. + * + * \param active true to start the scan, false to stop the scan. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_hid_ble_scan(bool active); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_hidapi_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_hints.h b/thirdparty/sdl/include/SDL3/SDL_hints.h new file mode 100644 index 00000000000..a081535716c --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_hints.h @@ -0,0 +1,4486 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryHints + * + * This file contains functions to set and get configuration hints, as well as + * listing each of them alphabetically. + * + * The convention for naming hints is SDL_HINT_X, where "SDL_X" is the + * environment variable that can be used to override the default. + * + * In general these hints are just that - they may or may not be supported or + * applicable on any given platform, but they provide a way for an application + * or user to give the library a hint as to how they would like the library to + * work. + */ + +#ifndef SDL_hints_h_ +#define SDL_hints_h_ + +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Specify the behavior of Alt+Tab while the keyboard is grabbed. + * + * By default, SDL emulates Alt+Tab functionality while the keyboard is + * grabbed and your window is full-screen. This prevents the user from getting + * stuck in your application if you've enabled keyboard grab. + * + * The variable can be set to the following values: + * + * - "0": SDL will not handle Alt+Tab. Your application is responsible for + * handling Alt+Tab while the keyboard is grabbed. + * - "1": SDL will minimize your window when Alt+Tab is pressed (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_ALLOW_ALT_TAB_WHILE_GRABBED "SDL_ALLOW_ALT_TAB_WHILE_GRABBED" + +/** + * A variable to control whether the SDL activity is allowed to be re-created. + * + * If this hint is true, the activity can be recreated on demand by the OS, + * and Java static data and C++ static data remain with their current values. + * If this hint is false, then SDL will call exit() when you return from your + * main function and the application will be terminated and then started fresh + * each time. + * + * The variable can be set to the following values: + * + * - "0": The application starts fresh at each launch. (default) + * - "1": The application activity can be recreated by the OS. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_ANDROID_ALLOW_RECREATE_ACTIVITY "SDL_ANDROID_ALLOW_RECREATE_ACTIVITY" + +/** + * A variable to control whether the event loop will block itself when the app + * is paused. + * + * The variable can be set to the following values: + * + * - "0": Non blocking. + * - "1": Blocking. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_ANDROID_BLOCK_ON_PAUSE "SDL_ANDROID_BLOCK_ON_PAUSE" + +/** + * A variable to control whether low latency audio should be enabled. + * + * Some devices have poor quality output when this is enabled, but this is + * usually an improvement in audio latency. + * + * The variable can be set to the following values: + * + * - "0": Low latency audio is not enabled. + * - "1": Low latency audio is enabled. (default) + * + * This hint should be set before SDL audio is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_ANDROID_LOW_LATENCY_AUDIO "SDL_ANDROID_LOW_LATENCY_AUDIO" + +/** + * A variable to control whether we trap the Android back button to handle it + * manually. + * + * This is necessary for the right mouse button to work on some Android + * devices, or to be able to trap the back button for use in your code + * reliably. If this hint is true, the back button will show up as an + * SDL_EVENT_KEY_DOWN / SDL_EVENT_KEY_UP pair with a keycode of + * SDL_SCANCODE_AC_BACK. + * + * The variable can be set to the following values: + * + * - "0": Back button will be handled as usual for system. (default) + * - "1": Back button will be trapped, allowing you to handle the key press + * manually. (This will also let right mouse click work on systems where the + * right mouse button functions as back.) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_ANDROID_TRAP_BACK_BUTTON "SDL_ANDROID_TRAP_BACK_BUTTON" + +/** + * A variable setting the app ID string. + * + * This string is used by desktop compositors to identify and group windows + * together, as well as match applications with associated desktop settings + * and icons. + * + * This will override SDL_PROP_APP_METADATA_IDENTIFIER_STRING, if set by the + * application. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_APP_ID "SDL_APP_ID" + +/** + * A variable setting the application name. + * + * This hint lets you specify the application name sent to the OS when + * required. For example, this will often appear in volume control applets for + * audio streams, and in lists of applications which are inhibiting the + * screensaver. You should use a string that describes your program ("My Game + * 2: The Revenge") + * + * This will override SDL_PROP_APP_METADATA_NAME_STRING, if set by the + * application. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_APP_NAME "SDL_APP_NAME" + +/** + * A variable controlling whether controllers used with the Apple TV generate + * UI events. + * + * When UI events are generated by controller input, the app will be + * backgrounded when the Apple TV remote's menu button is pressed, and when + * the pause or B buttons on gamepads are pressed. + * + * More information about properly making use of controllers for the Apple TV + * can be found here: + * https://developer.apple.com/tvos/human-interface-guidelines/remote-and-controllers/ + * + * The variable can be set to the following values: + * + * - "0": Controller input does not generate UI events. (default) + * - "1": Controller input generates UI events. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS "SDL_APPLE_TV_CONTROLLER_UI_EVENTS" + +/** + * A variable controlling whether the Apple TV remote's joystick axes will + * automatically match the rotation of the remote. + * + * The variable can be set to the following values: + * + * - "0": Remote orientation does not affect joystick axes. (default) + * - "1": Joystick axes are based on the orientation of the remote. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION "SDL_APPLE_TV_REMOTE_ALLOW_ROTATION" + +/** + * Specify the default ALSA audio device name. + * + * This variable is a specific audio device to open when the "default" audio + * device is used. + * + * This hint will be ignored when opening the default playback device if + * SDL_HINT_AUDIO_ALSA_DEFAULT_PLAYBACK_DEVICE is set, or when opening the + * default recording device if SDL_HINT_AUDIO_ALSA_DEFAULT_RECORDING_DEVICE is + * set. + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + * + * \sa SDL_HINT_AUDIO_ALSA_DEFAULT_PLAYBACK_DEVICE + * \sa SDL_HINT_AUDIO_ALSA_DEFAULT_RECORDING_DEVICE + */ +#define SDL_HINT_AUDIO_ALSA_DEFAULT_DEVICE "SDL_AUDIO_ALSA_DEFAULT_DEVICE" + +/** + * Specify the default ALSA audio playback device name. + * + * This variable is a specific audio device to open for playback, when the + * "default" audio device is used. + * + * If this hint isn't set, SDL will check SDL_HINT_AUDIO_ALSA_DEFAULT_DEVICE + * before choosing a reasonable default. + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + * + * \sa SDL_HINT_AUDIO_ALSA_DEFAULT_RECORDING_DEVICE + * \sa SDL_HINT_AUDIO_ALSA_DEFAULT_DEVICE + */ +#define SDL_HINT_AUDIO_ALSA_DEFAULT_PLAYBACK_DEVICE "SDL_AUDIO_ALSA_DEFAULT_PLAYBACK_DEVICE" + +/** + * Specify the default ALSA audio recording device name. + * + * This variable is a specific audio device to open for recording, when the + * "default" audio device is used. + * + * If this hint isn't set, SDL will check SDL_HINT_AUDIO_ALSA_DEFAULT_DEVICE + * before choosing a reasonable default. + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + * + * \sa SDL_HINT_AUDIO_ALSA_DEFAULT_PLAYBACK_DEVICE + * \sa SDL_HINT_AUDIO_ALSA_DEFAULT_DEVICE + */ +#define SDL_HINT_AUDIO_ALSA_DEFAULT_RECORDING_DEVICE "SDL_AUDIO_ALSA_DEFAULT_RECORDING_DEVICE" + +/** + * A variable controlling the audio category on iOS and macOS. + * + * The variable can be set to the following values: + * + * - "ambient": Use the AVAudioSessionCategoryAmbient audio category, will be + * muted by the phone mute switch (default) + * - "playback": Use the AVAudioSessionCategoryPlayback category. + * + * For more information, see Apple's documentation: + * https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionCategoriesandModes/AudioSessionCategoriesandModes.html + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_CATEGORY "SDL_AUDIO_CATEGORY" + +/** + * A variable controlling the default audio channel count. + * + * If the application doesn't specify the audio channel count when opening the + * device, this hint can be used to specify a default channel count that will + * be used. This defaults to "1" for recording and "2" for playback devices. + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_CHANNELS "SDL_AUDIO_CHANNELS" + +/** + * Specify an application icon name for an audio device. + * + * Some audio backends (such as Pulseaudio and Pipewire) allow you to set an + * XDG icon name for your application. Among other things, this icon might + * show up in a system control panel that lets the user adjust the volume on + * specific audio streams instead of using one giant master volume slider. + * Note that this is unrelated to the icon used by the windowing system, which + * may be set with SDL_SetWindowIcon (or via desktop file on Wayland). + * + * Setting this to "" or leaving it unset will have SDL use a reasonable + * default, "applications-games", which is likely to be installed. See + * https://specifications.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html + * and + * https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html + * for the relevant XDG icon specs. + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_DEVICE_APP_ICON_NAME "SDL_AUDIO_DEVICE_APP_ICON_NAME" + +/** + * A variable controlling device buffer size. + * + * This hint is an integer > 0, that represents the size of the device's + * buffer in sample frames (stereo audio data in 16-bit format is 4 bytes per + * sample frame, for example). + * + * SDL3 generally decides this value on behalf of the app, but if for some + * reason the app needs to dictate this (because they want either lower + * latency or higher throughput AND ARE WILLING TO DEAL WITH what that might + * require of the app), they can specify it. + * + * SDL will try to accommodate this value, but there is no promise you'll get + * the buffer size requested. Many platforms won't honor this request at all, + * or might adjust it. + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES "SDL_AUDIO_DEVICE_SAMPLE_FRAMES" + +/** + * Specify an audio stream name for an audio device. + * + * Some audio backends (such as PulseAudio) allow you to describe your audio + * stream. Among other things, this description might show up in a system + * control panel that lets the user adjust the volume on specific audio + * streams instead of using one giant master volume slider. + * + * This hints lets you transmit that information to the OS. The contents of + * this hint are used while opening an audio device. You should use a string + * that describes your what your program is playing ("audio stream" is + * probably sufficient in many cases, but this could be useful for something + * like "team chat" if you have a headset playing VoIP audio separately). + * + * Setting this to "" or leaving it unset will have SDL use a reasonable + * default: "audio stream" or something similar. + * + * Note that while this talks about audio streams, this is an OS-level + * concept, so it applies to a physical audio device in this case, and not an + * SDL_AudioStream, nor an SDL logical audio device. + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_DEVICE_STREAM_NAME "SDL_AUDIO_DEVICE_STREAM_NAME" + +/** + * Specify an application role for an audio device. + * + * Some audio backends (such as Pipewire) allow you to describe the role of + * your audio stream. Among other things, this description might show up in a + * system control panel or software for displaying and manipulating media + * playback/recording graphs. + * + * This hints lets you transmit that information to the OS. The contents of + * this hint are used while opening an audio device. You should use a string + * that describes your what your program is playing (Game, Music, Movie, + * etc...). + * + * Setting this to "" or leaving it unset will have SDL use a reasonable + * default: "Game" or something similar. + * + * Note that while this talks about audio streams, this is an OS-level + * concept, so it applies to a physical audio device in this case, and not an + * SDL_AudioStream, nor an SDL logical audio device. + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_DEVICE_STREAM_ROLE "SDL_AUDIO_DEVICE_STREAM_ROLE" + +/** + * Specify the input file when recording audio using the disk audio driver. + * + * This defaults to "sdlaudio-in.raw" + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_DISK_INPUT_FILE "SDL_AUDIO_DISK_INPUT_FILE" + +/** + * Specify the output file when playing audio using the disk audio driver. + * + * This defaults to "sdlaudio.raw" + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_DISK_OUTPUT_FILE "SDL_AUDIO_DISK_OUTPUT_FILE" + +/** + * A variable controlling the audio rate when using the disk audio driver. + * + * The disk audio driver normally simulates real-time for the audio rate that + * was specified, but you can use this variable to adjust this rate higher or + * lower down to 0. The default value is "1.0". + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_DISK_TIMESCALE "SDL_AUDIO_DISK_TIMESCALE" + +/** + * A variable that specifies an audio backend to use. + * + * By default, SDL will try all available audio backends in a reasonable order + * until it finds one that can work, but this hint allows the app or user to + * force a specific driver, such as "pipewire" if, say, you are on PulseAudio + * but want to try talking to the lower level instead. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_DRIVER "SDL_AUDIO_DRIVER" + +/** + * A variable controlling the audio rate when using the dummy audio driver. + * + * The dummy audio driver normally simulates real-time for the audio rate that + * was specified, but you can use this variable to adjust this rate higher or + * lower down to 0. The default value is "1.0". + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_DUMMY_TIMESCALE "SDL_AUDIO_DUMMY_TIMESCALE" + +/** + * A variable controlling the default audio format. + * + * If the application doesn't specify the audio format when opening the + * device, this hint can be used to specify a default format that will be + * used. + * + * The variable can be set to the following values: + * + * - "U8": Unsigned 8-bit audio + * - "S8": Signed 8-bit audio + * - "S16LE": Signed 16-bit little-endian audio + * - "S16BE": Signed 16-bit big-endian audio + * - "S16": Signed 16-bit native-endian audio (default) + * - "S32LE": Signed 32-bit little-endian audio + * - "S32BE": Signed 32-bit big-endian audio + * - "S32": Signed 32-bit native-endian audio + * - "F32LE": Floating point little-endian audio + * - "F32BE": Floating point big-endian audio + * - "F32": Floating point native-endian audio + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_FORMAT "SDL_AUDIO_FORMAT" + +/** + * A variable controlling the default audio frequency. + * + * If the application doesn't specify the audio frequency when opening the + * device, this hint can be used to specify a default frequency that will be + * used. This defaults to "44100". + * + * This hint should be set before an audio device is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_FREQUENCY "SDL_AUDIO_FREQUENCY" + +/** + * A variable that causes SDL to not ignore audio "monitors". + * + * This is currently only used by the PulseAudio driver. + * + * By default, SDL ignores audio devices that aren't associated with physical + * hardware. Changing this hint to "1" will expose anything SDL sees that + * appears to be an audio source or sink. This will add "devices" to the list + * that the user probably doesn't want or need, but it can be useful in + * scenarios where you want to hook up SDL to some sort of virtual device, + * etc. + * + * The variable can be set to the following values: + * + * - "0": Audio monitor devices will be ignored. (default) + * - "1": Audio monitor devices will show up in the device list. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUDIO_INCLUDE_MONITORS "SDL_AUDIO_INCLUDE_MONITORS" + +/** + * A variable controlling whether SDL updates joystick state when getting + * input events. + * + * The variable can be set to the following values: + * + * - "0": You'll call SDL_UpdateJoysticks() manually. + * - "1": SDL will automatically call SDL_UpdateJoysticks(). (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUTO_UPDATE_JOYSTICKS "SDL_AUTO_UPDATE_JOYSTICKS" + +/** + * A variable controlling whether SDL updates sensor state when getting input + * events. + * + * The variable can be set to the following values: + * + * - "0": You'll call SDL_UpdateSensors() manually. + * - "1": SDL will automatically call SDL_UpdateSensors(). (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_AUTO_UPDATE_SENSORS "SDL_AUTO_UPDATE_SENSORS" + +/** + * Prevent SDL from using version 4 of the bitmap header when saving BMPs. + * + * The bitmap header version 4 is required for proper alpha channel support + * and SDL will use it when required. Should this not be desired, this hint + * can force the use of the 40 byte header version which is supported + * everywhere. + * + * The variable can be set to the following values: + * + * - "0": Surfaces with a colorkey or an alpha channel are saved to a 32-bit + * BMP file with an alpha mask. SDL will use the bitmap header version 4 and + * set the alpha mask accordingly. (default) + * - "1": Surfaces with a colorkey or an alpha channel are saved to a 32-bit + * BMP file without an alpha mask. The alpha channel data will be in the + * file, but applications are going to ignore it. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_BMP_SAVE_LEGACY_FORMAT "SDL_BMP_SAVE_LEGACY_FORMAT" + +/** + * A variable that decides what camera backend to use. + * + * By default, SDL will try all available camera backends in a reasonable + * order until it finds one that can work, but this hint allows the app or + * user to force a specific target, such as "directshow" if, say, you are on + * Windows Media Foundations but want to try DirectShow instead. + * + * The default value is unset, in which case SDL will try to figure out the + * best camera backend on your behalf. This hint needs to be set before + * SDL_Init() is called to be useful. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_CAMERA_DRIVER "SDL_CAMERA_DRIVER" + +/** + * A variable that limits what CPU features are available. + * + * By default, SDL marks all features the current CPU supports as available. + * This hint allows to limit these to a subset. + * + * When the hint is unset, or empty, SDL will enable all detected CPU + * features. + * + * The variable can be set to a comma separated list containing the following + * items: + * + * - "all" + * - "altivec" + * - "sse" + * - "sse2" + * - "sse3" + * - "sse41" + * - "sse42" + * - "avx" + * - "avx2" + * - "avx512f" + * - "arm-simd" + * - "neon" + * - "lsx" + * - "lasx" + * + * The items can be prefixed by '+'/'-' to add/remove features. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_CPU_FEATURE_MASK "SDL_CPU_FEATURE_MASK" + +/** + * A variable controlling whether DirectInput should be used for controllers. + * + * The variable can be set to the following values: + * + * - "0": Disable DirectInput detection. + * - "1": Enable DirectInput detection. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_DIRECTINPUT "SDL_JOYSTICK_DIRECTINPUT" + +/** + * A variable that specifies a dialog backend to use. + * + * By default, SDL will try all available dialog backends in a reasonable + * order until it finds one that can work, but this hint allows the app or + * user to force a specific target. + * + * If the specified target does not exist or is not available, the + * dialog-related function calls will fail. + * + * This hint currently only applies to platforms using the generic "Unix" + * dialog implementation, but may be extended to more platforms in the future. + * Note that some Unix and Unix-like platforms have their own implementation, + * such as macOS and Haiku. + * + * The variable can be set to the following values: + * + * - NULL: Select automatically (default, all platforms) + * - "portal": Use XDG Portals through DBus (Unix only) + * - "zenity": Use the Zenity program (Unix only) + * + * More options may be added in the future. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_FILE_DIALOG_DRIVER "SDL_FILE_DIALOG_DRIVER" + +/** + * Override for SDL_GetDisplayUsableBounds(). + * + * If set, this hint will override the expected results for + * SDL_GetDisplayUsableBounds() for display index 0. Generally you don't want + * to do this, but this allows an embedded system to request that some of the + * screen be reserved for other uses when paired with a well-behaved + * application. + * + * The contents of this hint must be 4 comma-separated integers, the first is + * the bounds x, then y, width and height, in that order. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_DISPLAY_USABLE_BOUNDS "SDL_DISPLAY_USABLE_BOUNDS" + +/** + * Disable giving back control to the browser automatically when running with + * asyncify. + * + * With -s ASYNCIFY, SDL calls emscripten_sleep during operations such as + * refreshing the screen or polling events. + * + * This hint only applies to the emscripten platform. + * + * The variable can be set to the following values: + * + * - "0": Disable emscripten_sleep calls (if you give back browser control + * manually or use asyncify for other purposes). + * - "1": Enable emscripten_sleep calls. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_EMSCRIPTEN_ASYNCIFY "SDL_EMSCRIPTEN_ASYNCIFY" + +/** + * Specify the CSS selector used for the "default" window/canvas. + * + * This hint only applies to the emscripten platform. + * + * The default value is "#canvas" + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_EMSCRIPTEN_CANVAS_SELECTOR "SDL_EMSCRIPTEN_CANVAS_SELECTOR" + +/** + * Override the binding element for keyboard inputs for Emscripten builds. + * + * This hint only applies to the emscripten platform. + * + * The variable can be one of: + * + * - "#window": the javascript window object (default) + * - "#document": the javascript document object + * - "#screen": the javascript window.screen object + * - "#canvas": the WebGL canvas element + * - "#none": Don't bind anything at all + * - any other string without a leading # sign applies to the element on the + * page with that ID. + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT "SDL_EMSCRIPTEN_KEYBOARD_ELEMENT" + +/** + * A variable that controls whether the on-screen keyboard should be shown + * when text input is active. + * + * The variable can be set to the following values: + * + * - "auto": The on-screen keyboard will be shown if there is no physical + * keyboard attached. (default) + * - "0": Do not show the on-screen keyboard. + * - "1": Show the on-screen keyboard, if available. + * + * This hint must be set before SDL_StartTextInput() is called + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_ENABLE_SCREEN_KEYBOARD "SDL_ENABLE_SCREEN_KEYBOARD" + +/** + * A variable containing a list of evdev devices to use if udev is not + * available. + * + * The list of devices is in the form: + * + * deviceclass:path[,deviceclass:path[,...]] + * + * where device class is an integer representing the SDL_UDEV_deviceclass and + * path is the full path to the event device. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_EVDEV_DEVICES "SDL_EVDEV_DEVICES" + +/** + * A variable controlling verbosity of the logging of SDL events pushed onto + * the internal queue. + * + * The variable can be set to the following values, from least to most + * verbose: + * + * - "0": Don't log any events. (default) + * - "1": Log most events (other than the really spammy ones). + * - "2": Include mouse and finger motion events. + * + * This is generally meant to be used to debug SDL itself, but can be useful + * for application developers that need better visibility into what is going + * on in the event queue. Logged events are sent through SDL_Log(), which + * means by default they appear on stdout on most platforms or maybe + * OutputDebugString() on Windows, and can be funneled by the app with + * SDL_SetLogOutputFunction(), etc. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_EVENT_LOGGING "SDL_EVENT_LOGGING" + +/** + * A variable controlling whether raising the window should be done more + * forcefully. + * + * The variable can be set to the following values: + * + * - "0": Honor the OS policy for raising windows. (default) + * - "1": Force the window to be raised, overriding any OS policy. + * + * At present, this is only an issue under MS Windows, which makes it nearly + * impossible to programmatically move a window to the foreground, for + * "security" reasons. See http://stackoverflow.com/a/34414846 for a + * discussion. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_FORCE_RAISEWINDOW "SDL_FORCE_RAISEWINDOW" + +/** + * A variable controlling how 3D acceleration is used to accelerate the SDL + * screen surface. + * + * SDL can try to accelerate the SDL screen surface by using streaming + * textures with a 3D rendering engine. This variable controls whether and how + * this is done. + * + * The variable can be set to the following values: + * + * - "0": Disable 3D acceleration + * - "1": Enable 3D acceleration, using the default renderer. (default) + * - "X": Enable 3D acceleration, using X where X is one of the valid + * rendering drivers. (e.g. "direct3d", "opengl", etc.) + * + * This hint should be set before calling SDL_GetWindowSurface() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_FRAMEBUFFER_ACCELERATION "SDL_FRAMEBUFFER_ACCELERATION" + +/** + * A variable that lets you manually hint extra gamecontroller db entries. + * + * The variable should be newline delimited rows of gamecontroller config + * data, see SDL_gamepad.h + * + * You can update mappings after SDL is initialized with + * SDL_GetGamepadMappingForGUID() and SDL_AddGamepadMapping() + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GAMECONTROLLERCONFIG "SDL_GAMECONTROLLERCONFIG" + +/** + * A variable that lets you provide a file with extra gamecontroller db + * entries. + * + * The file should contain lines of gamecontroller config data, see + * SDL_gamepad.h + * + * You can update mappings after SDL is initialized with + * SDL_GetGamepadMappingForGUID() and SDL_AddGamepadMapping() + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GAMECONTROLLERCONFIG_FILE "SDL_GAMECONTROLLERCONFIG_FILE" + +/** + * A variable that overrides the automatic controller type detection. + * + * The variable should be comma separated entries, in the form: VID/PID=type + * + * The VID and PID should be hexadecimal with exactly 4 digits, e.g. 0x00fd + * + * This hint affects what low level protocol is used with the HIDAPI driver. + * + * The variable can be set to the following values: + * + * - "Xbox360" + * - "XboxOne" + * - "PS3" + * - "PS4" + * - "PS5" + * - "SwitchPro" + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GAMECONTROLLERTYPE "SDL_GAMECONTROLLERTYPE" + +/** + * A variable containing a list of devices to skip when scanning for game + * controllers. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES "SDL_GAMECONTROLLER_IGNORE_DEVICES" + +/** + * If set, all devices will be skipped when scanning for game controllers + * except for the ones listed in this variable. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT "SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT" + +/** + * A variable that controls whether the device's built-in accelerometer and + * gyro should be used as sensors for gamepads. + * + * The variable can be set to the following values: + * + * - "0": Sensor fusion is disabled + * - "1": Sensor fusion is enabled for all controllers that lack sensors + * + * Or the variable can be a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint should be set before a gamepad is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GAMECONTROLLER_SENSOR_FUSION "SDL_GAMECONTROLLER_SENSOR_FUSION" + +/** + * This variable sets the default text of the TextInput window on GDK + * platforms. + * + * This hint is available only if SDL_GDK_TEXTINPUT defined. + * + * This hint should be set before calling SDL_StartTextInput() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GDK_TEXTINPUT_DEFAULT_TEXT "SDL_GDK_TEXTINPUT_DEFAULT_TEXT" + +/** + * This variable sets the description of the TextInput window on GDK + * platforms. + * + * This hint is available only if SDL_GDK_TEXTINPUT defined. + * + * This hint should be set before calling SDL_StartTextInput() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GDK_TEXTINPUT_DESCRIPTION "SDL_GDK_TEXTINPUT_DESCRIPTION" + +/** + * This variable sets the maximum input length of the TextInput window on GDK + * platforms. + * + * The value must be a stringified integer, for example "10" to allow for up + * to 10 characters of text input. + * + * This hint is available only if SDL_GDK_TEXTINPUT defined. + * + * This hint should be set before calling SDL_StartTextInput() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GDK_TEXTINPUT_MAX_LENGTH "SDL_GDK_TEXTINPUT_MAX_LENGTH" + +/** + * This variable sets the input scope of the TextInput window on GDK + * platforms. + * + * Set this hint to change the XGameUiTextEntryInputScope value that will be + * passed to the window creation function. The value must be a stringified + * integer, for example "0" for XGameUiTextEntryInputScope::Default. + * + * This hint is available only if SDL_GDK_TEXTINPUT defined. + * + * This hint should be set before calling SDL_StartTextInput() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GDK_TEXTINPUT_SCOPE "SDL_GDK_TEXTINPUT_SCOPE" + +/** + * This variable sets the title of the TextInput window on GDK platforms. + * + * This hint is available only if SDL_GDK_TEXTINPUT defined. + * + * This hint should be set before calling SDL_StartTextInput() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GDK_TEXTINPUT_TITLE "SDL_GDK_TEXTINPUT_TITLE" + +/** + * A variable to control whether HIDAPI uses libusb for device access. + * + * By default libusb will only be used for a few devices that require direct + * USB access, and this can be controlled with + * SDL_HINT_HIDAPI_LIBUSB_WHITELIST. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI will not use libusb for device access. + * - "1": HIDAPI will use libusb for device access if available. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_HIDAPI_LIBUSB "SDL_HIDAPI_LIBUSB" + +/** + * A variable to control whether HIDAPI uses libusb only for whitelisted + * devices. + * + * By default libusb will only be used for a few devices that require direct + * USB access. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI will use libusb for all device access. + * - "1": HIDAPI will use libusb only for whitelisted devices. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_HIDAPI_LIBUSB_WHITELIST "SDL_HIDAPI_LIBUSB_WHITELIST" + +/** + * A variable to control whether HIDAPI uses udev for device detection. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI will poll for device changes. + * - "1": HIDAPI will use udev for device detection. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_HIDAPI_UDEV "SDL_HIDAPI_UDEV" + +/** + * A variable that specifies a GPU backend to use. + * + * By default, SDL will try all available GPU backends in a reasonable order + * until it finds one that can work, but this hint allows the app or user to + * force a specific target, such as "direct3d12" if, say, your hardware + * supports Vulkan but you want to try using D3D12 instead. + * + * This hint should be set before any GPU functions are called. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_GPU_DRIVER "SDL_GPU_DRIVER" + +/** + * A variable to control whether SDL_hid_enumerate() enumerates all HID + * devices or only controllers. + * + * The variable can be set to the following values: + * + * - "0": SDL_hid_enumerate() will enumerate all HID devices. + * - "1": SDL_hid_enumerate() will only enumerate controllers. (default) + * + * By default SDL will only enumerate controllers, to reduce risk of hanging + * or crashing on devices with bad drivers and avoiding macOS keyboard capture + * permission prompts. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_HIDAPI_ENUMERATE_ONLY_CONTROLLERS "SDL_HIDAPI_ENUMERATE_ONLY_CONTROLLERS" + +/** + * A variable containing a list of devices to ignore in SDL_hid_enumerate(). + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * For example, to ignore the Shanwan DS3 controller and any Valve controller, + * you might use the string "0x2563/0x0523,0x28de/0x0000" + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_HIDAPI_IGNORE_DEVICES "SDL_HIDAPI_IGNORE_DEVICES" + +/** + * A variable describing what IME UI elements the application can display. + * + * By default IME UI is handled using native components by the OS where + * possible, however this can interfere with or not be visible when exclusive + * fullscreen mode is used. + * + * The variable can be set to a comma separated list containing the following + * items: + * + * - "none" or "0": The application can't render any IME elements, and native + * UI should be used. (default) + * - "composition": The application handles SDL_EVENT_TEXT_EDITING events and + * can render the composition text. + * - "candidates": The application handles SDL_EVENT_TEXT_EDITING_CANDIDATES + * and can render the candidate list. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_IME_IMPLEMENTED_UI "SDL_IME_IMPLEMENTED_UI" + +/** + * A variable controlling whether the home indicator bar on iPhone X should be + * hidden. + * + * The variable can be set to the following values: + * + * - "0": The indicator bar is not hidden. (default for windowed applications) + * - "1": The indicator bar is hidden and is shown when the screen is touched + * (useful for movie playback applications). + * - "2": The indicator bar is dim and the first swipe makes it visible and + * the second swipe performs the "home" action. (default for fullscreen + * applications) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_IOS_HIDE_HOME_INDICATOR "SDL_IOS_HIDE_HOME_INDICATOR" + +/** + * A variable that lets you enable joystick (and gamecontroller) events even + * when your app is in the background. + * + * The variable can be set to the following values: + * + * - "0": Disable joystick & gamecontroller input events when the application + * is in the background. (default) + * - "1": Enable joystick & gamecontroller input events when the application + * is in the background. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS "SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS" + +/** + * A variable containing a list of arcade stick style controllers. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_ARCADESTICK_DEVICES "SDL_JOYSTICK_ARCADESTICK_DEVICES" + +/** + * A variable containing a list of devices that are not arcade stick style + * controllers. + * + * This will override SDL_HINT_JOYSTICK_ARCADESTICK_DEVICES and the built in + * device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_ARCADESTICK_DEVICES_EXCLUDED "SDL_JOYSTICK_ARCADESTICK_DEVICES_EXCLUDED" + +/** + * A variable containing a list of devices that should not be considered + * joysticks. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_BLACKLIST_DEVICES "SDL_JOYSTICK_BLACKLIST_DEVICES" + +/** + * A variable containing a list of devices that should be considered + * joysticks. + * + * This will override SDL_HINT_JOYSTICK_BLACKLIST_DEVICES and the built in + * device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_BLACKLIST_DEVICES_EXCLUDED "SDL_JOYSTICK_BLACKLIST_DEVICES_EXCLUDED" + +/** + * A variable containing a comma separated list of devices to open as + * joysticks. + * + * This variable is currently only used by the Linux joystick driver. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_DEVICE "SDL_JOYSTICK_DEVICE" + +/** + * A variable controlling whether enhanced reports should be used for + * controllers when using the HIDAPI driver. + * + * Enhanced reports allow rumble and effects on Bluetooth PlayStation + * controllers and gyro on Nintendo Switch controllers, but break Windows + * DirectInput for other applications that don't use SDL. + * + * Once enhanced reports are enabled, they can't be disabled on PlayStation + * controllers without power cycling the controller. + * + * The variable can be set to the following values: + * + * - "0": enhanced reports are not enabled. + * - "1": enhanced reports are enabled. (default) + * - "auto": enhanced features are advertised to the application, but SDL + * doesn't change the controller report mode unless the application uses + * them. + * + * This hint can be enabled anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_ENHANCED_REPORTS "SDL_JOYSTICK_ENHANCED_REPORTS" + +/** + * A variable containing a list of flightstick style controllers. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_FLIGHTSTICK_DEVICES "SDL_JOYSTICK_FLIGHTSTICK_DEVICES" + +/** + * A variable containing a list of devices that are not flightstick style + * controllers. + * + * This will override SDL_HINT_JOYSTICK_FLIGHTSTICK_DEVICES and the built in + * device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_FLIGHTSTICK_DEVICES_EXCLUDED "SDL_JOYSTICK_FLIGHTSTICK_DEVICES_EXCLUDED" + +/** + * A variable controlling whether GameInput should be used for controller + * handling on Windows. + * + * The variable can be set to the following values: + * + * - "0": GameInput is not used. + * - "1": GameInput is used. + * + * The default is "1" on GDK platforms, and "0" otherwise. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_GAMEINPUT "SDL_JOYSTICK_GAMEINPUT" + +/** + * A variable containing a list of devices known to have a GameCube form + * factor. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_GAMECUBE_DEVICES "SDL_JOYSTICK_GAMECUBE_DEVICES" + +/** + * A variable containing a list of devices known not to have a GameCube form + * factor. + * + * This will override SDL_HINT_JOYSTICK_GAMECUBE_DEVICES and the built in + * device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_GAMECUBE_DEVICES_EXCLUDED "SDL_JOYSTICK_GAMECUBE_DEVICES_EXCLUDED" + +/** + * A variable controlling whether the HIDAPI joystick drivers should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI drivers are not used. + * - "1": HIDAPI drivers are used. (default) + * + * This variable is the default for all drivers, but can be overridden by the + * hints for specific drivers below. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI "SDL_JOYSTICK_HIDAPI" + +/** + * A variable controlling whether Nintendo Switch Joy-Con controllers will be + * combined into a single Pro-like controller when using the HIDAPI driver. + * + * The variable can be set to the following values: + * + * - "0": Left and right Joy-Con controllers will not be combined and each + * will be a mini-gamepad. + * - "1": Left and right Joy-Con controllers will be combined into a single + * controller. (default) + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_COMBINE_JOY_CONS "SDL_JOYSTICK_HIDAPI_COMBINE_JOY_CONS" + +/** + * A variable controlling whether the HIDAPI driver for Nintendo GameCube + * controllers should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE "SDL_JOYSTICK_HIDAPI_GAMECUBE" + +/** + * A variable controlling whether rumble is used to implement the GameCube + * controller's 3 rumble modes, Stop(0), Rumble(1), and StopHard(2). + * + * This is useful for applications that need full compatibility for things + * like ADSR envelopes. - Stop is implemented by setting low_frequency_rumble + * to 0 and high_frequency_rumble >0 - Rumble is both at any arbitrary value - + * StopHard is implemented by setting both low_frequency_rumble and + * high_frequency_rumble to 0 + * + * The variable can be set to the following values: + * + * - "0": Normal rumble behavior is behavior is used. (default) + * - "1": Proper GameCube controller rumble behavior is used. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE_RUMBLE_BRAKE "SDL_JOYSTICK_HIDAPI_GAMECUBE_RUMBLE_BRAKE" + +/** + * A variable controlling whether the HIDAPI driver for Nintendo Switch + * Joy-Cons should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS "SDL_JOYSTICK_HIDAPI_JOY_CONS" + +/** + * A variable controlling whether the Home button LED should be turned on when + * a Nintendo Switch Joy-Con controller is opened. + * + * The variable can be set to the following values: + * + * - "0": home button LED is turned off + * - "1": home button LED is turned on + * + * By default the Home button LED state is not changed. This hint can also be + * set to a floating point value between 0.0 and 1.0 which controls the + * brightness of the Home button LED. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_JOYCON_HOME_LED "SDL_JOYSTICK_HIDAPI_JOYCON_HOME_LED" + +/** + * A variable controlling whether the HIDAPI driver for Amazon Luna + * controllers connected via Bluetooth should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_LUNA "SDL_JOYSTICK_HIDAPI_LUNA" + +/** + * A variable controlling whether the HIDAPI driver for Nintendo Online + * classic controllers should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC "SDL_JOYSTICK_HIDAPI_NINTENDO_CLASSIC" + +/** + * A variable controlling whether the HIDAPI driver for PS3 controllers should + * be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI on macOS, and "0" on + * other platforms. + * + * For official Sony driver (sixaxis.sys) use + * SDL_HINT_JOYSTICK_HIDAPI_PS3_SIXAXIS_DRIVER. See + * https://github.com/ViGEm/DsHidMini for an alternative driver on Windows. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS3 "SDL_JOYSTICK_HIDAPI_PS3" + +/** + * A variable controlling whether the Sony driver (sixaxis.sys) for PS3 + * controllers (Sixaxis/DualShock 3) should be used. + * + * The variable can be set to the following values: + * + * - "0": Sony driver (sixaxis.sys) is not used. + * - "1": Sony driver (sixaxis.sys) is used. + * + * The default value is 0. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS3_SIXAXIS_DRIVER "SDL_JOYSTICK_HIDAPI_PS3_SIXAXIS_DRIVER" + +/** + * A variable controlling whether the HIDAPI driver for PS4 controllers should + * be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS4 "SDL_JOYSTICK_HIDAPI_PS4" + +/** + * A variable controlling the update rate of the PS4 controller over Bluetooth + * when using the HIDAPI driver. + * + * This defaults to 4 ms, to match the behavior over USB, and to be more + * friendly to other Bluetooth devices and older Bluetooth hardware on the + * computer. It can be set to "1" (1000Hz), "2" (500Hz) and "4" (250Hz) + * + * This hint can be set anytime, but only takes effect when extended input + * reports are enabled. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS4_REPORT_INTERVAL "SDL_JOYSTICK_HIDAPI_PS4_REPORT_INTERVAL" + +/** + * A variable controlling whether the HIDAPI driver for PS5 controllers should + * be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS5 "SDL_JOYSTICK_HIDAPI_PS5" + +/** + * A variable controlling whether the player LEDs should be lit to indicate + * which player is associated with a PS5 controller. + * + * The variable can be set to the following values: + * + * - "0": player LEDs are not enabled. + * - "1": player LEDs are enabled. (default) + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED "SDL_JOYSTICK_HIDAPI_PS5_PLAYER_LED" + +/** + * A variable controlling whether the HIDAPI driver for NVIDIA SHIELD + * controllers should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_SHIELD "SDL_JOYSTICK_HIDAPI_SHIELD" + +/** + * A variable controlling whether the HIDAPI driver for Google Stadia + * controllers should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_STADIA "SDL_JOYSTICK_HIDAPI_STADIA" + +/** + * A variable controlling whether the HIDAPI driver for Bluetooth Steam + * Controllers should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. (default) + * - "1": HIDAPI driver is used for Steam Controllers, which requires + * Bluetooth access and may prompt the user for permission on iOS and + * Android. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_STEAM "SDL_JOYSTICK_HIDAPI_STEAM" + +/** + * A variable controlling whether the Steam button LED should be turned on + * when a Steam controller is opened. + * + * The variable can be set to the following values: + * + * - "0": Steam button LED is turned off. + * - "1": Steam button LED is turned on. + * + * By default the Steam button LED state is not changed. This hint can also be + * set to a floating point value between 0.0 and 1.0 which controls the + * brightness of the Steam button LED. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_STEAM_HOME_LED "SDL_JOYSTICK_HIDAPI_STEAM_HOME_LED" + +/** + * A variable controlling whether the HIDAPI driver for the Steam Deck builtin + * controller should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_STEAMDECK "SDL_JOYSTICK_HIDAPI_STEAMDECK" + +/** + * A variable controlling whether the HIDAPI driver for HORI licensed Steam + * controllers should be used. + * + * This variable can be set to the following values: "0" - HIDAPI driver is + * not used "1" - HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_STEAM_HORI "SDL_JOYSTICK_HIDAPI_STEAM_HORI" + +/** + * A variable controlling whether the HIDAPI driver for Nintendo Switch + * controllers should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_SWITCH "SDL_JOYSTICK_HIDAPI_SWITCH" + +/** + * A variable controlling whether the Home button LED should be turned on when + * a Nintendo Switch Pro controller is opened. + * + * The variable can be set to the following values: + * + * - "0": Home button LED is turned off. + * - "1": Home button LED is turned on. + * + * By default the Home button LED state is not changed. This hint can also be + * set to a floating point value between 0.0 and 1.0 which controls the + * brightness of the Home button LED. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_SWITCH_HOME_LED "SDL_JOYSTICK_HIDAPI_SWITCH_HOME_LED" + +/** + * A variable controlling whether the player LEDs should be lit to indicate + * which player is associated with a Nintendo Switch controller. + * + * The variable can be set to the following values: + * + * - "0": Player LEDs are not enabled. + * - "1": Player LEDs are enabled. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED "SDL_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED" + +/** + * A variable controlling whether Nintendo Switch Joy-Con controllers will be + * in vertical mode when using the HIDAPI driver. + * + * The variable can be set to the following values: + * + * - "0": Left and right Joy-Con controllers will not be in vertical mode. + * (default) + * - "1": Left and right Joy-Con controllers will be in vertical mode. + * + * This hint should be set before opening a Joy-Con controller. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_VERTICAL_JOY_CONS "SDL_JOYSTICK_HIDAPI_VERTICAL_JOY_CONS" + +/** + * A variable controlling whether the HIDAPI driver for Nintendo Wii and Wii U + * controllers should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * This driver doesn't work with the dolphinbar, so the default is false for + * now. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_WII "SDL_JOYSTICK_HIDAPI_WII" + +/** + * A variable controlling whether the player LEDs should be lit to indicate + * which player is associated with a Wii controller. + * + * The variable can be set to the following values: + * + * - "0": Player LEDs are not enabled. + * - "1": Player LEDs are enabled. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_WII_PLAYER_LED "SDL_JOYSTICK_HIDAPI_WII_PLAYER_LED" + +/** + * A variable controlling whether the HIDAPI driver for XBox controllers + * should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is "0" on Windows, otherwise the value of + * SDL_HINT_JOYSTICK_HIDAPI + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX "SDL_JOYSTICK_HIDAPI_XBOX" + +/** + * A variable controlling whether the HIDAPI driver for XBox 360 controllers + * should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI_XBOX + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_360 "SDL_JOYSTICK_HIDAPI_XBOX_360" + +/** + * A variable controlling whether the player LEDs should be lit to indicate + * which player is associated with an Xbox 360 controller. + * + * The variable can be set to the following values: + * + * - "0": Player LEDs are not enabled. + * - "1": Player LEDs are enabled. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_PLAYER_LED "SDL_JOYSTICK_HIDAPI_XBOX_360_PLAYER_LED" + +/** + * A variable controlling whether the HIDAPI driver for XBox 360 wireless + * controllers should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI_XBOX_360 + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_WIRELESS "SDL_JOYSTICK_HIDAPI_XBOX_360_WIRELESS" + +/** + * A variable controlling whether the HIDAPI driver for XBox One controllers + * should be used. + * + * The variable can be set to the following values: + * + * - "0": HIDAPI driver is not used. + * - "1": HIDAPI driver is used. + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI_XBOX. + * + * This hint should be set before initializing joysticks and gamepads. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE "SDL_JOYSTICK_HIDAPI_XBOX_ONE" + +/** + * A variable controlling whether the Home button LED should be turned on when + * an Xbox One controller is opened. + * + * The variable can be set to the following values: + * + * - "0": Home button LED is turned off. + * - "1": Home button LED is turned on. + * + * By default the Home button LED state is not changed. This hint can also be + * set to a floating point value between 0.0 and 1.0 which controls the + * brightness of the Home button LED. The default brightness is 0.4. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE_HOME_LED "SDL_JOYSTICK_HIDAPI_XBOX_ONE_HOME_LED" + +/** + * A variable controlling whether IOKit should be used for controller + * handling. + * + * The variable can be set to the following values: + * + * - "0": IOKit is not used. + * - "1": IOKit is used. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_IOKIT "SDL_JOYSTICK_IOKIT" + +/** + * A variable controlling whether to use the classic /dev/input/js* joystick + * interface or the newer /dev/input/event* joystick interface on Linux. + * + * The variable can be set to the following values: + * + * - "0": Use /dev/input/event* (default) + * - "1": Use /dev/input/js* + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_LINUX_CLASSIC "SDL_JOYSTICK_LINUX_CLASSIC" + +/** + * A variable controlling whether joysticks on Linux adhere to their + * HID-defined deadzones or return unfiltered values. + * + * The variable can be set to the following values: + * + * - "0": Return unfiltered joystick axis values. (default) + * - "1": Return axis values with deadzones taken into account. + * + * This hint should be set before a controller is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_LINUX_DEADZONES "SDL_JOYSTICK_LINUX_DEADZONES" + +/** + * A variable controlling whether joysticks on Linux will always treat 'hat' + * axis inputs (ABS_HAT0X - ABS_HAT3Y) as 8-way digital hats without checking + * whether they may be analog. + * + * The variable can be set to the following values: + * + * - "0": Only map hat axis inputs to digital hat outputs if the input axes + * appear to actually be digital. (default) + * - "1": Always handle the input axes numbered ABS_HAT0X to ABS_HAT3Y as + * digital hats. + * + * This hint should be set before a controller is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_LINUX_DIGITAL_HATS "SDL_JOYSTICK_LINUX_DIGITAL_HATS" + +/** + * A variable controlling whether digital hats on Linux will apply deadzones + * to their underlying input axes or use unfiltered values. + * + * The variable can be set to the following values: + * + * - "0": Return digital hat values based on unfiltered input axis values. + * - "1": Return digital hat values with deadzones on the input axes taken + * into account. (default) + * + * This hint should be set before a controller is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_LINUX_HAT_DEADZONES "SDL_JOYSTICK_LINUX_HAT_DEADZONES" + +/** + * A variable controlling whether GCController should be used for controller + * handling. + * + * The variable can be set to the following values: + * + * - "0": GCController is not used. + * - "1": GCController is used. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_MFI "SDL_JOYSTICK_MFI" + +/** + * A variable controlling whether the RAWINPUT joystick drivers should be used + * for better handling XInput-capable devices. + * + * The variable can be set to the following values: + * + * - "0": RAWINPUT drivers are not used. (default) + * - "1": RAWINPUT drivers are used. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_RAWINPUT "SDL_JOYSTICK_RAWINPUT" + +/** + * A variable controlling whether the RAWINPUT driver should pull correlated + * data from XInput. + * + * The variable can be set to the following values: + * + * - "0": RAWINPUT driver will only use data from raw input APIs. + * - "1": RAWINPUT driver will also pull data from XInput and + * Windows.Gaming.Input, providing better trigger axes, guide button + * presses, and rumble support for Xbox controllers. (default) + * + * This hint should be set before a gamepad is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT "SDL_JOYSTICK_RAWINPUT_CORRELATE_XINPUT" + +/** + * A variable controlling whether the ROG Chakram mice should show up as + * joysticks. + * + * The variable can be set to the following values: + * + * - "0": ROG Chakram mice do not show up as joysticks. (default) + * - "1": ROG Chakram mice show up as joysticks. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_ROG_CHAKRAM "SDL_JOYSTICK_ROG_CHAKRAM" + +/** + * A variable controlling whether a separate thread should be used for + * handling joystick detection and raw input messages on Windows. + * + * The variable can be set to the following values: + * + * - "0": A separate thread is not used. + * - "1": A separate thread is used for handling raw input messages. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_THREAD "SDL_JOYSTICK_THREAD" + +/** + * A variable containing a list of throttle style controllers. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_THROTTLE_DEVICES "SDL_JOYSTICK_THROTTLE_DEVICES" + +/** + * A variable containing a list of devices that are not throttle style + * controllers. + * + * This will override SDL_HINT_JOYSTICK_THROTTLE_DEVICES and the built in + * device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_THROTTLE_DEVICES_EXCLUDED "SDL_JOYSTICK_THROTTLE_DEVICES_EXCLUDED" + +/** + * A variable controlling whether Windows.Gaming.Input should be used for + * controller handling. + * + * The variable can be set to the following values: + * + * - "0": WGI is not used. + * - "1": WGI is used. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_WGI "SDL_JOYSTICK_WGI" + +/** + * A variable containing a list of wheel style controllers. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_WHEEL_DEVICES "SDL_JOYSTICK_WHEEL_DEVICES" + +/** + * A variable containing a list of devices that are not wheel style + * controllers. + * + * This will override SDL_HINT_JOYSTICK_WHEEL_DEVICES and the built in device + * list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_WHEEL_DEVICES_EXCLUDED "SDL_JOYSTICK_WHEEL_DEVICES_EXCLUDED" + +/** + * A variable containing a list of devices known to have all axes centered at + * zero. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint should be set before a controller is opened. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_JOYSTICK_ZERO_CENTERED_DEVICES "SDL_JOYSTICK_ZERO_CENTERED_DEVICES" + +/** + * A variable containing a list of devices and their desired number of haptic + * (force feedback) enabled axis. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form plus the number of desired axes, e.g. + * + * `0xAAAA/0xBBBB/1,0xCCCC/0xDDDD/3` + * + * This hint supports a "wildcard" device that will set the number of haptic + * axes on all initialized haptic devices which were not defined explicitly in + * this hint. + * + * `0xFFFF/0xFFFF/1` + * + * This hint should be set before a controller is opened. The number of haptic + * axes won't exceed the number of real axes found on the device. + * + * \since This hint is available since SDL 3.2.5. + */ +#define SDL_HINT_JOYSTICK_HAPTIC_AXES "SDL_JOYSTICK_HAPTIC_AXES" + +/** + * A variable that controls keycode representation in keyboard events. + * + * This variable is a comma separated set of options for translating keycodes + * in events: + * + * - "none": Keycode options are cleared, this overrides other options. + * - "hide_numpad": The numpad keysyms will be translated into their + * non-numpad versions based on the current NumLock state. For example, + * SDLK_KP_4 would become SDLK_4 if SDL_KMOD_NUM is set in the event + * modifiers, and SDLK_LEFT if it is unset. + * - "french_numbers": The number row on French keyboards is inverted, so + * pressing the 1 key would yield the keycode SDLK_1, or '1', instead of + * SDLK_AMPERSAND, or '&' + * - "latin_letters": For keyboards using non-Latin letters, such as Russian + * or Thai, the letter keys generate keycodes as though it had an en_US + * layout. e.g. pressing the key associated with SDL_SCANCODE_A on a Russian + * keyboard would yield 'a' instead of a Cyrillic letter. + * + * The default value for this hint is "french_numbers,latin_letters" + * + * Some platforms like Emscripten only provide modified keycodes and the + * options are not used. + * + * These options do not affect the return value of SDL_GetKeyFromScancode() or + * SDL_GetScancodeFromKey(), they just apply to the keycode included in key + * events. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_KEYCODE_OPTIONS "SDL_KEYCODE_OPTIONS" + +/** + * A variable that controls what KMSDRM device to use. + * + * SDL might open something like "/dev/dri/cardNN" to access KMSDRM + * functionality, where "NN" is a device index number. SDL makes a guess at + * the best index to use (usually zero), but the app or user can set this hint + * to a number between 0 and 99 to force selection. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_KMSDRM_DEVICE_INDEX "SDL_KMSDRM_DEVICE_INDEX" + +/** + * A variable that controls whether SDL requires DRM master access in order to + * initialize the KMSDRM video backend. + * + * The DRM subsystem has a concept of a "DRM master" which is a DRM client + * that has the ability to set planes, set cursor, etc. When SDL is DRM + * master, it can draw to the screen using the SDL rendering APIs. Without DRM + * master, SDL is still able to process input and query attributes of attached + * displays, but it cannot change display state or draw to the screen + * directly. + * + * In some cases, it can be useful to have the KMSDRM backend even if it + * cannot be used for rendering. An app may want to use SDL for input + * processing while using another rendering API (such as an MMAL overlay on + * Raspberry Pi) or using its own code to render to DRM overlays that SDL + * doesn't support. + * + * The variable can be set to the following values: + * + * - "0": SDL will allow usage of the KMSDRM backend without DRM master. + * - "1": SDL Will require DRM master to use the KMSDRM backend. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_KMSDRM_REQUIRE_DRM_MASTER "SDL_KMSDRM_REQUIRE_DRM_MASTER" + +/** + * A variable controlling the default SDL log levels. + * + * This variable is a comma separated set of category=level tokens that define + * the default logging levels for SDL applications. + * + * The category can be a numeric category, one of "app", "error", "assert", + * "system", "audio", "video", "render", "input", "test", or `*` for any + * unspecified category. + * + * The level can be a numeric level, one of "verbose", "debug", "info", + * "warn", "error", "critical", or "quiet" to disable that category. + * + * You can omit the category if you want to set the logging level for all + * categories. + * + * If this hint isn't set, the default log levels are equivalent to: + * + * `app=info,assert=warn,test=verbose,*=error` + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_LOGGING "SDL_LOGGING" + +/** + * A variable controlling whether to force the application to become the + * foreground process when launched on macOS. + * + * The variable can be set to the following values: + * + * - "0": The application is brought to the foreground when launched. + * (default) + * - "1": The application may remain in the background when launched. + * + * This hint needs to be set before SDL_Init(). + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MAC_BACKGROUND_APP "SDL_MAC_BACKGROUND_APP" + +/** + * A variable that determines whether Ctrl+Click should generate a right-click + * event on macOS. + * + * The variable can be set to the following values: + * + * - "0": Ctrl+Click does not generate a right mouse button click event. + * (default) + * - "1": Ctrl+Click generated a right mouse button click event. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK "SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK" + +/** + * A variable controlling whether dispatching OpenGL context updates should + * block the dispatching thread until the main thread finishes processing on + * macOS. + * + * The variable can be set to the following values: + * + * - "0": Dispatching OpenGL context updates will block the dispatching thread + * until the main thread finishes processing. (default) + * - "1": Dispatching OpenGL context updates will allow the dispatching thread + * to continue execution. + * + * Generally you want the default, but if you have OpenGL code in a background + * thread on a Mac, and the main thread hangs because it's waiting for that + * background thread, but that background thread is also hanging because it's + * waiting for the main thread to do an update, this might fix your issue. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MAC_OPENGL_ASYNC_DISPATCH "SDL_MAC_OPENGL_ASYNC_DISPATCH" + +/** + * A variable controlling whether the Option key on macOS should be remapped + * to act as the Alt key. + * + * The variable can be set to the following values: + * + * - "none": The Option key is not remapped to Alt. (default) + * - "only_left": Only the left Option key is remapped to Alt. + * - "only_right": Only the right Option key is remapped to Alt. + * - "both": Both Option keys are remapped to Alt. + * + * This will prevent the triggering of key compositions that rely on the + * Option key, but will still send the Alt modifier for keyboard events. In + * the case that both Alt and Option are pressed, the Option key will be + * ignored. This is particularly useful for applications like terminal + * emulators and graphical user interfaces (GUIs) that rely on Alt key + * functionality for shortcuts or navigation. This does not apply to + * SDL_GetKeyFromScancode and only has an effect if IME is enabled. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MAC_OPTION_AS_ALT "SDL_MAC_OPTION_AS_ALT" + +/** + * A variable controlling whether SDL_EVENT_MOUSE_WHEEL event values will have + * momentum on macOS. + * + * The variable can be set to the following values: + * + * - "0": The mouse wheel events will have no momentum. (default) + * - "1": The mouse wheel events will have momentum. + * + * This hint needs to be set before SDL_Init(). + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MAC_SCROLL_MOMENTUM "SDL_MAC_SCROLL_MOMENTUM" + +/** + * Request SDL_AppIterate() be called at a specific rate. + * + * If this is set to a number, it represents Hz, so "60" means try to iterate + * 60 times per second. "0" means to iterate as fast as possible. Negative + * values are illegal, but reserved, in case they are useful in a future + * revision of SDL. + * + * There are other strings that have special meaning. If set to "waitevent", + * SDL_AppIterate will not be called until new event(s) have arrived (and been + * processed by SDL_AppEvent). This can be useful for apps that are completely + * idle except in response to input. + * + * On some platforms, or if you are using SDL_main instead of SDL_AppIterate, + * this hint is ignored. When the hint can be used, it is allowed to be + * changed at any time. + * + * This defaults to 0, and specifying NULL for the hint's value will restore + * the default. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MAIN_CALLBACK_RATE "SDL_MAIN_CALLBACK_RATE" + +/** + * A variable controlling whether the mouse is captured while mouse buttons + * are pressed. + * + * The variable can be set to the following values: + * + * - "0": The mouse is not captured while mouse buttons are pressed. + * - "1": The mouse is captured while mouse buttons are pressed. + * + * By default the mouse is captured while mouse buttons are pressed so if the + * mouse is dragged outside the window, the application continues to receive + * mouse events until the button is released. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_AUTO_CAPTURE "SDL_MOUSE_AUTO_CAPTURE" + +/** + * A variable setting the double click radius, in pixels. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS "SDL_MOUSE_DOUBLE_CLICK_RADIUS" + +/** + * A variable setting the double click time, in milliseconds. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_DOUBLE_CLICK_TIME "SDL_MOUSE_DOUBLE_CLICK_TIME" + +/** + * A variable setting which system cursor to use as the default cursor. + * + * This should be an integer corresponding to the SDL_SystemCursor enum. The + * default value is zero (SDL_SYSTEM_CURSOR_DEFAULT). + * + * This hint needs to be set before SDL_Init(). + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_DEFAULT_SYSTEM_CURSOR "SDL_MOUSE_DEFAULT_SYSTEM_CURSOR" + +/** + * A variable controlling whether warping a hidden mouse cursor will activate + * relative mouse mode. + * + * When this hint is set, the mouse cursor is hidden, and multiple warps to + * the window center occur within a short time period, SDL will emulate mouse + * warps using relative mouse mode. This can provide smoother and more + * reliable mouse motion for some older games, which continuously calculate + * the distance travelled by the mouse pointer and warp it back to the center + * of the window, rather than using relative mouse motion. + * + * Note that relative mouse mode may have different mouse acceleration + * behavior than pointer warps. + * + * If your application needs to repeatedly warp the hidden mouse cursor at a + * high-frequency for other purposes, it should disable this hint. + * + * The variable can be set to the following values: + * + * - "0": Attempts to warp the mouse will always be made. + * - "1": Some mouse warps will be emulated by forcing relative mouse mode. + * (default) + * + * If not set, this is automatically enabled unless an application uses + * relative mouse mode directly. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_EMULATE_WARP_WITH_RELATIVE "SDL_MOUSE_EMULATE_WARP_WITH_RELATIVE" + +/** + * Allow mouse click events when clicking to focus an SDL window. + * + * The variable can be set to the following values: + * + * - "0": Ignore mouse clicks that activate a window. (default) + * - "1": Generate events for mouse clicks that activate a window. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH "SDL_MOUSE_FOCUS_CLICKTHROUGH" + +/** + * A variable setting the speed scale for mouse motion, in floating point, + * when the mouse is not in relative mode. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_NORMAL_SPEED_SCALE "SDL_MOUSE_NORMAL_SPEED_SCALE" + +/** + * A variable controlling whether relative mouse mode constrains the mouse to + * the center of the window. + * + * Constraining to the center of the window works better for FPS games and + * when the application is running over RDP. Constraining to the whole window + * works better for 2D games and increases the chance that the mouse will be + * in the correct position when using high DPI mice. + * + * The variable can be set to the following values: + * + * - "0": Relative mouse mode constrains the mouse to the window. + * - "1": Relative mouse mode constrains the mouse to the center of the + * window. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_RELATIVE_MODE_CENTER "SDL_MOUSE_RELATIVE_MODE_CENTER" + +/** + * A variable setting the scale for mouse motion, in floating point, when the + * mouse is in relative mode. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE "SDL_MOUSE_RELATIVE_SPEED_SCALE" + +/** + * A variable controlling whether the system mouse acceleration curve is used + * for relative mouse motion. + * + * The variable can be set to the following values: + * + * - "0": Relative mouse motion will be unscaled. (default) + * - "1": Relative mouse motion will be scaled using the system mouse + * acceleration curve. + * + * If SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE is set, that will be applied after + * system speed scale. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_RELATIVE_SYSTEM_SCALE "SDL_MOUSE_RELATIVE_SYSTEM_SCALE" + +/** + * A variable controlling whether a motion event should be generated for mouse + * warping in relative mode. + * + * The variable can be set to the following values: + * + * - "0": Warping the mouse will not generate a motion event in relative mode + * - "1": Warping the mouse will generate a motion event in relative mode + * + * By default warping the mouse will not generate motion events in relative + * mode. This avoids the application having to filter out large relative + * motion due to warping. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_RELATIVE_WARP_MOTION "SDL_MOUSE_RELATIVE_WARP_MOTION" + +/** + * A variable controlling whether the hardware cursor stays visible when + * relative mode is active. + * + * This variable can be set to the following values: + * + * - "0": The cursor will be hidden while relative mode is active (default) + * - "1": The cursor will remain visible while relative mode is active + * + * Note that for systems without raw hardware inputs, relative mode is + * implemented using warping, so the hardware cursor will visibly warp between + * frames if this is enabled on those systems. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_RELATIVE_CURSOR_VISIBLE "SDL_MOUSE_RELATIVE_CURSOR_VISIBLE" + +/** + * A variable controlling whether mouse events should generate synthetic touch + * events. + * + * The variable can be set to the following values: + * + * - "0": Mouse events will not generate touch events. (default for desktop + * platforms) + * - "1": Mouse events will generate touch events. (default for mobile + * platforms, such as Android and iOS) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MOUSE_TOUCH_EVENTS "SDL_MOUSE_TOUCH_EVENTS" + +/** + * A variable controlling whether the keyboard should be muted on the console. + * + * Normally the keyboard is muted while SDL applications are running so that + * keyboard input doesn't show up as key strokes on the console. This hint + * allows you to turn that off for debugging purposes. + * + * The variable can be set to the following values: + * + * - "0": Allow keystrokes to go through to the console. + * - "1": Mute keyboard input so it doesn't show up on the console. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_MUTE_CONSOLE_KEYBOARD "SDL_MUTE_CONSOLE_KEYBOARD" + +/** + * Tell SDL not to catch the SIGINT or SIGTERM signals on POSIX platforms. + * + * The variable can be set to the following values: + * + * - "0": SDL will install a SIGINT and SIGTERM handler, and when it catches a + * signal, convert it into an SDL_EVENT_QUIT event. (default) + * - "1": SDL will not install a signal handler at all. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_NO_SIGNAL_HANDLERS "SDL_NO_SIGNAL_HANDLERS" + +/** + * Specify the OpenGL library to load. + * + * This hint should be set before creating an OpenGL window or creating an + * OpenGL context. If this hint isn't set, SDL will choose a reasonable + * default. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_OPENGL_LIBRARY "SDL_OPENGL_LIBRARY" + +/** + * Specify the EGL library to load. + * + * This hint should be set before creating an OpenGL window or creating an + * OpenGL context. This hint is only considered if SDL is using EGL to manage + * OpenGL contexts. If this hint isn't set, SDL will choose a reasonable + * default. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_EGL_LIBRARY "SDL_EGL_LIBRARY" + +/** + * A variable controlling what driver to use for OpenGL ES contexts. + * + * On some platforms, currently Windows and X11, OpenGL drivers may support + * creating contexts with an OpenGL ES profile. By default SDL uses these + * profiles, when available, otherwise it attempts to load an OpenGL ES + * library, e.g. that provided by the ANGLE project. This variable controls + * whether SDL follows this default behaviour or will always load an OpenGL ES + * library. + * + * Circumstances where this is useful include - Testing an app with a + * particular OpenGL ES implementation, e.g ANGLE, or emulator, e.g. those + * from ARM, Imagination or Qualcomm. - Resolving OpenGL ES function addresses + * at link time by linking with the OpenGL ES library instead of querying them + * at run time with SDL_GL_GetProcAddress(). + * + * Caution: for an application to work with the default behaviour across + * different OpenGL drivers it must query the OpenGL ES function addresses at + * run time using SDL_GL_GetProcAddress(). + * + * This variable is ignored on most platforms because OpenGL ES is native or + * not supported. + * + * The variable can be set to the following values: + * + * - "0": Use ES profile of OpenGL, if available. (default) + * - "1": Load OpenGL ES library using the default library names. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_OPENGL_ES_DRIVER "SDL_OPENGL_ES_DRIVER" + +/** + * Mechanism to specify openvr_api library location + * + * By default, when using the OpenVR driver, it will search for the API + * library in the current folder. But, if you wish to use a system API you can + * specify that by using this hint. This should be the full or relative path + * to a .dll on Windows or .so on Linux. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_OPENVR_LIBRARY "SDL_OPENVR_LIBRARY" + +/** + * A variable controlling which orientations are allowed on iOS/Android. + * + * In some circumstances it is necessary to be able to explicitly control + * which UI orientations are allowed. + * + * This variable is a space delimited list of the following values: + * + * - "LandscapeLeft" + * - "LandscapeRight" + * - "Portrait" + * - "PortraitUpsideDown" + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_ORIENTATIONS "SDL_ORIENTATIONS" + +/** + * A variable controlling the use of a sentinel event when polling the event + * queue. + * + * When polling for events, SDL_PumpEvents is used to gather new events from + * devices. If a device keeps producing new events between calls to + * SDL_PumpEvents, a poll loop will become stuck until the new events stop. + * This is most noticeable when moving a high frequency mouse. + * + * The variable can be set to the following values: + * + * - "0": Disable poll sentinels. + * - "1": Enable poll sentinels. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_POLL_SENTINEL "SDL_POLL_SENTINEL" + +/** + * Override for SDL_GetPreferredLocales(). + * + * If set, this will be favored over anything the OS might report for the + * user's preferred locales. Changing this hint at runtime will not generate a + * SDL_EVENT_LOCALE_CHANGED event (but if you can change the hint, you can + * push your own event, if you want). + * + * The format of this hint is a comma-separated list of language and locale, + * combined with an underscore, as is a common format: "en_GB". Locale is + * optional: "en". So you might have a list like this: "en_GB,jp,es_PT" + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_PREFERRED_LOCALES "SDL_PREFERRED_LOCALES" + +/** + * A variable that decides whether to send SDL_EVENT_QUIT when closing the + * last window. + * + * The variable can be set to the following values: + * + * - "0": SDL will not send an SDL_EVENT_QUIT event when the last window is + * requesting to close. Note that in this case, there are still other + * legitimate reasons one might get an SDL_EVENT_QUIT event: choosing "Quit" + * from the macOS menu bar, sending a SIGINT (ctrl-c) on Unix, etc. + * - "1": SDL will send a quit event when the last window is requesting to + * close. (default) + * + * If there is at least one active system tray icon, SDL_EVENT_QUIT will + * instead be sent when both the last window will be closed and the last tray + * icon will be destroyed. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE "SDL_QUIT_ON_LAST_WINDOW_CLOSE" + +/** + * A variable controlling whether the Direct3D device is initialized for + * thread-safe operations. + * + * The variable can be set to the following values: + * + * - "0": Thread-safety is not enabled. (default) + * - "1": Thread-safety is enabled. + * + * This hint should be set before creating a renderer. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RENDER_DIRECT3D_THREADSAFE "SDL_RENDER_DIRECT3D_THREADSAFE" + +/** + * A variable controlling whether to enable Direct3D 11+'s Debug Layer. + * + * This variable does not have any effect on the Direct3D 9 based renderer. + * + * The variable can be set to the following values: + * + * - "0": Disable Debug Layer use. (default) + * - "1": Enable Debug Layer use. + * + * This hint should be set before creating a renderer. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RENDER_DIRECT3D11_DEBUG "SDL_RENDER_DIRECT3D11_DEBUG" + +/** + * A variable controlling whether to enable Vulkan Validation Layers. + * + * This variable can be set to the following values: + * + * - "0": Disable Validation Layer use + * - "1": Enable Validation Layer use + * + * By default, SDL does not use Vulkan Validation Layers. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RENDER_VULKAN_DEBUG "SDL_RENDER_VULKAN_DEBUG" + +/** + * A variable controlling whether to create the GPU device in debug mode. + * + * This variable can be set to the following values: + * + * - "0": Disable debug mode use (default) + * - "1": Enable debug mode use + * + * This hint should be set before creating a renderer. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RENDER_GPU_DEBUG "SDL_RENDER_GPU_DEBUG" + +/** + * A variable controlling whether to prefer a low-power GPU on multi-GPU + * systems. + * + * This variable can be set to the following values: + * + * - "0": Prefer high-performance GPU (default) + * - "1": Prefer low-power GPU + * + * This hint should be set before creating a renderer. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RENDER_GPU_LOW_POWER "SDL_RENDER_GPU_LOW_POWER" + +/** + * A variable specifying which render driver to use. + * + * If the application doesn't pick a specific renderer to use, this variable + * specifies the name of the preferred renderer. If the preferred renderer + * can't be initialized, creating a renderer will fail. + * + * This variable is case insensitive and can be set to the following values: + * + * - "direct3d" + * - "direct3d11" + * - "direct3d12" + * - "opengl" + * - "opengles2" + * - "opengles" + * - "metal" + * - "vulkan" + * - "gpu" + * - "software" + * + * This hint accepts a comma-separated list of driver names, and each will be + * tried in the order listed when creating a renderer until one succeeds or + * all of them fail. + * + * The default varies by platform, but it's the first one in the list that is + * available on the current platform. + * + * This hint should be set before creating a renderer. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RENDER_DRIVER "SDL_RENDER_DRIVER" + +/** + * A variable controlling how the 2D render API renders lines. + * + * The variable can be set to the following values: + * + * - "0": Use the default line drawing method (Bresenham's line algorithm) + * - "1": Use the driver point API using Bresenham's line algorithm (correct, + * draws many points) + * - "2": Use the driver line API (occasionally misses line endpoints based on + * hardware driver quirks + * - "3": Use the driver geometry API (correct, draws thicker diagonal lines) + * + * This hint should be set before creating a renderer. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RENDER_LINE_METHOD "SDL_RENDER_LINE_METHOD" + +/** + * A variable controlling whether the Metal render driver select low power + * device over default one. + * + * The variable can be set to the following values: + * + * - "0": Use the preferred OS device. (default) + * - "1": Select a low power device. + * + * This hint should be set before creating a renderer. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RENDER_METAL_PREFER_LOW_POWER_DEVICE "SDL_RENDER_METAL_PREFER_LOW_POWER_DEVICE" + +/** + * A variable controlling whether updates to the SDL screen surface should be + * synchronized with the vertical refresh, to avoid tearing. + * + * This hint overrides the application preference when creating a renderer. + * + * The variable can be set to the following values: + * + * - "0": Disable vsync. (default) + * - "1": Enable vsync. + * + * This hint should be set before creating a renderer. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RENDER_VSYNC "SDL_RENDER_VSYNC" + +/** + * A variable to control whether the return key on the soft keyboard should + * hide the soft keyboard on Android and iOS. + * + * This hint sets the default value of SDL_PROP_TEXTINPUT_MULTILINE_BOOLEAN. + * + * The variable can be set to the following values: + * + * - "0": The return key will be handled as a key event. (default) + * - "1": The return key will hide the keyboard. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RETURN_KEY_HIDES_IME "SDL_RETURN_KEY_HIDES_IME" + +/** + * A variable containing a list of ROG gamepad capable mice. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + * + * \sa SDL_HINT_ROG_GAMEPAD_MICE_EXCLUDED + */ +#define SDL_HINT_ROG_GAMEPAD_MICE "SDL_ROG_GAMEPAD_MICE" + +/** + * A variable containing a list of devices that are not ROG gamepad capable + * mice. + * + * This will override SDL_HINT_ROG_GAMEPAD_MICE and the built in device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * `0xAAAA/0xBBBB,0xCCCC/0xDDDD` + * + * The variable can also take the form of "@file", in which case the named + * file will be loaded and interpreted as the value of the variable. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_ROG_GAMEPAD_MICE_EXCLUDED "SDL_ROG_GAMEPAD_MICE_EXCLUDED" + +/** + * A variable controlling which Dispmanx layer to use on a Raspberry PI. + * + * Also known as Z-order. The variable can take a negative or positive value. + * The default is 10000. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_RPI_VIDEO_LAYER "SDL_RPI_VIDEO_LAYER" + +/** + * Specify an "activity name" for screensaver inhibition. + * + * Some platforms, notably Linux desktops, list the applications which are + * inhibiting the screensaver or other power-saving features. + * + * This hint lets you specify the "activity name" sent to the OS when + * SDL_DisableScreenSaver() is used (or the screensaver is automatically + * disabled). The contents of this hint are used when the screensaver is + * disabled. You should use a string that describes what your program is doing + * (and, therefore, why the screensaver is disabled). For example, "Playing a + * game" or "Watching a video". + * + * Setting this to "" or leaving it unset will have SDL use a reasonable + * default: "Playing a game" or something similar. + * + * This hint should be set before calling SDL_DisableScreenSaver() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME "SDL_SCREENSAVER_INHIBIT_ACTIVITY_NAME" + +/** + * A variable controlling whether SDL calls dbus_shutdown() on quit. + * + * This is useful as a debug tool to validate memory leaks, but shouldn't ever + * be set in production applications, as other libraries used by the + * application might use dbus under the hood and this can cause crashes if + * they continue after SDL_Quit(). + * + * The variable can be set to the following values: + * + * - "0": SDL will not call dbus_shutdown() on quit. (default) + * - "1": SDL will call dbus_shutdown() on quit. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_SHUTDOWN_DBUS_ON_QUIT "SDL_SHUTDOWN_DBUS_ON_QUIT" + +/** + * A variable that specifies a backend to use for title storage. + * + * By default, SDL will try all available storage backends in a reasonable + * order until it finds one that can work, but this hint allows the app or + * user to force a specific target, such as "pc" if, say, you are on Steam but + * want to avoid SteamRemoteStorage for title data. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_STORAGE_TITLE_DRIVER "SDL_STORAGE_TITLE_DRIVER" + +/** + * A variable that specifies a backend to use for user storage. + * + * By default, SDL will try all available storage backends in a reasonable + * order until it finds one that can work, but this hint allows the app or + * user to force a specific target, such as "pc" if, say, you are on Steam but + * want to avoid SteamRemoteStorage for user data. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_STORAGE_USER_DRIVER "SDL_STORAGE_USER_DRIVER" + +/** + * Specifies whether SDL_THREAD_PRIORITY_TIME_CRITICAL should be treated as + * realtime. + * + * On some platforms, like Linux, a realtime priority thread may be subject to + * restrictions that require special handling by the application. This hint + * exists to let SDL know that the app is prepared to handle said + * restrictions. + * + * On Linux, SDL will apply the following configuration to any thread that + * becomes realtime: + * + * - The SCHED_RESET_ON_FORK bit will be set on the scheduling policy, + * - An RLIMIT_RTTIME budget will be configured to the rtkit specified limit. + * - Exceeding this limit will result in the kernel sending SIGKILL to the + * app, refer to the man pages for more information. + * + * The variable can be set to the following values: + * + * - "0": default platform specific behaviour + * - "1": Force SDL_THREAD_PRIORITY_TIME_CRITICAL to a realtime scheduling + * policy + * + * This hint should be set before calling SDL_SetCurrentThreadPriority() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL "SDL_THREAD_FORCE_REALTIME_TIME_CRITICAL" + +/** + * A string specifying additional information to use with + * SDL_SetCurrentThreadPriority. + * + * By default SDL_SetCurrentThreadPriority will make appropriate system + * changes in order to apply a thread priority. For example on systems using + * pthreads the scheduler policy is changed automatically to a policy that + * works well with a given priority. Code which has specific requirements can + * override SDL's default behavior with this hint. + * + * pthread hint values are "current", "other", "fifo" and "rr". Currently no + * other platform hint values are defined but may be in the future. + * + * On Linux, the kernel may send SIGKILL to realtime tasks which exceed the + * distro configured execution budget for rtkit. This budget can be queried + * through RLIMIT_RTTIME after calling SDL_SetCurrentThreadPriority(). + * + * This hint should be set before calling SDL_SetCurrentThreadPriority() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_THREAD_PRIORITY_POLICY "SDL_THREAD_PRIORITY_POLICY" + +/** + * A variable that controls the timer resolution, in milliseconds. + * + * The higher resolution the timer, the more frequently the CPU services timer + * interrupts, and the more precise delays are, but this takes up power and + * CPU time. This hint is only used on Windows. + * + * See this blog post for more information: + * http://randomascii.wordpress.com/2013/07/08/windows-timer-resolution-megawatts-wasted/ + * + * The default value is "1". + * + * If this variable is set to "0", the system timer resolution is not set. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_TIMER_RESOLUTION "SDL_TIMER_RESOLUTION" + +/** + * A variable controlling whether touch events should generate synthetic mouse + * events. + * + * The variable can be set to the following values: + * + * - "0": Touch events will not generate mouse events. + * - "1": Touch events will generate mouse events. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_TOUCH_MOUSE_EVENTS "SDL_TOUCH_MOUSE_EVENTS" + +/** + * A variable controlling whether trackpads should be treated as touch + * devices. + * + * On macOS (and possibly other platforms in the future), SDL will report + * touches on a trackpad as mouse input, which is generally what users expect + * from this device; however, these are often actually full multitouch-capable + * touch devices, so it might be preferable to some apps to treat them as + * such. + * + * The variable can be set to the following values: + * + * - "0": Trackpad will send mouse events. (default) + * - "1": Trackpad will send touch events. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_TRACKPAD_IS_TOUCH_ONLY "SDL_TRACKPAD_IS_TOUCH_ONLY" + +/** + * A variable controlling whether the Android / tvOS remotes should be listed + * as joystick devices, instead of sending keyboard events. + * + * The variable can be set to the following values: + * + * - "0": Remotes send enter/escape/arrow key events. + * - "1": Remotes are available as 2 axis, 2 button joysticks. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_TV_REMOTE_AS_JOYSTICK "SDL_TV_REMOTE_AS_JOYSTICK" + +/** + * A variable controlling whether the screensaver is enabled. + * + * The variable can be set to the following values: + * + * - "0": Disable screensaver. (default) + * - "1": Enable screensaver. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_ALLOW_SCREENSAVER "SDL_VIDEO_ALLOW_SCREENSAVER" + +/** + * A comma separated list containing the names of the displays that SDL should + * sort to the front of the display list. + * + * When this hint is set, displays with matching name strings will be + * prioritized in the list of displays, as exposed by calling + * SDL_GetDisplays(), with the first listed becoming the primary display. The + * naming convention can vary depending on the environment, but it is usually + * a connector name (e.g. 'DP-1', 'DP-2', 'HDMI-A-1',etc...). + * + * On Wayland and X11 desktops, the connector names associated with displays + * can typically be found by using the `xrandr` utility. + * + * This hint is currently supported on the following drivers: + * + * - KMSDRM (kmsdrm) + * - Wayland (wayland) + * - X11 (x11) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_DISPLAY_PRIORITY "SDL_VIDEO_DISPLAY_PRIORITY" + +/** + * Tell the video driver that we only want a double buffer. + * + * By default, most lowlevel 2D APIs will use a triple buffer scheme that + * wastes no CPU time on waiting for vsync after issuing a flip, but + * introduces a frame of latency. On the other hand, using a double buffer + * scheme instead is recommended for cases where low latency is an important + * factor because we save a whole frame of latency. + * + * We do so by waiting for vsync immediately after issuing a flip, usually + * just after eglSwapBuffers call in the backend's *_SwapWindow function. + * + * This hint is currently supported on the following drivers: + * + * - Raspberry Pi (raspberrypi) + * - Wayland (wayland) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_DOUBLE_BUFFER "SDL_VIDEO_DOUBLE_BUFFER" + +/** + * A variable that specifies a video backend to use. + * + * By default, SDL will try all available video backends in a reasonable order + * until it finds one that can work, but this hint allows the app or user to + * force a specific target, such as "x11" if, say, you are on Wayland but want + * to try talking to the X server instead. + * + * This hint accepts a comma-separated list of driver names, and each will be + * tried in the order listed during init, until one succeeds or all of them + * fail. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_DRIVER "SDL_VIDEO_DRIVER" + +/** + * A variable controlling whether the dummy video driver saves output frames. + * + * - "0": Video frames are not saved to disk. (default) + * - "1": Video frames are saved to files in the format "SDL_windowX-Y.bmp", + * where X is the window ID, and Y is the frame number. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_DUMMY_SAVE_FRAMES "SDL_VIDEO_DUMMY_SAVE_FRAMES" + +/** + * If eglGetPlatformDisplay fails, fall back to calling eglGetDisplay. + * + * The variable can be set to one of the following values: + * + * - "0": Do not fall back to eglGetDisplay. + * - "1": Fall back to eglGetDisplay if eglGetPlatformDisplay fails. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_EGL_ALLOW_GETDISPLAY_FALLBACK "SDL_VIDEO_EGL_ALLOW_GETDISPLAY_FALLBACK" + +/** + * A variable controlling whether the OpenGL context should be created with + * EGL. + * + * The variable can be set to the following values: + * + * - "0": Use platform-specific GL context creation API (GLX, WGL, CGL, etc). + * (default) + * - "1": Use EGL + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_FORCE_EGL "SDL_VIDEO_FORCE_EGL" + +/** + * A variable that specifies the policy for fullscreen Spaces on macOS. + * + * The variable can be set to the following values: + * + * - "0": Disable Spaces support (FULLSCREEN_DESKTOP won't use them and + * SDL_WINDOW_RESIZABLE windows won't offer the "fullscreen" button on their + * titlebars). + * - "1": Enable Spaces support (FULLSCREEN_DESKTOP will use them and + * SDL_WINDOW_RESIZABLE windows will offer the "fullscreen" button on their + * titlebars). (default) + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES "SDL_VIDEO_MAC_FULLSCREEN_SPACES" + +/** + * A variable that specifies the menu visibility when a window is fullscreen + * in Spaces on macOS. + * + * The variable can be set to the following values: + * + * - "0": The menu will be hidden when the window is in a fullscreen space, + * and not accessible by moving the mouse to the top of the screen. + * - "1": The menu will be accessible when the window is in a fullscreen + * space. + * - "auto": The menu will be hidden if fullscreen mode was toggled on + * programmatically via `SDL_SetWindowFullscreen()`, and accessible if + * fullscreen was entered via the "fullscreen" button on the window title + * bar. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_MAC_FULLSCREEN_MENU_VISIBILITY "SDL_VIDEO_MAC_FULLSCREEN_MENU_VISIBILITY" + +/** + * A variable controlling whether fullscreen windows are minimized when they + * lose focus. + * + * The variable can be set to the following values: + * + * - "0": Fullscreen windows will not be minimized when they lose focus. + * (default) + * - "1": Fullscreen windows are minimized when they lose focus. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS "SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS" + +/** + * A variable controlling whether the offscreen video driver saves output + * frames. + * + * This only saves frames that are generated using software rendering, not + * accelerated OpenGL rendering. + * + * - "0": Video frames are not saved to disk. (default) + * - "1": Video frames are saved to files in the format "SDL_windowX-Y.bmp", + * where X is the window ID, and Y is the frame number. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_OFFSCREEN_SAVE_FRAMES "SDL_VIDEO_OFFSCREEN_SAVE_FRAMES" + +/** + * A variable controlling whether all window operations will block until + * complete. + * + * Window systems that run asynchronously may not have the results of window + * operations that resize or move the window applied immediately upon the + * return of the requesting function. Setting this hint will cause such + * operations to block after every call until the pending operation has + * completed. Setting this to '1' is the equivalent of calling + * SDL_SyncWindow() after every function call. + * + * Be aware that amount of time spent blocking while waiting for window + * operations to complete can be quite lengthy, as animations may have to + * complete, which can take upwards of multiple seconds in some cases. + * + * The variable can be set to the following values: + * + * - "0": Window operations are non-blocking. (default) + * - "1": Window operations will block until completed. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_SYNC_WINDOW_OPERATIONS "SDL_VIDEO_SYNC_WINDOW_OPERATIONS" + +/** + * A variable controlling whether the libdecor Wayland backend is allowed to + * be used. + * + * libdecor is used over xdg-shell when xdg-decoration protocol is + * unavailable. + * + * The variable can be set to the following values: + * + * - "0": libdecor use is disabled. + * - "1": libdecor use is enabled. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_WAYLAND_ALLOW_LIBDECOR "SDL_VIDEO_WAYLAND_ALLOW_LIBDECOR" + +/** + * A variable controlling whether video mode emulation is enabled under + * Wayland. + * + * When this hint is set, a standard set of emulated CVT video modes will be + * exposed for use by the application. If it is disabled, the only modes + * exposed will be the logical desktop size and, in the case of a scaled + * desktop, the native display resolution. + * + * The variable can be set to the following values: + * + * - "0": Video mode emulation is disabled. + * - "1": Video mode emulation is enabled. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_WAYLAND_MODE_EMULATION "SDL_VIDEO_WAYLAND_MODE_EMULATION" + +/** + * A variable controlling how modes with a non-native aspect ratio are + * displayed under Wayland. + * + * When this hint is set, the requested scaling will be used when displaying + * fullscreen video modes that don't match the display's native aspect ratio. + * This is contingent on compositor viewport support. + * + * The variable can be set to the following values: + * + * - "aspect" - Video modes will be displayed scaled, in their proper aspect + * ratio, with black bars. + * - "stretch" - Video modes will be scaled to fill the entire display. + * (default) + * - "none" - Video modes will be displayed as 1:1 with no scaling. + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_WAYLAND_MODE_SCALING "SDL_VIDEO_WAYLAND_MODE_SCALING" + +/** + * A variable controlling whether the libdecor Wayland backend is preferred + * over native decorations. + * + * When this hint is set, libdecor will be used to provide window decorations, + * even if xdg-decoration is available. (Note that, by default, libdecor will + * use xdg-decoration itself if available). + * + * The variable can be set to the following values: + * + * - "0": libdecor is enabled only if server-side decorations are unavailable. + * (default) + * - "1": libdecor is always enabled if available. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_WAYLAND_PREFER_LIBDECOR "SDL_VIDEO_WAYLAND_PREFER_LIBDECOR" + +/** + * A variable forcing non-DPI-aware Wayland windows to output at 1:1 scaling. + * + * This must be set before initializing the video subsystem. + * + * When this hint is set, Wayland windows that are not flagged as being + * DPI-aware will be output with scaling designed to force 1:1 pixel mapping. + * + * This is intended to allow legacy applications to be displayed without + * desktop scaling being applied, and has issues with certain display + * configurations, as this forces the window to behave in a way that Wayland + * desktops were not designed to accommodate: + * + * - Rounding errors can result with odd window sizes and/or desktop scales, + * which can cause the window contents to appear slightly blurry. + * - Positioning the window may be imprecise due to unit conversions and + * rounding. + * - The window may be unusably small on scaled desktops. + * - The window may jump in size when moving between displays of different + * scale factors. + * - Displays may appear to overlap when using a multi-monitor setup with + * scaling enabled. + * - Possible loss of cursor precision due to the logical size of the window + * being reduced. + * + * New applications should be designed with proper DPI awareness handling + * instead of enabling this. + * + * The variable can be set to the following values: + * + * - "0": Windows will be scaled normally. + * - "1": Windows will be forced to scale to achieve 1:1 output. + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_WAYLAND_SCALE_TO_DISPLAY "SDL_VIDEO_WAYLAND_SCALE_TO_DISPLAY" + +/** + * A variable specifying which shader compiler to preload when using the + * Chrome ANGLE binaries. + * + * SDL has EGL and OpenGL ES2 support on Windows via the ANGLE project. It can + * use two different sets of binaries, those compiled by the user from source + * or those provided by the Chrome browser. In the later case, these binaries + * require that SDL loads a DLL providing the shader compiler. + * + * The variable can be set to the following values: + * + * - "d3dcompiler_46.dll" - best for Vista or later. (default) + * - "d3dcompiler_43.dll" - for XP support. + * - "none" - do not load any library, useful if you compiled ANGLE from + * source and included the compiler in your binaries. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_WIN_D3DCOMPILER "SDL_VIDEO_WIN_D3DCOMPILER" + +/** + * A variable controlling whether SDL should call XSelectInput() to enable + * input events on X11 windows wrapped by SDL windows. + * + * The variable can be set to the following values: + * + * - "0": Don't call XSelectInput(), assuming the native window code has done + * it already. + * - "1": Call XSelectInput() to enable input events. (default) + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.10. + */ +#define SDL_HINT_VIDEO_X11_EXTERNAL_WINDOW_INPUT "SDL_VIDEO_X11_EXTERNAL_WINDOW_INPUT" + +/** + * A variable controlling whether the X11 _NET_WM_BYPASS_COMPOSITOR hint + * should be used. + * + * The variable can be set to the following values: + * + * - "0": Disable _NET_WM_BYPASS_COMPOSITOR. + * - "1": Enable _NET_WM_BYPASS_COMPOSITOR. (default) + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR "SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR" + +/** + * A variable controlling whether the X11 _NET_WM_PING protocol should be + * supported. + * + * By default SDL will use _NET_WM_PING, but for applications that know they + * will not always be able to respond to ping requests in a timely manner they + * can turn it off to avoid the window manager thinking the app is hung. + * + * The variable can be set to the following values: + * + * - "0": Disable _NET_WM_PING. + * - "1": Enable _NET_WM_PING. (default) + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_X11_NET_WM_PING "SDL_VIDEO_X11_NET_WM_PING" + +/** + * A variable controlling whether SDL uses DirectColor visuals. + * + * The variable can be set to the following values: + * + * - "0": Disable DirectColor visuals. + * - "1": Enable DirectColor visuals. (default) + * + * This hint should be set before initializing the video subsystem. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_X11_NODIRECTCOLOR "SDL_VIDEO_X11_NODIRECTCOLOR" + +/** + * A variable forcing the content scaling factor for X11 displays. + * + * The variable can be set to a floating point value in the range 1.0-10.0f + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_X11_SCALING_FACTOR "SDL_VIDEO_X11_SCALING_FACTOR" + +/** + * A variable forcing the visual ID used for X11 display modes. + * + * This hint should be set before initializing the video subsystem. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_X11_VISUALID "SDL_VIDEO_X11_VISUALID" + +/** + * A variable forcing the visual ID chosen for new X11 windows. + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_X11_WINDOW_VISUALID "SDL_VIDEO_X11_WINDOW_VISUALID" + +/** + * A variable controlling whether the X11 XRandR extension should be used. + * + * The variable can be set to the following values: + * + * - "0": Disable XRandR. + * - "1": Enable XRandR. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VIDEO_X11_XRANDR "SDL_VIDEO_X11_XRANDR" + +/** + * A variable controlling whether touch should be enabled on the back panel of + * the PlayStation Vita. + * + * The variable can be set to the following values: + * + * - "0": Disable touch on the back panel. + * - "1": Enable touch on the back panel. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VITA_ENABLE_BACK_TOUCH "SDL_VITA_ENABLE_BACK_TOUCH" + +/** + * A variable controlling whether touch should be enabled on the front panel + * of the PlayStation Vita. + * + * The variable can be set to the following values: + * + * - "0": Disable touch on the front panel. + * - "1": Enable touch on the front panel. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VITA_ENABLE_FRONT_TOUCH "SDL_VITA_ENABLE_FRONT_TOUCH" + +/** + * A variable controlling the module path on the PlayStation Vita. + * + * This hint defaults to "app0:module" + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VITA_MODULE_PATH "SDL_VITA_MODULE_PATH" + +/** + * A variable controlling whether to perform PVR initialization on the + * PlayStation Vita. + * + * - "0": Skip PVR initialization. + * - "1": Perform the normal PVR initialization. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VITA_PVR_INIT "SDL_VITA_PVR_INIT" + +/** + * A variable overriding the resolution reported on the PlayStation Vita. + * + * The variable can be set to the following values: + * + * - "544": 544p (default) + * - "720": 725p for PSTV + * - "1080": 1088i for PSTV + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VITA_RESOLUTION "SDL_VITA_RESOLUTION" + +/** + * A variable controlling whether OpenGL should be used instead of OpenGL ES + * on the PlayStation Vita. + * + * The variable can be set to the following values: + * + * - "0": Use OpenGL ES. (default) + * - "1": Use OpenGL. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VITA_PVR_OPENGL "SDL_VITA_PVR_OPENGL" + +/** + * A variable controlling which touchpad should generate synthetic mouse + * events. + * + * The variable can be set to the following values: + * + * - "0": Only front touchpad should generate mouse events. (default) + * - "1": Only back touchpad should generate mouse events. + * - "2": Both touchpads should generate mouse events. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VITA_TOUCH_MOUSE_DEVICE "SDL_VITA_TOUCH_MOUSE_DEVICE" + +/** + * A variable overriding the display index used in SDL_Vulkan_CreateSurface() + * + * The display index starts at 0, which is the default. + * + * This hint should be set before calling SDL_Vulkan_CreateSurface() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VULKAN_DISPLAY "SDL_VULKAN_DISPLAY" + +/** + * Specify the Vulkan library to load. + * + * This hint should be set before creating a Vulkan window or calling + * SDL_Vulkan_LoadLibrary(). + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_VULKAN_LIBRARY "SDL_VULKAN_LIBRARY" + +/** + * A variable controlling how the fact chunk affects the loading of a WAVE + * file. + * + * The fact chunk stores information about the number of samples of a WAVE + * file. The Standards Update from Microsoft notes that this value can be used + * to 'determine the length of the data in seconds'. This is especially useful + * for compressed formats (for which this is a mandatory chunk) if they + * produce multiple sample frames per block and truncating the block is not + * allowed. The fact chunk can exactly specify how many sample frames there + * should be in this case. + * + * Unfortunately, most application seem to ignore the fact chunk and so SDL + * ignores it by default as well. + * + * The variable can be set to the following values: + * + * - "truncate" - Use the number of samples to truncate the wave data if the + * fact chunk is present and valid. + * - "strict" - Like "truncate", but raise an error if the fact chunk is + * invalid, not present for non-PCM formats, or if the data chunk doesn't + * have that many samples. + * - "ignorezero" - Like "truncate", but ignore fact chunk if the number of + * samples is zero. + * - "ignore" - Ignore fact chunk entirely. (default) + * + * This hint should be set before calling SDL_LoadWAV() or SDL_LoadWAV_IO() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WAVE_FACT_CHUNK "SDL_WAVE_FACT_CHUNK" + +/** + * A variable controlling the maximum number of chunks in a WAVE file. + * + * This sets an upper bound on the number of chunks in a WAVE file to avoid + * wasting time on malformed or corrupt WAVE files. This defaults to "10000". + * + * This hint should be set before calling SDL_LoadWAV() or SDL_LoadWAV_IO() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WAVE_CHUNK_LIMIT "SDL_WAVE_CHUNK_LIMIT" + +/** + * A variable controlling how the size of the RIFF chunk affects the loading + * of a WAVE file. + * + * The size of the RIFF chunk (which includes all the sub-chunks of the WAVE + * file) is not always reliable. In case the size is wrong, it's possible to + * just ignore it and step through the chunks until a fixed limit is reached. + * + * Note that files that have trailing data unrelated to the WAVE file or + * corrupt files may slow down the loading process without a reliable + * boundary. By default, SDL stops after 10000 chunks to prevent wasting time. + * Use SDL_HINT_WAVE_CHUNK_LIMIT to adjust this value. + * + * The variable can be set to the following values: + * + * - "force" - Always use the RIFF chunk size as a boundary for the chunk + * search. + * - "ignorezero" - Like "force", but a zero size searches up to 4 GiB. + * (default) + * - "ignore" - Ignore the RIFF chunk size and always search up to 4 GiB. + * - "maximum" - Search for chunks until the end of file. (not recommended) + * + * This hint should be set before calling SDL_LoadWAV() or SDL_LoadWAV_IO() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WAVE_RIFF_CHUNK_SIZE "SDL_WAVE_RIFF_CHUNK_SIZE" + +/** + * A variable controlling how a truncated WAVE file is handled. + * + * A WAVE file is considered truncated if any of the chunks are incomplete or + * the data chunk size is not a multiple of the block size. By default, SDL + * decodes until the first incomplete block, as most applications seem to do. + * + * The variable can be set to the following values: + * + * - "verystrict" - Raise an error if the file is truncated. + * - "strict" - Like "verystrict", but the size of the RIFF chunk is ignored. + * - "dropframe" - Decode until the first incomplete sample frame. + * - "dropblock" - Decode until the first incomplete block. (default) + * + * This hint should be set before calling SDL_LoadWAV() or SDL_LoadWAV_IO() + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WAVE_TRUNCATION "SDL_WAVE_TRUNCATION" + +/** + * A variable controlling whether the window is activated when the + * SDL_RaiseWindow function is called. + * + * The variable can be set to the following values: + * + * - "0": The window is not activated when the SDL_RaiseWindow function is + * called. + * - "1": The window is activated when the SDL_RaiseWindow function is called. + * (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOW_ACTIVATE_WHEN_RAISED "SDL_WINDOW_ACTIVATE_WHEN_RAISED" + +/** + * A variable controlling whether the window is activated when the + * SDL_ShowWindow function is called. + * + * The variable can be set to the following values: + * + * - "0": The window is not activated when the SDL_ShowWindow function is + * called. + * - "1": The window is activated when the SDL_ShowWindow function is called. + * (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOW_ACTIVATE_WHEN_SHOWN "SDL_WINDOW_ACTIVATE_WHEN_SHOWN" + +/** + * If set to "0" then never set the top-most flag on an SDL Window even if the + * application requests it. + * + * This is a debugging aid for developers and not expected to be used by end + * users. + * + * The variable can be set to the following values: + * + * - "0": don't allow topmost + * - "1": allow topmost (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOW_ALLOW_TOPMOST "SDL_WINDOW_ALLOW_TOPMOST" + +/** + * A variable controlling whether the window frame and title bar are + * interactive when the cursor is hidden. + * + * The variable can be set to the following values: + * + * - "0": The window frame is not interactive when the cursor is hidden (no + * move, resize, etc). + * - "1": The window frame is interactive when the cursor is hidden. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN "SDL_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN" + +/** + * A variable controlling whether SDL generates window-close events for Alt+F4 + * on Windows. + * + * The variable can be set to the following values: + * + * - "0": SDL will only do normal key handling for Alt+F4. + * - "1": SDL will generate a window-close event when it sees Alt+F4. + * (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOWS_CLOSE_ON_ALT_F4 "SDL_WINDOWS_CLOSE_ON_ALT_F4" + +/** + * A variable controlling whether menus can be opened with their keyboard + * shortcut (Alt+mnemonic). + * + * If the mnemonics are enabled, then menus can be opened by pressing the Alt + * key and the corresponding mnemonic (for example, Alt+F opens the File + * menu). However, in case an invalid mnemonic is pressed, Windows makes an + * audible beep to convey that nothing happened. This is true even if the + * window has no menu at all! + * + * Because most SDL applications don't have menus, and some want to use the + * Alt key for other purposes, SDL disables mnemonics (and the beeping) by + * default. + * + * Note: This also affects keyboard events: with mnemonics enabled, when a + * menu is opened from the keyboard, you will not receive a KEYUP event for + * the mnemonic key, and *might* not receive one for Alt. + * + * The variable can be set to the following values: + * + * - "0": Alt+mnemonic does nothing, no beeping. (default) + * - "1": Alt+mnemonic opens menus, invalid mnemonics produce a beep. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOWS_ENABLE_MENU_MNEMONICS "SDL_WINDOWS_ENABLE_MENU_MNEMONICS" + +/** + * A variable controlling whether the windows message loop is processed by + * SDL. + * + * The variable can be set to the following values: + * + * - "0": The window message loop is not run. + * - "1": The window message loop is processed in SDL_PumpEvents(). (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP "SDL_WINDOWS_ENABLE_MESSAGELOOP" + +/** + * A variable controlling whether GameInput is used for raw keyboard and mouse + * on Windows. + * + * The variable can be set to the following values: + * + * - "0": GameInput is not used for raw keyboard and mouse events. + * - "1": GameInput is used for raw keyboard and mouse events, if available. + * (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOWS_GAMEINPUT "SDL_WINDOWS_GAMEINPUT" + +/** + * A variable controlling whether raw keyboard events are used on Windows. + * + * The variable can be set to the following values: + * + * - "0": The Windows message loop is used for keyboard events. (default) + * - "1": Low latency raw keyboard events are used. + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOWS_RAW_KEYBOARD "SDL_WINDOWS_RAW_KEYBOARD" + +/** + * A variable controlling whether SDL uses Kernel Semaphores on Windows. + * + * Kernel Semaphores are inter-process and require a context switch on every + * interaction. On Windows 8 and newer, the WaitOnAddress API is available. + * Using that and atomics to implement semaphores increases performance. SDL + * will fall back to Kernel Objects on older OS versions or if forced to by + * this hint. + * + * The variable can be set to the following values: + * + * - "0": Use Atomics and WaitOnAddress API when available, otherwise fall + * back to Kernel Objects. (default) + * - "1": Force the use of Kernel Objects in all cases. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOWS_FORCE_SEMAPHORE_KERNEL "SDL_WINDOWS_FORCE_SEMAPHORE_KERNEL" + +/** + * A variable to specify custom icon resource id from RC file on Windows + * platform. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOWS_INTRESOURCE_ICON "SDL_WINDOWS_INTRESOURCE_ICON" + +/** + * A variable to specify custom icon resource id from RC file on Windows + * platform. + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL "SDL_WINDOWS_INTRESOURCE_ICON_SMALL" + +/** + * A variable controlling whether SDL uses the D3D9Ex API introduced in + * Windows Vista, instead of normal D3D9. + * + * Direct3D 9Ex contains changes to state management that can eliminate device + * loss errors during scenarios like Alt+Tab or UAC prompts. D3D9Ex may + * require some changes to your application to cope with the new behavior, so + * this is disabled by default. + * + * For more information on Direct3D 9Ex, see: + * + * - https://docs.microsoft.com/en-us/windows/win32/direct3darticles/graphics-apis-in-windows-vista#direct3d-9ex + * - https://docs.microsoft.com/en-us/windows/win32/direct3darticles/direct3d-9ex-improvements + * + * The variable can be set to the following values: + * + * - "0": Use the original Direct3D 9 API. (default) + * - "1": Use the Direct3D 9Ex API on Vista and later (and fall back if D3D9Ex + * is unavailable) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOWS_USE_D3D9EX "SDL_WINDOWS_USE_D3D9EX" + +/** + * A variable controlling whether SDL will clear the window contents when the + * WM_ERASEBKGND message is received. + * + * The variable can be set to the following values: + * + * - "0"/"never": Never clear the window. + * - "1"/"initial": Clear the window when the first WM_ERASEBKGND event fires. + * (default) + * - "2"/"always": Clear the window on every WM_ERASEBKGND event. + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_WINDOWS_ERASE_BACKGROUND_MODE "SDL_WINDOWS_ERASE_BACKGROUND_MODE" + +/** + * A variable controlling whether X11 windows are marked as override-redirect. + * + * If set, this _might_ increase framerate at the expense of the desktop not + * working as expected. Override-redirect windows aren't noticed by the window + * manager at all. + * + * You should probably only use this for fullscreen windows, and you probably + * shouldn't even use it for that. But it's here if you want to try! + * + * The variable can be set to the following values: + * + * - "0": Do not mark the window as override-redirect. (default) + * - "1": Mark the window as override-redirect. + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_X11_FORCE_OVERRIDE_REDIRECT "SDL_X11_FORCE_OVERRIDE_REDIRECT" + +/** + * A variable specifying the type of an X11 window. + * + * During SDL_CreateWindow, SDL uses the _NET_WM_WINDOW_TYPE X11 property to + * report to the window manager the type of window it wants to create. This + * might be set to various things if SDL_WINDOW_TOOLTIP or + * SDL_WINDOW_POPUP_MENU, etc, were specified. For "normal" windows that + * haven't set a specific type, this hint can be used to specify a custom + * type. For example, a dock window might set this to + * "_NET_WM_WINDOW_TYPE_DOCK". + * + * This hint should be set before creating a window. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_X11_WINDOW_TYPE "SDL_X11_WINDOW_TYPE" + +/** + * Specify the XCB library to load for the X11 driver. + * + * The default is platform-specific, often "libX11-xcb.so.1". + * + * This hint should be set before initializing the video subsystem. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_X11_XCB_LIBRARY "SDL_X11_XCB_LIBRARY" + +/** + * A variable controlling whether XInput should be used for controller + * handling. + * + * The variable can be set to the following values: + * + * - "0": XInput is not enabled. + * - "1": XInput is enabled. (default) + * + * This hint should be set before SDL is initialized. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_XINPUT_ENABLED "SDL_XINPUT_ENABLED" + +/** + * A variable controlling response to SDL_assert failures. + * + * The variable can be set to the following case-sensitive values: + * + * - "abort": Program terminates immediately. + * - "break": Program triggers a debugger breakpoint. + * - "retry": Program reruns the SDL_assert's test again. + * - "ignore": Program continues on, ignoring this assertion failure this + * time. + * - "always_ignore": Program continues on, ignoring this assertion failure + * for the rest of the run. + * + * Note that SDL_SetAssertionHandler offers a programmatic means to deal with + * assertion failures through a callback, and this hint is largely intended to + * be used via environment variables by end users and automated tools. + * + * This hint should be set before an assertion failure is triggered and can be + * changed at any time. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_ASSERT "SDL_ASSERT" + +/** + * A variable controlling whether pen events should generate synthetic mouse + * events. + * + * The variable can be set to the following values: + * + * - "0": Pen events will not generate mouse events. + * - "1": Pen events will generate mouse events. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_PEN_MOUSE_EVENTS "SDL_PEN_MOUSE_EVENTS" + +/** + * A variable controlling whether pen events should generate synthetic touch + * events. + * + * The variable can be set to the following values: + * + * - "0": Pen events will not generate touch events. + * - "1": Pen events will generate touch events. (default) + * + * This hint can be set anytime. + * + * \since This hint is available since SDL 3.2.0. + */ +#define SDL_HINT_PEN_TOUCH_EVENTS "SDL_PEN_TOUCH_EVENTS" + + +/** + * An enumeration of hint priorities. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_HintPriority +{ + SDL_HINT_DEFAULT, + SDL_HINT_NORMAL, + SDL_HINT_OVERRIDE +} SDL_HintPriority; + +/** + * Set a hint with a specific priority. + * + * The priority controls the behavior when setting a hint that already has a + * value. Hints will replace existing hints of their priority and lower. + * Environment variables are considered to have override priority. + * + * \param name the hint to set. + * \param value the value of the hint variable. + * \param priority the SDL_HintPriority level for the hint. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetHint + * \sa SDL_ResetHint + * \sa SDL_SetHint + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetHintWithPriority(const char *name, const char *value, SDL_HintPriority priority); + +/** + * Set a hint with normal priority. + * + * Hints will not be set if there is an existing override hint or environment + * variable that takes precedence. You can use SDL_SetHintWithPriority() to + * set the hint with override priority instead. + * + * \param name the hint to set. + * \param value the value of the hint variable. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetHint + * \sa SDL_ResetHint + * \sa SDL_SetHintWithPriority + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetHint(const char *name, const char *value); + +/** + * Reset a hint to the default value. + * + * This will reset a hint to the value of the environment variable, or NULL if + * the environment isn't set. Callbacks will be called normally with this + * change. + * + * \param name the hint to set. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetHint + * \sa SDL_ResetHints + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ResetHint(const char *name); + +/** + * Reset all hints to the default values. + * + * This will reset all hints to the value of the associated environment + * variable, or NULL if the environment isn't set. Callbacks will be called + * normally with this change. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ResetHint + */ +extern SDL_DECLSPEC void SDLCALL SDL_ResetHints(void); + +/** + * Get the value of a hint. + * + * \param name the hint to query. + * \returns the string value of a hint or NULL if the hint isn't set. + * + * \threadsafety It is safe to call this function from any thread, however the + * return value only remains valid until the hint is changed; if + * another thread might do so, the app should supply locks + * and/or make a copy of the string. Note that using a hint + * callback instead is always thread-safe, as SDL holds a lock + * on the thread subsystem during the callback. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetHint + * \sa SDL_SetHintWithPriority + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetHint(const char *name); + +/** + * Get the boolean value of a hint variable. + * + * \param name the name of the hint to get the boolean value from. + * \param default_value the value to return if the hint does not exist. + * \returns the boolean value of a hint or the provided default value if the + * hint does not exist. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetHint + * \sa SDL_SetHint + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetHintBoolean(const char *name, bool default_value); + +/** + * A callback used to send notifications of hint value changes. + * + * This is called an initial time during SDL_AddHintCallback with the hint's + * current value, and then again each time the hint's value changes. + * + * \param userdata what was passed as `userdata` to SDL_AddHintCallback(). + * \param name what was passed as `name` to SDL_AddHintCallback(). + * \param oldValue the previous hint value. + * \param newValue the new value hint is to be set to. + * + * \threadsafety This callback is fired from whatever thread is setting a new + * hint value. SDL holds a lock on the hint subsystem when + * calling this callback. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_AddHintCallback + */ +typedef void(SDLCALL *SDL_HintCallback)(void *userdata, const char *name, const char *oldValue, const char *newValue); + +/** + * Add a function to watch a particular hint. + * + * The callback function is called _during_ this function, to provide it an + * initial value, and again each time the hint's value changes. + * + * \param name the hint to watch. + * \param callback An SDL_HintCallback function that will be called when the + * hint value changes. + * \param userdata a pointer to pass to the callback function. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RemoveHintCallback + */ +extern SDL_DECLSPEC bool SDLCALL SDL_AddHintCallback(const char *name, SDL_HintCallback callback, void *userdata); + +/** + * Remove a function watching a particular hint. + * + * \param name the hint being watched. + * \param callback an SDL_HintCallback function that will be called when the + * hint value changes. + * \param userdata a pointer being passed to the callback function. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddHintCallback + */ +extern SDL_DECLSPEC void SDLCALL SDL_RemoveHintCallback(const char *name, + SDL_HintCallback callback, + void *userdata); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_hints_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_init.h b/thirdparty/sdl/include/SDL3/SDL_init.h new file mode 100644 index 00000000000..27ebe4b0ede --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_init.h @@ -0,0 +1,497 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryInit + * + * All SDL programs need to initialize the library before starting to work + * with it. + * + * Almost everything can simply call SDL_Init() near startup, with a handful + * of flags to specify subsystems to touch. These are here to make sure SDL + * does not even attempt to touch low-level pieces of the operating system + * that you don't intend to use. For example, you might be using SDL for video + * and input but chose an external library for audio, and in this case you + * would just need to leave off the `SDL_INIT_AUDIO` flag to make sure that + * external library has complete control. + * + * Most apps, when terminating, should call SDL_Quit(). This will clean up + * (nearly) everything that SDL might have allocated, and crucially, it'll + * make sure that the display's resolution is back to what the user expects if + * you had previously changed it for your game. + * + * SDL3 apps are strongly encouraged to call SDL_SetAppMetadata() at startup + * to fill in details about the program. This is completely optional, but it + * helps in small ways (we can provide an About dialog box for the macOS menu, + * we can name the app in the system's audio mixer, etc). Those that want to + * provide a _lot_ of information should look at the more-detailed + * SDL_SetAppMetadataProperty(). + */ + +#ifndef SDL_init_h_ +#define SDL_init_h_ + +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* As of version 0.5, SDL is loaded dynamically into the application */ + +/** + * Initialization flags for SDL_Init and/or SDL_InitSubSystem + * + * These are the flags which may be passed to SDL_Init(). You should specify + * the subsystems which you will be using in your application. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_Init + * \sa SDL_Quit + * \sa SDL_InitSubSystem + * \sa SDL_QuitSubSystem + * \sa SDL_WasInit + */ +typedef Uint32 SDL_InitFlags; + +#define SDL_INIT_AUDIO 0x00000010u /**< `SDL_INIT_AUDIO` implies `SDL_INIT_EVENTS` */ +#define SDL_INIT_VIDEO 0x00000020u /**< `SDL_INIT_VIDEO` implies `SDL_INIT_EVENTS`, should be initialized on the main thread */ +#define SDL_INIT_JOYSTICK 0x00000200u /**< `SDL_INIT_JOYSTICK` implies `SDL_INIT_EVENTS` */ +#define SDL_INIT_HAPTIC 0x00001000u +#define SDL_INIT_GAMEPAD 0x00002000u /**< `SDL_INIT_GAMEPAD` implies `SDL_INIT_JOYSTICK` */ +#define SDL_INIT_EVENTS 0x00004000u +#define SDL_INIT_SENSOR 0x00008000u /**< `SDL_INIT_SENSOR` implies `SDL_INIT_EVENTS` */ +#define SDL_INIT_CAMERA 0x00010000u /**< `SDL_INIT_CAMERA` implies `SDL_INIT_EVENTS` */ + +/** + * Return values for optional main callbacks. + * + * Returning SDL_APP_SUCCESS or SDL_APP_FAILURE from SDL_AppInit, + * SDL_AppEvent, or SDL_AppIterate will terminate the program and report + * success/failure to the operating system. What that means is + * platform-dependent. On Unix, for example, on success, the process error + * code will be zero, and on failure it will be 1. This interface doesn't + * allow you to return specific exit codes, just whether there was an error + * generally or not. + * + * Returning SDL_APP_CONTINUE from these functions will let the app continue + * to run. + * + * See + * [Main callbacks in SDL3](https://wiki.libsdl.org/SDL3/README/main-functions#main-callbacks-in-sdl3) + * for complete details. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_AppResult +{ + SDL_APP_CONTINUE, /**< Value that requests that the app continue from the main callbacks. */ + SDL_APP_SUCCESS, /**< Value that requests termination with success from the main callbacks. */ + SDL_APP_FAILURE /**< Value that requests termination with error from the main callbacks. */ +} SDL_AppResult; + +/** + * Function pointer typedef for SDL_AppInit. + * + * These are used by SDL_EnterAppMainCallbacks. This mechanism operates behind + * the scenes for apps using the optional main callbacks. Apps that want to + * use this should just implement SDL_AppInit directly. + * + * \param appstate a place where the app can optionally store a pointer for + * future use. + * \param argc the standard ANSI C main's argc; number of elements in `argv`. + * \param argv the standard ANSI C main's argv; array of command line + * arguments. + * \returns SDL_APP_FAILURE to terminate with an error, SDL_APP_SUCCESS to + * terminate with success, SDL_APP_CONTINUE to continue. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef SDL_AppResult (SDLCALL *SDL_AppInit_func)(void **appstate, int argc, char *argv[]); + +/** + * Function pointer typedef for SDL_AppIterate. + * + * These are used by SDL_EnterAppMainCallbacks. This mechanism operates behind + * the scenes for apps using the optional main callbacks. Apps that want to + * use this should just implement SDL_AppIterate directly. + * + * \param appstate an optional pointer, provided by the app in SDL_AppInit. + * \returns SDL_APP_FAILURE to terminate with an error, SDL_APP_SUCCESS to + * terminate with success, SDL_APP_CONTINUE to continue. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef SDL_AppResult (SDLCALL *SDL_AppIterate_func)(void *appstate); + +/** + * Function pointer typedef for SDL_AppEvent. + * + * These are used by SDL_EnterAppMainCallbacks. This mechanism operates behind + * the scenes for apps using the optional main callbacks. Apps that want to + * use this should just implement SDL_AppEvent directly. + * + * \param appstate an optional pointer, provided by the app in SDL_AppInit. + * \param event the new event for the app to examine. + * \returns SDL_APP_FAILURE to terminate with an error, SDL_APP_SUCCESS to + * terminate with success, SDL_APP_CONTINUE to continue. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef SDL_AppResult (SDLCALL *SDL_AppEvent_func)(void *appstate, SDL_Event *event); + +/** + * Function pointer typedef for SDL_AppQuit. + * + * These are used by SDL_EnterAppMainCallbacks. This mechanism operates behind + * the scenes for apps using the optional main callbacks. Apps that want to + * use this should just implement SDL_AppEvent directly. + * + * \param appstate an optional pointer, provided by the app in SDL_AppInit. + * \param result the result code that terminated the app (success or failure). + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef void (SDLCALL *SDL_AppQuit_func)(void *appstate, SDL_AppResult result); + + +/** + * Initialize the SDL library. + * + * SDL_Init() simply forwards to calling SDL_InitSubSystem(). Therefore, the + * two may be used interchangeably. Though for readability of your code + * SDL_InitSubSystem() might be preferred. + * + * The file I/O (for example: SDL_IOFromFile) and threading (SDL_CreateThread) + * subsystems are initialized by default. Message boxes + * (SDL_ShowSimpleMessageBox) also attempt to work without initializing the + * video subsystem, in hopes of being useful in showing an error dialog when + * SDL_Init fails. You must specifically initialize other subsystems if you + * use them in your application. + * + * Logging (such as SDL_Log) works without initialization, too. + * + * `flags` may be any of the following OR'd together: + * + * - `SDL_INIT_AUDIO`: audio subsystem; automatically initializes the events + * subsystem + * - `SDL_INIT_VIDEO`: video subsystem; automatically initializes the events + * subsystem, should be initialized on the main thread. + * - `SDL_INIT_JOYSTICK`: joystick subsystem; automatically initializes the + * events subsystem + * - `SDL_INIT_HAPTIC`: haptic (force feedback) subsystem + * - `SDL_INIT_GAMEPAD`: gamepad subsystem; automatically initializes the + * joystick subsystem + * - `SDL_INIT_EVENTS`: events subsystem + * - `SDL_INIT_SENSOR`: sensor subsystem; automatically initializes the events + * subsystem + * - `SDL_INIT_CAMERA`: camera subsystem; automatically initializes the events + * subsystem + * + * Subsystem initialization is ref-counted, you must call SDL_QuitSubSystem() + * for each SDL_InitSubSystem() to correctly shutdown a subsystem manually (or + * call SDL_Quit() to force shutdown). If a subsystem is already loaded then + * this call will increase the ref-count and return. + * + * Consider reporting some basic metadata about your application before + * calling SDL_Init, using either SDL_SetAppMetadata() or + * SDL_SetAppMetadataProperty(). + * + * \param flags subsystem initialization flags. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAppMetadata + * \sa SDL_SetAppMetadataProperty + * \sa SDL_InitSubSystem + * \sa SDL_Quit + * \sa SDL_SetMainReady + * \sa SDL_WasInit + */ +extern SDL_DECLSPEC bool SDLCALL SDL_Init(SDL_InitFlags flags); + +/** + * Compatibility function to initialize the SDL library. + * + * This function and SDL_Init() are interchangeable. + * + * \param flags any of the flags used by SDL_Init(); see SDL_Init for details. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Init + * \sa SDL_Quit + * \sa SDL_QuitSubSystem + */ +extern SDL_DECLSPEC bool SDLCALL SDL_InitSubSystem(SDL_InitFlags flags); + +/** + * Shut down specific SDL subsystems. + * + * You still need to call SDL_Quit() even if you close all open subsystems + * with SDL_QuitSubSystem(). + * + * \param flags any of the flags used by SDL_Init(); see SDL_Init for details. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_InitSubSystem + * \sa SDL_Quit + */ +extern SDL_DECLSPEC void SDLCALL SDL_QuitSubSystem(SDL_InitFlags flags); + +/** + * Get a mask of the specified subsystems which are currently initialized. + * + * \param flags any of the flags used by SDL_Init(); see SDL_Init for details. + * \returns a mask of all initialized subsystems if `flags` is 0, otherwise it + * returns the initialization status of the specified subsystems. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Init + * \sa SDL_InitSubSystem + */ +extern SDL_DECLSPEC SDL_InitFlags SDLCALL SDL_WasInit(SDL_InitFlags flags); + +/** + * Clean up all initialized subsystems. + * + * You should call this function even if you have already shutdown each + * initialized subsystem with SDL_QuitSubSystem(). It is safe to call this + * function even in the case of errors in initialization. + * + * You can use this function with atexit() to ensure that it is run when your + * application is shutdown, but it is not wise to do this from a library or + * other dynamically loaded code. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Init + * \sa SDL_QuitSubSystem + */ +extern SDL_DECLSPEC void SDLCALL SDL_Quit(void); + +/** + * Return whether this is the main thread. + * + * On Apple platforms, the main thread is the thread that runs your program's + * main() entry point. On other platforms, the main thread is the one that + * calls SDL_Init(SDL_INIT_VIDEO), which should usually be the one that runs + * your program's main() entry point. If you are using the main callbacks, + * SDL_AppInit(), SDL_AppIterate(), and SDL_AppQuit() are all called on the + * main thread. + * + * \returns true if this thread is the main thread, or false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RunOnMainThread + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsMainThread(void); + +/** + * Callback run on the main thread. + * + * \param userdata an app-controlled pointer that is passed to the callback. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_RunOnMainThread + */ +typedef void (SDLCALL *SDL_MainThreadCallback)(void *userdata); + +/** + * Call a function on the main thread during event processing. + * + * If this is called on the main thread, the callback is executed immediately. + * If this is called on another thread, this callback is queued for execution + * on the main thread during event processing. + * + * Be careful of deadlocks when using this functionality. You should not have + * the main thread wait for the current thread while this function is being + * called with `wait_complete` true. + * + * \param callback the callback to call on the main thread. + * \param userdata a pointer that is passed to `callback`. + * \param wait_complete true to wait for the callback to complete, false to + * return immediately. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_IsMainThread + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RunOnMainThread(SDL_MainThreadCallback callback, void *userdata, bool wait_complete); + +/** + * Specify basic metadata about your app. + * + * You can optionally provide metadata about your app to SDL. This is not + * required, but strongly encouraged. + * + * There are several locations where SDL can make use of metadata (an "About" + * box in the macOS menu bar, the name of the app can be shown on some audio + * mixers, etc). Any piece of metadata can be left as NULL, if a specific + * detail doesn't make sense for the app. + * + * This function should be called as early as possible, before SDL_Init. + * Multiple calls to this function are allowed, but various state might not + * change once it has been set up with a previous call to this function. + * + * Passing a NULL removes any previous metadata. + * + * This is a simplified interface for the most important information. You can + * supply significantly more detailed metadata with + * SDL_SetAppMetadataProperty(). + * + * \param appname The name of the application ("My Game 2: Bad Guy's + * Revenge!"). + * \param appversion The version of the application ("1.0.0beta5" or a git + * hash, or whatever makes sense). + * \param appidentifier A unique string in reverse-domain format that + * identifies this app ("com.example.mygame2"). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAppMetadataProperty + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAppMetadata(const char *appname, const char *appversion, const char *appidentifier); + +/** + * Specify metadata about your app through a set of properties. + * + * You can optionally provide metadata about your app to SDL. This is not + * required, but strongly encouraged. + * + * There are several locations where SDL can make use of metadata (an "About" + * box in the macOS menu bar, the name of the app can be shown on some audio + * mixers, etc). Any piece of metadata can be left out, if a specific detail + * doesn't make sense for the app. + * + * This function should be called as early as possible, before SDL_Init. + * Multiple calls to this function are allowed, but various state might not + * change once it has been set up with a previous call to this function. + * + * Once set, this metadata can be read using SDL_GetAppMetadataProperty(). + * + * These are the supported properties: + * + * - `SDL_PROP_APP_METADATA_NAME_STRING`: The human-readable name of the + * application, like "My Game 2: Bad Guy's Revenge!". This will show up + * anywhere the OS shows the name of the application separately from window + * titles, such as volume control applets, etc. This defaults to "SDL + * Application". + * - `SDL_PROP_APP_METADATA_VERSION_STRING`: The version of the app that is + * running; there are no rules on format, so "1.0.3beta2" and "April 22nd, + * 2024" and a git hash are all valid options. This has no default. + * - `SDL_PROP_APP_METADATA_IDENTIFIER_STRING`: A unique string that + * identifies this app. This must be in reverse-domain format, like + * "com.example.mygame2". This string is used by desktop compositors to + * identify and group windows together, as well as match applications with + * associated desktop settings and icons. If you plan to package your + * application in a container such as Flatpak, the app ID should match the + * name of your Flatpak container as well. This has no default. + * - `SDL_PROP_APP_METADATA_CREATOR_STRING`: The human-readable name of the + * creator/developer/maker of this app, like "MojoWorkshop, LLC" + * - `SDL_PROP_APP_METADATA_COPYRIGHT_STRING`: The human-readable copyright + * notice, like "Copyright (c) 2024 MojoWorkshop, LLC" or whatnot. Keep this + * to one line, don't paste a copy of a whole software license in here. This + * has no default. + * - `SDL_PROP_APP_METADATA_URL_STRING`: A URL to the app on the web. Maybe a + * product page, or a storefront, or even a GitHub repository, for user's + * further information This has no default. + * - `SDL_PROP_APP_METADATA_TYPE_STRING`: The type of application this is. + * Currently this string can be "game" for a video game, "mediaplayer" for a + * media player, or generically "application" if nothing else applies. + * Future versions of SDL might add new types. This defaults to + * "application". + * + * \param name the name of the metadata property to set. + * \param value the value of the property, or NULL to remove that property. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAppMetadataProperty + * \sa SDL_SetAppMetadata + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetAppMetadataProperty(const char *name, const char *value); + +#define SDL_PROP_APP_METADATA_NAME_STRING "SDL.app.metadata.name" +#define SDL_PROP_APP_METADATA_VERSION_STRING "SDL.app.metadata.version" +#define SDL_PROP_APP_METADATA_IDENTIFIER_STRING "SDL.app.metadata.identifier" +#define SDL_PROP_APP_METADATA_CREATOR_STRING "SDL.app.metadata.creator" +#define SDL_PROP_APP_METADATA_COPYRIGHT_STRING "SDL.app.metadata.copyright" +#define SDL_PROP_APP_METADATA_URL_STRING "SDL.app.metadata.url" +#define SDL_PROP_APP_METADATA_TYPE_STRING "SDL.app.metadata.type" + +/** + * Get metadata about your app. + * + * This returns metadata previously set using SDL_SetAppMetadata() or + * SDL_SetAppMetadataProperty(). See SDL_SetAppMetadataProperty() for the list + * of available properties and their meanings. + * + * \param name the name of the metadata property to get. + * \returns the current value of the metadata property, or the default if it + * is not set, NULL for properties with no default. + * + * \threadsafety It is safe to call this function from any thread, although + * the string returned is not protected and could potentially be + * freed if you call SDL_SetAppMetadataProperty() to set that + * property from another thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetAppMetadata + * \sa SDL_SetAppMetadataProperty + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetAppMetadataProperty(const char *name); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_init_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_intrin.h b/thirdparty/sdl/include/SDL3/SDL_intrin.h new file mode 100644 index 00000000000..bac6d7ad4fa --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_intrin.h @@ -0,0 +1,407 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: Intrinsics */ + +/** + * # CategoryIntrinsics + * + * SDL does some preprocessor gymnastics to determine if any CPU-specific + * compiler intrinsics are available, as this is not necessarily an easy thing + * to calculate, and sometimes depends on quirks of a system, versions of + * build tools, and other external forces. + * + * Apps including SDL's headers will be able to check consistent preprocessor + * definitions to decide if it's safe to use compiler intrinsics for a + * specific CPU architecture. This check only tells you that the compiler is + * capable of using those intrinsics; at runtime, you should still check if + * they are available on the current system with the + * [CPU info functions](https://wiki.libsdl.org/SDL3/CategoryCPUInfo) + * , such as SDL_HasSSE() or SDL_HasNEON(). Otherwise, the process might crash + * for using an unsupported CPU instruction. + * + * SDL only sets preprocessor defines for CPU intrinsics if they are + * supported, so apps should check with `#ifdef` and not `#if`. + * + * SDL will also include the appropriate instruction-set-specific support + * headers, so if SDL decides to define SDL_SSE2_INTRINSICS, it will also + * `#include ` as well. + */ + +#ifndef SDL_intrin_h_ +#define SDL_intrin_h_ + +#include + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Defined if (and only if) the compiler supports Loongarch LSX intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_LASX_INTRINSICS + */ +#define SDL_LSX_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports Loongarch LSX intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_LASX_INTRINSICS + */ +#define SDL_LASX_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports ARM NEON intrinsics. + * + * If this macro is defined, SDL will have already included `` + * ``, ``, and ``, as appropriate. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NEON_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports PowerPC Altivec intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ALTIVEC_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports Intel MMX intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_SSE_INTRINSICS + */ +#define SDL_MMX_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports Intel SSE intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_SSE2_INTRINSICS + * \sa SDL_SSE3_INTRINSICS + * \sa SDL_SSE4_1_INTRINSICS + * \sa SDL_SSE4_2_INTRINSICS + */ +#define SDL_SSE_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports Intel SSE2 intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_SSE_INTRINSICS + * \sa SDL_SSE3_INTRINSICS + * \sa SDL_SSE4_1_INTRINSICS + * \sa SDL_SSE4_2_INTRINSICS + */ +#define SDL_SSE2_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports Intel SSE3 intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_SSE_INTRINSICS + * \sa SDL_SSE2_INTRINSICS + * \sa SDL_SSE4_1_INTRINSICS + * \sa SDL_SSE4_2_INTRINSICS + */ +#define SDL_SSE3_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports Intel SSE4.1 intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_SSE_INTRINSICS + * \sa SDL_SSE2_INTRINSICS + * \sa SDL_SSE3_INTRINSICS + * \sa SDL_SSE4_2_INTRINSICS + */ +#define SDL_SSE4_1_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports Intel SSE4.2 intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_SSE_INTRINSICS + * \sa SDL_SSE2_INTRINSICS + * \sa SDL_SSE3_INTRINSICS + * \sa SDL_SSE4_1_INTRINSICS + */ +#define SDL_SSE4_2_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports Intel AVX intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_AVX2_INTRINSICS + * \sa SDL_AVX512F_INTRINSICS + */ +#define SDL_AVX_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports Intel AVX2 intrinsics. + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_AVX_INTRINSICS + * \sa SDL_AVX512F_INTRINSICS + */ +#define SDL_AVX2_INTRINSICS 1 + +/** + * Defined if (and only if) the compiler supports Intel AVX-512F intrinsics. + * + * AVX-512F is also sometimes referred to as "AVX-512 Foundation." + * + * If this macro is defined, SDL will have already included `` + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_AVX_INTRINSICS + * \sa SDL_AVX2_INTRINSICS + */ +#define SDL_AVX512F_INTRINSICS 1 +#endif + +/* Need to do this here because intrin.h has C++ code in it */ +/* Visual Studio 2005 has a bug where intrin.h conflicts with winnt.h */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (defined(_M_IX86) || defined(_M_X64)) +#ifdef __clang__ +/* As of Clang 11, '_m_prefetchw' is conflicting with the winnt.h's version, + so we define the needed '_m_prefetch' here as a pseudo-header, until the issue is fixed. */ +#ifndef __PRFCHWINTRIN_H +#define __PRFCHWINTRIN_H +static __inline__ void __attribute__((__always_inline__, __nodebug__)) +_m_prefetch(void *__P) +{ + __builtin_prefetch (__P, 0, 3 /* _MM_HINT_T0 */); +} +#endif /* __PRFCHWINTRIN_H */ +#endif /* __clang__ */ +#include + +#elif defined(__MINGW64_VERSION_MAJOR) +#include +#if defined(__ARM_NEON) && !defined(SDL_DISABLE_NEON) +# define SDL_NEON_INTRINSICS 1 +# include +#endif + +#else +/* altivec.h redefining bool causes a number of problems, see bugs 3993 and 4392, so you need to explicitly define SDL_ENABLE_ALTIVEC to have it included. */ +#if defined(__ALTIVEC__) && defined(SDL_ENABLE_ALTIVEC) +#define SDL_ALTIVEC_INTRINSICS 1 +#include +#endif +#ifndef SDL_DISABLE_NEON +# ifdef __ARM_NEON +# define SDL_NEON_INTRINSICS 1 +# include +# elif defined(SDL_PLATFORM_WINDOWS) +/* Visual Studio doesn't define __ARM_ARCH, but _M_ARM (if set, always 7), and _M_ARM64 (if set, always 1). */ +# ifdef _M_ARM +# define SDL_NEON_INTRINSICS 1 +# include +# include +# define __ARM_NEON 1 /* Set __ARM_NEON so that it can be used elsewhere, at compile time */ +# endif +# if defined (_M_ARM64) +# define SDL_NEON_INTRINSICS 1 +# include +# include +# define __ARM_NEON 1 /* Set __ARM_NEON so that it can be used elsewhere, at compile time */ +# define __ARM_ARCH 8 +# endif +# endif +#endif +#endif /* compiler version */ + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION +/** + * A macro to decide if the compiler supports `__attribute__((target))`. + * + * Even though this is defined in SDL's public headers, it is generally not + * used directly by apps. Apps should probably just use SDL_TARGETING + * directly, instead. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_TARGETING + */ +#define SDL_HAS_TARGET_ATTRIBS + +#elif defined(__clang__) && defined(__has_attribute) +# if __has_attribute(target) +# define SDL_HAS_TARGET_ATTRIBS +# endif +#elif defined(__GNUC__) && (__GNUC__ + (__GNUC_MINOR__ >= 9) > 4) /* gcc >= 4.9 */ +# define SDL_HAS_TARGET_ATTRIBS +#elif defined(__ICC) && __ICC >= 1600 +# define SDL_HAS_TARGET_ATTRIBS +#endif + + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A macro to tag a function as targeting a specific CPU architecture. + * + * This is a hint to the compiler that a function should be built with support + * for a CPU instruction set that might be different than the rest of the + * program. + * + * The particulars of this are explained in the GCC documentation: + * + * https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-target-function-attribute + * + * An example of using this feature is to turn on SSE2 support for a specific + * function, even if the rest of the source code is not compiled to use SSE2 + * code: + * + * ```c + * #ifdef SDL_SSE2_INTRINSICS + * static void SDL_TARGETING("sse2") DoSomethingWithSSE2(char *x) { + * ...use SSE2 intrinsic functions, etc... + * } + * #endif + * + * // later... + * #ifdef SDL_SSE2_INTRINSICS + * if (SDL_HasSSE2()) { + * DoSomethingWithSSE2(str); + * } + * #endif + * ``` + * + * The application is, on a whole, built without SSE2 instructions, so it will + * run on Intel machines that don't support SSE2. But then at runtime, it + * checks if the system supports the instructions, and then calls into a + * function that uses SSE2 opcodes. The ifdefs make sure that this code isn't + * used on platforms that don't have SSE2 at all. + * + * On compilers without target support, this is defined to nothing. + * + * This symbol is used by SDL internally, but apps and other libraries are + * welcome to use it for their own interfaces as well. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_TARGETING(x) __attribute__((target(x))) + +#elif defined(SDL_HAS_TARGET_ATTRIBS) +# define SDL_TARGETING(x) __attribute__((target(x))) +#else +# define SDL_TARGETING(x) +#endif + +#ifdef __loongarch64 +# ifndef SDL_DISABLE_LSX +# define SDL_LSX_INTRINSICS 1 +# include +# endif +# ifndef SDL_DISABLE_LASX +# define SDL_LASX_INTRINSICS 1 +# include +# endif +#endif + +#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86) +# if ((defined(_MSC_VER) && !defined(_M_X64)) || defined(__MMX__) || defined(SDL_HAS_TARGET_ATTRIBS)) && !defined(SDL_DISABLE_MMX) +# define SDL_MMX_INTRINSICS 1 +# include +# endif +# if (defined(_MSC_VER) || defined(__SSE__) || defined(SDL_HAS_TARGET_ATTRIBS)) && !defined(SDL_DISABLE_SSE) +# define SDL_SSE_INTRINSICS 1 +# include +# endif +# if (defined(_MSC_VER) || defined(__SSE2__) || defined(SDL_HAS_TARGET_ATTRIBS)) && !defined(SDL_DISABLE_SSE2) +# define SDL_SSE2_INTRINSICS 1 +# include +# endif +# if (defined(_MSC_VER) || defined(__SSE3__) || defined(SDL_HAS_TARGET_ATTRIBS)) && !defined(SDL_DISABLE_SSE3) +# define SDL_SSE3_INTRINSICS 1 +# include +# endif +# if (defined(_MSC_VER) || defined(__SSE4_1__) || defined(SDL_HAS_TARGET_ATTRIBS)) && !defined(SDL_DISABLE_SSE4_1) +# define SDL_SSE4_1_INTRINSICS 1 +# include +# endif +# if (defined(_MSC_VER) || defined(__SSE4_2__) || defined(SDL_HAS_TARGET_ATTRIBS)) && !defined(SDL_DISABLE_SSE4_2) +# define SDL_SSE4_2_INTRINSICS 1 +# include +# endif +# if defined(__clang__) && (defined(_MSC_VER) || defined(__SCE__)) && !defined(__AVX__) && !defined(SDL_DISABLE_AVX) +# define SDL_DISABLE_AVX /* see https://reviews.llvm.org/D20291 and https://reviews.llvm.org/D79194 */ +# endif +# if (defined(_MSC_VER) || defined(__AVX__) || defined(SDL_HAS_TARGET_ATTRIBS)) && !defined(_M_ARM64EC) && !defined(SDL_DISABLE_AVX) +# define SDL_AVX_INTRINSICS 1 +# include +# endif +# if defined(__clang__) && (defined(_MSC_VER) || defined(__SCE__)) && !defined(__AVX2__) && !defined(SDL_DISABLE_AVX2) +# define SDL_DISABLE_AVX2 /* see https://reviews.llvm.org/D20291 and https://reviews.llvm.org/D79194 */ +# endif +# if (defined(_MSC_VER) || defined(__AVX2__) || defined(SDL_HAS_TARGET_ATTRIBS)) && !defined(_M_ARM64EC) && !defined(SDL_DISABLE_AVX2) +# define SDL_AVX2_INTRINSICS 1 +# include +# endif +# if defined(__clang__) && (defined(_MSC_VER) || defined(__SCE__)) && !defined(__AVX512F__) && !defined(SDL_DISABLE_AVX512F) +# define SDL_DISABLE_AVX512F /* see https://reviews.llvm.org/D20291 and https://reviews.llvm.org/D79194 */ +# endif +# if (defined(_MSC_VER) || defined(__AVX512F__) || defined(SDL_HAS_TARGET_ATTRIBS)) && !defined(_M_ARM64EC) && !defined(SDL_DISABLE_AVX512F) +# define SDL_AVX512F_INTRINSICS 1 +# include +# endif +#endif /* defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86) */ + +#endif /* SDL_intrin_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_iostream.h b/thirdparty/sdl/include/SDL3/SDL_iostream.h new file mode 100644 index 00000000000..4ca16093e52 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_iostream.h @@ -0,0 +1,1354 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: IOStream */ + +/** + * # CategoryIOStream + * + * SDL provides an abstract interface for reading and writing data streams. It + * offers implementations for files, memory, etc, and the app can provide + * their own implementations, too. + * + * SDL_IOStream is not related to the standard C++ iostream class, other than + * both are abstract interfaces to read/write data. + */ + +#ifndef SDL_iostream_h_ +#define SDL_iostream_h_ + +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * SDL_IOStream status, set by a read or write operation. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_IOStatus +{ + SDL_IO_STATUS_READY, /**< Everything is ready (no errors and not EOF). */ + SDL_IO_STATUS_ERROR, /**< Read or write I/O error */ + SDL_IO_STATUS_EOF, /**< End of file */ + SDL_IO_STATUS_NOT_READY, /**< Non blocking I/O, not ready */ + SDL_IO_STATUS_READONLY, /**< Tried to write a read-only buffer */ + SDL_IO_STATUS_WRITEONLY /**< Tried to read a write-only buffer */ +} SDL_IOStatus; + +/** + * Possible `whence` values for SDL_IOStream seeking. + * + * These map to the same "whence" concept that `fseek` or `lseek` use in the + * standard C runtime. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_IOWhence +{ + SDL_IO_SEEK_SET, /**< Seek from the beginning of data */ + SDL_IO_SEEK_CUR, /**< Seek relative to current read point */ + SDL_IO_SEEK_END /**< Seek relative to the end of data */ +} SDL_IOWhence; + +/** + * The function pointers that drive an SDL_IOStream. + * + * Applications can provide this struct to SDL_OpenIO() to create their own + * implementation of SDL_IOStream. This is not necessarily required, as SDL + * already offers several common types of I/O streams, via functions like + * SDL_IOFromFile() and SDL_IOFromMem(). + * + * This structure should be initialized using SDL_INIT_INTERFACE() + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_INIT_INTERFACE + */ +typedef struct SDL_IOStreamInterface +{ + /* The version of this interface */ + Uint32 version; + + /** + * Return the number of bytes in this SDL_IOStream + * + * \return the total size of the data stream, or -1 on error. + */ + Sint64 (SDLCALL *size)(void *userdata); + + /** + * Seek to `offset` relative to `whence`, one of stdio's whence values: + * SDL_IO_SEEK_SET, SDL_IO_SEEK_CUR, SDL_IO_SEEK_END + * + * \return the final offset in the data stream, or -1 on error. + */ + Sint64 (SDLCALL *seek)(void *userdata, Sint64 offset, SDL_IOWhence whence); + + /** + * Read up to `size` bytes from the data stream to the area pointed + * at by `ptr`. + * + * On an incomplete read, you should set `*status` to a value from the + * SDL_IOStatus enum. You do not have to explicitly set this on + * a complete, successful read. + * + * \return the number of bytes read + */ + size_t (SDLCALL *read)(void *userdata, void *ptr, size_t size, SDL_IOStatus *status); + + /** + * Write exactly `size` bytes from the area pointed at by `ptr` + * to data stream. + * + * On an incomplete write, you should set `*status` to a value from the + * SDL_IOStatus enum. You do not have to explicitly set this on + * a complete, successful write. + * + * \return the number of bytes written + */ + size_t (SDLCALL *write)(void *userdata, const void *ptr, size_t size, SDL_IOStatus *status); + + /** + * If the stream is buffering, make sure the data is written out. + * + * On failure, you should set `*status` to a value from the + * SDL_IOStatus enum. You do not have to explicitly set this on + * a successful flush. + * + * \return true if successful or false on write error when flushing data. + */ + bool (SDLCALL *flush)(void *userdata, SDL_IOStatus *status); + + /** + * Close and free any allocated resources. + * + * This does not guarantee file writes will sync to physical media; they + * can be in the system's file cache, waiting to go to disk. + * + * The SDL_IOStream is still destroyed even if this fails, so clean up anything + * even if flushing buffers, etc, returns an error. + * + * \return true if successful or false on write error when flushing data. + */ + bool (SDLCALL *close)(void *userdata); + +} SDL_IOStreamInterface; + +/* Check the size of SDL_IOStreamInterface + * + * If this assert fails, either the compiler is padding to an unexpected size, + * or the interface has been updated and this should be updated to match and + * the code using this interface should be updated to handle the old version. + */ +SDL_COMPILE_TIME_ASSERT(SDL_IOStreamInterface_SIZE, + (sizeof(void *) == 4 && sizeof(SDL_IOStreamInterface) == 28) || + (sizeof(void *) == 8 && sizeof(SDL_IOStreamInterface) == 56)); + +/** + * The read/write operation structure. + * + * This operates as an opaque handle. There are several APIs to create various + * types of I/O streams, or an app can supply an SDL_IOStreamInterface to + * SDL_OpenIO() to provide their own stream implementation behind this + * struct's abstract interface. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_IOStream SDL_IOStream; + + +/** + * \name IOFrom functions + * + * Functions to create SDL_IOStream structures from various data streams. + */ +/* @{ */ + +/** + * Use this function to create a new SDL_IOStream structure for reading from + * and/or writing to a named file. + * + * The `mode` string is treated roughly the same as in a call to the C + * library's fopen(), even if SDL doesn't happen to use fopen() behind the + * scenes. + * + * Available `mode` strings: + * + * - "r": Open a file for reading. The file must exist. + * - "w": Create an empty file for writing. If a file with the same name + * already exists its content is erased and the file is treated as a new + * empty file. + * - "a": Append to a file. Writing operations append data at the end of the + * file. The file is created if it does not exist. + * - "r+": Open a file for update both reading and writing. The file must + * exist. + * - "w+": Create an empty file for both reading and writing. If a file with + * the same name already exists its content is erased and the file is + * treated as a new empty file. + * - "a+": Open a file for reading and appending. All writing operations are + * performed at the end of the file, protecting the previous content to be + * overwritten. You can reposition (fseek, rewind) the internal pointer to + * anywhere in the file for reading, but writing operations will move it + * back to the end of file. The file is created if it does not exist. + * + * **NOTE**: In order to open a file as a binary file, a "b" character has to + * be included in the `mode` string. This additional "b" character can either + * be appended at the end of the string (thus making the following compound + * modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the + * letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+"). + * Additional characters may follow the sequence, although they should have no + * effect. For example, "t" is sometimes appended to make explicit the file is + * a text file. + * + * This function supports Unicode filenames, but they must be encoded in UTF-8 + * format, regardless of the underlying operating system. + * + * In Android, SDL_IOFromFile() can be used to open content:// URIs. As a + * fallback, SDL_IOFromFile() will transparently open a matching filename in + * the app's `assets`. + * + * Closing the SDL_IOStream will close SDL's internal file handle. + * + * The following properties may be set at creation time by SDL: + * + * - `SDL_PROP_IOSTREAM_WINDOWS_HANDLE_POINTER`: a pointer, that can be cast + * to a win32 `HANDLE`, that this SDL_IOStream is using to access the + * filesystem. If the program isn't running on Windows, or SDL used some + * other method to access the filesystem, this property will not be set. + * - `SDL_PROP_IOSTREAM_STDIO_FILE_POINTER`: a pointer, that can be cast to a + * stdio `FILE *`, that this SDL_IOStream is using to access the filesystem. + * If SDL used some other method to access the filesystem, this property + * will not be set. PLEASE NOTE that if SDL is using a different C runtime + * than your app, trying to use this pointer will almost certainly result in + * a crash! This is mostly a problem on Windows; make sure you build SDL and + * your app with the same compiler and settings to avoid it. + * - `SDL_PROP_IOSTREAM_FILE_DESCRIPTOR_NUMBER`: a file descriptor that this + * SDL_IOStream is using to access the filesystem. + * - `SDL_PROP_IOSTREAM_ANDROID_AASSET_POINTER`: a pointer, that can be cast + * to an Android NDK `AAsset *`, that this SDL_IOStream is using to access + * the filesystem. If SDL used some other method to access the filesystem, + * this property will not be set. + * + * \param file a UTF-8 string representing the filename to open. + * \param mode an ASCII string representing the mode to be used for opening + * the file. + * \returns a pointer to the SDL_IOStream structure that is created or NULL on + * failure; call SDL_GetError() for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseIO + * \sa SDL_FlushIO + * \sa SDL_ReadIO + * \sa SDL_SeekIO + * \sa SDL_TellIO + * \sa SDL_WriteIO + */ +extern SDL_DECLSPEC SDL_IOStream * SDLCALL SDL_IOFromFile(const char *file, const char *mode); + +#define SDL_PROP_IOSTREAM_WINDOWS_HANDLE_POINTER "SDL.iostream.windows.handle" +#define SDL_PROP_IOSTREAM_STDIO_FILE_POINTER "SDL.iostream.stdio.file" +#define SDL_PROP_IOSTREAM_FILE_DESCRIPTOR_NUMBER "SDL.iostream.file_descriptor" +#define SDL_PROP_IOSTREAM_ANDROID_AASSET_POINTER "SDL.iostream.android.aasset" + +/** + * Use this function to prepare a read-write memory buffer for use with + * SDL_IOStream. + * + * This function sets up an SDL_IOStream struct based on a memory area of a + * certain size, for both read and write access. + * + * This memory buffer is not copied by the SDL_IOStream; the pointer you + * provide must remain valid until you close the stream. Closing the stream + * will not free the original buffer. + * + * If you need to make sure the SDL_IOStream never writes to the memory + * buffer, you should use SDL_IOFromConstMem() with a read-only buffer of + * memory instead. + * + * The following properties will be set at creation time by SDL: + * + * - `SDL_PROP_IOSTREAM_MEMORY_POINTER`: this will be the `mem` parameter that + * was passed to this function. + * - `SDL_PROP_IOSTREAM_MEMORY_SIZE_NUMBER`: this will be the `size` parameter + * that was passed to this function. + * + * \param mem a pointer to a buffer to feed an SDL_IOStream stream. + * \param size the buffer size, in bytes. + * \returns a pointer to a new SDL_IOStream structure or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_IOFromConstMem + * \sa SDL_CloseIO + * \sa SDL_FlushIO + * \sa SDL_ReadIO + * \sa SDL_SeekIO + * \sa SDL_TellIO + * \sa SDL_WriteIO + */ +extern SDL_DECLSPEC SDL_IOStream * SDLCALL SDL_IOFromMem(void *mem, size_t size); + +#define SDL_PROP_IOSTREAM_MEMORY_POINTER "SDL.iostream.memory.base" +#define SDL_PROP_IOSTREAM_MEMORY_SIZE_NUMBER "SDL.iostream.memory.size" + +/** + * Use this function to prepare a read-only memory buffer for use with + * SDL_IOStream. + * + * This function sets up an SDL_IOStream struct based on a memory area of a + * certain size. It assumes the memory area is not writable. + * + * Attempting to write to this SDL_IOStream stream will report an error + * without writing to the memory buffer. + * + * This memory buffer is not copied by the SDL_IOStream; the pointer you + * provide must remain valid until you close the stream. Closing the stream + * will not free the original buffer. + * + * If you need to write to a memory buffer, you should use SDL_IOFromMem() + * with a writable buffer of memory instead. + * + * The following properties will be set at creation time by SDL: + * + * - `SDL_PROP_IOSTREAM_MEMORY_POINTER`: this will be the `mem` parameter that + * was passed to this function. + * - `SDL_PROP_IOSTREAM_MEMORY_SIZE_NUMBER`: this will be the `size` parameter + * that was passed to this function. + * + * \param mem a pointer to a read-only buffer to feed an SDL_IOStream stream. + * \param size the buffer size, in bytes. + * \returns a pointer to a new SDL_IOStream structure or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_IOFromMem + * \sa SDL_CloseIO + * \sa SDL_ReadIO + * \sa SDL_SeekIO + * \sa SDL_TellIO + */ +extern SDL_DECLSPEC SDL_IOStream * SDLCALL SDL_IOFromConstMem(const void *mem, size_t size); + +/** + * Use this function to create an SDL_IOStream that is backed by dynamically + * allocated memory. + * + * This supports the following properties to provide access to the memory and + * control over allocations: + * + * - `SDL_PROP_IOSTREAM_DYNAMIC_MEMORY_POINTER`: a pointer to the internal + * memory of the stream. This can be set to NULL to transfer ownership of + * the memory to the application, which should free the memory with + * SDL_free(). If this is done, the next operation on the stream must be + * SDL_CloseIO(). + * - `SDL_PROP_IOSTREAM_DYNAMIC_CHUNKSIZE_NUMBER`: memory will be allocated in + * multiples of this size, defaulting to 1024. + * + * \returns a pointer to a new SDL_IOStream structure or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseIO + * \sa SDL_ReadIO + * \sa SDL_SeekIO + * \sa SDL_TellIO + * \sa SDL_WriteIO + */ +extern SDL_DECLSPEC SDL_IOStream * SDLCALL SDL_IOFromDynamicMem(void); + +#define SDL_PROP_IOSTREAM_DYNAMIC_MEMORY_POINTER "SDL.iostream.dynamic.memory" +#define SDL_PROP_IOSTREAM_DYNAMIC_CHUNKSIZE_NUMBER "SDL.iostream.dynamic.chunksize" + +/* @} *//* IOFrom functions */ + + +/** + * Create a custom SDL_IOStream. + * + * Applications do not need to use this function unless they are providing + * their own SDL_IOStream implementation. If you just need an SDL_IOStream to + * read/write a common data source, you should use the built-in + * implementations in SDL, like SDL_IOFromFile() or SDL_IOFromMem(), etc. + * + * This function makes a copy of `iface` and the caller does not need to keep + * it around after this call. + * + * \param iface the interface that implements this SDL_IOStream, initialized + * using SDL_INIT_INTERFACE(). + * \param userdata the pointer that will be passed to the interface functions. + * \returns a pointer to the allocated memory on success or NULL on failure; + * call SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseIO + * \sa SDL_INIT_INTERFACE + * \sa SDL_IOFromConstMem + * \sa SDL_IOFromFile + * \sa SDL_IOFromMem + */ +extern SDL_DECLSPEC SDL_IOStream * SDLCALL SDL_OpenIO(const SDL_IOStreamInterface *iface, void *userdata); + +/** + * Close and free an allocated SDL_IOStream structure. + * + * SDL_CloseIO() closes and cleans up the SDL_IOStream stream. It releases any + * resources used by the stream and frees the SDL_IOStream itself. This + * returns true on success, or false if the stream failed to flush to its + * output (e.g. to disk). + * + * Note that if this fails to flush the stream for any reason, this function + * reports an error, but the SDL_IOStream is still invalid once this function + * returns. + * + * This call flushes any buffered writes to the operating system, but there + * are no guarantees that those writes have gone to physical media; they might + * be in the OS's file cache, waiting to go to disk later. If it's absolutely + * crucial that writes go to disk immediately, so they are definitely stored + * even if the power fails before the file cache would have caught up, one + * should call SDL_FlushIO() before closing. Note that flushing takes time and + * makes the system and your app operate less efficiently, so do so sparingly. + * + * \param context SDL_IOStream structure to close. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenIO + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CloseIO(SDL_IOStream *context); + +/** + * Get the properties associated with an SDL_IOStream. + * + * \param context a pointer to an SDL_IOStream structure. + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetIOProperties(SDL_IOStream *context); + +/** + * Query the stream status of an SDL_IOStream. + * + * This information can be useful to decide if a short read or write was due + * to an error, an EOF, or a non-blocking operation that isn't yet ready to + * complete. + * + * An SDL_IOStream's status is only expected to change after a SDL_ReadIO or + * SDL_WriteIO call; don't expect it to change if you just call this query + * function in a tight loop. + * + * \param context the SDL_IOStream to query. + * \returns an SDL_IOStatus enum with the current state. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_IOStatus SDLCALL SDL_GetIOStatus(SDL_IOStream *context); + +/** + * Use this function to get the size of the data stream in an SDL_IOStream. + * + * \param context the SDL_IOStream to get the size of the data stream from. + * \returns the size of the data stream in the SDL_IOStream on success or a + * negative error code on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Sint64 SDLCALL SDL_GetIOSize(SDL_IOStream *context); + +/** + * Seek within an SDL_IOStream data stream. + * + * This function seeks to byte `offset`, relative to `whence`. + * + * `whence` may be any of the following values: + * + * - `SDL_IO_SEEK_SET`: seek from the beginning of data + * - `SDL_IO_SEEK_CUR`: seek relative to current read point + * - `SDL_IO_SEEK_END`: seek relative to the end of data + * + * If this stream can not seek, it will return -1. + * + * \param context a pointer to an SDL_IOStream structure. + * \param offset an offset in bytes, relative to `whence` location; can be + * negative. + * \param whence any of `SDL_IO_SEEK_SET`, `SDL_IO_SEEK_CUR`, + * `SDL_IO_SEEK_END`. + * \returns the final offset in the data stream after the seek or -1 on + * failure; call SDL_GetError() for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_TellIO + */ +extern SDL_DECLSPEC Sint64 SDLCALL SDL_SeekIO(SDL_IOStream *context, Sint64 offset, SDL_IOWhence whence); + +/** + * Determine the current read/write offset in an SDL_IOStream data stream. + * + * SDL_TellIO is actually a wrapper function that calls the SDL_IOStream's + * `seek` method, with an offset of 0 bytes from `SDL_IO_SEEK_CUR`, to + * simplify application development. + * + * \param context an SDL_IOStream data stream object from which to get the + * current offset. + * \returns the current offset in the stream, or -1 if the information can not + * be determined. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SeekIO + */ +extern SDL_DECLSPEC Sint64 SDLCALL SDL_TellIO(SDL_IOStream *context); + +/** + * Read from a data source. + * + * This function reads up `size` bytes from the data source to the area + * pointed at by `ptr`. This function may read less bytes than requested. + * + * This function will return zero when the data stream is completely read, and + * SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If zero is returned and + * the stream is not at EOF, SDL_GetIOStatus() will return a different error + * value and SDL_GetError() will offer a human-readable message. + * + * \param context a pointer to an SDL_IOStream structure. + * \param ptr a pointer to a buffer to read data into. + * \param size the number of bytes to read from the data source. + * \returns the number of bytes read, or 0 on end of file or other failure; + * call SDL_GetError() for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_WriteIO + * \sa SDL_GetIOStatus + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_ReadIO(SDL_IOStream *context, void *ptr, size_t size); + +/** + * Write to an SDL_IOStream data stream. + * + * This function writes exactly `size` bytes from the area pointed at by `ptr` + * to the stream. If this fails for any reason, it'll return less than `size` + * to demonstrate how far the write progressed. On success, it returns `size`. + * + * On error, this function still attempts to write as much as possible, so it + * might return a positive value less than the requested write size. + * + * The caller can use SDL_GetIOStatus() to determine if the problem is + * recoverable, such as a non-blocking write that can simply be retried later, + * or a fatal error. + * + * \param context a pointer to an SDL_IOStream structure. + * \param ptr a pointer to a buffer containing data to write. + * \param size the number of bytes to write. + * \returns the number of bytes written, which will be less than `size` on + * failure; call SDL_GetError() for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_IOprintf + * \sa SDL_ReadIO + * \sa SDL_SeekIO + * \sa SDL_FlushIO + * \sa SDL_GetIOStatus + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_WriteIO(SDL_IOStream *context, const void *ptr, size_t size); + +/** + * Print to an SDL_IOStream data stream. + * + * This function does formatted printing to the stream. + * + * \param context a pointer to an SDL_IOStream structure. + * \param fmt a printf() style format string. + * \param ... additional parameters matching % tokens in the `fmt` string, if + * any. + * \returns the number of bytes written or 0 on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_IOvprintf + * \sa SDL_WriteIO + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_IOprintf(SDL_IOStream *context, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Print to an SDL_IOStream data stream. + * + * This function does formatted printing to the stream. + * + * \param context a pointer to an SDL_IOStream structure. + * \param fmt a printf() style format string. + * \param ap a variable argument list. + * \returns the number of bytes written or 0 on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_IOprintf + * \sa SDL_WriteIO + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_IOvprintf(SDL_IOStream *context, SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(2); + +/** + * Flush any buffered data in the stream. + * + * This function makes sure that any buffered data is written to the stream. + * Normally this isn't necessary but if the stream is a pipe or socket it + * guarantees that any pending data is sent. + * + * \param context SDL_IOStream structure to flush. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenIO + * \sa SDL_WriteIO + */ +extern SDL_DECLSPEC bool SDLCALL SDL_FlushIO(SDL_IOStream *context); + +/** + * Load all the data from an SDL data stream. + * + * The data is allocated with a zero byte at the end (null terminated) for + * convenience. This extra byte is not included in the value reported via + * `datasize`. + * + * The data should be freed with SDL_free(). + * + * \param src the SDL_IOStream to read all available data from. + * \param datasize a pointer filled in with the number of bytes read, may be + * NULL. + * \param closeio if true, calls SDL_CloseIO() on `src` before returning, even + * in the case of an error. + * \returns the data or NULL on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LoadFile + * \sa SDL_SaveFile_IO + */ +extern SDL_DECLSPEC void * SDLCALL SDL_LoadFile_IO(SDL_IOStream *src, size_t *datasize, bool closeio); + +/** + * Load all the data from a file path. + * + * The data is allocated with a zero byte at the end (null terminated) for + * convenience. This extra byte is not included in the value reported via + * `datasize`. + * + * The data should be freed with SDL_free(). + * + * \param file the path to read all available data from. + * \param datasize if not NULL, will store the number of bytes read. + * \returns the data or NULL on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LoadFile_IO + * \sa SDL_SaveFile + */ +extern SDL_DECLSPEC void * SDLCALL SDL_LoadFile(const char *file, size_t *datasize); + +/** + * Save all the data into an SDL data stream. + * + * \param src the SDL_IOStream to write all data to. + * \param data the data to be written. If datasize is 0, may be NULL or a + * invalid pointer. + * \param datasize the number of bytes to be written. + * \param closeio if true, calls SDL_CloseIO() on `src` before returning, even + * in the case of an error. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SaveFile + * \sa SDL_LoadFile_IO + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SaveFile_IO(SDL_IOStream *src, const void *data, size_t datasize, bool closeio); + +/** + * Save all the data into a file path. + * + * \param file the path to write all available data into. + * \param data the data to be written. If datasize is 0, may be NULL or a + * invalid pointer. + * \param datasize the number of bytes to be written. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SaveFile_IO + * \sa SDL_LoadFile + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SaveFile(const char *file, const void *data, size_t datasize); + +/** + * \name Read endian functions + * + * Read an item of the specified endianness and return in native format. + */ +/* @{ */ + +/** + * Use this function to read a byte from an SDL_IOStream. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the SDL_IOStream to read from. + * \param value a pointer filled in with the data read. + * \returns true on success or false on failure or EOF; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadU8(SDL_IOStream *src, Uint8 *value); + +/** + * Use this function to read a signed byte from an SDL_IOStream. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the SDL_IOStream to read from. + * \param value a pointer filled in with the data read. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadS8(SDL_IOStream *src, Sint8 *value); + +/** + * Use this function to read 16 bits of little-endian data from an + * SDL_IOStream and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadU16LE(SDL_IOStream *src, Uint16 *value); + +/** + * Use this function to read 16 bits of little-endian data from an + * SDL_IOStream and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadS16LE(SDL_IOStream *src, Sint16 *value); + +/** + * Use this function to read 16 bits of big-endian data from an SDL_IOStream + * and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadU16BE(SDL_IOStream *src, Uint16 *value); + +/** + * Use this function to read 16 bits of big-endian data from an SDL_IOStream + * and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadS16BE(SDL_IOStream *src, Sint16 *value); + +/** + * Use this function to read 32 bits of little-endian data from an + * SDL_IOStream and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadU32LE(SDL_IOStream *src, Uint32 *value); + +/** + * Use this function to read 32 bits of little-endian data from an + * SDL_IOStream and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadS32LE(SDL_IOStream *src, Sint32 *value); + +/** + * Use this function to read 32 bits of big-endian data from an SDL_IOStream + * and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadU32BE(SDL_IOStream *src, Uint32 *value); + +/** + * Use this function to read 32 bits of big-endian data from an SDL_IOStream + * and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadS32BE(SDL_IOStream *src, Sint32 *value); + +/** + * Use this function to read 64 bits of little-endian data from an + * SDL_IOStream and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadU64LE(SDL_IOStream *src, Uint64 *value); + +/** + * Use this function to read 64 bits of little-endian data from an + * SDL_IOStream and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadS64LE(SDL_IOStream *src, Sint64 *value); + +/** + * Use this function to read 64 bits of big-endian data from an SDL_IOStream + * and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadU64BE(SDL_IOStream *src, Uint64 *value); + +/** + * Use this function to read 64 bits of big-endian data from an SDL_IOStream + * and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * This function will return false when the data stream is completely read, + * and SDL_GetIOStatus() will return SDL_IO_STATUS_EOF. If false is returned + * and the stream is not at EOF, SDL_GetIOStatus() will return a different + * error value and SDL_GetError() will offer a human-readable message. + * + * \param src the stream from which to read data. + * \param value a pointer filled in with the data read. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadS64BE(SDL_IOStream *src, Sint64 *value); +/* @} *//* Read endian functions */ + +/** + * \name Write endian functions + * + * Write an item of native format to the specified endianness. + */ +/* @{ */ + +/** + * Use this function to write a byte to an SDL_IOStream. + * + * \param dst the SDL_IOStream to write to. + * \param value the byte value to write. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteU8(SDL_IOStream *dst, Uint8 value); + +/** + * Use this function to write a signed byte to an SDL_IOStream. + * + * \param dst the SDL_IOStream to write to. + * \param value the byte value to write. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteS8(SDL_IOStream *dst, Sint8 value); + +/** + * Use this function to write 16 bits in native format to an SDL_IOStream as + * little-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in little-endian + * format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteU16LE(SDL_IOStream *dst, Uint16 value); + +/** + * Use this function to write 16 bits in native format to an SDL_IOStream as + * little-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in little-endian + * format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteS16LE(SDL_IOStream *dst, Sint16 value); + +/** + * Use this function to write 16 bits in native format to an SDL_IOStream as + * big-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in big-endian format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteU16BE(SDL_IOStream *dst, Uint16 value); + +/** + * Use this function to write 16 bits in native format to an SDL_IOStream as + * big-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in big-endian format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteS16BE(SDL_IOStream *dst, Sint16 value); + +/** + * Use this function to write 32 bits in native format to an SDL_IOStream as + * little-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in little-endian + * format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteU32LE(SDL_IOStream *dst, Uint32 value); + +/** + * Use this function to write 32 bits in native format to an SDL_IOStream as + * little-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in little-endian + * format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteS32LE(SDL_IOStream *dst, Sint32 value); + +/** + * Use this function to write 32 bits in native format to an SDL_IOStream as + * big-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in big-endian format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteU32BE(SDL_IOStream *dst, Uint32 value); + +/** + * Use this function to write 32 bits in native format to an SDL_IOStream as + * big-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in big-endian format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteS32BE(SDL_IOStream *dst, Sint32 value); + +/** + * Use this function to write 64 bits in native format to an SDL_IOStream as + * little-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in little-endian + * format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteU64LE(SDL_IOStream *dst, Uint64 value); + +/** + * Use this function to write 64 bits in native format to an SDL_IOStream as + * little-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in little-endian + * format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteS64LE(SDL_IOStream *dst, Sint64 value); + +/** + * Use this function to write 64 bits in native format to an SDL_IOStream as + * big-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in big-endian format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteU64BE(SDL_IOStream *dst, Uint64 value); + +/** + * Use this function to write 64 bits in native format to an SDL_IOStream as + * big-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in big-endian format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns true on successful write or false on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteS64BE(SDL_IOStream *dst, Sint64 value); + +/* @} *//* Write endian functions */ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_iostream_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_joystick.h b/thirdparty/sdl/include/SDL3/SDL_joystick.h new file mode 100644 index 00000000000..d15668b66ac --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_joystick.h @@ -0,0 +1,1202 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryJoystick + * + * SDL joystick support. + * + * This is the lower-level joystick handling. If you want the simpler option, + * where what each button does is well-defined, you should use the gamepad API + * instead. + * + * The term "instance_id" is the current instantiation of a joystick device in + * the system, if the joystick is removed and then re-inserted then it will + * get a new instance_id, instance_id's are monotonically increasing + * identifiers of a joystick plugged in. + * + * The term "player_index" is the number assigned to a player on a specific + * controller. For XInput controllers this returns the XInput user index. Many + * joysticks will not be able to supply this information. + * + * SDL_GUID is used as a stable 128-bit identifier for a joystick device that + * does not change over time. It identifies class of the device (a X360 wired + * controller for example). This identifier is platform dependent. + * + * In order to use these functions, SDL_Init() must have been called with the + * SDL_INIT_JOYSTICK flag. This causes SDL to scan the system for joysticks, + * and load appropriate drivers. + * + * If you would like to receive joystick updates while the application is in + * the background, you should set the following hint before calling + * SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS + */ + +#ifndef SDL_joystick_h_ +#define SDL_joystick_h_ + +#include +#include +#include +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef SDL_THREAD_SAFETY_ANALYSIS +/* + * This is not an exported symbol from SDL, this is only in the headers to + * help Clang's thread safety analysis tools to function. Do not attempt + * to access this symbol from your app, it will not work! + */ +extern SDL_Mutex *SDL_joystick_lock; +#endif + +/** + * The joystick structure used to identify an SDL joystick. + * + * This is opaque data. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Joystick SDL_Joystick; + +/** + * This is a unique ID for a joystick for the time it is connected to the + * system, and is never reused for the lifetime of the application. + * + * If the joystick is disconnected and reconnected, it will get a new ID. + * + * The value 0 is an invalid ID. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_JoystickID; + +/** + * An enum of some common joystick types. + * + * In some cases, SDL can identify a low-level joystick as being a certain + * type of device, and will report it through SDL_GetJoystickType (or + * SDL_GetJoystickTypeForID). + * + * This is by no means a complete list of everything that can be plugged into + * a computer. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_JoystickType +{ + SDL_JOYSTICK_TYPE_UNKNOWN, + SDL_JOYSTICK_TYPE_GAMEPAD, + SDL_JOYSTICK_TYPE_WHEEL, + SDL_JOYSTICK_TYPE_ARCADE_STICK, + SDL_JOYSTICK_TYPE_FLIGHT_STICK, + SDL_JOYSTICK_TYPE_DANCE_PAD, + SDL_JOYSTICK_TYPE_GUITAR, + SDL_JOYSTICK_TYPE_DRUM_KIT, + SDL_JOYSTICK_TYPE_ARCADE_PAD, + SDL_JOYSTICK_TYPE_THROTTLE, + SDL_JOYSTICK_TYPE_COUNT +} SDL_JoystickType; + +/** + * Possible connection states for a joystick device. + * + * This is used by SDL_GetJoystickConnectionState to report how a device is + * connected to the system. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_JoystickConnectionState +{ + SDL_JOYSTICK_CONNECTION_INVALID = -1, + SDL_JOYSTICK_CONNECTION_UNKNOWN, + SDL_JOYSTICK_CONNECTION_WIRED, + SDL_JOYSTICK_CONNECTION_WIRELESS +} SDL_JoystickConnectionState; + +/** + * The largest value an SDL_Joystick's axis can report. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_JOYSTICK_AXIS_MIN + */ +#define SDL_JOYSTICK_AXIS_MAX 32767 + +/** + * The smallest value an SDL_Joystick's axis can report. + * + * This is a negative number! + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_JOYSTICK_AXIS_MAX + */ +#define SDL_JOYSTICK_AXIS_MIN -32768 + + +/* Function prototypes */ + +/** + * Locking for atomic access to the joystick API. + * + * The SDL joystick functions are thread-safe, however you can lock the + * joysticks while processing to guarantee that the joystick list won't change + * and joystick and gamepad events will not be delivered. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_LockJoysticks(void) SDL_ACQUIRE(SDL_joystick_lock); + +/** + * Unlocking for atomic access to the joystick API. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnlockJoysticks(void) SDL_RELEASE(SDL_joystick_lock); + +/** + * Return whether a joystick is currently connected. + * + * \returns true if a joystick is connected, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoysticks + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasJoystick(void); + +/** + * Get a list of currently connected joysticks. + * + * \param count a pointer filled in with the number of joysticks returned, may + * be NULL. + * \returns a 0 terminated array of joystick instance IDs or NULL on failure; + * call SDL_GetError() for more information. This should be freed + * with SDL_free() when it is no longer needed. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasJoystick + * \sa SDL_OpenJoystick + */ +extern SDL_DECLSPEC SDL_JoystickID * SDLCALL SDL_GetJoysticks(int *count); + +/** + * Get the implementation dependent name of a joystick. + * + * This can be called before any joysticks are opened. + * + * \param instance_id the joystick instance ID. + * \returns the name of the selected joystick. If no name can be found, this + * function returns NULL; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickName + * \sa SDL_GetJoysticks + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetJoystickNameForID(SDL_JoystickID instance_id); + +/** + * Get the implementation dependent path of a joystick. + * + * This can be called before any joysticks are opened. + * + * \param instance_id the joystick instance ID. + * \returns the path of the selected joystick. If no path can be found, this + * function returns NULL; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickPath + * \sa SDL_GetJoysticks + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetJoystickPathForID(SDL_JoystickID instance_id); + +/** + * Get the player index of a joystick. + * + * This can be called before any joysticks are opened. + * + * \param instance_id the joystick instance ID. + * \returns the player index of a joystick, or -1 if it's not available. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickPlayerIndex + * \sa SDL_GetJoysticks + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetJoystickPlayerIndexForID(SDL_JoystickID instance_id); + +/** + * Get the implementation-dependent GUID of a joystick. + * + * This can be called before any joysticks are opened. + * + * \param instance_id the joystick instance ID. + * \returns the GUID of the selected joystick. If called with an invalid + * instance_id, this function returns a zero GUID. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickGUID + * \sa SDL_GUIDToString + */ +extern SDL_DECLSPEC SDL_GUID SDLCALL SDL_GetJoystickGUIDForID(SDL_JoystickID instance_id); + +/** + * Get the USB vendor ID of a joystick, if available. + * + * This can be called before any joysticks are opened. If the vendor ID isn't + * available this function returns 0. + * + * \param instance_id the joystick instance ID. + * \returns the USB vendor ID of the selected joystick. If called with an + * invalid instance_id, this function returns 0. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickVendor + * \sa SDL_GetJoysticks + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetJoystickVendorForID(SDL_JoystickID instance_id); + +/** + * Get the USB product ID of a joystick, if available. + * + * This can be called before any joysticks are opened. If the product ID isn't + * available this function returns 0. + * + * \param instance_id the joystick instance ID. + * \returns the USB product ID of the selected joystick. If called with an + * invalid instance_id, this function returns 0. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickProduct + * \sa SDL_GetJoysticks + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetJoystickProductForID(SDL_JoystickID instance_id); + +/** + * Get the product version of a joystick, if available. + * + * This can be called before any joysticks are opened. If the product version + * isn't available this function returns 0. + * + * \param instance_id the joystick instance ID. + * \returns the product version of the selected joystick. If called with an + * invalid instance_id, this function returns 0. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickProductVersion + * \sa SDL_GetJoysticks + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetJoystickProductVersionForID(SDL_JoystickID instance_id); + +/** + * Get the type of a joystick, if available. + * + * This can be called before any joysticks are opened. + * + * \param instance_id the joystick instance ID. + * \returns the SDL_JoystickType of the selected joystick. If called with an + * invalid instance_id, this function returns + * `SDL_JOYSTICK_TYPE_UNKNOWN`. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickType + * \sa SDL_GetJoysticks + */ +extern SDL_DECLSPEC SDL_JoystickType SDLCALL SDL_GetJoystickTypeForID(SDL_JoystickID instance_id); + +/** + * Open a joystick for use. + * + * The joystick subsystem must be initialized before a joystick can be opened + * for use. + * + * \param instance_id the joystick instance ID. + * \returns a joystick identifier or NULL on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseJoystick + */ +extern SDL_DECLSPEC SDL_Joystick * SDLCALL SDL_OpenJoystick(SDL_JoystickID instance_id); + +/** + * Get the SDL_Joystick associated with an instance ID, if it has been opened. + * + * \param instance_id the instance ID to get the SDL_Joystick for. + * \returns an SDL_Joystick on success or NULL on failure or if it hasn't been + * opened yet; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Joystick * SDLCALL SDL_GetJoystickFromID(SDL_JoystickID instance_id); + +/** + * Get the SDL_Joystick associated with a player index. + * + * \param player_index the player index to get the SDL_Joystick for. + * \returns an SDL_Joystick on success or NULL on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickPlayerIndex + * \sa SDL_SetJoystickPlayerIndex + */ +extern SDL_DECLSPEC SDL_Joystick * SDLCALL SDL_GetJoystickFromPlayerIndex(int player_index); + +/** + * The structure that describes a virtual joystick touchpad. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_VirtualJoystickDesc + */ +typedef struct SDL_VirtualJoystickTouchpadDesc +{ + Uint16 nfingers; /**< the number of simultaneous fingers on this touchpad */ + Uint16 padding[3]; +} SDL_VirtualJoystickTouchpadDesc; + +/** + * The structure that describes a virtual joystick sensor. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_VirtualJoystickDesc + */ +typedef struct SDL_VirtualJoystickSensorDesc +{ + SDL_SensorType type; /**< the type of this sensor */ + float rate; /**< the update frequency of this sensor, may be 0.0f */ +} SDL_VirtualJoystickSensorDesc; + +/** + * The structure that describes a virtual joystick. + * + * This structure should be initialized using SDL_INIT_INTERFACE(). All + * elements of this structure are optional. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_AttachVirtualJoystick + * \sa SDL_INIT_INTERFACE + * \sa SDL_VirtualJoystickSensorDesc + * \sa SDL_VirtualJoystickTouchpadDesc + */ +typedef struct SDL_VirtualJoystickDesc +{ + Uint32 version; /**< the version of this interface */ + Uint16 type; /**< `SDL_JoystickType` */ + Uint16 padding; /**< unused */ + Uint16 vendor_id; /**< the USB vendor ID of this joystick */ + Uint16 product_id; /**< the USB product ID of this joystick */ + Uint16 naxes; /**< the number of axes on this joystick */ + Uint16 nbuttons; /**< the number of buttons on this joystick */ + Uint16 nballs; /**< the number of balls on this joystick */ + Uint16 nhats; /**< the number of hats on this joystick */ + Uint16 ntouchpads; /**< the number of touchpads on this joystick, requires `touchpads` to point at valid descriptions */ + Uint16 nsensors; /**< the number of sensors on this joystick, requires `sensors` to point at valid descriptions */ + Uint16 padding2[2]; /**< unused */ + Uint32 button_mask; /**< A mask of which buttons are valid for this controller + e.g. (1 << SDL_GAMEPAD_BUTTON_SOUTH) */ + Uint32 axis_mask; /**< A mask of which axes are valid for this controller + e.g. (1 << SDL_GAMEPAD_AXIS_LEFTX) */ + const char *name; /**< the name of the joystick */ + const SDL_VirtualJoystickTouchpadDesc *touchpads; /**< A pointer to an array of touchpad descriptions, required if `ntouchpads` is > 0 */ + const SDL_VirtualJoystickSensorDesc *sensors; /**< A pointer to an array of sensor descriptions, required if `nsensors` is > 0 */ + + void *userdata; /**< User data pointer passed to callbacks */ + void (SDLCALL *Update)(void *userdata); /**< Called when the joystick state should be updated */ + void (SDLCALL *SetPlayerIndex)(void *userdata, int player_index); /**< Called when the player index is set */ + bool (SDLCALL *Rumble)(void *userdata, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble); /**< Implements SDL_RumbleJoystick() */ + bool (SDLCALL *RumbleTriggers)(void *userdata, Uint16 left_rumble, Uint16 right_rumble); /**< Implements SDL_RumbleJoystickTriggers() */ + bool (SDLCALL *SetLED)(void *userdata, Uint8 red, Uint8 green, Uint8 blue); /**< Implements SDL_SetJoystickLED() */ + bool (SDLCALL *SendEffect)(void *userdata, const void *data, int size); /**< Implements SDL_SendJoystickEffect() */ + bool (SDLCALL *SetSensorsEnabled)(void *userdata, bool enabled); /**< Implements SDL_SetGamepadSensorEnabled() */ + void (SDLCALL *Cleanup)(void *userdata); /**< Cleans up the userdata when the joystick is detached */ +} SDL_VirtualJoystickDesc; + +/* Check the size of SDL_VirtualJoystickDesc + * + * If this assert fails, either the compiler is padding to an unexpected size, + * or the interface has been updated and this should be updated to match and + * the code using this interface should be updated to handle the old version. + */ +SDL_COMPILE_TIME_ASSERT(SDL_VirtualJoystickDesc_SIZE, + (sizeof(void *) == 4 && sizeof(SDL_VirtualJoystickDesc) == 84) || + (sizeof(void *) == 8 && sizeof(SDL_VirtualJoystickDesc) == 136)); + +/** + * Attach a new virtual joystick. + * + * \param desc joystick description, initialized using SDL_INIT_INTERFACE(). + * \returns the joystick instance ID, or 0 on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DetachVirtualJoystick + */ +extern SDL_DECLSPEC SDL_JoystickID SDLCALL SDL_AttachVirtualJoystick(const SDL_VirtualJoystickDesc *desc); + +/** + * Detach a virtual joystick. + * + * \param instance_id the joystick instance ID, previously returned from + * SDL_AttachVirtualJoystick(). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AttachVirtualJoystick + */ +extern SDL_DECLSPEC bool SDLCALL SDL_DetachVirtualJoystick(SDL_JoystickID instance_id); + +/** + * Query whether or not a joystick is virtual. + * + * \param instance_id the joystick instance ID. + * \returns true if the joystick is virtual, false otherwise. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsJoystickVirtual(SDL_JoystickID instance_id); + +/** + * Set the state of an axis on an opened virtual joystick. + * + * Please note that values set here will not be applied until the next call to + * SDL_UpdateJoysticks, which can either be called directly, or can be called + * indirectly through various other SDL APIs, including, but not limited to + * the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout, + * SDL_WaitEvent. + * + * Note that when sending trigger axes, you should scale the value to the full + * range of Sint16. For example, a trigger at rest would have the value of + * `SDL_JOYSTICK_AXIS_MIN`. + * + * \param joystick the virtual joystick on which to set state. + * \param axis the index of the axis on the virtual joystick to update. + * \param value the new value for the specified axis. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetJoystickVirtualAxis(SDL_Joystick *joystick, int axis, Sint16 value); + +/** + * Generate ball motion on an opened virtual joystick. + * + * Please note that values set here will not be applied until the next call to + * SDL_UpdateJoysticks, which can either be called directly, or can be called + * indirectly through various other SDL APIs, including, but not limited to + * the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout, + * SDL_WaitEvent. + * + * \param joystick the virtual joystick on which to set state. + * \param ball the index of the ball on the virtual joystick to update. + * \param xrel the relative motion on the X axis. + * \param yrel the relative motion on the Y axis. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetJoystickVirtualBall(SDL_Joystick *joystick, int ball, Sint16 xrel, Sint16 yrel); + +/** + * Set the state of a button on an opened virtual joystick. + * + * Please note that values set here will not be applied until the next call to + * SDL_UpdateJoysticks, which can either be called directly, or can be called + * indirectly through various other SDL APIs, including, but not limited to + * the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout, + * SDL_WaitEvent. + * + * \param joystick the virtual joystick on which to set state. + * \param button the index of the button on the virtual joystick to update. + * \param down true if the button is pressed, false otherwise. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetJoystickVirtualButton(SDL_Joystick *joystick, int button, bool down); + +/** + * Set the state of a hat on an opened virtual joystick. + * + * Please note that values set here will not be applied until the next call to + * SDL_UpdateJoysticks, which can either be called directly, or can be called + * indirectly through various other SDL APIs, including, but not limited to + * the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout, + * SDL_WaitEvent. + * + * \param joystick the virtual joystick on which to set state. + * \param hat the index of the hat on the virtual joystick to update. + * \param value the new value for the specified hat. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetJoystickVirtualHat(SDL_Joystick *joystick, int hat, Uint8 value); + +/** + * Set touchpad finger state on an opened virtual joystick. + * + * Please note that values set here will not be applied until the next call to + * SDL_UpdateJoysticks, which can either be called directly, or can be called + * indirectly through various other SDL APIs, including, but not limited to + * the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout, + * SDL_WaitEvent. + * + * \param joystick the virtual joystick on which to set state. + * \param touchpad the index of the touchpad on the virtual joystick to + * update. + * \param finger the index of the finger on the touchpad to set. + * \param down true if the finger is pressed, false if the finger is released. + * \param x the x coordinate of the finger on the touchpad, normalized 0 to 1, + * with the origin in the upper left. + * \param y the y coordinate of the finger on the touchpad, normalized 0 to 1, + * with the origin in the upper left. + * \param pressure the pressure of the finger. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetJoystickVirtualTouchpad(SDL_Joystick *joystick, int touchpad, int finger, bool down, float x, float y, float pressure); + +/** + * Send a sensor update for an opened virtual joystick. + * + * Please note that values set here will not be applied until the next call to + * SDL_UpdateJoysticks, which can either be called directly, or can be called + * indirectly through various other SDL APIs, including, but not limited to + * the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout, + * SDL_WaitEvent. + * + * \param joystick the virtual joystick on which to set state. + * \param type the type of the sensor on the virtual joystick to update. + * \param sensor_timestamp a 64-bit timestamp in nanoseconds associated with + * the sensor reading. + * \param data the data associated with the sensor reading. + * \param num_values the number of values pointed to by `data`. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SendJoystickVirtualSensorData(SDL_Joystick *joystick, SDL_SensorType type, Uint64 sensor_timestamp, const float *data, int num_values); + +/** + * Get the properties associated with a joystick. + * + * The following read-only properties are provided by SDL: + * + * - `SDL_PROP_JOYSTICK_CAP_MONO_LED_BOOLEAN`: true if this joystick has an + * LED that has adjustable brightness + * - `SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN`: true if this joystick has an LED + * that has adjustable color + * - `SDL_PROP_JOYSTICK_CAP_PLAYER_LED_BOOLEAN`: true if this joystick has a + * player LED + * - `SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN`: true if this joystick has + * left/right rumble + * - `SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN`: true if this joystick has + * simple trigger rumble + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetJoystickProperties(SDL_Joystick *joystick); + +#define SDL_PROP_JOYSTICK_CAP_MONO_LED_BOOLEAN "SDL.joystick.cap.mono_led" +#define SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN "SDL.joystick.cap.rgb_led" +#define SDL_PROP_JOYSTICK_CAP_PLAYER_LED_BOOLEAN "SDL.joystick.cap.player_led" +#define SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN "SDL.joystick.cap.rumble" +#define SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN "SDL.joystick.cap.trigger_rumble" + +/** + * Get the implementation dependent name of a joystick. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns the name of the selected joystick. If no name can be found, this + * function returns NULL; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickNameForID + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetJoystickName(SDL_Joystick *joystick); + +/** + * Get the implementation dependent path of a joystick. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns the path of the selected joystick. If no path can be found, this + * function returns NULL; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickPathForID + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetJoystickPath(SDL_Joystick *joystick); + +/** + * Get the player index of an opened joystick. + * + * For XInput controllers this returns the XInput user index. Many joysticks + * will not be able to supply this information. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns the player index, or -1 if it's not available. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetJoystickPlayerIndex + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetJoystickPlayerIndex(SDL_Joystick *joystick); + +/** + * Set the player index of an opened joystick. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \param player_index player index to assign to this joystick, or -1 to clear + * the player index and turn off player LEDs. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickPlayerIndex + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetJoystickPlayerIndex(SDL_Joystick *joystick, int player_index); + +/** + * Get the implementation-dependent GUID for the joystick. + * + * This function requires an open joystick. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns the GUID of the given joystick. If called on an invalid index, + * this function returns a zero GUID; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickGUIDForID + * \sa SDL_GUIDToString + */ +extern SDL_DECLSPEC SDL_GUID SDLCALL SDL_GetJoystickGUID(SDL_Joystick *joystick); + +/** + * Get the USB vendor ID of an opened joystick, if available. + * + * If the vendor ID isn't available this function returns 0. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns the USB vendor ID of the selected joystick, or 0 if unavailable. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickVendorForID + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetJoystickVendor(SDL_Joystick *joystick); + +/** + * Get the USB product ID of an opened joystick, if available. + * + * If the product ID isn't available this function returns 0. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns the USB product ID of the selected joystick, or 0 if unavailable. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickProductForID + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetJoystickProduct(SDL_Joystick *joystick); + +/** + * Get the product version of an opened joystick, if available. + * + * If the product version isn't available this function returns 0. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns the product version of the selected joystick, or 0 if unavailable. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickProductVersionForID + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetJoystickProductVersion(SDL_Joystick *joystick); + +/** + * Get the firmware version of an opened joystick, if available. + * + * If the firmware version isn't available this function returns 0. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns the firmware version of the selected joystick, or 0 if + * unavailable. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_GetJoystickFirmwareVersion(SDL_Joystick *joystick); + +/** + * Get the serial number of an opened joystick, if available. + * + * Returns the serial number of the joystick, or NULL if it is not available. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns the serial number of the selected joystick, or NULL if + * unavailable. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetJoystickSerial(SDL_Joystick *joystick); + +/** + * Get the type of an opened joystick. + * + * \param joystick the SDL_Joystick obtained from SDL_OpenJoystick(). + * \returns the SDL_JoystickType of the selected joystick. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickTypeForID + */ +extern SDL_DECLSPEC SDL_JoystickType SDLCALL SDL_GetJoystickType(SDL_Joystick *joystick); + +/** + * Get the device information encoded in a SDL_GUID structure. + * + * \param guid the SDL_GUID you wish to get info about. + * \param vendor a pointer filled in with the device VID, or 0 if not + * available. + * \param product a pointer filled in with the device PID, or 0 if not + * available. + * \param version a pointer filled in with the device version, or 0 if not + * available. + * \param crc16 a pointer filled in with a CRC used to distinguish different + * products with the same VID/PID, or 0 if not available. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickGUIDForID + */ +extern SDL_DECLSPEC void SDLCALL SDL_GetJoystickGUIDInfo(SDL_GUID guid, Uint16 *vendor, Uint16 *product, Uint16 *version, Uint16 *crc16); + +/** + * Get the status of a specified joystick. + * + * \param joystick the joystick to query. + * \returns true if the joystick has been opened, false if it has not; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_JoystickConnected(SDL_Joystick *joystick); + +/** + * Get the instance ID of an opened joystick. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \returns the instance ID of the specified joystick on success or 0 on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_JoystickID SDLCALL SDL_GetJoystickID(SDL_Joystick *joystick); + +/** + * Get the number of general axis controls on a joystick. + * + * Often, the directional pad on a game controller will either look like 4 + * separate buttons or a POV hat, and not axes, but all of this is up to the + * device and platform. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \returns the number of axis controls/number of axes on success or -1 on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickAxis + * \sa SDL_GetNumJoystickBalls + * \sa SDL_GetNumJoystickButtons + * \sa SDL_GetNumJoystickHats + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumJoystickAxes(SDL_Joystick *joystick); + +/** + * Get the number of trackballs on a joystick. + * + * Joystick trackballs have only relative motion events associated with them + * and their state cannot be polled. + * + * Most joysticks do not have trackballs. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \returns the number of trackballs on success or -1 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickBall + * \sa SDL_GetNumJoystickAxes + * \sa SDL_GetNumJoystickButtons + * \sa SDL_GetNumJoystickHats + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumJoystickBalls(SDL_Joystick *joystick); + +/** + * Get the number of POV hats on a joystick. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \returns the number of POV hats on success or -1 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickHat + * \sa SDL_GetNumJoystickAxes + * \sa SDL_GetNumJoystickBalls + * \sa SDL_GetNumJoystickButtons + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumJoystickHats(SDL_Joystick *joystick); + +/** + * Get the number of buttons on a joystick. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \returns the number of buttons on success or -1 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetJoystickButton + * \sa SDL_GetNumJoystickAxes + * \sa SDL_GetNumJoystickBalls + * \sa SDL_GetNumJoystickHats + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumJoystickButtons(SDL_Joystick *joystick); + +/** + * Set the state of joystick event processing. + * + * If joystick events are disabled, you must call SDL_UpdateJoysticks() + * yourself and check the state of the joystick when you want joystick + * information. + * + * \param enabled whether to process joystick events or not. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_JoystickEventsEnabled + * \sa SDL_UpdateJoysticks + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetJoystickEventsEnabled(bool enabled); + +/** + * Query the state of joystick event processing. + * + * If joystick events are disabled, you must call SDL_UpdateJoysticks() + * yourself and check the state of the joystick when you want joystick + * information. + * + * \returns true if joystick events are being processed, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetJoystickEventsEnabled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_JoystickEventsEnabled(void); + +/** + * Update the current state of the open joysticks. + * + * This is called automatically by the event loop if any joystick events are + * enabled. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_UpdateJoysticks(void); + +/** + * Get the current state of an axis control on a joystick. + * + * SDL makes no promises about what part of the joystick any given axis refers + * to. Your game should have some sort of configuration UI to let users + * specify what each axis should be bound to. Alternately, SDL's higher-level + * Game Controller API makes a great effort to apply order to this lower-level + * interface, so you know that a specific axis is the "left thumb stick," etc. + * + * The value returned by SDL_GetJoystickAxis() is a signed integer (-32768 to + * 32767) representing the current position of the axis. It may be necessary + * to impose certain tolerances on these values to account for jitter. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \param axis the axis to query; the axis indices start at index 0. + * \returns a 16-bit signed integer representing the current position of the + * axis or 0 on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumJoystickAxes + */ +extern SDL_DECLSPEC Sint16 SDLCALL SDL_GetJoystickAxis(SDL_Joystick *joystick, int axis); + +/** + * Get the initial state of an axis control on a joystick. + * + * The state is a value ranging from -32768 to 32767. + * + * The axis indices start at index 0. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \param axis the axis to query; the axis indices start at index 0. + * \param state upon return, the initial value is supplied here. + * \returns true if this axis has any initial value, or false if not. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetJoystickAxisInitialState(SDL_Joystick *joystick, int axis, Sint16 *state); + +/** + * Get the ball axis change since the last poll. + * + * Trackballs can only return relative motion since the last call to + * SDL_GetJoystickBall(), these motion deltas are placed into `dx` and `dy`. + * + * Most joysticks do not have trackballs. + * + * \param joystick the SDL_Joystick to query. + * \param ball the ball index to query; ball indices start at index 0. + * \param dx stores the difference in the x axis position since the last poll. + * \param dy stores the difference in the y axis position since the last poll. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumJoystickBalls + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetJoystickBall(SDL_Joystick *joystick, int ball, int *dx, int *dy); + +/** + * Get the current state of a POV hat on a joystick. + * + * The returned value will be one of the `SDL_HAT_*` values. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \param hat the hat index to get the state from; indices start at index 0. + * \returns the current hat position. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumJoystickHats + */ +extern SDL_DECLSPEC Uint8 SDLCALL SDL_GetJoystickHat(SDL_Joystick *joystick, int hat); + +#define SDL_HAT_CENTERED 0x00u +#define SDL_HAT_UP 0x01u +#define SDL_HAT_RIGHT 0x02u +#define SDL_HAT_DOWN 0x04u +#define SDL_HAT_LEFT 0x08u +#define SDL_HAT_RIGHTUP (SDL_HAT_RIGHT|SDL_HAT_UP) +#define SDL_HAT_RIGHTDOWN (SDL_HAT_RIGHT|SDL_HAT_DOWN) +#define SDL_HAT_LEFTUP (SDL_HAT_LEFT|SDL_HAT_UP) +#define SDL_HAT_LEFTDOWN (SDL_HAT_LEFT|SDL_HAT_DOWN) + +/** + * Get the current state of a button on a joystick. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \param button the button index to get the state from; indices start at + * index 0. + * \returns true if the button is pressed, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumJoystickButtons + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetJoystickButton(SDL_Joystick *joystick, int button); + +/** + * Start a rumble effect. + * + * Each call to this function cancels any previous rumble effect, and calling + * it with 0 intensity stops any rumbling. + * + * This function requires you to process SDL events or call + * SDL_UpdateJoysticks() to update rumble state. + * + * \param joystick the joystick to vibrate. + * \param low_frequency_rumble the intensity of the low frequency (left) + * rumble motor, from 0 to 0xFFFF. + * \param high_frequency_rumble the intensity of the high frequency (right) + * rumble motor, from 0 to 0xFFFF. + * \param duration_ms the duration of the rumble effect, in milliseconds. + * \returns true, or false if rumble isn't supported on this joystick. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RumbleJoystick(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms); + +/** + * Start a rumble effect in the joystick's triggers. + * + * Each call to this function cancels any previous trigger rumble effect, and + * calling it with 0 intensity stops any rumbling. + * + * Note that this is rumbling of the _triggers_ and not the game controller as + * a whole. This is currently only supported on Xbox One controllers. If you + * want the (more common) whole-controller rumble, use SDL_RumbleJoystick() + * instead. + * + * This function requires you to process SDL events or call + * SDL_UpdateJoysticks() to update rumble state. + * + * \param joystick the joystick to vibrate. + * \param left_rumble the intensity of the left trigger rumble motor, from 0 + * to 0xFFFF. + * \param right_rumble the intensity of the right trigger rumble motor, from 0 + * to 0xFFFF. + * \param duration_ms the duration of the rumble effect, in milliseconds. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RumbleJoystick + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RumbleJoystickTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms); + +/** + * Update a joystick's LED color. + * + * An example of a joystick LED is the light on the back of a PlayStation 4's + * DualShock 4 controller. + * + * For joysticks with a single color LED, the maximum of the RGB values will + * be used as the LED brightness. + * + * \param joystick the joystick to update. + * \param red the intensity of the red LED. + * \param green the intensity of the green LED. + * \param blue the intensity of the blue LED. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetJoystickLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue); + +/** + * Send a joystick specific effect packet. + * + * \param joystick the joystick to affect. + * \param data the data to send to the joystick. + * \param size the size of the data to send to the joystick. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SendJoystickEffect(SDL_Joystick *joystick, const void *data, int size); + +/** + * Close a joystick previously opened with SDL_OpenJoystick(). + * + * \param joystick the joystick device to close. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenJoystick + */ +extern SDL_DECLSPEC void SDLCALL SDL_CloseJoystick(SDL_Joystick *joystick); + +/** + * Get the connection state of a joystick. + * + * \param joystick the joystick to query. + * \returns the connection state on success or + * `SDL_JOYSTICK_CONNECTION_INVALID` on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_JoystickConnectionState SDLCALL SDL_GetJoystickConnectionState(SDL_Joystick *joystick); + +/** + * Get the battery state of a joystick. + * + * You should never take a battery status as absolute truth. Batteries + * (especially failing batteries) are delicate hardware, and the values + * reported here are best estimates based on what that hardware reports. It's + * not uncommon for older batteries to lose stored power much faster than it + * reports, or completely drain when reporting it has 20 percent left, etc. + * + * \param joystick the joystick to query. + * \param percent a pointer filled in with the percentage of battery life + * left, between 0 and 100, or NULL to ignore. This will be + * filled in with -1 we can't determine a value or there is no + * battery. + * \returns the current battery state or `SDL_POWERSTATE_ERROR` on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PowerState SDLCALL SDL_GetJoystickPowerInfo(SDL_Joystick *joystick, int *percent); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_joystick_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_keyboard.h b/thirdparty/sdl/include/SDL3/SDL_keyboard.h new file mode 100644 index 00000000000..afa77b6c2c3 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_keyboard.h @@ -0,0 +1,609 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryKeyboard + * + * SDL keyboard management. + * + * Please refer to the Best Keyboard Practices document for details on how + * best to accept keyboard input in various types of programs: + * + * https://wiki.libsdl.org/SDL3/BestKeyboardPractices + */ + +#ifndef SDL_keyboard_h_ +#define SDL_keyboard_h_ + +#include +#include +#include +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * This is a unique ID for a keyboard for the time it is connected to the + * system, and is never reused for the lifetime of the application. + * + * If the keyboard is disconnected and reconnected, it will get a new ID. + * + * The value 0 is an invalid ID. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_KeyboardID; + +/* Function prototypes */ + +/** + * Return whether a keyboard is currently connected. + * + * \returns true if a keyboard is connected, false otherwise. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetKeyboards + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasKeyboard(void); + +/** + * Get a list of currently connected keyboards. + * + * Note that this will include any device or virtual driver that includes + * keyboard functionality, including some mice, KVM switches, motherboard + * power buttons, etc. You should wait for input from a device before you + * consider it actively in use. + * + * \param count a pointer filled in with the number of keyboards returned, may + * be NULL. + * \returns a 0 terminated array of keyboards instance IDs or NULL on failure; + * call SDL_GetError() for more information. This should be freed + * with SDL_free() when it is no longer needed. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetKeyboardNameForID + * \sa SDL_HasKeyboard + */ +extern SDL_DECLSPEC SDL_KeyboardID * SDLCALL SDL_GetKeyboards(int *count); + +/** + * Get the name of a keyboard. + * + * This function returns "" if the keyboard doesn't have a name. + * + * \param instance_id the keyboard instance ID. + * \returns the name of the selected keyboard or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetKeyboards + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetKeyboardNameForID(SDL_KeyboardID instance_id); + +/** + * Query the window which currently has keyboard focus. + * + * \returns the window with keyboard focus. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GetKeyboardFocus(void); + +/** + * Get a snapshot of the current state of the keyboard. + * + * The pointer returned is a pointer to an internal SDL array. It will be + * valid for the whole lifetime of the application and should not be freed by + * the caller. + * + * A array element with a value of true means that the key is pressed and a + * value of false means that it is not. Indexes into this array are obtained + * by using SDL_Scancode values. + * + * Use SDL_PumpEvents() to update the state array. + * + * This function gives you the current state after all events have been + * processed, so if a key or button has been pressed and released before you + * process events, then the pressed state will never show up in the + * SDL_GetKeyboardState() calls. + * + * Note: This function doesn't take into account whether shift has been + * pressed or not. + * + * \param numkeys if non-NULL, receives the length of the returned array. + * \returns a pointer to an array of key states. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_PumpEvents + * \sa SDL_ResetKeyboard + */ +extern SDL_DECLSPEC const bool * SDLCALL SDL_GetKeyboardState(int *numkeys); + +/** + * Clear the state of the keyboard. + * + * This function will generate key up events for all pressed keys. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetKeyboardState + */ +extern SDL_DECLSPEC void SDLCALL SDL_ResetKeyboard(void); + +/** + * Get the current key modifier state for the keyboard. + * + * \returns an OR'd combination of the modifier keys for the keyboard. See + * SDL_Keymod for details. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetKeyboardState + * \sa SDL_SetModState + */ +extern SDL_DECLSPEC SDL_Keymod SDLCALL SDL_GetModState(void); + +/** + * Set the current key modifier state for the keyboard. + * + * The inverse of SDL_GetModState(), SDL_SetModState() allows you to impose + * modifier key states on your application. Simply pass your desired modifier + * states into `modstate`. This value may be a bitwise, OR'd combination of + * SDL_Keymod values. + * + * This does not change the keyboard state, only the key modifier flags that + * SDL reports. + * + * \param modstate the desired SDL_Keymod for the keyboard. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetModState + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetModState(SDL_Keymod modstate); + +/** + * Get the key code corresponding to the given scancode according to the + * current keyboard layout. + * + * If you want to get the keycode as it would be delivered in key events, + * including options specified in SDL_HINT_KEYCODE_OPTIONS, then you should + * pass `key_event` as true. Otherwise this function simply translates the + * scancode based on the given modifier state. + * + * \param scancode the desired SDL_Scancode to query. + * \param modstate the modifier state to use when translating the scancode to + * a keycode. + * \param key_event true if the keycode will be used in key events. + * \returns the SDL_Keycode that corresponds to the given SDL_Scancode. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetKeyName + * \sa SDL_GetScancodeFromKey + */ +extern SDL_DECLSPEC SDL_Keycode SDLCALL SDL_GetKeyFromScancode(SDL_Scancode scancode, SDL_Keymod modstate, bool key_event); + +/** + * Get the scancode corresponding to the given key code according to the + * current keyboard layout. + * + * Note that there may be multiple scancode+modifier states that can generate + * this keycode, this will just return the first one found. + * + * \param key the desired SDL_Keycode to query. + * \param modstate a pointer to the modifier state that would be used when the + * scancode generates this key, may be NULL. + * \returns the SDL_Scancode that corresponds to the given SDL_Keycode. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetKeyFromScancode + * \sa SDL_GetScancodeName + */ +extern SDL_DECLSPEC SDL_Scancode SDLCALL SDL_GetScancodeFromKey(SDL_Keycode key, SDL_Keymod *modstate); + +/** + * Set a human-readable name for a scancode. + * + * \param scancode the desired SDL_Scancode. + * \param name the name to use for the scancode, encoded as UTF-8. The string + * is not copied, so the pointer given to this function must stay + * valid while SDL is being used. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetScancodeName + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetScancodeName(SDL_Scancode scancode, const char *name); + +/** + * Get a human-readable name for a scancode. + * + * **Warning**: The returned name is by design not stable across platforms, + * e.g. the name for `SDL_SCANCODE_LGUI` is "Left GUI" under Linux but "Left + * Windows" under Microsoft Windows, and some scancodes like + * `SDL_SCANCODE_NONUSBACKSLASH` don't have any name at all. There are even + * scancodes that share names, e.g. `SDL_SCANCODE_RETURN` and + * `SDL_SCANCODE_RETURN2` (both called "Return"). This function is therefore + * unsuitable for creating a stable cross-platform two-way mapping between + * strings and scancodes. + * + * \param scancode the desired SDL_Scancode to query. + * \returns a pointer to the name for the scancode. If the scancode doesn't + * have a name this function returns an empty string (""). + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetScancodeFromKey + * \sa SDL_GetScancodeFromName + * \sa SDL_SetScancodeName + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetScancodeName(SDL_Scancode scancode); + +/** + * Get a scancode from a human-readable name. + * + * \param name the human-readable scancode name. + * \returns the SDL_Scancode, or `SDL_SCANCODE_UNKNOWN` if the name wasn't + * recognized; call SDL_GetError() for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetKeyFromName + * \sa SDL_GetScancodeFromKey + * \sa SDL_GetScancodeName + */ +extern SDL_DECLSPEC SDL_Scancode SDLCALL SDL_GetScancodeFromName(const char *name); + +/** + * Get a human-readable name for a key. + * + * If the key doesn't have a name, this function returns an empty string (""). + * + * Letters will be presented in their uppercase form, if applicable. + * + * \param key the desired SDL_Keycode to query. + * \returns a UTF-8 encoded string of the key name. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetKeyFromName + * \sa SDL_GetKeyFromScancode + * \sa SDL_GetScancodeFromKey + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetKeyName(SDL_Keycode key); + +/** + * Get a key code from a human-readable name. + * + * \param name the human-readable key name. + * \returns key code, or `SDLK_UNKNOWN` if the name wasn't recognized; call + * SDL_GetError() for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetKeyFromScancode + * \sa SDL_GetKeyName + * \sa SDL_GetScancodeFromName + */ +extern SDL_DECLSPEC SDL_Keycode SDLCALL SDL_GetKeyFromName(const char *name); + +/** + * Start accepting Unicode text input events in a window. + * + * This function will enable text input (SDL_EVENT_TEXT_INPUT and + * SDL_EVENT_TEXT_EDITING events) in the specified window. Please use this + * function paired with SDL_StopTextInput(). + * + * Text input events are not received by default. + * + * On some platforms using this function shows the screen keyboard and/or + * activates an IME, which can prevent some key press events from being passed + * through. + * + * \param window the window to enable text input. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetTextInputArea + * \sa SDL_StartTextInputWithProperties + * \sa SDL_StopTextInput + * \sa SDL_TextInputActive + */ +extern SDL_DECLSPEC bool SDLCALL SDL_StartTextInput(SDL_Window *window); + +/** + * Text input type. + * + * These are the valid values for SDL_PROP_TEXTINPUT_TYPE_NUMBER. Not every + * value is valid on every platform, but where a value isn't supported, a + * reasonable fallback will be used. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_StartTextInputWithProperties + */ +typedef enum SDL_TextInputType +{ + SDL_TEXTINPUT_TYPE_TEXT, /**< The input is text */ + SDL_TEXTINPUT_TYPE_TEXT_NAME, /**< The input is a person's name */ + SDL_TEXTINPUT_TYPE_TEXT_EMAIL, /**< The input is an e-mail address */ + SDL_TEXTINPUT_TYPE_TEXT_USERNAME, /**< The input is a username */ + SDL_TEXTINPUT_TYPE_TEXT_PASSWORD_HIDDEN, /**< The input is a secure password that is hidden */ + SDL_TEXTINPUT_TYPE_TEXT_PASSWORD_VISIBLE, /**< The input is a secure password that is visible */ + SDL_TEXTINPUT_TYPE_NUMBER, /**< The input is a number */ + SDL_TEXTINPUT_TYPE_NUMBER_PASSWORD_HIDDEN, /**< The input is a secure PIN that is hidden */ + SDL_TEXTINPUT_TYPE_NUMBER_PASSWORD_VISIBLE /**< The input is a secure PIN that is visible */ +} SDL_TextInputType; + +/** + * Auto capitalization type. + * + * These are the valid values for SDL_PROP_TEXTINPUT_CAPITALIZATION_NUMBER. + * Not every value is valid on every platform, but where a value isn't + * supported, a reasonable fallback will be used. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_StartTextInputWithProperties + */ +typedef enum SDL_Capitalization +{ + SDL_CAPITALIZE_NONE, /**< No auto-capitalization will be done */ + SDL_CAPITALIZE_SENTENCES, /**< The first letter of sentences will be capitalized */ + SDL_CAPITALIZE_WORDS, /**< The first letter of words will be capitalized */ + SDL_CAPITALIZE_LETTERS /**< All letters will be capitalized */ +} SDL_Capitalization; + +/** + * Start accepting Unicode text input events in a window, with properties + * describing the input. + * + * This function will enable text input (SDL_EVENT_TEXT_INPUT and + * SDL_EVENT_TEXT_EDITING events) in the specified window. Please use this + * function paired with SDL_StopTextInput(). + * + * Text input events are not received by default. + * + * On some platforms using this function shows the screen keyboard and/or + * activates an IME, which can prevent some key press events from being passed + * through. + * + * These are the supported properties: + * + * - `SDL_PROP_TEXTINPUT_TYPE_NUMBER` - an SDL_TextInputType value that + * describes text being input, defaults to SDL_TEXTINPUT_TYPE_TEXT. + * - `SDL_PROP_TEXTINPUT_CAPITALIZATION_NUMBER` - an SDL_Capitalization value + * that describes how text should be capitalized, defaults to + * SDL_CAPITALIZE_SENTENCES for normal text entry, SDL_CAPITALIZE_WORDS for + * SDL_TEXTINPUT_TYPE_TEXT_NAME, and SDL_CAPITALIZE_NONE for e-mail + * addresses, usernames, and passwords. + * - `SDL_PROP_TEXTINPUT_AUTOCORRECT_BOOLEAN` - true to enable auto completion + * and auto correction, defaults to true. + * - `SDL_PROP_TEXTINPUT_MULTILINE_BOOLEAN` - true if multiple lines of text + * are allowed. This defaults to true if SDL_HINT_RETURN_KEY_HIDES_IME is + * "0" or is not set, and defaults to false if SDL_HINT_RETURN_KEY_HIDES_IME + * is "1". + * + * On Android you can directly specify the input type: + * + * - `SDL_PROP_TEXTINPUT_ANDROID_INPUTTYPE_NUMBER` - the text input type to + * use, overriding other properties. This is documented at + * https://developer.android.com/reference/android/text/InputType + * + * \param window the window to enable text input. + * \param props the properties to use. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetTextInputArea + * \sa SDL_StartTextInput + * \sa SDL_StopTextInput + * \sa SDL_TextInputActive + */ +extern SDL_DECLSPEC bool SDLCALL SDL_StartTextInputWithProperties(SDL_Window *window, SDL_PropertiesID props); + +#define SDL_PROP_TEXTINPUT_TYPE_NUMBER "SDL.textinput.type" +#define SDL_PROP_TEXTINPUT_CAPITALIZATION_NUMBER "SDL.textinput.capitalization" +#define SDL_PROP_TEXTINPUT_AUTOCORRECT_BOOLEAN "SDL.textinput.autocorrect" +#define SDL_PROP_TEXTINPUT_MULTILINE_BOOLEAN "SDL.textinput.multiline" +#define SDL_PROP_TEXTINPUT_ANDROID_INPUTTYPE_NUMBER "SDL.textinput.android.inputtype" + +/** + * Check whether or not Unicode text input events are enabled for a window. + * + * \param window the window to check. + * \returns true if text input events are enabled else false. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StartTextInput + */ +extern SDL_DECLSPEC bool SDLCALL SDL_TextInputActive(SDL_Window *window); + +/** + * Stop receiving any text input events in a window. + * + * If SDL_StartTextInput() showed the screen keyboard, this function will hide + * it. + * + * \param window the window to disable text input. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StartTextInput + */ +extern SDL_DECLSPEC bool SDLCALL SDL_StopTextInput(SDL_Window *window); + +/** + * Dismiss the composition window/IME without disabling the subsystem. + * + * \param window the window to affect. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StartTextInput + * \sa SDL_StopTextInput + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ClearComposition(SDL_Window *window); + +/** + * Set the area used to type Unicode text input. + * + * Native input methods may place a window with word suggestions near the + * cursor, without covering the text being entered. + * + * \param window the window for which to set the text input area. + * \param rect the SDL_Rect representing the text input area, in window + * coordinates, or NULL to clear it. + * \param cursor the offset of the current cursor location relative to + * `rect->x`, in window coordinates. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextInputArea + * \sa SDL_StartTextInput + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetTextInputArea(SDL_Window *window, const SDL_Rect *rect, int cursor); + +/** + * Get the area used to type Unicode text input. + * + * This returns the values previously set by SDL_SetTextInputArea(). + * + * \param window the window for which to query the text input area. + * \param rect a pointer to an SDL_Rect filled in with the text input area, + * may be NULL. + * \param cursor a pointer to the offset of the current cursor location + * relative to `rect->x`, may be NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetTextInputArea + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetTextInputArea(SDL_Window *window, SDL_Rect *rect, int *cursor); + +/** + * Check whether the platform has screen keyboard support. + * + * \returns true if the platform has some screen keyboard support or false if + * not. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StartTextInput + * \sa SDL_ScreenKeyboardShown + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasScreenKeyboardSupport(void); + +/** + * Check whether the screen keyboard is shown for given window. + * + * \param window the window for which screen keyboard should be queried. + * \returns true if screen keyboard is shown or false if not. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasScreenKeyboardSupport + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ScreenKeyboardShown(SDL_Window *window); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_keyboard_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_keycode.h b/thirdparty/sdl/include/SDL3/SDL_keycode.h new file mode 100644 index 00000000000..61b68e794f8 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_keycode.h @@ -0,0 +1,343 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryKeycode + * + * Defines constants which identify keyboard keys and modifiers. + * + * Please refer to the Best Keyboard Practices document for details on what + * this information means and how best to use it. + * + * https://wiki.libsdl.org/SDL3/BestKeyboardPractices + */ + +#ifndef SDL_keycode_h_ +#define SDL_keycode_h_ + +#include +#include + +/** + * The SDL virtual key representation. + * + * Values of this type are used to represent keyboard keys using the current + * layout of the keyboard. These values include Unicode values representing + * the unmodified character that would be generated by pressing the key, or an + * `SDLK_*` constant for those keys that do not generate characters. + * + * A special exception is the number keys at the top of the keyboard which map + * to SDLK_0...SDLK_9 on AZERTY layouts. + * + * Keys with the `SDLK_EXTENDED_MASK` bit set do not map to a scancode or + * unicode code point. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_Keycode; + +#define SDLK_EXTENDED_MASK (1u << 29) +#define SDLK_SCANCODE_MASK (1u << 30) +#define SDL_SCANCODE_TO_KEYCODE(X) (X | SDLK_SCANCODE_MASK) +#define SDLK_UNKNOWN 0x00000000u /**< 0 */ +#define SDLK_RETURN 0x0000000du /**< '\r' */ +#define SDLK_ESCAPE 0x0000001bu /**< '\x1B' */ +#define SDLK_BACKSPACE 0x00000008u /**< '\b' */ +#define SDLK_TAB 0x00000009u /**< '\t' */ +#define SDLK_SPACE 0x00000020u /**< ' ' */ +#define SDLK_EXCLAIM 0x00000021u /**< '!' */ +#define SDLK_DBLAPOSTROPHE 0x00000022u /**< '"' */ +#define SDLK_HASH 0x00000023u /**< '#' */ +#define SDLK_DOLLAR 0x00000024u /**< '$' */ +#define SDLK_PERCENT 0x00000025u /**< '%' */ +#define SDLK_AMPERSAND 0x00000026u /**< '&' */ +#define SDLK_APOSTROPHE 0x00000027u /**< '\'' */ +#define SDLK_LEFTPAREN 0x00000028u /**< '(' */ +#define SDLK_RIGHTPAREN 0x00000029u /**< ')' */ +#define SDLK_ASTERISK 0x0000002au /**< '*' */ +#define SDLK_PLUS 0x0000002bu /**< '+' */ +#define SDLK_COMMA 0x0000002cu /**< ',' */ +#define SDLK_MINUS 0x0000002du /**< '-' */ +#define SDLK_PERIOD 0x0000002eu /**< '.' */ +#define SDLK_SLASH 0x0000002fu /**< '/' */ +#define SDLK_0 0x00000030u /**< '0' */ +#define SDLK_1 0x00000031u /**< '1' */ +#define SDLK_2 0x00000032u /**< '2' */ +#define SDLK_3 0x00000033u /**< '3' */ +#define SDLK_4 0x00000034u /**< '4' */ +#define SDLK_5 0x00000035u /**< '5' */ +#define SDLK_6 0x00000036u /**< '6' */ +#define SDLK_7 0x00000037u /**< '7' */ +#define SDLK_8 0x00000038u /**< '8' */ +#define SDLK_9 0x00000039u /**< '9' */ +#define SDLK_COLON 0x0000003au /**< ':' */ +#define SDLK_SEMICOLON 0x0000003bu /**< ';' */ +#define SDLK_LESS 0x0000003cu /**< '<' */ +#define SDLK_EQUALS 0x0000003du /**< '=' */ +#define SDLK_GREATER 0x0000003eu /**< '>' */ +#define SDLK_QUESTION 0x0000003fu /**< '?' */ +#define SDLK_AT 0x00000040u /**< '@' */ +#define SDLK_LEFTBRACKET 0x0000005bu /**< '[' */ +#define SDLK_BACKSLASH 0x0000005cu /**< '\\' */ +#define SDLK_RIGHTBRACKET 0x0000005du /**< ']' */ +#define SDLK_CARET 0x0000005eu /**< '^' */ +#define SDLK_UNDERSCORE 0x0000005fu /**< '_' */ +#define SDLK_GRAVE 0x00000060u /**< '`' */ +#define SDLK_A 0x00000061u /**< 'a' */ +#define SDLK_B 0x00000062u /**< 'b' */ +#define SDLK_C 0x00000063u /**< 'c' */ +#define SDLK_D 0x00000064u /**< 'd' */ +#define SDLK_E 0x00000065u /**< 'e' */ +#define SDLK_F 0x00000066u /**< 'f' */ +#define SDLK_G 0x00000067u /**< 'g' */ +#define SDLK_H 0x00000068u /**< 'h' */ +#define SDLK_I 0x00000069u /**< 'i' */ +#define SDLK_J 0x0000006au /**< 'j' */ +#define SDLK_K 0x0000006bu /**< 'k' */ +#define SDLK_L 0x0000006cu /**< 'l' */ +#define SDLK_M 0x0000006du /**< 'm' */ +#define SDLK_N 0x0000006eu /**< 'n' */ +#define SDLK_O 0x0000006fu /**< 'o' */ +#define SDLK_P 0x00000070u /**< 'p' */ +#define SDLK_Q 0x00000071u /**< 'q' */ +#define SDLK_R 0x00000072u /**< 'r' */ +#define SDLK_S 0x00000073u /**< 's' */ +#define SDLK_T 0x00000074u /**< 't' */ +#define SDLK_U 0x00000075u /**< 'u' */ +#define SDLK_V 0x00000076u /**< 'v' */ +#define SDLK_W 0x00000077u /**< 'w' */ +#define SDLK_X 0x00000078u /**< 'x' */ +#define SDLK_Y 0x00000079u /**< 'y' */ +#define SDLK_Z 0x0000007au /**< 'z' */ +#define SDLK_LEFTBRACE 0x0000007bu /**< '{' */ +#define SDLK_PIPE 0x0000007cu /**< '|' */ +#define SDLK_RIGHTBRACE 0x0000007du /**< '}' */ +#define SDLK_TILDE 0x0000007eu /**< '~' */ +#define SDLK_DELETE 0x0000007fu /**< '\x7F' */ +#define SDLK_PLUSMINUS 0x000000b1u /**< '\xB1' */ +#define SDLK_CAPSLOCK 0x40000039u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CAPSLOCK) */ +#define SDLK_F1 0x4000003au /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F1) */ +#define SDLK_F2 0x4000003bu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F2) */ +#define SDLK_F3 0x4000003cu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F3) */ +#define SDLK_F4 0x4000003du /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F4) */ +#define SDLK_F5 0x4000003eu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F5) */ +#define SDLK_F6 0x4000003fu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F6) */ +#define SDLK_F7 0x40000040u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F7) */ +#define SDLK_F8 0x40000041u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F8) */ +#define SDLK_F9 0x40000042u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F9) */ +#define SDLK_F10 0x40000043u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F10) */ +#define SDLK_F11 0x40000044u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F11) */ +#define SDLK_F12 0x40000045u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F12) */ +#define SDLK_PRINTSCREEN 0x40000046u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRINTSCREEN) */ +#define SDLK_SCROLLLOCK 0x40000047u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SCROLLLOCK) */ +#define SDLK_PAUSE 0x40000048u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAUSE) */ +#define SDLK_INSERT 0x40000049u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INSERT) */ +#define SDLK_HOME 0x4000004au /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HOME) */ +#define SDLK_PAGEUP 0x4000004bu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEUP) */ +#define SDLK_END 0x4000004du /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_END) */ +#define SDLK_PAGEDOWN 0x4000004eu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEDOWN) */ +#define SDLK_RIGHT 0x4000004fu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RIGHT) */ +#define SDLK_LEFT 0x40000050u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LEFT) */ +#define SDLK_DOWN 0x40000051u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DOWN) */ +#define SDLK_UP 0x40000052u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UP) */ +#define SDLK_NUMLOCKCLEAR 0x40000053u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_NUMLOCKCLEAR) */ +#define SDLK_KP_DIVIDE 0x40000054u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DIVIDE) */ +#define SDLK_KP_MULTIPLY 0x40000055u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MULTIPLY) */ +#define SDLK_KP_MINUS 0x40000056u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MINUS) */ +#define SDLK_KP_PLUS 0x40000057u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUS) */ +#define SDLK_KP_ENTER 0x40000058u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_ENTER) */ +#define SDLK_KP_1 0x40000059u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_1) */ +#define SDLK_KP_2 0x4000005au /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_2) */ +#define SDLK_KP_3 0x4000005bu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_3) */ +#define SDLK_KP_4 0x4000005cu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_4) */ +#define SDLK_KP_5 0x4000005du /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_5) */ +#define SDLK_KP_6 0x4000005eu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_6) */ +#define SDLK_KP_7 0x4000005fu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_7) */ +#define SDLK_KP_8 0x40000060u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_8) */ +#define SDLK_KP_9 0x40000061u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_9) */ +#define SDLK_KP_0 0x40000062u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_0) */ +#define SDLK_KP_PERIOD 0x40000063u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERIOD) */ +#define SDLK_APPLICATION 0x40000065u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APPLICATION) */ +#define SDLK_POWER 0x40000066u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_POWER) */ +#define SDLK_KP_EQUALS 0x40000067u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALS) */ +#define SDLK_F13 0x40000068u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F13) */ +#define SDLK_F14 0x40000069u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F14) */ +#define SDLK_F15 0x4000006au /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F15) */ +#define SDLK_F16 0x4000006bu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F16) */ +#define SDLK_F17 0x4000006cu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F17) */ +#define SDLK_F18 0x4000006du /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F18) */ +#define SDLK_F19 0x4000006eu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F19) */ +#define SDLK_F20 0x4000006fu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F20) */ +#define SDLK_F21 0x40000070u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F21) */ +#define SDLK_F22 0x40000071u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F22) */ +#define SDLK_F23 0x40000072u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F23) */ +#define SDLK_F24 0x40000073u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F24) */ +#define SDLK_EXECUTE 0x40000074u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXECUTE) */ +#define SDLK_HELP 0x40000075u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HELP) */ +#define SDLK_MENU 0x40000076u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MENU) */ +#define SDLK_SELECT 0x40000077u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SELECT) */ +#define SDLK_STOP 0x40000078u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_STOP) */ +#define SDLK_AGAIN 0x40000079u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AGAIN) */ +#define SDLK_UNDO 0x4000007au /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UNDO) */ +#define SDLK_CUT 0x4000007bu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CUT) */ +#define SDLK_COPY 0x4000007cu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COPY) */ +#define SDLK_PASTE 0x4000007du /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PASTE) */ +#define SDLK_FIND 0x4000007eu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_FIND) */ +#define SDLK_MUTE 0x4000007fu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MUTE) */ +#define SDLK_VOLUMEUP 0x40000080u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEUP) */ +#define SDLK_VOLUMEDOWN 0x40000081u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEDOWN) */ +#define SDLK_KP_COMMA 0x40000085u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COMMA) */ +#define SDLK_KP_EQUALSAS400 0x40000086u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALSAS400) */ +#define SDLK_ALTERASE 0x40000099u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_ALTERASE) */ +#define SDLK_SYSREQ 0x4000009au /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SYSREQ) */ +#define SDLK_CANCEL 0x4000009bu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CANCEL) */ +#define SDLK_CLEAR 0x4000009cu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEAR) */ +#define SDLK_PRIOR 0x4000009du /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRIOR) */ +#define SDLK_RETURN2 0x4000009eu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RETURN2) */ +#define SDLK_SEPARATOR 0x4000009fu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SEPARATOR) */ +#define SDLK_OUT 0x400000a0u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OUT) */ +#define SDLK_OPER 0x400000a1u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OPER) */ +#define SDLK_CLEARAGAIN 0x400000a2u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEARAGAIN) */ +#define SDLK_CRSEL 0x400000a3u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CRSEL) */ +#define SDLK_EXSEL 0x400000a4u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXSEL) */ +#define SDLK_KP_00 0x400000b0u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_00) */ +#define SDLK_KP_000 0x400000b1u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_000) */ +#define SDLK_THOUSANDSSEPARATOR 0x400000b2u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_THOUSANDSSEPARATOR) */ +#define SDLK_DECIMALSEPARATOR 0x400000b3u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DECIMALSEPARATOR) */ +#define SDLK_CURRENCYUNIT 0x400000b4u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYUNIT) */ +#define SDLK_CURRENCYSUBUNIT 0x400000b5u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYSUBUNIT) */ +#define SDLK_KP_LEFTPAREN 0x400000b6u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTPAREN) */ +#define SDLK_KP_RIGHTPAREN 0x400000b7u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTPAREN) */ +#define SDLK_KP_LEFTBRACE 0x400000b8u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTBRACE) */ +#define SDLK_KP_RIGHTBRACE 0x400000b9u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTBRACE) */ +#define SDLK_KP_TAB 0x400000bau /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_TAB) */ +#define SDLK_KP_BACKSPACE 0x400000bbu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BACKSPACE) */ +#define SDLK_KP_A 0x400000bcu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_A) */ +#define SDLK_KP_B 0x400000bdu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_B) */ +#define SDLK_KP_C 0x400000beu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_C) */ +#define SDLK_KP_D 0x400000bfu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_D) */ +#define SDLK_KP_E 0x400000c0u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_E) */ +#define SDLK_KP_F 0x400000c1u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_F) */ +#define SDLK_KP_XOR 0x400000c2u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_XOR) */ +#define SDLK_KP_POWER 0x400000c3u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_POWER) */ +#define SDLK_KP_PERCENT 0x400000c4u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERCENT) */ +#define SDLK_KP_LESS 0x400000c5u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LESS) */ +#define SDLK_KP_GREATER 0x400000c6u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_GREATER) */ +#define SDLK_KP_AMPERSAND 0x400000c7u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AMPERSAND) */ +#define SDLK_KP_DBLAMPERSAND 0x400000c8u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLAMPERSAND) */ +#define SDLK_KP_VERTICALBAR 0x400000c9u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_VERTICALBAR) */ +#define SDLK_KP_DBLVERTICALBAR 0x400000cau /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLVERTICALBAR) */ +#define SDLK_KP_COLON 0x400000cbu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COLON) */ +#define SDLK_KP_HASH 0x400000ccu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HASH) */ +#define SDLK_KP_SPACE 0x400000cdu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_SPACE) */ +#define SDLK_KP_AT 0x400000ceu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AT) */ +#define SDLK_KP_EXCLAM 0x400000cfu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EXCLAM) */ +#define SDLK_KP_MEMSTORE 0x400000d0u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSTORE) */ +#define SDLK_KP_MEMRECALL 0x400000d1u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMRECALL) */ +#define SDLK_KP_MEMCLEAR 0x400000d2u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMCLEAR) */ +#define SDLK_KP_MEMADD 0x400000d3u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMADD) */ +#define SDLK_KP_MEMSUBTRACT 0x400000d4u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSUBTRACT) */ +#define SDLK_KP_MEMMULTIPLY 0x400000d5u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMMULTIPLY) */ +#define SDLK_KP_MEMDIVIDE 0x400000d6u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMDIVIDE) */ +#define SDLK_KP_PLUSMINUS 0x400000d7u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUSMINUS) */ +#define SDLK_KP_CLEAR 0x400000d8u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEAR) */ +#define SDLK_KP_CLEARENTRY 0x400000d9u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEARENTRY) */ +#define SDLK_KP_BINARY 0x400000dau /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BINARY) */ +#define SDLK_KP_OCTAL 0x400000dbu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_OCTAL) */ +#define SDLK_KP_DECIMAL 0x400000dcu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DECIMAL) */ +#define SDLK_KP_HEXADECIMAL 0x400000ddu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HEXADECIMAL) */ +#define SDLK_LCTRL 0x400000e0u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LCTRL) */ +#define SDLK_LSHIFT 0x400000e1u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LSHIFT) */ +#define SDLK_LALT 0x400000e2u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LALT) */ +#define SDLK_LGUI 0x400000e3u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LGUI) */ +#define SDLK_RCTRL 0x400000e4u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RCTRL) */ +#define SDLK_RSHIFT 0x400000e5u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RSHIFT) */ +#define SDLK_RALT 0x400000e6u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RALT) */ +#define SDLK_RGUI 0x400000e7u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RGUI) */ +#define SDLK_MODE 0x40000101u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MODE) */ +#define SDLK_SLEEP 0x40000102u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SLEEP) */ +#define SDLK_WAKE 0x40000103u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_WAKE) */ +#define SDLK_CHANNEL_INCREMENT 0x40000104u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CHANNEL_INCREMENT) */ +#define SDLK_CHANNEL_DECREMENT 0x40000105u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CHANNEL_DECREMENT) */ +#define SDLK_MEDIA_PLAY 0x40000106u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_PLAY) */ +#define SDLK_MEDIA_PAUSE 0x40000107u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_PAUSE) */ +#define SDLK_MEDIA_RECORD 0x40000108u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_RECORD) */ +#define SDLK_MEDIA_FAST_FORWARD 0x40000109u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_FAST_FORWARD) */ +#define SDLK_MEDIA_REWIND 0x4000010au /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_REWIND) */ +#define SDLK_MEDIA_NEXT_TRACK 0x4000010bu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_NEXT_TRACK) */ +#define SDLK_MEDIA_PREVIOUS_TRACK 0x4000010cu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_PREVIOUS_TRACK) */ +#define SDLK_MEDIA_STOP 0x4000010du /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_STOP) */ +#define SDLK_MEDIA_EJECT 0x4000010eu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_EJECT) */ +#define SDLK_MEDIA_PLAY_PAUSE 0x4000010fu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_PLAY_PAUSE) */ +#define SDLK_MEDIA_SELECT 0x40000110u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIA_SELECT) */ +#define SDLK_AC_NEW 0x40000111u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_NEW) */ +#define SDLK_AC_OPEN 0x40000112u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_OPEN) */ +#define SDLK_AC_CLOSE 0x40000113u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_CLOSE) */ +#define SDLK_AC_EXIT 0x40000114u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_EXIT) */ +#define SDLK_AC_SAVE 0x40000115u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_SAVE) */ +#define SDLK_AC_PRINT 0x40000116u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_PRINT) */ +#define SDLK_AC_PROPERTIES 0x40000117u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_PROPERTIES) */ +#define SDLK_AC_SEARCH 0x40000118u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_SEARCH) */ +#define SDLK_AC_HOME 0x40000119u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_HOME) */ +#define SDLK_AC_BACK 0x4000011au /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BACK) */ +#define SDLK_AC_FORWARD 0x4000011bu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_FORWARD) */ +#define SDLK_AC_STOP 0x4000011cu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_STOP) */ +#define SDLK_AC_REFRESH 0x4000011du /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_REFRESH) */ +#define SDLK_AC_BOOKMARKS 0x4000011eu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BOOKMARKS) */ +#define SDLK_SOFTLEFT 0x4000011fu /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SOFTLEFT) */ +#define SDLK_SOFTRIGHT 0x40000120u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SOFTRIGHT) */ +#define SDLK_CALL 0x40000121u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CALL) */ +#define SDLK_ENDCALL 0x40000122u /**< SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_ENDCALL) */ +#define SDLK_LEFT_TAB 0x20000001u /**< Extended key Left Tab */ +#define SDLK_LEVEL5_SHIFT 0x20000002u /**< Extended key Level 5 Shift */ +#define SDLK_MULTI_KEY_COMPOSE 0x20000003u /**< Extended key Multi-key Compose */ +#define SDLK_LMETA 0x20000004u /**< Extended key Left Meta */ +#define SDLK_RMETA 0x20000005u /**< Extended key Right Meta */ +#define SDLK_LHYPER 0x20000006u /**< Extended key Left Hyper */ +#define SDLK_RHYPER 0x20000007u /**< Extended key Right Hyper */ + +/** + * Valid key modifiers (possibly OR'd together). + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint16 SDL_Keymod; + +#define SDL_KMOD_NONE 0x0000u /**< no modifier is applicable. */ +#define SDL_KMOD_LSHIFT 0x0001u /**< the left Shift key is down. */ +#define SDL_KMOD_RSHIFT 0x0002u /**< the right Shift key is down. */ +#define SDL_KMOD_LEVEL5 0x0004u /**< the Level 5 Shift key is down. */ +#define SDL_KMOD_LCTRL 0x0040u /**< the left Ctrl (Control) key is down. */ +#define SDL_KMOD_RCTRL 0x0080u /**< the right Ctrl (Control) key is down. */ +#define SDL_KMOD_LALT 0x0100u /**< the left Alt key is down. */ +#define SDL_KMOD_RALT 0x0200u /**< the right Alt key is down. */ +#define SDL_KMOD_LGUI 0x0400u /**< the left GUI key (often the Windows key) is down. */ +#define SDL_KMOD_RGUI 0x0800u /**< the right GUI key (often the Windows key) is down. */ +#define SDL_KMOD_NUM 0x1000u /**< the Num Lock key (may be located on an extended keypad) is down. */ +#define SDL_KMOD_CAPS 0x2000u /**< the Caps Lock key is down. */ +#define SDL_KMOD_MODE 0x4000u /**< the !AltGr key is down. */ +#define SDL_KMOD_SCROLL 0x8000u /**< the Scroll Lock key is down. */ +#define SDL_KMOD_CTRL (SDL_KMOD_LCTRL | SDL_KMOD_RCTRL) /**< Any Ctrl key is down. */ +#define SDL_KMOD_SHIFT (SDL_KMOD_LSHIFT | SDL_KMOD_RSHIFT) /**< Any Shift key is down. */ +#define SDL_KMOD_ALT (SDL_KMOD_LALT | SDL_KMOD_RALT) /**< Any Alt key is down. */ +#define SDL_KMOD_GUI (SDL_KMOD_LGUI | SDL_KMOD_RGUI) /**< Any GUI key is down. */ + +#endif /* SDL_keycode_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_loadso.h b/thirdparty/sdl/include/SDL3/SDL_loadso.h new file mode 100644 index 00000000000..f8649d75801 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_loadso.h @@ -0,0 +1,145 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: SharedObject */ + +/** + * # CategorySharedObject + * + * System-dependent library loading routines. + * + * Shared objects are code that is programmatically loadable at runtime. + * Windows calls these "DLLs", Linux calls them "shared libraries", etc. + * + * To use them, build such a library, then call SDL_LoadObject() on it. Once + * loaded, you can use SDL_LoadFunction() on that object to find the address + * of its exported symbols. When done with the object, call SDL_UnloadObject() + * to dispose of it. + * + * Some things to keep in mind: + * + * - These functions only work on C function names. Other languages may have + * name mangling and intrinsic language support that varies from compiler to + * compiler. + * - Make sure you declare your function pointers with the same calling + * convention as the actual library function. Your code will crash + * mysteriously if you do not do this. + * - Avoid namespace collisions. If you load a symbol from the library, it is + * not defined whether or not it goes into the global symbol namespace for + * the application. If it does and it conflicts with symbols in your code or + * other shared libraries, you will not get the results you expect. :) + * - Once a library is unloaded, all pointers into it obtained through + * SDL_LoadFunction() become invalid, even if the library is later reloaded. + * Don't unload a library if you plan to use these pointers in the future. + * Notably: beware of giving one of these pointers to atexit(), since it may + * call that pointer after the library unloads. + */ + +#ifndef SDL_loadso_h_ +#define SDL_loadso_h_ + +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * An opaque datatype that represents a loaded shared object. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_LoadObject + * \sa SDL_LoadFunction + * \sa SDL_UnloadObject + */ +typedef struct SDL_SharedObject SDL_SharedObject; + +/** + * Dynamically load a shared object. + * + * \param sofile a system-dependent name of the object file. + * \returns an opaque pointer to the object handle or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LoadFunction + * \sa SDL_UnloadObject + */ +extern SDL_DECLSPEC SDL_SharedObject * SDLCALL SDL_LoadObject(const char *sofile); + +/** + * Look up the address of the named function in a shared object. + * + * This function pointer is no longer valid after calling SDL_UnloadObject(). + * + * This function can only look up C function names. Other languages may have + * name mangling and intrinsic language support that varies from compiler to + * compiler. + * + * Make sure you declare your function pointers with the same calling + * convention as the actual library function. Your code will crash + * mysteriously if you do not do this. + * + * If the requested function doesn't exist, NULL is returned. + * + * \param handle a valid shared object handle returned by SDL_LoadObject(). + * \param name the name of the function to look up. + * \returns a pointer to the function or NULL on failure; call SDL_GetError() + * for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LoadObject + */ +extern SDL_DECLSPEC SDL_FunctionPointer SDLCALL SDL_LoadFunction(SDL_SharedObject *handle, const char *name); + +/** + * Unload a shared object from memory. + * + * Note that any pointers from this object looked up through + * SDL_LoadFunction() will no longer be valid. + * + * \param handle a valid shared object handle returned by SDL_LoadObject(). + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LoadObject + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnloadObject(SDL_SharedObject *handle); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_loadso_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_locale.h b/thirdparty/sdl/include/SDL3/SDL_locale.h new file mode 100644 index 00000000000..902843e81f3 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_locale.h @@ -0,0 +1,117 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryLocale + * + * SDL locale services. + * + * This provides a way to get a list of preferred locales (language plus + * country) for the user. There is exactly one function: + * SDL_GetPreferredLocales(), which handles all the heavy lifting, and offers + * documentation on all the strange ways humans might have configured their + * language settings. + */ + +#ifndef SDL_locale_h +#define SDL_locale_h + +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +/** + * A struct to provide locale data. + * + * Locale data is split into a spoken language, like English, and an optional + * country, like Canada. The language will be in ISO-639 format (so English + * would be "en"), and the country, if not NULL, will be an ISO-3166 country + * code (so Canada would be "CA"). + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPreferredLocales + */ +typedef struct SDL_Locale +{ + const char *language; /**< A language name, like "en" for English. */ + const char *country; /**< A country, like "US" for America. Can be NULL. */ +} SDL_Locale; + +/** + * Report the user's preferred locale. + * + * Returned language strings are in the format xx, where 'xx' is an ISO-639 + * language specifier (such as "en" for English, "de" for German, etc). + * Country strings are in the format YY, where "YY" is an ISO-3166 country + * code (such as "US" for the United States, "CA" for Canada, etc). Country + * might be NULL if there's no specific guidance on them (so you might get { + * "en", "US" } for American English, but { "en", NULL } means "English + * language, generically"). Language strings are never NULL, except to + * terminate the array. + * + * Please note that not all of these strings are 2 characters; some are three + * or more. + * + * The returned list of locales are in the order of the user's preference. For + * example, a German citizen that is fluent in US English and knows enough + * Japanese to navigate around Tokyo might have a list like: { "de", "en_US", + * "jp", NULL }. Someone from England might prefer British English (where + * "color" is spelled "colour", etc), but will settle for anything like it: { + * "en_GB", "en", NULL }. + * + * This function returns NULL on error, including when the platform does not + * supply this information at all. + * + * This might be a "slow" call that has to query the operating system. It's + * best to ask for this once and save the results. However, this list can + * change, usually because the user has changed a system preference outside of + * your program; SDL will send an SDL_EVENT_LOCALE_CHANGED event in this case, + * if possible, and you can call this function again to get an updated copy of + * preferred locales. + * + * \param count a pointer filled in with the number of locales returned, may + * be NULL. + * \returns a NULL terminated array of locale pointers, or NULL on failure; + * call SDL_GetError() for more information. This is a single + * allocation that should be freed with SDL_free() when it is no + * longer needed. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Locale ** SDLCALL SDL_GetPreferredLocales(int *count); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif +#include + +#endif /* SDL_locale_h */ diff --git a/thirdparty/sdl/include/SDL3/SDL_log.h b/thirdparty/sdl/include/SDL3/SDL_log.h new file mode 100644 index 00000000000..3fd7ec2ede6 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_log.h @@ -0,0 +1,538 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryLog + * + * Simple log messages with priorities and categories. A message's + * SDL_LogPriority signifies how important the message is. A message's + * SDL_LogCategory signifies from what domain it belongs to. Every category + * has a minimum priority specified: when a message belongs to that category, + * it will only be sent out if it has that minimum priority or higher. + * + * SDL's own logs are sent below the default priority threshold, so they are + * quiet by default. + * + * You can change the log verbosity programmatically using + * SDL_SetLogPriority() or with SDL_SetHint(SDL_HINT_LOGGING, ...), or with + * the "SDL_LOGGING" environment variable. This variable is a comma separated + * set of category=level tokens that define the default logging levels for SDL + * applications. + * + * The category can be a numeric category, one of "app", "error", "assert", + * "system", "audio", "video", "render", "input", "test", or `*` for any + * unspecified category. + * + * The level can be a numeric level, one of "trace", "verbose", "debug", + * "info", "warn", "error", "critical", or "quiet" to disable that category. + * + * You can omit the category if you want to set the logging level for all + * categories. + * + * If this hint isn't set, the default log levels are equivalent to: + * + * `app=info,assert=warn,test=verbose,*=error` + * + * Here's where the messages go on different platforms: + * + * - Windows: debug output stream + * - Android: log output + * - Others: standard error output (stderr) + * + * You don't need to have a newline (`\n`) on the end of messages, the + * functions will do that for you. For consistent behavior cross-platform, you + * shouldn't have any newlines in messages, such as to log multiple lines in + * one call; unusual platform-specific behavior can be observed in such usage. + * Do one log call per line instead, with no newlines in messages. + * + * Each log call is atomic, so you won't see log messages cut off one another + * when logging from multiple threads. + */ + +#ifndef SDL_log_h_ +#define SDL_log_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The predefined log categories + * + * By default the application and gpu categories are enabled at the INFO + * level, the assert category is enabled at the WARN level, test is enabled at + * the VERBOSE level and all other categories are enabled at the ERROR level. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_LogCategory +{ + SDL_LOG_CATEGORY_APPLICATION, + SDL_LOG_CATEGORY_ERROR, + SDL_LOG_CATEGORY_ASSERT, + SDL_LOG_CATEGORY_SYSTEM, + SDL_LOG_CATEGORY_AUDIO, + SDL_LOG_CATEGORY_VIDEO, + SDL_LOG_CATEGORY_RENDER, + SDL_LOG_CATEGORY_INPUT, + SDL_LOG_CATEGORY_TEST, + SDL_LOG_CATEGORY_GPU, + + /* Reserved for future SDL library use */ + SDL_LOG_CATEGORY_RESERVED2, + SDL_LOG_CATEGORY_RESERVED3, + SDL_LOG_CATEGORY_RESERVED4, + SDL_LOG_CATEGORY_RESERVED5, + SDL_LOG_CATEGORY_RESERVED6, + SDL_LOG_CATEGORY_RESERVED7, + SDL_LOG_CATEGORY_RESERVED8, + SDL_LOG_CATEGORY_RESERVED9, + SDL_LOG_CATEGORY_RESERVED10, + + /* Beyond this point is reserved for application use, e.g. + enum { + MYAPP_CATEGORY_AWESOME1 = SDL_LOG_CATEGORY_CUSTOM, + MYAPP_CATEGORY_AWESOME2, + MYAPP_CATEGORY_AWESOME3, + ... + }; + */ + SDL_LOG_CATEGORY_CUSTOM +} SDL_LogCategory; + +/** + * The predefined log priorities + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_LogPriority +{ + SDL_LOG_PRIORITY_INVALID, + SDL_LOG_PRIORITY_TRACE, + SDL_LOG_PRIORITY_VERBOSE, + SDL_LOG_PRIORITY_DEBUG, + SDL_LOG_PRIORITY_INFO, + SDL_LOG_PRIORITY_WARN, + SDL_LOG_PRIORITY_ERROR, + SDL_LOG_PRIORITY_CRITICAL, + SDL_LOG_PRIORITY_COUNT +} SDL_LogPriority; + + +/** + * Set the priority of all log categories. + * + * \param priority the SDL_LogPriority to assign. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ResetLogPriorities + * \sa SDL_SetLogPriority + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetLogPriorities(SDL_LogPriority priority); + +/** + * Set the priority of a particular log category. + * + * \param category the category to assign a priority to. + * \param priority the SDL_LogPriority to assign. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetLogPriority + * \sa SDL_ResetLogPriorities + * \sa SDL_SetLogPriorities + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetLogPriority(int category, SDL_LogPriority priority); + +/** + * Get the priority of a particular log category. + * + * \param category the category to query. + * \returns the SDL_LogPriority for the requested category. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetLogPriority + */ +extern SDL_DECLSPEC SDL_LogPriority SDLCALL SDL_GetLogPriority(int category); + +/** + * Reset all priorities to default. + * + * This is called by SDL_Quit(). + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetLogPriorities + * \sa SDL_SetLogPriority + */ +extern SDL_DECLSPEC void SDLCALL SDL_ResetLogPriorities(void); + +/** + * Set the text prepended to log messages of a given priority. + * + * By default SDL_LOG_PRIORITY_INFO and below have no prefix, and + * SDL_LOG_PRIORITY_WARN and higher have a prefix showing their priority, e.g. + * "WARNING: ". + * + * \param priority the SDL_LogPriority to modify. + * \param prefix the prefix to use for that log priority, or NULL to use no + * prefix. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetLogPriorities + * \sa SDL_SetLogPriority + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetLogPriorityPrefix(SDL_LogPriority priority, const char *prefix); + +/** + * Log a message with SDL_LOG_CATEGORY_APPLICATION and SDL_LOG_PRIORITY_INFO. + * + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the `fmt` string, if + * any. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogTrace + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern SDL_DECLSPEC void SDLCALL SDL_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1); + +/** + * Log a message with SDL_LOG_PRIORITY_TRACE. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogTrace + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern SDL_DECLSPEC void SDLCALL SDL_LogTrace(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_VERBOSE. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogWarn + */ +extern SDL_DECLSPEC void SDLCALL SDL_LogVerbose(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_DEBUG. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogTrace + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern SDL_DECLSPEC void SDLCALL SDL_LogDebug(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_INFO. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogTrace + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern SDL_DECLSPEC void SDLCALL SDL_LogInfo(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_WARN. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogTrace + * \sa SDL_LogVerbose + */ +extern SDL_DECLSPEC void SDLCALL SDL_LogWarn(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_ERROR. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogTrace + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern SDL_DECLSPEC void SDLCALL SDL_LogError(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_CRITICAL. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Log + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogTrace + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern SDL_DECLSPEC void SDLCALL SDL_LogCritical(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with the specified category and priority. + * + * \param category the category of the message. + * \param priority the priority of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessageV + * \sa SDL_LogTrace + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern SDL_DECLSPEC void SDLCALL SDL_LogMessage(int category, + SDL_LogPriority priority, + SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(3); + +/** + * Log a message with the specified category and priority. + * + * \param category the category of the message. + * \param priority the priority of the message. + * \param fmt a printf() style message format string. + * \param ap a variable argument list. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogTrace + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern SDL_DECLSPEC void SDLCALL SDL_LogMessageV(int category, + SDL_LogPriority priority, + SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(3); + +/** + * The prototype for the log output callback function. + * + * This function is called by SDL when there is new text to be logged. A mutex + * is held so that this function is never called by more than one thread at + * once. + * + * \param userdata what was passed as `userdata` to + * SDL_SetLogOutputFunction(). + * \param category the category of the message. + * \param priority the priority of the message. + * \param message the message being output. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef void (SDLCALL *SDL_LogOutputFunction)(void *userdata, int category, SDL_LogPriority priority, const char *message); + +/** + * Get the default log output function. + * + * \returns the default log output callback. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetLogOutputFunction + * \sa SDL_GetLogOutputFunction + */ +extern SDL_DECLSPEC SDL_LogOutputFunction SDLCALL SDL_GetDefaultLogOutputFunction(void); + +/** + * Get the current log output function. + * + * \param callback an SDL_LogOutputFunction filled in with the current log + * callback. + * \param userdata a pointer filled in with the pointer that is passed to + * `callback`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDefaultLogOutputFunction + * \sa SDL_SetLogOutputFunction + */ +extern SDL_DECLSPEC void SDLCALL SDL_GetLogOutputFunction(SDL_LogOutputFunction *callback, void **userdata); + +/** + * Replace the default log output function with one of your own. + * + * \param callback an SDL_LogOutputFunction to call instead of the default. + * \param userdata a pointer that is passed to `callback`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDefaultLogOutputFunction + * \sa SDL_GetLogOutputFunction + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetLogOutputFunction(SDL_LogOutputFunction callback, void *userdata); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_log_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_main.h b/thirdparty/sdl/include/SDL3/SDL_main.h new file mode 100644 index 00000000000..905d78e9641 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_main.h @@ -0,0 +1,675 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryMain + * + * Redefine main() if necessary so that it is called by SDL. + * + * In order to make this consistent on all platforms, the application's main() + * should look like this: + * + * ```c + * #include + * #include + * + * int main(int argc, char *argv[]) + * { + * } + * ``` + * + * SDL will take care of platform specific details on how it gets called. + * + * This is also where an app can be configured to use the main callbacks, via + * the SDL_MAIN_USE_CALLBACKS macro. + * + * SDL_main.h is a "single-header library," which is to say that including + * this header inserts code into your program, and you should only include it + * once in most cases. SDL.h does not include this header automatically. + * + * For more information, see: + * + * https://wiki.libsdl.org/SDL3/README/main-functions + */ + +#ifndef SDL_main_h_ +#define SDL_main_h_ + +#include +#include +#include +#include + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Inform SDL that the app is providing an entry point instead of SDL. + * + * SDL does not define this macro, but will check if it is defined when + * including `SDL_main.h`. If defined, SDL will expect the app to provide the + * proper entry point for the platform, and all the other magic details + * needed, like manually calling SDL_SetMainReady. + * + * Please see [README/main-functions](README/main-functions), (or + * docs/README-main-functions.md in the source tree) for a more detailed + * explanation. + * + * \since This macro is used by the headers since SDL 3.2.0. + */ +#define SDL_MAIN_HANDLED 1 + +/** + * Inform SDL to use the main callbacks instead of main. + * + * SDL does not define this macro, but will check if it is defined when + * including `SDL_main.h`. If defined, SDL will expect the app to provide + * several functions: SDL_AppInit, SDL_AppEvent, SDL_AppIterate, and + * SDL_AppQuit. The app should not provide a `main` function in this case, and + * doing so will likely cause the build to fail. + * + * Please see [README/main-functions](README/main-functions), (or + * docs/README-main-functions.md in the source tree) for a more detailed + * explanation. + * + * \since This macro is used by the headers since SDL 3.2.0. + * + * \sa SDL_AppInit + * \sa SDL_AppEvent + * \sa SDL_AppIterate + * \sa SDL_AppQuit + */ +#define SDL_MAIN_USE_CALLBACKS 1 + +/** + * Defined if the target platform offers a special mainline through SDL. + * + * This won't be defined otherwise. If defined, SDL's headers will redefine + * `main` to `SDL_main`. + * + * This macro is defined by `SDL_main.h`, which is not automatically included + * by `SDL.h`. + * + * Even if available, an app can define SDL_MAIN_HANDLED and provide their + * own, if they know what they're doing. + * + * This macro is used internally by SDL, and apps probably shouldn't rely on it. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_MAIN_AVAILABLE + +/** + * Defined if the target platform _requires_ a special mainline through SDL. + * + * This won't be defined otherwise. If defined, SDL's headers will redefine + * `main` to `SDL_main`. + * + * This macro is defined by `SDL_main.h`, which is not automatically included + * by `SDL.h`. + * + * Even if required, an app can define SDL_MAIN_HANDLED and provide their + * own, if they know what they're doing. + * + * This macro is used internally by SDL, and apps probably shouldn't rely on it. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_MAIN_NEEDED + +#endif + +#if defined(__has_include) + #if __has_include("SDL_main_private.h") && __has_include("SDL_main_impl_private.h") + #define SDL_PLATFORM_PRIVATE_MAIN + #endif +#endif + +#ifndef SDL_MAIN_HANDLED + #if defined(SDL_PLATFORM_PRIVATE_MAIN) + /* Private platforms may have their own ideas about entry points. */ + #include "SDL_main_private.h" + + #elif defined(SDL_PLATFORM_WIN32) + /* On Windows SDL provides WinMain(), which parses the command line and passes + the arguments to your main function. + + If you provide your own WinMain(), you may define SDL_MAIN_HANDLED + */ + #define SDL_MAIN_AVAILABLE + + #elif defined(SDL_PLATFORM_GDK) + /* On GDK, SDL provides a main function that initializes the game runtime. + + If you prefer to write your own WinMain-function instead of having SDL + provide one that calls your main() function, + #define SDL_MAIN_HANDLED before #include'ing SDL_main.h + and call the SDL_RunApp function from your entry point. + */ + #define SDL_MAIN_NEEDED + + #elif defined(SDL_PLATFORM_IOS) + /* On iOS SDL provides a main function that creates an application delegate + and starts the iOS application run loop. + + To use it, just #include SDL_main.h in the source file that contains your + main() function. + + See src/video/uikit/SDL_uikitappdelegate.m for more details. + */ + #define SDL_MAIN_NEEDED + + #elif defined(SDL_PLATFORM_ANDROID) + /* On Android SDL provides a Java class in SDLActivity.java that is the + main activity entry point. + + See docs/README-android.md for more details on extending that class. + */ + #define SDL_MAIN_NEEDED + + /* As this is launched from Java, the real entry point (main() function) + is outside of the the binary built from this code. + This define makes sure that, unlike on other platforms, SDL_main.h + and SDL_main_impl.h export an `SDL_main()` function (to be called + from Java), but don't implement a native `int main(int argc, char* argv[])` + or similar. + */ + #define SDL_MAIN_EXPORTED + + #elif defined(SDL_PLATFORM_EMSCRIPTEN) + /* On Emscripten, SDL provides a main function that converts URL + parameters that start with "SDL_" to environment variables, so + they can be used as SDL hints, etc. + + This is 100% optional, so if you don't want this to happen, you may + define SDL_MAIN_HANDLED + */ + #define SDL_MAIN_AVAILABLE + + #elif defined(SDL_PLATFORM_PSP) + /* On PSP SDL provides a main function that sets the module info, + activates the GPU and starts the thread required to be able to exit + the software. + + If you provide this yourself, you may define SDL_MAIN_HANDLED + */ + #define SDL_MAIN_AVAILABLE + + #elif defined(SDL_PLATFORM_PS2) + #define SDL_MAIN_AVAILABLE + + #define SDL_PS2_SKIP_IOP_RESET() \ + void reset_IOP(); \ + void reset_IOP() {} + + #elif defined(SDL_PLATFORM_3DS) + /* + On N3DS, SDL provides a main function that sets up the screens + and storage. + + If you provide this yourself, you may define SDL_MAIN_HANDLED + */ + #define SDL_MAIN_AVAILABLE + + #endif +#endif /* SDL_MAIN_HANDLED */ + + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A macro to tag a main entry point function as exported. + * + * Most platforms don't need this, and the macro will be defined to nothing. + * Some, like Android, keep the entry points in a shared library and need to + * explicitly export the symbols. + * + * External code rarely needs this, and if it needs something, it's almost + * always SDL_DECLSPEC instead. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_DECLSPEC + */ +#define SDLMAIN_DECLSPEC + +#elif defined(SDL_MAIN_EXPORTED) +/* We need to export SDL_main so it can be launched from external code, + like SDLActivity.java on Android */ +#define SDLMAIN_DECLSPEC SDL_DECLSPEC +#else +/* usually this is empty */ +#define SDLMAIN_DECLSPEC +#endif /* SDL_MAIN_EXPORTED */ + +#if defined(SDL_MAIN_NEEDED) || defined(SDL_MAIN_AVAILABLE) || defined(SDL_MAIN_USE_CALLBACKS) +#define main SDL_main +#endif + +#include +#include +#ifdef __cplusplus +extern "C" { +#endif + +/* + * You can (optionally!) define SDL_MAIN_USE_CALLBACKS before including + * SDL_main.h, and then your application will _not_ have a standard + * "main" entry point. Instead, it will operate as a collection of + * functions that are called as necessary by the system. On some + * platforms, this is just a layer where SDL drives your program + * instead of your program driving SDL, on other platforms this might + * hook into the OS to manage the lifecycle. Programs on most platforms + * can use whichever approach they prefer, but the decision boils down + * to: + * + * - Using a standard "main" function: this works like it always has for + * the past 50+ years in C programming, and your app is in control. + * - Using the callback functions: this might clean up some code, + * avoid some #ifdef blocks in your program for some platforms, be more + * resource-friendly to the system, and possibly be the primary way to + * access some future platforms (but none require this at the moment). + * + * This is up to the app; both approaches are considered valid and supported + * ways to write SDL apps. + * + * If using the callbacks, don't define a "main" function. Instead, implement + * the functions listed below in your program. + */ +#ifdef SDL_MAIN_USE_CALLBACKS + +/** + * App-implemented initial entry point for SDL_MAIN_USE_CALLBACKS apps. + * + * Apps implement this function when using SDL_MAIN_USE_CALLBACKS. If using a + * standard "main" function, you should not supply this. + * + * This function is called by SDL once, at startup. The function should + * initialize whatever is necessary, possibly create windows and open audio + * devices, etc. The `argc` and `argv` parameters work like they would with a + * standard "main" function. + * + * This function should not go into an infinite mainloop; it should do any + * one-time setup it requires and then return. + * + * The app may optionally assign a pointer to `*appstate`. This pointer will + * be provided on every future call to the other entry points, to allow + * application state to be preserved between functions without the app needing + * to use a global variable. If this isn't set, the pointer will be NULL in + * future entry points. + * + * If this function returns SDL_APP_CONTINUE, the app will proceed to normal + * operation, and will begin receiving repeated calls to SDL_AppIterate and + * SDL_AppEvent for the life of the program. If this function returns + * SDL_APP_FAILURE, SDL will call SDL_AppQuit and terminate the process with + * an exit code that reports an error to the platform. If it returns + * SDL_APP_SUCCESS, SDL calls SDL_AppQuit and terminates with an exit code + * that reports success to the platform. + * + * This function is called by SDL on the main thread. + * + * \param appstate a place where the app can optionally store a pointer for + * future use. + * \param argc the standard ANSI C main's argc; number of elements in `argv`. + * \param argv the standard ANSI C main's argv; array of command line + * arguments. + * \returns SDL_APP_FAILURE to terminate with an error, SDL_APP_SUCCESS to + * terminate with success, SDL_APP_CONTINUE to continue. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AppIterate + * \sa SDL_AppEvent + * \sa SDL_AppQuit + */ +extern SDLMAIN_DECLSPEC SDL_AppResult SDLCALL SDL_AppInit(void **appstate, int argc, char *argv[]); + +/** + * App-implemented iteration entry point for SDL_MAIN_USE_CALLBACKS apps. + * + * Apps implement this function when using SDL_MAIN_USE_CALLBACKS. If using a + * standard "main" function, you should not supply this. + * + * This function is called repeatedly by SDL after SDL_AppInit returns 0. The + * function should operate as a single iteration the program's primary loop; + * it should update whatever state it needs and draw a new frame of video, + * usually. + * + * On some platforms, this function will be called at the refresh rate of the + * display (which might change during the life of your app!). There are no + * promises made about what frequency this function might run at. You should + * use SDL's timer functions if you need to see how much time has passed since + * the last iteration. + * + * There is no need to process the SDL event queue during this function; SDL + * will send events as they arrive in SDL_AppEvent, and in most cases the + * event queue will be empty when this function runs anyhow. + * + * This function should not go into an infinite mainloop; it should do one + * iteration of whatever the program does and return. + * + * The `appstate` parameter is an optional pointer provided by the app during + * SDL_AppInit(). If the app never provided a pointer, this will be NULL. + * + * If this function returns SDL_APP_CONTINUE, the app will continue normal + * operation, receiving repeated calls to SDL_AppIterate and SDL_AppEvent for + * the life of the program. If this function returns SDL_APP_FAILURE, SDL will + * call SDL_AppQuit and terminate the process with an exit code that reports + * an error to the platform. If it returns SDL_APP_SUCCESS, SDL calls + * SDL_AppQuit and terminates with an exit code that reports success to the + * platform. + * + * This function is called by SDL on the main thread. + * + * \param appstate an optional pointer, provided by the app in SDL_AppInit. + * \returns SDL_APP_FAILURE to terminate with an error, SDL_APP_SUCCESS to + * terminate with success, SDL_APP_CONTINUE to continue. + * + * \threadsafety This function may get called concurrently with SDL_AppEvent() + * for events not pushed on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AppInit + * \sa SDL_AppEvent + */ +extern SDLMAIN_DECLSPEC SDL_AppResult SDLCALL SDL_AppIterate(void *appstate); + +/** + * App-implemented event entry point for SDL_MAIN_USE_CALLBACKS apps. + * + * Apps implement this function when using SDL_MAIN_USE_CALLBACKS. If using a + * standard "main" function, you should not supply this. + * + * This function is called as needed by SDL after SDL_AppInit returns + * SDL_APP_CONTINUE. It is called once for each new event. + * + * There is (currently) no guarantee about what thread this will be called + * from; whatever thread pushes an event onto SDL's queue will trigger this + * function. SDL is responsible for pumping the event queue between each call + * to SDL_AppIterate, so in normal operation one should only get events in a + * serial fashion, but be careful if you have a thread that explicitly calls + * SDL_PushEvent. SDL itself will push events to the queue on the main thread. + * + * Events sent to this function are not owned by the app; if you need to save + * the data, you should copy it. + * + * This function should not go into an infinite mainloop; it should handle the + * provided event appropriately and return. + * + * The `appstate` parameter is an optional pointer provided by the app during + * SDL_AppInit(). If the app never provided a pointer, this will be NULL. + * + * If this function returns SDL_APP_CONTINUE, the app will continue normal + * operation, receiving repeated calls to SDL_AppIterate and SDL_AppEvent for + * the life of the program. If this function returns SDL_APP_FAILURE, SDL will + * call SDL_AppQuit and terminate the process with an exit code that reports + * an error to the platform. If it returns SDL_APP_SUCCESS, SDL calls + * SDL_AppQuit and terminates with an exit code that reports success to the + * platform. + * + * \param appstate an optional pointer, provided by the app in SDL_AppInit. + * \param event the new event for the app to examine. + * \returns SDL_APP_FAILURE to terminate with an error, SDL_APP_SUCCESS to + * terminate with success, SDL_APP_CONTINUE to continue. + * + * \threadsafety This function may get called concurrently with + * SDL_AppIterate() or SDL_AppQuit() for events not pushed from + * the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AppInit + * \sa SDL_AppIterate + */ +extern SDLMAIN_DECLSPEC SDL_AppResult SDLCALL SDL_AppEvent(void *appstate, SDL_Event *event); + +/** + * App-implemented deinit entry point for SDL_MAIN_USE_CALLBACKS apps. + * + * Apps implement this function when using SDL_MAIN_USE_CALLBACKS. If using a + * standard "main" function, you should not supply this. + * + * This function is called once by SDL before terminating the program. + * + * This function will be called no matter what, even if SDL_AppInit requests + * termination. + * + * This function should not go into an infinite mainloop; it should + * deinitialize any resources necessary, perform whatever shutdown activities, + * and return. + * + * You do not need to call SDL_Quit() in this function, as SDL will call it + * after this function returns and before the process terminates, but it is + * safe to do so. + * + * The `appstate` parameter is an optional pointer provided by the app during + * SDL_AppInit(). If the app never provided a pointer, this will be NULL. This + * function call is the last time this pointer will be provided, so any + * resources to it should be cleaned up here. + * + * This function is called by SDL on the main thread. + * + * \param appstate an optional pointer, provided by the app in SDL_AppInit. + * \param result the result code that terminated the app (success or failure). + * + * \threadsafety SDL_AppEvent() may get called concurrently with this function + * if other threads that push events are still active. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AppInit + */ +extern SDLMAIN_DECLSPEC void SDLCALL SDL_AppQuit(void *appstate, SDL_AppResult result); + +#endif /* SDL_MAIN_USE_CALLBACKS */ + + +/** + * The prototype for the application's main() function + * + * \param argc an ANSI-C style main function's argc. + * \param argv an ANSI-C style main function's argv. + * \returns an ANSI-C main return code; generally 0 is considered successful + * program completion, and small non-zero values are considered + * errors. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef int (SDLCALL *SDL_main_func)(int argc, char *argv[]); + +/** + * An app-supplied function for program entry. + * + * Apps do not directly create this function; they should create a standard + * ANSI-C `main` function instead. If SDL needs to insert some startup code + * before `main` runs, or the platform doesn't actually _use_ a function + * called "main", SDL will do some macro magic to redefine `main` to + * `SDL_main` and provide its own `main`. + * + * Apps should include `SDL_main.h` in the same file as their `main` function, + * and they should not use that symbol for anything else in that file, as it + * might get redefined. + * + * This function is only provided by the app if it isn't using + * SDL_MAIN_USE_CALLBACKS. + * + * Program startup is a surprisingly complex topic. Please see + * [README/main-functions](README/main-functions), (or + * docs/README-main-functions.md in the source tree) for a more detailed + * explanation. + * + * \param argc an ANSI-C style main function's argc. + * \param argv an ANSI-C style main function's argv. + * \returns an ANSI-C main return code; generally 0 is considered successful + * program completion, and small non-zero values are considered + * errors. + * + * \threadsafety This is the program entry point. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDLMAIN_DECLSPEC int SDLCALL SDL_main(int argc, char *argv[]); + +/** + * Circumvent failure of SDL_Init() when not using SDL_main() as an entry + * point. + * + * This function is defined in SDL_main.h, along with the preprocessor rule to + * redefine main() as SDL_main(). Thus to ensure that your main() function + * will not be changed it is necessary to define SDL_MAIN_HANDLED before + * including SDL.h. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Init + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetMainReady(void); + +/** + * Initializes and launches an SDL application, by doing platform-specific + * initialization before calling your mainFunction and cleanups after it + * returns, if that is needed for a specific platform, otherwise it just calls + * mainFunction. + * + * You can use this if you want to use your own main() implementation without + * using SDL_main (like when using SDL_MAIN_HANDLED). When using this, you do + * *not* need SDL_SetMainReady(). + * + * \param argc the argc parameter from the application's main() function, or 0 + * if the platform's main-equivalent has no argc. + * \param argv the argv parameter from the application's main() function, or + * NULL if the platform's main-equivalent has no argv. + * \param mainFunction your SDL app's C-style main(). NOT the function you're + * calling this from! Its name doesn't matter; it doesn't + * literally have to be `main`. + * \param reserved should be NULL (reserved for future use, will probably be + * platform-specific then). + * \returns the return value from mainFunction: 0 on success, otherwise + * failure; SDL_GetError() might have more information on the + * failure. + * + * \threadsafety Generally this is called once, near startup, from the + * process's initial thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_RunApp(int argc, char *argv[], SDL_main_func mainFunction, void *reserved); + +/** + * An entry point for SDL's use in SDL_MAIN_USE_CALLBACKS. + * + * Generally, you should not call this function directly. This only exists to + * hand off work into SDL as soon as possible, where it has a lot more control + * and functionality available, and make the inline code in SDL_main.h as + * small as possible. + * + * Not all platforms use this, it's actual use is hidden in a magic + * header-only library, and you should not call this directly unless you + * _really_ know what you're doing. + * + * \param argc standard Unix main argc. + * \param argv standard Unix main argv. + * \param appinit the application's SDL_AppInit function. + * \param appiter the application's SDL_AppIterate function. + * \param appevent the application's SDL_AppEvent function. + * \param appquit the application's SDL_AppQuit function. + * \returns standard Unix main return value. + * + * \threadsafety It is not safe to call this anywhere except as the only + * function call in SDL_main. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_EnterAppMainCallbacks(int argc, char *argv[], SDL_AppInit_func appinit, SDL_AppIterate_func appiter, SDL_AppEvent_func appevent, SDL_AppQuit_func appquit); + + +#if defined(SDL_PLATFORM_WINDOWS) + +/** + * Register a win32 window class for SDL's use. + * + * This can be called to set the application window class at startup. It is + * safe to call this multiple times, as long as every call is eventually + * paired with a call to SDL_UnregisterApp, but a second registration attempt + * while a previous registration is still active will be ignored, other than + * to increment a counter. + * + * Most applications do not need to, and should not, call this directly; SDL + * will call it when initializing the video subsystem. + * + * \param name the window class name, in UTF-8 encoding. If NULL, SDL + * currently uses "SDL_app" but this isn't guaranteed. + * \param style the value to use in WNDCLASSEX::style. If `name` is NULL, SDL + * currently uses `(CS_BYTEALIGNCLIENT | CS_OWNDC)` regardless of + * what is specified here. + * \param hInst the HINSTANCE to use in WNDCLASSEX::hInstance. If zero, SDL + * will use `GetModuleHandle(NULL)` instead. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RegisterApp(const char *name, Uint32 style, void *hInst); + +/** + * Deregister the win32 window class from an SDL_RegisterApp call. + * + * This can be called to undo the effects of SDL_RegisterApp. + * + * Most applications do not need to, and should not, call this directly; SDL + * will call it when deinitializing the video subsystem. + * + * It is safe to call this multiple times, as long as every call is eventually + * paired with a prior call to SDL_RegisterApp. The window class will only be + * deregistered when the registration counter in SDL_RegisterApp decrements to + * zero through calls to this function. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnregisterApp(void); + +#endif /* defined(SDL_PLATFORM_WINDOWS) */ + +/** + * Callback from the application to let the suspend continue. + * + * This function is only needed for Xbox GDK support; all other platforms will + * do nothing and set an "unsupported" error message. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_GDKSuspendComplete(void); + +#ifdef __cplusplus +} +#endif + +#include + +#if !defined(SDL_MAIN_HANDLED) && !defined(SDL_MAIN_NOIMPL) + /* include header-only SDL_main implementations */ + #if defined(SDL_MAIN_USE_CALLBACKS) || defined(SDL_MAIN_NEEDED) || defined(SDL_MAIN_AVAILABLE) + /* platforms which main (-equivalent) can be implemented in plain C */ + #include + #endif +#endif + +#endif /* SDL_main_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_main_impl.h b/thirdparty/sdl/include/SDL3/SDL_main_impl.h new file mode 100644 index 00000000000..14ebb429164 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_main_impl.h @@ -0,0 +1,151 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: Main */ + +#ifndef SDL_main_impl_h_ +#define SDL_main_impl_h_ + +#ifndef SDL_main_h_ +#error "This header should not be included directly, but only via SDL_main.h!" +#endif + +/* if someone wants to include SDL_main.h but doesn't want the main handing magic, + (maybe to call SDL_RegisterApp()) they can #define SDL_MAIN_HANDLED first. + SDL_MAIN_NOIMPL is for SDL-internal usage (only affects implementation, + not definition of SDL_MAIN_AVAILABLE etc in SDL_main.h) and if the user wants + to have the SDL_main implementation (from this header) in another source file + than their main() function, for example if SDL_main requires C++ + and main() is implemented in plain C */ +#if !defined(SDL_MAIN_HANDLED) && !defined(SDL_MAIN_NOIMPL) + + /* the implementations below must be able to use the implement real main(), nothing renamed + (the user's main() will be renamed to SDL_main so it can be called from here) */ + #ifdef main + #undef main + #endif + + #ifdef SDL_MAIN_USE_CALLBACKS + + #if 0 + /* currently there are no platforms that _need_ a magic entry point here + for callbacks, but if one shows up, implement it here. */ + + #else /* use a standard SDL_main, which the app SHOULD NOT ALSO SUPPLY. */ + + /* this define makes the normal SDL_main entry point stuff work...we just provide SDL_main() instead of the app. */ + #define SDL_MAIN_CALLBACK_STANDARD 1 + + int SDL_main(int argc, char **argv) + { + return SDL_EnterAppMainCallbacks(argc, argv, SDL_AppInit, SDL_AppIterate, SDL_AppEvent, SDL_AppQuit); + } + + #endif /* platform-specific tests */ + + #endif /* SDL_MAIN_USE_CALLBACKS */ + + + /* set up the usual SDL_main stuff if we're not using callbacks or if we are but need the normal entry point, + unless the real entry point needs to be somewhere else entirely, like Android where it's in Java code */ + #if (!defined(SDL_MAIN_USE_CALLBACKS) || defined(SDL_MAIN_CALLBACK_STANDARD)) && !defined(SDL_MAIN_EXPORTED) + + #if defined(SDL_PLATFORM_PRIVATE_MAIN) + /* Private platforms may have their own ideas about entry points. */ + #include "SDL_main_impl_private.h" + + #elif defined(SDL_PLATFORM_WINDOWS) + + /* these defines/typedefs are needed for the WinMain() definition */ + #ifndef WINAPI + #define WINAPI __stdcall + #endif + + typedef struct HINSTANCE__ * HINSTANCE; + typedef char *LPSTR; + typedef wchar_t *PWSTR; + + /* The VC++ compiler needs main/wmain defined, but not for GDK */ + #if defined(_MSC_VER) && !defined(SDL_PLATFORM_GDK) + + /* This is where execution begins [console apps] */ + #if defined(UNICODE) && UNICODE + int wmain(int argc, wchar_t *wargv[], wchar_t *wenvp) + { + (void)argc; + (void)wargv; + (void)wenvp; + return SDL_RunApp(0, NULL, SDL_main, NULL); + } + #else /* ANSI */ + int main(int argc, char *argv[]) + { + (void)argc; + (void)argv; + return SDL_RunApp(0, NULL, SDL_main, NULL); + } + #endif /* UNICODE */ + + #endif /* _MSC_VER && ! SDL_PLATFORM_GDK */ + + /* This is where execution begins [windowed apps and GDK] */ + + #ifdef __cplusplus + extern "C" { + #endif + + #if defined(UNICODE) && UNICODE + int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrev, PWSTR szCmdLine, int sw) + #else /* ANSI */ + int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) + #endif + { + (void)hInst; + (void)hPrev; + (void)szCmdLine; + (void)sw; + return SDL_RunApp(0, NULL, SDL_main, NULL); + } + + #ifdef __cplusplus + } /* extern "C" */ + #endif + + /* end of SDL_PLATFORM_WINDOWS impls */ + + #else /* platforms that use a standard main() and just call SDL_RunApp(), like iOS and 3DS */ + int main(int argc, char *argv[]) + { + return SDL_RunApp(argc, argv, SDL_main, NULL); + } + + /* end of impls for standard-conforming platforms */ + + #endif /* SDL_PLATFORM_WIN32 etc */ + + #endif /* !defined(SDL_MAIN_USE_CALLBACKS) || defined(SDL_MAIN_CALLBACK_STANDARD) */ + + /* rename users main() function to SDL_main() so it can be called from the wrappers above */ + #define main SDL_main + +#endif /* SDL_MAIN_HANDLED */ + +#endif /* SDL_main_impl_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_messagebox.h b/thirdparty/sdl/include/SDL3/SDL_messagebox.h new file mode 100644 index 00000000000..365ae36a5a6 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_messagebox.h @@ -0,0 +1,226 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryMessagebox + * + * SDL offers a simple message box API, which is useful for simple alerts, + * such as informing the user when something fatal happens at startup without + * the need to build a UI for it (or informing the user _before_ your UI is + * ready). + * + * These message boxes are native system dialogs where possible. + * + * There is both a customizable function (SDL_ShowMessageBox()) that offers + * lots of options for what to display and reports on what choice the user + * made, and also a much-simplified version (SDL_ShowSimpleMessageBox()), + * merely takes a text message and title, and waits until the user presses a + * single "OK" UI button. Often, this is all that is necessary. + */ + +#ifndef SDL_messagebox_h_ +#define SDL_messagebox_h_ + +#include +#include +#include /* For SDL_Window */ + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Message box flags. + * + * If supported will display warning icon, etc. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_MessageBoxFlags; + +#define SDL_MESSAGEBOX_ERROR 0x00000010u /**< error dialog */ +#define SDL_MESSAGEBOX_WARNING 0x00000020u /**< warning dialog */ +#define SDL_MESSAGEBOX_INFORMATION 0x00000040u /**< informational dialog */ +#define SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT 0x00000080u /**< buttons placed left to right */ +#define SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT 0x00000100u /**< buttons placed right to left */ + +/** + * SDL_MessageBoxButtonData flags. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_MessageBoxButtonFlags; + +#define SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT 0x00000001u /**< Marks the default button when return is hit */ +#define SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT 0x00000002u /**< Marks the default button when escape is hit */ + +/** + * Individual button data. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_MessageBoxButtonData +{ + SDL_MessageBoxButtonFlags flags; + int buttonID; /**< User defined button id (value returned via SDL_ShowMessageBox) */ + const char *text; /**< The UTF-8 button text */ +} SDL_MessageBoxButtonData; + +/** + * RGB value used in a message box color scheme + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_MessageBoxColor +{ + Uint8 r, g, b; +} SDL_MessageBoxColor; + +/** + * An enumeration of indices inside the colors array of + * SDL_MessageBoxColorScheme. + */ +typedef enum SDL_MessageBoxColorType +{ + SDL_MESSAGEBOX_COLOR_BACKGROUND, + SDL_MESSAGEBOX_COLOR_TEXT, + SDL_MESSAGEBOX_COLOR_BUTTON_BORDER, + SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND, + SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED, + SDL_MESSAGEBOX_COLOR_COUNT /**< Size of the colors array of SDL_MessageBoxColorScheme. */ +} SDL_MessageBoxColorType; + +/** + * A set of colors to use for message box dialogs + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_MessageBoxColorScheme +{ + SDL_MessageBoxColor colors[SDL_MESSAGEBOX_COLOR_COUNT]; +} SDL_MessageBoxColorScheme; + +/** + * MessageBox structure containing title, text, window, etc. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_MessageBoxData +{ + SDL_MessageBoxFlags flags; + SDL_Window *window; /**< Parent window, can be NULL */ + const char *title; /**< UTF-8 title */ + const char *message; /**< UTF-8 message text */ + + int numbuttons; + const SDL_MessageBoxButtonData *buttons; + + const SDL_MessageBoxColorScheme *colorScheme; /**< SDL_MessageBoxColorScheme, can be NULL to use system settings */ +} SDL_MessageBoxData; + +/** + * Create a modal message box. + * + * If your needs aren't complex, it might be easier to use + * SDL_ShowSimpleMessageBox. + * + * This function should be called on the thread that created the parent + * window, or on the main thread if the messagebox has no parent. It will + * block execution of that thread until the user clicks a button or closes the + * messagebox. + * + * This function may be called at any time, even before SDL_Init(). This makes + * it useful for reporting errors like a failure to create a renderer or + * OpenGL context. + * + * On X11, SDL rolls its own dialog box with X11 primitives instead of a + * formal toolkit like GTK+ or Qt. + * + * Note that if SDL_Init() would fail because there isn't any available video + * target, this function is likely to fail for the same reasons. If this is a + * concern, check the return value from this function and fall back to writing + * to stderr if you can. + * + * \param messageboxdata the SDL_MessageBoxData structure with title, text and + * other options. + * \param buttonid the pointer to which user id of hit button should be + * copied. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ShowSimpleMessageBox + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid); + +/** + * Display a simple modal message box. + * + * If your needs aren't complex, this function is preferred over + * SDL_ShowMessageBox. + * + * `flags` may be any of the following: + * + * - `SDL_MESSAGEBOX_ERROR`: error dialog + * - `SDL_MESSAGEBOX_WARNING`: warning dialog + * - `SDL_MESSAGEBOX_INFORMATION`: informational dialog + * + * This function should be called on the thread that created the parent + * window, or on the main thread if the messagebox has no parent. It will + * block execution of that thread until the user clicks a button or closes the + * messagebox. + * + * This function may be called at any time, even before SDL_Init(). This makes + * it useful for reporting errors like a failure to create a renderer or + * OpenGL context. + * + * On X11, SDL rolls its own dialog box with X11 primitives instead of a + * formal toolkit like GTK+ or Qt. + * + * Note that if SDL_Init() would fail because there isn't any available video + * target, this function is likely to fail for the same reasons. If this is a + * concern, check the return value from this function and fall back to writing + * to stderr if you can. + * + * \param flags an SDL_MessageBoxFlags value. + * \param title UTF-8 title text. + * \param message UTF-8 message text. + * \param window the parent window, or NULL for no parent. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ShowMessageBox + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ShowSimpleMessageBox(SDL_MessageBoxFlags flags, const char *title, const char *message, SDL_Window *window); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_messagebox_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_metal.h b/thirdparty/sdl/include/SDL3/SDL_metal.h new file mode 100644 index 00000000000..14b1bc87a2f --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_metal.h @@ -0,0 +1,107 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryMetal + * + * Functions to creating Metal layers and views on SDL windows. + * + * This provides some platform-specific glue for Apple platforms. Most macOS + * and iOS apps can use SDL without these functions, but this API they can be + * useful for specific OS-level integration tasks. + */ + +#ifndef SDL_metal_h_ +#define SDL_metal_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A handle to a CAMetalLayer-backed NSView (macOS) or UIView (iOS/tvOS). + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef void *SDL_MetalView; + +/** + * \name Metal support functions + */ +/* @{ */ + +/** + * Create a CAMetalLayer-backed NSView/UIView and attach it to the specified + * window. + * + * On macOS, this does *not* associate a MTLDevice with the CAMetalLayer on + * its own. It is up to user code to do that. + * + * The returned handle can be casted directly to a NSView or UIView. To access + * the backing CAMetalLayer, call SDL_Metal_GetLayer(). + * + * \param window the window. + * \returns handle NSView or UIView. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Metal_DestroyView + * \sa SDL_Metal_GetLayer + */ +extern SDL_DECLSPEC SDL_MetalView SDLCALL SDL_Metal_CreateView(SDL_Window *window); + +/** + * Destroy an existing SDL_MetalView object. + * + * This should be called before SDL_DestroyWindow, if SDL_Metal_CreateView was + * called after SDL_CreateWindow. + * + * \param view the SDL_MetalView object. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Metal_CreateView + */ +extern SDL_DECLSPEC void SDLCALL SDL_Metal_DestroyView(SDL_MetalView view); + +/** + * Get a pointer to the backing CAMetalLayer for the given view. + * + * \param view the SDL_MetalView object. + * \returns a pointer. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void * SDLCALL SDL_Metal_GetLayer(SDL_MetalView view); + +/* @} *//* Metal support functions */ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_metal_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_misc.h b/thirdparty/sdl/include/SDL3/SDL_misc.h new file mode 100644 index 00000000000..3dd6fcddd60 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_misc.h @@ -0,0 +1,78 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryMisc + * + * SDL API functions that don't fit elsewhere. + */ + +#ifndef SDL_misc_h_ +#define SDL_misc_h_ + +#include +#include + +#include + +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Open a URL/URI in the browser or other appropriate external application. + * + * Open a URL in a separate, system-provided application. How this works will + * vary wildly depending on the platform. This will likely launch what makes + * sense to handle a specific URL's protocol (a web browser for `http://`, + * etc), but it might also be able to launch file managers for directories and + * other things. + * + * What happens when you open a URL varies wildly as well: your game window + * may lose focus (and may or may not lose focus if your game was fullscreen + * or grabbing input at the time). On mobile devices, your app will likely + * move to the background or your process might be paused. Any given platform + * may or may not handle a given URL. + * + * If this is unimplemented (or simply unavailable) for a platform, this will + * fail with an error. A successful result does not mean the URL loaded, just + * that we launched _something_ to handle it (or at least believe we did). + * + * All this to say: this function can be useful, but you should definitely + * test it on every platform you target. + * + * \param url a valid URL/URI to open. Use `file:///full/path/to/file` for + * local files, if supported. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_OpenURL(const char *url); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_misc_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_mouse.h b/thirdparty/sdl/include/SDL3/SDL_mouse.h new file mode 100644 index 00000000000..864135d2be0 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_mouse.h @@ -0,0 +1,689 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryMouse + * + * Any GUI application has to deal with the mouse, and SDL provides functions + * to manage mouse input and the displayed cursor. + * + * Most interactions with the mouse will come through the event subsystem. + * Moving a mouse generates an SDL_EVENT_MOUSE_MOTION event, pushing a button + * generates SDL_EVENT_MOUSE_BUTTON_DOWN, etc, but one can also query the + * current state of the mouse at any time with SDL_GetMouseState(). + * + * For certain games, it's useful to disassociate the mouse cursor from mouse + * input. An FPS, for example, would not want the player's motion to stop as + * the mouse hits the edge of the window. For these scenarios, use + * SDL_SetWindowRelativeMouseMode(), which hides the cursor, grabs mouse input + * to the window, and reads mouse input no matter how far it moves. + * + * Games that want the system to track the mouse but want to draw their own + * cursor can use SDL_HideCursor() and SDL_ShowCursor(). It might be more + * efficient to let the system manage the cursor, if possible, using + * SDL_SetCursor() with a custom image made through SDL_CreateColorCursor(), + * or perhaps just a specific system cursor from SDL_CreateSystemCursor(). + * + * SDL can, on many platforms, differentiate between multiple connected mice, + * allowing for interesting input scenarios and multiplayer games. They can be + * enumerated with SDL_GetMice(), and SDL will send SDL_EVENT_MOUSE_ADDED and + * SDL_EVENT_MOUSE_REMOVED events as they are connected and unplugged. + * + * Since many apps only care about basic mouse input, SDL offers a virtual + * mouse device for touch and pen input, which often can make a desktop + * application work on a touchscreen phone without any code changes. Apps that + * care about touch/pen separately from mouse input should filter out events + * with a `which` field of SDL_TOUCH_MOUSEID/SDL_PEN_MOUSEID. + */ + +#ifndef SDL_mouse_h_ +#define SDL_mouse_h_ + +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * This is a unique ID for a mouse for the time it is connected to the system, + * and is never reused for the lifetime of the application. + * + * If the mouse is disconnected and reconnected, it will get a new ID. + * + * The value 0 is an invalid ID. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_MouseID; + +/** + * The structure used to identify an SDL cursor. + * + * This is opaque data. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Cursor SDL_Cursor; + +/** + * Cursor types for SDL_CreateSystemCursor(). + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_SystemCursor +{ + SDL_SYSTEM_CURSOR_DEFAULT, /**< Default cursor. Usually an arrow. */ + SDL_SYSTEM_CURSOR_TEXT, /**< Text selection. Usually an I-beam. */ + SDL_SYSTEM_CURSOR_WAIT, /**< Wait. Usually an hourglass or watch or spinning ball. */ + SDL_SYSTEM_CURSOR_CROSSHAIR, /**< Crosshair. */ + SDL_SYSTEM_CURSOR_PROGRESS, /**< Program is busy but still interactive. Usually it's WAIT with an arrow. */ + SDL_SYSTEM_CURSOR_NWSE_RESIZE, /**< Double arrow pointing northwest and southeast. */ + SDL_SYSTEM_CURSOR_NESW_RESIZE, /**< Double arrow pointing northeast and southwest. */ + SDL_SYSTEM_CURSOR_EW_RESIZE, /**< Double arrow pointing west and east. */ + SDL_SYSTEM_CURSOR_NS_RESIZE, /**< Double arrow pointing north and south. */ + SDL_SYSTEM_CURSOR_MOVE, /**< Four pointed arrow pointing north, south, east, and west. */ + SDL_SYSTEM_CURSOR_NOT_ALLOWED, /**< Not permitted. Usually a slashed circle or crossbones. */ + SDL_SYSTEM_CURSOR_POINTER, /**< Pointer that indicates a link. Usually a pointing hand. */ + SDL_SYSTEM_CURSOR_NW_RESIZE, /**< Window resize top-left. This may be a single arrow or a double arrow like NWSE_RESIZE. */ + SDL_SYSTEM_CURSOR_N_RESIZE, /**< Window resize top. May be NS_RESIZE. */ + SDL_SYSTEM_CURSOR_NE_RESIZE, /**< Window resize top-right. May be NESW_RESIZE. */ + SDL_SYSTEM_CURSOR_E_RESIZE, /**< Window resize right. May be EW_RESIZE. */ + SDL_SYSTEM_CURSOR_SE_RESIZE, /**< Window resize bottom-right. May be NWSE_RESIZE. */ + SDL_SYSTEM_CURSOR_S_RESIZE, /**< Window resize bottom. May be NS_RESIZE. */ + SDL_SYSTEM_CURSOR_SW_RESIZE, /**< Window resize bottom-left. May be NESW_RESIZE. */ + SDL_SYSTEM_CURSOR_W_RESIZE, /**< Window resize left. May be EW_RESIZE. */ + SDL_SYSTEM_CURSOR_COUNT +} SDL_SystemCursor; + +/** + * Scroll direction types for the Scroll event + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_MouseWheelDirection +{ + SDL_MOUSEWHEEL_NORMAL, /**< The scroll direction is normal */ + SDL_MOUSEWHEEL_FLIPPED /**< The scroll direction is flipped / natural */ +} SDL_MouseWheelDirection; + +/** + * A bitmask of pressed mouse buttons, as reported by SDL_GetMouseState, etc. + * + * - Button 1: Left mouse button + * - Button 2: Middle mouse button + * - Button 3: Right mouse button + * - Button 4: Side mouse button 1 + * - Button 5: Side mouse button 2 + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_GetMouseState + * \sa SDL_GetGlobalMouseState + * \sa SDL_GetRelativeMouseState + */ +typedef Uint32 SDL_MouseButtonFlags; + +#define SDL_BUTTON_LEFT 1 +#define SDL_BUTTON_MIDDLE 2 +#define SDL_BUTTON_RIGHT 3 +#define SDL_BUTTON_X1 4 +#define SDL_BUTTON_X2 5 + +#define SDL_BUTTON_MASK(X) (1u << ((X)-1)) +#define SDL_BUTTON_LMASK SDL_BUTTON_MASK(SDL_BUTTON_LEFT) +#define SDL_BUTTON_MMASK SDL_BUTTON_MASK(SDL_BUTTON_MIDDLE) +#define SDL_BUTTON_RMASK SDL_BUTTON_MASK(SDL_BUTTON_RIGHT) +#define SDL_BUTTON_X1MASK SDL_BUTTON_MASK(SDL_BUTTON_X1) +#define SDL_BUTTON_X2MASK SDL_BUTTON_MASK(SDL_BUTTON_X2) + + +/* Function prototypes */ + +/** + * Return whether a mouse is currently connected. + * + * \returns true if a mouse is connected, false otherwise. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetMice + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasMouse(void); + +/** + * Get a list of currently connected mice. + * + * Note that this will include any device or virtual driver that includes + * mouse functionality, including some game controllers, KVM switches, etc. + * You should wait for input from a device before you consider it actively in + * use. + * + * \param count a pointer filled in with the number of mice returned, may be + * NULL. + * \returns a 0 terminated array of mouse instance IDs or NULL on failure; + * call SDL_GetError() for more information. This should be freed + * with SDL_free() when it is no longer needed. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetMouseNameForID + * \sa SDL_HasMouse + */ +extern SDL_DECLSPEC SDL_MouseID * SDLCALL SDL_GetMice(int *count); + +/** + * Get the name of a mouse. + * + * This function returns "" if the mouse doesn't have a name. + * + * \param instance_id the mouse instance ID. + * \returns the name of the selected mouse, or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetMice + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetMouseNameForID(SDL_MouseID instance_id); + +/** + * Get the window which currently has mouse focus. + * + * \returns the window with mouse focus. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GetMouseFocus(void); + +/** + * Query SDL's cache for the synchronous mouse button state and the + * window-relative SDL-cursor position. + * + * This function returns the cached synchronous state as SDL understands it + * from the last pump of the event queue. + * + * To query the platform for immediate asynchronous state, use + * SDL_GetGlobalMouseState. + * + * Passing non-NULL pointers to `x` or `y` will write the destination with + * respective x or y coordinates relative to the focused window. + * + * In Relative Mode, the SDL-cursor's position usually contradicts the + * platform-cursor's position as manually calculated from + * SDL_GetGlobalMouseState() and SDL_GetWindowPosition. + * + * \param x a pointer to receive the SDL-cursor's x-position from the focused + * window's top left corner, can be NULL if unused. + * \param y a pointer to receive the SDL-cursor's y-position from the focused + * window's top left corner, can be NULL if unused. + * \returns a 32-bit bitmask of the button state that can be bitwise-compared + * against the SDL_BUTTON_MASK(X) macro. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGlobalMouseState + * \sa SDL_GetRelativeMouseState + */ +extern SDL_DECLSPEC SDL_MouseButtonFlags SDLCALL SDL_GetMouseState(float *x, float *y); + +/** + * Query the platform for the asynchronous mouse button state and the + * desktop-relative platform-cursor position. + * + * This function immediately queries the platform for the most recent + * asynchronous state, more costly than retrieving SDL's cached state in + * SDL_GetMouseState(). + * + * Passing non-NULL pointers to `x` or `y` will write the destination with + * respective x or y coordinates relative to the desktop. + * + * In Relative Mode, the platform-cursor's position usually contradicts the + * SDL-cursor's position as manually calculated from SDL_GetMouseState() and + * SDL_GetWindowPosition. + * + * This function can be useful if you need to track the mouse outside of a + * specific window and SDL_CaptureMouse() doesn't fit your needs. For example, + * it could be useful if you need to track the mouse while dragging a window, + * where coordinates relative to a window might not be in sync at all times. + * + * \param x a pointer to receive the platform-cursor's x-position from the + * desktop's top left corner, can be NULL if unused. + * \param y a pointer to receive the platform-cursor's y-position from the + * desktop's top left corner, can be NULL if unused. + * \returns a 32-bit bitmask of the button state that can be bitwise-compared + * against the SDL_BUTTON_MASK(X) macro. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CaptureMouse + * \sa SDL_GetMouseState + * \sa SDL_GetGlobalMouseState + */ +extern SDL_DECLSPEC SDL_MouseButtonFlags SDLCALL SDL_GetGlobalMouseState(float *x, float *y); + +/** + * Query SDL's cache for the synchronous mouse button state and accumulated + * mouse delta since last call. + * + * This function returns the cached synchronous state as SDL understands it + * from the last pump of the event queue. + * + * To query the platform for immediate asynchronous state, use + * SDL_GetGlobalMouseState. + * + * Passing non-NULL pointers to `x` or `y` will write the destination with + * respective x or y deltas accumulated since the last call to this function + * (or since event initialization). + * + * This function is useful for reducing overhead by processing relative mouse + * inputs in one go per-frame instead of individually per-event, at the + * expense of losing the order between events within the frame (e.g. quickly + * pressing and releasing a button within the same frame). + * + * \param x a pointer to receive the x mouse delta accumulated since last + * call, can be NULL if unused. + * \param y a pointer to receive the y mouse delta accumulated since last + * call, can be NULL if unused. + * \returns a 32-bit bitmask of the button state that can be bitwise-compared + * against the SDL_BUTTON_MASK(X) macro. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetMouseState + * \sa SDL_GetGlobalMouseState + */ +extern SDL_DECLSPEC SDL_MouseButtonFlags SDLCALL SDL_GetRelativeMouseState(float *x, float *y); + +/** + * Move the mouse cursor to the given position within the window. + * + * This function generates a mouse motion event if relative mode is not + * enabled. If relative mode is enabled, you can force mouse events for the + * warp by setting the SDL_HINT_MOUSE_RELATIVE_WARP_MOTION hint. + * + * Note that this function will appear to succeed, but not actually move the + * mouse when used over Microsoft Remote Desktop. + * + * \param window the window to move the mouse into, or NULL for the current + * mouse focus. + * \param x the x coordinate within the window. + * \param y the y coordinate within the window. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_WarpMouseGlobal + */ +extern SDL_DECLSPEC void SDLCALL SDL_WarpMouseInWindow(SDL_Window *window, + float x, float y); + +/** + * Move the mouse to the given position in global screen space. + * + * This function generates a mouse motion event. + * + * A failure of this function usually means that it is unsupported by a + * platform. + * + * Note that this function will appear to succeed, but not actually move the + * mouse when used over Microsoft Remote Desktop. + * + * \param x the x coordinate. + * \param y the y coordinate. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_WarpMouseInWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WarpMouseGlobal(float x, float y); + +/** + * Set relative mouse mode for a window. + * + * While the window has focus and relative mouse mode is enabled, the cursor + * is hidden, the mouse position is constrained to the window, and SDL will + * report continuous relative mouse motion even if the mouse is at the edge of + * the window. + * + * If you'd like to keep the mouse position fixed while in relative mode you + * can use SDL_SetWindowMouseRect(). If you'd like the cursor to be at a + * specific location when relative mode ends, you should use + * SDL_WarpMouseInWindow() before disabling relative mode. + * + * This function will flush any pending mouse motion for this window. + * + * \param window the window to change. + * \param enabled true to enable relative mode, false to disable. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowRelativeMouseMode + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowRelativeMouseMode(SDL_Window *window, bool enabled); + +/** + * Query whether relative mouse mode is enabled for a window. + * + * \param window the window to query. + * \returns true if relative mode is enabled for a window or false otherwise. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowRelativeMouseMode + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowRelativeMouseMode(SDL_Window *window); + +/** + * Capture the mouse and to track input outside an SDL window. + * + * Capturing enables your app to obtain mouse events globally, instead of just + * within your window. Not all video targets support this function. When + * capturing is enabled, the current window will get all mouse events, but + * unlike relative mode, no change is made to the cursor and it is not + * restrained to your window. + * + * This function may also deny mouse input to other windows--both those in + * your application and others on the system--so you should use this function + * sparingly, and in small bursts. For example, you might want to track the + * mouse while the user is dragging something, until the user releases a mouse + * button. It is not recommended that you capture the mouse for long periods + * of time, such as the entire time your app is running. For that, you should + * probably use SDL_SetWindowRelativeMouseMode() or SDL_SetWindowMouseGrab(), + * depending on your goals. + * + * While captured, mouse events still report coordinates relative to the + * current (foreground) window, but those coordinates may be outside the + * bounds of the window (including negative values). Capturing is only allowed + * for the foreground window. If the window loses focus while capturing, the + * capture will be disabled automatically. + * + * While capturing is enabled, the current window will have the + * `SDL_WINDOW_MOUSE_CAPTURE` flag set. + * + * Please note that SDL will attempt to "auto capture" the mouse while the + * user is pressing a button; this is to try and make mouse behavior more + * consistent between platforms, and deal with the common case of a user + * dragging the mouse outside of the window. This means that if you are + * calling SDL_CaptureMouse() only to deal with this situation, you do not + * have to (although it is safe to do so). If this causes problems for your + * app, you can disable auto capture by setting the + * `SDL_HINT_MOUSE_AUTO_CAPTURE` hint to zero. + * + * \param enabled true to enable capturing, false to disable. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetGlobalMouseState + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CaptureMouse(bool enabled); + +/** + * Create a cursor using the specified bitmap data and mask (in MSB format). + * + * `mask` has to be in MSB (Most Significant Bit) format. + * + * The cursor width (`w`) must be a multiple of 8 bits. + * + * The cursor is created in black and white according to the following: + * + * - data=0, mask=1: white + * - data=1, mask=1: black + * - data=0, mask=0: transparent + * - data=1, mask=0: inverted color if possible, black if not. + * + * Cursors created with this function must be freed with SDL_DestroyCursor(). + * + * If you want to have a color cursor, or create your cursor from an + * SDL_Surface, you should use SDL_CreateColorCursor(). Alternately, you can + * hide the cursor and draw your own as part of your game's rendering, but it + * will be bound to the framerate. + * + * Also, SDL_CreateSystemCursor() is available, which provides several + * readily-available system cursors to pick from. + * + * \param data the color value for each pixel of the cursor. + * \param mask the mask value for each pixel of the cursor. + * \param w the width of the cursor. + * \param h the height of the cursor. + * \param hot_x the x-axis offset from the left of the cursor image to the + * mouse x position, in the range of 0 to `w` - 1. + * \param hot_y the y-axis offset from the top of the cursor image to the + * mouse y position, in the range of 0 to `h` - 1. + * \returns a new cursor with the specified parameters on success or NULL on + * failure; call SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateColorCursor + * \sa SDL_CreateSystemCursor + * \sa SDL_DestroyCursor + * \sa SDL_SetCursor + */ +extern SDL_DECLSPEC SDL_Cursor * SDLCALL SDL_CreateCursor(const Uint8 *data, + const Uint8 *mask, + int w, int h, int hot_x, + int hot_y); + +/** + * Create a color cursor. + * + * If this function is passed a surface with alternate representations, the + * surface will be interpreted as the content to be used for 100% display + * scale, and the alternate representations will be used for high DPI + * situations. For example, if the original surface is 32x32, then on a 2x + * macOS display or 200% display scale on Windows, a 64x64 version of the + * image will be used, if available. If a matching version of the image isn't + * available, the closest larger size image will be downscaled to the + * appropriate size and be used instead, if available. Otherwise, the closest + * smaller image will be upscaled and be used instead. + * + * \param surface an SDL_Surface structure representing the cursor image. + * \param hot_x the x position of the cursor hot spot. + * \param hot_y the y position of the cursor hot spot. + * \returns the new cursor on success or NULL on failure; call SDL_GetError() + * for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateCursor + * \sa SDL_CreateSystemCursor + * \sa SDL_DestroyCursor + * \sa SDL_SetCursor + */ +extern SDL_DECLSPEC SDL_Cursor * SDLCALL SDL_CreateColorCursor(SDL_Surface *surface, + int hot_x, + int hot_y); + +/** + * Create a system cursor. + * + * \param id an SDL_SystemCursor enum value. + * \returns a cursor on success or NULL on failure; call SDL_GetError() for + * more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroyCursor + */ +extern SDL_DECLSPEC SDL_Cursor * SDLCALL SDL_CreateSystemCursor(SDL_SystemCursor id); + +/** + * Set the active cursor. + * + * This function sets the currently active cursor to the specified one. If the + * cursor is currently visible, the change will be immediately represented on + * the display. SDL_SetCursor(NULL) can be used to force cursor redraw, if + * this is desired for any reason. + * + * \param cursor a cursor to make active. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetCursor + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetCursor(SDL_Cursor *cursor); + +/** + * Get the active cursor. + * + * This function returns a pointer to the current cursor which is owned by the + * library. It is not necessary to free the cursor with SDL_DestroyCursor(). + * + * \returns the active cursor or NULL if there is no mouse. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetCursor + */ +extern SDL_DECLSPEC SDL_Cursor * SDLCALL SDL_GetCursor(void); + +/** + * Get the default cursor. + * + * You do not have to call SDL_DestroyCursor() on the return value, but it is + * safe to do so. + * + * \returns the default cursor on success or NULL on failuree; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Cursor * SDLCALL SDL_GetDefaultCursor(void); + +/** + * Free a previously-created cursor. + * + * Use this function to free cursor resources created with SDL_CreateCursor(), + * SDL_CreateColorCursor() or SDL_CreateSystemCursor(). + * + * \param cursor the cursor to free. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateColorCursor + * \sa SDL_CreateCursor + * \sa SDL_CreateSystemCursor + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyCursor(SDL_Cursor *cursor); + +/** + * Show the cursor. + * + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CursorVisible + * \sa SDL_HideCursor + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ShowCursor(void); + +/** + * Hide the cursor. + * + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CursorVisible + * \sa SDL_ShowCursor + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HideCursor(void); + +/** + * Return whether the cursor is currently being shown. + * + * \returns `true` if the cursor is being shown, or `false` if the cursor is + * hidden. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HideCursor + * \sa SDL_ShowCursor + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CursorVisible(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_mouse_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_mutex.h b/thirdparty/sdl/include/SDL3/SDL_mutex.h new file mode 100644 index 00000000000..c88ec153153 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_mutex.h @@ -0,0 +1,1073 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_mutex_h_ +#define SDL_mutex_h_ + +/** + * # CategoryMutex + * + * SDL offers several thread synchronization primitives. This document can't + * cover the complicated topic of thread safety, but reading up on what each + * of these primitives are, why they are useful, and how to correctly use them + * is vital to writing correct and safe multithreaded programs. + * + * - Mutexes: SDL_CreateMutex() + * - Read/Write locks: SDL_CreateRWLock() + * - Semaphores: SDL_CreateSemaphore() + * - Condition variables: SDL_CreateCondition() + * + * SDL also offers a datatype, SDL_InitState, which can be used to make sure + * only one thread initializes/deinitializes some resource that several + * threads might try to use for the first time simultaneously. + */ + +#include +#include +#include +#include + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Enable thread safety attributes, only with clang. + * + * The attributes can be safely erased when compiling with other compilers. + * + * To enable analysis, set these environment variables before running cmake: + * + * ```bash + * export CC=clang + * export CFLAGS="-DSDL_THREAD_SAFETY_ANALYSIS -Wthread-safety" + * ``` + */ +#define SDL_THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) + +#elif defined(SDL_THREAD_SAFETY_ANALYSIS) && defined(__clang__) && (!defined(SWIG)) +#define SDL_THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) +#else +#define SDL_THREAD_ANNOTATION_ATTRIBUTE__(x) /* no-op */ +#endif + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_CAPABILITY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_SCOPED_CAPABILITY \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_GUARDED_BY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PT_GUARDED_BY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ACQUIRED_BEFORE(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ACQUIRED_AFTER(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_REQUIRES(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_REQUIRES_SHARED(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ACQUIRE(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ACQUIRE_SHARED(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_RELEASE(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(release_capability(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_RELEASE_SHARED(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_RELEASE_GENERIC(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(release_generic_capability(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_TRY_ACQUIRE(x, y) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(x, y)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_TRY_ACQUIRE_SHARED(x, y) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(x, y)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_EXCLUDES(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ASSERT_CAPABILITY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ASSERT_SHARED_CAPABILITY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_RETURN_CAPABILITY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) + +/** + * Wrapper around Clang thread safety analysis annotations. + * + * Please see https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutex-h + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NO_THREAD_SAFETY_ANALYSIS \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) + +/******************************************************************************/ + + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \name Mutex functions + */ +/* @{ */ + +/** + * A means to serialize access to a resource between threads. + * + * Mutexes (short for "mutual exclusion") are a synchronization primitive that + * allows exactly one thread to proceed at a time. + * + * Wikipedia has a thorough explanation of the concept: + * + * https://en.wikipedia.org/wiki/Mutex + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Mutex SDL_Mutex; + +/** + * Create a new mutex. + * + * All newly-created mutexes begin in the _unlocked_ state. + * + * Calls to SDL_LockMutex() will not return while the mutex is locked by + * another thread. See SDL_TryLockMutex() to attempt to lock without blocking. + * + * SDL mutexes are reentrant. + * + * \returns the initialized and unlocked mutex or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroyMutex + * \sa SDL_LockMutex + * \sa SDL_TryLockMutex + * \sa SDL_UnlockMutex + */ +extern SDL_DECLSPEC SDL_Mutex * SDLCALL SDL_CreateMutex(void); + +/** + * Lock the mutex. + * + * This will block until the mutex is available, which is to say it is in the + * unlocked state and the OS has chosen the caller as the next thread to lock + * it. Of all threads waiting to lock the mutex, only one may do so at a time. + * + * It is legal for the owning thread to lock an already-locked mutex. It must + * unlock it the same number of times before it is actually made available for + * other threads in the system (this is known as a "recursive mutex"). + * + * This function does not fail; if mutex is NULL, it will return immediately + * having locked nothing. If the mutex is valid, this function will always + * block until it can lock the mutex, and return with it locked. + * + * \param mutex the mutex to lock. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_TryLockMutex + * \sa SDL_UnlockMutex + */ +extern SDL_DECLSPEC void SDLCALL SDL_LockMutex(SDL_Mutex *mutex) SDL_ACQUIRE(mutex); + +/** + * Try to lock a mutex without blocking. + * + * This works just like SDL_LockMutex(), but if the mutex is not available, + * this function returns false immediately. + * + * This technique is useful if you need exclusive access to a resource but + * don't want to wait for it, and will return to it to try again later. + * + * This function returns true if passed a NULL mutex. + * + * \param mutex the mutex to try to lock. + * \returns true on success, false if the mutex would block. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockMutex + * \sa SDL_UnlockMutex + */ +extern SDL_DECLSPEC bool SDLCALL SDL_TryLockMutex(SDL_Mutex *mutex) SDL_TRY_ACQUIRE(0, mutex); + +/** + * Unlock the mutex. + * + * It is legal for the owning thread to lock an already-locked mutex. It must + * unlock it the same number of times before it is actually made available for + * other threads in the system (this is known as a "recursive mutex"). + * + * It is illegal to unlock a mutex that has not been locked by the current + * thread, and doing so results in undefined behavior. + * + * \param mutex the mutex to unlock. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockMutex + * \sa SDL_TryLockMutex + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnlockMutex(SDL_Mutex *mutex) SDL_RELEASE(mutex); + +/** + * Destroy a mutex created with SDL_CreateMutex(). + * + * This function must be called on any mutex that is no longer needed. Failure + * to destroy a mutex will result in a system memory or resource leak. While + * it is safe to destroy a mutex that is _unlocked_, it is not safe to attempt + * to destroy a locked mutex, and may result in undefined behavior depending + * on the platform. + * + * \param mutex the mutex to destroy. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateMutex + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyMutex(SDL_Mutex *mutex); + +/* @} *//* Mutex functions */ + + +/** + * \name Read/write lock functions + */ +/* @{ */ + +/** + * A mutex that allows read-only threads to run in parallel. + * + * A rwlock is roughly the same concept as SDL_Mutex, but allows threads that + * request read-only access to all hold the lock at the same time. If a thread + * requests write access, it will block until all read-only threads have + * released the lock, and no one else can hold the thread (for reading or + * writing) at the same time as the writing thread. + * + * This can be more efficient in cases where several threads need to access + * data frequently, but changes to that data are rare. + * + * There are other rules that apply to rwlocks that don't apply to mutexes, + * about how threads are scheduled and when they can be recursively locked. + * These are documented in the other rwlock functions. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_RWLock SDL_RWLock; + +/** + * Create a new read/write lock. + * + * A read/write lock is useful for situations where you have multiple threads + * trying to access a resource that is rarely updated. All threads requesting + * a read-only lock will be allowed to run in parallel; if a thread requests a + * write lock, it will be provided exclusive access. This makes it safe for + * multiple threads to use a resource at the same time if they promise not to + * change it, and when it has to be changed, the rwlock will serve as a + * gateway to make sure those changes can be made safely. + * + * In the right situation, a rwlock can be more efficient than a mutex, which + * only lets a single thread proceed at a time, even if it won't be modifying + * the data. + * + * All newly-created read/write locks begin in the _unlocked_ state. + * + * Calls to SDL_LockRWLockForReading() and SDL_LockRWLockForWriting will not + * return while the rwlock is locked _for writing_ by another thread. See + * SDL_TryLockRWLockForReading() and SDL_TryLockRWLockForWriting() to attempt + * to lock without blocking. + * + * SDL read/write locks are only recursive for read-only locks! They are not + * guaranteed to be fair, or provide access in a FIFO manner! They are not + * guaranteed to favor writers. You may not lock a rwlock for both read-only + * and write access at the same time from the same thread (so you can't + * promote your read-only lock to a write lock without unlocking first). + * + * \returns the initialized and unlocked read/write lock or NULL on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroyRWLock + * \sa SDL_LockRWLockForReading + * \sa SDL_LockRWLockForWriting + * \sa SDL_TryLockRWLockForReading + * \sa SDL_TryLockRWLockForWriting + * \sa SDL_UnlockRWLock + */ +extern SDL_DECLSPEC SDL_RWLock * SDLCALL SDL_CreateRWLock(void); + +/** + * Lock the read/write lock for _read only_ operations. + * + * This will block until the rwlock is available, which is to say it is not + * locked for writing by any other thread. Of all threads waiting to lock the + * rwlock, all may do so at the same time as long as they are requesting + * read-only access; if a thread wants to lock for writing, only one may do so + * at a time, and no other threads, read-only or not, may hold the lock at the + * same time. + * + * It is legal for the owning thread to lock an already-locked rwlock for + * reading. It must unlock it the same number of times before it is actually + * made available for other threads in the system (this is known as a + * "recursive rwlock"). + * + * Note that locking for writing is not recursive (this is only available to + * read-only locks). + * + * It is illegal to request a read-only lock from a thread that already holds + * the write lock. Doing so results in undefined behavior. Unlock the write + * lock before requesting a read-only lock. (But, of course, if you have the + * write lock, you don't need further locks to read in any case.) + * + * This function does not fail; if rwlock is NULL, it will return immediately + * having locked nothing. If the rwlock is valid, this function will always + * block until it can lock the mutex, and return with it locked. + * + * \param rwlock the read/write lock to lock. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockRWLockForWriting + * \sa SDL_TryLockRWLockForReading + * \sa SDL_UnlockRWLock + */ +extern SDL_DECLSPEC void SDLCALL SDL_LockRWLockForReading(SDL_RWLock *rwlock) SDL_ACQUIRE_SHARED(rwlock); + +/** + * Lock the read/write lock for _write_ operations. + * + * This will block until the rwlock is available, which is to say it is not + * locked for reading or writing by any other thread. Only one thread may hold + * the lock when it requests write access; all other threads, whether they + * also want to write or only want read-only access, must wait until the + * writer thread has released the lock. + * + * It is illegal for the owning thread to lock an already-locked rwlock for + * writing (read-only may be locked recursively, writing can not). Doing so + * results in undefined behavior. + * + * It is illegal to request a write lock from a thread that already holds a + * read-only lock. Doing so results in undefined behavior. Unlock the + * read-only lock before requesting a write lock. + * + * This function does not fail; if rwlock is NULL, it will return immediately + * having locked nothing. If the rwlock is valid, this function will always + * block until it can lock the mutex, and return with it locked. + * + * \param rwlock the read/write lock to lock. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockRWLockForReading + * \sa SDL_TryLockRWLockForWriting + * \sa SDL_UnlockRWLock + */ +extern SDL_DECLSPEC void SDLCALL SDL_LockRWLockForWriting(SDL_RWLock *rwlock) SDL_ACQUIRE(rwlock); + +/** + * Try to lock a read/write lock _for reading_ without blocking. + * + * This works just like SDL_LockRWLockForReading(), but if the rwlock is not + * available, then this function returns false immediately. + * + * This technique is useful if you need access to a resource but don't want to + * wait for it, and will return to it to try again later. + * + * Trying to lock for read-only access can succeed if other threads are + * holding read-only locks, as this won't prevent access. + * + * This function returns true if passed a NULL rwlock. + * + * \param rwlock the rwlock to try to lock. + * \returns true on success, false if the lock would block. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockRWLockForReading + * \sa SDL_TryLockRWLockForWriting + * \sa SDL_UnlockRWLock + */ +extern SDL_DECLSPEC bool SDLCALL SDL_TryLockRWLockForReading(SDL_RWLock *rwlock) SDL_TRY_ACQUIRE_SHARED(0, rwlock); + +/** + * Try to lock a read/write lock _for writing_ without blocking. + * + * This works just like SDL_LockRWLockForWriting(), but if the rwlock is not + * available, then this function returns false immediately. + * + * This technique is useful if you need exclusive access to a resource but + * don't want to wait for it, and will return to it to try again later. + * + * It is illegal for the owning thread to lock an already-locked rwlock for + * writing (read-only may be locked recursively, writing can not). Doing so + * results in undefined behavior. + * + * It is illegal to request a write lock from a thread that already holds a + * read-only lock. Doing so results in undefined behavior. Unlock the + * read-only lock before requesting a write lock. + * + * This function returns true if passed a NULL rwlock. + * + * \param rwlock the rwlock to try to lock. + * \returns true on success, false if the lock would block. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockRWLockForWriting + * \sa SDL_TryLockRWLockForReading + * \sa SDL_UnlockRWLock + */ +extern SDL_DECLSPEC bool SDLCALL SDL_TryLockRWLockForWriting(SDL_RWLock *rwlock) SDL_TRY_ACQUIRE(0, rwlock); + +/** + * Unlock the read/write lock. + * + * Use this function to unlock the rwlock, whether it was locked for read-only + * or write operations. + * + * It is legal for the owning thread to lock an already-locked read-only lock. + * It must unlock it the same number of times before it is actually made + * available for other threads in the system (this is known as a "recursive + * rwlock"). + * + * It is illegal to unlock a rwlock that has not been locked by the current + * thread, and doing so results in undefined behavior. + * + * \param rwlock the rwlock to unlock. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockRWLockForReading + * \sa SDL_LockRWLockForWriting + * \sa SDL_TryLockRWLockForReading + * \sa SDL_TryLockRWLockForWriting + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnlockRWLock(SDL_RWLock *rwlock) SDL_RELEASE_GENERIC(rwlock); + +/** + * Destroy a read/write lock created with SDL_CreateRWLock(). + * + * This function must be called on any read/write lock that is no longer + * needed. Failure to destroy a rwlock will result in a system memory or + * resource leak. While it is safe to destroy a rwlock that is _unlocked_, it + * is not safe to attempt to destroy a locked rwlock, and may result in + * undefined behavior depending on the platform. + * + * \param rwlock the rwlock to destroy. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateRWLock + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyRWLock(SDL_RWLock *rwlock); + +/* @} *//* Read/write lock functions */ + + +/** + * \name Semaphore functions + */ +/* @{ */ + +/** + * A means to manage access to a resource, by count, between threads. + * + * Semaphores (specifically, "counting semaphores"), let X number of threads + * request access at the same time, each thread granted access decrementing a + * counter. When the counter reaches zero, future requests block until a prior + * thread releases their request, incrementing the counter again. + * + * Wikipedia has a thorough explanation of the concept: + * + * https://en.wikipedia.org/wiki/Semaphore_(programming) + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Semaphore SDL_Semaphore; + +/** + * Create a semaphore. + * + * This function creates a new semaphore and initializes it with the value + * `initial_value`. Each wait operation on the semaphore will atomically + * decrement the semaphore value and potentially block if the semaphore value + * is 0. Each post operation will atomically increment the semaphore value and + * wake waiting threads and allow them to retry the wait operation. + * + * \param initial_value the starting value of the semaphore. + * \returns a new semaphore or NULL on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroySemaphore + * \sa SDL_SignalSemaphore + * \sa SDL_TryWaitSemaphore + * \sa SDL_GetSemaphoreValue + * \sa SDL_WaitSemaphore + * \sa SDL_WaitSemaphoreTimeout + */ +extern SDL_DECLSPEC SDL_Semaphore * SDLCALL SDL_CreateSemaphore(Uint32 initial_value); + +/** + * Destroy a semaphore. + * + * It is not safe to destroy a semaphore if there are threads currently + * waiting on it. + * + * \param sem the semaphore to destroy. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateSemaphore + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroySemaphore(SDL_Semaphore *sem); + +/** + * Wait until a semaphore has a positive value and then decrements it. + * + * This function suspends the calling thread until the semaphore pointed to by + * `sem` has a positive value, and then atomically decrement the semaphore + * value. + * + * This function is the equivalent of calling SDL_WaitSemaphoreTimeout() with + * a time length of -1. + * + * \param sem the semaphore wait on. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SignalSemaphore + * \sa SDL_TryWaitSemaphore + * \sa SDL_WaitSemaphoreTimeout + */ +extern SDL_DECLSPEC void SDLCALL SDL_WaitSemaphore(SDL_Semaphore *sem); + +/** + * See if a semaphore has a positive value and decrement it if it does. + * + * This function checks to see if the semaphore pointed to by `sem` has a + * positive value and atomically decrements the semaphore value if it does. If + * the semaphore doesn't have a positive value, the function immediately + * returns false. + * + * \param sem the semaphore to wait on. + * \returns true if the wait succeeds, false if the wait would block. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SignalSemaphore + * \sa SDL_WaitSemaphore + * \sa SDL_WaitSemaphoreTimeout + */ +extern SDL_DECLSPEC bool SDLCALL SDL_TryWaitSemaphore(SDL_Semaphore *sem); + +/** + * Wait until a semaphore has a positive value and then decrements it. + * + * This function suspends the calling thread until either the semaphore + * pointed to by `sem` has a positive value or the specified time has elapsed. + * If the call is successful it will atomically decrement the semaphore value. + * + * \param sem the semaphore to wait on. + * \param timeoutMS the length of the timeout, in milliseconds, or -1 to wait + * indefinitely. + * \returns true if the wait succeeds or false if the wait times out. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SignalSemaphore + * \sa SDL_TryWaitSemaphore + * \sa SDL_WaitSemaphore + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WaitSemaphoreTimeout(SDL_Semaphore *sem, Sint32 timeoutMS); + +/** + * Atomically increment a semaphore's value and wake waiting threads. + * + * \param sem the semaphore to increment. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_TryWaitSemaphore + * \sa SDL_WaitSemaphore + * \sa SDL_WaitSemaphoreTimeout + */ +extern SDL_DECLSPEC void SDLCALL SDL_SignalSemaphore(SDL_Semaphore *sem); + +/** + * Get the current value of a semaphore. + * + * \param sem the semaphore to query. + * \returns the current value of the semaphore. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_GetSemaphoreValue(SDL_Semaphore *sem); + +/* @} *//* Semaphore functions */ + + +/** + * \name Condition variable functions + */ +/* @{ */ + +/** + * A means to block multiple threads until a condition is satisfied. + * + * Condition variables, paired with an SDL_Mutex, let an app halt multiple + * threads until a condition has occurred, at which time the app can release + * one or all waiting threads. + * + * Wikipedia has a thorough explanation of the concept: + * + * https://en.wikipedia.org/wiki/Condition_variable + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Condition SDL_Condition; + +/** + * Create a condition variable. + * + * \returns a new condition variable or NULL on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BroadcastCondition + * \sa SDL_SignalCondition + * \sa SDL_WaitCondition + * \sa SDL_WaitConditionTimeout + * \sa SDL_DestroyCondition + */ +extern SDL_DECLSPEC SDL_Condition * SDLCALL SDL_CreateCondition(void); + +/** + * Destroy a condition variable. + * + * \param cond the condition variable to destroy. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateCondition + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyCondition(SDL_Condition *cond); + +/** + * Restart one of the threads that are waiting on the condition variable. + * + * \param cond the condition variable to signal. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BroadcastCondition + * \sa SDL_WaitCondition + * \sa SDL_WaitConditionTimeout + */ +extern SDL_DECLSPEC void SDLCALL SDL_SignalCondition(SDL_Condition *cond); + +/** + * Restart all threads that are waiting on the condition variable. + * + * \param cond the condition variable to signal. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SignalCondition + * \sa SDL_WaitCondition + * \sa SDL_WaitConditionTimeout + */ +extern SDL_DECLSPEC void SDLCALL SDL_BroadcastCondition(SDL_Condition *cond); + +/** + * Wait until a condition variable is signaled. + * + * This function unlocks the specified `mutex` and waits for another thread to + * call SDL_SignalCondition() or SDL_BroadcastCondition() on the condition + * variable `cond`. Once the condition variable is signaled, the mutex is + * re-locked and the function returns. + * + * The mutex must be locked before calling this function. Locking the mutex + * recursively (more than once) is not supported and leads to undefined + * behavior. + * + * This function is the equivalent of calling SDL_WaitConditionTimeout() with + * a time length of -1. + * + * \param cond the condition variable to wait on. + * \param mutex the mutex used to coordinate thread access. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BroadcastCondition + * \sa SDL_SignalCondition + * \sa SDL_WaitConditionTimeout + */ +extern SDL_DECLSPEC void SDLCALL SDL_WaitCondition(SDL_Condition *cond, SDL_Mutex *mutex); + +/** + * Wait until a condition variable is signaled or a certain time has passed. + * + * This function unlocks the specified `mutex` and waits for another thread to + * call SDL_SignalCondition() or SDL_BroadcastCondition() on the condition + * variable `cond`, or for the specified time to elapse. Once the condition + * variable is signaled or the time elapsed, the mutex is re-locked and the + * function returns. + * + * The mutex must be locked before calling this function. Locking the mutex + * recursively (more than once) is not supported and leads to undefined + * behavior. + * + * \param cond the condition variable to wait on. + * \param mutex the mutex used to coordinate thread access. + * \param timeoutMS the maximum time to wait, in milliseconds, or -1 to wait + * indefinitely. + * \returns true if the condition variable is signaled, false if the condition + * is not signaled in the allotted time. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BroadcastCondition + * \sa SDL_SignalCondition + * \sa SDL_WaitCondition + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WaitConditionTimeout(SDL_Condition *cond, + SDL_Mutex *mutex, Sint32 timeoutMS); + +/* @} *//* Condition variable functions */ + +/** + * \name Thread-safe initialization state functions + */ +/* @{ */ + +/** + * The current status of an SDL_InitState structure. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_InitStatus +{ + SDL_INIT_STATUS_UNINITIALIZED, + SDL_INIT_STATUS_INITIALIZING, + SDL_INIT_STATUS_INITIALIZED, + SDL_INIT_STATUS_UNINITIALIZING +} SDL_InitStatus; + +/** + * A structure used for thread-safe initialization and shutdown. + * + * Here is an example of using this: + * + * ```c + * static SDL_AtomicInitState init; + * + * bool InitSystem(void) + * { + * if (!SDL_ShouldInit(&init)) { + * // The system is initialized + * return true; + * } + * + * // At this point, you should not leave this function without calling SDL_SetInitialized() + * + * bool initialized = DoInitTasks(); + * SDL_SetInitialized(&init, initialized); + * return initialized; + * } + * + * bool UseSubsystem(void) + * { + * if (SDL_ShouldInit(&init)) { + * // Error, the subsystem isn't initialized + * SDL_SetInitialized(&init, false); + * return false; + * } + * + * // Do work using the initialized subsystem + * + * return true; + * } + * + * void QuitSystem(void) + * { + * if (!SDL_ShouldQuit(&init)) { + * // The system is not initialized + * return; + * } + * + * // At this point, you should not leave this function without calling SDL_SetInitialized() + * + * DoQuitTasks(); + * SDL_SetInitialized(&init, false); + * } + * ``` + * + * Note that this doesn't protect any resources created during initialization, + * or guarantee that nobody is using those resources during cleanup. You + * should use other mechanisms to protect those, if that's a concern for your + * code. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_InitState +{ + SDL_AtomicInt status; + SDL_ThreadID thread; + void *reserved; +} SDL_InitState; + +/** + * Return whether initialization should be done. + * + * This function checks the passed in state and if initialization should be + * done, sets the status to `SDL_INIT_STATUS_INITIALIZING` and returns true. + * If another thread is already modifying this state, it will wait until + * that's done before returning. + * + * If this function returns true, the calling code must call + * SDL_SetInitialized() to complete the initialization. + * + * \param state the initialization state to check. + * \returns true if initialization needs to be done, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetInitialized + * \sa SDL_ShouldQuit + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ShouldInit(SDL_InitState *state); + +/** + * Return whether cleanup should be done. + * + * This function checks the passed in state and if cleanup should be done, + * sets the status to `SDL_INIT_STATUS_UNINITIALIZING` and returns true. + * + * If this function returns true, the calling code must call + * SDL_SetInitialized() to complete the cleanup. + * + * \param state the initialization state to check. + * \returns true if cleanup needs to be done, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetInitialized + * \sa SDL_ShouldInit + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ShouldQuit(SDL_InitState *state); + +/** + * Finish an initialization state transition. + * + * This function sets the status of the passed in state to + * `SDL_INIT_STATUS_INITIALIZED` or `SDL_INIT_STATUS_UNINITIALIZED` and allows + * any threads waiting for the status to proceed. + * + * \param state the initialization state to check. + * \param initialized the new initialization state. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ShouldInit + * \sa SDL_ShouldQuit + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetInitialized(SDL_InitState *state, bool initialized); + +/* @} *//* Thread-safe initialization state functions */ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_mutex_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_pen.h b/thirdparty/sdl/include/SDL3/SDL_pen.h new file mode 100644 index 00000000000..5182eeb0ce1 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_pen.h @@ -0,0 +1,127 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryPen + * + * SDL pen event handling. + * + * SDL provides an API for pressure-sensitive pen (stylus and/or eraser) + * handling, e.g., for input and drawing tablets or suitably equipped mobile / + * tablet devices. + * + * To get started with pens, simply handle SDL_EVENT_PEN_* events. When a pen + * starts providing input, SDL will assign it a unique SDL_PenID, which will + * remain for the life of the process, as long as the pen stays connected. + * + * Pens may provide more than simple touch input; they might have other axes, + * such as pressure, tilt, rotation, etc. + */ + +#ifndef SDL_pen_h_ +#define SDL_pen_h_ + +#include +#include +#include + +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * SDL pen instance IDs. + * + * Zero is used to signify an invalid/null device. + * + * These show up in pen events when SDL sees input from them. They remain + * consistent as long as SDL can recognize a tool to be the same pen; but if a + * pen physically leaves the area and returns, it might get a new ID. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_PenID; + +/** + * The SDL_MouseID for mouse events simulated with pen input. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PEN_MOUSEID ((SDL_MouseID)-2) + +/** + * The SDL_TouchID for touch events simulated with pen input. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PEN_TOUCHID ((SDL_TouchID)-2) + + +/** + * Pen input flags, as reported by various pen events' `pen_state` field. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_PenInputFlags; + +#define SDL_PEN_INPUT_DOWN (1u << 0) /**< pen is pressed down */ +#define SDL_PEN_INPUT_BUTTON_1 (1u << 1) /**< button 1 is pressed */ +#define SDL_PEN_INPUT_BUTTON_2 (1u << 2) /**< button 2 is pressed */ +#define SDL_PEN_INPUT_BUTTON_3 (1u << 3) /**< button 3 is pressed */ +#define SDL_PEN_INPUT_BUTTON_4 (1u << 4) /**< button 4 is pressed */ +#define SDL_PEN_INPUT_BUTTON_5 (1u << 5) /**< button 5 is pressed */ +#define SDL_PEN_INPUT_ERASER_TIP (1u << 30) /**< eraser tip is used */ + +/** + * Pen axis indices. + * + * These are the valid values for the `axis` field in SDL_PenAxisEvent. All + * axes are either normalised to 0..1 or report a (positive or negative) angle + * in degrees, with 0.0 representing the centre. Not all pens/backends support + * all axes: unsupported axes are always zero. + * + * To convert angles for tilt and rotation into vector representation, use + * SDL_sinf on the XTILT, YTILT, or ROTATION component, for example: + * + * `SDL_sinf(xtilt * SDL_PI_F / 180.0)`. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_PenAxis +{ + SDL_PEN_AXIS_PRESSURE, /**< Pen pressure. Unidirectional: 0 to 1.0 */ + SDL_PEN_AXIS_XTILT, /**< Pen horizontal tilt angle. Bidirectional: -90.0 to 90.0 (left-to-right). */ + SDL_PEN_AXIS_YTILT, /**< Pen vertical tilt angle. Bidirectional: -90.0 to 90.0 (top-to-down). */ + SDL_PEN_AXIS_DISTANCE, /**< Pen distance to drawing surface. Unidirectional: 0.0 to 1.0 */ + SDL_PEN_AXIS_ROTATION, /**< Pen barrel rotation. Bidirectional: -180 to 179.9 (clockwise, 0 is facing up, -180.0 is facing down). */ + SDL_PEN_AXIS_SLIDER, /**< Pen finger wheel or slider (e.g., Airbrush Pen). Unidirectional: 0 to 1.0 */ + SDL_PEN_AXIS_TANGENTIAL_PRESSURE, /**< Pressure from squeezing the pen ("barrel pressure"). */ + SDL_PEN_AXIS_COUNT /**< Total known pen axis types in this version of SDL. This number may grow in future releases! */ +} SDL_PenAxis; + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif + +#endif /* SDL_pen_h_ */ + diff --git a/thirdparty/sdl/include/SDL3/SDL_pixels.h b/thirdparty/sdl/include/SDL3/SDL_pixels.h new file mode 100644 index 00000000000..39596c1c986 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_pixels.h @@ -0,0 +1,1441 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryPixels + * + * SDL offers facilities for pixel management. + * + * Largely these facilities deal with pixel _format_: what does this set of + * bits represent? + * + * If you mostly want to think of a pixel as some combination of red, green, + * blue, and maybe alpha intensities, this is all pretty straightforward, and + * in many cases, is enough information to build a perfectly fine game. + * + * However, the actual definition of a pixel is more complex than that: + * + * Pixels are a representation of a color in a particular color space. + * + * The first characteristic of a color space is the color type. SDL + * understands two different color types, RGB and YCbCr, or in SDL also + * referred to as YUV. + * + * RGB colors consist of red, green, and blue channels of color that are added + * together to represent the colors we see on the screen. + * + * https://en.wikipedia.org/wiki/RGB_color_model + * + * YCbCr colors represent colors as a Y luma brightness component and red and + * blue chroma color offsets. This color representation takes advantage of the + * fact that the human eye is more sensitive to brightness than the color in + * an image. The Cb and Cr components are often compressed and have lower + * resolution than the luma component. + * + * https://en.wikipedia.org/wiki/YCbCr + * + * When the color information in YCbCr is compressed, the Y pixels are left at + * full resolution and each Cr and Cb pixel represents an average of the color + * information in a block of Y pixels. The chroma location determines where in + * that block of pixels the color information is coming from. + * + * The color range defines how much of the pixel to use when converting a + * pixel into a color on the display. When the full color range is used, the + * entire numeric range of the pixel bits is significant. When narrow color + * range is used, for historical reasons, the pixel uses only a portion of the + * numeric range to represent colors. + * + * The color primaries and white point are a definition of the colors in the + * color space relative to the standard XYZ color space. + * + * https://en.wikipedia.org/wiki/CIE_1931_color_space + * + * The transfer characteristic, or opto-electrical transfer function (OETF), + * is the way a color is converted from mathematically linear space into a + * non-linear output signals. + * + * https://en.wikipedia.org/wiki/Rec._709#Transfer_characteristics + * + * The matrix coefficients are used to convert between YCbCr and RGB colors. + */ + +#ifndef SDL_pixels_h_ +#define SDL_pixels_h_ + +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A fully opaque 8-bit alpha value. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_ALPHA_TRANSPARENT + */ +#define SDL_ALPHA_OPAQUE 255 + +/** + * A fully opaque floating point alpha value. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_ALPHA_TRANSPARENT_FLOAT + */ +#define SDL_ALPHA_OPAQUE_FLOAT 1.0f + +/** + * A fully transparent 8-bit alpha value. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_ALPHA_OPAQUE + */ +#define SDL_ALPHA_TRANSPARENT 0 + +/** + * A fully transparent floating point alpha value. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_ALPHA_OPAQUE_FLOAT + */ +#define SDL_ALPHA_TRANSPARENT_FLOAT 0.0f + +/** + * Pixel type. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_PixelType +{ + SDL_PIXELTYPE_UNKNOWN, + SDL_PIXELTYPE_INDEX1, + SDL_PIXELTYPE_INDEX4, + SDL_PIXELTYPE_INDEX8, + SDL_PIXELTYPE_PACKED8, + SDL_PIXELTYPE_PACKED16, + SDL_PIXELTYPE_PACKED32, + SDL_PIXELTYPE_ARRAYU8, + SDL_PIXELTYPE_ARRAYU16, + SDL_PIXELTYPE_ARRAYU32, + SDL_PIXELTYPE_ARRAYF16, + SDL_PIXELTYPE_ARRAYF32, + /* appended at the end for compatibility with sdl2-compat: */ + SDL_PIXELTYPE_INDEX2 +} SDL_PixelType; + +/** + * Bitmap pixel order, high bit -> low bit. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_BitmapOrder +{ + SDL_BITMAPORDER_NONE, + SDL_BITMAPORDER_4321, + SDL_BITMAPORDER_1234 +} SDL_BitmapOrder; + +/** + * Packed component order, high bit -> low bit. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_PackedOrder +{ + SDL_PACKEDORDER_NONE, + SDL_PACKEDORDER_XRGB, + SDL_PACKEDORDER_RGBX, + SDL_PACKEDORDER_ARGB, + SDL_PACKEDORDER_RGBA, + SDL_PACKEDORDER_XBGR, + SDL_PACKEDORDER_BGRX, + SDL_PACKEDORDER_ABGR, + SDL_PACKEDORDER_BGRA +} SDL_PackedOrder; + +/** + * Array component order, low byte -> high byte. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_ArrayOrder +{ + SDL_ARRAYORDER_NONE, + SDL_ARRAYORDER_RGB, + SDL_ARRAYORDER_RGBA, + SDL_ARRAYORDER_ARGB, + SDL_ARRAYORDER_BGR, + SDL_ARRAYORDER_BGRA, + SDL_ARRAYORDER_ABGR +} SDL_ArrayOrder; + +/** + * Packed component layout. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_PackedLayout +{ + SDL_PACKEDLAYOUT_NONE, + SDL_PACKEDLAYOUT_332, + SDL_PACKEDLAYOUT_4444, + SDL_PACKEDLAYOUT_1555, + SDL_PACKEDLAYOUT_5551, + SDL_PACKEDLAYOUT_565, + SDL_PACKEDLAYOUT_8888, + SDL_PACKEDLAYOUT_2101010, + SDL_PACKEDLAYOUT_1010102 +} SDL_PackedLayout; + +/** + * A macro for defining custom FourCC pixel formats. + * + * For example, defining SDL_PIXELFORMAT_YV12 looks like this: + * + * ```c + * SDL_DEFINE_PIXELFOURCC('Y', 'V', '1', '2') + * ``` + * + * \param A the first character of the FourCC code. + * \param B the second character of the FourCC code. + * \param C the third character of the FourCC code. + * \param D the fourth character of the FourCC code. + * \returns a format value in the style of SDL_PixelFormat. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_DEFINE_PIXELFOURCC(A, B, C, D) SDL_FOURCC(A, B, C, D) + +/** + * A macro for defining custom non-FourCC pixel formats. + * + * For example, defining SDL_PIXELFORMAT_RGBA8888 looks like this: + * + * ```c + * SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_RGBA, SDL_PACKEDLAYOUT_8888, 32, 4) + * ``` + * + * \param type the type of the new format, probably a SDL_PixelType value. + * \param order the order of the new format, probably a SDL_BitmapOrder, + * SDL_PackedOrder, or SDL_ArrayOrder value. + * \param layout the layout of the new format, probably an SDL_PackedLayout + * value or zero. + * \param bits the number of bits per pixel of the new format. + * \param bytes the number of bytes per pixel of the new format. + * \returns a format value in the style of SDL_PixelFormat. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_DEFINE_PIXELFORMAT(type, order, layout, bits, bytes) \ + ((1 << 28) | ((type) << 24) | ((order) << 20) | ((layout) << 16) | \ + ((bits) << 8) | ((bytes) << 0)) + +/** + * A macro to retrieve the flags of an SDL_PixelFormat. + * + * This macro is generally not needed directly by an app, which should use + * specific tests, like SDL_ISPIXELFORMAT_FOURCC, instead. + * + * \param format an SDL_PixelFormat to check. + * \returns the flags of `format`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PIXELFLAG(format) (((format) >> 28) & 0x0F) + +/** + * A macro to retrieve the type of an SDL_PixelFormat. + * + * This is usually a value from the SDL_PixelType enumeration. + * + * \param format an SDL_PixelFormat to check. + * \returns the type of `format`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PIXELTYPE(format) (((format) >> 24) & 0x0F) + +/** + * A macro to retrieve the order of an SDL_PixelFormat. + * + * This is usually a value from the SDL_BitmapOrder, SDL_PackedOrder, or + * SDL_ArrayOrder enumerations, depending on the format type. + * + * \param format an SDL_PixelFormat to check. + * \returns the order of `format`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PIXELORDER(format) (((format) >> 20) & 0x0F) + +/** + * A macro to retrieve the layout of an SDL_PixelFormat. + * + * This is usually a value from the SDL_PackedLayout enumeration, or zero if a + * layout doesn't make sense for the format type. + * + * \param format an SDL_PixelFormat to check. + * \returns the layout of `format`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PIXELLAYOUT(format) (((format) >> 16) & 0x0F) + +/** + * A macro to determine an SDL_PixelFormat's bits per pixel. + * + * Note that this macro double-evaluates its parameter, so do not use + * expressions with side-effects here. + * + * FourCC formats will report zero here, as it rarely makes sense to measure + * them per-pixel. + * + * \param format an SDL_PixelFormat to check. + * \returns the bits-per-pixel of `format`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_BYTESPERPIXEL + */ +#define SDL_BITSPERPIXEL(format) \ + (SDL_ISPIXELFORMAT_FOURCC(format) ? 0 : (((format) >> 8) & 0xFF)) + +/** + * A macro to determine an SDL_PixelFormat's bytes per pixel. + * + * Note that this macro double-evaluates its parameter, so do not use + * expressions with side-effects here. + * + * FourCC formats do their best here, but many of them don't have a meaningful + * measurement of bytes per pixel. + * + * \param format an SDL_PixelFormat to check. + * \returns the bytes-per-pixel of `format`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_BITSPERPIXEL + */ +#define SDL_BYTESPERPIXEL(format) \ + (SDL_ISPIXELFORMAT_FOURCC(format) ? \ + ((((format) == SDL_PIXELFORMAT_YUY2) || \ + ((format) == SDL_PIXELFORMAT_UYVY) || \ + ((format) == SDL_PIXELFORMAT_YVYU) || \ + ((format) == SDL_PIXELFORMAT_P010)) ? 2 : 1) : (((format) >> 0) & 0xFF)) + + +/** + * A macro to determine if an SDL_PixelFormat is an indexed format. + * + * Note that this macro double-evaluates its parameter, so do not use + * expressions with side-effects here. + * + * \param format an SDL_PixelFormat to check. + * \returns true if the format is indexed, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISPIXELFORMAT_INDEXED(format) \ + (!SDL_ISPIXELFORMAT_FOURCC(format) && \ + ((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX1) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX2) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX4) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX8))) + +/** + * A macro to determine if an SDL_PixelFormat is a packed format. + * + * Note that this macro double-evaluates its parameter, so do not use + * expressions with side-effects here. + * + * \param format an SDL_PixelFormat to check. + * \returns true if the format is packed, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISPIXELFORMAT_PACKED(format) \ + (!SDL_ISPIXELFORMAT_FOURCC(format) && \ + ((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED8) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED16) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED32))) + +/** + * A macro to determine if an SDL_PixelFormat is an array format. + * + * Note that this macro double-evaluates its parameter, so do not use + * expressions with side-effects here. + * + * \param format an SDL_PixelFormat to check. + * \returns true if the format is an array, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISPIXELFORMAT_ARRAY(format) \ + (!SDL_ISPIXELFORMAT_FOURCC(format) && \ + ((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU8) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU16) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU32) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF16) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF32))) + +/** + * A macro to determine if an SDL_PixelFormat is a 10-bit format. + * + * Note that this macro double-evaluates its parameter, so do not use + * expressions with side-effects here. + * + * \param format an SDL_PixelFormat to check. + * \returns true if the format is 10-bit, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISPIXELFORMAT_10BIT(format) \ + (!SDL_ISPIXELFORMAT_FOURCC(format) && \ + ((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED32) && \ + (SDL_PIXELLAYOUT(format) == SDL_PACKEDLAYOUT_2101010))) + +/** + * A macro to determine if an SDL_PixelFormat is a floating point format. + * + * Note that this macro double-evaluates its parameter, so do not use + * expressions with side-effects here. + * + * \param format an SDL_PixelFormat to check. + * \returns true if the format is 10-bit, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISPIXELFORMAT_FLOAT(format) \ + (!SDL_ISPIXELFORMAT_FOURCC(format) && \ + ((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF16) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF32))) + +/** + * A macro to determine if an SDL_PixelFormat has an alpha channel. + * + * Note that this macro double-evaluates its parameter, so do not use + * expressions with side-effects here. + * + * \param format an SDL_PixelFormat to check. + * \returns true if the format has alpha, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISPIXELFORMAT_ALPHA(format) \ + ((SDL_ISPIXELFORMAT_PACKED(format) && \ + ((SDL_PIXELORDER(format) == SDL_PACKEDORDER_ARGB) || \ + (SDL_PIXELORDER(format) == SDL_PACKEDORDER_RGBA) || \ + (SDL_PIXELORDER(format) == SDL_PACKEDORDER_ABGR) || \ + (SDL_PIXELORDER(format) == SDL_PACKEDORDER_BGRA))) || \ + (SDL_ISPIXELFORMAT_ARRAY(format) && \ + ((SDL_PIXELORDER(format) == SDL_ARRAYORDER_ARGB) || \ + (SDL_PIXELORDER(format) == SDL_ARRAYORDER_RGBA) || \ + (SDL_PIXELORDER(format) == SDL_ARRAYORDER_ABGR) || \ + (SDL_PIXELORDER(format) == SDL_ARRAYORDER_BGRA)))) + + +/** + * A macro to determine if an SDL_PixelFormat is a "FourCC" format. + * + * This covers custom and other unusual formats. + * + * Note that this macro double-evaluates its parameter, so do not use + * expressions with side-effects here. + * + * \param format an SDL_PixelFormat to check. + * \returns true if the format has alpha, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISPIXELFORMAT_FOURCC(format) /* The flag is set to 1 because 0x1? is not in the printable ASCII range */ \ + ((format) && (SDL_PIXELFLAG(format) != 1)) + +/* Note: If you modify this enum, update SDL_GetPixelFormatName() */ + +/** + * Pixel format. + * + * SDL's pixel formats have the following naming convention: + * + * - Names with a list of components and a single bit count, such as RGB24 and + * ABGR32, define a platform-independent encoding into bytes in the order + * specified. For example, in RGB24 data, each pixel is encoded in 3 bytes + * (red, green, blue) in that order, and in ABGR32 data, each pixel is + * encoded in 4 bytes (alpha, blue, green, red) in that order. Use these + * names if the property of a format that is important to you is the order + * of the bytes in memory or on disk. + * - Names with a bit count per component, such as ARGB8888 and XRGB1555, are + * "packed" into an appropriately-sized integer in the platform's native + * endianness. For example, ARGB8888 is a sequence of 32-bit integers; in + * each integer, the most significant bits are alpha, and the least + * significant bits are blue. On a little-endian CPU such as x86, the least + * significant bits of each integer are arranged first in memory, but on a + * big-endian CPU such as s390x, the most significant bits are arranged + * first. Use these names if the property of a format that is important to + * you is the meaning of each bit position within a native-endianness + * integer. + * - In indexed formats such as INDEX4LSB, each pixel is represented by + * encoding an index into the palette into the indicated number of bits, + * with multiple pixels packed into each byte if appropriate. In LSB + * formats, the first (leftmost) pixel is stored in the least-significant + * bits of the byte; in MSB formats, it's stored in the most-significant + * bits. INDEX8 does not need LSB/MSB variants, because each pixel exactly + * fills one byte. + * + * The 32-bit byte-array encodings such as RGBA32 are aliases for the + * appropriate 8888 encoding for the current platform. For example, RGBA32 is + * an alias for ABGR8888 on little-endian CPUs like x86, or an alias for + * RGBA8888 on big-endian CPUs. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_PixelFormat +{ + SDL_PIXELFORMAT_UNKNOWN = 0, + SDL_PIXELFORMAT_INDEX1LSB = 0x11100100u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX1, SDL_BITMAPORDER_4321, 0, 1, 0), */ + SDL_PIXELFORMAT_INDEX1MSB = 0x11200100u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX1, SDL_BITMAPORDER_1234, 0, 1, 0), */ + SDL_PIXELFORMAT_INDEX2LSB = 0x1c100200u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX2, SDL_BITMAPORDER_4321, 0, 2, 0), */ + SDL_PIXELFORMAT_INDEX2MSB = 0x1c200200u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX2, SDL_BITMAPORDER_1234, 0, 2, 0), */ + SDL_PIXELFORMAT_INDEX4LSB = 0x12100400u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX4, SDL_BITMAPORDER_4321, 0, 4, 0), */ + SDL_PIXELFORMAT_INDEX4MSB = 0x12200400u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX4, SDL_BITMAPORDER_1234, 0, 4, 0), */ + SDL_PIXELFORMAT_INDEX8 = 0x13000801u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX8, 0, 0, 8, 1), */ + SDL_PIXELFORMAT_RGB332 = 0x14110801u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED8, SDL_PACKEDORDER_XRGB, SDL_PACKEDLAYOUT_332, 8, 1), */ + SDL_PIXELFORMAT_XRGB4444 = 0x15120c02u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XRGB, SDL_PACKEDLAYOUT_4444, 12, 2), */ + SDL_PIXELFORMAT_XBGR4444 = 0x15520c02u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XBGR, SDL_PACKEDLAYOUT_4444, 12, 2), */ + SDL_PIXELFORMAT_XRGB1555 = 0x15130f02u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XRGB, SDL_PACKEDLAYOUT_1555, 15, 2), */ + SDL_PIXELFORMAT_XBGR1555 = 0x15530f02u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XBGR, SDL_PACKEDLAYOUT_1555, 15, 2), */ + SDL_PIXELFORMAT_ARGB4444 = 0x15321002u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_ARGB, SDL_PACKEDLAYOUT_4444, 16, 2), */ + SDL_PIXELFORMAT_RGBA4444 = 0x15421002u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_RGBA, SDL_PACKEDLAYOUT_4444, 16, 2), */ + SDL_PIXELFORMAT_ABGR4444 = 0x15721002u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_ABGR, SDL_PACKEDLAYOUT_4444, 16, 2), */ + SDL_PIXELFORMAT_BGRA4444 = 0x15821002u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_BGRA, SDL_PACKEDLAYOUT_4444, 16, 2), */ + SDL_PIXELFORMAT_ARGB1555 = 0x15331002u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_ARGB, SDL_PACKEDLAYOUT_1555, 16, 2), */ + SDL_PIXELFORMAT_RGBA5551 = 0x15441002u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_RGBA, SDL_PACKEDLAYOUT_5551, 16, 2), */ + SDL_PIXELFORMAT_ABGR1555 = 0x15731002u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_ABGR, SDL_PACKEDLAYOUT_1555, 16, 2), */ + SDL_PIXELFORMAT_BGRA5551 = 0x15841002u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_BGRA, SDL_PACKEDLAYOUT_5551, 16, 2), */ + SDL_PIXELFORMAT_RGB565 = 0x15151002u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XRGB, SDL_PACKEDLAYOUT_565, 16, 2), */ + SDL_PIXELFORMAT_BGR565 = 0x15551002u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XBGR, SDL_PACKEDLAYOUT_565, 16, 2), */ + SDL_PIXELFORMAT_RGB24 = 0x17101803u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU8, SDL_ARRAYORDER_RGB, 0, 24, 3), */ + SDL_PIXELFORMAT_BGR24 = 0x17401803u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU8, SDL_ARRAYORDER_BGR, 0, 24, 3), */ + SDL_PIXELFORMAT_XRGB8888 = 0x16161804u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_XRGB, SDL_PACKEDLAYOUT_8888, 24, 4), */ + SDL_PIXELFORMAT_RGBX8888 = 0x16261804u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_RGBX, SDL_PACKEDLAYOUT_8888, 24, 4), */ + SDL_PIXELFORMAT_XBGR8888 = 0x16561804u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_XBGR, SDL_PACKEDLAYOUT_8888, 24, 4), */ + SDL_PIXELFORMAT_BGRX8888 = 0x16661804u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_BGRX, SDL_PACKEDLAYOUT_8888, 24, 4), */ + SDL_PIXELFORMAT_ARGB8888 = 0x16362004u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ARGB, SDL_PACKEDLAYOUT_8888, 32, 4), */ + SDL_PIXELFORMAT_RGBA8888 = 0x16462004u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_RGBA, SDL_PACKEDLAYOUT_8888, 32, 4), */ + SDL_PIXELFORMAT_ABGR8888 = 0x16762004u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ABGR, SDL_PACKEDLAYOUT_8888, 32, 4), */ + SDL_PIXELFORMAT_BGRA8888 = 0x16862004u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_BGRA, SDL_PACKEDLAYOUT_8888, 32, 4), */ + SDL_PIXELFORMAT_XRGB2101010 = 0x16172004u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_XRGB, SDL_PACKEDLAYOUT_2101010, 32, 4), */ + SDL_PIXELFORMAT_XBGR2101010 = 0x16572004u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_XBGR, SDL_PACKEDLAYOUT_2101010, 32, 4), */ + SDL_PIXELFORMAT_ARGB2101010 = 0x16372004u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ARGB, SDL_PACKEDLAYOUT_2101010, 32, 4), */ + SDL_PIXELFORMAT_ABGR2101010 = 0x16772004u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ABGR, SDL_PACKEDLAYOUT_2101010, 32, 4), */ + SDL_PIXELFORMAT_RGB48 = 0x18103006u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU16, SDL_ARRAYORDER_RGB, 0, 48, 6), */ + SDL_PIXELFORMAT_BGR48 = 0x18403006u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU16, SDL_ARRAYORDER_BGR, 0, 48, 6), */ + SDL_PIXELFORMAT_RGBA64 = 0x18204008u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU16, SDL_ARRAYORDER_RGBA, 0, 64, 8), */ + SDL_PIXELFORMAT_ARGB64 = 0x18304008u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU16, SDL_ARRAYORDER_ARGB, 0, 64, 8), */ + SDL_PIXELFORMAT_BGRA64 = 0x18504008u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU16, SDL_ARRAYORDER_BGRA, 0, 64, 8), */ + SDL_PIXELFORMAT_ABGR64 = 0x18604008u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU16, SDL_ARRAYORDER_ABGR, 0, 64, 8), */ + SDL_PIXELFORMAT_RGB48_FLOAT = 0x1a103006u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF16, SDL_ARRAYORDER_RGB, 0, 48, 6), */ + SDL_PIXELFORMAT_BGR48_FLOAT = 0x1a403006u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF16, SDL_ARRAYORDER_BGR, 0, 48, 6), */ + SDL_PIXELFORMAT_RGBA64_FLOAT = 0x1a204008u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF16, SDL_ARRAYORDER_RGBA, 0, 64, 8), */ + SDL_PIXELFORMAT_ARGB64_FLOAT = 0x1a304008u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF16, SDL_ARRAYORDER_ARGB, 0, 64, 8), */ + SDL_PIXELFORMAT_BGRA64_FLOAT = 0x1a504008u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF16, SDL_ARRAYORDER_BGRA, 0, 64, 8), */ + SDL_PIXELFORMAT_ABGR64_FLOAT = 0x1a604008u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF16, SDL_ARRAYORDER_ABGR, 0, 64, 8), */ + SDL_PIXELFORMAT_RGB96_FLOAT = 0x1b10600cu, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF32, SDL_ARRAYORDER_RGB, 0, 96, 12), */ + SDL_PIXELFORMAT_BGR96_FLOAT = 0x1b40600cu, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF32, SDL_ARRAYORDER_BGR, 0, 96, 12), */ + SDL_PIXELFORMAT_RGBA128_FLOAT = 0x1b208010u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF32, SDL_ARRAYORDER_RGBA, 0, 128, 16), */ + SDL_PIXELFORMAT_ARGB128_FLOAT = 0x1b308010u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF32, SDL_ARRAYORDER_ARGB, 0, 128, 16), */ + SDL_PIXELFORMAT_BGRA128_FLOAT = 0x1b508010u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF32, SDL_ARRAYORDER_BGRA, 0, 128, 16), */ + SDL_PIXELFORMAT_ABGR128_FLOAT = 0x1b608010u, + /* SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYF32, SDL_ARRAYORDER_ABGR, 0, 128, 16), */ + + SDL_PIXELFORMAT_YV12 = 0x32315659u, /**< Planar mode: Y + V + U (3 planes) */ + /* SDL_DEFINE_PIXELFOURCC('Y', 'V', '1', '2'), */ + SDL_PIXELFORMAT_IYUV = 0x56555949u, /**< Planar mode: Y + U + V (3 planes) */ + /* SDL_DEFINE_PIXELFOURCC('I', 'Y', 'U', 'V'), */ + SDL_PIXELFORMAT_YUY2 = 0x32595559u, /**< Packed mode: Y0+U0+Y1+V0 (1 plane) */ + /* SDL_DEFINE_PIXELFOURCC('Y', 'U', 'Y', '2'), */ + SDL_PIXELFORMAT_UYVY = 0x59565955u, /**< Packed mode: U0+Y0+V0+Y1 (1 plane) */ + /* SDL_DEFINE_PIXELFOURCC('U', 'Y', 'V', 'Y'), */ + SDL_PIXELFORMAT_YVYU = 0x55595659u, /**< Packed mode: Y0+V0+Y1+U0 (1 plane) */ + /* SDL_DEFINE_PIXELFOURCC('Y', 'V', 'Y', 'U'), */ + SDL_PIXELFORMAT_NV12 = 0x3231564eu, /**< Planar mode: Y + U/V interleaved (2 planes) */ + /* SDL_DEFINE_PIXELFOURCC('N', 'V', '1', '2'), */ + SDL_PIXELFORMAT_NV21 = 0x3132564eu, /**< Planar mode: Y + V/U interleaved (2 planes) */ + /* SDL_DEFINE_PIXELFOURCC('N', 'V', '2', '1'), */ + SDL_PIXELFORMAT_P010 = 0x30313050u, /**< Planar mode: Y + U/V interleaved (2 planes) */ + /* SDL_DEFINE_PIXELFOURCC('P', '0', '1', '0'), */ + SDL_PIXELFORMAT_EXTERNAL_OES = 0x2053454fu, /**< Android video texture format */ + /* SDL_DEFINE_PIXELFOURCC('O', 'E', 'S', ' ') */ + + SDL_PIXELFORMAT_MJPG = 0x47504a4du, /**< Motion JPEG */ + /* SDL_DEFINE_PIXELFOURCC('M', 'J', 'P', 'G') */ + + /* Aliases for RGBA byte arrays of color data, for the current platform */ + #if SDL_BYTEORDER == SDL_BIG_ENDIAN + SDL_PIXELFORMAT_RGBA32 = SDL_PIXELFORMAT_RGBA8888, + SDL_PIXELFORMAT_ARGB32 = SDL_PIXELFORMAT_ARGB8888, + SDL_PIXELFORMAT_BGRA32 = SDL_PIXELFORMAT_BGRA8888, + SDL_PIXELFORMAT_ABGR32 = SDL_PIXELFORMAT_ABGR8888, + SDL_PIXELFORMAT_RGBX32 = SDL_PIXELFORMAT_RGBX8888, + SDL_PIXELFORMAT_XRGB32 = SDL_PIXELFORMAT_XRGB8888, + SDL_PIXELFORMAT_BGRX32 = SDL_PIXELFORMAT_BGRX8888, + SDL_PIXELFORMAT_XBGR32 = SDL_PIXELFORMAT_XBGR8888 + #else + SDL_PIXELFORMAT_RGBA32 = SDL_PIXELFORMAT_ABGR8888, + SDL_PIXELFORMAT_ARGB32 = SDL_PIXELFORMAT_BGRA8888, + SDL_PIXELFORMAT_BGRA32 = SDL_PIXELFORMAT_ARGB8888, + SDL_PIXELFORMAT_ABGR32 = SDL_PIXELFORMAT_RGBA8888, + SDL_PIXELFORMAT_RGBX32 = SDL_PIXELFORMAT_XBGR8888, + SDL_PIXELFORMAT_XRGB32 = SDL_PIXELFORMAT_BGRX8888, + SDL_PIXELFORMAT_BGRX32 = SDL_PIXELFORMAT_XRGB8888, + SDL_PIXELFORMAT_XBGR32 = SDL_PIXELFORMAT_RGBX8888 + #endif +} SDL_PixelFormat; + +/** + * Colorspace color type. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_ColorType +{ + SDL_COLOR_TYPE_UNKNOWN = 0, + SDL_COLOR_TYPE_RGB = 1, + SDL_COLOR_TYPE_YCBCR = 2 +} SDL_ColorType; + +/** + * Colorspace color range, as described by + * https://www.itu.int/rec/R-REC-BT.2100-2-201807-I/en + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_ColorRange +{ + SDL_COLOR_RANGE_UNKNOWN = 0, + SDL_COLOR_RANGE_LIMITED = 1, /**< Narrow range, e.g. 16-235 for 8-bit RGB and luma, and 16-240 for 8-bit chroma */ + SDL_COLOR_RANGE_FULL = 2 /**< Full range, e.g. 0-255 for 8-bit RGB and luma, and 1-255 for 8-bit chroma */ +} SDL_ColorRange; + +/** + * Colorspace color primaries, as described by + * https://www.itu.int/rec/T-REC-H.273-201612-S/en + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_ColorPrimaries +{ + SDL_COLOR_PRIMARIES_UNKNOWN = 0, + SDL_COLOR_PRIMARIES_BT709 = 1, /**< ITU-R BT.709-6 */ + SDL_COLOR_PRIMARIES_UNSPECIFIED = 2, + SDL_COLOR_PRIMARIES_BT470M = 4, /**< ITU-R BT.470-6 System M */ + SDL_COLOR_PRIMARIES_BT470BG = 5, /**< ITU-R BT.470-6 System B, G / ITU-R BT.601-7 625 */ + SDL_COLOR_PRIMARIES_BT601 = 6, /**< ITU-R BT.601-7 525, SMPTE 170M */ + SDL_COLOR_PRIMARIES_SMPTE240 = 7, /**< SMPTE 240M, functionally the same as SDL_COLOR_PRIMARIES_BT601 */ + SDL_COLOR_PRIMARIES_GENERIC_FILM = 8, /**< Generic film (color filters using Illuminant C) */ + SDL_COLOR_PRIMARIES_BT2020 = 9, /**< ITU-R BT.2020-2 / ITU-R BT.2100-0 */ + SDL_COLOR_PRIMARIES_XYZ = 10, /**< SMPTE ST 428-1 */ + SDL_COLOR_PRIMARIES_SMPTE431 = 11, /**< SMPTE RP 431-2 */ + SDL_COLOR_PRIMARIES_SMPTE432 = 12, /**< SMPTE EG 432-1 / DCI P3 */ + SDL_COLOR_PRIMARIES_EBU3213 = 22, /**< EBU Tech. 3213-E */ + SDL_COLOR_PRIMARIES_CUSTOM = 31 +} SDL_ColorPrimaries; + +/** + * Colorspace transfer characteristics. + * + * These are as described by https://www.itu.int/rec/T-REC-H.273-201612-S/en + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_TransferCharacteristics +{ + SDL_TRANSFER_CHARACTERISTICS_UNKNOWN = 0, + SDL_TRANSFER_CHARACTERISTICS_BT709 = 1, /**< Rec. ITU-R BT.709-6 / ITU-R BT1361 */ + SDL_TRANSFER_CHARACTERISTICS_UNSPECIFIED = 2, + SDL_TRANSFER_CHARACTERISTICS_GAMMA22 = 4, /**< ITU-R BT.470-6 System M / ITU-R BT1700 625 PAL & SECAM */ + SDL_TRANSFER_CHARACTERISTICS_GAMMA28 = 5, /**< ITU-R BT.470-6 System B, G */ + SDL_TRANSFER_CHARACTERISTICS_BT601 = 6, /**< SMPTE ST 170M / ITU-R BT.601-7 525 or 625 */ + SDL_TRANSFER_CHARACTERISTICS_SMPTE240 = 7, /**< SMPTE ST 240M */ + SDL_TRANSFER_CHARACTERISTICS_LINEAR = 8, + SDL_TRANSFER_CHARACTERISTICS_LOG100 = 9, + SDL_TRANSFER_CHARACTERISTICS_LOG100_SQRT10 = 10, + SDL_TRANSFER_CHARACTERISTICS_IEC61966 = 11, /**< IEC 61966-2-4 */ + SDL_TRANSFER_CHARACTERISTICS_BT1361 = 12, /**< ITU-R BT1361 Extended Colour Gamut */ + SDL_TRANSFER_CHARACTERISTICS_SRGB = 13, /**< IEC 61966-2-1 (sRGB or sYCC) */ + SDL_TRANSFER_CHARACTERISTICS_BT2020_10BIT = 14, /**< ITU-R BT2020 for 10-bit system */ + SDL_TRANSFER_CHARACTERISTICS_BT2020_12BIT = 15, /**< ITU-R BT2020 for 12-bit system */ + SDL_TRANSFER_CHARACTERISTICS_PQ = 16, /**< SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems */ + SDL_TRANSFER_CHARACTERISTICS_SMPTE428 = 17, /**< SMPTE ST 428-1 */ + SDL_TRANSFER_CHARACTERISTICS_HLG = 18, /**< ARIB STD-B67, known as "hybrid log-gamma" (HLG) */ + SDL_TRANSFER_CHARACTERISTICS_CUSTOM = 31 +} SDL_TransferCharacteristics; + +/** + * Colorspace matrix coefficients. + * + * These are as described by https://www.itu.int/rec/T-REC-H.273-201612-S/en + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_MatrixCoefficients +{ + SDL_MATRIX_COEFFICIENTS_IDENTITY = 0, + SDL_MATRIX_COEFFICIENTS_BT709 = 1, /**< ITU-R BT.709-6 */ + SDL_MATRIX_COEFFICIENTS_UNSPECIFIED = 2, + SDL_MATRIX_COEFFICIENTS_FCC = 4, /**< US FCC Title 47 */ + SDL_MATRIX_COEFFICIENTS_BT470BG = 5, /**< ITU-R BT.470-6 System B, G / ITU-R BT.601-7 625, functionally the same as SDL_MATRIX_COEFFICIENTS_BT601 */ + SDL_MATRIX_COEFFICIENTS_BT601 = 6, /**< ITU-R BT.601-7 525 */ + SDL_MATRIX_COEFFICIENTS_SMPTE240 = 7, /**< SMPTE 240M */ + SDL_MATRIX_COEFFICIENTS_YCGCO = 8, + SDL_MATRIX_COEFFICIENTS_BT2020_NCL = 9, /**< ITU-R BT.2020-2 non-constant luminance */ + SDL_MATRIX_COEFFICIENTS_BT2020_CL = 10, /**< ITU-R BT.2020-2 constant luminance */ + SDL_MATRIX_COEFFICIENTS_SMPTE2085 = 11, /**< SMPTE ST 2085 */ + SDL_MATRIX_COEFFICIENTS_CHROMA_DERIVED_NCL = 12, + SDL_MATRIX_COEFFICIENTS_CHROMA_DERIVED_CL = 13, + SDL_MATRIX_COEFFICIENTS_ICTCP = 14, /**< ITU-R BT.2100-0 ICTCP */ + SDL_MATRIX_COEFFICIENTS_CUSTOM = 31 +} SDL_MatrixCoefficients; + +/** + * Colorspace chroma sample location. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_ChromaLocation +{ + SDL_CHROMA_LOCATION_NONE = 0, /**< RGB, no chroma sampling */ + SDL_CHROMA_LOCATION_LEFT = 1, /**< In MPEG-2, MPEG-4, and AVC, Cb and Cr are taken on midpoint of the left-edge of the 2x2 square. In other words, they have the same horizontal location as the top-left pixel, but is shifted one-half pixel down vertically. */ + SDL_CHROMA_LOCATION_CENTER = 2, /**< In JPEG/JFIF, H.261, and MPEG-1, Cb and Cr are taken at the center of the 2x2 square. In other words, they are offset one-half pixel to the right and one-half pixel down compared to the top-left pixel. */ + SDL_CHROMA_LOCATION_TOPLEFT = 3 /**< In HEVC for BT.2020 and BT.2100 content (in particular on Blu-rays), Cb and Cr are sampled at the same location as the group's top-left Y pixel ("co-sited", "co-located"). */ +} SDL_ChromaLocation; + + +/* Colorspace definition */ + +/** + * A macro for defining custom SDL_Colorspace formats. + * + * For example, defining SDL_COLORSPACE_SRGB looks like this: + * + * ```c + * SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_RGB, + * SDL_COLOR_RANGE_FULL, + * SDL_COLOR_PRIMARIES_BT709, + * SDL_TRANSFER_CHARACTERISTICS_SRGB, + * SDL_MATRIX_COEFFICIENTS_IDENTITY, + * SDL_CHROMA_LOCATION_NONE) + * ``` + * + * \param type the type of the new format, probably an SDL_ColorType value. + * \param range the range of the new format, probably a SDL_ColorRange value. + * \param primaries the primaries of the new format, probably an + * SDL_ColorPrimaries value. + * \param transfer the transfer characteristics of the new format, probably an + * SDL_TransferCharacteristics value. + * \param matrix the matrix coefficients of the new format, probably an + * SDL_MatrixCoefficients value. + * \param chroma the chroma sample location of the new format, probably an + * SDL_ChromaLocation value. + * \returns a format value in the style of SDL_Colorspace. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_DEFINE_COLORSPACE(type, range, primaries, transfer, matrix, chroma) \ + (((Uint32)(type) << 28) | ((Uint32)(range) << 24) | ((Uint32)(chroma) << 20) | \ + ((Uint32)(primaries) << 10) | ((Uint32)(transfer) << 5) | ((Uint32)(matrix) << 0)) + +/** + * A macro to retrieve the type of an SDL_Colorspace. + * + * \param cspace an SDL_Colorspace to check. + * \returns the SDL_ColorType for `cspace`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_COLORSPACETYPE(cspace) (SDL_ColorType)(((cspace) >> 28) & 0x0F) + +/** + * A macro to retrieve the range of an SDL_Colorspace. + * + * \param cspace an SDL_Colorspace to check. + * \returns the SDL_ColorRange of `cspace`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_COLORSPACERANGE(cspace) (SDL_ColorRange)(((cspace) >> 24) & 0x0F) + +/** + * A macro to retrieve the chroma sample location of an SDL_Colorspace. + * + * \param cspace an SDL_Colorspace to check. + * \returns the SDL_ChromaLocation of `cspace`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_COLORSPACECHROMA(cspace) (SDL_ChromaLocation)(((cspace) >> 20) & 0x0F) + +/** + * A macro to retrieve the primaries of an SDL_Colorspace. + * + * \param cspace an SDL_Colorspace to check. + * \returns the SDL_ColorPrimaries of `cspace`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_COLORSPACEPRIMARIES(cspace) (SDL_ColorPrimaries)(((cspace) >> 10) & 0x1F) + +/** + * A macro to retrieve the transfer characteristics of an SDL_Colorspace. + * + * \param cspace an SDL_Colorspace to check. + * \returns the SDL_TransferCharacteristics of `cspace`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_COLORSPACETRANSFER(cspace) (SDL_TransferCharacteristics)(((cspace) >> 5) & 0x1F) + +/** + * A macro to retrieve the matrix coefficients of an SDL_Colorspace. + * + * \param cspace an SDL_Colorspace to check. + * \returns the SDL_MatrixCoefficients of `cspace`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_COLORSPACEMATRIX(cspace) (SDL_MatrixCoefficients)((cspace) & 0x1F) + +/** + * A macro to determine if an SDL_Colorspace uses BT601 (or BT470BG) matrix + * coefficients. + * + * Note that this macro double-evaluates its parameter, so do not use + * expressions with side-effects here. + * + * \param cspace an SDL_Colorspace to check. + * \returns true if BT601 or BT470BG, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISCOLORSPACE_MATRIX_BT601(cspace) (SDL_COLORSPACEMATRIX(cspace) == SDL_MATRIX_COEFFICIENTS_BT601 || SDL_COLORSPACEMATRIX(cspace) == SDL_MATRIX_COEFFICIENTS_BT470BG) + +/** + * A macro to determine if an SDL_Colorspace uses BT709 matrix coefficients. + * + * \param cspace an SDL_Colorspace to check. + * \returns true if BT709, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISCOLORSPACE_MATRIX_BT709(cspace) (SDL_COLORSPACEMATRIX(cspace) == SDL_MATRIX_COEFFICIENTS_BT709) + +/** + * A macro to determine if an SDL_Colorspace uses BT2020_NCL matrix + * coefficients. + * + * \param cspace an SDL_Colorspace to check. + * \returns true if BT2020_NCL, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISCOLORSPACE_MATRIX_BT2020_NCL(cspace) (SDL_COLORSPACEMATRIX(cspace) == SDL_MATRIX_COEFFICIENTS_BT2020_NCL) + +/** + * A macro to determine if an SDL_Colorspace has a limited range. + * + * \param cspace an SDL_Colorspace to check. + * \returns true if limited range, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISCOLORSPACE_LIMITED_RANGE(cspace) (SDL_COLORSPACERANGE(cspace) != SDL_COLOR_RANGE_FULL) + +/** + * A macro to determine if an SDL_Colorspace has a full range. + * + * \param cspace an SDL_Colorspace to check. + * \returns true if full range, false otherwise. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ISCOLORSPACE_FULL_RANGE(cspace) (SDL_COLORSPACERANGE(cspace) == SDL_COLOR_RANGE_FULL) + +/** + * Colorspace definitions. + * + * Since similar colorspaces may vary in their details (matrix, transfer + * function, etc.), this is not an exhaustive list, but rather a + * representative sample of the kinds of colorspaces supported in SDL. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_ColorPrimaries + * \sa SDL_ColorRange + * \sa SDL_ColorType + * \sa SDL_MatrixCoefficients + * \sa SDL_TransferCharacteristics + */ +typedef enum SDL_Colorspace +{ + SDL_COLORSPACE_UNKNOWN = 0, + + /* sRGB is a gamma corrected colorspace, and the default colorspace for SDL rendering and 8-bit RGB surfaces */ + SDL_COLORSPACE_SRGB = 0x120005a0u, /**< Equivalent to DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709 */ + /* SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_RGB, + SDL_COLOR_RANGE_FULL, + SDL_COLOR_PRIMARIES_BT709, + SDL_TRANSFER_CHARACTERISTICS_SRGB, + SDL_MATRIX_COEFFICIENTS_IDENTITY, + SDL_CHROMA_LOCATION_NONE), */ + + /* This is a linear colorspace and the default colorspace for floating point surfaces. On Windows this is the scRGB colorspace, and on Apple platforms this is kCGColorSpaceExtendedLinearSRGB for EDR content */ + SDL_COLORSPACE_SRGB_LINEAR = 0x12000500u, /**< Equivalent to DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709 */ + /* SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_RGB, + SDL_COLOR_RANGE_FULL, + SDL_COLOR_PRIMARIES_BT709, + SDL_TRANSFER_CHARACTERISTICS_LINEAR, + SDL_MATRIX_COEFFICIENTS_IDENTITY, + SDL_CHROMA_LOCATION_NONE), */ + + /* HDR10 is a non-linear HDR colorspace and the default colorspace for 10-bit surfaces */ + SDL_COLORSPACE_HDR10 = 0x12002600u, /**< Equivalent to DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020 */ + /* SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_RGB, + SDL_COLOR_RANGE_FULL, + SDL_COLOR_PRIMARIES_BT2020, + SDL_TRANSFER_CHARACTERISTICS_PQ, + SDL_MATRIX_COEFFICIENTS_IDENTITY, + SDL_CHROMA_LOCATION_NONE), */ + + SDL_COLORSPACE_JPEG = 0x220004c6u, /**< Equivalent to DXGI_COLOR_SPACE_YCBCR_FULL_G22_NONE_P709_X601 */ + /* SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_YCBCR, + SDL_COLOR_RANGE_FULL, + SDL_COLOR_PRIMARIES_BT709, + SDL_TRANSFER_CHARACTERISTICS_BT601, + SDL_MATRIX_COEFFICIENTS_BT601, + SDL_CHROMA_LOCATION_NONE), */ + + SDL_COLORSPACE_BT601_LIMITED = 0x211018c6u, /**< Equivalent to DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P601 */ + /* SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_YCBCR, + SDL_COLOR_RANGE_LIMITED, + SDL_COLOR_PRIMARIES_BT601, + SDL_TRANSFER_CHARACTERISTICS_BT601, + SDL_MATRIX_COEFFICIENTS_BT601, + SDL_CHROMA_LOCATION_LEFT), */ + + SDL_COLORSPACE_BT601_FULL = 0x221018c6u, /**< Equivalent to DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P601 */ + /* SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_YCBCR, + SDL_COLOR_RANGE_FULL, + SDL_COLOR_PRIMARIES_BT601, + SDL_TRANSFER_CHARACTERISTICS_BT601, + SDL_MATRIX_COEFFICIENTS_BT601, + SDL_CHROMA_LOCATION_LEFT), */ + + SDL_COLORSPACE_BT709_LIMITED = 0x21100421u, /**< Equivalent to DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709 */ + /* SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_YCBCR, + SDL_COLOR_RANGE_LIMITED, + SDL_COLOR_PRIMARIES_BT709, + SDL_TRANSFER_CHARACTERISTICS_BT709, + SDL_MATRIX_COEFFICIENTS_BT709, + SDL_CHROMA_LOCATION_LEFT), */ + + SDL_COLORSPACE_BT709_FULL = 0x22100421u, /**< Equivalent to DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709 */ + /* SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_YCBCR, + SDL_COLOR_RANGE_FULL, + SDL_COLOR_PRIMARIES_BT709, + SDL_TRANSFER_CHARACTERISTICS_BT709, + SDL_MATRIX_COEFFICIENTS_BT709, + SDL_CHROMA_LOCATION_LEFT), */ + + SDL_COLORSPACE_BT2020_LIMITED = 0x21102609u, /**< Equivalent to DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P2020 */ + /* SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_YCBCR, + SDL_COLOR_RANGE_LIMITED, + SDL_COLOR_PRIMARIES_BT2020, + SDL_TRANSFER_CHARACTERISTICS_PQ, + SDL_MATRIX_COEFFICIENTS_BT2020_NCL, + SDL_CHROMA_LOCATION_LEFT), */ + + SDL_COLORSPACE_BT2020_FULL = 0x22102609u, /**< Equivalent to DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P2020 */ + /* SDL_DEFINE_COLORSPACE(SDL_COLOR_TYPE_YCBCR, + SDL_COLOR_RANGE_FULL, + SDL_COLOR_PRIMARIES_BT2020, + SDL_TRANSFER_CHARACTERISTICS_PQ, + SDL_MATRIX_COEFFICIENTS_BT2020_NCL, + SDL_CHROMA_LOCATION_LEFT), */ + + SDL_COLORSPACE_RGB_DEFAULT = SDL_COLORSPACE_SRGB, /**< The default colorspace for RGB surfaces if no colorspace is specified */ + SDL_COLORSPACE_YUV_DEFAULT = SDL_COLORSPACE_JPEG /**< The default colorspace for YUV surfaces if no colorspace is specified */ +} SDL_Colorspace; + +/** + * A structure that represents a color as RGBA components. + * + * The bits of this structure can be directly reinterpreted as an + * integer-packed color which uses the SDL_PIXELFORMAT_RGBA32 format + * (SDL_PIXELFORMAT_ABGR8888 on little-endian systems and + * SDL_PIXELFORMAT_RGBA8888 on big-endian systems). + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Color +{ + Uint8 r; + Uint8 g; + Uint8 b; + Uint8 a; +} SDL_Color; + +/** + * The bits of this structure can be directly reinterpreted as a float-packed + * color which uses the SDL_PIXELFORMAT_RGBA128_FLOAT format + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_FColor +{ + float r; + float g; + float b; + float a; +} SDL_FColor; + +/** + * A set of indexed colors representing a palette. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_SetPaletteColors + */ +typedef struct SDL_Palette +{ + int ncolors; /**< number of elements in `colors`. */ + SDL_Color *colors; /**< an array of colors, `ncolors` long. */ + Uint32 version; /**< internal use only, do not touch. */ + int refcount; /**< internal use only, do not touch. */ +} SDL_Palette; + +/** + * Details about the format of a pixel. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_PixelFormatDetails +{ + SDL_PixelFormat format; + Uint8 bits_per_pixel; + Uint8 bytes_per_pixel; + Uint8 padding[2]; + Uint32 Rmask; + Uint32 Gmask; + Uint32 Bmask; + Uint32 Amask; + Uint8 Rbits; + Uint8 Gbits; + Uint8 Bbits; + Uint8 Abits; + Uint8 Rshift; + Uint8 Gshift; + Uint8 Bshift; + Uint8 Ashift; +} SDL_PixelFormatDetails; + +/** + * Get the human readable name of a pixel format. + * + * \param format the pixel format to query. + * \returns the human readable name of the specified pixel format or + * "SDL_PIXELFORMAT_UNKNOWN" if the format isn't recognized. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetPixelFormatName(SDL_PixelFormat format); + +/** + * Convert one of the enumerated pixel formats to a bpp value and RGBA masks. + * + * \param format one of the SDL_PixelFormat values. + * \param bpp a bits per pixel value; usually 15, 16, or 32. + * \param Rmask a pointer filled in with the red mask for the format. + * \param Gmask a pointer filled in with the green mask for the format. + * \param Bmask a pointer filled in with the blue mask for the format. + * \param Amask a pointer filled in with the alpha mask for the format. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPixelFormatForMasks + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetMasksForPixelFormat(SDL_PixelFormat format, int *bpp, Uint32 *Rmask, Uint32 *Gmask, Uint32 *Bmask, Uint32 *Amask); + +/** + * Convert a bpp value and RGBA masks to an enumerated pixel format. + * + * This will return `SDL_PIXELFORMAT_UNKNOWN` if the conversion wasn't + * possible. + * + * \param bpp a bits per pixel value; usually 15, 16, or 32. + * \param Rmask the red mask for the format. + * \param Gmask the green mask for the format. + * \param Bmask the blue mask for the format. + * \param Amask the alpha mask for the format. + * \returns the SDL_PixelFormat value corresponding to the format masks, or + * SDL_PIXELFORMAT_UNKNOWN if there isn't a match. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetMasksForPixelFormat + */ +extern SDL_DECLSPEC SDL_PixelFormat SDLCALL SDL_GetPixelFormatForMasks(int bpp, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); + +/** + * Create an SDL_PixelFormatDetails structure corresponding to a pixel format. + * + * Returned structure may come from a shared global cache (i.e. not newly + * allocated), and hence should not be modified, especially the palette. Weird + * errors such as `Blit combination not supported` may occur. + * + * \param format one of the SDL_PixelFormat values. + * \returns a pointer to a SDL_PixelFormatDetails structure or NULL on + * failure; call SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const SDL_PixelFormatDetails * SDLCALL SDL_GetPixelFormatDetails(SDL_PixelFormat format); + +/** + * Create a palette structure with the specified number of color entries. + * + * The palette entries are initialized to white. + * + * \param ncolors represents the number of color entries in the color palette. + * \returns a new SDL_Palette structure on success or NULL on failure (e.g. if + * there wasn't enough memory); call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroyPalette + * \sa SDL_SetPaletteColors + * \sa SDL_SetSurfacePalette + */ +extern SDL_DECLSPEC SDL_Palette * SDLCALL SDL_CreatePalette(int ncolors); + +/** + * Set a range of colors in a palette. + * + * \param palette the SDL_Palette structure to modify. + * \param colors an array of SDL_Color structures to copy into the palette. + * \param firstcolor the index of the first palette entry to modify. + * \param ncolors the number of entries to modify. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, as long as + * the palette is not modified or destroyed in another thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetPaletteColors(SDL_Palette *palette, const SDL_Color *colors, int firstcolor, int ncolors); + +/** + * Free a palette created with SDL_CreatePalette(). + * + * \param palette the SDL_Palette structure to be freed. + * + * \threadsafety It is safe to call this function from any thread, as long as + * the palette is not modified or destroyed in another thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreatePalette + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyPalette(SDL_Palette *palette); + +/** + * Map an RGB triple to an opaque pixel value for a given pixel format. + * + * This function maps the RGB color value to the specified pixel format and + * returns the pixel value best approximating the given RGB color value for + * the given pixel format. + * + * If the format has a palette (8-bit) the index of the closest matching color + * in the palette will be returned. + * + * If the specified pixel format has an alpha component it will be returned as + * all 1 bits (fully opaque). + * + * If the pixel format bpp (color depth) is less than 32-bpp then the unused + * upper bits of the return value can safely be ignored (e.g., with a 16-bpp + * format the return value can be assigned to a Uint16, and similarly a Uint8 + * for an 8-bpp format). + * + * \param format a pointer to SDL_PixelFormatDetails describing the pixel + * format. + * \param palette an optional palette for indexed formats, may be NULL. + * \param r the red component of the pixel in the range 0-255. + * \param g the green component of the pixel in the range 0-255. + * \param b the blue component of the pixel in the range 0-255. + * \returns a pixel value. + * + * \threadsafety It is safe to call this function from any thread, as long as + * the palette is not modified. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPixelFormatDetails + * \sa SDL_GetRGB + * \sa SDL_MapRGBA + * \sa SDL_MapSurfaceRGB + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_MapRGB(const SDL_PixelFormatDetails *format, const SDL_Palette *palette, Uint8 r, Uint8 g, Uint8 b); + +/** + * Map an RGBA quadruple to a pixel value for a given pixel format. + * + * This function maps the RGBA color value to the specified pixel format and + * returns the pixel value best approximating the given RGBA color value for + * the given pixel format. + * + * If the specified pixel format has no alpha component the alpha value will + * be ignored (as it will be in formats with a palette). + * + * If the format has a palette (8-bit) the index of the closest matching color + * in the palette will be returned. + * + * If the pixel format bpp (color depth) is less than 32-bpp then the unused + * upper bits of the return value can safely be ignored (e.g., with a 16-bpp + * format the return value can be assigned to a Uint16, and similarly a Uint8 + * for an 8-bpp format). + * + * \param format a pointer to SDL_PixelFormatDetails describing the pixel + * format. + * \param palette an optional palette for indexed formats, may be NULL. + * \param r the red component of the pixel in the range 0-255. + * \param g the green component of the pixel in the range 0-255. + * \param b the blue component of the pixel in the range 0-255. + * \param a the alpha component of the pixel in the range 0-255. + * \returns a pixel value. + * + * \threadsafety It is safe to call this function from any thread, as long as + * the palette is not modified. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPixelFormatDetails + * \sa SDL_GetRGBA + * \sa SDL_MapRGB + * \sa SDL_MapSurfaceRGBA + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_MapRGBA(const SDL_PixelFormatDetails *format, const SDL_Palette *palette, Uint8 r, Uint8 g, Uint8 b, Uint8 a); + +/** + * Get RGB values from a pixel in the specified format. + * + * This function uses the entire 8-bit [0..255] range when converting color + * components from pixel formats with less than 8-bits per RGB component + * (e.g., a completely white pixel in 16-bit RGB565 format would return [0xff, + * 0xff, 0xff] not [0xf8, 0xfc, 0xf8]). + * + * \param pixel a pixel value. + * \param format a pointer to SDL_PixelFormatDetails describing the pixel + * format. + * \param palette an optional palette for indexed formats, may be NULL. + * \param r a pointer filled in with the red component, may be NULL. + * \param g a pointer filled in with the green component, may be NULL. + * \param b a pointer filled in with the blue component, may be NULL. + * + * \threadsafety It is safe to call this function from any thread, as long as + * the palette is not modified. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPixelFormatDetails + * \sa SDL_GetRGBA + * \sa SDL_MapRGB + * \sa SDL_MapRGBA + */ +extern SDL_DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixel, const SDL_PixelFormatDetails *format, const SDL_Palette *palette, Uint8 *r, Uint8 *g, Uint8 *b); + +/** + * Get RGBA values from a pixel in the specified format. + * + * This function uses the entire 8-bit [0..255] range when converting color + * components from pixel formats with less than 8-bits per RGB component + * (e.g., a completely white pixel in 16-bit RGB565 format would return [0xff, + * 0xff, 0xff] not [0xf8, 0xfc, 0xf8]). + * + * If the surface has no alpha component, the alpha will be returned as 0xff + * (100% opaque). + * + * \param pixel a pixel value. + * \param format a pointer to SDL_PixelFormatDetails describing the pixel + * format. + * \param palette an optional palette for indexed formats, may be NULL. + * \param r a pointer filled in with the red component, may be NULL. + * \param g a pointer filled in with the green component, may be NULL. + * \param b a pointer filled in with the blue component, may be NULL. + * \param a a pointer filled in with the alpha component, may be NULL. + * + * \threadsafety It is safe to call this function from any thread, as long as + * the palette is not modified. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPixelFormatDetails + * \sa SDL_GetRGB + * \sa SDL_MapRGB + * \sa SDL_MapRGBA + */ +extern SDL_DECLSPEC void SDLCALL SDL_GetRGBA(Uint32 pixel, const SDL_PixelFormatDetails *format, const SDL_Palette *palette, Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_pixels_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_platform.h b/thirdparty/sdl/include/SDL3/SDL_platform.h new file mode 100644 index 00000000000..e40f009bad6 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_platform.h @@ -0,0 +1,64 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryPlatform + * + * SDL provides a means to identify the app's platform, both at compile time + * and runtime. + */ + +#ifndef SDL_platform_h_ +#define SDL_platform_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Get the name of the platform. + * + * Here are the names returned for some (but not all) supported platforms: + * + * - "Windows" + * - "macOS" + * - "Linux" + * - "iOS" + * - "Android" + * + * \returns the name of the platform. If the correct platform name is not + * available, returns a string beginning with the text "Unknown". + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetPlatform(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_platform_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_platform_defines.h b/thirdparty/sdl/include/SDL3/SDL_platform_defines.h new file mode 100644 index 00000000000..6b240a8be45 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_platform_defines.h @@ -0,0 +1,476 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: Platform */ + +/* + * SDL_platform_defines.h tries to get a standard set of platform defines. + */ + +#ifndef SDL_platform_defines_h_ +#define SDL_platform_defines_h_ + +#ifdef _AIX + +/** + * A preprocessor macro that is only defined if compiling for AIX. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_AIX 1 +#endif + +#ifdef __HAIKU__ + +/** + * A preprocessor macro that is only defined if compiling for Haiku OS. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_HAIKU 1 +#endif + +#if defined(bsdi) || defined(__bsdi) || defined(__bsdi__) + +/** + * A preprocessor macro that is only defined if compiling for BSDi + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_BSDI 1 +#endif + +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) + +/** + * A preprocessor macro that is only defined if compiling for FreeBSD. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_FREEBSD 1 +#endif + +#if defined(hpux) || defined(__hpux) || defined(__hpux__) + +/** + * A preprocessor macro that is only defined if compiling for HP-UX. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_HPUX 1 +#endif + +#if defined(sgi) || defined(__sgi) || defined(__sgi__) || defined(_SGI_SOURCE) + +/** + * A preprocessor macro that is only defined if compiling for IRIX. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_IRIX 1 +#endif + +#if (defined(linux) || defined(__linux) || defined(__linux__)) + +/** + * A preprocessor macro that is only defined if compiling for Linux. + * + * Note that Android, although ostensibly a Linux-based system, will not + * define this. It defines SDL_PLATFORM_ANDROID instead. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_LINUX 1 +#endif + +#if defined(ANDROID) || defined(__ANDROID__) + +/** + * A preprocessor macro that is only defined if compiling for Android. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_ANDROID 1 +#undef SDL_PLATFORM_LINUX +#endif + +#if defined(__unix__) || defined(__unix) || defined(unix) + +/** + * A preprocessor macro that is only defined if compiling for a Unix-like + * system. + * + * Other platforms, like Linux, might define this in addition to their primary + * define. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_UNIX 1 +#endif + +#ifdef __APPLE__ + +/** + * A preprocessor macro that is only defined if compiling for Apple platforms. + * + * iOS, macOS, etc will additionally define a more specific platform macro. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_PLATFORM_MACOS + * \sa SDL_PLATFORM_IOS + * \sa SDL_PLATFORM_TVOS + * \sa SDL_PLATFORM_VISIONOS + */ +#define SDL_PLATFORM_APPLE 1 + +/* lets us know what version of macOS we're compiling on */ +#include +#ifndef __has_extension /* Older compilers don't support this */ + #define __has_extension(x) 0 + #include + #undef __has_extension +#else + #include +#endif + +/* Fix building with older SDKs that don't define these + See this for more information: + https://stackoverflow.com/questions/12132933/preprocessor-macro-for-os-x-targets +*/ +#ifndef TARGET_OS_MACCATALYST + #define TARGET_OS_MACCATALYST 0 +#endif +#ifndef TARGET_OS_IOS + #define TARGET_OS_IOS 0 +#endif +#ifndef TARGET_OS_IPHONE + #define TARGET_OS_IPHONE 0 +#endif +#ifndef TARGET_OS_TV + #define TARGET_OS_TV 0 +#endif +#ifndef TARGET_OS_SIMULATOR + #define TARGET_OS_SIMULATOR 0 +#endif +#ifndef TARGET_OS_VISION + #define TARGET_OS_VISION 0 +#endif + +#if TARGET_OS_TV + +/** + * A preprocessor macro that is only defined if compiling for tvOS. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_PLATFORM_APPLE + */ +#define SDL_PLATFORM_TVOS 1 +#endif + +#if TARGET_OS_VISION + +/** + * A preprocessor macro that is only defined if compiling for VisionOS. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_PLATFORM_APPLE + */ +#define SDL_PLATFORM_VISIONOS 1 +#endif + +#if TARGET_OS_IPHONE + +/** + * A preprocessor macro that is only defined if compiling for iOS. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_PLATFORM_APPLE + */ +#define SDL_PLATFORM_IOS 1 + +#else + +/** + * A preprocessor macro that is only defined if compiling for macOS. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_PLATFORM_APPLE + */ +#define SDL_PLATFORM_MACOS 1 + +#if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 + #error SDL for macOS only supports deploying on 10.7 and above. +#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < 1070 */ +#endif /* TARGET_OS_IPHONE */ +#endif /* defined(__APPLE__) */ + +#ifdef __EMSCRIPTEN__ + +/** + * A preprocessor macro that is only defined if compiling for Emscripten. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_EMSCRIPTEN 1 +#endif + +#ifdef __NetBSD__ + +/** + * A preprocessor macro that is only defined if compiling for NetBSD. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_NETBSD 1 +#endif + +#ifdef __OpenBSD__ + +/** + * A preprocessor macro that is only defined if compiling for OpenBSD. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_OPENBSD 1 +#endif + +#if defined(__OS2__) || defined(__EMX__) + +/** + * A preprocessor macro that is only defined if compiling for OS/2. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_OS2 1 +#endif + +#if defined(osf) || defined(__osf) || defined(__osf__) || defined(_OSF_SOURCE) + +/** + * A preprocessor macro that is only defined if compiling for Tru64 (OSF/1). + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_OSF 1 +#endif + +#ifdef __QNXNTO__ + +/** + * A preprocessor macro that is only defined if compiling for QNX Neutrino. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_QNXNTO 1 +#endif + +#if defined(riscos) || defined(__riscos) || defined(__riscos__) + +/** + * A preprocessor macro that is only defined if compiling for RISC OS. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_RISCOS 1 +#endif + +#if defined(__sun) && defined(__SVR4) + +/** + * A preprocessor macro that is only defined if compiling for SunOS/Solaris. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_SOLARIS 1 +#endif + +#if defined(__CYGWIN__) + +/** + * A preprocessor macro that is only defined if compiling for Cygwin. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_CYGWIN 1 +#endif + +#if defined(_WIN32) || defined(SDL_PLATFORM_CYGWIN) + +/** + * A preprocessor macro that is only defined if compiling for Windows. + * + * This also covers several other platforms, like Microsoft GDK, Xbox, WinRT, + * etc. Each will have their own more-specific platform macros, too. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_PLATFORM_WIN32 + * \sa SDL_PLATFORM_XBOXONE + * \sa SDL_PLATFORM_XBOXSERIES + * \sa SDL_PLATFORM_WINGDK + * \sa SDL_PLATFORM_GDK + */ +#define SDL_PLATFORM_WINDOWS 1 + +/* Try to find out if we're compiling for WinRT, GDK or non-WinRT/GDK */ +#if defined(_MSC_VER) && defined(__has_include) + #if __has_include() + #define HAVE_WINAPIFAMILY_H 1 + #else + #define HAVE_WINAPIFAMILY_H 0 + #endif + + /* If _USING_V110_SDK71_ is defined it means we are using the Windows XP toolset. */ +#elif defined(_MSC_VER) && (_MSC_VER >= 1700 && !_USING_V110_SDK71_) /* _MSC_VER == 1700 for Visual Studio 2012 */ + #define HAVE_WINAPIFAMILY_H 1 +#else + #define HAVE_WINAPIFAMILY_H 0 +#endif + +#if HAVE_WINAPIFAMILY_H + #include + #define WINAPI_FAMILY_WINRT (!WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)) +#else + #define WINAPI_FAMILY_WINRT 0 +#endif /* HAVE_WINAPIFAMILY_H */ + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A preprocessor macro that defined to 1 if compiling for Windows Phone. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WINAPI_FAMILY_PHONE (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) + +#elif defined(HAVE_WINAPIFAMILY_H) && HAVE_WINAPIFAMILY_H + #define SDL_WINAPI_FAMILY_PHONE (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) +#else + #define SDL_WINAPI_FAMILY_PHONE 0 +#endif + +#if WINAPI_FAMILY_WINRT +#error Windows RT/UWP is no longer supported in SDL + +#elif defined(_GAMING_DESKTOP) /* GDK project configuration always defines _GAMING_XXX */ + +/** + * A preprocessor macro that is only defined if compiling for Microsoft GDK + * for Windows. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_WINGDK 1 + +#elif defined(_GAMING_XBOX_XBOXONE) + +/** + * A preprocessor macro that is only defined if compiling for Xbox One. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_XBOXONE 1 + +#elif defined(_GAMING_XBOX_SCARLETT) + +/** + * A preprocessor macro that is only defined if compiling for Xbox Series. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_XBOXSERIES 1 + +#else + +/** + * A preprocessor macro that is only defined if compiling for desktop Windows. + * + * Despite the "32", this also covers 64-bit Windows; as an informal + * convention, its system layer tends to still be referred to as "the Win32 + * API." + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_WIN32 1 + +#endif +#endif /* defined(_WIN32) || defined(SDL_PLATFORM_CYGWIN) */ + + +/* This is to support generic "any GDK" separate from a platform-specific GDK */ +#if defined(SDL_PLATFORM_WINGDK) || defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) + +/** + * A preprocessor macro that is only defined if compiling for Microsoft GDK on + * any platform. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_GDK 1 +#endif + +#if defined(__PSP__) || defined(__psp__) + +/** + * A preprocessor macro that is only defined if compiling for Sony PSP. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_PSP 1 +#endif + +#if defined(__PS2__) || defined(PS2) + +/** + * A preprocessor macro that is only defined if compiling for Sony PlayStation + * 2. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_PS2 1 +#endif + +#if defined(__vita__) || defined(__psp2__) + +/** + * A preprocessor macro that is only defined if compiling for Sony Vita. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_VITA 1 +#endif + +#ifdef __3DS__ + +/** + * A preprocessor macro that is only defined if compiling for Nintendo 3DS. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PLATFORM_3DS 1 +#endif + +#endif /* SDL_platform_defines_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_power.h b/thirdparty/sdl/include/SDL3/SDL_power.h new file mode 100644 index 00000000000..694fb0924d3 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_power.h @@ -0,0 +1,106 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_power_h_ +#define SDL_power_h_ + +/** + * # CategoryPower + * + * SDL power management routines. + * + * There is a single function in this category: SDL_GetPowerInfo(). + * + * This function is useful for games on the go. This allows an app to know if + * it's running on a draining battery, which can be useful if the app wants to + * reduce processing, or perhaps framerate, to extend the duration of the + * battery's charge. Perhaps the app just wants to show a battery meter when + * fullscreen, or alert the user when the power is getting extremely low, so + * they can save their game. + */ + +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The basic state for the system's power supply. + * + * These are results returned by SDL_GetPowerInfo(). + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_PowerState +{ + SDL_POWERSTATE_ERROR = -1, /**< error determining power status */ + SDL_POWERSTATE_UNKNOWN, /**< cannot determine power status */ + SDL_POWERSTATE_ON_BATTERY, /**< Not plugged in, running on the battery */ + SDL_POWERSTATE_NO_BATTERY, /**< Plugged in, no battery available */ + SDL_POWERSTATE_CHARGING, /**< Plugged in, charging battery */ + SDL_POWERSTATE_CHARGED /**< Plugged in, battery charged */ +} SDL_PowerState; + +/** + * Get the current power supply details. + * + * You should never take a battery status as absolute truth. Batteries + * (especially failing batteries) are delicate hardware, and the values + * reported here are best estimates based on what that hardware reports. It's + * not uncommon for older batteries to lose stored power much faster than it + * reports, or completely drain when reporting it has 20 percent left, etc. + * + * Battery status can change at any time; if you are concerned with power + * state, you should call this function frequently, and perhaps ignore changes + * until they seem to be stable for a few seconds. + * + * It's possible a platform can only report battery percentage or time left + * but not both. + * + * On some platforms, retrieving power supply details might be expensive. If + * you want to display continuous status you could call this function every + * minute or so. + * + * \param seconds a pointer filled in with the seconds of battery life left, + * or NULL to ignore. This will be filled in with -1 if we + * can't determine a value or there is no battery. + * \param percent a pointer filled in with the percentage of battery life + * left, between 0 and 100, or NULL to ignore. This will be + * filled in with -1 we can't determine a value or there is no + * battery. + * \returns the current battery state or `SDL_POWERSTATE_ERROR` on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PowerState SDLCALL SDL_GetPowerInfo(int *seconds, int *percent); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_power_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_process.h b/thirdparty/sdl/include/SDL3/SDL_process.h new file mode 100644 index 00000000000..511b2f9c51f --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_process.h @@ -0,0 +1,430 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryProcess + * + * Process control support. + * + * These functions provide a cross-platform way to spawn and manage OS-level + * processes. + * + * You can create a new subprocess with SDL_CreateProcess() and optionally + * read and write to it using SDL_ReadProcess() or SDL_GetProcessInput() and + * SDL_GetProcessOutput(). If more advanced functionality like chaining input + * between processes is necessary, you can use + * SDL_CreateProcessWithProperties(). + * + * You can get the status of a created process with SDL_WaitProcess(), or + * terminate the process with SDL_KillProcess(). + * + * Don't forget to call SDL_DestroyProcess() to clean up, whether the process + * process was killed, terminated on its own, or is still running! + */ + +#ifndef SDL_process_h_ +#define SDL_process_h_ + +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * An opaque handle representing a system process. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_CreateProcess + */ +typedef struct SDL_Process SDL_Process; + +/** + * Create a new process. + * + * The path to the executable is supplied in args[0]. args[1..N] are + * additional arguments passed on the command line of the new process, and the + * argument list should be terminated with a NULL, e.g.: + * + * ```c + * const char *args[] = { "myprogram", "argument", NULL }; + * ``` + * + * Setting pipe_stdio to true is equivalent to setting + * `SDL_PROP_PROCESS_CREATE_STDIN_NUMBER` and + * `SDL_PROP_PROCESS_CREATE_STDOUT_NUMBER` to `SDL_PROCESS_STDIO_APP`, and + * will allow the use of SDL_ReadProcess() or SDL_GetProcessInput() and + * SDL_GetProcessOutput(). + * + * See SDL_CreateProcessWithProperties() for more details. + * + * \param args the path and arguments for the new process. + * \param pipe_stdio true to create pipes to the process's standard input and + * from the process's standard output, false for the process + * to have no input and inherit the application's standard + * output. + * \returns the newly created and running process, or NULL if the process + * couldn't be created. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProcessWithProperties + * \sa SDL_GetProcessProperties + * \sa SDL_ReadProcess + * \sa SDL_GetProcessInput + * \sa SDL_GetProcessOutput + * \sa SDL_KillProcess + * \sa SDL_WaitProcess + * \sa SDL_DestroyProcess + */ +extern SDL_DECLSPEC SDL_Process * SDLCALL SDL_CreateProcess(const char * const *args, bool pipe_stdio); + +/** + * Description of where standard I/O should be directed when creating a + * process. + * + * If a standard I/O stream is set to SDL_PROCESS_STDIO_INHERITED, it will go + * to the same place as the application's I/O stream. This is the default for + * standard output and standard error. + * + * If a standard I/O stream is set to SDL_PROCESS_STDIO_NULL, it is connected + * to `NUL:` on Windows and `/dev/null` on POSIX systems. This is the default + * for standard input. + * + * If a standard I/O stream is set to SDL_PROCESS_STDIO_APP, it is connected + * to a new SDL_IOStream that is available to the application. Standard input + * will be available as `SDL_PROP_PROCESS_STDIN_POINTER` and allows + * SDL_GetProcessInput(), standard output will be available as + * `SDL_PROP_PROCESS_STDOUT_POINTER` and allows SDL_ReadProcess() and + * SDL_GetProcessOutput(), and standard error will be available as + * `SDL_PROP_PROCESS_STDERR_POINTER` in the properties for the created + * process. + * + * If a standard I/O stream is set to SDL_PROCESS_STDIO_REDIRECT, it is + * connected to an existing SDL_IOStream provided by the application. Standard + * input is provided using `SDL_PROP_PROCESS_CREATE_STDIN_POINTER`, standard + * output is provided using `SDL_PROP_PROCESS_CREATE_STDOUT_POINTER`, and + * standard error is provided using `SDL_PROP_PROCESS_CREATE_STDERR_POINTER` + * in the creation properties. These existing streams should be closed by the + * application once the new process is created. + * + * In order to use an SDL_IOStream with SDL_PROCESS_STDIO_REDIRECT, it must + * have `SDL_PROP_IOSTREAM_WINDOWS_HANDLE_POINTER` or + * `SDL_PROP_IOSTREAM_FILE_DESCRIPTOR_NUMBER` set. This is true for streams + * representing files and process I/O. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_CreateProcessWithProperties + * \sa SDL_GetProcessProperties + * \sa SDL_ReadProcess + * \sa SDL_GetProcessInput + * \sa SDL_GetProcessOutput + */ +typedef enum SDL_ProcessIO +{ + SDL_PROCESS_STDIO_INHERITED, /**< The I/O stream is inherited from the application. */ + SDL_PROCESS_STDIO_NULL, /**< The I/O stream is ignored. */ + SDL_PROCESS_STDIO_APP, /**< The I/O stream is connected to a new SDL_IOStream that the application can read or write */ + SDL_PROCESS_STDIO_REDIRECT /**< The I/O stream is redirected to an existing SDL_IOStream. */ +} SDL_ProcessIO; + +/** + * Create a new process with the specified properties. + * + * These are the supported properties: + * + * - `SDL_PROP_PROCESS_CREATE_ARGS_POINTER`: an array of strings containing + * the program to run, any arguments, and a NULL pointer, e.g. const char + * *args[] = { "myprogram", "argument", NULL }. This is a required property. + * - `SDL_PROP_PROCESS_CREATE_ENVIRONMENT_POINTER`: an SDL_Environment + * pointer. If this property is set, it will be the entire environment for + * the process, otherwise the current environment is used. + * - `SDL_PROP_PROCESS_CREATE_STDIN_NUMBER`: an SDL_ProcessIO value describing + * where standard input for the process comes from, defaults to + * `SDL_PROCESS_STDIO_NULL`. + * - `SDL_PROP_PROCESS_CREATE_STDIN_POINTER`: an SDL_IOStream pointer used for + * standard input when `SDL_PROP_PROCESS_CREATE_STDIN_NUMBER` is set to + * `SDL_PROCESS_STDIO_REDIRECT`. + * - `SDL_PROP_PROCESS_CREATE_STDOUT_NUMBER`: an SDL_ProcessIO value + * describing where standard output for the process goes to, defaults to + * `SDL_PROCESS_STDIO_INHERITED`. + * - `SDL_PROP_PROCESS_CREATE_STDOUT_POINTER`: an SDL_IOStream pointer used + * for standard output when `SDL_PROP_PROCESS_CREATE_STDOUT_NUMBER` is set + * to `SDL_PROCESS_STDIO_REDIRECT`. + * - `SDL_PROP_PROCESS_CREATE_STDERR_NUMBER`: an SDL_ProcessIO value + * describing where standard error for the process goes to, defaults to + * `SDL_PROCESS_STDIO_INHERITED`. + * - `SDL_PROP_PROCESS_CREATE_STDERR_POINTER`: an SDL_IOStream pointer used + * for standard error when `SDL_PROP_PROCESS_CREATE_STDERR_NUMBER` is set to + * `SDL_PROCESS_STDIO_REDIRECT`. + * - `SDL_PROP_PROCESS_CREATE_STDERR_TO_STDOUT_BOOLEAN`: true if the error + * output of the process should be redirected into the standard output of + * the process. This property has no effect if + * `SDL_PROP_PROCESS_CREATE_STDERR_NUMBER` is set. + * - `SDL_PROP_PROCESS_CREATE_BACKGROUND_BOOLEAN`: true if the process should + * run in the background. In this case the default input and output is + * `SDL_PROCESS_STDIO_NULL` and the exitcode of the process is not + * available, and will always be 0. + * + * On POSIX platforms, wait() and waitpid(-1, ...) should not be called, and + * SIGCHLD should not be ignored or handled because those would prevent SDL + * from properly tracking the lifetime of the underlying process. You should + * use SDL_WaitProcess() instead. + * + * \param props the properties to use. + * \returns the newly created and running process, or NULL if the process + * couldn't be created. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProcess + * \sa SDL_GetProcessProperties + * \sa SDL_ReadProcess + * \sa SDL_GetProcessInput + * \sa SDL_GetProcessOutput + * \sa SDL_KillProcess + * \sa SDL_WaitProcess + * \sa SDL_DestroyProcess + */ +extern SDL_DECLSPEC SDL_Process * SDLCALL SDL_CreateProcessWithProperties(SDL_PropertiesID props); + +#define SDL_PROP_PROCESS_CREATE_ARGS_POINTER "SDL.process.create.args" +#define SDL_PROP_PROCESS_CREATE_ENVIRONMENT_POINTER "SDL.process.create.environment" +#define SDL_PROP_PROCESS_CREATE_STDIN_NUMBER "SDL.process.create.stdin_option" +#define SDL_PROP_PROCESS_CREATE_STDIN_POINTER "SDL.process.create.stdin_source" +#define SDL_PROP_PROCESS_CREATE_STDOUT_NUMBER "SDL.process.create.stdout_option" +#define SDL_PROP_PROCESS_CREATE_STDOUT_POINTER "SDL.process.create.stdout_source" +#define SDL_PROP_PROCESS_CREATE_STDERR_NUMBER "SDL.process.create.stderr_option" +#define SDL_PROP_PROCESS_CREATE_STDERR_POINTER "SDL.process.create.stderr_source" +#define SDL_PROP_PROCESS_CREATE_STDERR_TO_STDOUT_BOOLEAN "SDL.process.create.stderr_to_stdout" +#define SDL_PROP_PROCESS_CREATE_BACKGROUND_BOOLEAN "SDL.process.create.background" + +/** + * Get the properties associated with a process. + * + * The following read-only properties are provided by SDL: + * + * - `SDL_PROP_PROCESS_PID_NUMBER`: the process ID of the process. + * - `SDL_PROP_PROCESS_STDIN_POINTER`: an SDL_IOStream that can be used to + * write input to the process, if it was created with + * `SDL_PROP_PROCESS_CREATE_STDIN_NUMBER` set to `SDL_PROCESS_STDIO_APP`. + * - `SDL_PROP_PROCESS_STDOUT_POINTER`: a non-blocking SDL_IOStream that can + * be used to read output from the process, if it was created with + * `SDL_PROP_PROCESS_CREATE_STDOUT_NUMBER` set to `SDL_PROCESS_STDIO_APP`. + * - `SDL_PROP_PROCESS_STDERR_POINTER`: a non-blocking SDL_IOStream that can + * be used to read error output from the process, if it was created with + * `SDL_PROP_PROCESS_CREATE_STDERR_NUMBER` set to `SDL_PROCESS_STDIO_APP`. + * - `SDL_PROP_PROCESS_BACKGROUND_BOOLEAN`: true if the process is running in + * the background. + * + * \param process the process to query. + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProcess + * \sa SDL_CreateProcessWithProperties + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetProcessProperties(SDL_Process *process); + +#define SDL_PROP_PROCESS_PID_NUMBER "SDL.process.pid" +#define SDL_PROP_PROCESS_STDIN_POINTER "SDL.process.stdin" +#define SDL_PROP_PROCESS_STDOUT_POINTER "SDL.process.stdout" +#define SDL_PROP_PROCESS_STDERR_POINTER "SDL.process.stderr" +#define SDL_PROP_PROCESS_BACKGROUND_BOOLEAN "SDL.process.background" + +/** + * Read all the output from a process. + * + * If a process was created with I/O enabled, you can use this function to + * read the output. This function blocks until the process is complete, + * capturing all output, and providing the process exit code. + * + * The data is allocated with a zero byte at the end (null terminated) for + * convenience. This extra byte is not included in the value reported via + * `datasize`. + * + * The data should be freed with SDL_free(). + * + * \param process The process to read. + * \param datasize a pointer filled in with the number of bytes read, may be + * NULL. + * \param exitcode a pointer filled in with the process exit code if the + * process has exited, may be NULL. + * \returns the data or NULL on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProcess + * \sa SDL_CreateProcessWithProperties + * \sa SDL_DestroyProcess + */ +extern SDL_DECLSPEC void * SDLCALL SDL_ReadProcess(SDL_Process *process, size_t *datasize, int *exitcode); + +/** + * Get the SDL_IOStream associated with process standard input. + * + * The process must have been created with SDL_CreateProcess() and pipe_stdio + * set to true, or with SDL_CreateProcessWithProperties() and + * `SDL_PROP_PROCESS_CREATE_STDIN_NUMBER` set to `SDL_PROCESS_STDIO_APP`. + * + * Writing to this stream can return less data than expected if the process + * hasn't read its input. It may be blocked waiting for its output to be read, + * if so you may need to call SDL_GetProcessOutput() and read the output in + * parallel with writing input. + * + * \param process The process to get the input stream for. + * \returns the input stream or NULL on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProcess + * \sa SDL_CreateProcessWithProperties + * \sa SDL_GetProcessOutput + */ +extern SDL_DECLSPEC SDL_IOStream * SDLCALL SDL_GetProcessInput(SDL_Process *process); + +/** + * Get the SDL_IOStream associated with process standard output. + * + * The process must have been created with SDL_CreateProcess() and pipe_stdio + * set to true, or with SDL_CreateProcessWithProperties() and + * `SDL_PROP_PROCESS_CREATE_STDOUT_NUMBER` set to `SDL_PROCESS_STDIO_APP`. + * + * Reading from this stream can return 0 with SDL_GetIOStatus() returning + * SDL_IO_STATUS_NOT_READY if no output is available yet. + * + * \param process The process to get the output stream for. + * \returns the output stream or NULL on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProcess + * \sa SDL_CreateProcessWithProperties + * \sa SDL_GetProcessInput + */ +extern SDL_DECLSPEC SDL_IOStream * SDLCALL SDL_GetProcessOutput(SDL_Process *process); + +/** + * Stop a process. + * + * \param process The process to stop. + * \param force true to terminate the process immediately, false to try to + * stop the process gracefully. In general you should try to stop + * the process gracefully first as terminating a process may + * leave it with half-written data or in some other unstable + * state. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProcess + * \sa SDL_CreateProcessWithProperties + * \sa SDL_WaitProcess + * \sa SDL_DestroyProcess + */ +extern SDL_DECLSPEC bool SDLCALL SDL_KillProcess(SDL_Process *process, bool force); + +/** + * Wait for a process to finish. + * + * This can be called multiple times to get the status of a process. + * + * The exit code will be the exit code of the process if it terminates + * normally, a negative signal if it terminated due to a signal, or -255 + * otherwise. It will not be changed if the process is still running. + * + * If you create a process with standard output piped to the application + * (`pipe_stdio` being true) then you should read all of the process output + * before calling SDL_WaitProcess(). If you don't do this the process might be + * blocked indefinitely waiting for output to be read and SDL_WaitProcess() + * will never return true; + * + * \param process The process to wait for. + * \param block If true, block until the process finishes; otherwise, report + * on the process' status. + * \param exitcode a pointer filled in with the process exit code if the + * process has exited, may be NULL. + * \returns true if the process exited, false otherwise. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProcess + * \sa SDL_CreateProcessWithProperties + * \sa SDL_KillProcess + * \sa SDL_DestroyProcess + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WaitProcess(SDL_Process *process, bool block, int *exitcode); + +/** + * Destroy a previously created process object. + * + * Note that this does not stop the process, just destroys the SDL object used + * to track it. If you want to stop the process you should use + * SDL_KillProcess(). + * + * \param process The process object to destroy. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProcess + * \sa SDL_CreateProcessWithProperties + * \sa SDL_KillProcess + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyProcess(SDL_Process *process); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_process_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_properties.h b/thirdparty/sdl/include/SDL3/SDL_properties.h new file mode 100644 index 00000000000..1f47d5f4ad8 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_properties.h @@ -0,0 +1,543 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryProperties + * + * A property is a variable that can be created and retrieved by name at + * runtime. + * + * All properties are part of a property group (SDL_PropertiesID). A property + * group can be created with the SDL_CreateProperties function and destroyed + * with the SDL_DestroyProperties function. + * + * Properties can be added to and retrieved from a property group through the + * following functions: + * + * - SDL_SetPointerProperty and SDL_GetPointerProperty operate on `void*` + * pointer types. + * - SDL_SetStringProperty and SDL_GetStringProperty operate on string types. + * - SDL_SetNumberProperty and SDL_GetNumberProperty operate on signed 64-bit + * integer types. + * - SDL_SetFloatProperty and SDL_GetFloatProperty operate on floating point + * types. + * - SDL_SetBooleanProperty and SDL_GetBooleanProperty operate on boolean + * types. + * + * Properties can be removed from a group by using SDL_ClearProperty. + */ + + +#ifndef SDL_properties_h_ +#define SDL_properties_h_ + +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * SDL properties ID + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_PropertiesID; + +/** + * SDL property type + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_PropertyType +{ + SDL_PROPERTY_TYPE_INVALID, + SDL_PROPERTY_TYPE_POINTER, + SDL_PROPERTY_TYPE_STRING, + SDL_PROPERTY_TYPE_NUMBER, + SDL_PROPERTY_TYPE_FLOAT, + SDL_PROPERTY_TYPE_BOOLEAN +} SDL_PropertyType; + +/** + * Get the global SDL properties. + * + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetGlobalProperties(void); + +/** + * Create a group of properties. + * + * All properties are automatically destroyed when SDL_Quit() is called. + * + * \returns an ID for a new group of properties, or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroyProperties + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_CreateProperties(void); + +/** + * Copy a group of properties. + * + * Copy all the properties from one group of properties to another, with the + * exception of properties requiring cleanup (set using + * SDL_SetPointerPropertyWithCleanup()), which will not be copied. Any + * property that already exists on `dst` will be overwritten. + * + * \param src the properties to copy. + * \param dst the destination properties. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CopyProperties(SDL_PropertiesID src, SDL_PropertiesID dst); + +/** + * Lock a group of properties. + * + * Obtain a multi-threaded lock for these properties. Other threads will wait + * while trying to lock these properties until they are unlocked. Properties + * must be unlocked before they are destroyed. + * + * The lock is automatically taken when setting individual properties, this + * function is only needed when you want to set several properties atomically + * or want to guarantee that properties being queried aren't freed in another + * thread. + * + * \param props the properties to lock. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_UnlockProperties + */ +extern SDL_DECLSPEC bool SDLCALL SDL_LockProperties(SDL_PropertiesID props); + +/** + * Unlock a group of properties. + * + * \param props the properties to unlock. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockProperties + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnlockProperties(SDL_PropertiesID props); + +/** + * A callback used to free resources when a property is deleted. + * + * This should release any resources associated with `value` that are no + * longer needed. + * + * This callback is set per-property. Different properties in the same group + * can have different cleanup callbacks. + * + * This callback will be called _during_ SDL_SetPointerPropertyWithCleanup if + * the function fails for any reason. + * + * \param userdata an app-defined pointer passed to the callback. + * \param value the pointer assigned to the property to clean up. + * + * \threadsafety This callback may fire without any locks held; if this is a + * concern, the app should provide its own locking. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_SetPointerPropertyWithCleanup + */ +typedef void (SDLCALL *SDL_CleanupPropertyCallback)(void *userdata, void *value); + +/** + * Set a pointer property in a group of properties with a cleanup function + * that is called when the property is deleted. + * + * The cleanup function is also called if setting the property fails for any + * reason. + * + * For simply setting basic data types, like numbers, bools, or strings, use + * SDL_SetNumberProperty, SDL_SetBooleanProperty, or SDL_SetStringProperty + * instead, as those functions will handle cleanup on your behalf. This + * function is only for more complex, custom data. + * + * \param props the properties to modify. + * \param name the name of the property to modify. + * \param value the new value of the property, or NULL to delete the property. + * \param cleanup the function to call when this property is deleted, or NULL + * if no cleanup is necessary. + * \param userdata a pointer that is passed to the cleanup function. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPointerProperty + * \sa SDL_SetPointerProperty + * \sa SDL_CleanupPropertyCallback + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetPointerPropertyWithCleanup(SDL_PropertiesID props, const char *name, void *value, SDL_CleanupPropertyCallback cleanup, void *userdata); + +/** + * Set a pointer property in a group of properties. + * + * \param props the properties to modify. + * \param name the name of the property to modify. + * \param value the new value of the property, or NULL to delete the property. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPointerProperty + * \sa SDL_HasProperty + * \sa SDL_SetBooleanProperty + * \sa SDL_SetFloatProperty + * \sa SDL_SetNumberProperty + * \sa SDL_SetPointerPropertyWithCleanup + * \sa SDL_SetStringProperty + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetPointerProperty(SDL_PropertiesID props, const char *name, void *value); + +/** + * Set a string property in a group of properties. + * + * This function makes a copy of the string; the caller does not have to + * preserve the data after this call completes. + * + * \param props the properties to modify. + * \param name the name of the property to modify. + * \param value the new value of the property, or NULL to delete the property. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetStringProperty + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetStringProperty(SDL_PropertiesID props, const char *name, const char *value); + +/** + * Set an integer property in a group of properties. + * + * \param props the properties to modify. + * \param name the name of the property to modify. + * \param value the new value of the property. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumberProperty + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetNumberProperty(SDL_PropertiesID props, const char *name, Sint64 value); + +/** + * Set a floating point property in a group of properties. + * + * \param props the properties to modify. + * \param name the name of the property to modify. + * \param value the new value of the property. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetFloatProperty + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetFloatProperty(SDL_PropertiesID props, const char *name, float value); + +/** + * Set a boolean property in a group of properties. + * + * \param props the properties to modify. + * \param name the name of the property to modify. + * \param value the new value of the property. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetBooleanProperty + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetBooleanProperty(SDL_PropertiesID props, const char *name, bool value); + +/** + * Return whether a property exists in a group of properties. + * + * \param props the properties to query. + * \param name the name of the property to query. + * \returns true if the property exists, or false if it doesn't. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPropertyType + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasProperty(SDL_PropertiesID props, const char *name); + +/** + * Get the type of a property in a group of properties. + * + * \param props the properties to query. + * \param name the name of the property to query. + * \returns the type of the property, or SDL_PROPERTY_TYPE_INVALID if it is + * not set. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasProperty + */ +extern SDL_DECLSPEC SDL_PropertyType SDLCALL SDL_GetPropertyType(SDL_PropertiesID props, const char *name); + +/** + * Get a pointer property from a group of properties. + * + * By convention, the names of properties that SDL exposes on objects will + * start with "SDL.", and properties that SDL uses internally will start with + * "SDL.internal.". These should be considered read-only and should not be + * modified by applications. + * + * \param props the properties to query. + * \param name the name of the property to query. + * \param default_value the default value of the property. + * \returns the value of the property, or `default_value` if it is not set or + * not a pointer property. + * + * \threadsafety It is safe to call this function from any thread, although + * the data returned is not protected and could potentially be + * freed if you call SDL_SetPointerProperty() or + * SDL_ClearProperty() on these properties from another thread. + * If you need to avoid this, use SDL_LockProperties() and + * SDL_UnlockProperties(). + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetBooleanProperty + * \sa SDL_GetFloatProperty + * \sa SDL_GetNumberProperty + * \sa SDL_GetPropertyType + * \sa SDL_GetStringProperty + * \sa SDL_HasProperty + * \sa SDL_SetPointerProperty + */ +extern SDL_DECLSPEC void * SDLCALL SDL_GetPointerProperty(SDL_PropertiesID props, const char *name, void *default_value); + +/** + * Get a string property from a group of properties. + * + * \param props the properties to query. + * \param name the name of the property to query. + * \param default_value the default value of the property. + * \returns the value of the property, or `default_value` if it is not set or + * not a string property. + * + * \threadsafety It is safe to call this function from any thread, although + * the data returned is not protected and could potentially be + * freed if you call SDL_SetStringProperty() or + * SDL_ClearProperty() on these properties from another thread. + * If you need to avoid this, use SDL_LockProperties() and + * SDL_UnlockProperties(). + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPropertyType + * \sa SDL_HasProperty + * \sa SDL_SetStringProperty + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetStringProperty(SDL_PropertiesID props, const char *name, const char *default_value); + +/** + * Get a number property from a group of properties. + * + * You can use SDL_GetPropertyType() to query whether the property exists and + * is a number property. + * + * \param props the properties to query. + * \param name the name of the property to query. + * \param default_value the default value of the property. + * \returns the value of the property, or `default_value` if it is not set or + * not a number property. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPropertyType + * \sa SDL_HasProperty + * \sa SDL_SetNumberProperty + */ +extern SDL_DECLSPEC Sint64 SDLCALL SDL_GetNumberProperty(SDL_PropertiesID props, const char *name, Sint64 default_value); + +/** + * Get a floating point property from a group of properties. + * + * You can use SDL_GetPropertyType() to query whether the property exists and + * is a floating point property. + * + * \param props the properties to query. + * \param name the name of the property to query. + * \param default_value the default value of the property. + * \returns the value of the property, or `default_value` if it is not set or + * not a float property. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPropertyType + * \sa SDL_HasProperty + * \sa SDL_SetFloatProperty + */ +extern SDL_DECLSPEC float SDLCALL SDL_GetFloatProperty(SDL_PropertiesID props, const char *name, float default_value); + +/** + * Get a boolean property from a group of properties. + * + * You can use SDL_GetPropertyType() to query whether the property exists and + * is a boolean property. + * + * \param props the properties to query. + * \param name the name of the property to query. + * \param default_value the default value of the property. + * \returns the value of the property, or `default_value` if it is not set or + * not a boolean property. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPropertyType + * \sa SDL_HasProperty + * \sa SDL_SetBooleanProperty + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetBooleanProperty(SDL_PropertiesID props, const char *name, bool default_value); + +/** + * Clear a property from a group of properties. + * + * \param props the properties to modify. + * \param name the name of the property to clear. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ClearProperty(SDL_PropertiesID props, const char *name); + +/** + * A callback used to enumerate all the properties in a group of properties. + * + * This callback is called from SDL_EnumerateProperties(), and is called once + * per property in the set. + * + * \param userdata an app-defined pointer passed to the callback. + * \param props the SDL_PropertiesID that is being enumerated. + * \param name the next property name in the enumeration. + * + * \threadsafety SDL_EnumerateProperties holds a lock on `props` during this + * callback. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_EnumerateProperties + */ +typedef void (SDLCALL *SDL_EnumeratePropertiesCallback)(void *userdata, SDL_PropertiesID props, const char *name); + +/** + * Enumerate the properties contained in a group of properties. + * + * The callback function is called for each property in the group of + * properties. The properties are locked during enumeration. + * + * \param props the properties to query. + * \param callback the function to call for each property. + * \param userdata a pointer that is passed to `callback`. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_EnumerateProperties(SDL_PropertiesID props, SDL_EnumeratePropertiesCallback callback, void *userdata); + +/** + * Destroy a group of properties. + * + * All properties are deleted and their cleanup functions will be called, if + * any. + * + * \param props the properties to destroy. + * + * \threadsafety This function should not be called while these properties are + * locked or other threads might be setting or getting values + * from these properties. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProperties + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyProperties(SDL_PropertiesID props); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_properties_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_rect.h b/thirdparty/sdl/include/SDL3/SDL_rect.h new file mode 100644 index 00000000000..eb2d34a69a1 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_rect.h @@ -0,0 +1,507 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryRect + * + * Some helper functions for managing rectangles and 2D points, in both + * integer and floating point versions. + */ + +#ifndef SDL_rect_h_ +#define SDL_rect_h_ + +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The structure that defines a point (using integers). + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_GetRectEnclosingPoints + * \sa SDL_PointInRect + */ +typedef struct SDL_Point +{ + int x; + int y; +} SDL_Point; + +/** + * The structure that defines a point (using floating point values). + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_GetRectEnclosingPointsFloat + * \sa SDL_PointInRectFloat + */ +typedef struct SDL_FPoint +{ + float x; + float y; +} SDL_FPoint; + + +/** + * A rectangle, with the origin at the upper left (using integers). + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_RectEmpty + * \sa SDL_RectsEqual + * \sa SDL_HasRectIntersection + * \sa SDL_GetRectIntersection + * \sa SDL_GetRectAndLineIntersection + * \sa SDL_GetRectUnion + * \sa SDL_GetRectEnclosingPoints + */ +typedef struct SDL_Rect +{ + int x, y; + int w, h; +} SDL_Rect; + + +/** + * A rectangle, with the origin at the upper left (using floating point + * values). + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_RectEmptyFloat + * \sa SDL_RectsEqualFloat + * \sa SDL_RectsEqualEpsilon + * \sa SDL_HasRectIntersectionFloat + * \sa SDL_GetRectIntersectionFloat + * \sa SDL_GetRectAndLineIntersectionFloat + * \sa SDL_GetRectUnionFloat + * \sa SDL_GetRectEnclosingPointsFloat + * \sa SDL_PointInRectFloat + */ +typedef struct SDL_FRect +{ + float x; + float y; + float w; + float h; +} SDL_FRect; + + +/** + * Convert an SDL_Rect to SDL_FRect + * + * \param rect a pointer to an SDL_Rect. + * \param frect a pointer filled in with the floating point representation of + * `rect`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE void SDL_RectToFRect(const SDL_Rect *rect, SDL_FRect *frect) +{ + frect->x = (float)rect->x; + frect->y = (float)rect->y; + frect->w = (float)rect->w; + frect->h = (float)rect->h; +} + +/** + * Determine whether a point resides inside a rectangle. + * + * A point is considered part of a rectangle if both `p` and `r` are not NULL, + * and `p`'s x and y coordinates are >= to the rectangle's top left corner, + * and < the rectangle's x+w and y+h. So a 1x1 rectangle considers point (0,0) + * as "inside" and (0,1) as not. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param p the point to test. + * \param r the rectangle to test. + * \returns true if `p` is contained by `r`, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE bool SDL_PointInRect(const SDL_Point *p, const SDL_Rect *r) +{ + return ( p && r && (p->x >= r->x) && (p->x < (r->x + r->w)) && + (p->y >= r->y) && (p->y < (r->y + r->h)) ) ? true : false; +} + +/** + * Determine whether a rectangle has no area. + * + * A rectangle is considered "empty" for this function if `r` is NULL, or if + * `r`'s width and/or height are <= 0. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param r the rectangle to test. + * \returns true if the rectangle is "empty", false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE bool SDL_RectEmpty(const SDL_Rect *r) +{ + return ((!r) || (r->w <= 0) || (r->h <= 0)) ? true : false; +} + +/** + * Determine whether two rectangles are equal. + * + * Rectangles are considered equal if both are not NULL and each of their x, + * y, width and height match. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param a the first rectangle to test. + * \param b the second rectangle to test. + * \returns true if the rectangles are equal, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE bool SDL_RectsEqual(const SDL_Rect *a, const SDL_Rect *b) +{ + return (a && b && (a->x == b->x) && (a->y == b->y) && + (a->w == b->w) && (a->h == b->h)) ? true : false; +} + +/** + * Determine whether two rectangles intersect. + * + * If either pointer is NULL the function will return false. + * + * \param A an SDL_Rect structure representing the first rectangle. + * \param B an SDL_Rect structure representing the second rectangle. + * \returns true if there is an intersection, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRectIntersection + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasRectIntersection(const SDL_Rect *A, const SDL_Rect *B); + +/** + * Calculate the intersection of two rectangles. + * + * If `result` is NULL then this function will return false. + * + * \param A an SDL_Rect structure representing the first rectangle. + * \param B an SDL_Rect structure representing the second rectangle. + * \param result an SDL_Rect structure filled in with the intersection of + * rectangles `A` and `B`. + * \returns true if there is an intersection, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasRectIntersection + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRectIntersection(const SDL_Rect *A, const SDL_Rect *B, SDL_Rect *result); + +/** + * Calculate the union of two rectangles. + * + * \param A an SDL_Rect structure representing the first rectangle. + * \param B an SDL_Rect structure representing the second rectangle. + * \param result an SDL_Rect structure filled in with the union of rectangles + * `A` and `B`. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRectUnion(const SDL_Rect *A, const SDL_Rect *B, SDL_Rect *result); + +/** + * Calculate a minimal rectangle enclosing a set of points. + * + * If `clip` is not NULL then only points inside of the clipping rectangle are + * considered. + * + * \param points an array of SDL_Point structures representing points to be + * enclosed. + * \param count the number of structures in the `points` array. + * \param clip an SDL_Rect used for clipping or NULL to enclose all points. + * \param result an SDL_Rect structure filled in with the minimal enclosing + * rectangle. + * \returns true if any points were enclosed or false if all the points were + * outside of the clipping rectangle. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRectEnclosingPoints(const SDL_Point *points, int count, const SDL_Rect *clip, SDL_Rect *result); + +/** + * Calculate the intersection of a rectangle and line segment. + * + * This function is used to clip a line segment to a rectangle. A line segment + * contained entirely within the rectangle or that does not intersect will + * remain unchanged. A line segment that crosses the rectangle at either or + * both ends will be clipped to the boundary of the rectangle and the new + * coordinates saved in `X1`, `Y1`, `X2`, and/or `Y2` as necessary. + * + * \param rect an SDL_Rect structure representing the rectangle to intersect. + * \param X1 a pointer to the starting X-coordinate of the line. + * \param Y1 a pointer to the starting Y-coordinate of the line. + * \param X2 a pointer to the ending X-coordinate of the line. + * \param Y2 a pointer to the ending Y-coordinate of the line. + * \returns true if there is an intersection, false otherwise. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRectAndLineIntersection(const SDL_Rect *rect, int *X1, int *Y1, int *X2, int *Y2); + + +/* SDL_FRect versions... */ + +/** + * Determine whether a point resides inside a floating point rectangle. + * + * A point is considered part of a rectangle if both `p` and `r` are not NULL, + * and `p`'s x and y coordinates are >= to the rectangle's top left corner, + * and <= the rectangle's x+w and y+h. So a 1x1 rectangle considers point + * (0,0) and (0,1) as "inside" and (0,2) as not. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param p the point to test. + * \param r the rectangle to test. + * \returns true if `p` is contained by `r`, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE bool SDL_PointInRectFloat(const SDL_FPoint *p, const SDL_FRect *r) +{ + return ( p && r && (p->x >= r->x) && (p->x <= (r->x + r->w)) && + (p->y >= r->y) && (p->y <= (r->y + r->h)) ) ? true : false; +} + +/** + * Determine whether a floating point rectangle can contain any point. + * + * A rectangle is considered "empty" for this function if `r` is NULL, or if + * `r`'s width and/or height are < 0.0f. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param r the rectangle to test. + * \returns true if the rectangle is "empty", false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE bool SDL_RectEmptyFloat(const SDL_FRect *r) +{ + return ((!r) || (r->w < 0.0f) || (r->h < 0.0f)) ? true : false; +} + +/** + * Determine whether two floating point rectangles are equal, within some + * given epsilon. + * + * Rectangles are considered equal if both are not NULL and each of their x, + * y, width and height are within `epsilon` of each other. If you don't know + * what value to use for `epsilon`, you should call the SDL_RectsEqualFloat + * function instead. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param a the first rectangle to test. + * \param b the second rectangle to test. + * \param epsilon the epsilon value for comparison. + * \returns true if the rectangles are equal, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RectsEqualFloat + */ +SDL_FORCE_INLINE bool SDL_RectsEqualEpsilon(const SDL_FRect *a, const SDL_FRect *b, float epsilon) +{ + return (a && b && ((a == b) || + ((SDL_fabsf(a->x - b->x) <= epsilon) && + (SDL_fabsf(a->y - b->y) <= epsilon) && + (SDL_fabsf(a->w - b->w) <= epsilon) && + (SDL_fabsf(a->h - b->h) <= epsilon)))) + ? true : false; +} + +/** + * Determine whether two floating point rectangles are equal, within a default + * epsilon. + * + * Rectangles are considered equal if both are not NULL and each of their x, + * y, width and height are within SDL_FLT_EPSILON of each other. This is often + * a reasonable way to compare two floating point rectangles and deal with the + * slight precision variations in floating point calculations that tend to pop + * up. + * + * Note that this is a forced-inline function in a header, and not a public + * API function available in the SDL library (which is to say, the code is + * embedded in the calling program and the linker and dynamic loader will not + * be able to find this function inside SDL itself). + * + * \param a the first rectangle to test. + * \param b the second rectangle to test. + * \returns true if the rectangles are equal, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RectsEqualEpsilon + */ +SDL_FORCE_INLINE bool SDL_RectsEqualFloat(const SDL_FRect *a, const SDL_FRect *b) +{ + return SDL_RectsEqualEpsilon(a, b, SDL_FLT_EPSILON); +} + +/** + * Determine whether two rectangles intersect with float precision. + * + * If either pointer is NULL the function will return false. + * + * \param A an SDL_FRect structure representing the first rectangle. + * \param B an SDL_FRect structure representing the second rectangle. + * \returns true if there is an intersection, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRectIntersection + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HasRectIntersectionFloat(const SDL_FRect *A, const SDL_FRect *B); + +/** + * Calculate the intersection of two rectangles with float precision. + * + * If `result` is NULL then this function will return false. + * + * \param A an SDL_FRect structure representing the first rectangle. + * \param B an SDL_FRect structure representing the second rectangle. + * \param result an SDL_FRect structure filled in with the intersection of + * rectangles `A` and `B`. + * \returns true if there is an intersection, false otherwise. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HasRectIntersectionFloat + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRectIntersectionFloat(const SDL_FRect *A, const SDL_FRect *B, SDL_FRect *result); + +/** + * Calculate the union of two rectangles with float precision. + * + * \param A an SDL_FRect structure representing the first rectangle. + * \param B an SDL_FRect structure representing the second rectangle. + * \param result an SDL_FRect structure filled in with the union of rectangles + * `A` and `B`. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRectUnionFloat(const SDL_FRect *A, const SDL_FRect *B, SDL_FRect *result); + +/** + * Calculate a minimal rectangle enclosing a set of points with float + * precision. + * + * If `clip` is not NULL then only points inside of the clipping rectangle are + * considered. + * + * \param points an array of SDL_FPoint structures representing points to be + * enclosed. + * \param count the number of structures in the `points` array. + * \param clip an SDL_FRect used for clipping or NULL to enclose all points. + * \param result an SDL_FRect structure filled in with the minimal enclosing + * rectangle. + * \returns true if any points were enclosed or false if all the points were + * outside of the clipping rectangle. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRectEnclosingPointsFloat(const SDL_FPoint *points, int count, const SDL_FRect *clip, SDL_FRect *result); + +/** + * Calculate the intersection of a rectangle and line segment with float + * precision. + * + * This function is used to clip a line segment to a rectangle. A line segment + * contained entirely within the rectangle or that does not intersect will + * remain unchanged. A line segment that crosses the rectangle at either or + * both ends will be clipped to the boundary of the rectangle and the new + * coordinates saved in `X1`, `Y1`, `X2`, and/or `Y2` as necessary. + * + * \param rect an SDL_FRect structure representing the rectangle to intersect. + * \param X1 a pointer to the starting X-coordinate of the line. + * \param Y1 a pointer to the starting Y-coordinate of the line. + * \param X2 a pointer to the ending X-coordinate of the line. + * \param Y2 a pointer to the ending Y-coordinate of the line. + * \returns true if there is an intersection, false otherwise. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRectAndLineIntersectionFloat(const SDL_FRect *rect, float *X1, float *Y1, float *X2, float *Y2); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_rect_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_render.h b/thirdparty/sdl/include/SDL3/SDL_render.h new file mode 100644 index 00000000000..c9d184cc07c --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_render.h @@ -0,0 +1,2645 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryRender + * + * Header file for SDL 2D rendering functions. + * + * This API supports the following features: + * + * - single pixel points + * - single pixel lines + * - filled rectangles + * - texture images + * - 2D polygons + * + * The primitives may be drawn in opaque, blended, or additive modes. + * + * The texture images may be drawn in opaque, blended, or additive modes. They + * can have an additional color tint or alpha modulation applied to them, and + * may also be stretched with linear interpolation. + * + * This API is designed to accelerate simple 2D operations. You may want more + * functionality such as polygons and particle effects and in that case you + * should use SDL's OpenGL/Direct3D support, the SDL3 GPU API, or one of the + * many good 3D engines. + * + * These functions must be called from the main thread. See this bug for + * details: https://github.com/libsdl-org/SDL/issues/986 + */ + +#ifndef SDL_render_h_ +#define SDL_render_h_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The name of the software renderer. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_SOFTWARE_RENDERER "software" + +/** + * Vertex structure. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Vertex +{ + SDL_FPoint position; /**< Vertex position, in SDL_Renderer coordinates */ + SDL_FColor color; /**< Vertex color */ + SDL_FPoint tex_coord; /**< Normalized texture coordinates, if needed */ +} SDL_Vertex; + +/** + * The access pattern allowed for a texture. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_TextureAccess +{ + SDL_TEXTUREACCESS_STATIC, /**< Changes rarely, not lockable */ + SDL_TEXTUREACCESS_STREAMING, /**< Changes frequently, lockable */ + SDL_TEXTUREACCESS_TARGET /**< Texture can be used as a render target */ +} SDL_TextureAccess; + +/** + * How the logical size is mapped to the output. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_RendererLogicalPresentation +{ + SDL_LOGICAL_PRESENTATION_DISABLED, /**< There is no logical size in effect */ + SDL_LOGICAL_PRESENTATION_STRETCH, /**< The rendered content is stretched to the output resolution */ + SDL_LOGICAL_PRESENTATION_LETTERBOX, /**< The rendered content is fit to the largest dimension and the other dimension is letterboxed with black bars */ + SDL_LOGICAL_PRESENTATION_OVERSCAN, /**< The rendered content is fit to the smallest dimension and the other dimension extends beyond the output bounds */ + SDL_LOGICAL_PRESENTATION_INTEGER_SCALE /**< The rendered content is scaled up by integer multiples to fit the output resolution */ +} SDL_RendererLogicalPresentation; + +/** + * A structure representing rendering state + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Renderer SDL_Renderer; + +#ifndef SDL_INTERNAL + +/** + * An efficient driver-specific representation of pixel data + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_CreateTexture + * \sa SDL_CreateTextureFromSurface + * \sa SDL_CreateTextureWithProperties + * \sa SDL_DestroyTexture + */ +struct SDL_Texture +{ + SDL_PixelFormat format; /**< The format of the texture, read-only */ + int w; /**< The width of the texture, read-only. */ + int h; /**< The height of the texture, read-only. */ + + int refcount; /**< Application reference count, used when freeing texture */ +}; +#endif /* !SDL_INTERNAL */ + +typedef struct SDL_Texture SDL_Texture; + +/* Function prototypes */ + +/** + * Get the number of 2D rendering drivers available for the current display. + * + * A render driver is a set of code that handles rendering and texture + * management on a particular display. Normally there is only one, but some + * drivers may have several available with different capabilities. + * + * There may be none if SDL was compiled without render support. + * + * \returns the number of built in render drivers. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateRenderer + * \sa SDL_GetRenderDriver + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumRenderDrivers(void); + +/** + * Use this function to get the name of a built in 2D rendering driver. + * + * The list of rendering drivers is given in the order that they are normally + * initialized by default; the drivers that seem more reasonable to choose + * first (as far as the SDL developers believe) are earlier in the list. + * + * The names of drivers are all simple, low-ASCII identifiers, like "opengl", + * "direct3d12" or "metal". These never have Unicode characters, and are not + * meant to be proper names. + * + * \param index the index of the rendering driver; the value ranges from 0 to + * SDL_GetNumRenderDrivers() - 1. + * \returns the name of the rendering driver at the requested index, or NULL + * if an invalid index was specified. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumRenderDrivers + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetRenderDriver(int index); + +/** + * Create a window and default renderer. + * + * \param title the title of the window, in UTF-8 encoding. + * \param width the width of the window. + * \param height the height of the window. + * \param window_flags the flags used to create the window (see + * SDL_CreateWindow()). + * \param window a pointer filled with the window, or NULL on error. + * \param renderer a pointer filled with the renderer, or NULL on error. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateRenderer + * \sa SDL_CreateWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CreateWindowAndRenderer(const char *title, int width, int height, SDL_WindowFlags window_flags, SDL_Window **window, SDL_Renderer **renderer); + +/** + * Create a 2D rendering context for a window. + * + * If you want a specific renderer, you can specify its name here. A list of + * available renderers can be obtained by calling SDL_GetRenderDriver() + * multiple times, with indices from 0 to SDL_GetNumRenderDrivers()-1. If you + * don't need a specific renderer, specify NULL and SDL will attempt to choose + * the best option for you, based on what is available on the user's system. + * + * If `name` is a comma-separated list, SDL will try each name, in the order + * listed, until one succeeds or all of them fail. + * + * By default the rendering size matches the window size in pixels, but you + * can call SDL_SetRenderLogicalPresentation() to change the content size and + * scaling options. + * + * \param window the window where rendering is displayed. + * \param name the name of the rendering driver to initialize, or NULL to let + * SDL choose one. + * \returns a valid rendering context or NULL if there was an error; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateRendererWithProperties + * \sa SDL_CreateSoftwareRenderer + * \sa SDL_DestroyRenderer + * \sa SDL_GetNumRenderDrivers + * \sa SDL_GetRenderDriver + * \sa SDL_GetRendererName + */ +extern SDL_DECLSPEC SDL_Renderer * SDLCALL SDL_CreateRenderer(SDL_Window *window, const char *name); + +/** + * Create a 2D rendering context for a window, with the specified properties. + * + * These are the supported properties: + * + * - `SDL_PROP_RENDERER_CREATE_NAME_STRING`: the name of the rendering driver + * to use, if a specific one is desired + * - `SDL_PROP_RENDERER_CREATE_WINDOW_POINTER`: the window where rendering is + * displayed, required if this isn't a software renderer using a surface + * - `SDL_PROP_RENDERER_CREATE_SURFACE_POINTER`: the surface where rendering + * is displayed, if you want a software renderer without a window + * - `SDL_PROP_RENDERER_CREATE_OUTPUT_COLORSPACE_NUMBER`: an SDL_Colorspace + * value describing the colorspace for output to the display, defaults to + * SDL_COLORSPACE_SRGB. The direct3d11, direct3d12, and metal renderers + * support SDL_COLORSPACE_SRGB_LINEAR, which is a linear color space and + * supports HDR output. If you select SDL_COLORSPACE_SRGB_LINEAR, drawing + * still uses the sRGB colorspace, but values can go beyond 1.0 and float + * (linear) format textures can be used for HDR content. + * - `SDL_PROP_RENDERER_CREATE_PRESENT_VSYNC_NUMBER`: non-zero if you want + * present synchronized with the refresh rate. This property can take any + * value that is supported by SDL_SetRenderVSync() for the renderer. + * + * With the vulkan renderer: + * + * - `SDL_PROP_RENDERER_CREATE_VULKAN_INSTANCE_POINTER`: the VkInstance to use + * with the renderer, optional. + * - `SDL_PROP_RENDERER_CREATE_VULKAN_SURFACE_NUMBER`: the VkSurfaceKHR to use + * with the renderer, optional. + * - `SDL_PROP_RENDERER_CREATE_VULKAN_PHYSICAL_DEVICE_POINTER`: the + * VkPhysicalDevice to use with the renderer, optional. + * - `SDL_PROP_RENDERER_CREATE_VULKAN_DEVICE_POINTER`: the VkDevice to use + * with the renderer, optional. + * - `SDL_PROP_RENDERER_CREATE_VULKAN_GRAPHICS_QUEUE_FAMILY_INDEX_NUMBER`: the + * queue family index used for rendering. + * - `SDL_PROP_RENDERER_CREATE_VULKAN_PRESENT_QUEUE_FAMILY_INDEX_NUMBER`: the + * queue family index used for presentation. + * + * \param props the properties to use. + * \returns a valid rendering context or NULL if there was an error; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProperties + * \sa SDL_CreateRenderer + * \sa SDL_CreateSoftwareRenderer + * \sa SDL_DestroyRenderer + * \sa SDL_GetRendererName + */ +extern SDL_DECLSPEC SDL_Renderer * SDLCALL SDL_CreateRendererWithProperties(SDL_PropertiesID props); + +#define SDL_PROP_RENDERER_CREATE_NAME_STRING "SDL.renderer.create.name" +#define SDL_PROP_RENDERER_CREATE_WINDOW_POINTER "SDL.renderer.create.window" +#define SDL_PROP_RENDERER_CREATE_SURFACE_POINTER "SDL.renderer.create.surface" +#define SDL_PROP_RENDERER_CREATE_OUTPUT_COLORSPACE_NUMBER "SDL.renderer.create.output_colorspace" +#define SDL_PROP_RENDERER_CREATE_PRESENT_VSYNC_NUMBER "SDL.renderer.create.present_vsync" +#define SDL_PROP_RENDERER_CREATE_VULKAN_INSTANCE_POINTER "SDL.renderer.create.vulkan.instance" +#define SDL_PROP_RENDERER_CREATE_VULKAN_SURFACE_NUMBER "SDL.renderer.create.vulkan.surface" +#define SDL_PROP_RENDERER_CREATE_VULKAN_PHYSICAL_DEVICE_POINTER "SDL.renderer.create.vulkan.physical_device" +#define SDL_PROP_RENDERER_CREATE_VULKAN_DEVICE_POINTER "SDL.renderer.create.vulkan.device" +#define SDL_PROP_RENDERER_CREATE_VULKAN_GRAPHICS_QUEUE_FAMILY_INDEX_NUMBER "SDL.renderer.create.vulkan.graphics_queue_family_index" +#define SDL_PROP_RENDERER_CREATE_VULKAN_PRESENT_QUEUE_FAMILY_INDEX_NUMBER "SDL.renderer.create.vulkan.present_queue_family_index" + +/** + * Create a 2D software rendering context for a surface. + * + * Two other API which can be used to create SDL_Renderer: + * SDL_CreateRenderer() and SDL_CreateWindowAndRenderer(). These can _also_ + * create a software renderer, but they are intended to be used with an + * SDL_Window as the final destination and not an SDL_Surface. + * + * \param surface the SDL_Surface structure representing the surface where + * rendering is done. + * \returns a valid rendering context or NULL if there was an error; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroyRenderer + */ +extern SDL_DECLSPEC SDL_Renderer * SDLCALL SDL_CreateSoftwareRenderer(SDL_Surface *surface); + +/** + * Get the renderer associated with a window. + * + * \param window the window to query. + * \returns the rendering context on success or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Renderer * SDLCALL SDL_GetRenderer(SDL_Window *window); + +/** + * Get the window associated with a renderer. + * + * \param renderer the renderer to query. + * \returns the window on success or NULL on failure; call SDL_GetError() for + * more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GetRenderWindow(SDL_Renderer *renderer); + +/** + * Get the name of a renderer. + * + * \param renderer the rendering context. + * \returns the name of the selected renderer, or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateRenderer + * \sa SDL_CreateRendererWithProperties + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetRendererName(SDL_Renderer *renderer); + +/** + * Get the properties associated with a renderer. + * + * The following read-only properties are provided by SDL: + * + * - `SDL_PROP_RENDERER_NAME_STRING`: the name of the rendering driver + * - `SDL_PROP_RENDERER_WINDOW_POINTER`: the window where rendering is + * displayed, if any + * - `SDL_PROP_RENDERER_SURFACE_POINTER`: the surface where rendering is + * displayed, if this is a software renderer without a window + * - `SDL_PROP_RENDERER_VSYNC_NUMBER`: the current vsync setting + * - `SDL_PROP_RENDERER_MAX_TEXTURE_SIZE_NUMBER`: the maximum texture width + * and height + * - `SDL_PROP_RENDERER_TEXTURE_FORMATS_POINTER`: a (const SDL_PixelFormat *) + * array of pixel formats, terminated with SDL_PIXELFORMAT_UNKNOWN, + * representing the available texture formats for this renderer. + * - `SDL_PROP_RENDERER_OUTPUT_COLORSPACE_NUMBER`: an SDL_Colorspace value + * describing the colorspace for output to the display, defaults to + * SDL_COLORSPACE_SRGB. + * - `SDL_PROP_RENDERER_HDR_ENABLED_BOOLEAN`: true if the output colorspace is + * SDL_COLORSPACE_SRGB_LINEAR and the renderer is showing on a display with + * HDR enabled. This property can change dynamically when + * SDL_EVENT_WINDOW_HDR_STATE_CHANGED is sent. + * - `SDL_PROP_RENDERER_SDR_WHITE_POINT_FLOAT`: the value of SDR white in the + * SDL_COLORSPACE_SRGB_LINEAR colorspace. When HDR is enabled, this value is + * automatically multiplied into the color scale. This property can change + * dynamically when SDL_EVENT_WINDOW_HDR_STATE_CHANGED is sent. + * - `SDL_PROP_RENDERER_HDR_HEADROOM_FLOAT`: the additional high dynamic range + * that can be displayed, in terms of the SDR white point. When HDR is not + * enabled, this will be 1.0. This property can change dynamically when + * SDL_EVENT_WINDOW_HDR_STATE_CHANGED is sent. + * + * With the direct3d renderer: + * + * - `SDL_PROP_RENDERER_D3D9_DEVICE_POINTER`: the IDirect3DDevice9 associated + * with the renderer + * + * With the direct3d11 renderer: + * + * - `SDL_PROP_RENDERER_D3D11_DEVICE_POINTER`: the ID3D11Device associated + * with the renderer + * - `SDL_PROP_RENDERER_D3D11_SWAPCHAIN_POINTER`: the IDXGISwapChain1 + * associated with the renderer. This may change when the window is resized. + * + * With the direct3d12 renderer: + * + * - `SDL_PROP_RENDERER_D3D12_DEVICE_POINTER`: the ID3D12Device associated + * with the renderer + * - `SDL_PROP_RENDERER_D3D12_SWAPCHAIN_POINTER`: the IDXGISwapChain4 + * associated with the renderer. + * - `SDL_PROP_RENDERER_D3D12_COMMAND_QUEUE_POINTER`: the ID3D12CommandQueue + * associated with the renderer + * + * With the vulkan renderer: + * + * - `SDL_PROP_RENDERER_VULKAN_INSTANCE_POINTER`: the VkInstance associated + * with the renderer + * - `SDL_PROP_RENDERER_VULKAN_SURFACE_NUMBER`: the VkSurfaceKHR associated + * with the renderer + * - `SDL_PROP_RENDERER_VULKAN_PHYSICAL_DEVICE_POINTER`: the VkPhysicalDevice + * associated with the renderer + * - `SDL_PROP_RENDERER_VULKAN_DEVICE_POINTER`: the VkDevice associated with + * the renderer + * - `SDL_PROP_RENDERER_VULKAN_GRAPHICS_QUEUE_FAMILY_INDEX_NUMBER`: the queue + * family index used for rendering + * - `SDL_PROP_RENDERER_VULKAN_PRESENT_QUEUE_FAMILY_INDEX_NUMBER`: the queue + * family index used for presentation + * - `SDL_PROP_RENDERER_VULKAN_SWAPCHAIN_IMAGE_COUNT_NUMBER`: the number of + * swapchain images, or potential frames in flight, used by the Vulkan + * renderer + * + * With the gpu renderer: + * + * - `SDL_PROP_RENDERER_GPU_DEVICE_POINTER`: the SDL_GPUDevice associated with + * the renderer + * + * \param renderer the rendering context. + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetRendererProperties(SDL_Renderer *renderer); + +#define SDL_PROP_RENDERER_NAME_STRING "SDL.renderer.name" +#define SDL_PROP_RENDERER_WINDOW_POINTER "SDL.renderer.window" +#define SDL_PROP_RENDERER_SURFACE_POINTER "SDL.renderer.surface" +#define SDL_PROP_RENDERER_VSYNC_NUMBER "SDL.renderer.vsync" +#define SDL_PROP_RENDERER_MAX_TEXTURE_SIZE_NUMBER "SDL.renderer.max_texture_size" +#define SDL_PROP_RENDERER_TEXTURE_FORMATS_POINTER "SDL.renderer.texture_formats" +#define SDL_PROP_RENDERER_OUTPUT_COLORSPACE_NUMBER "SDL.renderer.output_colorspace" +#define SDL_PROP_RENDERER_HDR_ENABLED_BOOLEAN "SDL.renderer.HDR_enabled" +#define SDL_PROP_RENDERER_SDR_WHITE_POINT_FLOAT "SDL.renderer.SDR_white_point" +#define SDL_PROP_RENDERER_HDR_HEADROOM_FLOAT "SDL.renderer.HDR_headroom" +#define SDL_PROP_RENDERER_D3D9_DEVICE_POINTER "SDL.renderer.d3d9.device" +#define SDL_PROP_RENDERER_D3D11_DEVICE_POINTER "SDL.renderer.d3d11.device" +#define SDL_PROP_RENDERER_D3D11_SWAPCHAIN_POINTER "SDL.renderer.d3d11.swap_chain" +#define SDL_PROP_RENDERER_D3D12_DEVICE_POINTER "SDL.renderer.d3d12.device" +#define SDL_PROP_RENDERER_D3D12_SWAPCHAIN_POINTER "SDL.renderer.d3d12.swap_chain" +#define SDL_PROP_RENDERER_D3D12_COMMAND_QUEUE_POINTER "SDL.renderer.d3d12.command_queue" +#define SDL_PROP_RENDERER_VULKAN_INSTANCE_POINTER "SDL.renderer.vulkan.instance" +#define SDL_PROP_RENDERER_VULKAN_SURFACE_NUMBER "SDL.renderer.vulkan.surface" +#define SDL_PROP_RENDERER_VULKAN_PHYSICAL_DEVICE_POINTER "SDL.renderer.vulkan.physical_device" +#define SDL_PROP_RENDERER_VULKAN_DEVICE_POINTER "SDL.renderer.vulkan.device" +#define SDL_PROP_RENDERER_VULKAN_GRAPHICS_QUEUE_FAMILY_INDEX_NUMBER "SDL.renderer.vulkan.graphics_queue_family_index" +#define SDL_PROP_RENDERER_VULKAN_PRESENT_QUEUE_FAMILY_INDEX_NUMBER "SDL.renderer.vulkan.present_queue_family_index" +#define SDL_PROP_RENDERER_VULKAN_SWAPCHAIN_IMAGE_COUNT_NUMBER "SDL.renderer.vulkan.swapchain_image_count" +#define SDL_PROP_RENDERER_GPU_DEVICE_POINTER "SDL.renderer.gpu.device" + +/** + * Get the output size in pixels of a rendering context. + * + * This returns the true output size in pixels, ignoring any render targets or + * logical size and presentation. + * + * For the output size of the current rendering target, with logical size + * adjustments, use SDL_GetCurrentRenderOutputSize() instead. + * + * \param renderer the rendering context. + * \param w a pointer filled in with the width in pixels. + * \param h a pointer filled in with the height in pixels. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetCurrentRenderOutputSize + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderOutputSize(SDL_Renderer *renderer, int *w, int *h); + +/** + * Get the current output size in pixels of a rendering context. + * + * If a rendering target is active, this will return the size of the rendering + * target in pixels, otherwise return the value of SDL_GetRenderOutputSize(). + * + * Rendering target or not, the output will be adjusted by the current logical + * presentation state, dictated by SDL_SetRenderLogicalPresentation(). + * + * \param renderer the rendering context. + * \param w a pointer filled in with the current width. + * \param h a pointer filled in with the current height. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderOutputSize + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetCurrentRenderOutputSize(SDL_Renderer *renderer, int *w, int *h); + +/** + * Create a texture for a rendering context. + * + * The contents of a texture when first created are not defined. + * + * \param renderer the rendering context. + * \param format one of the enumerated values in SDL_PixelFormat. + * \param access one of the enumerated values in SDL_TextureAccess. + * \param w the width of the texture in pixels. + * \param h the height of the texture in pixels. + * \returns the created texture or NULL on failure; call SDL_GetError() for + * more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTextureFromSurface + * \sa SDL_CreateTextureWithProperties + * \sa SDL_DestroyTexture + * \sa SDL_GetTextureSize + * \sa SDL_UpdateTexture + */ +extern SDL_DECLSPEC SDL_Texture * SDLCALL SDL_CreateTexture(SDL_Renderer *renderer, SDL_PixelFormat format, SDL_TextureAccess access, int w, int h); + +/** + * Create a texture from an existing surface. + * + * The surface is not modified or freed by this function. + * + * The SDL_TextureAccess hint for the created texture is + * `SDL_TEXTUREACCESS_STATIC`. + * + * The pixel format of the created texture may be different from the pixel + * format of the surface, and can be queried using the + * SDL_PROP_TEXTURE_FORMAT_NUMBER property. + * + * \param renderer the rendering context. + * \param surface the SDL_Surface structure containing pixel data used to fill + * the texture. + * \returns the created texture or NULL on failure; call SDL_GetError() for + * more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTexture + * \sa SDL_CreateTextureWithProperties + * \sa SDL_DestroyTexture + */ +extern SDL_DECLSPEC SDL_Texture * SDLCALL SDL_CreateTextureFromSurface(SDL_Renderer *renderer, SDL_Surface *surface); + +/** + * Create a texture for a rendering context with the specified properties. + * + * These are the supported properties: + * + * - `SDL_PROP_TEXTURE_CREATE_COLORSPACE_NUMBER`: an SDL_Colorspace value + * describing the texture colorspace, defaults to SDL_COLORSPACE_SRGB_LINEAR + * for floating point textures, SDL_COLORSPACE_HDR10 for 10-bit textures, + * SDL_COLORSPACE_SRGB for other RGB textures and SDL_COLORSPACE_JPEG for + * YUV textures. + * - `SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER`: one of the enumerated values in + * SDL_PixelFormat, defaults to the best RGBA format for the renderer + * - `SDL_PROP_TEXTURE_CREATE_ACCESS_NUMBER`: one of the enumerated values in + * SDL_TextureAccess, defaults to SDL_TEXTUREACCESS_STATIC + * - `SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER`: the width of the texture in + * pixels, required + * - `SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER`: the height of the texture in + * pixels, required + * - `SDL_PROP_TEXTURE_CREATE_SDR_WHITE_POINT_FLOAT`: for HDR10 and floating + * point textures, this defines the value of 100% diffuse white, with higher + * values being displayed in the High Dynamic Range headroom. This defaults + * to 100 for HDR10 textures and 1.0 for floating point textures. + * - `SDL_PROP_TEXTURE_CREATE_HDR_HEADROOM_FLOAT`: for HDR10 and floating + * point textures, this defines the maximum dynamic range used by the + * content, in terms of the SDR white point. This would be equivalent to + * maxCLL / SDL_PROP_TEXTURE_CREATE_SDR_WHITE_POINT_FLOAT for HDR10 content. + * If this is defined, any values outside the range supported by the display + * will be scaled into the available HDR headroom, otherwise they are + * clipped. + * + * With the direct3d11 renderer: + * + * - `SDL_PROP_TEXTURE_CREATE_D3D11_TEXTURE_POINTER`: the ID3D11Texture2D + * associated with the texture, if you want to wrap an existing texture. + * - `SDL_PROP_TEXTURE_CREATE_D3D11_TEXTURE_U_POINTER`: the ID3D11Texture2D + * associated with the U plane of a YUV texture, if you want to wrap an + * existing texture. + * - `SDL_PROP_TEXTURE_CREATE_D3D11_TEXTURE_V_POINTER`: the ID3D11Texture2D + * associated with the V plane of a YUV texture, if you want to wrap an + * existing texture. + * + * With the direct3d12 renderer: + * + * - `SDL_PROP_TEXTURE_CREATE_D3D12_TEXTURE_POINTER`: the ID3D12Resource + * associated with the texture, if you want to wrap an existing texture. + * - `SDL_PROP_TEXTURE_CREATE_D3D12_TEXTURE_U_POINTER`: the ID3D12Resource + * associated with the U plane of a YUV texture, if you want to wrap an + * existing texture. + * - `SDL_PROP_TEXTURE_CREATE_D3D12_TEXTURE_V_POINTER`: the ID3D12Resource + * associated with the V plane of a YUV texture, if you want to wrap an + * existing texture. + * + * With the metal renderer: + * + * - `SDL_PROP_TEXTURE_CREATE_METAL_PIXELBUFFER_POINTER`: the CVPixelBufferRef + * associated with the texture, if you want to create a texture from an + * existing pixel buffer. + * + * With the opengl renderer: + * + * - `SDL_PROP_TEXTURE_CREATE_OPENGL_TEXTURE_NUMBER`: the GLuint texture + * associated with the texture, if you want to wrap an existing texture. + * - `SDL_PROP_TEXTURE_CREATE_OPENGL_TEXTURE_UV_NUMBER`: the GLuint texture + * associated with the UV plane of an NV12 texture, if you want to wrap an + * existing texture. + * - `SDL_PROP_TEXTURE_CREATE_OPENGL_TEXTURE_U_NUMBER`: the GLuint texture + * associated with the U plane of a YUV texture, if you want to wrap an + * existing texture. + * - `SDL_PROP_TEXTURE_CREATE_OPENGL_TEXTURE_V_NUMBER`: the GLuint texture + * associated with the V plane of a YUV texture, if you want to wrap an + * existing texture. + * + * With the opengles2 renderer: + * + * - `SDL_PROP_TEXTURE_CREATE_OPENGLES2_TEXTURE_NUMBER`: the GLuint texture + * associated with the texture, if you want to wrap an existing texture. + * - `SDL_PROP_TEXTURE_CREATE_OPENGLES2_TEXTURE_NUMBER`: the GLuint texture + * associated with the texture, if you want to wrap an existing texture. + * - `SDL_PROP_TEXTURE_CREATE_OPENGLES2_TEXTURE_UV_NUMBER`: the GLuint texture + * associated with the UV plane of an NV12 texture, if you want to wrap an + * existing texture. + * - `SDL_PROP_TEXTURE_CREATE_OPENGLES2_TEXTURE_U_NUMBER`: the GLuint texture + * associated with the U plane of a YUV texture, if you want to wrap an + * existing texture. + * - `SDL_PROP_TEXTURE_CREATE_OPENGLES2_TEXTURE_V_NUMBER`: the GLuint texture + * associated with the V plane of a YUV texture, if you want to wrap an + * existing texture. + * + * With the vulkan renderer: + * + * - `SDL_PROP_TEXTURE_CREATE_VULKAN_TEXTURE_NUMBER`: the VkImage with layout + * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL associated with the texture, if + * you want to wrap an existing texture. + * + * \param renderer the rendering context. + * \param props the properties to use. + * \returns the created texture or NULL on failure; call SDL_GetError() for + * more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProperties + * \sa SDL_CreateTexture + * \sa SDL_CreateTextureFromSurface + * \sa SDL_DestroyTexture + * \sa SDL_GetTextureSize + * \sa SDL_UpdateTexture + */ +extern SDL_DECLSPEC SDL_Texture * SDLCALL SDL_CreateTextureWithProperties(SDL_Renderer *renderer, SDL_PropertiesID props); + +#define SDL_PROP_TEXTURE_CREATE_COLORSPACE_NUMBER "SDL.texture.create.colorspace" +#define SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER "SDL.texture.create.format" +#define SDL_PROP_TEXTURE_CREATE_ACCESS_NUMBER "SDL.texture.create.access" +#define SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER "SDL.texture.create.width" +#define SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER "SDL.texture.create.height" +#define SDL_PROP_TEXTURE_CREATE_SDR_WHITE_POINT_FLOAT "SDL.texture.create.SDR_white_point" +#define SDL_PROP_TEXTURE_CREATE_HDR_HEADROOM_FLOAT "SDL.texture.create.HDR_headroom" +#define SDL_PROP_TEXTURE_CREATE_D3D11_TEXTURE_POINTER "SDL.texture.create.d3d11.texture" +#define SDL_PROP_TEXTURE_CREATE_D3D11_TEXTURE_U_POINTER "SDL.texture.create.d3d11.texture_u" +#define SDL_PROP_TEXTURE_CREATE_D3D11_TEXTURE_V_POINTER "SDL.texture.create.d3d11.texture_v" +#define SDL_PROP_TEXTURE_CREATE_D3D12_TEXTURE_POINTER "SDL.texture.create.d3d12.texture" +#define SDL_PROP_TEXTURE_CREATE_D3D12_TEXTURE_U_POINTER "SDL.texture.create.d3d12.texture_u" +#define SDL_PROP_TEXTURE_CREATE_D3D12_TEXTURE_V_POINTER "SDL.texture.create.d3d12.texture_v" +#define SDL_PROP_TEXTURE_CREATE_METAL_PIXELBUFFER_POINTER "SDL.texture.create.metal.pixelbuffer" +#define SDL_PROP_TEXTURE_CREATE_OPENGL_TEXTURE_NUMBER "SDL.texture.create.opengl.texture" +#define SDL_PROP_TEXTURE_CREATE_OPENGL_TEXTURE_UV_NUMBER "SDL.texture.create.opengl.texture_uv" +#define SDL_PROP_TEXTURE_CREATE_OPENGL_TEXTURE_U_NUMBER "SDL.texture.create.opengl.texture_u" +#define SDL_PROP_TEXTURE_CREATE_OPENGL_TEXTURE_V_NUMBER "SDL.texture.create.opengl.texture_v" +#define SDL_PROP_TEXTURE_CREATE_OPENGLES2_TEXTURE_NUMBER "SDL.texture.create.opengles2.texture" +#define SDL_PROP_TEXTURE_CREATE_OPENGLES2_TEXTURE_UV_NUMBER "SDL.texture.create.opengles2.texture_uv" +#define SDL_PROP_TEXTURE_CREATE_OPENGLES2_TEXTURE_U_NUMBER "SDL.texture.create.opengles2.texture_u" +#define SDL_PROP_TEXTURE_CREATE_OPENGLES2_TEXTURE_V_NUMBER "SDL.texture.create.opengles2.texture_v" +#define SDL_PROP_TEXTURE_CREATE_VULKAN_TEXTURE_NUMBER "SDL.texture.create.vulkan.texture" + +/** + * Get the properties associated with a texture. + * + * The following read-only properties are provided by SDL: + * + * - `SDL_PROP_TEXTURE_COLORSPACE_NUMBER`: an SDL_Colorspace value describing + * the texture colorspace. + * - `SDL_PROP_TEXTURE_FORMAT_NUMBER`: one of the enumerated values in + * SDL_PixelFormat. + * - `SDL_PROP_TEXTURE_ACCESS_NUMBER`: one of the enumerated values in + * SDL_TextureAccess. + * - `SDL_PROP_TEXTURE_WIDTH_NUMBER`: the width of the texture in pixels. + * - `SDL_PROP_TEXTURE_HEIGHT_NUMBER`: the height of the texture in pixels. + * - `SDL_PROP_TEXTURE_SDR_WHITE_POINT_FLOAT`: for HDR10 and floating point + * textures, this defines the value of 100% diffuse white, with higher + * values being displayed in the High Dynamic Range headroom. This defaults + * to 100 for HDR10 textures and 1.0 for other textures. + * - `SDL_PROP_TEXTURE_HDR_HEADROOM_FLOAT`: for HDR10 and floating point + * textures, this defines the maximum dynamic range used by the content, in + * terms of the SDR white point. If this is defined, any values outside the + * range supported by the display will be scaled into the available HDR + * headroom, otherwise they are clipped. This defaults to 1.0 for SDR + * textures, 4.0 for HDR10 textures, and no default for floating point + * textures. + * + * With the direct3d11 renderer: + * + * - `SDL_PROP_TEXTURE_D3D11_TEXTURE_POINTER`: the ID3D11Texture2D associated + * with the texture + * - `SDL_PROP_TEXTURE_D3D11_TEXTURE_U_POINTER`: the ID3D11Texture2D + * associated with the U plane of a YUV texture + * - `SDL_PROP_TEXTURE_D3D11_TEXTURE_V_POINTER`: the ID3D11Texture2D + * associated with the V plane of a YUV texture + * + * With the direct3d12 renderer: + * + * - `SDL_PROP_TEXTURE_D3D12_TEXTURE_POINTER`: the ID3D12Resource associated + * with the texture + * - `SDL_PROP_TEXTURE_D3D12_TEXTURE_U_POINTER`: the ID3D12Resource associated + * with the U plane of a YUV texture + * - `SDL_PROP_TEXTURE_D3D12_TEXTURE_V_POINTER`: the ID3D12Resource associated + * with the V plane of a YUV texture + * + * With the vulkan renderer: + * + * - `SDL_PROP_TEXTURE_VULKAN_TEXTURE_NUMBER`: the VkImage associated with the + * texture + * + * With the opengl renderer: + * + * - `SDL_PROP_TEXTURE_OPENGL_TEXTURE_NUMBER`: the GLuint texture associated + * with the texture + * - `SDL_PROP_TEXTURE_OPENGL_TEXTURE_UV_NUMBER`: the GLuint texture + * associated with the UV plane of an NV12 texture + * - `SDL_PROP_TEXTURE_OPENGL_TEXTURE_U_NUMBER`: the GLuint texture associated + * with the U plane of a YUV texture + * - `SDL_PROP_TEXTURE_OPENGL_TEXTURE_V_NUMBER`: the GLuint texture associated + * with the V plane of a YUV texture + * - `SDL_PROP_TEXTURE_OPENGL_TEXTURE_TARGET_NUMBER`: the GLenum for the + * texture target (`GL_TEXTURE_2D`, `GL_TEXTURE_RECTANGLE_ARB`, etc) + * - `SDL_PROP_TEXTURE_OPENGL_TEX_W_FLOAT`: the texture coordinate width of + * the texture (0.0 - 1.0) + * - `SDL_PROP_TEXTURE_OPENGL_TEX_H_FLOAT`: the texture coordinate height of + * the texture (0.0 - 1.0) + * + * With the opengles2 renderer: + * + * - `SDL_PROP_TEXTURE_OPENGLES2_TEXTURE_NUMBER`: the GLuint texture + * associated with the texture + * - `SDL_PROP_TEXTURE_OPENGLES2_TEXTURE_UV_NUMBER`: the GLuint texture + * associated with the UV plane of an NV12 texture + * - `SDL_PROP_TEXTURE_OPENGLES2_TEXTURE_U_NUMBER`: the GLuint texture + * associated with the U plane of a YUV texture + * - `SDL_PROP_TEXTURE_OPENGLES2_TEXTURE_V_NUMBER`: the GLuint texture + * associated with the V plane of a YUV texture + * - `SDL_PROP_TEXTURE_OPENGLES2_TEXTURE_TARGET_NUMBER`: the GLenum for the + * texture target (`GL_TEXTURE_2D`, `GL_TEXTURE_EXTERNAL_OES`, etc) + * + * \param texture the texture to query. + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetTextureProperties(SDL_Texture *texture); + +#define SDL_PROP_TEXTURE_COLORSPACE_NUMBER "SDL.texture.colorspace" +#define SDL_PROP_TEXTURE_FORMAT_NUMBER "SDL.texture.format" +#define SDL_PROP_TEXTURE_ACCESS_NUMBER "SDL.texture.access" +#define SDL_PROP_TEXTURE_WIDTH_NUMBER "SDL.texture.width" +#define SDL_PROP_TEXTURE_HEIGHT_NUMBER "SDL.texture.height" +#define SDL_PROP_TEXTURE_SDR_WHITE_POINT_FLOAT "SDL.texture.SDR_white_point" +#define SDL_PROP_TEXTURE_HDR_HEADROOM_FLOAT "SDL.texture.HDR_headroom" +#define SDL_PROP_TEXTURE_D3D11_TEXTURE_POINTER "SDL.texture.d3d11.texture" +#define SDL_PROP_TEXTURE_D3D11_TEXTURE_U_POINTER "SDL.texture.d3d11.texture_u" +#define SDL_PROP_TEXTURE_D3D11_TEXTURE_V_POINTER "SDL.texture.d3d11.texture_v" +#define SDL_PROP_TEXTURE_D3D12_TEXTURE_POINTER "SDL.texture.d3d12.texture" +#define SDL_PROP_TEXTURE_D3D12_TEXTURE_U_POINTER "SDL.texture.d3d12.texture_u" +#define SDL_PROP_TEXTURE_D3D12_TEXTURE_V_POINTER "SDL.texture.d3d12.texture_v" +#define SDL_PROP_TEXTURE_OPENGL_TEXTURE_NUMBER "SDL.texture.opengl.texture" +#define SDL_PROP_TEXTURE_OPENGL_TEXTURE_UV_NUMBER "SDL.texture.opengl.texture_uv" +#define SDL_PROP_TEXTURE_OPENGL_TEXTURE_U_NUMBER "SDL.texture.opengl.texture_u" +#define SDL_PROP_TEXTURE_OPENGL_TEXTURE_V_NUMBER "SDL.texture.opengl.texture_v" +#define SDL_PROP_TEXTURE_OPENGL_TEXTURE_TARGET_NUMBER "SDL.texture.opengl.target" +#define SDL_PROP_TEXTURE_OPENGL_TEX_W_FLOAT "SDL.texture.opengl.tex_w" +#define SDL_PROP_TEXTURE_OPENGL_TEX_H_FLOAT "SDL.texture.opengl.tex_h" +#define SDL_PROP_TEXTURE_OPENGLES2_TEXTURE_NUMBER "SDL.texture.opengles2.texture" +#define SDL_PROP_TEXTURE_OPENGLES2_TEXTURE_UV_NUMBER "SDL.texture.opengles2.texture_uv" +#define SDL_PROP_TEXTURE_OPENGLES2_TEXTURE_U_NUMBER "SDL.texture.opengles2.texture_u" +#define SDL_PROP_TEXTURE_OPENGLES2_TEXTURE_V_NUMBER "SDL.texture.opengles2.texture_v" +#define SDL_PROP_TEXTURE_OPENGLES2_TEXTURE_TARGET_NUMBER "SDL.texture.opengles2.target" +#define SDL_PROP_TEXTURE_VULKAN_TEXTURE_NUMBER "SDL.texture.vulkan.texture" + +/** + * Get the renderer that created an SDL_Texture. + * + * \param texture the texture to query. + * \returns a pointer to the SDL_Renderer that created the texture, or NULL on + * failure; call SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Renderer * SDLCALL SDL_GetRendererFromTexture(SDL_Texture *texture); + +/** + * Get the size of a texture, as floating point values. + * + * \param texture the texture to query. + * \param w a pointer filled in with the width of the texture in pixels. This + * argument can be NULL if you don't need this information. + * \param h a pointer filled in with the height of the texture in pixels. This + * argument can be NULL if you don't need this information. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetTextureSize(SDL_Texture *texture, float *w, float *h); + +/** + * Set an additional color value multiplied into render copy operations. + * + * When this texture is rendered, during the copy operation each source color + * channel is modulated by the appropriate color value according to the + * following formula: + * + * `srcC = srcC * (color / 255)` + * + * Color modulation is not always supported by the renderer; it will return + * false if color modulation is not supported. + * + * \param texture the texture to update. + * \param r the red color value multiplied into copy operations. + * \param g the green color value multiplied into copy operations. + * \param b the blue color value multiplied into copy operations. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextureColorMod + * \sa SDL_SetTextureAlphaMod + * \sa SDL_SetTextureColorModFloat + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetTextureColorMod(SDL_Texture *texture, Uint8 r, Uint8 g, Uint8 b); + + +/** + * Set an additional color value multiplied into render copy operations. + * + * When this texture is rendered, during the copy operation each source color + * channel is modulated by the appropriate color value according to the + * following formula: + * + * `srcC = srcC * color` + * + * Color modulation is not always supported by the renderer; it will return + * false if color modulation is not supported. + * + * \param texture the texture to update. + * \param r the red color value multiplied into copy operations. + * \param g the green color value multiplied into copy operations. + * \param b the blue color value multiplied into copy operations. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextureColorModFloat + * \sa SDL_SetTextureAlphaModFloat + * \sa SDL_SetTextureColorMod + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetTextureColorModFloat(SDL_Texture *texture, float r, float g, float b); + + +/** + * Get the additional color value multiplied into render copy operations. + * + * \param texture the texture to query. + * \param r a pointer filled in with the current red color value. + * \param g a pointer filled in with the current green color value. + * \param b a pointer filled in with the current blue color value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextureAlphaMod + * \sa SDL_GetTextureColorModFloat + * \sa SDL_SetTextureColorMod + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetTextureColorMod(SDL_Texture *texture, Uint8 *r, Uint8 *g, Uint8 *b); + +/** + * Get the additional color value multiplied into render copy operations. + * + * \param texture the texture to query. + * \param r a pointer filled in with the current red color value. + * \param g a pointer filled in with the current green color value. + * \param b a pointer filled in with the current blue color value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextureAlphaModFloat + * \sa SDL_GetTextureColorMod + * \sa SDL_SetTextureColorModFloat + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetTextureColorModFloat(SDL_Texture *texture, float *r, float *g, float *b); + +/** + * Set an additional alpha value multiplied into render copy operations. + * + * When this texture is rendered, during the copy operation the source alpha + * value is modulated by this alpha value according to the following formula: + * + * `srcA = srcA * (alpha / 255)` + * + * Alpha modulation is not always supported by the renderer; it will return + * false if alpha modulation is not supported. + * + * \param texture the texture to update. + * \param alpha the source alpha value multiplied into copy operations. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextureAlphaMod + * \sa SDL_SetTextureAlphaModFloat + * \sa SDL_SetTextureColorMod + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetTextureAlphaMod(SDL_Texture *texture, Uint8 alpha); + +/** + * Set an additional alpha value multiplied into render copy operations. + * + * When this texture is rendered, during the copy operation the source alpha + * value is modulated by this alpha value according to the following formula: + * + * `srcA = srcA * alpha` + * + * Alpha modulation is not always supported by the renderer; it will return + * false if alpha modulation is not supported. + * + * \param texture the texture to update. + * \param alpha the source alpha value multiplied into copy operations. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextureAlphaModFloat + * \sa SDL_SetTextureAlphaMod + * \sa SDL_SetTextureColorModFloat + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetTextureAlphaModFloat(SDL_Texture *texture, float alpha); + +/** + * Get the additional alpha value multiplied into render copy operations. + * + * \param texture the texture to query. + * \param alpha a pointer filled in with the current alpha value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextureAlphaModFloat + * \sa SDL_GetTextureColorMod + * \sa SDL_SetTextureAlphaMod + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetTextureAlphaMod(SDL_Texture *texture, Uint8 *alpha); + +/** + * Get the additional alpha value multiplied into render copy operations. + * + * \param texture the texture to query. + * \param alpha a pointer filled in with the current alpha value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextureAlphaMod + * \sa SDL_GetTextureColorModFloat + * \sa SDL_SetTextureAlphaModFloat + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetTextureAlphaModFloat(SDL_Texture *texture, float *alpha); + +/** + * Set the blend mode for a texture, used by SDL_RenderTexture(). + * + * If the blend mode is not supported, the closest supported mode is chosen + * and this function returns false. + * + * \param texture the texture to update. + * \param blendMode the SDL_BlendMode to use for texture blending. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextureBlendMode + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetTextureBlendMode(SDL_Texture *texture, SDL_BlendMode blendMode); + +/** + * Get the blend mode used for texture copy operations. + * + * \param texture the texture to query. + * \param blendMode a pointer filled in with the current SDL_BlendMode. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetTextureBlendMode + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetTextureBlendMode(SDL_Texture *texture, SDL_BlendMode *blendMode); + +/** + * Set the scale mode used for texture scale operations. + * + * The default texture scale mode is SDL_SCALEMODE_LINEAR. + * + * If the scale mode is not supported, the closest supported mode is chosen. + * + * \param texture the texture to update. + * \param scaleMode the SDL_ScaleMode to use for texture scaling. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTextureScaleMode + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetTextureScaleMode(SDL_Texture *texture, SDL_ScaleMode scaleMode); + +/** + * Get the scale mode used for texture scale operations. + * + * \param texture the texture to query. + * \param scaleMode a pointer filled in with the current scale mode. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetTextureScaleMode + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetTextureScaleMode(SDL_Texture *texture, SDL_ScaleMode *scaleMode); + +/** + * Update the given texture rectangle with new pixel data. + * + * The pixel data must be in the pixel format of the texture, which can be + * queried using the SDL_PROP_TEXTURE_FORMAT_NUMBER property. + * + * This is a fairly slow function, intended for use with static textures that + * do not change often. + * + * If the texture is intended to be updated often, it is preferred to create + * the texture as streaming and use the locking functions referenced below. + * While this function will work with streaming textures, for optimization + * reasons you may not get the pixels back if you lock the texture afterward. + * + * \param texture the texture to update. + * \param rect an SDL_Rect structure representing the area to update, or NULL + * to update the entire texture. + * \param pixels the raw pixel data in the format of the texture. + * \param pitch the number of bytes in a row of pixel data, including padding + * between lines. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockTexture + * \sa SDL_UnlockTexture + * \sa SDL_UpdateNVTexture + * \sa SDL_UpdateYUVTexture + */ +extern SDL_DECLSPEC bool SDLCALL SDL_UpdateTexture(SDL_Texture *texture, const SDL_Rect *rect, const void *pixels, int pitch); + +/** + * Update a rectangle within a planar YV12 or IYUV texture with new pixel + * data. + * + * You can use SDL_UpdateTexture() as long as your pixel data is a contiguous + * block of Y and U/V planes in the proper order, but this function is + * available if your pixel data is not contiguous. + * + * \param texture the texture to update. + * \param rect a pointer to the rectangle of pixels to update, or NULL to + * update the entire texture. + * \param Yplane the raw pixel data for the Y plane. + * \param Ypitch the number of bytes between rows of pixel data for the Y + * plane. + * \param Uplane the raw pixel data for the U plane. + * \param Upitch the number of bytes between rows of pixel data for the U + * plane. + * \param Vplane the raw pixel data for the V plane. + * \param Vpitch the number of bytes between rows of pixel data for the V + * plane. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_UpdateNVTexture + * \sa SDL_UpdateTexture + */ +extern SDL_DECLSPEC bool SDLCALL SDL_UpdateYUVTexture(SDL_Texture *texture, + const SDL_Rect *rect, + const Uint8 *Yplane, int Ypitch, + const Uint8 *Uplane, int Upitch, + const Uint8 *Vplane, int Vpitch); + +/** + * Update a rectangle within a planar NV12 or NV21 texture with new pixels. + * + * You can use SDL_UpdateTexture() as long as your pixel data is a contiguous + * block of NV12/21 planes in the proper order, but this function is available + * if your pixel data is not contiguous. + * + * \param texture the texture to update. + * \param rect a pointer to the rectangle of pixels to update, or NULL to + * update the entire texture. + * \param Yplane the raw pixel data for the Y plane. + * \param Ypitch the number of bytes between rows of pixel data for the Y + * plane. + * \param UVplane the raw pixel data for the UV plane. + * \param UVpitch the number of bytes between rows of pixel data for the UV + * plane. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_UpdateTexture + * \sa SDL_UpdateYUVTexture + */ +extern SDL_DECLSPEC bool SDLCALL SDL_UpdateNVTexture(SDL_Texture *texture, + const SDL_Rect *rect, + const Uint8 *Yplane, int Ypitch, + const Uint8 *UVplane, int UVpitch); + +/** + * Lock a portion of the texture for **write-only** pixel access. + * + * As an optimization, the pixels made available for editing don't necessarily + * contain the old texture data. This is a write-only operation, and if you + * need to keep a copy of the texture data you should do that at the + * application level. + * + * You must use SDL_UnlockTexture() to unlock the pixels and apply any + * changes. + * + * \param texture the texture to lock for access, which was created with + * `SDL_TEXTUREACCESS_STREAMING`. + * \param rect an SDL_Rect structure representing the area to lock for access; + * NULL to lock the entire texture. + * \param pixels this is filled in with a pointer to the locked pixels, + * appropriately offset by the locked area. + * \param pitch this is filled in with the pitch of the locked pixels; the + * pitch is the length of one row in bytes. + * \returns true on success or false if the texture is not valid or was not + * created with `SDL_TEXTUREACCESS_STREAMING`; call SDL_GetError() + * for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockTextureToSurface + * \sa SDL_UnlockTexture + */ +extern SDL_DECLSPEC bool SDLCALL SDL_LockTexture(SDL_Texture *texture, + const SDL_Rect *rect, + void **pixels, int *pitch); + +/** + * Lock a portion of the texture for **write-only** pixel access, and expose + * it as a SDL surface. + * + * Besides providing an SDL_Surface instead of raw pixel data, this function + * operates like SDL_LockTexture. + * + * As an optimization, the pixels made available for editing don't necessarily + * contain the old texture data. This is a write-only operation, and if you + * need to keep a copy of the texture data you should do that at the + * application level. + * + * You must use SDL_UnlockTexture() to unlock the pixels and apply any + * changes. + * + * The returned surface is freed internally after calling SDL_UnlockTexture() + * or SDL_DestroyTexture(). The caller should not free it. + * + * \param texture the texture to lock for access, which must be created with + * `SDL_TEXTUREACCESS_STREAMING`. + * \param rect a pointer to the rectangle to lock for access. If the rect is + * NULL, the entire texture will be locked. + * \param surface a pointer to an SDL surface of size **rect**. Don't assume + * any specific pixel content. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockTexture + * \sa SDL_UnlockTexture + */ +extern SDL_DECLSPEC bool SDLCALL SDL_LockTextureToSurface(SDL_Texture *texture, const SDL_Rect *rect, SDL_Surface **surface); + +/** + * Unlock a texture, uploading the changes to video memory, if needed. + * + * **Warning**: Please note that SDL_LockTexture() is intended to be + * write-only; it will not guarantee the previous contents of the texture will + * be provided. You must fully initialize any area of a texture that you lock + * before unlocking it, as the pixels might otherwise be uninitialized memory. + * + * Which is to say: locking and immediately unlocking a texture can result in + * corrupted textures, depending on the renderer in use. + * + * \param texture a texture locked by SDL_LockTexture(). + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockTexture + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnlockTexture(SDL_Texture *texture); + +/** + * Set a texture as the current rendering target. + * + * The default render target is the window for which the renderer was created. + * To stop rendering to a texture and render to the window again, call this + * function with a NULL `texture`. + * + * Viewport, cliprect, scale, and logical presentation are unique to each + * render target. Get and set functions for these states apply to the current + * render target set by this function, and those states persist on each target + * when the current render target changes. + * + * \param renderer the rendering context. + * \param texture the targeted texture, which must be created with the + * `SDL_TEXTUREACCESS_TARGET` flag, or NULL to render to the + * window instead of a texture. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderTarget + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderTarget(SDL_Renderer *renderer, SDL_Texture *texture); + +/** + * Get the current render target. + * + * The default render target is the window for which the renderer was created, + * and is reported a NULL here. + * + * \param renderer the rendering context. + * \returns the current render target or NULL for the default render target. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderTarget + */ +extern SDL_DECLSPEC SDL_Texture * SDLCALL SDL_GetRenderTarget(SDL_Renderer *renderer); + +/** + * Set a device-independent resolution and presentation mode for rendering. + * + * This function sets the width and height of the logical rendering output. + * The renderer will act as if the current render target is always the + * requested dimensions, scaling to the actual resolution as necessary. + * + * This can be useful for games that expect a fixed size, but would like to + * scale the output to whatever is available, regardless of how a user resizes + * a window, or if the display is high DPI. + * + * Logical presentation can be used with both render target textures and the + * renderer's window; the state is unique to each render target, and this + * function sets the state for the current render target. It might be useful + * to draw to a texture that matches the window dimensions with logical + * presentation enabled, and then draw that texture across the entire window + * with logical presentation disabled. Be careful not to render both with + * logical presentation enabled, however, as this could produce + * double-letterboxing, etc. + * + * You can disable logical coordinates by setting the mode to + * SDL_LOGICAL_PRESENTATION_DISABLED, and in that case you get the full pixel + * resolution of the render target; it is safe to toggle logical presentation + * during the rendering of a frame: perhaps most of the rendering is done to + * specific dimensions but to make fonts look sharp, the app turns off logical + * presentation while drawing text, for example. + * + * For the renderer's window, letterboxing is drawn into the framebuffer if + * logical presentation is enabled during SDL_RenderPresent; be sure to + * reenable it before presenting if you were toggling it, otherwise the + * letterbox areas might have artifacts from previous frames (or artifacts + * from external overlays, etc). Letterboxing is never drawn into texture + * render targets; be sure to call SDL_RenderClear() before drawing into the + * texture so the letterboxing areas are cleared, if appropriate. + * + * You can convert coordinates in an event into rendering coordinates using + * SDL_ConvertEventToRenderCoordinates(). + * + * \param renderer the rendering context. + * \param w the width of the logical resolution. + * \param h the height of the logical resolution. + * \param mode the presentation mode used. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ConvertEventToRenderCoordinates + * \sa SDL_GetRenderLogicalPresentation + * \sa SDL_GetRenderLogicalPresentationRect + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderLogicalPresentation(SDL_Renderer *renderer, int w, int h, SDL_RendererLogicalPresentation mode); + +/** + * Get device independent resolution and presentation mode for rendering. + * + * This function gets the width and height of the logical rendering output, or + * the output size in pixels if a logical resolution is not enabled. + * + * Each render target has its own logical presentation state. This function + * gets the state for the current render target. + * + * \param renderer the rendering context. + * \param w an int to be filled with the width. + * \param h an int to be filled with the height. + * \param mode the presentation mode used. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderLogicalPresentation + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderLogicalPresentation(SDL_Renderer *renderer, int *w, int *h, SDL_RendererLogicalPresentation *mode); + +/** + * Get the final presentation rectangle for rendering. + * + * This function returns the calculated rectangle used for logical + * presentation, based on the presentation mode and output size. If logical + * presentation is disabled, it will fill the rectangle with the output size, + * in pixels. + * + * Each render target has its own logical presentation state. This function + * gets the rectangle for the current render target. + * + * \param renderer the rendering context. + * \param rect a pointer filled in with the final presentation rectangle, may + * be NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderLogicalPresentation + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderLogicalPresentationRect(SDL_Renderer *renderer, SDL_FRect *rect); + +/** + * Get a point in render coordinates when given a point in window coordinates. + * + * This takes into account several states: + * + * - The window dimensions. + * - The logical presentation settings (SDL_SetRenderLogicalPresentation) + * - The scale (SDL_SetRenderScale) + * - The viewport (SDL_SetRenderViewport) + * + * \param renderer the rendering context. + * \param window_x the x coordinate in window coordinates. + * \param window_y the y coordinate in window coordinates. + * \param x a pointer filled with the x coordinate in render coordinates. + * \param y a pointer filled with the y coordinate in render coordinates. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderLogicalPresentation + * \sa SDL_SetRenderScale + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderCoordinatesFromWindow(SDL_Renderer *renderer, float window_x, float window_y, float *x, float *y); + +/** + * Get a point in window coordinates when given a point in render coordinates. + * + * This takes into account several states: + * + * - The window dimensions. + * - The logical presentation settings (SDL_SetRenderLogicalPresentation) + * - The scale (SDL_SetRenderScale) + * - The viewport (SDL_SetRenderViewport) + * + * \param renderer the rendering context. + * \param x the x coordinate in render coordinates. + * \param y the y coordinate in render coordinates. + * \param window_x a pointer filled with the x coordinate in window + * coordinates. + * \param window_y a pointer filled with the y coordinate in window + * coordinates. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderLogicalPresentation + * \sa SDL_SetRenderScale + * \sa SDL_SetRenderViewport + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderCoordinatesToWindow(SDL_Renderer *renderer, float x, float y, float *window_x, float *window_y); + +/** + * Convert the coordinates in an event to render coordinates. + * + * This takes into account several states: + * + * - The window dimensions. + * - The logical presentation settings (SDL_SetRenderLogicalPresentation) + * - The scale (SDL_SetRenderScale) + * - The viewport (SDL_SetRenderViewport) + * + * Various event types are converted with this function: mouse, touch, pen, + * etc. + * + * Touch coordinates are converted from normalized coordinates in the window + * to non-normalized rendering coordinates. + * + * Relative mouse coordinates (xrel and yrel event fields) are _also_ + * converted. Applications that do not want these fields converted should use + * SDL_RenderCoordinatesFromWindow() on the specific event fields instead of + * converting the entire event structure. + * + * Once converted, coordinates may be outside the rendering area. + * + * \param renderer the rendering context. + * \param event the event to modify. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderCoordinatesFromWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ConvertEventToRenderCoordinates(SDL_Renderer *renderer, SDL_Event *event); + +/** + * Set the drawing area for rendering on the current target. + * + * Drawing will clip to this area (separately from any clipping done with + * SDL_SetRenderClipRect), and the top left of the area will become coordinate + * (0, 0) for future drawing commands. + * + * The area's width and height must be >= 0. + * + * Each render target has its own viewport. This function sets the viewport + * for the current render target. + * + * \param renderer the rendering context. + * \param rect the SDL_Rect structure representing the drawing area, or NULL + * to set the viewport to the entire target. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderViewport + * \sa SDL_RenderViewportSet + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderViewport(SDL_Renderer *renderer, const SDL_Rect *rect); + +/** + * Get the drawing area for the current target. + * + * Each render target has its own viewport. This function gets the viewport + * for the current render target. + * + * \param renderer the rendering context. + * \param rect an SDL_Rect structure filled in with the current drawing area. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderViewportSet + * \sa SDL_SetRenderViewport + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderViewport(SDL_Renderer *renderer, SDL_Rect *rect); + +/** + * Return whether an explicit rectangle was set as the viewport. + * + * This is useful if you're saving and restoring the viewport and want to know + * whether you should restore a specific rectangle or NULL. + * + * Each render target has its own viewport. This function checks the viewport + * for the current render target. + * + * \param renderer the rendering context. + * \returns true if the viewport was set to a specific rectangle, or false if + * it was set to NULL (the entire target). + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderViewport + * \sa SDL_SetRenderViewport + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderViewportSet(SDL_Renderer *renderer); + +/** + * Get the safe area for rendering within the current viewport. + * + * Some devices have portions of the screen which are partially obscured or + * not interactive, possibly due to on-screen controls, curved edges, camera + * notches, TV overscan, etc. This function provides the area of the current + * viewport which is safe to have interactible content. You should continue + * rendering into the rest of the render target, but it should not contain + * visually important or interactible content. + * + * \param renderer the rendering context. + * \param rect a pointer filled in with the area that is safe for interactive + * content. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderSafeArea(SDL_Renderer *renderer, SDL_Rect *rect); + +/** + * Set the clip rectangle for rendering on the specified target. + * + * Each render target has its own clip rectangle. This function sets the + * cliprect for the current render target. + * + * \param renderer the rendering context. + * \param rect an SDL_Rect structure representing the clip area, relative to + * the viewport, or NULL to disable clipping. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderClipRect + * \sa SDL_RenderClipEnabled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderClipRect(SDL_Renderer *renderer, const SDL_Rect *rect); + +/** + * Get the clip rectangle for the current target. + * + * Each render target has its own clip rectangle. This function gets the + * cliprect for the current render target. + * + * \param renderer the rendering context. + * \param rect an SDL_Rect structure filled in with the current clipping area + * or an empty rectangle if clipping is disabled. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderClipEnabled + * \sa SDL_SetRenderClipRect + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderClipRect(SDL_Renderer *renderer, SDL_Rect *rect); + +/** + * Get whether clipping is enabled on the given render target. + * + * Each render target has its own clip rectangle. This function checks the + * cliprect for the current render target. + * + * \param renderer the rendering context. + * \returns true if clipping is enabled or false if not; call SDL_GetError() + * for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderClipRect + * \sa SDL_SetRenderClipRect + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderClipEnabled(SDL_Renderer *renderer); + +/** + * Set the drawing scale for rendering on the current target. + * + * The drawing coordinates are scaled by the x/y scaling factors before they + * are used by the renderer. This allows resolution independent drawing with a + * single coordinate system. + * + * If this results in scaling or subpixel drawing by the rendering backend, it + * will be handled using the appropriate quality hints. For best results use + * integer scaling factors. + * + * Each render target has its own scale. This function sets the scale for the + * current render target. + * + * \param renderer the rendering context. + * \param scaleX the horizontal scaling factor. + * \param scaleY the vertical scaling factor. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderScale + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderScale(SDL_Renderer *renderer, float scaleX, float scaleY); + +/** + * Get the drawing scale for the current target. + * + * Each render target has its own scale. This function gets the scale for the + * current render target. + * + * \param renderer the rendering context. + * \param scaleX a pointer filled in with the horizontal scaling factor. + * \param scaleY a pointer filled in with the vertical scaling factor. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderScale + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderScale(SDL_Renderer *renderer, float *scaleX, float *scaleY); + +/** + * Set the color used for drawing operations. + * + * Set the color for drawing or filling rectangles, lines, and points, and for + * SDL_RenderClear(). + * + * \param renderer the rendering context. + * \param r the red value used to draw on the rendering target. + * \param g the green value used to draw on the rendering target. + * \param b the blue value used to draw on the rendering target. + * \param a the alpha value used to draw on the rendering target; usually + * `SDL_ALPHA_OPAQUE` (255). Use SDL_SetRenderDrawBlendMode to + * specify how the alpha channel is used. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderDrawColor + * \sa SDL_SetRenderDrawColorFloat + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderDrawColor(SDL_Renderer *renderer, Uint8 r, Uint8 g, Uint8 b, Uint8 a); + +/** + * Set the color used for drawing operations (Rect, Line and Clear). + * + * Set the color for drawing or filling rectangles, lines, and points, and for + * SDL_RenderClear(). + * + * \param renderer the rendering context. + * \param r the red value used to draw on the rendering target. + * \param g the green value used to draw on the rendering target. + * \param b the blue value used to draw on the rendering target. + * \param a the alpha value used to draw on the rendering target. Use + * SDL_SetRenderDrawBlendMode to specify how the alpha channel is + * used. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderDrawColorFloat + * \sa SDL_SetRenderDrawColor + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderDrawColorFloat(SDL_Renderer *renderer, float r, float g, float b, float a); + +/** + * Get the color used for drawing operations (Rect, Line and Clear). + * + * \param renderer the rendering context. + * \param r a pointer filled in with the red value used to draw on the + * rendering target. + * \param g a pointer filled in with the green value used to draw on the + * rendering target. + * \param b a pointer filled in with the blue value used to draw on the + * rendering target. + * \param a a pointer filled in with the alpha value used to draw on the + * rendering target; usually `SDL_ALPHA_OPAQUE` (255). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderDrawColorFloat + * \sa SDL_SetRenderDrawColor + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderDrawColor(SDL_Renderer *renderer, Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a); + +/** + * Get the color used for drawing operations (Rect, Line and Clear). + * + * \param renderer the rendering context. + * \param r a pointer filled in with the red value used to draw on the + * rendering target. + * \param g a pointer filled in with the green value used to draw on the + * rendering target. + * \param b a pointer filled in with the blue value used to draw on the + * rendering target. + * \param a a pointer filled in with the alpha value used to draw on the + * rendering target. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderDrawColorFloat + * \sa SDL_GetRenderDrawColor + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderDrawColorFloat(SDL_Renderer *renderer, float *r, float *g, float *b, float *a); + +/** + * Set the color scale used for render operations. + * + * The color scale is an additional scale multiplied into the pixel color + * value while rendering. This can be used to adjust the brightness of colors + * during HDR rendering, or changing HDR video brightness when playing on an + * SDR display. + * + * The color scale does not affect the alpha channel, only the color + * brightness. + * + * \param renderer the rendering context. + * \param scale the color scale value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderColorScale + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderColorScale(SDL_Renderer *renderer, float scale); + +/** + * Get the color scale used for render operations. + * + * \param renderer the rendering context. + * \param scale a pointer filled in with the current color scale value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderColorScale + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderColorScale(SDL_Renderer *renderer, float *scale); + +/** + * Set the blend mode used for drawing operations (Fill and Line). + * + * If the blend mode is not supported, the closest supported mode is chosen. + * + * \param renderer the rendering context. + * \param blendMode the SDL_BlendMode to use for blending. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderDrawBlendMode + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderDrawBlendMode(SDL_Renderer *renderer, SDL_BlendMode blendMode); + +/** + * Get the blend mode used for drawing operations. + * + * \param renderer the rendering context. + * \param blendMode a pointer filled in with the current SDL_BlendMode. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderDrawBlendMode + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderDrawBlendMode(SDL_Renderer *renderer, SDL_BlendMode *blendMode); + +/** + * Clear the current rendering target with the drawing color. + * + * This function clears the entire rendering target, ignoring the viewport and + * the clip rectangle. Note, that clearing will also set/fill all pixels of + * the rendering target to current renderer draw color, so make sure to invoke + * SDL_SetRenderDrawColor() when needed. + * + * \param renderer the rendering context. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderDrawColor + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderClear(SDL_Renderer *renderer); + +/** + * Draw a point on the current rendering target at subpixel precision. + * + * \param renderer the renderer which should draw a point. + * \param x the x coordinate of the point. + * \param y the y coordinate of the point. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderPoints + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderPoint(SDL_Renderer *renderer, float x, float y); + +/** + * Draw multiple points on the current rendering target at subpixel precision. + * + * \param renderer the renderer which should draw multiple points. + * \param points the points to draw. + * \param count the number of points to draw. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderPoint + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderPoints(SDL_Renderer *renderer, const SDL_FPoint *points, int count); + +/** + * Draw a line on the current rendering target at subpixel precision. + * + * \param renderer the renderer which should draw a line. + * \param x1 the x coordinate of the start point. + * \param y1 the y coordinate of the start point. + * \param x2 the x coordinate of the end point. + * \param y2 the y coordinate of the end point. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderLines + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderLine(SDL_Renderer *renderer, float x1, float y1, float x2, float y2); + +/** + * Draw a series of connected lines on the current rendering target at + * subpixel precision. + * + * \param renderer the renderer which should draw multiple lines. + * \param points the points along the lines. + * \param count the number of points, drawing count-1 lines. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderLine + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderLines(SDL_Renderer *renderer, const SDL_FPoint *points, int count); + +/** + * Draw a rectangle on the current rendering target at subpixel precision. + * + * \param renderer the renderer which should draw a rectangle. + * \param rect a pointer to the destination rectangle, or NULL to outline the + * entire rendering target. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderRects + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderRect(SDL_Renderer *renderer, const SDL_FRect *rect); + +/** + * Draw some number of rectangles on the current rendering target at subpixel + * precision. + * + * \param renderer the renderer which should draw multiple rectangles. + * \param rects a pointer to an array of destination rectangles. + * \param count the number of rectangles. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderRect + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderRects(SDL_Renderer *renderer, const SDL_FRect *rects, int count); + +/** + * Fill a rectangle on the current rendering target with the drawing color at + * subpixel precision. + * + * \param renderer the renderer which should fill a rectangle. + * \param rect a pointer to the destination rectangle, or NULL for the entire + * rendering target. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderFillRects + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderFillRect(SDL_Renderer *renderer, const SDL_FRect *rect); + +/** + * Fill some number of rectangles on the current rendering target with the + * drawing color at subpixel precision. + * + * \param renderer the renderer which should fill multiple rectangles. + * \param rects a pointer to an array of destination rectangles. + * \param count the number of rectangles. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderFillRect + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderFillRects(SDL_Renderer *renderer, const SDL_FRect *rects, int count); + +/** + * Copy a portion of the texture to the current rendering target at subpixel + * precision. + * + * \param renderer the renderer which should copy parts of a texture. + * \param texture the source texture. + * \param srcrect a pointer to the source rectangle, or NULL for the entire + * texture. + * \param dstrect a pointer to the destination rectangle, or NULL for the + * entire rendering target. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderTextureRotated + * \sa SDL_RenderTextureTiled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderTexture(SDL_Renderer *renderer, SDL_Texture *texture, const SDL_FRect *srcrect, const SDL_FRect *dstrect); + +/** + * Copy a portion of the source texture to the current rendering target, with + * rotation and flipping, at subpixel precision. + * + * \param renderer the renderer which should copy parts of a texture. + * \param texture the source texture. + * \param srcrect a pointer to the source rectangle, or NULL for the entire + * texture. + * \param dstrect a pointer to the destination rectangle, or NULL for the + * entire rendering target. + * \param angle an angle in degrees that indicates the rotation that will be + * applied to dstrect, rotating it in a clockwise direction. + * \param center a pointer to a point indicating the point around which + * dstrect will be rotated (if NULL, rotation will be done + * around dstrect.w/2, dstrect.h/2). + * \param flip an SDL_FlipMode value stating which flipping actions should be + * performed on the texture. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderTexture + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderTextureRotated(SDL_Renderer *renderer, SDL_Texture *texture, + const SDL_FRect *srcrect, const SDL_FRect *dstrect, + double angle, const SDL_FPoint *center, + SDL_FlipMode flip); + +/** + * Copy a portion of the source texture to the current rendering target, with + * affine transform, at subpixel precision. + * + * \param renderer the renderer which should copy parts of a texture. + * \param texture the source texture. + * \param srcrect a pointer to the source rectangle, or NULL for the entire + * texture. + * \param origin a pointer to a point indicating where the top-left corner of + * srcrect should be mapped to, or NULL for the rendering + * target's origin. + * \param right a pointer to a point indicating where the top-right corner of + * srcrect should be mapped to, or NULL for the rendering + * target's top-right corner. + * \param down a pointer to a point indicating where the bottom-left corner of + * srcrect should be mapped to, or NULL for the rendering target's + * bottom-left corner. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety You may only call this function from the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderTexture + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderTextureAffine(SDL_Renderer *renderer, SDL_Texture *texture, + const SDL_FRect *srcrect, const SDL_FPoint *origin, + const SDL_FPoint *right, const SDL_FPoint *down); + +/** + * Tile a portion of the texture to the current rendering target at subpixel + * precision. + * + * The pixels in `srcrect` will be repeated as many times as needed to + * completely fill `dstrect`. + * + * \param renderer the renderer which should copy parts of a texture. + * \param texture the source texture. + * \param srcrect a pointer to the source rectangle, or NULL for the entire + * texture. + * \param scale the scale used to transform srcrect into the destination + * rectangle, e.g. a 32x32 texture with a scale of 2 would fill + * 64x64 tiles. + * \param dstrect a pointer to the destination rectangle, or NULL for the + * entire rendering target. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderTexture + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderTextureTiled(SDL_Renderer *renderer, SDL_Texture *texture, const SDL_FRect *srcrect, float scale, const SDL_FRect *dstrect); + +/** + * Perform a scaled copy using the 9-grid algorithm to the current rendering + * target at subpixel precision. + * + * The pixels in the texture are split into a 3x3 grid, using the different + * corner sizes for each corner, and the sides and center making up the + * remaining pixels. The corners are then scaled using `scale` and fit into + * the corners of the destination rectangle. The sides and center are then + * stretched into place to cover the remaining destination rectangle. + * + * \param renderer the renderer which should copy parts of a texture. + * \param texture the source texture. + * \param srcrect the SDL_Rect structure representing the rectangle to be used + * for the 9-grid, or NULL to use the entire texture. + * \param left_width the width, in pixels, of the left corners in `srcrect`. + * \param right_width the width, in pixels, of the right corners in `srcrect`. + * \param top_height the height, in pixels, of the top corners in `srcrect`. + * \param bottom_height the height, in pixels, of the bottom corners in + * `srcrect`. + * \param scale the scale used to transform the corner of `srcrect` into the + * corner of `dstrect`, or 0.0f for an unscaled copy. + * \param dstrect a pointer to the destination rectangle, or NULL for the + * entire rendering target. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderTexture + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderTexture9Grid(SDL_Renderer *renderer, SDL_Texture *texture, const SDL_FRect *srcrect, float left_width, float right_width, float top_height, float bottom_height, float scale, const SDL_FRect *dstrect); + +/** + * Render a list of triangles, optionally using a texture and indices into the + * vertex array Color and alpha modulation is done per vertex + * (SDL_SetTextureColorMod and SDL_SetTextureAlphaMod are ignored). + * + * \param renderer the rendering context. + * \param texture (optional) The SDL texture to use. + * \param vertices vertices. + * \param num_vertices number of vertices. + * \param indices (optional) An array of integer indices into the 'vertices' + * array, if NULL all vertices will be rendered in sequential + * order. + * \param num_indices number of indices. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderGeometryRaw + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderGeometry(SDL_Renderer *renderer, + SDL_Texture *texture, + const SDL_Vertex *vertices, int num_vertices, + const int *indices, int num_indices); + +/** + * Render a list of triangles, optionally using a texture and indices into the + * vertex arrays Color and alpha modulation is done per vertex + * (SDL_SetTextureColorMod and SDL_SetTextureAlphaMod are ignored). + * + * \param renderer the rendering context. + * \param texture (optional) The SDL texture to use. + * \param xy vertex positions. + * \param xy_stride byte size to move from one element to the next element. + * \param color vertex colors (as SDL_FColor). + * \param color_stride byte size to move from one element to the next element. + * \param uv vertex normalized texture coordinates. + * \param uv_stride byte size to move from one element to the next element. + * \param num_vertices number of vertices. + * \param indices (optional) An array of indices into the 'vertices' arrays, + * if NULL all vertices will be rendered in sequential order. + * \param num_indices number of indices. + * \param size_indices index size: 1 (byte), 2 (short), 4 (int). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderGeometry + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderGeometryRaw(SDL_Renderer *renderer, + SDL_Texture *texture, + const float *xy, int xy_stride, + const SDL_FColor *color, int color_stride, + const float *uv, int uv_stride, + int num_vertices, + const void *indices, int num_indices, int size_indices); + +/** + * Read pixels from the current rendering target. + * + * The returned surface contains pixels inside the desired area clipped to the + * current viewport, and should be freed with SDL_DestroySurface(). + * + * Note that this returns the actual pixels on the screen, so if you are using + * logical presentation you should use SDL_GetRenderLogicalPresentationRect() + * to get the area containing your content. + * + * **WARNING**: This is a very slow operation, and should not be used + * frequently. If you're using this on the main rendering target, it should be + * called after rendering and before SDL_RenderPresent(). + * + * \param renderer the rendering context. + * \param rect an SDL_Rect structure representing the area to read, which will + * be clipped to the current viewport, or NULL for the entire + * viewport. + * \returns a new SDL_Surface on success or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_RenderReadPixels(SDL_Renderer *renderer, const SDL_Rect *rect); + +/** + * Update the screen with any rendering performed since the previous call. + * + * SDL's rendering functions operate on a backbuffer; that is, calling a + * rendering function such as SDL_RenderLine() does not directly put a line on + * the screen, but rather updates the backbuffer. As such, you compose your + * entire scene and *present* the composed backbuffer to the screen as a + * complete picture. + * + * Therefore, when using SDL's rendering API, one does all drawing intended + * for the frame, and then calls this function once per frame to present the + * final drawing to the user. + * + * The backbuffer should be considered invalidated after each present; do not + * assume that previous contents will exist between frames. You are strongly + * encouraged to call SDL_RenderClear() to initialize the backbuffer before + * starting each new frame's drawing, even if you plan to overwrite every + * pixel. + * + * Please note, that in case of rendering to a texture - there is **no need** + * to call `SDL_RenderPresent` after drawing needed objects to a texture, and + * should not be done; you are only required to change back the rendering + * target to default via `SDL_SetRenderTarget(renderer, NULL)` afterwards, as + * textures by themselves do not have a concept of backbuffers. Calling + * SDL_RenderPresent while rendering to a texture will still update the screen + * with any current drawing that has been done _to the window itself_. + * + * \param renderer the rendering context. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateRenderer + * \sa SDL_RenderClear + * \sa SDL_RenderFillRect + * \sa SDL_RenderFillRects + * \sa SDL_RenderLine + * \sa SDL_RenderLines + * \sa SDL_RenderPoint + * \sa SDL_RenderPoints + * \sa SDL_RenderRect + * \sa SDL_RenderRects + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_SetRenderDrawColor + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderPresent(SDL_Renderer *renderer); + +/** + * Destroy the specified texture. + * + * Passing NULL or an otherwise invalid texture will set the SDL error message + * to "Invalid texture". + * + * \param texture the texture to destroy. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTexture + * \sa SDL_CreateTextureFromSurface + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyTexture(SDL_Texture *texture); + +/** + * Destroy the rendering context for a window and free all associated + * textures. + * + * This should be called before destroying the associated window. + * + * \param renderer the rendering context. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateRenderer + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyRenderer(SDL_Renderer *renderer); + +/** + * Force the rendering context to flush any pending commands and state. + * + * You do not need to (and in fact, shouldn't) call this function unless you + * are planning to call into OpenGL/Direct3D/Metal/whatever directly, in + * addition to using an SDL_Renderer. + * + * This is for a very-specific case: if you are using SDL's render API, and + * you plan to make OpenGL/D3D/whatever calls in addition to SDL render API + * calls. If this applies, you should call this function between calls to + * SDL's render API and the low-level API you're using in cooperation. + * + * In all other cases, you can ignore this function. + * + * This call makes SDL flush any pending rendering work it was queueing up to + * do later in a single batch, and marks any internal cached state as invalid, + * so it'll prepare all its state again later, from scratch. + * + * This means you do not need to save state in your rendering code to protect + * the SDL renderer. However, there lots of arbitrary pieces of Direct3D and + * OpenGL state that can confuse things; you should use your best judgment and + * be prepared to make changes if specific state needs to be protected. + * + * \param renderer the rendering context. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_FlushRenderer(SDL_Renderer *renderer); + +/** + * Get the CAMetalLayer associated with the given Metal renderer. + * + * This function returns `void *`, so SDL doesn't have to include Metal's + * headers, but it can be safely cast to a `CAMetalLayer *`. + * + * \param renderer the renderer to query. + * \returns a `CAMetalLayer *` on success, or NULL if the renderer isn't a + * Metal renderer. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderMetalCommandEncoder + */ +extern SDL_DECLSPEC void * SDLCALL SDL_GetRenderMetalLayer(SDL_Renderer *renderer); + +/** + * Get the Metal command encoder for the current frame. + * + * This function returns `void *`, so SDL doesn't have to include Metal's + * headers, but it can be safely cast to an `id`. + * + * This will return NULL if Metal refuses to give SDL a drawable to render to, + * which might happen if the window is hidden/minimized/offscreen. This + * doesn't apply to command encoders for render targets, just the window's + * backbuffer. Check your return values! + * + * \param renderer the renderer to query. + * \returns an `id` on success, or NULL if the + * renderer isn't a Metal renderer or there was an error. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderMetalLayer + */ +extern SDL_DECLSPEC void * SDLCALL SDL_GetRenderMetalCommandEncoder(SDL_Renderer *renderer); + + +/** + * Add a set of synchronization semaphores for the current frame. + * + * The Vulkan renderer will wait for `wait_semaphore` before submitting + * rendering commands and signal `signal_semaphore` after rendering commands + * are complete for this frame. + * + * This should be called each frame that you want semaphore synchronization. + * The Vulkan renderer may have multiple frames in flight on the GPU, so you + * should have multiple semaphores that are used for synchronization. Querying + * SDL_PROP_RENDERER_VULKAN_SWAPCHAIN_IMAGE_COUNT_NUMBER will give you the + * maximum number of semaphores you'll need. + * + * \param renderer the rendering context. + * \param wait_stage_mask the VkPipelineStageFlags for the wait. + * \param wait_semaphore a VkSempahore to wait on before rendering the current + * frame, or 0 if not needed. + * \param signal_semaphore a VkSempahore that SDL will signal when rendering + * for the current frame is complete, or 0 if not + * needed. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is **NOT** safe to call this function from two threads at + * once. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_AddVulkanRenderSemaphores(SDL_Renderer *renderer, Uint32 wait_stage_mask, Sint64 wait_semaphore, Sint64 signal_semaphore); + +/** + * Toggle VSync of the given renderer. + * + * When a renderer is created, vsync defaults to SDL_RENDERER_VSYNC_DISABLED. + * + * The `vsync` parameter can be 1 to synchronize present with every vertical + * refresh, 2 to synchronize present with every second vertical refresh, etc., + * SDL_RENDERER_VSYNC_ADAPTIVE for late swap tearing (adaptive vsync), or + * SDL_RENDERER_VSYNC_DISABLED to disable. Not every value is supported by + * every driver, so you should check the return value to see whether the + * requested setting is supported. + * + * \param renderer the renderer to toggle. + * \param vsync the vertical refresh sync interval. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderVSync + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderVSync(SDL_Renderer *renderer, int vsync); + +#define SDL_RENDERER_VSYNC_DISABLED 0 +#define SDL_RENDERER_VSYNC_ADAPTIVE (-1) + +/** + * Get VSync of the given renderer. + * + * \param renderer the renderer to toggle. + * \param vsync an int filled with the current vertical refresh sync interval. + * See SDL_SetRenderVSync() for the meaning of the value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetRenderVSync + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderVSync(SDL_Renderer *renderer, int *vsync); + +/** + * The size, in pixels, of a single SDL_RenderDebugText() character. + * + * The font is monospaced and square, so this applies to all characters. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_RenderDebugText + */ +#define SDL_DEBUG_TEXT_FONT_CHARACTER_SIZE 8 + +/** + * Draw debug text to an SDL_Renderer. + * + * This function will render a string of text to an SDL_Renderer. Note that + * this is a convenience function for debugging, with severe limitations, and + * not intended to be used for production apps and games. + * + * Among these limitations: + * + * - It accepts UTF-8 strings, but will only renders ASCII characters. + * - It has a single, tiny size (8x8 pixels). One can use logical presentation + * or scaling to adjust it, but it will be blurry. + * - It uses a simple, hardcoded bitmap font. It does not allow different font + * selections and it does not support truetype, for proper scaling. + * - It does no word-wrapping and does not treat newline characters as a line + * break. If the text goes out of the window, it's gone. + * + * For serious text rendering, there are several good options, such as + * SDL_ttf, stb_truetype, or other external libraries. + * + * On first use, this will create an internal texture for rendering glyphs. + * This texture will live until the renderer is destroyed. + * + * The text is drawn in the color specified by SDL_SetRenderDrawColor(). + * + * \param renderer the renderer which should draw a line of text. + * \param x the x coordinate where the top-left corner of the text will draw. + * \param y the y coordinate where the top-left corner of the text will draw. + * \param str the string to render. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderDebugTextFormat + * \sa SDL_DEBUG_TEXT_FONT_CHARACTER_SIZE + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderDebugText(SDL_Renderer *renderer, float x, float y, const char *str); + +/** + * Draw debug text to an SDL_Renderer. + * + * This function will render a printf()-style format string to a renderer. + * Note that this is a convinence function for debugging, with severe + * limitations, and is not intended to be used for production apps and games. + * + * For the full list of limitations and other useful information, see + * SDL_RenderDebugText. + * + * \param renderer the renderer which should draw the text. + * \param x the x coordinate where the top-left corner of the text will draw. + * \param y the y coordinate where the top-left corner of the text will draw. + * \param fmt the format string to draw. + * \param ... additional parameters matching % tokens in the `fmt` string, if + * any. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RenderDebugText + * \sa SDL_DEBUG_TEXT_FONT_CHARACTER_SIZE + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenderDebugTextFormat(SDL_Renderer *renderer, float x, float y, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(4); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_render_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_revision.h b/thirdparty/sdl/include/SDL3/SDL_revision.h new file mode 100644 index 00000000000..f0f57cd59b6 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_revision.h @@ -0,0 +1,56 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: Version */ + +/* + * SDL_revision.h contains the SDL revision, which might be defined on the + * compiler command line, or generated right into the header itself by the + * build system. + */ + +#ifndef SDL_revision_h_ +#define SDL_revision_h_ + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * This macro is a string describing the source at a particular point in + * development. + * + * This string is often generated from revision control's state at build time. + * + * This string can be quite complex and does not follow any standard. For + * example, it might be something like "SDL-prerelease-3.1.1-47-gf687e0732". + * It might also be user-defined at build time, so it's best to treat it as a + * clue in debugging forensics and not something the app will parse in any + * way. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_REVISION "Some arbitrary string decided at SDL build time" +#elif defined(SDL_VENDOR_INFO) +#define SDL_REVISION SDL_VENDOR_INFO +#else +#define SDL_REVISION "" +#endif + +#endif /* SDL_revision_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_scancode.h b/thirdparty/sdl/include/SDL3/SDL_scancode.h new file mode 100644 index 00000000000..9650a6cfe35 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_scancode.h @@ -0,0 +1,429 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryScancode + * + * Defines keyboard scancodes. + * + * Please refer to the Best Keyboard Practices document for details on what + * this information means and how best to use it. + * + * https://wiki.libsdl.org/SDL3/BestKeyboardPractices + */ + +#ifndef SDL_scancode_h_ +#define SDL_scancode_h_ + +#include + +/** + * The SDL keyboard scancode representation. + * + * An SDL scancode is the physical representation of a key on the keyboard, + * independent of language and keyboard mapping. + * + * Values of this type are used to represent keyboard keys, among other places + * in the `scancode` field of the SDL_KeyboardEvent structure. + * + * The values in this enumeration are based on the USB usage page standard: + * https://usb.org/sites/default/files/hut1_5.pdf + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_Scancode +{ + SDL_SCANCODE_UNKNOWN = 0, + + /** + * \name Usage page 0x07 + * + * These values are from usage page 0x07 (USB keyboard page). + */ + /* @{ */ + + SDL_SCANCODE_A = 4, + SDL_SCANCODE_B = 5, + SDL_SCANCODE_C = 6, + SDL_SCANCODE_D = 7, + SDL_SCANCODE_E = 8, + SDL_SCANCODE_F = 9, + SDL_SCANCODE_G = 10, + SDL_SCANCODE_H = 11, + SDL_SCANCODE_I = 12, + SDL_SCANCODE_J = 13, + SDL_SCANCODE_K = 14, + SDL_SCANCODE_L = 15, + SDL_SCANCODE_M = 16, + SDL_SCANCODE_N = 17, + SDL_SCANCODE_O = 18, + SDL_SCANCODE_P = 19, + SDL_SCANCODE_Q = 20, + SDL_SCANCODE_R = 21, + SDL_SCANCODE_S = 22, + SDL_SCANCODE_T = 23, + SDL_SCANCODE_U = 24, + SDL_SCANCODE_V = 25, + SDL_SCANCODE_W = 26, + SDL_SCANCODE_X = 27, + SDL_SCANCODE_Y = 28, + SDL_SCANCODE_Z = 29, + + SDL_SCANCODE_1 = 30, + SDL_SCANCODE_2 = 31, + SDL_SCANCODE_3 = 32, + SDL_SCANCODE_4 = 33, + SDL_SCANCODE_5 = 34, + SDL_SCANCODE_6 = 35, + SDL_SCANCODE_7 = 36, + SDL_SCANCODE_8 = 37, + SDL_SCANCODE_9 = 38, + SDL_SCANCODE_0 = 39, + + SDL_SCANCODE_RETURN = 40, + SDL_SCANCODE_ESCAPE = 41, + SDL_SCANCODE_BACKSPACE = 42, + SDL_SCANCODE_TAB = 43, + SDL_SCANCODE_SPACE = 44, + + SDL_SCANCODE_MINUS = 45, + SDL_SCANCODE_EQUALS = 46, + SDL_SCANCODE_LEFTBRACKET = 47, + SDL_SCANCODE_RIGHTBRACKET = 48, + SDL_SCANCODE_BACKSLASH = 49, /**< Located at the lower left of the return + * key on ISO keyboards and at the right end + * of the QWERTY row on ANSI keyboards. + * Produces REVERSE SOLIDUS (backslash) and + * VERTICAL LINE in a US layout, REVERSE + * SOLIDUS and VERTICAL LINE in a UK Mac + * layout, NUMBER SIGN and TILDE in a UK + * Windows layout, DOLLAR SIGN and POUND SIGN + * in a Swiss German layout, NUMBER SIGN and + * APOSTROPHE in a German layout, GRAVE + * ACCENT and POUND SIGN in a French Mac + * layout, and ASTERISK and MICRO SIGN in a + * French Windows layout. + */ + SDL_SCANCODE_NONUSHASH = 50, /**< ISO USB keyboards actually use this code + * instead of 49 for the same key, but all + * OSes I've seen treat the two codes + * identically. So, as an implementor, unless + * your keyboard generates both of those + * codes and your OS treats them differently, + * you should generate SDL_SCANCODE_BACKSLASH + * instead of this code. As a user, you + * should not rely on this code because SDL + * will never generate it with most (all?) + * keyboards. + */ + SDL_SCANCODE_SEMICOLON = 51, + SDL_SCANCODE_APOSTROPHE = 52, + SDL_SCANCODE_GRAVE = 53, /**< Located in the top left corner (on both ANSI + * and ISO keyboards). Produces GRAVE ACCENT and + * TILDE in a US Windows layout and in US and UK + * Mac layouts on ANSI keyboards, GRAVE ACCENT + * and NOT SIGN in a UK Windows layout, SECTION + * SIGN and PLUS-MINUS SIGN in US and UK Mac + * layouts on ISO keyboards, SECTION SIGN and + * DEGREE SIGN in a Swiss German layout (Mac: + * only on ISO keyboards), CIRCUMFLEX ACCENT and + * DEGREE SIGN in a German layout (Mac: only on + * ISO keyboards), SUPERSCRIPT TWO and TILDE in a + * French Windows layout, COMMERCIAL AT and + * NUMBER SIGN in a French Mac layout on ISO + * keyboards, and LESS-THAN SIGN and GREATER-THAN + * SIGN in a Swiss German, German, or French Mac + * layout on ANSI keyboards. + */ + SDL_SCANCODE_COMMA = 54, + SDL_SCANCODE_PERIOD = 55, + SDL_SCANCODE_SLASH = 56, + + SDL_SCANCODE_CAPSLOCK = 57, + + SDL_SCANCODE_F1 = 58, + SDL_SCANCODE_F2 = 59, + SDL_SCANCODE_F3 = 60, + SDL_SCANCODE_F4 = 61, + SDL_SCANCODE_F5 = 62, + SDL_SCANCODE_F6 = 63, + SDL_SCANCODE_F7 = 64, + SDL_SCANCODE_F8 = 65, + SDL_SCANCODE_F9 = 66, + SDL_SCANCODE_F10 = 67, + SDL_SCANCODE_F11 = 68, + SDL_SCANCODE_F12 = 69, + + SDL_SCANCODE_PRINTSCREEN = 70, + SDL_SCANCODE_SCROLLLOCK = 71, + SDL_SCANCODE_PAUSE = 72, + SDL_SCANCODE_INSERT = 73, /**< insert on PC, help on some Mac keyboards (but + does send code 73, not 117) */ + SDL_SCANCODE_HOME = 74, + SDL_SCANCODE_PAGEUP = 75, + SDL_SCANCODE_DELETE = 76, + SDL_SCANCODE_END = 77, + SDL_SCANCODE_PAGEDOWN = 78, + SDL_SCANCODE_RIGHT = 79, + SDL_SCANCODE_LEFT = 80, + SDL_SCANCODE_DOWN = 81, + SDL_SCANCODE_UP = 82, + + SDL_SCANCODE_NUMLOCKCLEAR = 83, /**< num lock on PC, clear on Mac keyboards + */ + SDL_SCANCODE_KP_DIVIDE = 84, + SDL_SCANCODE_KP_MULTIPLY = 85, + SDL_SCANCODE_KP_MINUS = 86, + SDL_SCANCODE_KP_PLUS = 87, + SDL_SCANCODE_KP_ENTER = 88, + SDL_SCANCODE_KP_1 = 89, + SDL_SCANCODE_KP_2 = 90, + SDL_SCANCODE_KP_3 = 91, + SDL_SCANCODE_KP_4 = 92, + SDL_SCANCODE_KP_5 = 93, + SDL_SCANCODE_KP_6 = 94, + SDL_SCANCODE_KP_7 = 95, + SDL_SCANCODE_KP_8 = 96, + SDL_SCANCODE_KP_9 = 97, + SDL_SCANCODE_KP_0 = 98, + SDL_SCANCODE_KP_PERIOD = 99, + + SDL_SCANCODE_NONUSBACKSLASH = 100, /**< This is the additional key that ISO + * keyboards have over ANSI ones, + * located between left shift and Y. + * Produces GRAVE ACCENT and TILDE in a + * US or UK Mac layout, REVERSE SOLIDUS + * (backslash) and VERTICAL LINE in a + * US or UK Windows layout, and + * LESS-THAN SIGN and GREATER-THAN SIGN + * in a Swiss German, German, or French + * layout. */ + SDL_SCANCODE_APPLICATION = 101, /**< windows contextual menu, compose */ + SDL_SCANCODE_POWER = 102, /**< The USB document says this is a status flag, + * not a physical key - but some Mac keyboards + * do have a power key. */ + SDL_SCANCODE_KP_EQUALS = 103, + SDL_SCANCODE_F13 = 104, + SDL_SCANCODE_F14 = 105, + SDL_SCANCODE_F15 = 106, + SDL_SCANCODE_F16 = 107, + SDL_SCANCODE_F17 = 108, + SDL_SCANCODE_F18 = 109, + SDL_SCANCODE_F19 = 110, + SDL_SCANCODE_F20 = 111, + SDL_SCANCODE_F21 = 112, + SDL_SCANCODE_F22 = 113, + SDL_SCANCODE_F23 = 114, + SDL_SCANCODE_F24 = 115, + SDL_SCANCODE_EXECUTE = 116, + SDL_SCANCODE_HELP = 117, /**< AL Integrated Help Center */ + SDL_SCANCODE_MENU = 118, /**< Menu (show menu) */ + SDL_SCANCODE_SELECT = 119, + SDL_SCANCODE_STOP = 120, /**< AC Stop */ + SDL_SCANCODE_AGAIN = 121, /**< AC Redo/Repeat */ + SDL_SCANCODE_UNDO = 122, /**< AC Undo */ + SDL_SCANCODE_CUT = 123, /**< AC Cut */ + SDL_SCANCODE_COPY = 124, /**< AC Copy */ + SDL_SCANCODE_PASTE = 125, /**< AC Paste */ + SDL_SCANCODE_FIND = 126, /**< AC Find */ + SDL_SCANCODE_MUTE = 127, + SDL_SCANCODE_VOLUMEUP = 128, + SDL_SCANCODE_VOLUMEDOWN = 129, +/* not sure whether there's a reason to enable these */ +/* SDL_SCANCODE_LOCKINGCAPSLOCK = 130, */ +/* SDL_SCANCODE_LOCKINGNUMLOCK = 131, */ +/* SDL_SCANCODE_LOCKINGSCROLLLOCK = 132, */ + SDL_SCANCODE_KP_COMMA = 133, + SDL_SCANCODE_KP_EQUALSAS400 = 134, + + SDL_SCANCODE_INTERNATIONAL1 = 135, /**< used on Asian keyboards, see + footnotes in USB doc */ + SDL_SCANCODE_INTERNATIONAL2 = 136, + SDL_SCANCODE_INTERNATIONAL3 = 137, /**< Yen */ + SDL_SCANCODE_INTERNATIONAL4 = 138, + SDL_SCANCODE_INTERNATIONAL5 = 139, + SDL_SCANCODE_INTERNATIONAL6 = 140, + SDL_SCANCODE_INTERNATIONAL7 = 141, + SDL_SCANCODE_INTERNATIONAL8 = 142, + SDL_SCANCODE_INTERNATIONAL9 = 143, + SDL_SCANCODE_LANG1 = 144, /**< Hangul/English toggle */ + SDL_SCANCODE_LANG2 = 145, /**< Hanja conversion */ + SDL_SCANCODE_LANG3 = 146, /**< Katakana */ + SDL_SCANCODE_LANG4 = 147, /**< Hiragana */ + SDL_SCANCODE_LANG5 = 148, /**< Zenkaku/Hankaku */ + SDL_SCANCODE_LANG6 = 149, /**< reserved */ + SDL_SCANCODE_LANG7 = 150, /**< reserved */ + SDL_SCANCODE_LANG8 = 151, /**< reserved */ + SDL_SCANCODE_LANG9 = 152, /**< reserved */ + + SDL_SCANCODE_ALTERASE = 153, /**< Erase-Eaze */ + SDL_SCANCODE_SYSREQ = 154, + SDL_SCANCODE_CANCEL = 155, /**< AC Cancel */ + SDL_SCANCODE_CLEAR = 156, + SDL_SCANCODE_PRIOR = 157, + SDL_SCANCODE_RETURN2 = 158, + SDL_SCANCODE_SEPARATOR = 159, + SDL_SCANCODE_OUT = 160, + SDL_SCANCODE_OPER = 161, + SDL_SCANCODE_CLEARAGAIN = 162, + SDL_SCANCODE_CRSEL = 163, + SDL_SCANCODE_EXSEL = 164, + + SDL_SCANCODE_KP_00 = 176, + SDL_SCANCODE_KP_000 = 177, + SDL_SCANCODE_THOUSANDSSEPARATOR = 178, + SDL_SCANCODE_DECIMALSEPARATOR = 179, + SDL_SCANCODE_CURRENCYUNIT = 180, + SDL_SCANCODE_CURRENCYSUBUNIT = 181, + SDL_SCANCODE_KP_LEFTPAREN = 182, + SDL_SCANCODE_KP_RIGHTPAREN = 183, + SDL_SCANCODE_KP_LEFTBRACE = 184, + SDL_SCANCODE_KP_RIGHTBRACE = 185, + SDL_SCANCODE_KP_TAB = 186, + SDL_SCANCODE_KP_BACKSPACE = 187, + SDL_SCANCODE_KP_A = 188, + SDL_SCANCODE_KP_B = 189, + SDL_SCANCODE_KP_C = 190, + SDL_SCANCODE_KP_D = 191, + SDL_SCANCODE_KP_E = 192, + SDL_SCANCODE_KP_F = 193, + SDL_SCANCODE_KP_XOR = 194, + SDL_SCANCODE_KP_POWER = 195, + SDL_SCANCODE_KP_PERCENT = 196, + SDL_SCANCODE_KP_LESS = 197, + SDL_SCANCODE_KP_GREATER = 198, + SDL_SCANCODE_KP_AMPERSAND = 199, + SDL_SCANCODE_KP_DBLAMPERSAND = 200, + SDL_SCANCODE_KP_VERTICALBAR = 201, + SDL_SCANCODE_KP_DBLVERTICALBAR = 202, + SDL_SCANCODE_KP_COLON = 203, + SDL_SCANCODE_KP_HASH = 204, + SDL_SCANCODE_KP_SPACE = 205, + SDL_SCANCODE_KP_AT = 206, + SDL_SCANCODE_KP_EXCLAM = 207, + SDL_SCANCODE_KP_MEMSTORE = 208, + SDL_SCANCODE_KP_MEMRECALL = 209, + SDL_SCANCODE_KP_MEMCLEAR = 210, + SDL_SCANCODE_KP_MEMADD = 211, + SDL_SCANCODE_KP_MEMSUBTRACT = 212, + SDL_SCANCODE_KP_MEMMULTIPLY = 213, + SDL_SCANCODE_KP_MEMDIVIDE = 214, + SDL_SCANCODE_KP_PLUSMINUS = 215, + SDL_SCANCODE_KP_CLEAR = 216, + SDL_SCANCODE_KP_CLEARENTRY = 217, + SDL_SCANCODE_KP_BINARY = 218, + SDL_SCANCODE_KP_OCTAL = 219, + SDL_SCANCODE_KP_DECIMAL = 220, + SDL_SCANCODE_KP_HEXADECIMAL = 221, + + SDL_SCANCODE_LCTRL = 224, + SDL_SCANCODE_LSHIFT = 225, + SDL_SCANCODE_LALT = 226, /**< alt, option */ + SDL_SCANCODE_LGUI = 227, /**< windows, command (apple), meta */ + SDL_SCANCODE_RCTRL = 228, + SDL_SCANCODE_RSHIFT = 229, + SDL_SCANCODE_RALT = 230, /**< alt gr, option */ + SDL_SCANCODE_RGUI = 231, /**< windows, command (apple), meta */ + + SDL_SCANCODE_MODE = 257, /**< I'm not sure if this is really not covered + * by any of the above, but since there's a + * special SDL_KMOD_MODE for it I'm adding it here + */ + + /* @} *//* Usage page 0x07 */ + + /** + * \name Usage page 0x0C + * + * These values are mapped from usage page 0x0C (USB consumer page). + * + * There are way more keys in the spec than we can represent in the + * current scancode range, so pick the ones that commonly come up in + * real world usage. + */ + /* @{ */ + + SDL_SCANCODE_SLEEP = 258, /**< Sleep */ + SDL_SCANCODE_WAKE = 259, /**< Wake */ + + SDL_SCANCODE_CHANNEL_INCREMENT = 260, /**< Channel Increment */ + SDL_SCANCODE_CHANNEL_DECREMENT = 261, /**< Channel Decrement */ + + SDL_SCANCODE_MEDIA_PLAY = 262, /**< Play */ + SDL_SCANCODE_MEDIA_PAUSE = 263, /**< Pause */ + SDL_SCANCODE_MEDIA_RECORD = 264, /**< Record */ + SDL_SCANCODE_MEDIA_FAST_FORWARD = 265, /**< Fast Forward */ + SDL_SCANCODE_MEDIA_REWIND = 266, /**< Rewind */ + SDL_SCANCODE_MEDIA_NEXT_TRACK = 267, /**< Next Track */ + SDL_SCANCODE_MEDIA_PREVIOUS_TRACK = 268, /**< Previous Track */ + SDL_SCANCODE_MEDIA_STOP = 269, /**< Stop */ + SDL_SCANCODE_MEDIA_EJECT = 270, /**< Eject */ + SDL_SCANCODE_MEDIA_PLAY_PAUSE = 271, /**< Play / Pause */ + SDL_SCANCODE_MEDIA_SELECT = 272, /* Media Select */ + + SDL_SCANCODE_AC_NEW = 273, /**< AC New */ + SDL_SCANCODE_AC_OPEN = 274, /**< AC Open */ + SDL_SCANCODE_AC_CLOSE = 275, /**< AC Close */ + SDL_SCANCODE_AC_EXIT = 276, /**< AC Exit */ + SDL_SCANCODE_AC_SAVE = 277, /**< AC Save */ + SDL_SCANCODE_AC_PRINT = 278, /**< AC Print */ + SDL_SCANCODE_AC_PROPERTIES = 279, /**< AC Properties */ + + SDL_SCANCODE_AC_SEARCH = 280, /**< AC Search */ + SDL_SCANCODE_AC_HOME = 281, /**< AC Home */ + SDL_SCANCODE_AC_BACK = 282, /**< AC Back */ + SDL_SCANCODE_AC_FORWARD = 283, /**< AC Forward */ + SDL_SCANCODE_AC_STOP = 284, /**< AC Stop */ + SDL_SCANCODE_AC_REFRESH = 285, /**< AC Refresh */ + SDL_SCANCODE_AC_BOOKMARKS = 286, /**< AC Bookmarks */ + + /* @} *//* Usage page 0x0C */ + + + /** + * \name Mobile keys + * + * These are values that are often used on mobile phones. + */ + /* @{ */ + + SDL_SCANCODE_SOFTLEFT = 287, /**< Usually situated below the display on phones and + used as a multi-function feature key for selecting + a software defined function shown on the bottom left + of the display. */ + SDL_SCANCODE_SOFTRIGHT = 288, /**< Usually situated below the display on phones and + used as a multi-function feature key for selecting + a software defined function shown on the bottom right + of the display. */ + SDL_SCANCODE_CALL = 289, /**< Used for accepting phone calls. */ + SDL_SCANCODE_ENDCALL = 290, /**< Used for rejecting phone calls. */ + + /* @} *//* Mobile keys */ + + /* Add any other keys here. */ + + SDL_SCANCODE_RESERVED = 400, /**< 400-500 reserved for dynamic keycodes */ + + SDL_SCANCODE_COUNT = 512 /**< not a key, just marks the number of scancodes for array bounds */ + +} SDL_Scancode; + +#endif /* SDL_scancode_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_sensor.h b/thirdparty/sdl/include/SDL3/SDL_sensor.h new file mode 100644 index 00000000000..b220f0538c0 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_sensor.h @@ -0,0 +1,320 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategorySensor + * + * SDL sensor management. + * + * These APIs grant access to gyros and accelerometers on various platforms. + * + * In order to use these functions, SDL_Init() must have been called with the + * SDL_INIT_SENSOR flag. This causes SDL to scan the system for sensors, and + * load appropriate drivers. + */ + +#ifndef SDL_sensor_h_ +#define SDL_sensor_h_ + +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +/** + * The opaque structure used to identify an opened SDL sensor. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Sensor SDL_Sensor; + +/** + * This is a unique ID for a sensor for the time it is connected to the + * system, and is never reused for the lifetime of the application. + * + * The value 0 is an invalid ID. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_SensorID; + +/** + * A constant to represent standard gravity for accelerometer sensors. + * + * The accelerometer returns the current acceleration in SI meters per second + * squared. This measurement includes the force of gravity, so a device at + * rest will have an value of SDL_STANDARD_GRAVITY away from the center of the + * earth, which is a positive Y value. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_STANDARD_GRAVITY 9.80665f + +/** + * The different sensors defined by SDL. + * + * Additional sensors may be available, using platform dependent semantics. + * + * Here are the additional Android sensors: + * + * https://developer.android.com/reference/android/hardware/SensorEvent.html#values + * + * Accelerometer sensor notes: + * + * The accelerometer returns the current acceleration in SI meters per second + * squared. This measurement includes the force of gravity, so a device at + * rest will have an value of SDL_STANDARD_GRAVITY away from the center of the + * earth, which is a positive Y value. + * + * - `values[0]`: Acceleration on the x axis + * - `values[1]`: Acceleration on the y axis + * - `values[2]`: Acceleration on the z axis + * + * For phones and tablets held in natural orientation and game controllers + * held in front of you, the axes are defined as follows: + * + * - -X ... +X : left ... right + * - -Y ... +Y : bottom ... top + * - -Z ... +Z : farther ... closer + * + * The accelerometer axis data is not changed when the device is rotated. + * + * Gyroscope sensor notes: + * + * The gyroscope returns the current rate of rotation in radians per second. + * The rotation is positive in the counter-clockwise direction. That is, an + * observer looking from a positive location on one of the axes would see + * positive rotation on that axis when it appeared to be rotating + * counter-clockwise. + * + * - `values[0]`: Angular speed around the x axis (pitch) + * - `values[1]`: Angular speed around the y axis (yaw) + * - `values[2]`: Angular speed around the z axis (roll) + * + * For phones and tablets held in natural orientation and game controllers + * held in front of you, the axes are defined as follows: + * + * - -X ... +X : left ... right + * - -Y ... +Y : bottom ... top + * - -Z ... +Z : farther ... closer + * + * The gyroscope axis data is not changed when the device is rotated. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_GetCurrentDisplayOrientation + */ +typedef enum SDL_SensorType +{ + SDL_SENSOR_INVALID = -1, /**< Returned for an invalid sensor */ + SDL_SENSOR_UNKNOWN, /**< Unknown sensor type */ + SDL_SENSOR_ACCEL, /**< Accelerometer */ + SDL_SENSOR_GYRO, /**< Gyroscope */ + SDL_SENSOR_ACCEL_L, /**< Accelerometer for left Joy-Con controller and Wii nunchuk */ + SDL_SENSOR_GYRO_L, /**< Gyroscope for left Joy-Con controller */ + SDL_SENSOR_ACCEL_R, /**< Accelerometer for right Joy-Con controller */ + SDL_SENSOR_GYRO_R /**< Gyroscope for right Joy-Con controller */ +} SDL_SensorType; + + +/* Function prototypes */ + +/** + * Get a list of currently connected sensors. + * + * \param count a pointer filled in with the number of sensors returned, may + * be NULL. + * \returns a 0 terminated array of sensor instance IDs or NULL on failure; + * call SDL_GetError() for more information. This should be freed + * with SDL_free() when it is no longer needed. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_SensorID * SDLCALL SDL_GetSensors(int *count); + +/** + * Get the implementation dependent name of a sensor. + * + * This can be called before any sensors are opened. + * + * \param instance_id the sensor instance ID. + * \returns the sensor name, or NULL if `instance_id` is not valid. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetSensorNameForID(SDL_SensorID instance_id); + +/** + * Get the type of a sensor. + * + * This can be called before any sensors are opened. + * + * \param instance_id the sensor instance ID. + * \returns the SDL_SensorType, or `SDL_SENSOR_INVALID` if `instance_id` is + * not valid. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_SensorType SDLCALL SDL_GetSensorTypeForID(SDL_SensorID instance_id); + +/** + * Get the platform dependent type of a sensor. + * + * This can be called before any sensors are opened. + * + * \param instance_id the sensor instance ID. + * \returns the sensor platform dependent type, or -1 if `instance_id` is not + * valid. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetSensorNonPortableTypeForID(SDL_SensorID instance_id); + +/** + * Open a sensor for use. + * + * \param instance_id the sensor instance ID. + * \returns an SDL_Sensor object or NULL on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Sensor * SDLCALL SDL_OpenSensor(SDL_SensorID instance_id); + +/** + * Return the SDL_Sensor associated with an instance ID. + * + * \param instance_id the sensor instance ID. + * \returns an SDL_Sensor object or NULL on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Sensor * SDLCALL SDL_GetSensorFromID(SDL_SensorID instance_id); + +/** + * Get the properties associated with a sensor. + * + * \param sensor the SDL_Sensor object. + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetSensorProperties(SDL_Sensor *sensor); + +/** + * Get the implementation dependent name of a sensor. + * + * \param sensor the SDL_Sensor object. + * \returns the sensor name or NULL on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetSensorName(SDL_Sensor *sensor); + +/** + * Get the type of a sensor. + * + * \param sensor the SDL_Sensor object to inspect. + * \returns the SDL_SensorType type, or `SDL_SENSOR_INVALID` if `sensor` is + * NULL. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_SensorType SDLCALL SDL_GetSensorType(SDL_Sensor *sensor); + +/** + * Get the platform dependent type of a sensor. + * + * \param sensor the SDL_Sensor object to inspect. + * \returns the sensor platform dependent type, or -1 if `sensor` is NULL. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetSensorNonPortableType(SDL_Sensor *sensor); + +/** + * Get the instance ID of a sensor. + * + * \param sensor the SDL_Sensor object to inspect. + * \returns the sensor instance ID, or 0 on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_SensorID SDLCALL SDL_GetSensorID(SDL_Sensor *sensor); + +/** + * Get the current state of an opened sensor. + * + * The number of values and interpretation of the data is sensor dependent. + * + * \param sensor the SDL_Sensor object to query. + * \param data a pointer filled with the current sensor state. + * \param num_values the number of values to write to data. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetSensorData(SDL_Sensor *sensor, float *data, int num_values); + +/** + * Close a sensor previously opened with SDL_OpenSensor(). + * + * \param sensor the SDL_Sensor object to close. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_CloseSensor(SDL_Sensor *sensor); + +/** + * Update the current state of the open sensors. + * + * This is called automatically by the event loop if sensor events are + * enabled. + * + * This needs to be called from the thread that initialized the sensor + * subsystem. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_UpdateSensors(void); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif +#include + +#endif /* SDL_sensor_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_stdinc.h b/thirdparty/sdl/include/SDL3/SDL_stdinc.h new file mode 100644 index 00000000000..7df253feceb --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_stdinc.h @@ -0,0 +1,6137 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryStdinc + * + * SDL provides its own implementation of some of the most important C runtime + * functions. + * + * Using these functions allows an app to have access to common C + * functionality without depending on a specific C runtime (or a C runtime at + * all). More importantly, the SDL implementations work identically across + * platforms, so apps can avoid surprises like snprintf() behaving differently + * between Windows and Linux builds, or itoa() only existing on some + * platforms. + * + * For many of the most common functions, like SDL_memcpy, SDL might just call + * through to the usual C runtime behind the scenes, if it makes sense to do + * so (if it's faster and always available/reliable on a given platform), + * reducing library size and offering the most optimized option. + * + * SDL also offers other C-runtime-adjacent functionality in this header that + * either isn't, strictly speaking, part of any C runtime standards, like + * SDL_crc32() and SDL_reinterpret_cast, etc. It also offers a few better + * options, like SDL_strlcpy(), which functions as a safer form of strcpy(). + */ + +#ifndef SDL_stdinc_h_ +#define SDL_stdinc_h_ + +#include + +#include +#include +#include +#include + +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || \ + defined(SDL_INCLUDE_INTTYPES_H) +#include +#endif + +#ifndef __cplusplus +#if defined(__has_include) && !defined(SDL_INCLUDE_STDBOOL_H) +#if __has_include() +#define SDL_INCLUDE_STDBOOL_H +#endif +#endif +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || \ + (defined(_MSC_VER) && (_MSC_VER >= 1910 /* Visual Studio 2017 */)) || \ + defined(SDL_INCLUDE_STDBOOL_H) +#include +#elif !defined(__bool_true_false_are_defined) && !defined(bool) +#define bool unsigned char +#define false 0 +#define true 1 +#define __bool_true_false_are_defined 1 +#endif +#endif /* !__cplusplus */ + +#ifndef SDL_DISABLE_ALLOCA +# ifndef alloca +# ifdef HAVE_ALLOCA_H +# include +# elif defined(SDL_PLATFORM_NETBSD) +# if defined(__STRICT_ANSI__) +# define SDL_DISABLE_ALLOCA +# else +# include +# endif +# elif defined(__GNUC__) +# define alloca __builtin_alloca +# elif defined(_MSC_VER) +# include +# define alloca _alloca +# elif defined(__WATCOMC__) +# include +# elif defined(__BORLANDC__) +# include +# elif defined(__DMC__) +# include +# elif defined(SDL_PLATFORM_AIX) +# pragma alloca +# elif defined(__MRC__) +void *alloca(unsigned); +# else +void *alloca(size_t); +# endif +# endif +#endif + + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Don't let SDL use "long long" C types. + * + * SDL will define this if it believes the compiler doesn't understand the + * "long long" syntax for C datatypes. This can happen on older compilers. + * + * If _your_ compiler doesn't support "long long" but SDL doesn't know it, it + * is safe to define this yourself to build against the SDL headers. + * + * If this is defined, it will remove access to some C runtime support + * functions, like SDL_ulltoa and SDL_strtoll that refer to this datatype + * explicitly. The rest of SDL will still be available. + * + * SDL's own source code cannot be built with a compiler that has this + * defined, for various technical reasons. + */ +#define SDL_NOLONGLONG 1 + +#elif defined(_MSC_VER) && (_MSC_VER < 1310) /* long long introduced in Visual Studio.NET 2003 */ +# define SDL_NOLONGLONG 1 +#endif + + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * The largest value that a `size_t` can hold for the target platform. + * + * `size_t` is generally the same size as a pointer in modern times, but this + * can get weird on very old and very esoteric machines. For example, on a + * 16-bit Intel 286, you might have a 32-bit "far" pointer (16-bit segment + * plus 16-bit offset), but `size_t` is 16 bits, because it can only deal with + * the offset into an individual segment. + * + * In modern times, it's generally expected to cover an entire linear address + * space. But be careful! + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_SIZE_MAX SIZE_MAX + +#elif defined(SIZE_MAX) +# define SDL_SIZE_MAX SIZE_MAX +#else +# define SDL_SIZE_MAX ((size_t) -1) +#endif + +#ifndef SDL_COMPILE_TIME_ASSERT +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A compile-time assertion. + * + * This can check constant values _known to the compiler at build time_ for + * correctness, and end the compile with the error if they fail. + * + * Often times these are used to verify basic truths, like the size of a + * datatype is what is expected: + * + * ```c + * SDL_COMPILE_TIME_ASSERT(uint32_size, sizeof(Uint32) == 4); + * ``` + * + * The `name` parameter must be a valid C symbol, and must be unique across + * all compile-time asserts in the same compilation unit (one run of the + * compiler), or the build might fail with cryptic errors on some targets. + * This is used with a C language trick that works on older compilers that + * don't support better assertion techniques. + * + * If you need an assertion that operates at runtime, on variable data, you + * should try SDL_assert instead. + * + * \param name a unique identifier for this assertion. + * \param x the value to test. Must be a boolean value. + * + * \threadsafety This macro doesn't generate any code to run. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_assert + */ +#define SDL_COMPILE_TIME_ASSERT(name, x) FailToCompileIf_x_IsFalse(x) +#elif defined(__cplusplus) +/* Keep C++ case alone: Some versions of gcc will define __STDC_VERSION__ even when compiling in C++ mode. */ +#if (__cplusplus >= 201103L) +#define SDL_COMPILE_TIME_ASSERT(name, x) static_assert(x, #x) +#endif +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L) +#define SDL_COMPILE_TIME_ASSERT(name, x) static_assert(x, #x) +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) +#define SDL_COMPILE_TIME_ASSERT(name, x) _Static_assert(x, #x) +#endif +#endif /* !SDL_COMPILE_TIME_ASSERT */ + +#ifndef SDL_COMPILE_TIME_ASSERT +/* universal, but may trigger -Wunused-local-typedefs */ +#define SDL_COMPILE_TIME_ASSERT(name, x) \ + typedef int SDL_compile_time_assert_ ## name[(x) * 2 - 1] +#endif + +/** + * The number of elements in a static array. + * + * This will compile but return incorrect results for a pointer to an array; + * it has to be an array the compiler knows the size of. + * + * This macro looks like it double-evaluates the argument, but it does so + * inside of `sizeof`, so there are no side-effects here, as expressions do + * not actually run any code in these cases. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_arraysize(array) (sizeof(array)/sizeof(array[0])) + +/** + * Macro useful for building other macros with strings in them. + * + * For example: + * + * ```c + * #define LOG_ERROR(X) OutputDebugString(SDL_STRINGIFY_ARG(__FUNCTION__) ": " X "\n")` + * ``` + * + * \param arg the text to turn into a string literal. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_STRINGIFY_ARG(arg) #arg + +/** + * \name Cast operators + * + * Use proper C++ casts when compiled as C++ to be compatible with the option + * -Wold-style-cast of GCC (and -Werror=old-style-cast in GCC 4.2 and above). + */ +/* @{ */ + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Handle a Reinterpret Cast properly whether using C or C++. + * + * If compiled as C++, this macro offers a proper C++ reinterpret_cast<>. + * + * If compiled as C, this macro does a normal C-style cast. + * + * This is helpful to avoid compiler warnings in C++. + * + * \param type the type to cast the expression to. + * \param expression the expression to cast to a different type. + * \returns `expression`, cast to `type`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_static_cast + * \sa SDL_const_cast + */ +#define SDL_reinterpret_cast(type, expression) reinterpret_cast(expression) /* or `((type)(expression))` in C */ + +/** + * Handle a Static Cast properly whether using C or C++. + * + * If compiled as C++, this macro offers a proper C++ static_cast<>. + * + * If compiled as C, this macro does a normal C-style cast. + * + * This is helpful to avoid compiler warnings in C++. + * + * \param type the type to cast the expression to. + * \param expression the expression to cast to a different type. + * \returns `expression`, cast to `type`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_reinterpret_cast + * \sa SDL_const_cast + */ +#define SDL_static_cast(type, expression) static_cast(expression) /* or `((type)(expression))` in C */ + +/** + * Handle a Const Cast properly whether using C or C++. + * + * If compiled as C++, this macro offers a proper C++ const_cast<>. + * + * If compiled as C, this macro does a normal C-style cast. + * + * This is helpful to avoid compiler warnings in C++. + * + * \param type the type to cast the expression to. + * \param expression the expression to cast to a different type. + * \returns `expression`, cast to `type`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_reinterpret_cast + * \sa SDL_static_cast + */ +#define SDL_const_cast(type, expression) const_cast(expression) /* or `((type)(expression))` in C */ + +#elif defined(__cplusplus) +#define SDL_reinterpret_cast(type, expression) reinterpret_cast(expression) +#define SDL_static_cast(type, expression) static_cast(expression) +#define SDL_const_cast(type, expression) const_cast(expression) +#else +#define SDL_reinterpret_cast(type, expression) ((type)(expression)) +#define SDL_static_cast(type, expression) ((type)(expression)) +#define SDL_const_cast(type, expression) ((type)(expression)) +#endif + +/* @} *//* Cast operators */ + +/** + * Define a four character code as a Uint32. + * + * \param A the first ASCII character. + * \param B the second ASCII character. + * \param C the third ASCII character. + * \param D the fourth ASCII character. + * \returns the four characters converted into a Uint32, one character + * per-byte. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_FOURCC(A, B, C, D) \ + ((SDL_static_cast(Uint32, SDL_static_cast(Uint8, (A))) << 0) | \ + (SDL_static_cast(Uint32, SDL_static_cast(Uint8, (B))) << 8) | \ + (SDL_static_cast(Uint32, SDL_static_cast(Uint8, (C))) << 16) | \ + (SDL_static_cast(Uint32, SDL_static_cast(Uint8, (D))) << 24)) + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Append the 64 bit integer suffix to a signed integer literal. + * + * This helps compilers that might believe a integer literal larger than + * 0xFFFFFFFF is overflowing a 32-bit value. Use `SDL_SINT64_C(0xFFFFFFFF1)` + * instead of `0xFFFFFFFF1` by itself. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_UINT64_C + */ +#define SDL_SINT64_C(c) c ## LL /* or whatever the current compiler uses. */ + +/** + * Append the 64 bit integer suffix to an unsigned integer literal. + * + * This helps compilers that might believe a integer literal larger than + * 0xFFFFFFFF is overflowing a 32-bit value. Use `SDL_UINT64_C(0xFFFFFFFF1)` + * instead of `0xFFFFFFFF1` by itself. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_SINT64_C + */ +#define SDL_UINT64_C(c) c ## ULL /* or whatever the current compiler uses. */ + +#else /* !SDL_WIKI_DOCUMENTATION_SECTION */ + +#ifndef SDL_SINT64_C +#if defined(INT64_C) +#define SDL_SINT64_C(c) INT64_C(c) +#elif defined(_MSC_VER) +#define SDL_SINT64_C(c) c ## i64 +#elif defined(__LP64__) || defined(_LP64) +#define SDL_SINT64_C(c) c ## L +#else +#define SDL_SINT64_C(c) c ## LL +#endif +#endif /* !SDL_SINT64_C */ + +#ifndef SDL_UINT64_C +#if defined(UINT64_C) +#define SDL_UINT64_C(c) UINT64_C(c) +#elif defined(_MSC_VER) +#define SDL_UINT64_C(c) c ## ui64 +#elif defined(__LP64__) || defined(_LP64) +#define SDL_UINT64_C(c) c ## UL +#else +#define SDL_UINT64_C(c) c ## ULL +#endif +#endif /* !SDL_UINT64_C */ + +#endif /* !SDL_WIKI_DOCUMENTATION_SECTION */ + +/** + * \name Basic data types + */ +/* @{ */ + +/** + * A signed 8-bit integer type. + * + * \since This macro is available since SDL 3.2.0. + */ +typedef int8_t Sint8; +#define SDL_MAX_SINT8 ((Sint8)0x7F) /* 127 */ +#define SDL_MIN_SINT8 ((Sint8)(~0x7F)) /* -128 */ + +/** + * An unsigned 8-bit integer type. + * + * \since This macro is available since SDL 3.2.0. + */ +typedef uint8_t Uint8; +#define SDL_MAX_UINT8 ((Uint8)0xFF) /* 255 */ +#define SDL_MIN_UINT8 ((Uint8)0x00) /* 0 */ + +/** + * A signed 16-bit integer type. + * + * \since This macro is available since SDL 3.2.0. + */ +typedef int16_t Sint16; +#define SDL_MAX_SINT16 ((Sint16)0x7FFF) /* 32767 */ +#define SDL_MIN_SINT16 ((Sint16)(~0x7FFF)) /* -32768 */ + +/** + * An unsigned 16-bit integer type. + * + * \since This macro is available since SDL 3.2.0. + */ +typedef uint16_t Uint16; +#define SDL_MAX_UINT16 ((Uint16)0xFFFF) /* 65535 */ +#define SDL_MIN_UINT16 ((Uint16)0x0000) /* 0 */ + +/** + * A signed 32-bit integer type. + * + * \since This macro is available since SDL 3.2.0. + */ +typedef int32_t Sint32; +#define SDL_MAX_SINT32 ((Sint32)0x7FFFFFFF) /* 2147483647 */ +#define SDL_MIN_SINT32 ((Sint32)(~0x7FFFFFFF)) /* -2147483648 */ + +/** + * An unsigned 32-bit integer type. + * + * \since This macro is available since SDL 3.2.0. + */ +typedef uint32_t Uint32; +#define SDL_MAX_UINT32 ((Uint32)0xFFFFFFFFu) /* 4294967295 */ +#define SDL_MIN_UINT32 ((Uint32)0x00000000) /* 0 */ + +/** + * A signed 64-bit integer type. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_SINT64_C + */ +typedef int64_t Sint64; +#define SDL_MAX_SINT64 SDL_SINT64_C(0x7FFFFFFFFFFFFFFF) /* 9223372036854775807 */ +#define SDL_MIN_SINT64 ~SDL_SINT64_C(0x7FFFFFFFFFFFFFFF) /* -9223372036854775808 */ + +/** + * An unsigned 64-bit integer type. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_UINT64_C + */ +typedef uint64_t Uint64; +#define SDL_MAX_UINT64 SDL_UINT64_C(0xFFFFFFFFFFFFFFFF) /* 18446744073709551615 */ +#define SDL_MIN_UINT64 SDL_UINT64_C(0x0000000000000000) /* 0 */ + +/** + * SDL times are signed, 64-bit integers representing nanoseconds since the + * Unix epoch (Jan 1, 1970). + * + * They can be converted between POSIX time_t values with SDL_NS_TO_SECONDS() + * and SDL_SECONDS_TO_NS(), and between Windows FILETIME values with + * SDL_TimeToWindows() and SDL_TimeFromWindows(). + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_MAX_SINT64 + * \sa SDL_MIN_SINT64 + */ +typedef Sint64 SDL_Time; +#define SDL_MAX_TIME SDL_MAX_SINT64 +#define SDL_MIN_TIME SDL_MIN_SINT64 + +/* @} *//* Basic data types */ + +/** + * \name Floating-point constants + */ +/* @{ */ + +#ifdef FLT_EPSILON +#define SDL_FLT_EPSILON FLT_EPSILON +#else + +/** + * Epsilon constant, used for comparing floating-point numbers. + * + * Equals by default to platform-defined `FLT_EPSILON`, or + * `1.1920928955078125e-07F` if that's not available. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_FLT_EPSILON 1.1920928955078125e-07F /* 0x0.000002p0 */ +#endif + +/* @} *//* Floating-point constants */ + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A printf-formatting string for an Sint64 value. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRIs64 " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRIs64 "lld" + +/** + * A printf-formatting string for a Uint64 value. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRIu64 " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRIu64 "llu" + +/** + * A printf-formatting string for a Uint64 value as lower-case hexadecimal. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRIx64 " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRIx64 "llx" + +/** + * A printf-formatting string for a Uint64 value as upper-case hexadecimal. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRIX64 " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRIX64 "llX" + +/** + * A printf-formatting string for an Sint32 value. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRIs32 " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRIs32 "d" + +/** + * A printf-formatting string for a Uint32 value. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRIu32 " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRIu32 "u" + +/** + * A printf-formatting string for a Uint32 value as lower-case hexadecimal. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRIx32 " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRIx32 "x" + +/** + * A printf-formatting string for a Uint32 value as upper-case hexadecimal. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRIX32 " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRIX32 "X" + +/** + * A printf-formatting string prefix for a `long long` value. + * + * This is just the prefix! You probably actually want SDL_PRILLd, SDL_PRILLu, + * SDL_PRILLx, or SDL_PRILLX instead. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRILL_PREFIX "d bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRILL_PREFIX "ll" + +/** + * A printf-formatting string for a `long long` value. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRILLd " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRILLd SDL_PRILL_PREFIX "d" + +/** + * A printf-formatting string for a `unsigned long long` value. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRILLu " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRILLu SDL_PRILL_PREFIX "u" + +/** + * A printf-formatting string for an `unsigned long long` value as lower-case + * hexadecimal. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRILLx " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRILLx SDL_PRILL_PREFIX "x" + +/** + * A printf-formatting string for an `unsigned long long` value as upper-case + * hexadecimal. + * + * Use it like this: + * + * ```c + * SDL_Log("There are %" SDL_PRILLX " bottles of beer on the wall.", bottles); + * ``` + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRILLX SDL_PRILL_PREFIX "X" +#endif /* SDL_WIKI_DOCUMENTATION_SECTION */ + +/* Make sure we have macros for printing width-based integers. + * should define these but this is not true all platforms. + * (for example win32) */ +#ifndef SDL_PRIs64 +#if defined(SDL_PLATFORM_WINDOWS) +#define SDL_PRIs64 "I64d" +#elif defined(PRId64) +#define SDL_PRIs64 PRId64 +#elif defined(__LP64__) && !defined(SDL_PLATFORM_APPLE) && !defined(__EMSCRIPTEN__) +#define SDL_PRIs64 "ld" +#else +#define SDL_PRIs64 "lld" +#endif +#endif +#ifndef SDL_PRIu64 +#if defined(SDL_PLATFORM_WINDOWS) +#define SDL_PRIu64 "I64u" +#elif defined(PRIu64) +#define SDL_PRIu64 PRIu64 +#elif defined(__LP64__) && !defined(SDL_PLATFORM_APPLE) && !defined(__EMSCRIPTEN__) +#define SDL_PRIu64 "lu" +#else +#define SDL_PRIu64 "llu" +#endif +#endif +#ifndef SDL_PRIx64 +#if defined(SDL_PLATFORM_WINDOWS) +#define SDL_PRIx64 "I64x" +#elif defined(PRIx64) +#define SDL_PRIx64 PRIx64 +#elif defined(__LP64__) && !defined(SDL_PLATFORM_APPLE) +#define SDL_PRIx64 "lx" +#else +#define SDL_PRIx64 "llx" +#endif +#endif +#ifndef SDL_PRIX64 +#if defined(SDL_PLATFORM_WINDOWS) +#define SDL_PRIX64 "I64X" +#elif defined(PRIX64) +#define SDL_PRIX64 PRIX64 +#elif defined(__LP64__) && !defined(SDL_PLATFORM_APPLE) +#define SDL_PRIX64 "lX" +#else +#define SDL_PRIX64 "llX" +#endif +#endif +#ifndef SDL_PRIs32 +#ifdef PRId32 +#define SDL_PRIs32 PRId32 +#else +#define SDL_PRIs32 "d" +#endif +#endif +#ifndef SDL_PRIu32 +#ifdef PRIu32 +#define SDL_PRIu32 PRIu32 +#else +#define SDL_PRIu32 "u" +#endif +#endif +#ifndef SDL_PRIx32 +#ifdef PRIx32 +#define SDL_PRIx32 PRIx32 +#else +#define SDL_PRIx32 "x" +#endif +#endif +#ifndef SDL_PRIX32 +#ifdef PRIX32 +#define SDL_PRIX32 PRIX32 +#else +#define SDL_PRIX32 "X" +#endif +#endif +/* Specifically for the `long long` -- SDL-specific. */ +#ifdef SDL_PLATFORM_WINDOWS +#ifndef SDL_NOLONGLONG +SDL_COMPILE_TIME_ASSERT(longlong_size64, sizeof(long long) == 8); /* using I64 for windows - make sure `long long` is 64 bits. */ +#endif +#define SDL_PRILL_PREFIX "I64" +#else +#define SDL_PRILL_PREFIX "ll" +#endif +#ifndef SDL_PRILLd +#define SDL_PRILLd SDL_PRILL_PREFIX "d" +#endif +#ifndef SDL_PRILLu +#define SDL_PRILLu SDL_PRILL_PREFIX "u" +#endif +#ifndef SDL_PRILLx +#define SDL_PRILLx SDL_PRILL_PREFIX "x" +#endif +#ifndef SDL_PRILLX +#define SDL_PRILLX SDL_PRILL_PREFIX "X" +#endif + +/* Annotations to help code analysis tools */ +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Macro that annotates function params with input buffer size. + * + * If we were to annotate `memcpy`: + * + * ```c + * void *memcpy(void *dst, SDL_IN_BYTECAP(len) const void *src, size_t len); + * ``` + * + * This notes that `src` should be `len` bytes in size and is only read by the + * function. The compiler or other analysis tools can warn when this doesn't + * appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_IN_BYTECAP(x) _In_bytecount_(x) + +/** + * Macro that annotates function params with input/output string buffer size. + * + * If we were to annotate `strlcat`: + * + * ```c + * size_t strlcat(SDL_INOUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen); + * ``` + * + * This notes that `dst` is a null-terminated C string, should be `maxlen` + * bytes in size, and is both read from and written to by the function. The + * compiler or other analysis tools can warn when this doesn't appear to be + * the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_INOUT_Z_CAP(x) _Inout_z_cap_(x) + +/** + * Macro that annotates function params with output string buffer size. + * + * If we were to annotate `snprintf`: + * + * ```c + * int snprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt, ...); + * ``` + * + * This notes that `text` is a null-terminated C string, should be `maxlen` + * bytes in size, and is only written to by the function. The compiler or + * other analysis tools can warn when this doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_OUT_Z_CAP(x) _Out_z_cap_(x) + +/** + * Macro that annotates function params with output buffer size. + * + * If we were to annotate `wcsncpy`: + * + * ```c + * char *wcscpy(SDL_OUT_CAP(bufsize) wchar_t *dst, const wchar_t *src, size_t bufsize); + * ``` + * + * This notes that `dst` should have a capacity of `bufsize` wchar_t in size, + * and is only written to by the function. The compiler or other analysis + * tools can warn when this doesn't appear to be the case. + * + * This operates on counts of objects, not bytes. Use SDL_OUT_BYTECAP for + * bytes. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_OUT_CAP(x) _Out_cap_(x) + +/** + * Macro that annotates function params with output buffer size. + * + * If we were to annotate `memcpy`: + * + * ```c + * void *memcpy(SDL_OUT_BYTECAP(bufsize) void *dst, const void *src, size_t bufsize); + * ``` + * + * This notes that `dst` should have a capacity of `bufsize` bytes in size, + * and is only written to by the function. The compiler or other analysis + * tools can warn when this doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_OUT_BYTECAP(x) _Out_bytecap_(x) + +/** + * Macro that annotates function params with output buffer string size. + * + * If we were to annotate `strcpy`: + * + * ```c + * char *strcpy(SDL_OUT_Z_BYTECAP(bufsize) char *dst, const char *src, size_t bufsize); + * ``` + * + * This notes that `dst` should have a capacity of `bufsize` bytes in size, + * and a zero-terminated string is written to it by the function. The compiler + * or other analysis tools can warn when this doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_OUT_Z_BYTECAP(x) _Out_z_bytecap_(x) + +/** + * Macro that annotates function params as printf-style format strings. + * + * If we were to annotate `fprintf`: + * + * ```c + * int fprintf(FILE *f, SDL_PRINTF_FORMAT_STRING const char *fmt, ...); + * ``` + * + * This notes that `fmt` should be a printf-style format string. The compiler + * or other analysis tools can warn when this doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRINTF_FORMAT_STRING _Printf_format_string_ + +/** + * Macro that annotates function params as scanf-style format strings. + * + * If we were to annotate `fscanf`: + * + * ```c + * int fscanf(FILE *f, SDL_SCANF_FORMAT_STRING const char *fmt, ...); + * ``` + * + * This notes that `fmt` should be a scanf-style format string. The compiler + * or other analysis tools can warn when this doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_SCANF_FORMAT_STRING _Scanf_format_string_impl_ + +/** + * Macro that annotates a vararg function that operates like printf. + * + * If we were to annotate `fprintf`: + * + * ```c + * int fprintf(FILE *f, const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + * ``` + * + * This notes that the second parameter should be a printf-style format + * string, followed by `...`. The compiler or other analysis tools can warn + * when this doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * This can (and should) be used with SDL_PRINTF_FORMAT_STRING as well, which + * between them will cover at least Visual Studio, GCC, and Clang. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRINTF_VARARG_FUNC( fmtargnumber ) __attribute__ (( format( __printf__, fmtargnumber, fmtargnumber+1 ))) + +/** + * Macro that annotates a va_list function that operates like printf. + * + * If we were to annotate `vfprintf`: + * + * ```c + * int vfprintf(FILE *f, const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(2); + * ``` + * + * This notes that the second parameter should be a printf-style format + * string, followed by a va_list. The compiler or other analysis tools can + * warn when this doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * This can (and should) be used with SDL_PRINTF_FORMAT_STRING as well, which + * between them will cover at least Visual Studio, GCC, and Clang. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_PRINTF_VARARG_FUNCV( fmtargnumber ) __attribute__(( format( __printf__, fmtargnumber, 0 ))) + +/** + * Macro that annotates a vararg function that operates like scanf. + * + * If we were to annotate `fscanf`: + * + * ```c + * int fscanf(FILE *f, const char *fmt, ...) SDL_PRINTF_VARARG_FUNCV(2); + * ``` + * + * This notes that the second parameter should be a scanf-style format string, + * followed by `...`. The compiler or other analysis tools can warn when this + * doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * This can (and should) be used with SDL_SCANF_FORMAT_STRING as well, which + * between them will cover at least Visual Studio, GCC, and Clang. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_SCANF_VARARG_FUNC( fmtargnumber ) __attribute__ (( format( __scanf__, fmtargnumber, fmtargnumber+1 ))) + +/** + * Macro that annotates a va_list function that operates like scanf. + * + * If we were to annotate `vfscanf`: + * + * ```c + * int vfscanf(FILE *f, const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(2); + * ``` + * + * This notes that the second parameter should be a scanf-style format string, + * followed by a va_list. The compiler or other analysis tools can warn when + * this doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * This can (and should) be used with SDL_SCANF_FORMAT_STRING as well, which + * between them will cover at least Visual Studio, GCC, and Clang. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_SCANF_VARARG_FUNCV( fmtargnumber ) __attribute__(( format( __scanf__, fmtargnumber, 0 ))) + +/** + * Macro that annotates a vararg function that operates like wprintf. + * + * If we were to annotate `fwprintf`: + * + * ```c + * int fwprintf(FILE *f, const wchar_t *fmt, ...) SDL_WPRINTF_VARARG_FUNC(2); + * ``` + * + * This notes that the second parameter should be a wprintf-style format wide + * string, followed by `...`. The compiler or other analysis tools can warn + * when this doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * This can (and should) be used with SDL_PRINTF_FORMAT_STRING as well, which + * between them will cover at least Visual Studio, GCC, and Clang. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WPRINTF_VARARG_FUNC( fmtargnumber ) /* __attribute__ (( format( __wprintf__, fmtargnumber, fmtargnumber+1 ))) */ + +/** + * Macro that annotates a va_list function that operates like wprintf. + * + * If we were to annotate `vfwprintf`: + * + * ```c + * int vfwprintf(FILE *f, const wchar_t *fmt, va_list ap) SDL_WPRINTF_VARARG_FUNC(2); + * ``` + * + * This notes that the second parameter should be a wprintf-style format wide + * string, followed by a va_list. The compiler or other analysis tools can + * warn when this doesn't appear to be the case. + * + * On compilers without this annotation mechanism, this is defined to nothing. + * + * This can (and should) be used with SDL_PRINTF_FORMAT_STRING as well, which + * between them will cover at least Visual Studio, GCC, and Clang. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WPRINTF_VARARG_FUNCV( fmtargnumber ) /* __attribute__ (( format( __wprintf__, fmtargnumber, 0 ))) */ + +#elif defined(SDL_DISABLE_ANALYZE_MACROS) +#define SDL_IN_BYTECAP(x) +#define SDL_INOUT_Z_CAP(x) +#define SDL_OUT_Z_CAP(x) +#define SDL_OUT_CAP(x) +#define SDL_OUT_BYTECAP(x) +#define SDL_OUT_Z_BYTECAP(x) +#define SDL_PRINTF_FORMAT_STRING +#define SDL_SCANF_FORMAT_STRING +#define SDL_PRINTF_VARARG_FUNC( fmtargnumber ) +#define SDL_PRINTF_VARARG_FUNCV( fmtargnumber ) +#define SDL_SCANF_VARARG_FUNC( fmtargnumber ) +#define SDL_SCANF_VARARG_FUNCV( fmtargnumber ) +#define SDL_WPRINTF_VARARG_FUNC( fmtargnumber ) +#define SDL_WPRINTF_VARARG_FUNCV( fmtargnumber ) +#else +#if defined(_MSC_VER) && (_MSC_VER >= 1600) /* VS 2010 and above */ +#include + +#define SDL_IN_BYTECAP(x) _In_bytecount_(x) +#define SDL_INOUT_Z_CAP(x) _Inout_z_cap_(x) +#define SDL_OUT_Z_CAP(x) _Out_z_cap_(x) +#define SDL_OUT_CAP(x) _Out_cap_(x) +#define SDL_OUT_BYTECAP(x) _Out_bytecap_(x) +#define SDL_OUT_Z_BYTECAP(x) _Out_z_bytecap_(x) + +#define SDL_PRINTF_FORMAT_STRING _Printf_format_string_ +#define SDL_SCANF_FORMAT_STRING _Scanf_format_string_impl_ +#else +#define SDL_IN_BYTECAP(x) +#define SDL_INOUT_Z_CAP(x) +#define SDL_OUT_Z_CAP(x) +#define SDL_OUT_CAP(x) +#define SDL_OUT_BYTECAP(x) +#define SDL_OUT_Z_BYTECAP(x) +#define SDL_PRINTF_FORMAT_STRING +#define SDL_SCANF_FORMAT_STRING +#endif +#if defined(__GNUC__) || defined(__clang__) +#define SDL_PRINTF_VARARG_FUNC( fmtargnumber ) __attribute__ (( format( __printf__, fmtargnumber, fmtargnumber+1 ))) +#define SDL_PRINTF_VARARG_FUNCV( fmtargnumber ) __attribute__(( format( __printf__, fmtargnumber, 0 ))) +#define SDL_SCANF_VARARG_FUNC( fmtargnumber ) __attribute__ (( format( __scanf__, fmtargnumber, fmtargnumber+1 ))) +#define SDL_SCANF_VARARG_FUNCV( fmtargnumber ) __attribute__(( format( __scanf__, fmtargnumber, 0 ))) +#define SDL_WPRINTF_VARARG_FUNC( fmtargnumber ) /* __attribute__ (( format( __wprintf__, fmtargnumber, fmtargnumber+1 ))) */ +#define SDL_WPRINTF_VARARG_FUNCV( fmtargnumber ) /* __attribute__ (( format( __wprintf__, fmtargnumber, 0 ))) */ +#else +#define SDL_PRINTF_VARARG_FUNC( fmtargnumber ) +#define SDL_PRINTF_VARARG_FUNCV( fmtargnumber ) +#define SDL_SCANF_VARARG_FUNC( fmtargnumber ) +#define SDL_SCANF_VARARG_FUNCV( fmtargnumber ) +#define SDL_WPRINTF_VARARG_FUNC( fmtargnumber ) +#define SDL_WPRINTF_VARARG_FUNCV( fmtargnumber ) +#endif +#endif /* SDL_DISABLE_ANALYZE_MACROS */ + +/** \cond */ +#ifndef DOXYGEN_SHOULD_IGNORE_THIS +SDL_COMPILE_TIME_ASSERT(bool_size, sizeof(bool) == 1); +SDL_COMPILE_TIME_ASSERT(uint8_size, sizeof(Uint8) == 1); +SDL_COMPILE_TIME_ASSERT(sint8_size, sizeof(Sint8) == 1); +SDL_COMPILE_TIME_ASSERT(uint16_size, sizeof(Uint16) == 2); +SDL_COMPILE_TIME_ASSERT(sint16_size, sizeof(Sint16) == 2); +SDL_COMPILE_TIME_ASSERT(uint32_size, sizeof(Uint32) == 4); +SDL_COMPILE_TIME_ASSERT(sint32_size, sizeof(Sint32) == 4); +SDL_COMPILE_TIME_ASSERT(uint64_size, sizeof(Uint64) == 8); +SDL_COMPILE_TIME_ASSERT(sint64_size, sizeof(Sint64) == 8); +#ifndef SDL_NOLONGLONG +SDL_COMPILE_TIME_ASSERT(uint64_longlong, sizeof(Uint64) <= sizeof(unsigned long long)); +SDL_COMPILE_TIME_ASSERT(size_t_longlong, sizeof(size_t) <= sizeof(unsigned long long)); +#endif +typedef struct SDL_alignment_test +{ + Uint8 a; + void *b; +} SDL_alignment_test; +SDL_COMPILE_TIME_ASSERT(struct_alignment, sizeof(SDL_alignment_test) == (2 * sizeof(void *))); +SDL_COMPILE_TIME_ASSERT(two_s_complement, (int)~(int)0 == (int)(-1)); +#endif /* DOXYGEN_SHOULD_IGNORE_THIS */ +/** \endcond */ + +/* Check to make sure enums are the size of ints, for structure packing. + For both Watcom C/C++ and Borland C/C++ the compiler option that makes + enums having the size of an int must be enabled. + This is "-b" for Borland C/C++ and "-ei" for Watcom C/C++ (v11). +*/ + +/** \cond */ +#ifndef DOXYGEN_SHOULD_IGNORE_THIS +#if !defined(SDL_PLATFORM_VITA) && !defined(SDL_PLATFORM_3DS) +/* TODO: include/SDL_stdinc.h:390: error: size of array 'SDL_dummy_enum' is negative */ +typedef enum SDL_DUMMY_ENUM +{ + DUMMY_ENUM_VALUE +} SDL_DUMMY_ENUM; + +SDL_COMPILE_TIME_ASSERT(enum, sizeof(SDL_DUMMY_ENUM) == sizeof(int)); +#endif +#endif /* DOXYGEN_SHOULD_IGNORE_THIS */ +/** \endcond */ + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A macro to initialize an SDL interface. + * + * This macro will initialize an SDL interface structure and should be called + * before you fill out the fields with your implementation. + * + * You can use it like this: + * + * ```c + * SDL_IOStreamInterface iface; + * + * SDL_INIT_INTERFACE(&iface); + * + * // Fill in the interface function pointers with your implementation + * iface.seek = ... + * + * stream = SDL_OpenIO(&iface, NULL); + * ``` + * + * If you are using designated initializers, you can use the size of the + * interface as the version, e.g. + * + * ```c + * SDL_IOStreamInterface iface = { + * .version = sizeof(iface), + * .seek = ... + * }; + * stream = SDL_OpenIO(&iface, NULL); + * ``` + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_IOStreamInterface + * \sa SDL_StorageInterface + * \sa SDL_VirtualJoystickDesc + */ +#define SDL_INIT_INTERFACE(iface) \ + do { \ + SDL_zerop(iface); \ + (iface)->version = sizeof(*(iface)); \ + } while (0) + + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * Allocate memory on the stack (maybe). + * + * If SDL knows how to access alloca() on the current platform, it will use it + * to stack-allocate memory here. If it doesn't, it will use SDL_malloc() to + * heap-allocate memory. + * + * Since this might not be stack memory at all, it's important that you check + * the returned pointer for NULL, and that you call SDL_stack_free on the + * memory when done with it. Since this might be stack memory, it's important + * that you don't allocate large amounts of it, or allocate in a loop without + * returning from the function, so the stack doesn't overflow. + * + * \param type the datatype of the memory to allocate. + * \param count the number of `type` objects to allocate. + * \returns newly-allocated memory, or NULL on failure. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_stack_free + */ +#define SDL_stack_alloc(type, count) (type*)alloca(sizeof(type)*(count)) + +/** + * Free memory previously allocated with SDL_stack_alloc. + * + * If SDL used alloca() to allocate this memory, this macro does nothing and + * the allocated memory will be automatically released when the function that + * called SDL_stack_alloc() returns. If SDL used SDL_malloc(), it will + * SDL_free the memory immediately. + * + * \param data the pointer, from SDL_stack_alloc(), to free. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_stack_alloc + */ +#define SDL_stack_free(data) +#elif !defined(SDL_DISABLE_ALLOCA) +#define SDL_stack_alloc(type, count) (type*)alloca(sizeof(type)*(count)) +#define SDL_stack_free(data) +#else +#define SDL_stack_alloc(type, count) (type*)SDL_malloc(sizeof(type)*(count)) +#define SDL_stack_free(data) SDL_free(data) +#endif + +/** + * Allocate uninitialized memory. + * + * The allocated memory returned by this function must be freed with + * SDL_free(). + * + * If `size` is 0, it will be set to 1. + * + * If the allocation is successful, the returned pointer is guaranteed to be + * aligned to either the *fundamental alignment* (`alignof(max_align_t)` in + * C11 and later) or `2 * sizeof(void *)`, whichever is smaller. Use + * SDL_aligned_alloc() if you need to allocate memory aligned to an alignment + * greater than this guarantee. + * + * \param size the size to allocate. + * \returns a pointer to the allocated memory, or NULL if allocation failed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_free + * \sa SDL_calloc + * \sa SDL_realloc + * \sa SDL_aligned_alloc + */ +extern SDL_DECLSPEC SDL_MALLOC void * SDLCALL SDL_malloc(size_t size); + +/** + * Allocate a zero-initialized array. + * + * The memory returned by this function must be freed with SDL_free(). + * + * If either of `nmemb` or `size` is 0, they will both be set to 1. + * + * If the allocation is successful, the returned pointer is guaranteed to be + * aligned to either the *fundamental alignment* (`alignof(max_align_t)` in + * C11 and later) or `2 * sizeof(void *)`, whichever is smaller. + * + * \param nmemb the number of elements in the array. + * \param size the size of each element of the array. + * \returns a pointer to the allocated array, or NULL if allocation failed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_free + * \sa SDL_malloc + * \sa SDL_realloc + */ +extern SDL_DECLSPEC SDL_MALLOC SDL_ALLOC_SIZE2(1, 2) void * SDLCALL SDL_calloc(size_t nmemb, size_t size); + +/** + * Change the size of allocated memory. + * + * The memory returned by this function must be freed with SDL_free(). + * + * If `size` is 0, it will be set to 1. Note that this is unlike some other C + * runtime `realloc` implementations, which may treat `realloc(mem, 0)` the + * same way as `free(mem)`. + * + * If `mem` is NULL, the behavior of this function is equivalent to + * SDL_malloc(). Otherwise, the function can have one of three possible + * outcomes: + * + * - If it returns the same pointer as `mem`, it means that `mem` was resized + * in place without freeing. + * - If it returns a different non-NULL pointer, it means that `mem` was freed + * and cannot be dereferenced anymore. + * - If it returns NULL (indicating failure), then `mem` will remain valid and + * must still be freed with SDL_free(). + * + * If the allocation is successfully resized, the returned pointer is + * guaranteed to be aligned to either the *fundamental alignment* + * (`alignof(max_align_t)` in C11 and later) or `2 * sizeof(void *)`, + * whichever is smaller. + * + * \param mem a pointer to allocated memory to reallocate, or NULL. + * \param size the new size of the memory. + * \returns a pointer to the newly allocated memory, or NULL if allocation + * failed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_free + * \sa SDL_malloc + * \sa SDL_calloc + */ +extern SDL_DECLSPEC SDL_ALLOC_SIZE(2) void * SDLCALL SDL_realloc(void *mem, size_t size); + +/** + * Free allocated memory. + * + * The pointer is no longer valid after this call and cannot be dereferenced + * anymore. + * + * If `mem` is NULL, this function does nothing. + * + * \param mem a pointer to allocated memory, or NULL. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_malloc + * \sa SDL_calloc + * \sa SDL_realloc + */ +extern SDL_DECLSPEC void SDLCALL SDL_free(void *mem); + +/** + * A callback used to implement SDL_malloc(). + * + * SDL will always ensure that the passed `size` is greater than 0. + * + * \param size the size to allocate. + * \returns a pointer to the allocated memory, or NULL if allocation failed. + * + * \threadsafety It should be safe to call this callback from any thread. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_malloc + * \sa SDL_GetOriginalMemoryFunctions + * \sa SDL_GetMemoryFunctions + * \sa SDL_SetMemoryFunctions + */ +typedef void *(SDLCALL *SDL_malloc_func)(size_t size); + +/** + * A callback used to implement SDL_calloc(). + * + * SDL will always ensure that the passed `nmemb` and `size` are both greater + * than 0. + * + * \param nmemb the number of elements in the array. + * \param size the size of each element of the array. + * \returns a pointer to the allocated array, or NULL if allocation failed. + * + * \threadsafety It should be safe to call this callback from any thread. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_calloc + * \sa SDL_GetOriginalMemoryFunctions + * \sa SDL_GetMemoryFunctions + * \sa SDL_SetMemoryFunctions + */ +typedef void *(SDLCALL *SDL_calloc_func)(size_t nmemb, size_t size); + +/** + * A callback used to implement SDL_realloc(). + * + * SDL will always ensure that the passed `size` is greater than 0. + * + * \param mem a pointer to allocated memory to reallocate, or NULL. + * \param size the new size of the memory. + * \returns a pointer to the newly allocated memory, or NULL if allocation + * failed. + * + * \threadsafety It should be safe to call this callback from any thread. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_realloc + * \sa SDL_GetOriginalMemoryFunctions + * \sa SDL_GetMemoryFunctions + * \sa SDL_SetMemoryFunctions + */ +typedef void *(SDLCALL *SDL_realloc_func)(void *mem, size_t size); + +/** + * A callback used to implement SDL_free(). + * + * SDL will always ensure that the passed `mem` is a non-NULL pointer. + * + * \param mem a pointer to allocated memory. + * + * \threadsafety It should be safe to call this callback from any thread. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_free + * \sa SDL_GetOriginalMemoryFunctions + * \sa SDL_GetMemoryFunctions + * \sa SDL_SetMemoryFunctions + */ +typedef void (SDLCALL *SDL_free_func)(void *mem); + +/** + * Get the original set of SDL memory functions. + * + * This is what SDL_malloc and friends will use by default, if there has been + * no call to SDL_SetMemoryFunctions. This is not necessarily using the C + * runtime's `malloc` functions behind the scenes! Different platforms and + * build configurations might do any number of unexpected things. + * + * \param malloc_func filled with malloc function. + * \param calloc_func filled with calloc function. + * \param realloc_func filled with realloc function. + * \param free_func filled with free function. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_GetOriginalMemoryFunctions(SDL_malloc_func *malloc_func, + SDL_calloc_func *calloc_func, + SDL_realloc_func *realloc_func, + SDL_free_func *free_func); + +/** + * Get the current set of SDL memory functions. + * + * \param malloc_func filled with malloc function. + * \param calloc_func filled with calloc function. + * \param realloc_func filled with realloc function. + * \param free_func filled with free function. + * + * \threadsafety This does not hold a lock, so do not call this in the + * unlikely event of a background thread calling + * SDL_SetMemoryFunctions simultaneously. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetMemoryFunctions + * \sa SDL_GetOriginalMemoryFunctions + */ +extern SDL_DECLSPEC void SDLCALL SDL_GetMemoryFunctions(SDL_malloc_func *malloc_func, + SDL_calloc_func *calloc_func, + SDL_realloc_func *realloc_func, + SDL_free_func *free_func); + +/** + * Replace SDL's memory allocation functions with a custom set. + * + * It is not safe to call this function once any allocations have been made, + * as future calls to SDL_free will use the new allocator, even if they came + * from an SDL_malloc made with the old one! + * + * If used, usually this needs to be the first call made into the SDL library, + * if not the very first thing done at program startup time. + * + * \param malloc_func custom malloc function. + * \param calloc_func custom calloc function. + * \param realloc_func custom realloc function. + * \param free_func custom free function. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread, but one + * should not replace the memory functions once any allocations + * are made! + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetMemoryFunctions + * \sa SDL_GetOriginalMemoryFunctions + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetMemoryFunctions(SDL_malloc_func malloc_func, + SDL_calloc_func calloc_func, + SDL_realloc_func realloc_func, + SDL_free_func free_func); + +/** + * Allocate memory aligned to a specific alignment. + * + * The memory returned by this function must be freed with SDL_aligned_free(), + * _not_ SDL_free(). + * + * If `alignment` is less than the size of `void *`, it will be increased to + * match that. + * + * The returned memory address will be a multiple of the alignment value, and + * the size of the memory allocated will be a multiple of the alignment value. + * + * \param alignment the alignment of the memory. + * \param size the size to allocate. + * \returns a pointer to the aligned memory, or NULL if allocation failed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_aligned_free + */ +extern SDL_DECLSPEC SDL_MALLOC void * SDLCALL SDL_aligned_alloc(size_t alignment, size_t size); + +/** + * Free memory allocated by SDL_aligned_alloc(). + * + * The pointer is no longer valid after this call and cannot be dereferenced + * anymore. + * + * If `mem` is NULL, this function does nothing. + * + * \param mem a pointer previously returned by SDL_aligned_alloc(), or NULL. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_aligned_alloc + */ +extern SDL_DECLSPEC void SDLCALL SDL_aligned_free(void *mem); + +/** + * Get the number of outstanding (unfreed) allocations. + * + * \returns the number of allocations or -1 if allocation counting is + * disabled. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumAllocations(void); + +/** + * A thread-safe set of environment variables + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_GetEnvironment + * \sa SDL_CreateEnvironment + * \sa SDL_GetEnvironmentVariable + * \sa SDL_GetEnvironmentVariables + * \sa SDL_SetEnvironmentVariable + * \sa SDL_UnsetEnvironmentVariable + * \sa SDL_DestroyEnvironment + */ +typedef struct SDL_Environment SDL_Environment; + +/** + * Get the process environment. + * + * This is initialized at application start and is not affected by setenv() + * and unsetenv() calls after that point. Use SDL_SetEnvironmentVariable() and + * SDL_UnsetEnvironmentVariable() if you want to modify this environment, or + * SDL_setenv_unsafe() or SDL_unsetenv_unsafe() if you want changes to persist + * in the C runtime environment after SDL_Quit(). + * + * \returns a pointer to the environment for the process or NULL on failure; + * call SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetEnvironmentVariable + * \sa SDL_GetEnvironmentVariables + * \sa SDL_SetEnvironmentVariable + * \sa SDL_UnsetEnvironmentVariable + */ +extern SDL_DECLSPEC SDL_Environment * SDLCALL SDL_GetEnvironment(void); + +/** + * Create a set of environment variables + * + * \param populated true to initialize it from the C runtime environment, + * false to create an empty environment. + * \returns a pointer to the new environment or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety If `populated` is false, it is safe to call this function + * from any thread, otherwise it is safe if no other threads are + * calling setenv() or unsetenv() + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetEnvironmentVariable + * \sa SDL_GetEnvironmentVariables + * \sa SDL_SetEnvironmentVariable + * \sa SDL_UnsetEnvironmentVariable + * \sa SDL_DestroyEnvironment + */ +extern SDL_DECLSPEC SDL_Environment * SDLCALL SDL_CreateEnvironment(bool populated); + +/** + * Get the value of a variable in the environment. + * + * \param env the environment to query. + * \param name the name of the variable to get. + * \returns a pointer to the value of the variable or NULL if it can't be + * found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetEnvironment + * \sa SDL_CreateEnvironment + * \sa SDL_GetEnvironmentVariables + * \sa SDL_SetEnvironmentVariable + * \sa SDL_UnsetEnvironmentVariable + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetEnvironmentVariable(SDL_Environment *env, const char *name); + +/** + * Get all variables in the environment. + * + * \param env the environment to query. + * \returns a NULL terminated array of pointers to environment variables in + * the form "variable=value" or NULL on failure; call SDL_GetError() + * for more information. This is a single allocation that should be + * freed with SDL_free() when it is no longer needed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetEnvironment + * \sa SDL_CreateEnvironment + * \sa SDL_GetEnvironmentVariables + * \sa SDL_SetEnvironmentVariable + * \sa SDL_UnsetEnvironmentVariable + */ +extern SDL_DECLSPEC char ** SDLCALL SDL_GetEnvironmentVariables(SDL_Environment *env); + +/** + * Set the value of a variable in the environment. + * + * \param env the environment to modify. + * \param name the name of the variable to set. + * \param value the value of the variable to set. + * \param overwrite true to overwrite the variable if it exists, false to + * return success without setting the variable if it already + * exists. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetEnvironment + * \sa SDL_CreateEnvironment + * \sa SDL_GetEnvironmentVariable + * \sa SDL_GetEnvironmentVariables + * \sa SDL_UnsetEnvironmentVariable + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetEnvironmentVariable(SDL_Environment *env, const char *name, const char *value, bool overwrite); + +/** + * Clear a variable from the environment. + * + * \param env the environment to modify. + * \param name the name of the variable to unset. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetEnvironment + * \sa SDL_CreateEnvironment + * \sa SDL_GetEnvironmentVariable + * \sa SDL_GetEnvironmentVariables + * \sa SDL_SetEnvironmentVariable + * \sa SDL_UnsetEnvironmentVariable + */ +extern SDL_DECLSPEC bool SDLCALL SDL_UnsetEnvironmentVariable(SDL_Environment *env, const char *name); + +/** + * Destroy a set of environment variables. + * + * \param env the environment to destroy. + * + * \threadsafety It is safe to call this function from any thread, as long as + * the environment is no longer in use. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateEnvironment + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyEnvironment(SDL_Environment *env); + +/** + * Get the value of a variable in the environment. + * + * This function uses SDL's cached copy of the environment and is thread-safe. + * + * \param name the name of the variable to get. + * \returns a pointer to the value of the variable or NULL if it can't be + * found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_getenv(const char *name); + +/** + * Get the value of a variable in the environment. + * + * This function bypasses SDL's cached copy of the environment and is not + * thread-safe. + * + * \param name the name of the variable to get. + * \returns a pointer to the value of the variable or NULL if it can't be + * found. + * + * \threadsafety This function is not thread safe, consider using SDL_getenv() + * instead. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_getenv + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_getenv_unsafe(const char *name); + +/** + * Set the value of a variable in the environment. + * + * \param name the name of the variable to set. + * \param value the value of the variable to set. + * \param overwrite 1 to overwrite the variable if it exists, 0 to return + * success without setting the variable if it already exists. + * \returns 0 on success, -1 on error. + * + * \threadsafety This function is not thread safe, consider using + * SDL_SetEnvironmentVariable() instead. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetEnvironmentVariable + */ +extern SDL_DECLSPEC int SDLCALL SDL_setenv_unsafe(const char *name, const char *value, int overwrite); + +/** + * Clear a variable from the environment. + * + * \param name the name of the variable to unset. + * \returns 0 on success, -1 on error. + * + * \threadsafety This function is not thread safe, consider using + * SDL_UnsetEnvironmentVariable() instead. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_UnsetEnvironmentVariable + */ +extern SDL_DECLSPEC int SDLCALL SDL_unsetenv_unsafe(const char *name); + +/** + * A callback used with SDL sorting and binary search functions. + * + * \param a a pointer to the first element being compared. + * \param b a pointer to the second element being compared. + * \returns -1 if `a` should be sorted before `b`, 1 if `b` should be sorted + * before `a`, 0 if they are equal. If two elements are equal, their + * order in the sorted array is undefined. + * + * \since This callback is available since SDL 3.2.0. + * + * \sa SDL_bsearch + * \sa SDL_qsort + */ +typedef int (SDLCALL *SDL_CompareCallback)(const void *a, const void *b); + +/** + * Sort an array. + * + * For example: + * + * ```c + * typedef struct { + * int key; + * const char *string; + * } data; + * + * int SDLCALL compare(const void *a, const void *b) + * { + * const data *A = (const data *)a; + * const data *B = (const data *)b; + * + * if (A->n < B->n) { + * return -1; + * } else if (B->n < A->n) { + * return 1; + * } else { + * return 0; + * } + * } + * + * data values[] = { + * { 3, "third" }, { 1, "first" }, { 2, "second" } + * }; + * + * SDL_qsort(values, SDL_arraysize(values), sizeof(values[0]), compare); + * ``` + * + * \param base a pointer to the start of the array. + * \param nmemb the number of elements in the array. + * \param size the size of the elements in the array. + * \param compare a function used to compare elements in the array. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_bsearch + * \sa SDL_qsort_r + */ +extern SDL_DECLSPEC void SDLCALL SDL_qsort(void *base, size_t nmemb, size_t size, SDL_CompareCallback compare); + +/** + * Perform a binary search on a previously sorted array. + * + * For example: + * + * ```c + * typedef struct { + * int key; + * const char *string; + * } data; + * + * int SDLCALL compare(const void *a, const void *b) + * { + * const data *A = (const data *)a; + * const data *B = (const data *)b; + * + * if (A->n < B->n) { + * return -1; + * } else if (B->n < A->n) { + * return 1; + * } else { + * return 0; + * } + * } + * + * data values[] = { + * { 1, "first" }, { 2, "second" }, { 3, "third" } + * }; + * data key = { 2, NULL }; + * + * data *result = SDL_bsearch(&key, values, SDL_arraysize(values), sizeof(values[0]), compare); + * ``` + * + * \param key a pointer to a key equal to the element being searched for. + * \param base a pointer to the start of the array. + * \param nmemb the number of elements in the array. + * \param size the size of the elements in the array. + * \param compare a function used to compare elements in the array. + * \returns a pointer to the matching element in the array, or NULL if not + * found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_bsearch_r + * \sa SDL_qsort + */ +extern SDL_DECLSPEC void * SDLCALL SDL_bsearch(const void *key, const void *base, size_t nmemb, size_t size, SDL_CompareCallback compare); + +/** + * A callback used with SDL sorting and binary search functions. + * + * \param userdata the `userdata` pointer passed to the sort function. + * \param a a pointer to the first element being compared. + * \param b a pointer to the second element being compared. + * \returns -1 if `a` should be sorted before `b`, 1 if `b` should be sorted + * before `a`, 0 if they are equal. If two elements are equal, their + * order in the sorted array is undefined. + * + * \since This callback is available since SDL 3.2.0. + * + * \sa SDL_qsort_r + * \sa SDL_bsearch_r + */ +typedef int (SDLCALL *SDL_CompareCallback_r)(void *userdata, const void *a, const void *b); + +/** + * Sort an array, passing a userdata pointer to the compare function. + * + * For example: + * + * ```c + * typedef enum { + * sort_increasing, + * sort_decreasing, + * } sort_method; + * + * typedef struct { + * int key; + * const char *string; + * } data; + * + * int SDLCALL compare(const void *userdata, const void *a, const void *b) + * { + * sort_method method = (sort_method)(uintptr_t)userdata; + * const data *A = (const data *)a; + * const data *B = (const data *)b; + * + * if (A->key < B->key) { + * return (method == sort_increasing) ? -1 : 1; + * } else if (B->key < A->key) { + * return (method == sort_increasing) ? 1 : -1; + * } else { + * return 0; + * } + * } + * + * data values[] = { + * { 3, "third" }, { 1, "first" }, { 2, "second" } + * }; + * + * SDL_qsort_r(values, SDL_arraysize(values), sizeof(values[0]), compare, (const void *)(uintptr_t)sort_increasing); + * ``` + * + * \param base a pointer to the start of the array. + * \param nmemb the number of elements in the array. + * \param size the size of the elements in the array. + * \param compare a function used to compare elements in the array. + * \param userdata a pointer to pass to the compare function. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_bsearch_r + * \sa SDL_qsort + */ +extern SDL_DECLSPEC void SDLCALL SDL_qsort_r(void *base, size_t nmemb, size_t size, SDL_CompareCallback_r compare, void *userdata); + +/** + * Perform a binary search on a previously sorted array, passing a userdata + * pointer to the compare function. + * + * For example: + * + * ```c + * typedef enum { + * sort_increasing, + * sort_decreasing, + * } sort_method; + * + * typedef struct { + * int key; + * const char *string; + * } data; + * + * int SDLCALL compare(const void *userdata, const void *a, const void *b) + * { + * sort_method method = (sort_method)(uintptr_t)userdata; + * const data *A = (const data *)a; + * const data *B = (const data *)b; + * + * if (A->key < B->key) { + * return (method == sort_increasing) ? -1 : 1; + * } else if (B->key < A->key) { + * return (method == sort_increasing) ? 1 : -1; + * } else { + * return 0; + * } + * } + * + * data values[] = { + * { 1, "first" }, { 2, "second" }, { 3, "third" } + * }; + * data key = { 2, NULL }; + * + * data *result = SDL_bsearch_r(&key, values, SDL_arraysize(values), sizeof(values[0]), compare, (const void *)(uintptr_t)sort_increasing); + * ``` + * + * \param key a pointer to a key equal to the element being searched for. + * \param base a pointer to the start of the array. + * \param nmemb the number of elements in the array. + * \param size the size of the elements in the array. + * \param compare a function used to compare elements in the array. + * \param userdata a pointer to pass to the compare function. + * \returns a pointer to the matching element in the array, or NULL if not + * found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_bsearch + * \sa SDL_qsort_r + */ +extern SDL_DECLSPEC void * SDLCALL SDL_bsearch_r(const void *key, const void *base, size_t nmemb, size_t size, SDL_CompareCallback_r compare, void *userdata); + +/** + * Compute the absolute value of `x`. + * + * \param x an integer value. + * \returns the absolute value of x. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_abs(int x); + +/** + * Return the lesser of two values. + * + * This is a helper macro that might be more clear than writing out the + * comparisons directly, and works with any type that can be compared with the + * `<` operator. However, it double-evaluates both its parameters, so do not + * use expressions with side-effects here. + * + * \param x the first value to compare. + * \param y the second value to compare. + * \returns the lesser of `x` and `y`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_min(x, y) (((x) < (y)) ? (x) : (y)) + +/** + * Return the greater of two values. + * + * This is a helper macro that might be more clear than writing out the + * comparisons directly, and works with any type that can be compared with the + * `>` operator. However, it double-evaluates both its parameters, so do not + * use expressions with side-effects here. + * + * \param x the first value to compare. + * \param y the second value to compare. + * \returns the lesser of `x` and `y`. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_max(x, y) (((x) > (y)) ? (x) : (y)) + +/** + * Return a value clamped to a range. + * + * If `x` is outside the range a values between `a` and `b`, the returned + * value will be `a` or `b` as appropriate. Otherwise, `x` is returned. + * + * This macro will produce incorrect results if `b` is less than `a`. + * + * This is a helper macro that might be more clear than writing out the + * comparisons directly, and works with any type that can be compared with the + * `<` and `>` operators. However, it double-evaluates all its parameters, so + * do not use expressions with side-effects here. + * + * \param x the value to compare. + * \param a the low end value. + * \param b the high end value. + * \returns x, clamped between a and b. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_clamp(x, a, b) (((x) < (a)) ? (a) : (((x) > (b)) ? (b) : (x))) + +/** + * Query if a character is alphabetic (a letter). + * + * **WARNING**: Regardless of system locale, this will only treat ASCII values + * for English 'a-z' and 'A-Z' as true. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_isalpha(int x); + +/** + * Query if a character is alphabetic (a letter) or a number. + * + * **WARNING**: Regardless of system locale, this will only treat ASCII values + * for English 'a-z', 'A-Z', and '0-9' as true. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_isalnum(int x); + +/** + * Report if a character is blank (a space or tab). + * + * **WARNING**: Regardless of system locale, this will only treat ASCII values + * 0x20 (space) or 0x9 (tab) as true. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_isblank(int x); + +/** + * Report if a character is a control character. + * + * **WARNING**: Regardless of system locale, this will only treat ASCII values + * 0 through 0x1F, and 0x7F, as true. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_iscntrl(int x); + +/** + * Report if a character is a numeric digit. + * + * **WARNING**: Regardless of system locale, this will only treat ASCII values + * '0' (0x30) through '9' (0x39), as true. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_isdigit(int x); + +/** + * Report if a character is a hexadecimal digit. + * + * **WARNING**: Regardless of system locale, this will only treat ASCII values + * 'A' through 'F', 'a' through 'f', and '0' through '9', as true. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_isxdigit(int x); + +/** + * Report if a character is a punctuation mark. + * + * **WARNING**: Regardless of system locale, this is equivalent to + * `((SDL_isgraph(x)) && (!SDL_isalnum(x)))`. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_isgraph + * \sa SDL_isalnum + */ +extern SDL_DECLSPEC int SDLCALL SDL_ispunct(int x); + +/** + * Report if a character is whitespace. + * + * **WARNING**: Regardless of system locale, this will only treat the + * following ASCII values as true: + * + * - space (0x20) + * - tab (0x09) + * - newline (0x0A) + * - vertical tab (0x0B) + * - form feed (0x0C) + * - return (0x0D) + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_isspace(int x); + +/** + * Report if a character is upper case. + * + * **WARNING**: Regardless of system locale, this will only treat ASCII values + * 'A' through 'Z' as true. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_isupper(int x); + +/** + * Report if a character is lower case. + * + * **WARNING**: Regardless of system locale, this will only treat ASCII values + * 'a' through 'z' as true. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_islower(int x); + +/** + * Report if a character is "printable". + * + * Be advised that "printable" has a definition that goes back to text + * terminals from the dawn of computing, making this a sort of special case + * function that is not suitable for Unicode (or most any) text management. + * + * **WARNING**: Regardless of system locale, this will only treat ASCII values + * ' ' (0x20) through '~' (0x7E) as true. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_isprint(int x); + +/** + * Report if a character is any "printable" except space. + * + * Be advised that "printable" has a definition that goes back to text + * terminals from the dawn of computing, making this a sort of special case + * function that is not suitable for Unicode (or most any) text management. + * + * **WARNING**: Regardless of system locale, this is equivalent to + * `(SDL_isprint(x)) && ((x) != ' ')`. + * + * \param x character value to check. + * \returns non-zero if x falls within the character class, zero otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_isprint + */ +extern SDL_DECLSPEC int SDLCALL SDL_isgraph(int x); + +/** + * Convert low-ASCII English letters to uppercase. + * + * **WARNING**: Regardless of system locale, this will only convert ASCII + * values 'a' through 'z' to uppercase. + * + * This function returns the uppercase equivalent of `x`. If a character + * cannot be converted, or is already uppercase, this function returns `x`. + * + * \param x character value to check. + * \returns capitalized version of x, or x if no conversion available. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_toupper(int x); + +/** + * Convert low-ASCII English letters to lowercase. + * + * **WARNING**: Regardless of system locale, this will only convert ASCII + * values 'A' through 'Z' to lowercase. + * + * This function returns the lowercase equivalent of `x`. If a character + * cannot be converted, or is already lowercase, this function returns `x`. + * + * \param x character value to check. + * \returns lowercase version of x, or x if no conversion available. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_tolower(int x); + +/** + * Calculate a CRC-16 value. + * + * https://en.wikipedia.org/wiki/Cyclic_redundancy_check + * + * This function can be called multiple times, to stream data to be + * checksummed in blocks. Each call must provide the previous CRC-16 return + * value to be updated with the next block. The first call to this function + * for a set of blocks should pass in a zero CRC value. + * + * \param crc the current checksum for this data set, or 0 for a new data set. + * \param data a new block of data to add to the checksum. + * \param len the size, in bytes, of the new block of data. + * \returns a CRC-16 checksum value of all blocks in the data set. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint16 SDLCALL SDL_crc16(Uint16 crc, const void *data, size_t len); + +/** + * Calculate a CRC-32 value. + * + * https://en.wikipedia.org/wiki/Cyclic_redundancy_check + * + * This function can be called multiple times, to stream data to be + * checksummed in blocks. Each call must provide the previous CRC-32 return + * value to be updated with the next block. The first call to this function + * for a set of blocks should pass in a zero CRC value. + * + * \param crc the current checksum for this data set, or 0 for a new data set. + * \param data a new block of data to add to the checksum. + * \param len the size, in bytes, of the new block of data. + * \returns a CRC-32 checksum value of all blocks in the data set. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_crc32(Uint32 crc, const void *data, size_t len); + +/** + * Calculate a 32-bit MurmurHash3 value for a block of data. + * + * https://en.wikipedia.org/wiki/MurmurHash + * + * A seed may be specified, which changes the final results consistently, but + * this does not work like SDL_crc16 and SDL_crc32: you can't feed a previous + * result from this function back into itself as the next seed value to + * calculate a hash in chunks; it won't produce the same hash as it would if + * the same data was provided in a single call. + * + * If you aren't sure what to provide for a seed, zero is fine. Murmur3 is not + * cryptographically secure, so it shouldn't be used for hashing top-secret + * data. + * + * \param data the data to be hashed. + * \param len the size of data, in bytes. + * \param seed a value that alters the final hash value. + * \returns a Murmur3 32-bit hash value. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_murmur3_32(const void *data, size_t len, Uint32 seed); + +/** + * Copy non-overlapping memory. + * + * The memory regions must not overlap. If they do, use SDL_memmove() instead. + * + * \param dst The destination memory region. Must not be NULL, and must not + * overlap with `src`. + * \param src The source memory region. Must not be NULL, and must not overlap + * with `dst`. + * \param len The length in bytes of both `dst` and `src`. + * \returns `dst`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_memmove + */ +extern SDL_DECLSPEC void * SDLCALL SDL_memcpy(SDL_OUT_BYTECAP(len) void *dst, SDL_IN_BYTECAP(len) const void *src, size_t len); + +/* Take advantage of compiler optimizations for memcpy */ +#ifndef SDL_SLOW_MEMCPY +#ifdef SDL_memcpy +#undef SDL_memcpy +#endif +#define SDL_memcpy memcpy +#endif + + +/** + * A macro to copy memory between objects, with basic type checking. + * + * SDL_memcpy and SDL_memmove do not care where you copy memory to and from, + * which can lead to bugs. This macro aims to avoid most of those bugs by + * making sure that the source and destination are both pointers to objects + * that are the same size. It does not check that the objects are the same + * _type_, just that the copy will not overflow either object. + * + * The size check happens at compile time, and the compiler will throw an + * error if the objects are different sizes. + * + * Generally this is intended to copy a single object, not an array. + * + * This macro looks like it double-evaluates its parameters, but the extras + * them are in `sizeof` sections, which generate no code nor side-effects. + * + * \param dst a pointer to the destination object. Must not be NULL. + * \param src a pointer to the source object. Must not be NULL. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +#define SDL_copyp(dst, src) \ + { SDL_COMPILE_TIME_ASSERT(SDL_copyp, sizeof (*(dst)) == sizeof (*(src))); } \ + SDL_memcpy((dst), (src), sizeof(*(src))) + +/** + * Copy memory ranges that might overlap. + * + * It is okay for the memory regions to overlap. If you are confident that the + * regions never overlap, using SDL_memcpy() may improve performance. + * + * \param dst The destination memory region. Must not be NULL. + * \param src The source memory region. Must not be NULL. + * \param len The length in bytes of both `dst` and `src`. + * \returns `dst`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_memcpy + */ +extern SDL_DECLSPEC void * SDLCALL SDL_memmove(SDL_OUT_BYTECAP(len) void *dst, SDL_IN_BYTECAP(len) const void *src, size_t len); + +/* Take advantage of compiler optimizations for memmove */ +#ifndef SDL_SLOW_MEMMOVE +#ifdef SDL_memmove +#undef SDL_memmove +#endif +#define SDL_memmove memmove +#endif + +/** + * Initialize all bytes of buffer of memory to a specific value. + * + * This function will set `len` bytes, pointed to by `dst`, to the value + * specified in `c`. + * + * Despite `c` being an `int` instead of a `char`, this only operates on + * bytes; `c` must be a value between 0 and 255, inclusive. + * + * \param dst the destination memory region. Must not be NULL. + * \param c the byte value to set. + * \param len the length, in bytes, to set in `dst`. + * \returns `dst`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void * SDLCALL SDL_memset(SDL_OUT_BYTECAP(len) void *dst, int c, size_t len); + +/** + * Initialize all 32-bit words of buffer of memory to a specific value. + * + * This function will set a buffer of `dwords` Uint32 values, pointed to by + * `dst`, to the value specified in `val`. + * + * Unlike SDL_memset, this sets 32-bit values, not bytes, so it's not limited + * to a range of 0-255. + * + * \param dst the destination memory region. Must not be NULL. + * \param val the Uint32 value to set. + * \param dwords the number of Uint32 values to set in `dst`. + * \returns `dst`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void * SDLCALL SDL_memset4(void *dst, Uint32 val, size_t dwords); + +/* Take advantage of compiler optimizations for memset */ +#ifndef SDL_SLOW_MEMSET +#ifdef SDL_memset +#undef SDL_memset +#endif +#define SDL_memset memset +#endif + +/** + * Clear an object's memory to zero. + * + * This is wrapper over SDL_memset that handles calculating the object size, + * so there's no chance of copy/paste errors, and the code is cleaner. + * + * This requires an object, not a pointer to an object, nor an array. + * + * \param x the object to clear. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_zerop + * \sa SDL_zeroa + */ +#define SDL_zero(x) SDL_memset(&(x), 0, sizeof((x))) + +/** + * Clear an object's memory to zero, using a pointer. + * + * This is wrapper over SDL_memset that handles calculating the object size, + * so there's no chance of copy/paste errors, and the code is cleaner. + * + * This requires a pointer to an object, not an object itself, nor an array. + * + * \param x a pointer to the object to clear. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_zero + * \sa SDL_zeroa + */ +#define SDL_zerop(x) SDL_memset((x), 0, sizeof(*(x))) + +/** + * Clear an array's memory to zero. + * + * This is wrapper over SDL_memset that handles calculating the array size, so + * there's no chance of copy/paste errors, and the code is cleaner. + * + * This requires an array, not an object, nor a pointer to an object. + * + * \param x an array to clear. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_zero + * \sa SDL_zeroa + */ +#define SDL_zeroa(x) SDL_memset((x), 0, sizeof((x))) + + +/** + * Compare two buffers of memory. + * + * \param s1 the first buffer to compare. NULL is not permitted! + * \param s2 the second buffer to compare. NULL is not permitted! + * \param len the number of bytes to compare between the buffers. + * \returns less than zero if s1 is "less than" s2, greater than zero if s1 is + * "greater than" s2, and zero if the buffers match exactly for `len` + * bytes. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_memcmp(const void *s1, const void *s2, size_t len); + +/** + * This works exactly like wcslen() but doesn't require access to a C runtime. + * + * Counts the number of wchar_t values in `wstr`, excluding the null + * terminator. + * + * Like SDL_strlen only counts bytes and not codepoints in a UTF-8 string, + * this counts wchar_t values in a string, even if the string's encoding is of + * variable width, like UTF-16. + * + * Also be aware that wchar_t is different sizes on different platforms (4 + * bytes on Linux, 2 on Windows, etc). + * + * \param wstr The null-terminated wide string to read. Must not be NULL. + * \returns the length (in wchar_t values, excluding the null terminator) of + * `wstr`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_wcsnlen + * \sa SDL_utf8strlen + * \sa SDL_utf8strnlen + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_wcslen(const wchar_t *wstr); + +/** + * This works exactly like wcsnlen() but doesn't require access to a C + * runtime. + * + * Counts up to a maximum of `maxlen` wchar_t values in `wstr`, excluding the + * null terminator. + * + * Like SDL_strnlen only counts bytes and not codepoints in a UTF-8 string, + * this counts wchar_t values in a string, even if the string's encoding is of + * variable width, like UTF-16. + * + * Also be aware that wchar_t is different sizes on different platforms (4 + * bytes on Linux, 2 on Windows, etc). + * + * Also, `maxlen` is a count of wide characters, not bytes! + * + * \param wstr The null-terminated wide string to read. Must not be NULL. + * \param maxlen The maximum amount of wide characters to count. + * \returns the length (in wide characters, excluding the null terminator) of + * `wstr` but never more than `maxlen`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_wcslen + * \sa SDL_utf8strlen + * \sa SDL_utf8strnlen + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_wcsnlen(const wchar_t *wstr, size_t maxlen); + +/** + * Copy a wide string. + * + * This function copies `maxlen` - 1 wide characters from `src` to `dst`, then + * appends a null terminator. + * + * `src` and `dst` must not overlap. + * + * If `maxlen` is 0, no wide characters are copied and no null terminator is + * written. + * + * \param dst The destination buffer. Must not be NULL, and must not overlap + * with `src`. + * \param src The null-terminated wide string to copy. Must not be NULL, and + * must not overlap with `dst`. + * \param maxlen The length (in wide characters) of the destination buffer. + * \returns the length (in wide characters, excluding the null terminator) of + * `src`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_wcslcat + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_wcslcpy(SDL_OUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t maxlen); + +/** + * Concatenate wide strings. + * + * This function appends up to `maxlen` - SDL_wcslen(dst) - 1 wide characters + * from `src` to the end of the wide string in `dst`, then appends a null + * terminator. + * + * `src` and `dst` must not overlap. + * + * If `maxlen` - SDL_wcslen(dst) - 1 is less than or equal to 0, then `dst` is + * unmodified. + * + * \param dst The destination buffer already containing the first + * null-terminated wide string. Must not be NULL and must not + * overlap with `src`. + * \param src The second null-terminated wide string. Must not be NULL, and + * must not overlap with `dst`. + * \param maxlen The length (in wide characters) of the destination buffer. + * \returns the length (in wide characters, excluding the null terminator) of + * the string in `dst` plus the length of `src`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_wcslcpy + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_wcslcat(SDL_INOUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t maxlen); + +/** + * Allocate a copy of a wide string. + * + * This allocates enough space for a null-terminated copy of `wstr`, using + * SDL_malloc, and then makes a copy of the string into this space. + * + * The returned string is owned by the caller, and should be passed to + * SDL_free when no longer needed. + * + * \param wstr the string to copy. + * \returns a pointer to the newly-allocated wide string. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC wchar_t * SDLCALL SDL_wcsdup(const wchar_t *wstr); + +/** + * Search a wide string for the first instance of a specific substring. + * + * The search ends once it finds the requested substring, or a null terminator + * byte to end the string. + * + * Note that this looks for strings of _wide characters_, not _codepoints_, so + * it's legal to search for malformed and incomplete UTF-16 sequences. + * + * \param haystack the wide string to search. Must not be NULL. + * \param needle the wide string to search for. Must not be NULL. + * \returns a pointer to the first instance of `needle` in the string, or NULL + * if not found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC wchar_t * SDLCALL SDL_wcsstr(const wchar_t *haystack, const wchar_t *needle); + +/** + * Search a wide string, up to n wide chars, for the first instance of a + * specific substring. + * + * The search ends once it finds the requested substring, or a null terminator + * value to end the string, or `maxlen` wide character have been examined. It + * is possible to use this function on a wide string without a null + * terminator. + * + * Note that this looks for strings of _wide characters_, not _codepoints_, so + * it's legal to search for malformed and incomplete UTF-16 sequences. + * + * \param haystack the wide string to search. Must not be NULL. + * \param needle the wide string to search for. Must not be NULL. + * \param maxlen the maximum number of wide characters to search in + * `haystack`. + * \returns a pointer to the first instance of `needle` in the string, or NULL + * if not found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC wchar_t * SDLCALL SDL_wcsnstr(const wchar_t *haystack, const wchar_t *needle, size_t maxlen); + +/** + * Compare two null-terminated wide strings. + * + * This only compares wchar_t values until it hits a null-terminating + * character; it does not care if the string is well-formed UTF-16 (or UTF-32, + * depending on your platform's wchar_t size), or uses valid Unicode values. + * + * \param str1 the first string to compare. NULL is not permitted! + * \param str2 the second string to compare. NULL is not permitted! + * \returns less than zero if str1 is "less than" str2, greater than zero if + * str1 is "greater than" str2, and zero if the strings match + * exactly. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_wcscmp(const wchar_t *str1, const wchar_t *str2); + +/** + * Compare two wide strings up to a number of wchar_t values. + * + * This only compares wchar_t values; it does not care if the string is + * well-formed UTF-16 (or UTF-32, depending on your platform's wchar_t size), + * or uses valid Unicode values. + * + * Note that while this function is intended to be used with UTF-16 (or + * UTF-32, depending on your platform's definition of wchar_t), it is + * comparing raw wchar_t values and not Unicode codepoints: `maxlen` specifies + * a wchar_t limit! If the limit lands in the middle of a multi-wchar UTF-16 + * sequence, it will only compare a portion of the final character. + * + * `maxlen` specifies a maximum number of wchar_t to compare; if the strings + * match to this number of wide chars (or both have matched to a + * null-terminator character before this count), they will be considered + * equal. + * + * \param str1 the first string to compare. NULL is not permitted! + * \param str2 the second string to compare. NULL is not permitted! + * \param maxlen the maximum number of wchar_t to compare. + * \returns less than zero if str1 is "less than" str2, greater than zero if + * str1 is "greater than" str2, and zero if the strings match + * exactly. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_wcsncmp(const wchar_t *str1, const wchar_t *str2, size_t maxlen); + +/** + * Compare two null-terminated wide strings, case-insensitively. + * + * This will work with Unicode strings, using a technique called + * "case-folding" to handle the vast majority of case-sensitive human + * languages regardless of system locale. It can deal with expanding values: a + * German Eszett character can compare against two ASCII 's' chars and be + * considered a match, for example. A notable exception: it does not handle + * the Turkish 'i' character; human language is complicated! + * + * Depending on your platform, "wchar_t" might be 2 bytes, and expected to be + * UTF-16 encoded (like Windows), or 4 bytes in UTF-32 format. Since this + * handles Unicode, it expects the string to be well-formed and not a + * null-terminated string of arbitrary bytes. Characters that are not valid + * UTF-16 (or UTF-32) are treated as Unicode character U+FFFD (REPLACEMENT + * CHARACTER), which is to say two strings of random bits may turn out to + * match if they convert to the same amount of replacement characters. + * + * \param str1 the first string to compare. NULL is not permitted! + * \param str2 the second string to compare. NULL is not permitted! + * \returns less than zero if str1 is "less than" str2, greater than zero if + * str1 is "greater than" str2, and zero if the strings match + * exactly. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_wcscasecmp(const wchar_t *str1, const wchar_t *str2); + +/** + * Compare two wide strings, case-insensitively, up to a number of wchar_t. + * + * This will work with Unicode strings, using a technique called + * "case-folding" to handle the vast majority of case-sensitive human + * languages regardless of system locale. It can deal with expanding values: a + * German Eszett character can compare against two ASCII 's' chars and be + * considered a match, for example. A notable exception: it does not handle + * the Turkish 'i' character; human language is complicated! + * + * Depending on your platform, "wchar_t" might be 2 bytes, and expected to be + * UTF-16 encoded (like Windows), or 4 bytes in UTF-32 format. Since this + * handles Unicode, it expects the string to be well-formed and not a + * null-terminated string of arbitrary bytes. Characters that are not valid + * UTF-16 (or UTF-32) are treated as Unicode character U+FFFD (REPLACEMENT + * CHARACTER), which is to say two strings of random bits may turn out to + * match if they convert to the same amount of replacement characters. + * + * Note that while this function might deal with variable-sized characters, + * `maxlen` specifies a _wchar_ limit! If the limit lands in the middle of a + * multi-byte UTF-16 sequence, it may convert a portion of the final character + * to one or more Unicode character U+FFFD (REPLACEMENT CHARACTER) so as not + * to overflow a buffer. + * + * `maxlen` specifies a maximum number of wchar_t values to compare; if the + * strings match to this number of wchar_t (or both have matched to a + * null-terminator character before this number of bytes), they will be + * considered equal. + * + * \param str1 the first string to compare. NULL is not permitted! + * \param str2 the second string to compare. NULL is not permitted! + * \param maxlen the maximum number of wchar_t values to compare. + * \returns less than zero if str1 is "less than" str2, greater than zero if + * str1 is "greater than" str2, and zero if the strings match + * exactly. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_wcsncasecmp(const wchar_t *str1, const wchar_t *str2, size_t maxlen); + +/** + * Parse a `long` from a wide string. + * + * If `str` starts with whitespace, then those whitespace characters are + * skipped before attempting to parse the number. + * + * If the parsed number does not fit inside a `long`, the result is clamped to + * the minimum and maximum representable `long` values. + * + * \param str The null-terminated wide string to read. Must not be NULL. + * \param endp If not NULL, the address of the first invalid wide character + * (i.e. the next character after the parsed number) will be + * written to this pointer. + * \param base The base of the integer to read. Supported values are 0 and 2 + * to 36 inclusive. If 0, the base will be inferred from the + * number's prefix (0x for hexadecimal, 0 for octal, decimal + * otherwise). + * \returns the parsed `long`, or 0 if no number could be parsed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_strtol + */ +extern SDL_DECLSPEC long SDLCALL SDL_wcstol(const wchar_t *str, wchar_t **endp, int base); + +/** + * This works exactly like strlen() but doesn't require access to a C runtime. + * + * Counts the bytes in `str`, excluding the null terminator. + * + * If you need the length of a UTF-8 string, consider using SDL_utf8strlen(). + * + * \param str The null-terminated string to read. Must not be NULL. + * \returns the length (in bytes, excluding the null terminator) of `src`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_strnlen + * \sa SDL_utf8strlen + * \sa SDL_utf8strnlen + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_strlen(const char *str); + +/** + * This works exactly like strnlen() but doesn't require access to a C + * runtime. + * + * Counts up to a maximum of `maxlen` bytes in `str`, excluding the null + * terminator. + * + * If you need the length of a UTF-8 string, consider using SDL_utf8strnlen(). + * + * \param str The null-terminated string to read. Must not be NULL. + * \param maxlen The maximum amount of bytes to count. + * \returns the length (in bytes, excluding the null terminator) of `src` but + * never more than `maxlen`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_strlen + * \sa SDL_utf8strlen + * \sa SDL_utf8strnlen + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_strnlen(const char *str, size_t maxlen); + +/** + * Copy a string. + * + * This function copies up to `maxlen` - 1 characters from `src` to `dst`, + * then appends a null terminator. + * + * If `maxlen` is 0, no characters are copied and no null terminator is + * written. + * + * If you want to copy an UTF-8 string but need to ensure that multi-byte + * sequences are not truncated, consider using SDL_utf8strlcpy(). + * + * \param dst The destination buffer. Must not be NULL, and must not overlap + * with `src`. + * \param src The null-terminated string to copy. Must not be NULL, and must + * not overlap with `dst`. + * \param maxlen The length (in characters) of the destination buffer. + * \returns the length (in characters, excluding the null terminator) of + * `src`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_strlcat + * \sa SDL_utf8strlcpy + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_strlcpy(SDL_OUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen); + +/** + * Copy an UTF-8 string. + * + * This function copies up to `dst_bytes` - 1 bytes from `src` to `dst` while + * also ensuring that the string written to `dst` does not end in a truncated + * multi-byte sequence. Finally, it appends a null terminator. + * + * `src` and `dst` must not overlap. + * + * Note that unlike SDL_strlcpy(), this function returns the number of bytes + * written, not the length of `src`. + * + * \param dst The destination buffer. Must not be NULL, and must not overlap + * with `src`. + * \param src The null-terminated UTF-8 string to copy. Must not be NULL, and + * must not overlap with `dst`. + * \param dst_bytes The length (in bytes) of the destination buffer. Must not + * be 0. + * \returns the number of bytes written, excluding the null terminator. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_strlcpy + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_utf8strlcpy(SDL_OUT_Z_CAP(dst_bytes) char *dst, const char *src, size_t dst_bytes); + +/** + * Concatenate strings. + * + * This function appends up to `maxlen` - SDL_strlen(dst) - 1 characters from + * `src` to the end of the string in `dst`, then appends a null terminator. + * + * `src` and `dst` must not overlap. + * + * If `maxlen` - SDL_strlen(dst) - 1 is less than or equal to 0, then `dst` is + * unmodified. + * + * \param dst The destination buffer already containing the first + * null-terminated string. Must not be NULL and must not overlap + * with `src`. + * \param src The second null-terminated string. Must not be NULL, and must + * not overlap with `dst`. + * \param maxlen The length (in characters) of the destination buffer. + * \returns the length (in characters, excluding the null terminator) of the + * string in `dst` plus the length of `src`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_strlcpy + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_strlcat(SDL_INOUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen); + +/** + * Allocate a copy of a string. + * + * This allocates enough space for a null-terminated copy of `str`, using + * SDL_malloc, and then makes a copy of the string into this space. + * + * The returned string is owned by the caller, and should be passed to + * SDL_free when no longer needed. + * + * \param str the string to copy. + * \returns a pointer to the newly-allocated string. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_MALLOC char * SDLCALL SDL_strdup(const char *str); + +/** + * Allocate a copy of a string, up to n characters. + * + * This allocates enough space for a null-terminated copy of `str`, up to + * `maxlen` bytes, using SDL_malloc, and then makes a copy of the string into + * this space. + * + * If the string is longer than `maxlen` bytes, the returned string will be + * `maxlen` bytes long, plus a null-terminator character that isn't included + * in the count. + * + * The returned string is owned by the caller, and should be passed to + * SDL_free when no longer needed. + * + * \param str the string to copy. + * \param maxlen the maximum length of the copied string, not counting the + * null-terminator character. + * \returns a pointer to the newly-allocated string. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_MALLOC char * SDLCALL SDL_strndup(const char *str, size_t maxlen); + +/** + * Reverse a string's contents. + * + * This reverses a null-terminated string in-place. Only the content of the + * string is reversed; the null-terminator character remains at the end of the + * reversed string. + * + * **WARNING**: This function reverses the _bytes_ of the string, not the + * codepoints. If `str` is a UTF-8 string with Unicode codepoints > 127, this + * will ruin the string data. You should only use this function on strings + * that are completely comprised of low ASCII characters. + * + * \param str the string to reverse. + * \returns `str`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char * SDLCALL SDL_strrev(char *str); + +/** + * Convert a string to uppercase. + * + * **WARNING**: Regardless of system locale, this will only convert ASCII + * values 'A' through 'Z' to uppercase. + * + * This function operates on a null-terminated string of bytes--even if it is + * malformed UTF-8!--and converts ASCII characters 'a' through 'z' to their + * uppercase equivalents in-place, returning the original `str` pointer. + * + * \param str the string to convert in-place. Can not be NULL. + * \returns the `str` pointer passed into this function. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_strlwr + */ +extern SDL_DECLSPEC char * SDLCALL SDL_strupr(char *str); + +/** + * Convert a string to lowercase. + * + * **WARNING**: Regardless of system locale, this will only convert ASCII + * values 'A' through 'Z' to lowercase. + * + * This function operates on a null-terminated string of bytes--even if it is + * malformed UTF-8!--and converts ASCII characters 'A' through 'Z' to their + * lowercase equivalents in-place, returning the original `str` pointer. + * + * \param str the string to convert in-place. Can not be NULL. + * \returns the `str` pointer passed into this function. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_strupr + */ +extern SDL_DECLSPEC char * SDLCALL SDL_strlwr(char *str); + +/** + * Search a string for the first instance of a specific byte. + * + * The search ends once it finds the requested byte value, or a null + * terminator byte to end the string. + * + * Note that this looks for _bytes_, not _characters_, so you cannot match + * against a Unicode codepoint > 255, regardless of character encoding. + * + * \param str the string to search. Must not be NULL. + * \param c the byte value to search for. + * \returns a pointer to the first instance of `c` in the string, or NULL if + * not found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char * SDLCALL SDL_strchr(const char *str, int c); + +/** + * Search a string for the last instance of a specific byte. + * + * The search must go until it finds a null terminator byte to end the string. + * + * Note that this looks for _bytes_, not _characters_, so you cannot match + * against a Unicode codepoint > 255, regardless of character encoding. + * + * \param str the string to search. Must not be NULL. + * \param c the byte value to search for. + * \returns a pointer to the last instance of `c` in the string, or NULL if + * not found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char * SDLCALL SDL_strrchr(const char *str, int c); + +/** + * Search a string for the first instance of a specific substring. + * + * The search ends once it finds the requested substring, or a null terminator + * byte to end the string. + * + * Note that this looks for strings of _bytes_, not _characters_, so it's + * legal to search for malformed and incomplete UTF-8 sequences. + * + * \param haystack the string to search. Must not be NULL. + * \param needle the string to search for. Must not be NULL. + * \returns a pointer to the first instance of `needle` in the string, or NULL + * if not found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char * SDLCALL SDL_strstr(const char *haystack, const char *needle); + +/** + * Search a string, up to n bytes, for the first instance of a specific + * substring. + * + * The search ends once it finds the requested substring, or a null terminator + * byte to end the string, or `maxlen` bytes have been examined. It is + * possible to use this function on a string without a null terminator. + * + * Note that this looks for strings of _bytes_, not _characters_, so it's + * legal to search for malformed and incomplete UTF-8 sequences. + * + * \param haystack the string to search. Must not be NULL. + * \param needle the string to search for. Must not be NULL. + * \param maxlen the maximum number of bytes to search in `haystack`. + * \returns a pointer to the first instance of `needle` in the string, or NULL + * if not found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char * SDLCALL SDL_strnstr(const char *haystack, const char *needle, size_t maxlen); + +/** + * Search a UTF-8 string for the first instance of a specific substring, + * case-insensitively. + * + * This will work with Unicode strings, using a technique called + * "case-folding" to handle the vast majority of case-sensitive human + * languages regardless of system locale. It can deal with expanding values: a + * German Eszett character can compare against two ASCII 's' chars and be + * considered a match, for example. A notable exception: it does not handle + * the Turkish 'i' character; human language is complicated! + * + * Since this handles Unicode, it expects the strings to be well-formed UTF-8 + * and not a null-terminated string of arbitrary bytes. Bytes that are not + * valid UTF-8 are treated as Unicode character U+FFFD (REPLACEMENT + * CHARACTER), which is to say two strings of random bits may turn out to + * match if they convert to the same amount of replacement characters. + * + * \param haystack the string to search. Must not be NULL. + * \param needle the string to search for. Must not be NULL. + * \returns a pointer to the first instance of `needle` in the string, or NULL + * if not found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char * SDLCALL SDL_strcasestr(const char *haystack, const char *needle); + +/** + * This works exactly like strtok_r() but doesn't require access to a C + * runtime. + * + * Break a string up into a series of tokens. + * + * To start tokenizing a new string, `str` should be the non-NULL address of + * the string to start tokenizing. Future calls to get the next token from the + * same string should specify a NULL. + * + * Note that this function will overwrite pieces of `str` with null chars to + * split it into tokens. This function cannot be used with const/read-only + * strings! + * + * `saveptr` just needs to point to a `char *` that can be overwritten; SDL + * will use this to save tokenizing state between calls. It is initialized if + * `str` is non-NULL, and used to resume tokenizing when `str` is NULL. + * + * \param str the string to tokenize, or NULL to continue tokenizing. + * \param delim the delimiter string that separates tokens. + * \param saveptr pointer to a char *, used for ongoing state. + * \returns A pointer to the next token, or NULL if no tokens remain. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char * SDLCALL SDL_strtok_r(char *str, const char *delim, char **saveptr); + +/** + * Count the number of codepoints in a UTF-8 string. + * + * Counts the _codepoints_, not _bytes_, in `str`, excluding the null + * terminator. + * + * If you need to count the bytes in a string instead, consider using + * SDL_strlen(). + * + * Since this handles Unicode, it expects the strings to be well-formed UTF-8 + * and not a null-terminated string of arbitrary bytes. Bytes that are not + * valid UTF-8 are treated as Unicode character U+FFFD (REPLACEMENT + * CHARACTER), so a malformed or incomplete UTF-8 sequence might increase the + * count by several replacement characters. + * + * \param str The null-terminated UTF-8 string to read. Must not be NULL. + * \returns The length (in codepoints, excluding the null terminator) of + * `src`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_utf8strnlen + * \sa SDL_strlen + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_utf8strlen(const char *str); + +/** + * Count the number of codepoints in a UTF-8 string, up to n bytes. + * + * Counts the _codepoints_, not _bytes_, in `str`, excluding the null + * terminator. + * + * If you need to count the bytes in a string instead, consider using + * SDL_strnlen(). + * + * The counting stops at `bytes` bytes (not codepoints!). This seems + * counterintuitive, but makes it easy to express the total size of the + * string's buffer. + * + * Since this handles Unicode, it expects the strings to be well-formed UTF-8 + * and not a null-terminated string of arbitrary bytes. Bytes that are not + * valid UTF-8 are treated as Unicode character U+FFFD (REPLACEMENT + * CHARACTER), so a malformed or incomplete UTF-8 sequence might increase the + * count by several replacement characters. + * + * \param str The null-terminated UTF-8 string to read. Must not be NULL. + * \param bytes The maximum amount of bytes to count. + * \returns The length (in codepoints, excluding the null terminator) of `src` + * but never more than `maxlen`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_utf8strlen + * \sa SDL_strnlen + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_utf8strnlen(const char *str, size_t bytes); + +/** + * Convert an integer into a string. + * + * This requires a radix to specified for string format. Specifying 10 + * produces a decimal number, 16 hexidecimal, etc. Must be in the range of 2 + * to 36. + * + * Note that this function will overflow a buffer if `str` is not large enough + * to hold the output! It may be safer to use SDL_snprintf to clamp output, or + * SDL_asprintf to allocate a buffer. Otherwise, it doesn't hurt to allocate + * much more space than you expect to use (and don't forget possible negative + * signs, null terminator bytes, etc). + * + * \param value the integer to convert. + * \param str the buffer to write the string into. + * \param radix the radix to use for string generation. + * \returns `str`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_uitoa + * \sa SDL_ltoa + * \sa SDL_lltoa + */ +extern SDL_DECLSPEC char * SDLCALL SDL_itoa(int value, char *str, int radix); + +/** + * Convert an unsigned integer into a string. + * + * This requires a radix to specified for string format. Specifying 10 + * produces a decimal number, 16 hexidecimal, etc. Must be in the range of 2 + * to 36. + * + * Note that this function will overflow a buffer if `str` is not large enough + * to hold the output! It may be safer to use SDL_snprintf to clamp output, or + * SDL_asprintf to allocate a buffer. Otherwise, it doesn't hurt to allocate + * much more space than you expect to use (and don't forget null terminator + * bytes, etc). + * + * \param value the unsigned integer to convert. + * \param str the buffer to write the string into. + * \param radix the radix to use for string generation. + * \returns `str`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_itoa + * \sa SDL_ultoa + * \sa SDL_ulltoa + */ +extern SDL_DECLSPEC char * SDLCALL SDL_uitoa(unsigned int value, char *str, int radix); + +/** + * Convert a long integer into a string. + * + * This requires a radix to specified for string format. Specifying 10 + * produces a decimal number, 16 hexidecimal, etc. Must be in the range of 2 + * to 36. + * + * Note that this function will overflow a buffer if `str` is not large enough + * to hold the output! It may be safer to use SDL_snprintf to clamp output, or + * SDL_asprintf to allocate a buffer. Otherwise, it doesn't hurt to allocate + * much more space than you expect to use (and don't forget possible negative + * signs, null terminator bytes, etc). + * + * \param value the long integer to convert. + * \param str the buffer to write the string into. + * \param radix the radix to use for string generation. + * \returns `str`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ultoa + * \sa SDL_itoa + * \sa SDL_lltoa + */ +extern SDL_DECLSPEC char * SDLCALL SDL_ltoa(long value, char *str, int radix); + +/** + * Convert an unsigned long integer into a string. + * + * This requires a radix to specified for string format. Specifying 10 + * produces a decimal number, 16 hexidecimal, etc. Must be in the range of 2 + * to 36. + * + * Note that this function will overflow a buffer if `str` is not large enough + * to hold the output! It may be safer to use SDL_snprintf to clamp output, or + * SDL_asprintf to allocate a buffer. Otherwise, it doesn't hurt to allocate + * much more space than you expect to use (and don't forget null terminator + * bytes, etc). + * + * \param value the unsigned long integer to convert. + * \param str the buffer to write the string into. + * \param radix the radix to use for string generation. + * \returns `str`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ltoa + * \sa SDL_uitoa + * \sa SDL_ulltoa + */ +extern SDL_DECLSPEC char * SDLCALL SDL_ultoa(unsigned long value, char *str, int radix); + +#ifndef SDL_NOLONGLONG + +/** + * Convert a long long integer into a string. + * + * This requires a radix to specified for string format. Specifying 10 + * produces a decimal number, 16 hexidecimal, etc. Must be in the range of 2 + * to 36. + * + * Note that this function will overflow a buffer if `str` is not large enough + * to hold the output! It may be safer to use SDL_snprintf to clamp output, or + * SDL_asprintf to allocate a buffer. Otherwise, it doesn't hurt to allocate + * much more space than you expect to use (and don't forget possible negative + * signs, null terminator bytes, etc). + * + * \param value the long long integer to convert. + * \param str the buffer to write the string into. + * \param radix the radix to use for string generation. + * \returns `str`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ulltoa + * \sa SDL_itoa + * \sa SDL_ltoa + */ +extern SDL_DECLSPEC char * SDLCALL SDL_lltoa(long long value, char *str, int radix); + +/** + * Convert an unsigned long long integer into a string. + * + * This requires a radix to specified for string format. Specifying 10 + * produces a decimal number, 16 hexidecimal, etc. Must be in the range of 2 + * to 36. + * + * Note that this function will overflow a buffer if `str` is not large enough + * to hold the output! It may be safer to use SDL_snprintf to clamp output, or + * SDL_asprintf to allocate a buffer. Otherwise, it doesn't hurt to allocate + * much more space than you expect to use (and don't forget null terminator + * bytes, etc). + * + * \param value the unsigned long long integer to convert. + * \param str the buffer to write the string into. + * \param radix the radix to use for string generation. + * \returns `str`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_lltoa + * \sa SDL_uitoa + * \sa SDL_ultoa + */ +extern SDL_DECLSPEC char * SDLCALL SDL_ulltoa(unsigned long long value, char *str, int radix); +#endif + +/** + * Parse an `int` from a string. + * + * The result of calling `SDL_atoi(str)` is equivalent to + * `(int)SDL_strtol(str, NULL, 10)`. + * + * \param str The null-terminated string to read. Must not be NULL. + * \returns the parsed `int`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atof + * \sa SDL_strtol + * \sa SDL_strtoul + * \sa SDL_strtoll + * \sa SDL_strtoull + * \sa SDL_strtod + * \sa SDL_itoa + */ +extern SDL_DECLSPEC int SDLCALL SDL_atoi(const char *str); + +/** + * Parse a `double` from a string. + * + * The result of calling `SDL_atof(str)` is equivalent to `SDL_strtod(str, + * NULL)`. + * + * \param str The null-terminated string to read. Must not be NULL. + * \returns the parsed `double`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atoi + * \sa SDL_strtol + * \sa SDL_strtoul + * \sa SDL_strtoll + * \sa SDL_strtoull + * \sa SDL_strtod + */ +extern SDL_DECLSPEC double SDLCALL SDL_atof(const char *str); + +/** + * Parse a `long` from a string. + * + * If `str` starts with whitespace, then those whitespace characters are + * skipped before attempting to parse the number. + * + * If the parsed number does not fit inside a `long`, the result is clamped to + * the minimum and maximum representable `long` values. + * + * \param str The null-terminated string to read. Must not be NULL. + * \param endp If not NULL, the address of the first invalid character (i.e. + * the next character after the parsed number) will be written to + * this pointer. + * \param base The base of the integer to read. Supported values are 0 and 2 + * to 36 inclusive. If 0, the base will be inferred from the + * number's prefix (0x for hexadecimal, 0 for octal, decimal + * otherwise). + * \returns the parsed `long`, or 0 if no number could be parsed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atoi + * \sa SDL_atof + * \sa SDL_strtoul + * \sa SDL_strtoll + * \sa SDL_strtoull + * \sa SDL_strtod + * \sa SDL_ltoa + * \sa SDL_wcstol + */ +extern SDL_DECLSPEC long SDLCALL SDL_strtol(const char *str, char **endp, int base); + +/** + * Parse an `unsigned long` from a string. + * + * If `str` starts with whitespace, then those whitespace characters are + * skipped before attempting to parse the number. + * + * If the parsed number does not fit inside an `unsigned long`, the result is + * clamped to the maximum representable `unsigned long` value. + * + * \param str The null-terminated string to read. Must not be NULL. + * \param endp If not NULL, the address of the first invalid character (i.e. + * the next character after the parsed number) will be written to + * this pointer. + * \param base The base of the integer to read. Supported values are 0 and 2 + * to 36 inclusive. If 0, the base will be inferred from the + * number's prefix (0x for hexadecimal, 0 for octal, decimal + * otherwise). + * \returns the parsed `unsigned long`, or 0 if no number could be parsed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atoi + * \sa SDL_atof + * \sa SDL_strtol + * \sa SDL_strtoll + * \sa SDL_strtoull + * \sa SDL_strtod + * \sa SDL_ultoa + */ +extern SDL_DECLSPEC unsigned long SDLCALL SDL_strtoul(const char *str, char **endp, int base); + +#ifndef SDL_NOLONGLONG + +/** + * Parse a `long long` from a string. + * + * If `str` starts with whitespace, then those whitespace characters are + * skipped before attempting to parse the number. + * + * If the parsed number does not fit inside a `long long`, the result is + * clamped to the minimum and maximum representable `long long` values. + * + * \param str The null-terminated string to read. Must not be NULL. + * \param endp If not NULL, the address of the first invalid character (i.e. + * the next character after the parsed number) will be written to + * this pointer. + * \param base The base of the integer to read. Supported values are 0 and 2 + * to 36 inclusive. If 0, the base will be inferred from the + * number's prefix (0x for hexadecimal, 0 for octal, decimal + * otherwise). + * \returns the parsed `long long`, or 0 if no number could be parsed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atoi + * \sa SDL_atof + * \sa SDL_strtol + * \sa SDL_strtoul + * \sa SDL_strtoull + * \sa SDL_strtod + * \sa SDL_lltoa + */ +extern SDL_DECLSPEC long long SDLCALL SDL_strtoll(const char *str, char **endp, int base); + +/** + * Parse an `unsigned long long` from a string. + * + * If `str` starts with whitespace, then those whitespace characters are + * skipped before attempting to parse the number. + * + * If the parsed number does not fit inside an `unsigned long long`, the + * result is clamped to the maximum representable `unsigned long long` value. + * + * \param str The null-terminated string to read. Must not be NULL. + * \param endp If not NULL, the address of the first invalid character (i.e. + * the next character after the parsed number) will be written to + * this pointer. + * \param base The base of the integer to read. Supported values are 0 and 2 + * to 36 inclusive. If 0, the base will be inferred from the + * number's prefix (0x for hexadecimal, 0 for octal, decimal + * otherwise). + * \returns the parsed `unsigned long long`, or 0 if no number could be + * parsed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atoi + * \sa SDL_atof + * \sa SDL_strtol + * \sa SDL_strtoll + * \sa SDL_strtoul + * \sa SDL_strtod + * \sa SDL_ulltoa + */ +extern SDL_DECLSPEC unsigned long long SDLCALL SDL_strtoull(const char *str, char **endp, int base); +#endif + +/** + * Parse a `double` from a string. + * + * This function makes fewer guarantees than the C runtime `strtod`: + * + * - Only decimal notation is guaranteed to be supported. The handling of + * scientific and hexadecimal notation is unspecified. + * - Whether or not INF and NAN can be parsed is unspecified. + * - The precision of the result is unspecified. + * + * \param str the null-terminated string to read. Must not be NULL. + * \param endp if not NULL, the address of the first invalid character (i.e. + * the next character after the parsed number) will be written to + * this pointer. + * \returns the parsed `double`, or 0 if no number could be parsed. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atoi + * \sa SDL_atof + * \sa SDL_strtol + * \sa SDL_strtoll + * \sa SDL_strtoul + * \sa SDL_strtoull + */ +extern SDL_DECLSPEC double SDLCALL SDL_strtod(const char *str, char **endp); + +/** + * Compare two null-terminated UTF-8 strings. + * + * Due to the nature of UTF-8 encoding, this will work with Unicode strings, + * since effectively this function just compares bytes until it hits a + * null-terminating character. Also due to the nature of UTF-8, this can be + * used with SDL_qsort() to put strings in (roughly) alphabetical order. + * + * \param str1 the first string to compare. NULL is not permitted! + * \param str2 the second string to compare. NULL is not permitted! + * \returns less than zero if str1 is "less than" str2, greater than zero if + * str1 is "greater than" str2, and zero if the strings match + * exactly. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_strcmp(const char *str1, const char *str2); + +/** + * Compare two UTF-8 strings up to a number of bytes. + * + * Due to the nature of UTF-8 encoding, this will work with Unicode strings, + * since effectively this function just compares bytes until it hits a + * null-terminating character. Also due to the nature of UTF-8, this can be + * used with SDL_qsort() to put strings in (roughly) alphabetical order. + * + * Note that while this function is intended to be used with UTF-8, it is + * doing a bytewise comparison, and `maxlen` specifies a _byte_ limit! If the + * limit lands in the middle of a multi-byte UTF-8 sequence, it will only + * compare a portion of the final character. + * + * `maxlen` specifies a maximum number of bytes to compare; if the strings + * match to this number of bytes (or both have matched to a null-terminator + * character before this number of bytes), they will be considered equal. + * + * \param str1 the first string to compare. NULL is not permitted! + * \param str2 the second string to compare. NULL is not permitted! + * \param maxlen the maximum number of _bytes_ to compare. + * \returns less than zero if str1 is "less than" str2, greater than zero if + * str1 is "greater than" str2, and zero if the strings match + * exactly. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_strncmp(const char *str1, const char *str2, size_t maxlen); + +/** + * Compare two null-terminated UTF-8 strings, case-insensitively. + * + * This will work with Unicode strings, using a technique called + * "case-folding" to handle the vast majority of case-sensitive human + * languages regardless of system locale. It can deal with expanding values: a + * German Eszett character can compare against two ASCII 's' chars and be + * considered a match, for example. A notable exception: it does not handle + * the Turkish 'i' character; human language is complicated! + * + * Since this handles Unicode, it expects the string to be well-formed UTF-8 + * and not a null-terminated string of arbitrary bytes. Bytes that are not + * valid UTF-8 are treated as Unicode character U+FFFD (REPLACEMENT + * CHARACTER), which is to say two strings of random bits may turn out to + * match if they convert to the same amount of replacement characters. + * + * \param str1 the first string to compare. NULL is not permitted! + * \param str2 the second string to compare. NULL is not permitted! + * \returns less than zero if str1 is "less than" str2, greater than zero if + * str1 is "greater than" str2, and zero if the strings match + * exactly. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_strcasecmp(const char *str1, const char *str2); + + +/** + * Compare two UTF-8 strings, case-insensitively, up to a number of bytes. + * + * This will work with Unicode strings, using a technique called + * "case-folding" to handle the vast majority of case-sensitive human + * languages regardless of system locale. It can deal with expanding values: a + * German Eszett character can compare against two ASCII 's' chars and be + * considered a match, for example. A notable exception: it does not handle + * the Turkish 'i' character; human language is complicated! + * + * Since this handles Unicode, it expects the string to be well-formed UTF-8 + * and not a null-terminated string of arbitrary bytes. Bytes that are not + * valid UTF-8 are treated as Unicode character U+FFFD (REPLACEMENT + * CHARACTER), which is to say two strings of random bits may turn out to + * match if they convert to the same amount of replacement characters. + * + * Note that while this function is intended to be used with UTF-8, `maxlen` + * specifies a _byte_ limit! If the limit lands in the middle of a multi-byte + * UTF-8 sequence, it may convert a portion of the final character to one or + * more Unicode character U+FFFD (REPLACEMENT CHARACTER) so as not to overflow + * a buffer. + * + * `maxlen` specifies a maximum number of bytes to compare; if the strings + * match to this number of bytes (or both have matched to a null-terminator + * character before this number of bytes), they will be considered equal. + * + * \param str1 the first string to compare. NULL is not permitted! + * \param str2 the second string to compare. NULL is not permitted! + * \param maxlen the maximum number of bytes to compare. + * \returns less than zero if str1 is "less than" str2, greater than zero if + * str1 is "greater than" str2, and zero if the strings match + * exactly. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_strncasecmp(const char *str1, const char *str2, size_t maxlen); + +/** + * Searches a string for the first occurence of any character contained in a + * breakset, and returns a pointer from the string to that character. + * + * \param str The null-terminated string to be searched. Must not be NULL, and + * must not overlap with `breakset`. + * \param breakset A null-terminated string containing the list of characters + * to look for. Must not be NULL, and must not overlap with + * `str`. + * \returns A pointer to the location, in str, of the first occurence of a + * character present in the breakset, or NULL if none is found. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char * SDLCALL SDL_strpbrk(const char *str, const char *breakset); + +/** + * The Unicode REPLACEMENT CHARACTER codepoint. + * + * SDL_StepUTF8() and SDL_StepBackUTF8() report this codepoint when they + * encounter a UTF-8 string with encoding errors. + * + * This tends to render as something like a question mark in most places. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_StepBackUTF8 + * \sa SDL_StepUTF8 + */ +#define SDL_INVALID_UNICODE_CODEPOINT 0xFFFD + +/** + * Decode a UTF-8 string, one Unicode codepoint at a time. + * + * This will return the first Unicode codepoint in the UTF-8 encoded string in + * `*pstr`, and then advance `*pstr` past any consumed bytes before returning. + * + * It will not access more than `*pslen` bytes from the string. `*pslen` will + * be adjusted, as well, subtracting the number of bytes consumed. + * + * `pslen` is allowed to be NULL, in which case the string _must_ be + * NULL-terminated, as the function will blindly read until it sees the NULL + * char. + * + * if `*pslen` is zero, it assumes the end of string is reached and returns a + * zero codepoint regardless of the contents of the string buffer. + * + * If the resulting codepoint is zero (a NULL terminator), or `*pslen` is + * zero, it will not advance `*pstr` or `*pslen` at all. + * + * Generally this function is called in a loop until it returns zero, + * adjusting its parameters each iteration. + * + * If an invalid UTF-8 sequence is encountered, this function returns + * SDL_INVALID_UNICODE_CODEPOINT and advances the string/length by one byte + * (which is to say, a multibyte sequence might produce several + * SDL_INVALID_UNICODE_CODEPOINT returns before it syncs to the next valid + * UTF-8 sequence). + * + * Several things can generate invalid UTF-8 sequences, including overlong + * encodings, the use of UTF-16 surrogate values, and truncated data. Please + * refer to + * [RFC3629](https://www.ietf.org/rfc/rfc3629.txt) + * for details. + * + * \param pstr a pointer to a UTF-8 string pointer to be read and adjusted. + * \param pslen a pointer to the number of bytes in the string, to be read and + * adjusted. NULL is allowed. + * \returns the first Unicode codepoint in the string. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_StepUTF8(const char **pstr, size_t *pslen); + +/** + * Decode a UTF-8 string in reverse, one Unicode codepoint at a time. + * + * This will go to the start of the previous Unicode codepoint in the string, + * move `*pstr` to that location and return that codepoint. + * + * If `*pstr` is already at the start of the string), it will not advance + * `*pstr` at all. + * + * Generally this function is called in a loop until it returns zero, + * adjusting its parameter each iteration. + * + * If an invalid UTF-8 sequence is encountered, this function returns + * SDL_INVALID_UNICODE_CODEPOINT. + * + * Several things can generate invalid UTF-8 sequences, including overlong + * encodings, the use of UTF-16 surrogate values, and truncated data. Please + * refer to + * [RFC3629](https://www.ietf.org/rfc/rfc3629.txt) + * for details. + * + * \param start a pointer to the beginning of the UTF-8 string. + * \param pstr a pointer to a UTF-8 string pointer to be read and adjusted. + * \returns the previous Unicode codepoint in the string. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_StepBackUTF8(const char *start, const char **pstr); + +/** + * Convert a single Unicode codepoint to UTF-8. + * + * The buffer pointed to by `dst` must be at least 4 bytes long, as this + * function may generate between 1 and 4 bytes of output. + * + * This function returns the first byte _after_ the newly-written UTF-8 + * sequence, which is useful for encoding multiple codepoints in a loop, or + * knowing where to write a NULL-terminator character to end the string (in + * either case, plan to have a buffer of _more_ than 4 bytes!). + * + * If `codepoint` is an invalid value (outside the Unicode range, or a UTF-16 + * surrogate value, etc), this will use U+FFFD (REPLACEMENT CHARACTER) for the + * codepoint instead, and not set an error. + * + * If `dst` is NULL, this returns NULL immediately without writing to the + * pointer and without setting an error. + * + * \param codepoint a Unicode codepoint to convert to UTF-8. + * \param dst the location to write the encoded UTF-8. Must point to at least + * 4 bytes! + * \returns the first byte past the newly-written UTF-8 sequence. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char * SDLCALL SDL_UCS4ToUTF8(Uint32 codepoint, char *dst); + +/** + * This works exactly like sscanf() but doesn't require access to a C runtime. + * + * Scan a string, matching a format string, converting each '%' item and + * storing it to pointers provided through variable arguments. + * + * \param text the string to scan. Must not be NULL. + * \param fmt a printf-style format string. Must not be NULL. + * \param ... a list of pointers to values to be filled in with scanned items. + * \returns the number of items that matched the format string. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_sscanf(const char *text, SDL_SCANF_FORMAT_STRING const char *fmt, ...) SDL_SCANF_VARARG_FUNC(2); + +/** + * This works exactly like vsscanf() but doesn't require access to a C + * runtime. + * + * Functions identically to SDL_sscanf(), except it takes a `va_list` instead + * of using `...` variable arguments. + * + * \param text the string to scan. Must not be NULL. + * \param fmt a printf-style format string. Must not be NULL. + * \param ap a `va_list` of pointers to values to be filled in with scanned + * items. + * \returns the number of items that matched the format string. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_vsscanf(const char *text, SDL_SCANF_FORMAT_STRING const char *fmt, va_list ap) SDL_SCANF_VARARG_FUNCV(2); + +/** + * This works exactly like snprintf() but doesn't require access to a C + * runtime. + * + * Format a string of up to `maxlen`-1 bytes, converting each '%' item with + * values provided through variable arguments. + * + * While some C runtimes differ on how to deal with too-large strings, this + * function null-terminates the output, by treating the null-terminator as + * part of the `maxlen` count. Note that if `maxlen` is zero, however, no + * bytes will be written at all. + * + * This function returns the number of _bytes_ (not _characters_) that should + * be written, excluding the null-terminator character. If this returns a + * number >= `maxlen`, it means the output string was truncated. A negative + * return value means an error occurred. + * + * Referencing the output string's pointer with a format item is undefined + * behavior. + * + * \param text the buffer to write the string into. Must not be NULL. + * \param maxlen the maximum bytes to write, including the null-terminator. + * \param fmt a printf-style format string. Must not be NULL. + * \param ... a list of values to be used with the format string. + * \returns the number of bytes that should be written, not counting the + * null-terminator char, or a negative value on error. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_snprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(3); + +/** + * This works exactly like swprintf() but doesn't require access to a C + * runtime. + * + * Format a wide string of up to `maxlen`-1 wchar_t values, converting each + * '%' item with values provided through variable arguments. + * + * While some C runtimes differ on how to deal with too-large strings, this + * function null-terminates the output, by treating the null-terminator as + * part of the `maxlen` count. Note that if `maxlen` is zero, however, no wide + * characters will be written at all. + * + * This function returns the number of _wide characters_ (not _codepoints_) + * that should be written, excluding the null-terminator character. If this + * returns a number >= `maxlen`, it means the output string was truncated. A + * negative return value means an error occurred. + * + * Referencing the output string's pointer with a format item is undefined + * behavior. + * + * \param text the buffer to write the wide string into. Must not be NULL. + * \param maxlen the maximum wchar_t values to write, including the + * null-terminator. + * \param fmt a printf-style format string. Must not be NULL. + * \param ... a list of values to be used with the format string. + * \returns the number of wide characters that should be written, not counting + * the null-terminator char, or a negative value on error. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_swprintf(SDL_OUT_Z_CAP(maxlen) wchar_t *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const wchar_t *fmt, ...) SDL_WPRINTF_VARARG_FUNC(3); + +/** + * This works exactly like vsnprintf() but doesn't require access to a C + * runtime. + * + * Functions identically to SDL_snprintf(), except it takes a `va_list` + * instead of using `...` variable arguments. + * + * \param text the buffer to write the string into. Must not be NULL. + * \param maxlen the maximum bytes to write, including the null-terminator. + * \param fmt a printf-style format string. Must not be NULL. + * \param ap a `va_list` values to be used with the format string. + * \returns the number of bytes that should be written, not counting the + * null-terminator char, or a negative value on error. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(3); + +/** + * This works exactly like vswprintf() but doesn't require access to a C + * runtime. + * + * Functions identically to SDL_swprintf(), except it takes a `va_list` + * instead of using `...` variable arguments. + * + * \param text the buffer to write the string into. Must not be NULL. + * \param maxlen the maximum wide characters to write, including the + * null-terminator. + * \param fmt a printf-style format wide string. Must not be NULL. + * \param ap a `va_list` values to be used with the format string. + * \returns the number of wide characters that should be written, not counting + * the null-terminator char, or a negative value on error. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_vswprintf(SDL_OUT_Z_CAP(maxlen) wchar_t *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const wchar_t *fmt, va_list ap) SDL_WPRINTF_VARARG_FUNCV(3); + +/** + * This works exactly like asprintf() but doesn't require access to a C + * runtime. + * + * Functions identically to SDL_snprintf(), except it allocates a buffer large + * enough to hold the output string on behalf of the caller. + * + * On success, this function returns the number of bytes (not characters) + * comprising the output string, not counting the null-terminator character, + * and sets `*strp` to the newly-allocated string. + * + * On error, this function returns a negative number, and the value of `*strp` + * is undefined. + * + * The returned string is owned by the caller, and should be passed to + * SDL_free when no longer needed. + * + * \param strp on output, is set to the new string. Must not be NULL. + * \param fmt a printf-style format string. Must not be NULL. + * \param ... a list of values to be used with the format string. + * \returns the number of bytes in the newly-allocated string, not counting + * the null-terminator char, or a negative value on error. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_asprintf(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * This works exactly like vasprintf() but doesn't require access to a C + * runtime. + * + * Functions identically to SDL_asprintf(), except it takes a `va_list` + * instead of using `...` variable arguments. + * + * \param strp on output, is set to the new string. Must not be NULL. + * \param fmt a printf-style format string. Must not be NULL. + * \param ap a `va_list` values to be used with the format string. + * \returns the number of bytes in the newly-allocated string, not counting + * the null-terminator char, or a negative value on error. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_vasprintf(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(2); + +/** + * Seeds the pseudo-random number generator. + * + * Reusing the seed number will cause SDL_rand() to repeat the same stream of + * 'random' numbers. + * + * \param seed the value to use as a random number seed, or 0 to use + * SDL_GetPerformanceCounter(). + * + * \threadsafety This should be called on the same thread that calls + * SDL_rand() + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_rand + * \sa SDL_rand_bits + * \sa SDL_randf + */ +extern SDL_DECLSPEC void SDLCALL SDL_srand(Uint64 seed); + +/** + * Generate a pseudo-random number less than n for positive n + * + * The method used is faster and of better quality than `rand() % n`. Odds are + * roughly 99.9% even for n = 1 million. Evenness is better for smaller n, and + * much worse as n gets bigger. + * + * Example: to simulate a d6 use `SDL_rand(6) + 1` The +1 converts 0..5 to + * 1..6 + * + * If you want to generate a pseudo-random number in the full range of Sint32, + * you should use: (Sint32)SDL_rand_bits() + * + * If you want reproducible output, be sure to initialize with SDL_srand() + * first. + * + * There are no guarantees as to the quality of the random sequence produced, + * and this should not be used for security (cryptography, passwords) or where + * money is on the line (loot-boxes, casinos). There are many random number + * libraries available with different characteristics and you should pick one + * of those to meet any serious needs. + * + * \param n the number of possible outcomes. n must be positive. + * \returns a random value in the range of [0 .. n-1]. + * + * \threadsafety All calls should be made from a single thread + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_srand + * \sa SDL_randf + */ +extern SDL_DECLSPEC Sint32 SDLCALL SDL_rand(Sint32 n); + +/** + * Generate a uniform pseudo-random floating point number less than 1.0 + * + * If you want reproducible output, be sure to initialize with SDL_srand() + * first. + * + * There are no guarantees as to the quality of the random sequence produced, + * and this should not be used for security (cryptography, passwords) or where + * money is on the line (loot-boxes, casinos). There are many random number + * libraries available with different characteristics and you should pick one + * of those to meet any serious needs. + * + * \returns a random value in the range of [0.0, 1.0). + * + * \threadsafety All calls should be made from a single thread + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_srand + * \sa SDL_rand + */ +extern SDL_DECLSPEC float SDLCALL SDL_randf(void); + +/** + * Generate 32 pseudo-random bits. + * + * You likely want to use SDL_rand() to get a psuedo-random number instead. + * + * There are no guarantees as to the quality of the random sequence produced, + * and this should not be used for security (cryptography, passwords) or where + * money is on the line (loot-boxes, casinos). There are many random number + * libraries available with different characteristics and you should pick one + * of those to meet any serious needs. + * + * \returns a random value in the range of [0-SDL_MAX_UINT32]. + * + * \threadsafety All calls should be made from a single thread + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_rand + * \sa SDL_randf + * \sa SDL_srand + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_rand_bits(void); + +/** + * Generate a pseudo-random number less than n for positive n + * + * The method used is faster and of better quality than `rand() % n`. Odds are + * roughly 99.9% even for n = 1 million. Evenness is better for smaller n, and + * much worse as n gets bigger. + * + * Example: to simulate a d6 use `SDL_rand_r(state, 6) + 1` The +1 converts + * 0..5 to 1..6 + * + * If you want to generate a pseudo-random number in the full range of Sint32, + * you should use: (Sint32)SDL_rand_bits_r(state) + * + * There are no guarantees as to the quality of the random sequence produced, + * and this should not be used for security (cryptography, passwords) or where + * money is on the line (loot-boxes, casinos). There are many random number + * libraries available with different characteristics and you should pick one + * of those to meet any serious needs. + * + * \param state a pointer to the current random number state, this may not be + * NULL. + * \param n the number of possible outcomes. n must be positive. + * \returns a random value in the range of [0 .. n-1]. + * + * \threadsafety This function is thread-safe, as long as the state pointer + * isn't shared between threads. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_rand + * \sa SDL_rand_bits_r + * \sa SDL_randf_r + */ +extern SDL_DECLSPEC Sint32 SDLCALL SDL_rand_r(Uint64 *state, Sint32 n); + +/** + * Generate a uniform pseudo-random floating point number less than 1.0 + * + * If you want reproducible output, be sure to initialize with SDL_srand() + * first. + * + * There are no guarantees as to the quality of the random sequence produced, + * and this should not be used for security (cryptography, passwords) or where + * money is on the line (loot-boxes, casinos). There are many random number + * libraries available with different characteristics and you should pick one + * of those to meet any serious needs. + * + * \param state a pointer to the current random number state, this may not be + * NULL. + * \returns a random value in the range of [0.0, 1.0). + * + * \threadsafety This function is thread-safe, as long as the state pointer + * isn't shared between threads. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_rand_bits_r + * \sa SDL_rand_r + * \sa SDL_randf + */ +extern SDL_DECLSPEC float SDLCALL SDL_randf_r(Uint64 *state); + +/** + * Generate 32 pseudo-random bits. + * + * You likely want to use SDL_rand_r() to get a psuedo-random number instead. + * + * There are no guarantees as to the quality of the random sequence produced, + * and this should not be used for security (cryptography, passwords) or where + * money is on the line (loot-boxes, casinos). There are many random number + * libraries available with different characteristics and you should pick one + * of those to meet any serious needs. + * + * \param state a pointer to the current random number state, this may not be + * NULL. + * \returns a random value in the range of [0-SDL_MAX_UINT32]. + * + * \threadsafety This function is thread-safe, as long as the state pointer + * isn't shared between threads. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_rand_r + * \sa SDL_randf_r + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_rand_bits_r(Uint64 *state); + +#ifndef SDL_PI_D + +/** + * The value of Pi, as a double-precision floating point literal. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_PI_F + */ +#define SDL_PI_D 3.141592653589793238462643383279502884 /**< pi (double) */ +#endif + +#ifndef SDL_PI_F + +/** + * The value of Pi, as a single-precision floating point literal. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_PI_D + */ +#define SDL_PI_F 3.141592653589793238462643383279502884F /**< pi (float) */ +#endif + +/** + * Compute the arc cosine of `x`. + * + * The definition of `y = acos(x)` is `x = cos(y)`. + * + * Domain: `-1 <= x <= 1` + * + * Range: `0 <= y <= Pi` + * + * This function operates on double-precision floating point values, use + * SDL_acosf for single-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. + * \returns arc cosine of `x`, in radians. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_acosf + * \sa SDL_asin + * \sa SDL_cos + */ +extern SDL_DECLSPEC double SDLCALL SDL_acos(double x); + +/** + * Compute the arc cosine of `x`. + * + * The definition of `y = acos(x)` is `x = cos(y)`. + * + * Domain: `-1 <= x <= 1` + * + * Range: `0 <= y <= Pi` + * + * This function operates on single-precision floating point values, use + * SDL_acos for double-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. + * \returns arc cosine of `x`, in radians. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_acos + * \sa SDL_asinf + * \sa SDL_cosf + */ +extern SDL_DECLSPEC float SDLCALL SDL_acosf(float x); + +/** + * Compute the arc sine of `x`. + * + * The definition of `y = asin(x)` is `x = sin(y)`. + * + * Domain: `-1 <= x <= 1` + * + * Range: `-Pi/2 <= y <= Pi/2` + * + * This function operates on double-precision floating point values, use + * SDL_asinf for single-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. + * \returns arc sine of `x`, in radians. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_asinf + * \sa SDL_acos + * \sa SDL_sin + */ +extern SDL_DECLSPEC double SDLCALL SDL_asin(double x); + +/** + * Compute the arc sine of `x`. + * + * The definition of `y = asin(x)` is `x = sin(y)`. + * + * Domain: `-1 <= x <= 1` + * + * Range: `-Pi/2 <= y <= Pi/2` + * + * This function operates on single-precision floating point values, use + * SDL_asin for double-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. + * \returns arc sine of `x`, in radians. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_asin + * \sa SDL_acosf + * \sa SDL_sinf + */ +extern SDL_DECLSPEC float SDLCALL SDL_asinf(float x); + +/** + * Compute the arc tangent of `x`. + * + * The definition of `y = atan(x)` is `x = tan(y)`. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-Pi/2 <= y <= Pi/2` + * + * This function operates on double-precision floating point values, use + * SDL_atanf for single-precision floats. + * + * To calculate the arc tangent of y / x, use SDL_atan2. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. + * \returns arc tangent of of `x` in radians, or 0 if `x = 0`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atanf + * \sa SDL_atan2 + * \sa SDL_tan + */ +extern SDL_DECLSPEC double SDLCALL SDL_atan(double x); + +/** + * Compute the arc tangent of `x`. + * + * The definition of `y = atan(x)` is `x = tan(y)`. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-Pi/2 <= y <= Pi/2` + * + * This function operates on single-precision floating point values, use + * SDL_atan for dboule-precision floats. + * + * To calculate the arc tangent of y / x, use SDL_atan2f. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. + * \returns arc tangent of of `x` in radians, or 0 if `x = 0`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atan + * \sa SDL_atan2f + * \sa SDL_tanf + */ +extern SDL_DECLSPEC float SDLCALL SDL_atanf(float x); + +/** + * Compute the arc tangent of `y / x`, using the signs of x and y to adjust + * the result's quadrant. + * + * The definition of `z = atan2(x, y)` is `y = x tan(z)`, where the quadrant + * of z is determined based on the signs of x and y. + * + * Domain: `-INF <= x <= INF`, `-INF <= y <= INF` + * + * Range: `-Pi <= y <= Pi` + * + * This function operates on double-precision floating point values, use + * SDL_atan2f for single-precision floats. + * + * To calculate the arc tangent of a single value, use SDL_atan. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param y floating point value of the numerator (y coordinate). + * \param x floating point value of the denominator (x coordinate). + * \returns arc tangent of of `y / x` in radians, or, if `x = 0`, either + * `-Pi/2`, `0`, or `Pi/2`, depending on the value of `y`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atan2f + * \sa SDL_atan + * \sa SDL_tan + */ +extern SDL_DECLSPEC double SDLCALL SDL_atan2(double y, double x); + +/** + * Compute the arc tangent of `y / x`, using the signs of x and y to adjust + * the result's quadrant. + * + * The definition of `z = atan2(x, y)` is `y = x tan(z)`, where the quadrant + * of z is determined based on the signs of x and y. + * + * Domain: `-INF <= x <= INF`, `-INF <= y <= INF` + * + * Range: `-Pi <= y <= Pi` + * + * This function operates on single-precision floating point values, use + * SDL_atan2 for double-precision floats. + * + * To calculate the arc tangent of a single value, use SDL_atanf. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param y floating point value of the numerator (y coordinate). + * \param x floating point value of the denominator (x coordinate). + * \returns arc tangent of of `y / x` in radians, or, if `x = 0`, either + * `-Pi/2`, `0`, or `Pi/2`, depending on the value of `y`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_atan2 + * \sa SDL_atan + * \sa SDL_tan + */ +extern SDL_DECLSPEC float SDLCALL SDL_atan2f(float y, float x); + +/** + * Compute the ceiling of `x`. + * + * The ceiling of `x` is the smallest integer `y` such that `y > x`, i.e `x` + * rounded up to the nearest integer. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-INF <= y <= INF`, y integer + * + * This function operates on double-precision floating point values, use + * SDL_ceilf for single-precision floats. + * + * \param x floating point value. + * \returns the ceiling of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ceilf + * \sa SDL_floor + * \sa SDL_trunc + * \sa SDL_round + * \sa SDL_lround + */ +extern SDL_DECLSPEC double SDLCALL SDL_ceil(double x); + +/** + * Compute the ceiling of `x`. + * + * The ceiling of `x` is the smallest integer `y` such that `y > x`, i.e `x` + * rounded up to the nearest integer. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-INF <= y <= INF`, y integer + * + * This function operates on single-precision floating point values, use + * SDL_ceil for double-precision floats. + * + * \param x floating point value. + * \returns the ceiling of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ceil + * \sa SDL_floorf + * \sa SDL_truncf + * \sa SDL_roundf + * \sa SDL_lroundf + */ +extern SDL_DECLSPEC float SDLCALL SDL_ceilf(float x); + +/** + * Copy the sign of one floating-point value to another. + * + * The definition of copysign is that ``copysign(x, y) = abs(x) * sign(y)``. + * + * Domain: `-INF <= x <= INF`, ``-INF <= y <= f`` + * + * Range: `-INF <= z <= INF` + * + * This function operates on double-precision floating point values, use + * SDL_copysignf for single-precision floats. + * + * \param x floating point value to use as the magnitude. + * \param y floating point value to use as the sign. + * \returns the floating point value with the sign of y and the magnitude of + * x. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_copysignf + * \sa SDL_fabs + */ +extern SDL_DECLSPEC double SDLCALL SDL_copysign(double x, double y); + +/** + * Copy the sign of one floating-point value to another. + * + * The definition of copysign is that ``copysign(x, y) = abs(x) * sign(y)``. + * + * Domain: `-INF <= x <= INF`, ``-INF <= y <= f`` + * + * Range: `-INF <= z <= INF` + * + * This function operates on single-precision floating point values, use + * SDL_copysign for double-precision floats. + * + * \param x floating point value to use as the magnitude. + * \param y floating point value to use as the sign. + * \returns the floating point value with the sign of y and the magnitude of + * x. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_copysign + * \sa SDL_fabsf + */ +extern SDL_DECLSPEC float SDLCALL SDL_copysignf(float x, float y); + +/** + * Compute the cosine of `x`. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-1 <= y <= 1` + * + * This function operates on double-precision floating point values, use + * SDL_cosf for single-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value, in radians. + * \returns cosine of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_cosf + * \sa SDL_acos + * \sa SDL_sin + */ +extern SDL_DECLSPEC double SDLCALL SDL_cos(double x); + +/** + * Compute the cosine of `x`. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-1 <= y <= 1` + * + * This function operates on single-precision floating point values, use + * SDL_cos for double-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value, in radians. + * \returns cosine of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_cos + * \sa SDL_acosf + * \sa SDL_sinf + */ +extern SDL_DECLSPEC float SDLCALL SDL_cosf(float x); + +/** + * Compute the exponential of `x`. + * + * The definition of `y = exp(x)` is `y = e^x`, where `e` is the base of the + * natural logarithm. The inverse is the natural logarithm, SDL_log. + * + * Domain: `-INF <= x <= INF` + * + * Range: `0 <= y <= INF` + * + * The output will overflow if `exp(x)` is too large to be represented. + * + * This function operates on double-precision floating point values, use + * SDL_expf for single-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. + * \returns value of `e^x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_expf + * \sa SDL_log + */ +extern SDL_DECLSPEC double SDLCALL SDL_exp(double x); + +/** + * Compute the exponential of `x`. + * + * The definition of `y = exp(x)` is `y = e^x`, where `e` is the base of the + * natural logarithm. The inverse is the natural logarithm, SDL_logf. + * + * Domain: `-INF <= x <= INF` + * + * Range: `0 <= y <= INF` + * + * The output will overflow if `exp(x)` is too large to be represented. + * + * This function operates on single-precision floating point values, use + * SDL_exp for double-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. + * \returns value of `e^x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_exp + * \sa SDL_logf + */ +extern SDL_DECLSPEC float SDLCALL SDL_expf(float x); + +/** + * Compute the absolute value of `x` + * + * Domain: `-INF <= x <= INF` + * + * Range: `0 <= y <= INF` + * + * This function operates on double-precision floating point values, use + * SDL_fabsf for single-precision floats. + * + * \param x floating point value to use as the magnitude. + * \returns the absolute value of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_fabsf + */ +extern SDL_DECLSPEC double SDLCALL SDL_fabs(double x); + +/** + * Compute the absolute value of `x` + * + * Domain: `-INF <= x <= INF` + * + * Range: `0 <= y <= INF` + * + * This function operates on single-precision floating point values, use + * SDL_fabs for double-precision floats. + * + * \param x floating point value to use as the magnitude. + * \returns the absolute value of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_fabs + */ +extern SDL_DECLSPEC float SDLCALL SDL_fabsf(float x); + +/** + * Compute the floor of `x`. + * + * The floor of `x` is the largest integer `y` such that `y > x`, i.e `x` + * rounded down to the nearest integer. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-INF <= y <= INF`, y integer + * + * This function operates on double-precision floating point values, use + * SDL_floorf for single-precision floats. + * + * \param x floating point value. + * \returns the floor of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_floorf + * \sa SDL_ceil + * \sa SDL_trunc + * \sa SDL_round + * \sa SDL_lround + */ +extern SDL_DECLSPEC double SDLCALL SDL_floor(double x); + +/** + * Compute the floor of `x`. + * + * The floor of `x` is the largest integer `y` such that `y > x`, i.e `x` + * rounded down to the nearest integer. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-INF <= y <= INF`, y integer + * + * This function operates on single-precision floating point values, use + * SDL_floor for double-precision floats. + * + * \param x floating point value. + * \returns the floor of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_floor + * \sa SDL_ceilf + * \sa SDL_truncf + * \sa SDL_roundf + * \sa SDL_lroundf + */ +extern SDL_DECLSPEC float SDLCALL SDL_floorf(float x); + +/** + * Truncate `x` to an integer. + * + * Rounds `x` to the next closest integer to 0. This is equivalent to removing + * the fractional part of `x`, leaving only the integer part. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-INF <= y <= INF`, y integer + * + * This function operates on double-precision floating point values, use + * SDL_truncf for single-precision floats. + * + * \param x floating point value. + * \returns `x` truncated to an integer. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_truncf + * \sa SDL_fmod + * \sa SDL_ceil + * \sa SDL_floor + * \sa SDL_round + * \sa SDL_lround + */ +extern SDL_DECLSPEC double SDLCALL SDL_trunc(double x); + +/** + * Truncate `x` to an integer. + * + * Rounds `x` to the next closest integer to 0. This is equivalent to removing + * the fractional part of `x`, leaving only the integer part. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-INF <= y <= INF`, y integer + * + * This function operates on single-precision floating point values, use + * SDL_trunc for double-precision floats. + * + * \param x floating point value. + * \returns `x` truncated to an integer. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_trunc + * \sa SDL_fmodf + * \sa SDL_ceilf + * \sa SDL_floorf + * \sa SDL_roundf + * \sa SDL_lroundf + */ +extern SDL_DECLSPEC float SDLCALL SDL_truncf(float x); + +/** + * Return the floating-point remainder of `x / y` + * + * Divides `x` by `y`, and returns the remainder. + * + * Domain: `-INF <= x <= INF`, `-INF <= y <= INF`, `y != 0` + * + * Range: `-y <= z <= y` + * + * This function operates on double-precision floating point values, use + * SDL_fmodf for single-precision floats. + * + * \param x the numerator. + * \param y the denominator. Must not be 0. + * \returns the remainder of `x / y`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_fmodf + * \sa SDL_modf + * \sa SDL_trunc + * \sa SDL_ceil + * \sa SDL_floor + * \sa SDL_round + * \sa SDL_lround + */ +extern SDL_DECLSPEC double SDLCALL SDL_fmod(double x, double y); + +/** + * Return the floating-point remainder of `x / y` + * + * Divides `x` by `y`, and returns the remainder. + * + * Domain: `-INF <= x <= INF`, `-INF <= y <= INF`, `y != 0` + * + * Range: `-y <= z <= y` + * + * This function operates on single-precision floating point values, use + * SDL_fmod for double-precision floats. + * + * \param x the numerator. + * \param y the denominator. Must not be 0. + * \returns the remainder of `x / y`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_fmod + * \sa SDL_truncf + * \sa SDL_modff + * \sa SDL_ceilf + * \sa SDL_floorf + * \sa SDL_roundf + * \sa SDL_lroundf + */ +extern SDL_DECLSPEC float SDLCALL SDL_fmodf(float x, float y); + +/** + * Return whether the value is infinity. + * + * \param x double-precision floating point value. + * \returns non-zero if the value is infinity, 0 otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_isinff + */ +extern SDL_DECLSPEC int SDLCALL SDL_isinf(double x); + +/** + * Return whether the value is infinity. + * + * \param x floating point value. + * \returns non-zero if the value is infinity, 0 otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_isinf + */ +extern SDL_DECLSPEC int SDLCALL SDL_isinff(float x); + +/** + * Return whether the value is NaN. + * + * \param x double-precision floating point value. + * \returns non-zero if the value is NaN, 0 otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_isnanf + */ +extern SDL_DECLSPEC int SDLCALL SDL_isnan(double x); + +/** + * Return whether the value is NaN. + * + * \param x floating point value. + * \returns non-zero if the value is NaN, 0 otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_isnan + */ +extern SDL_DECLSPEC int SDLCALL SDL_isnanf(float x); + +/** + * Compute the natural logarithm of `x`. + * + * Domain: `0 < x <= INF` + * + * Range: `-INF <= y <= INF` + * + * It is an error for `x` to be less than or equal to 0. + * + * This function operates on double-precision floating point values, use + * SDL_logf for single-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. Must be greater than 0. + * \returns the natural logarithm of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_logf + * \sa SDL_log10 + * \sa SDL_exp + */ +extern SDL_DECLSPEC double SDLCALL SDL_log(double x); + +/** + * Compute the natural logarithm of `x`. + * + * Domain: `0 < x <= INF` + * + * Range: `-INF <= y <= INF` + * + * It is an error for `x` to be less than or equal to 0. + * + * This function operates on single-precision floating point values, use + * SDL_log for double-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. Must be greater than 0. + * \returns the natural logarithm of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_log + * \sa SDL_expf + */ +extern SDL_DECLSPEC float SDLCALL SDL_logf(float x); + +/** + * Compute the base-10 logarithm of `x`. + * + * Domain: `0 < x <= INF` + * + * Range: `-INF <= y <= INF` + * + * It is an error for `x` to be less than or equal to 0. + * + * This function operates on double-precision floating point values, use + * SDL_log10f for single-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. Must be greater than 0. + * \returns the logarithm of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_log10f + * \sa SDL_log + * \sa SDL_pow + */ +extern SDL_DECLSPEC double SDLCALL SDL_log10(double x); + +/** + * Compute the base-10 logarithm of `x`. + * + * Domain: `0 < x <= INF` + * + * Range: `-INF <= y <= INF` + * + * It is an error for `x` to be less than or equal to 0. + * + * This function operates on single-precision floating point values, use + * SDL_log10 for double-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. Must be greater than 0. + * \returns the logarithm of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_log10 + * \sa SDL_logf + * \sa SDL_powf + */ +extern SDL_DECLSPEC float SDLCALL SDL_log10f(float x); + +/** + * Split `x` into integer and fractional parts + * + * This function operates on double-precision floating point values, use + * SDL_modff for single-precision floats. + * + * \param x floating point value. + * \param y output pointer to store the integer part of `x`. + * \returns the fractional part of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_modff + * \sa SDL_trunc + * \sa SDL_fmod + */ +extern SDL_DECLSPEC double SDLCALL SDL_modf(double x, double *y); + +/** + * Split `x` into integer and fractional parts + * + * This function operates on single-precision floating point values, use + * SDL_modf for double-precision floats. + * + * \param x floating point value. + * \param y output pointer to store the integer part of `x`. + * \returns the fractional part of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_modf + * \sa SDL_truncf + * \sa SDL_fmodf + */ +extern SDL_DECLSPEC float SDLCALL SDL_modff(float x, float *y); + +/** + * Raise `x` to the power `y` + * + * Domain: `-INF <= x <= INF`, `-INF <= y <= INF` + * + * Range: `-INF <= z <= INF` + * + * If `y` is the base of the natural logarithm (e), consider using SDL_exp + * instead. + * + * This function operates on double-precision floating point values, use + * SDL_powf for single-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x the base. + * \param y the exponent. + * \returns `x` raised to the power `y`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_powf + * \sa SDL_exp + * \sa SDL_log + */ +extern SDL_DECLSPEC double SDLCALL SDL_pow(double x, double y); + +/** + * Raise `x` to the power `y` + * + * Domain: `-INF <= x <= INF`, `-INF <= y <= INF` + * + * Range: `-INF <= z <= INF` + * + * If `y` is the base of the natural logarithm (e), consider using SDL_exp + * instead. + * + * This function operates on single-precision floating point values, use + * SDL_pow for double-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x the base. + * \param y the exponent. + * \returns `x` raised to the power `y`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_pow + * \sa SDL_expf + * \sa SDL_logf + */ +extern SDL_DECLSPEC float SDLCALL SDL_powf(float x, float y); + +/** + * Round `x` to the nearest integer. + * + * Rounds `x` to the nearest integer. Values halfway between integers will be + * rounded away from zero. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-INF <= y <= INF`, y integer + * + * This function operates on double-precision floating point values, use + * SDL_roundf for single-precision floats. To get the result as an integer + * type, use SDL_lround. + * + * \param x floating point value. + * \returns the nearest integer to `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_roundf + * \sa SDL_lround + * \sa SDL_floor + * \sa SDL_ceil + * \sa SDL_trunc + */ +extern SDL_DECLSPEC double SDLCALL SDL_round(double x); + +/** + * Round `x` to the nearest integer. + * + * Rounds `x` to the nearest integer. Values halfway between integers will be + * rounded away from zero. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-INF <= y <= INF`, y integer + * + * This function operates on single-precision floating point values, use + * SDL_round for double-precision floats. To get the result as an integer + * type, use SDL_lroundf. + * + * \param x floating point value. + * \returns the nearest integer to `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_round + * \sa SDL_lroundf + * \sa SDL_floorf + * \sa SDL_ceilf + * \sa SDL_truncf + */ +extern SDL_DECLSPEC float SDLCALL SDL_roundf(float x); + +/** + * Round `x` to the nearest integer representable as a long + * + * Rounds `x` to the nearest integer. Values halfway between integers will be + * rounded away from zero. + * + * Domain: `-INF <= x <= INF` + * + * Range: `MIN_LONG <= y <= MAX_LONG` + * + * This function operates on double-precision floating point values, use + * SDL_lroundf for single-precision floats. To get the result as a + * floating-point type, use SDL_round. + * + * \param x floating point value. + * \returns the nearest integer to `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_lroundf + * \sa SDL_round + * \sa SDL_floor + * \sa SDL_ceil + * \sa SDL_trunc + */ +extern SDL_DECLSPEC long SDLCALL SDL_lround(double x); + +/** + * Round `x` to the nearest integer representable as a long + * + * Rounds `x` to the nearest integer. Values halfway between integers will be + * rounded away from zero. + * + * Domain: `-INF <= x <= INF` + * + * Range: `MIN_LONG <= y <= MAX_LONG` + * + * This function operates on single-precision floating point values, use + * SDL_lround for double-precision floats. To get the result as a + * floating-point type, use SDL_roundf. + * + * \param x floating point value. + * \returns the nearest integer to `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_lround + * \sa SDL_roundf + * \sa SDL_floorf + * \sa SDL_ceilf + * \sa SDL_truncf + */ +extern SDL_DECLSPEC long SDLCALL SDL_lroundf(float x); + +/** + * Scale `x` by an integer power of two. + * + * Multiplies `x` by the `n`th power of the floating point radix (always 2). + * + * Domain: `-INF <= x <= INF`, `n` integer + * + * Range: `-INF <= y <= INF` + * + * This function operates on double-precision floating point values, use + * SDL_scalbnf for single-precision floats. + * + * \param x floating point value to be scaled. + * \param n integer exponent. + * \returns `x * 2^n`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_scalbnf + * \sa SDL_pow + */ +extern SDL_DECLSPEC double SDLCALL SDL_scalbn(double x, int n); + +/** + * Scale `x` by an integer power of two. + * + * Multiplies `x` by the `n`th power of the floating point radix (always 2). + * + * Domain: `-INF <= x <= INF`, `n` integer + * + * Range: `-INF <= y <= INF` + * + * This function operates on single-precision floating point values, use + * SDL_scalbn for double-precision floats. + * + * \param x floating point value to be scaled. + * \param n integer exponent. + * \returns `x * 2^n`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_scalbn + * \sa SDL_powf + */ +extern SDL_DECLSPEC float SDLCALL SDL_scalbnf(float x, int n); + +/** + * Compute the sine of `x`. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-1 <= y <= 1` + * + * This function operates on double-precision floating point values, use + * SDL_sinf for single-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value, in radians. + * \returns sine of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_sinf + * \sa SDL_asin + * \sa SDL_cos + */ +extern SDL_DECLSPEC double SDLCALL SDL_sin(double x); + +/** + * Compute the sine of `x`. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-1 <= y <= 1` + * + * This function operates on single-precision floating point values, use + * SDL_sin for double-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value, in radians. + * \returns sine of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_sin + * \sa SDL_asinf + * \sa SDL_cosf + */ +extern SDL_DECLSPEC float SDLCALL SDL_sinf(float x); + +/** + * Compute the square root of `x`. + * + * Domain: `0 <= x <= INF` + * + * Range: `0 <= y <= INF` + * + * This function operates on double-precision floating point values, use + * SDL_sqrtf for single-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. Must be greater than or equal to 0. + * \returns square root of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_sqrtf + */ +extern SDL_DECLSPEC double SDLCALL SDL_sqrt(double x); + +/** + * Compute the square root of `x`. + * + * Domain: `0 <= x <= INF` + * + * Range: `0 <= y <= INF` + * + * This function operates on single-precision floating point values, use + * SDL_sqrt for double-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value. Must be greater than or equal to 0. + * \returns square root of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_sqrt + */ +extern SDL_DECLSPEC float SDLCALL SDL_sqrtf(float x); + +/** + * Compute the tangent of `x`. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-INF <= y <= INF` + * + * This function operates on double-precision floating point values, use + * SDL_tanf for single-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value, in radians. + * \returns tangent of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_tanf + * \sa SDL_sin + * \sa SDL_cos + * \sa SDL_atan + * \sa SDL_atan2 + */ +extern SDL_DECLSPEC double SDLCALL SDL_tan(double x); + +/** + * Compute the tangent of `x`. + * + * Domain: `-INF <= x <= INF` + * + * Range: `-INF <= y <= INF` + * + * This function operates on single-precision floating point values, use + * SDL_tan for double-precision floats. + * + * This function may use a different approximation across different versions, + * platforms and configurations. i.e, it can return a different value given + * the same input on different machines or operating systems, or if SDL is + * updated. + * + * \param x floating point value, in radians. + * \returns tangent of `x`. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_tan + * \sa SDL_sinf + * \sa SDL_cosf + * \sa SDL_atanf + * \sa SDL_atan2f + */ +extern SDL_DECLSPEC float SDLCALL SDL_tanf(float x); + +/** + * An opaque handle representing string encoding conversion state. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_iconv_open + */ +typedef struct SDL_iconv_data_t *SDL_iconv_t; + +/** + * This function allocates a context for the specified character set + * conversion. + * + * \param tocode The target character encoding, must not be NULL. + * \param fromcode The source character encoding, must not be NULL. + * \returns a handle that must be freed with SDL_iconv_close, or + * SDL_ICONV_ERROR on failure. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_iconv + * \sa SDL_iconv_close + * \sa SDL_iconv_string + */ +extern SDL_DECLSPEC SDL_iconv_t SDLCALL SDL_iconv_open(const char *tocode, + const char *fromcode); + +/** + * This function frees a context used for character set conversion. + * + * \param cd The character set conversion handle. + * \returns 0 on success, or -1 on failure. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_iconv + * \sa SDL_iconv_open + * \sa SDL_iconv_string + */ +extern SDL_DECLSPEC int SDLCALL SDL_iconv_close(SDL_iconv_t cd); + +/** + * This function converts text between encodings, reading from and writing to + * a buffer. + * + * It returns the number of succesful conversions on success. On error, + * SDL_ICONV_E2BIG is returned when the output buffer is too small, or + * SDL_ICONV_EILSEQ is returned when an invalid input sequence is encountered, + * or SDL_ICONV_EINVAL is returned when an incomplete input sequence is + * encountered. + * + * On exit: + * + * - inbuf will point to the beginning of the next multibyte sequence. On + * error, this is the location of the problematic input sequence. On + * success, this is the end of the input sequence. + * - inbytesleft will be set to the number of bytes left to convert, which + * will be 0 on success. + * - outbuf will point to the location where to store the next output byte. + * - outbytesleft will be set to the number of bytes left in the output + * buffer. + * + * \param cd The character set conversion context, created in + * SDL_iconv_open(). + * \param inbuf Address of variable that points to the first character of the + * input sequence. + * \param inbytesleft The number of bytes in the input buffer. + * \param outbuf Address of variable that points to the output buffer. + * \param outbytesleft The number of bytes in the output buffer. + * \returns the number of conversions on success, or a negative error code. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_iconv_open + * \sa SDL_iconv_close + * \sa SDL_iconv_string + */ +extern SDL_DECLSPEC size_t SDLCALL SDL_iconv(SDL_iconv_t cd, const char **inbuf, + size_t *inbytesleft, char **outbuf, + size_t *outbytesleft); + +#define SDL_ICONV_ERROR (size_t)-1 /**< Generic error. Check SDL_GetError()? */ +#define SDL_ICONV_E2BIG (size_t)-2 /**< Output buffer was too small. */ +#define SDL_ICONV_EILSEQ (size_t)-3 /**< Invalid input sequence was encountered. */ +#define SDL_ICONV_EINVAL (size_t)-4 /**< Incomplete input sequence was encountered. */ + + +/** + * Helper function to convert a string's encoding in one call. + * + * This function converts a buffer or string between encodings in one pass. + * + * The string does not need to be NULL-terminated; this function operates on + * the number of bytes specified in `inbytesleft` whether there is a NULL + * character anywhere in the buffer. + * + * The returned string is owned by the caller, and should be passed to + * SDL_free when no longer needed. + * + * \param tocode the character encoding of the output string. Examples are + * "UTF-8", "UCS-4", etc. + * \param fromcode the character encoding of data in `inbuf`. + * \param inbuf the string to convert to a different encoding. + * \param inbytesleft the size of the input string _in bytes_. + * \returns a new string, converted to the new encoding, or NULL on error. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_iconv_open + * \sa SDL_iconv_close + * \sa SDL_iconv + */ +extern SDL_DECLSPEC char * SDLCALL SDL_iconv_string(const char *tocode, + const char *fromcode, + const char *inbuf, + size_t inbytesleft); + +/* Some helper macros for common SDL_iconv_string cases... */ + +/** + * Convert a UTF-8 string to the current locale's character encoding. + * + * This is a helper macro that might be more clear than calling + * SDL_iconv_string directly. However, it double-evaluates its parameter, so + * do not use an expression with side-effects here. + * + * \param S the string to convert. + * \returns a new string, converted to the new encoding, or NULL on error. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_iconv_utf8_locale(S) SDL_iconv_string("", "UTF-8", S, SDL_strlen(S)+1) + +/** + * Convert a UTF-8 string to UCS-2. + * + * This is a helper macro that might be more clear than calling + * SDL_iconv_string directly. However, it double-evaluates its parameter, so + * do not use an expression with side-effects here. + * + * \param S the string to convert. + * \returns a new string, converted to the new encoding, or NULL on error. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_iconv_utf8_ucs2(S) (Uint16 *)SDL_iconv_string("UCS-2", "UTF-8", S, SDL_strlen(S)+1) + +/** + * Convert a UTF-8 string to UCS-4. + * + * This is a helper macro that might be more clear than calling + * SDL_iconv_string directly. However, it double-evaluates its parameter, so + * do not use an expression with side-effects here. + * + * \param S the string to convert. + * \returns a new string, converted to the new encoding, or NULL on error. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_iconv_utf8_ucs4(S) (Uint32 *)SDL_iconv_string("UCS-4", "UTF-8", S, SDL_strlen(S)+1) + +/** + * Convert a wchar_t string to UTF-8. + * + * This is a helper macro that might be more clear than calling + * SDL_iconv_string directly. However, it double-evaluates its parameter, so + * do not use an expression with side-effects here. + * + * \param S the string to convert. + * \returns a new string, converted to the new encoding, or NULL on error. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_iconv_wchar_utf8(S) SDL_iconv_string("UTF-8", "WCHAR_T", (char *)S, (SDL_wcslen(S)+1)*sizeof(wchar_t)) + + +/* force builds using Clang's static analysis tools to use literal C runtime + here, since there are possibly tests that are ineffective otherwise. */ +#if defined(__clang_analyzer__) && !defined(SDL_DISABLE_ANALYZE_MACROS) + +/* The analyzer knows about strlcpy even when the system doesn't provide it */ +#if !defined(HAVE_STRLCPY) && !defined(strlcpy) +size_t strlcpy(char *dst, const char *src, size_t size); +#endif + +/* The analyzer knows about strlcat even when the system doesn't provide it */ +#if !defined(HAVE_STRLCAT) && !defined(strlcat) +size_t strlcat(char *dst, const char *src, size_t size); +#endif + +#if !defined(HAVE_WCSLCPY) && !defined(wcslcpy) +size_t wcslcpy(wchar_t *dst, const wchar_t *src, size_t size); +#endif + +#if !defined(HAVE_WCSLCAT) && !defined(wcslcat) +size_t wcslcat(wchar_t *dst, const wchar_t *src, size_t size); +#endif + +#ifndef _WIN32 +/* strdup is not ANSI but POSIX, and its prototype might be hidden... */ +/* not for windows: might conflict with string.h where strdup may have + * dllimport attribute: https://github.com/libsdl-org/SDL/issues/12948 */ +char *strdup(const char *str); +#endif + +/* Starting LLVM 16, the analyser errors out if these functions do not have + their prototype defined (clang-diagnostic-implicit-function-declaration) */ +#include +#include + +#define SDL_malloc malloc +#define SDL_calloc calloc +#define SDL_realloc realloc +#define SDL_free free +#ifndef SDL_memcpy +#define SDL_memcpy memcpy +#endif +#ifndef SDL_memmove +#define SDL_memmove memmove +#endif +#ifndef SDL_memset +#define SDL_memset memset +#endif +#define SDL_memcmp memcmp +#define SDL_strlcpy strlcpy +#define SDL_strlcat strlcat +#define SDL_strlen strlen +#define SDL_wcslen wcslen +#define SDL_wcslcpy wcslcpy +#define SDL_wcslcat wcslcat +#define SDL_strdup strdup +#define SDL_wcsdup wcsdup +#define SDL_strchr strchr +#define SDL_strrchr strrchr +#define SDL_strstr strstr +#define SDL_wcsstr wcsstr +#define SDL_strtok_r strtok_r +#define SDL_strcmp strcmp +#define SDL_wcscmp wcscmp +#define SDL_strncmp strncmp +#define SDL_wcsncmp wcsncmp +#define SDL_strcasecmp strcasecmp +#define SDL_strncasecmp strncasecmp +#define SDL_strpbrk strpbrk +#define SDL_sscanf sscanf +#define SDL_vsscanf vsscanf +#define SDL_snprintf snprintf +#define SDL_vsnprintf vsnprintf +#endif + +/** + * Multiply two integers, checking for overflow. + * + * If `a * b` would overflow, return false. + * + * Otherwise store `a * b` via ret and return true. + * + * \param a the multiplicand. + * \param b the multiplier. + * \param ret on non-overflow output, stores the multiplication result, may + * not be NULL. + * \returns false on overflow, true if result is multiplied without overflow. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE bool SDL_size_mul_check_overflow(size_t a, size_t b, size_t *ret) +{ + if (a != 0 && b > SDL_SIZE_MAX / a) { + return false; + } + *ret = a * b; + return true; +} + +#ifndef SDL_WIKI_DOCUMENTATION_SECTION +#if SDL_HAS_BUILTIN(__builtin_mul_overflow) +/* This needs to be wrapped in an inline rather than being a direct #define, + * because __builtin_mul_overflow() is type-generic, but we want to be + * consistent about interpreting a and b as size_t. */ +SDL_FORCE_INLINE bool SDL_size_mul_check_overflow_builtin(size_t a, size_t b, size_t *ret) +{ + return (__builtin_mul_overflow(a, b, ret) == 0); +} +#define SDL_size_mul_check_overflow(a, b, ret) SDL_size_mul_check_overflow_builtin(a, b, ret) +#endif +#endif + +/** + * Add two integers, checking for overflow. + * + * If `a + b` would overflow, return false. + * + * Otherwise store `a + b` via ret and return true. + * + * \param a the first addend. + * \param b the second addend. + * \param ret on non-overflow output, stores the addition result, may not be + * NULL. + * \returns false on overflow, true if result is added without overflow. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +SDL_FORCE_INLINE bool SDL_size_add_check_overflow(size_t a, size_t b, size_t *ret) +{ + if (b > SDL_SIZE_MAX - a) { + return false; + } + *ret = a + b; + return true; +} + +#ifndef SDL_WIKI_DOCUMENTATION_SECTION +#if SDL_HAS_BUILTIN(__builtin_add_overflow) +/* This needs to be wrapped in an inline rather than being a direct #define, + * the same as the call to __builtin_mul_overflow() above. */ +SDL_FORCE_INLINE bool SDL_size_add_check_overflow_builtin(size_t a, size_t b, size_t *ret) +{ + return (__builtin_add_overflow(a, b, ret) == 0); +} +#define SDL_size_add_check_overflow(a, b, ret) SDL_size_add_check_overflow_builtin(a, b, ret) +#endif +#endif + +/* This is a generic function pointer which should be cast to the type you expect */ +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/** + * A generic function pointer. + * + * In theory, generic function pointers should use this, instead of `void *`, + * since some platforms could treat code addresses differently than data + * addresses. Although in current times no popular platforms make this + * distinction, it is more correct and portable to use the correct type for a + * generic pointer. + * + * If for some reason you need to force this typedef to be an actual `void *`, + * perhaps to work around a compiler or existing code, you can define + * `SDL_FUNCTION_POINTER_IS_VOID_POINTER` before including any SDL headers. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef void (*SDL_FunctionPointer)(void); +#elif defined(SDL_FUNCTION_POINTER_IS_VOID_POINTER) +typedef void *SDL_FunctionPointer; +#else +typedef void (*SDL_FunctionPointer)(void); +#endif + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_stdinc_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_storage.h b/thirdparty/sdl/include/SDL3/SDL_storage.h new file mode 100644 index 00000000000..6837ebaacf0 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_storage.h @@ -0,0 +1,682 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryStorage + * + * The storage API is a high-level API designed to abstract away the + * portability issues that come up when using something lower-level (in SDL's + * case, this sits on top of the [Filesystem](CategoryFilesystem) and + * [IOStream](CategoryIOStream) subsystems). It is significantly more + * restrictive than a typical filesystem API, for a number of reasons: + * + * 1. **What to Access:** A common pitfall with existing filesystem APIs is + * the assumption that all storage is monolithic. However, many other + * platforms (game consoles in particular) are more strict about what _type_ + * of filesystem is being accessed; for example, game content and user data + * are usually two separate storage devices with entirely different + * characteristics (and possibly different low-level APIs altogether!). + * + * 2. **How to Access:** Another common mistake is applications assuming that + * all storage is universally writeable - again, many platforms treat game + * content and user data as two separate storage devices, and only user data + * is writeable while game content is read-only. + * + * 3. **When to Access:** The most common portability issue with filesystem + * access is _timing_ - you cannot always assume that the storage device is + * always accessible all of the time, nor can you assume that there are no + * limits to how long you have access to a particular device. + * + * Consider the following example: + * + * ```c + * void ReadGameData(void) + * { + * extern char** fileNames; + * extern size_t numFiles; + * for (size_t i = 0; i < numFiles; i += 1) { + * FILE *data = fopen(fileNames[i], "rwb"); + * if (data == NULL) { + * // Something bad happened! + * } else { + * // A bunch of stuff happens here + * fclose(data); + * } + * } + * } + * + * void ReadSave(void) + * { + * FILE *save = fopen("saves/save0.sav", "rb"); + * if (save == NULL) { + * // Something bad happened! + * } else { + * // A bunch of stuff happens here + * fclose(save); + * } + * } + * + * void WriteSave(void) + * { + * FILE *save = fopen("saves/save0.sav", "wb"); + * if (save == NULL) { + * // Something bad happened! + * } else { + * // A bunch of stuff happens here + * fclose(save); + * } + * } + * ``` + * + * Going over the bullet points again: + * + * 1. **What to Access:** This code accesses a global filesystem; game data + * and saves are all presumed to be in the current working directory (which + * may or may not be the game's installation folder!). + * + * 2. **How to Access:** This code assumes that content paths are writeable, + * and that save data is also writeable despite being in the same location as + * the game data. + * + * 3. **When to Access:** This code assumes that they can be called at any + * time, since the filesystem is always accessible and has no limits on how + * long the filesystem is being accessed. + * + * Due to these assumptions, the filesystem code is not portable and will fail + * under these common scenarios: + * + * - The game is installed on a device that is read-only, both content loading + * and game saves will fail or crash outright + * - Game/User storage is not implicitly mounted, so no files will be found + * for either scenario when a platform requires explicitly mounting + * filesystems + * - Save data may not be safe since the I/O is not being flushed or + * validated, so an error occurring elsewhere in the program may result in + * missing/corrupted save data + * + * When using SDL_Storage, these types of problems are virtually impossible to + * trip over: + * + * ```c + * void ReadGameData(void) + * { + * extern char** fileNames; + * extern size_t numFiles; + * + * SDL_Storage *title = SDL_OpenTitleStorage(NULL, 0); + * if (title == NULL) { + * // Something bad happened! + * } + * while (!SDL_StorageReady(title)) { + * SDL_Delay(1); + * } + * + * for (size_t i = 0; i < numFiles; i += 1) { + * void* dst; + * Uint64 dstLen = 0; + * + * if (SDL_GetStorageFileSize(title, fileNames[i], &dstLen) && dstLen > 0) { + * dst = SDL_malloc(dstLen); + * if (SDL_ReadStorageFile(title, fileNames[i], dst, dstLen)) { + * // A bunch of stuff happens here + * } else { + * // Something bad happened! + * } + * SDL_free(dst); + * } else { + * // Something bad happened! + * } + * } + * + * SDL_CloseStorage(title); + * } + * + * void ReadSave(void) + * { + * SDL_Storage *user = SDL_OpenUserStorage("libsdl", "Storage Example", 0); + * if (user == NULL) { + * // Something bad happened! + * } + * while (!SDL_StorageReady(user)) { + * SDL_Delay(1); + * } + * + * Uint64 saveLen = 0; + * if (SDL_GetStorageFileSize(user, "save0.sav", &saveLen) && saveLen > 0) { + * void* dst = SDL_malloc(saveLen); + * if (SDL_ReadStorageFile(user, "save0.sav", dst, saveLen)) { + * // A bunch of stuff happens here + * } else { + * // Something bad happened! + * } + * SDL_free(dst); + * } else { + * // Something bad happened! + * } + * + * SDL_CloseStorage(user); + * } + * + * void WriteSave(void) + * { + * SDL_Storage *user = SDL_OpenUserStorage("libsdl", "Storage Example", 0); + * if (user == NULL) { + * // Something bad happened! + * } + * while (!SDL_StorageReady(user)) { + * SDL_Delay(1); + * } + * + * extern void *saveData; // A bunch of stuff happened here... + * extern Uint64 saveLen; + * if (!SDL_WriteStorageFile(user, "save0.sav", saveData, saveLen)) { + * // Something bad happened! + * } + * + * SDL_CloseStorage(user); + * } + * ``` + * + * Note the improvements that SDL_Storage makes: + * + * 1. **What to Access:** This code explicitly reads from a title or user + * storage device based on the context of the function. + * + * 2. **How to Access:** This code explicitly uses either a read or write + * function based on the context of the function. + * + * 3. **When to Access:** This code explicitly opens the device when it needs + * to, and closes it when it is finished working with the filesystem. + * + * The result is an application that is significantly more robust against the + * increasing demands of platforms and their filesystems! + * + * A publicly available example of an SDL_Storage backend is the + * [Steam Cloud](https://partner.steamgames.com/doc/features/cloud) + * backend - you can initialize Steamworks when starting the program, and then + * SDL will recognize that Steamworks is initialized and automatically use + * ISteamRemoteStorage when the application opens user storage. More + * importantly, when you _open_ storage it knows to begin a "batch" of + * filesystem operations, and when you _close_ storage it knows to end and + * flush the batch. This is used by Steam to support + * [Dynamic Cloud Sync](https://steamcommunity.com/groups/steamworks/announcements/detail/3142949576401813670) + * ; users can save data on one PC, put the device to sleep, and then continue + * playing on another PC (and vice versa) with the save data fully + * synchronized across all devices, allowing for a seamless experience without + * having to do full restarts of the program. + * + * ## Notes on valid paths + * + * All paths in the Storage API use Unix-style path separators ('/'). Using a + * different path separator will not work, even if the underlying platform + * would otherwise accept it. This is to keep code using the Storage API + * portable between platforms and Storage implementations and simplify app + * code. + * + * Paths with relative directories ("." and "..") are forbidden by the Storage + * API. + * + * All valid UTF-8 strings (discounting the NULL terminator character and the + * '/' path separator) are usable for filenames, however, an underlying + * Storage implementation may not support particularly strange sequences and + * refuse to create files with those names, etc. + */ + +#ifndef SDL_storage_h_ +#define SDL_storage_h_ + +#include +#include +#include +#include + +#include + +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Function interface for SDL_Storage. + * + * Apps that want to supply a custom implementation of SDL_Storage will fill + * in all the functions in this struct, and then pass it to SDL_OpenStorage to + * create a custom SDL_Storage object. + * + * It is not usually necessary to do this; SDL provides standard + * implementations for many things you might expect to do with an SDL_Storage. + * + * This structure should be initialized using SDL_INIT_INTERFACE() + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_INIT_INTERFACE + */ +typedef struct SDL_StorageInterface +{ + /* The version of this interface */ + Uint32 version; + + /* Called when the storage is closed */ + bool (SDLCALL *close)(void *userdata); + + /* Optional, returns whether the storage is currently ready for access */ + bool (SDLCALL *ready)(void *userdata); + + /* Enumerate a directory, optional for write-only storage */ + bool (SDLCALL *enumerate)(void *userdata, const char *path, SDL_EnumerateDirectoryCallback callback, void *callback_userdata); + + /* Get path information, optional for write-only storage */ + bool (SDLCALL *info)(void *userdata, const char *path, SDL_PathInfo *info); + + /* Read a file from storage, optional for write-only storage */ + bool (SDLCALL *read_file)(void *userdata, const char *path, void *destination, Uint64 length); + + /* Write a file to storage, optional for read-only storage */ + bool (SDLCALL *write_file)(void *userdata, const char *path, const void *source, Uint64 length); + + /* Create a directory, optional for read-only storage */ + bool (SDLCALL *mkdir)(void *userdata, const char *path); + + /* Remove a file or empty directory, optional for read-only storage */ + bool (SDLCALL *remove)(void *userdata, const char *path); + + /* Rename a path, optional for read-only storage */ + bool (SDLCALL *rename)(void *userdata, const char *oldpath, const char *newpath); + + /* Copy a file, optional for read-only storage */ + bool (SDLCALL *copy)(void *userdata, const char *oldpath, const char *newpath); + + /* Get the space remaining, optional for read-only storage */ + Uint64 (SDLCALL *space_remaining)(void *userdata); +} SDL_StorageInterface; + +/* Check the size of SDL_StorageInterface + * + * If this assert fails, either the compiler is padding to an unexpected size, + * or the interface has been updated and this should be updated to match and + * the code using this interface should be updated to handle the old version. + */ +SDL_COMPILE_TIME_ASSERT(SDL_StorageInterface_SIZE, + (sizeof(void *) == 4 && sizeof(SDL_StorageInterface) == 48) || + (sizeof(void *) == 8 && sizeof(SDL_StorageInterface) == 96)); + +/** + * An abstract interface for filesystem access. + * + * This is an opaque datatype. One can create this object using standard SDL + * functions like SDL_OpenTitleStorage or SDL_OpenUserStorage, etc, or create + * an object with a custom implementation using SDL_OpenStorage. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Storage SDL_Storage; + +/** + * Opens up a read-only container for the application's filesystem. + * + * \param override a path to override the backend's default title root. + * \param props a property list that may contain backend-specific information. + * \returns a title storage container on success or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseStorage + * \sa SDL_GetStorageFileSize + * \sa SDL_OpenUserStorage + * \sa SDL_ReadStorageFile + */ +extern SDL_DECLSPEC SDL_Storage * SDLCALL SDL_OpenTitleStorage(const char *override, SDL_PropertiesID props); + +/** + * Opens up a container for a user's unique read/write filesystem. + * + * While title storage can generally be kept open throughout runtime, user + * storage should only be opened when the client is ready to read/write files. + * This allows the backend to properly batch file operations and flush them + * when the container has been closed; ensuring safe and optimal save I/O. + * + * \param org the name of your organization. + * \param app the name of your application. + * \param props a property list that may contain backend-specific information. + * \returns a user storage container on success or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseStorage + * \sa SDL_GetStorageFileSize + * \sa SDL_GetStorageSpaceRemaining + * \sa SDL_OpenTitleStorage + * \sa SDL_ReadStorageFile + * \sa SDL_StorageReady + * \sa SDL_WriteStorageFile + */ +extern SDL_DECLSPEC SDL_Storage * SDLCALL SDL_OpenUserStorage(const char *org, const char *app, SDL_PropertiesID props); + +/** + * Opens up a container for local filesystem storage. + * + * This is provided for development and tools. Portable applications should + * use SDL_OpenTitleStorage() for access to game data and + * SDL_OpenUserStorage() for access to user data. + * + * \param path the base path prepended to all storage paths, or NULL for no + * base path. + * \returns a filesystem storage container on success or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseStorage + * \sa SDL_GetStorageFileSize + * \sa SDL_GetStorageSpaceRemaining + * \sa SDL_OpenTitleStorage + * \sa SDL_OpenUserStorage + * \sa SDL_ReadStorageFile + * \sa SDL_WriteStorageFile + */ +extern SDL_DECLSPEC SDL_Storage * SDLCALL SDL_OpenFileStorage(const char *path); + +/** + * Opens up a container using a client-provided storage interface. + * + * Applications do not need to use this function unless they are providing + * their own SDL_Storage implementation. If you just need an SDL_Storage, you + * should use the built-in implementations in SDL, like SDL_OpenTitleStorage() + * or SDL_OpenUserStorage(). + * + * This function makes a copy of `iface` and the caller does not need to keep + * it around after this call. + * + * \param iface the interface that implements this storage, initialized using + * SDL_INIT_INTERFACE(). + * \param userdata the pointer that will be passed to the interface functions. + * \returns a storage container on success or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CloseStorage + * \sa SDL_GetStorageFileSize + * \sa SDL_GetStorageSpaceRemaining + * \sa SDL_INIT_INTERFACE + * \sa SDL_ReadStorageFile + * \sa SDL_StorageReady + * \sa SDL_WriteStorageFile + */ +extern SDL_DECLSPEC SDL_Storage * SDLCALL SDL_OpenStorage(const SDL_StorageInterface *iface, void *userdata); + +/** + * Closes and frees a storage container. + * + * \param storage a storage container to close. + * \returns true if the container was freed with no errors, false otherwise; + * call SDL_GetError() for more information. Even if the function + * returns an error, the container data will be freed; the error is + * only for informational purposes. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_OpenFileStorage + * \sa SDL_OpenStorage + * \sa SDL_OpenTitleStorage + * \sa SDL_OpenUserStorage + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CloseStorage(SDL_Storage *storage); + +/** + * Checks if the storage container is ready to use. + * + * This function should be called in regular intervals until it returns true - + * however, it is not recommended to spinwait on this call, as the backend may + * depend on a synchronous message loop. You might instead poll this in your + * game's main loop while processing events and drawing a loading screen. + * + * \param storage a storage container to query. + * \returns true if the container is ready, false otherwise. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_StorageReady(SDL_Storage *storage); + +/** + * Query the size of a file within a storage container. + * + * \param storage a storage container to query. + * \param path the relative path of the file to query. + * \param length a pointer to be filled with the file's length. + * \returns true if the file could be queried or false on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ReadStorageFile + * \sa SDL_StorageReady + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetStorageFileSize(SDL_Storage *storage, const char *path, Uint64 *length); + +/** + * Synchronously read a file from a storage container into a client-provided + * buffer. + * + * The value of `length` must match the length of the file exactly; call + * SDL_GetStorageFileSize() to get this value. This behavior may be relaxed in + * a future release. + * + * \param storage a storage container to read from. + * \param path the relative path of the file to read. + * \param destination a client-provided buffer to read the file into. + * \param length the length of the destination buffer. + * \returns true if the file was read or false on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetStorageFileSize + * \sa SDL_StorageReady + * \sa SDL_WriteStorageFile + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadStorageFile(SDL_Storage *storage, const char *path, void *destination, Uint64 length); + +/** + * Synchronously write a file from client memory into a storage container. + * + * \param storage a storage container to write to. + * \param path the relative path of the file to write. + * \param source a client-provided buffer to write from. + * \param length the length of the source buffer. + * \returns true if the file was written or false on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetStorageSpaceRemaining + * \sa SDL_ReadStorageFile + * \sa SDL_StorageReady + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteStorageFile(SDL_Storage *storage, const char *path, const void *source, Uint64 length); + +/** + * Create a directory in a writable storage container. + * + * \param storage a storage container. + * \param path the path of the directory to create. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StorageReady + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CreateStorageDirectory(SDL_Storage *storage, const char *path); + +/** + * Enumerate a directory in a storage container through a callback function. + * + * This function provides every directory entry through an app-provided + * callback, called once for each directory entry, until all results have been + * provided or the callback returns either SDL_ENUM_SUCCESS or + * SDL_ENUM_FAILURE. + * + * This will return false if there was a system problem in general, or if a + * callback returns SDL_ENUM_FAILURE. A successful return means a callback + * returned SDL_ENUM_SUCCESS to halt enumeration, or all directory entries + * were enumerated. + * + * If `path` is NULL, this is treated as a request to enumerate the root of + * the storage container's tree. An empty string also works for this. + * + * \param storage a storage container. + * \param path the path of the directory to enumerate, or NULL for the root. + * \param callback a function that is called for each entry in the directory. + * \param userdata a pointer that is passed to `callback`. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StorageReady + */ +extern SDL_DECLSPEC bool SDLCALL SDL_EnumerateStorageDirectory(SDL_Storage *storage, const char *path, SDL_EnumerateDirectoryCallback callback, void *userdata); + +/** + * Remove a file or an empty directory in a writable storage container. + * + * \param storage a storage container. + * \param path the path of the directory to enumerate. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StorageReady + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RemoveStoragePath(SDL_Storage *storage, const char *path); + +/** + * Rename a file or directory in a writable storage container. + * + * \param storage a storage container. + * \param oldpath the old path. + * \param newpath the new path. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StorageReady + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RenameStoragePath(SDL_Storage *storage, const char *oldpath, const char *newpath); + +/** + * Copy a file in a writable storage container. + * + * \param storage a storage container. + * \param oldpath the old path. + * \param newpath the new path. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StorageReady + */ +extern SDL_DECLSPEC bool SDLCALL SDL_CopyStorageFile(SDL_Storage *storage, const char *oldpath, const char *newpath); + +/** + * Get information about a filesystem path in a storage container. + * + * \param storage a storage container. + * \param path the path to query. + * \param info a pointer filled in with information about the path, or NULL to + * check for the existence of a file. + * \returns true on success or false if the file doesn't exist, or another + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StorageReady + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetStoragePathInfo(SDL_Storage *storage, const char *path, SDL_PathInfo *info); + +/** + * Queries the remaining space in a storage container. + * + * \param storage a storage container to query. + * \returns the amount of remaining space, in bytes. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_StorageReady + * \sa SDL_WriteStorageFile + */ +extern SDL_DECLSPEC Uint64 SDLCALL SDL_GetStorageSpaceRemaining(SDL_Storage *storage); + +/** + * Enumerate a directory tree, filtered by pattern, and return a list. + * + * Files are filtered out if they don't match the string in `pattern`, which + * may contain wildcard characters `*` (match everything) and `?` (match one + * character). If pattern is NULL, no filtering is done and all results are + * returned. Subdirectories are permitted, and are specified with a path + * separator of '/'. Wildcard characters `*` and `?` never match a path + * separator. + * + * `flags` may be set to SDL_GLOB_CASEINSENSITIVE to make the pattern matching + * case-insensitive. + * + * The returned array is always NULL-terminated, for your iterating + * convenience, but if `count` is non-NULL, on return it will contain the + * number of items in the array, not counting the NULL terminator. + * + * If `path` is NULL, this is treated as a request to enumerate the root of + * the storage container's tree. An empty string also works for this. + * + * \param storage a storage container. + * \param path the path of the directory to enumerate, or NULL for the root. + * \param pattern the pattern that files in the directory must match. Can be + * NULL. + * \param flags `SDL_GLOB_*` bitflags that affect this search. + * \param count on return, will be set to the number of items in the returned + * array. Can be NULL. + * \returns an array of strings on success or NULL on failure; call + * SDL_GetError() for more information. The caller should pass the + * returned pointer to SDL_free when done with it. This is a single + * allocation that should be freed with SDL_free() when it is no + * longer needed. + * + * \threadsafety It is safe to call this function from any thread, assuming + * the `storage` object is thread-safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC char ** SDLCALL SDL_GlobStorageDirectory(SDL_Storage *storage, const char *path, const char *pattern, SDL_GlobFlags flags, int *count); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_storage_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_surface.h b/thirdparty/sdl/include/SDL3/SDL_surface.h new file mode 100644 index 00000000000..15fce042f73 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_surface.h @@ -0,0 +1,1563 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategorySurface + * + * SDL surfaces are buffers of pixels in system RAM. These are useful for + * passing around and manipulating images that are not stored in GPU memory. + * + * SDL_Surface makes serious efforts to manage images in various formats, and + * provides a reasonable toolbox for transforming the data, including copying + * between surfaces, filling rectangles in the image data, etc. + * + * There is also a simple .bmp loader, SDL_LoadBMP(). SDL itself does not + * provide loaders for various other file formats, but there are several + * excellent external libraries that do, including its own satellite library, + * SDL_image: + * + * https://github.com/libsdl-org/SDL_image + */ + +#ifndef SDL_surface_h_ +#define SDL_surface_h_ + +#include +#include +#include +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The flags on an SDL_Surface. + * + * These are generally considered read-only. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_SurfaceFlags; + +#define SDL_SURFACE_PREALLOCATED 0x00000001u /**< Surface uses preallocated pixel memory */ +#define SDL_SURFACE_LOCK_NEEDED 0x00000002u /**< Surface needs to be locked to access pixels */ +#define SDL_SURFACE_LOCKED 0x00000004u /**< Surface is currently locked */ +#define SDL_SURFACE_SIMD_ALIGNED 0x00000008u /**< Surface uses pixel memory allocated with SDL_aligned_alloc() */ + +/** + * Evaluates to true if the surface needs to be locked before access. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_MUSTLOCK(S) (((S)->flags & SDL_SURFACE_LOCK_NEEDED) == SDL_SURFACE_LOCK_NEEDED) + +/** + * The scaling mode. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_ScaleMode +{ + SDL_SCALEMODE_INVALID = -1, + SDL_SCALEMODE_NEAREST, /**< nearest pixel sampling */ + SDL_SCALEMODE_LINEAR /**< linear filtering */ +} SDL_ScaleMode; + +/** + * The flip mode. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_FlipMode +{ + SDL_FLIP_NONE, /**< Do not flip */ + SDL_FLIP_HORIZONTAL, /**< flip horizontally */ + SDL_FLIP_VERTICAL /**< flip vertically */ +} SDL_FlipMode; + +#ifndef SDL_INTERNAL + +/** + * A collection of pixels used in software blitting. + * + * Pixels are arranged in memory in rows, with the top row first. Each row + * occupies an amount of memory given by the pitch (sometimes known as the row + * stride in non-SDL APIs). + * + * Within each row, pixels are arranged from left to right until the width is + * reached. Each pixel occupies a number of bits appropriate for its format, + * with most formats representing each pixel as one or more whole bytes (in + * some indexed formats, instead multiple pixels are packed into each byte), + * and a byte order given by the format. After encoding all pixels, any + * remaining bytes to reach the pitch are used as padding to reach a desired + * alignment, and have undefined contents. + * + * When a surface holds YUV format data, the planes are assumed to be + * contiguous without padding between them, e.g. a 32x32 surface in NV12 + * format with a pitch of 32 would consist of 32x32 bytes of Y plane followed + * by 32x16 bytes of UV plane. + * + * When a surface holds MJPG format data, pixels points at the compressed JPEG + * image and pitch is the length of that data. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_CreateSurface + * \sa SDL_DestroySurface + */ +struct SDL_Surface +{ + SDL_SurfaceFlags flags; /**< The flags of the surface, read-only */ + SDL_PixelFormat format; /**< The format of the surface, read-only */ + int w; /**< The width of the surface, read-only. */ + int h; /**< The height of the surface, read-only. */ + int pitch; /**< The distance in bytes between rows of pixels, read-only */ + void *pixels; /**< A pointer to the pixels of the surface, the pixels are writeable if non-NULL */ + + int refcount; /**< Application reference count, used when freeing surface */ + + void *reserved; /**< Reserved for internal use */ +}; +#endif /* !SDL_INTERNAL */ + +typedef struct SDL_Surface SDL_Surface; + +/** + * Allocate a new surface with a specific pixel format. + * + * The pixels of the new surface are initialized to zero. + * + * \param width the width of the surface. + * \param height the height of the surface. + * \param format the SDL_PixelFormat for the new surface's pixel format. + * \returns the new SDL_Surface structure that is created or NULL on failure; + * call SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateSurfaceFrom + * \sa SDL_DestroySurface + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_CreateSurface(int width, int height, SDL_PixelFormat format); + +/** + * Allocate a new surface with a specific pixel format and existing pixel + * data. + * + * No copy is made of the pixel data. Pixel data is not managed automatically; + * you must free the surface before you free the pixel data. + * + * Pitch is the offset in bytes from one row of pixels to the next, e.g. + * `width*4` for `SDL_PIXELFORMAT_RGBA8888`. + * + * You may pass NULL for pixels and 0 for pitch to create a surface that you + * will fill in with valid values later. + * + * \param width the width of the surface. + * \param height the height of the surface. + * \param format the SDL_PixelFormat for the new surface's pixel format. + * \param pixels a pointer to existing pixel data. + * \param pitch the number of bytes between each row, including padding. + * \returns the new SDL_Surface structure that is created or NULL on failure; + * call SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateSurface + * \sa SDL_DestroySurface + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_CreateSurfaceFrom(int width, int height, SDL_PixelFormat format, void *pixels, int pitch); + +/** + * Free a surface. + * + * It is safe to pass NULL to this function. + * + * \param surface the SDL_Surface to free. + * + * \threadsafety No other thread should be using the surface when it is freed. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateSurface + * \sa SDL_CreateSurfaceFrom + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroySurface(SDL_Surface *surface); + +/** + * Get the properties associated with a surface. + * + * The following properties are understood by SDL: + * + * - `SDL_PROP_SURFACE_SDR_WHITE_POINT_FLOAT`: for HDR10 and floating point + * surfaces, this defines the value of 100% diffuse white, with higher + * values being displayed in the High Dynamic Range headroom. This defaults + * to 203 for HDR10 surfaces and 1.0 for floating point surfaces. + * - `SDL_PROP_SURFACE_HDR_HEADROOM_FLOAT`: for HDR10 and floating point + * surfaces, this defines the maximum dynamic range used by the content, in + * terms of the SDR white point. This defaults to 0.0, which disables tone + * mapping. + * - `SDL_PROP_SURFACE_TONEMAP_OPERATOR_STRING`: the tone mapping operator + * used when compressing from a surface with high dynamic range to another + * with lower dynamic range. Currently this supports "chrome", which uses + * the same tone mapping that Chrome uses for HDR content, the form "*=N", + * where N is a floating point scale factor applied in linear space, and + * "none", which disables tone mapping. This defaults to "chrome". + * - `SDL_PROP_SURFACE_HOTSPOT_X_NUMBER`: the hotspot pixel offset from the + * left edge of the image, if this surface is being used as a cursor. + * - `SDL_PROP_SURFACE_HOTSPOT_Y_NUMBER`: the hotspot pixel offset from the + * top edge of the image, if this surface is being used as a cursor. + * + * \param surface the SDL_Surface structure to query. + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetSurfaceProperties(SDL_Surface *surface); + +#define SDL_PROP_SURFACE_SDR_WHITE_POINT_FLOAT "SDL.surface.SDR_white_point" +#define SDL_PROP_SURFACE_HDR_HEADROOM_FLOAT "SDL.surface.HDR_headroom" +#define SDL_PROP_SURFACE_TONEMAP_OPERATOR_STRING "SDL.surface.tonemap" +#define SDL_PROP_SURFACE_HOTSPOT_X_NUMBER "SDL.surface.hotspot.x" +#define SDL_PROP_SURFACE_HOTSPOT_Y_NUMBER "SDL.surface.hotspot.y" + +/** + * Set the colorspace used by a surface. + * + * Setting the colorspace doesn't change the pixels, only how they are + * interpreted in color operations. + * + * \param surface the SDL_Surface structure to update. + * \param colorspace an SDL_Colorspace value describing the surface + * colorspace. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetSurfaceColorspace + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetSurfaceColorspace(SDL_Surface *surface, SDL_Colorspace colorspace); + +/** + * Get the colorspace used by a surface. + * + * The colorspace defaults to SDL_COLORSPACE_SRGB_LINEAR for floating point + * formats, SDL_COLORSPACE_HDR10 for 10-bit formats, SDL_COLORSPACE_SRGB for + * other RGB surfaces and SDL_COLORSPACE_BT709_FULL for YUV textures. + * + * \param surface the SDL_Surface structure to query. + * \returns the colorspace used by the surface, or SDL_COLORSPACE_UNKNOWN if + * the surface is NULL. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetSurfaceColorspace + */ +extern SDL_DECLSPEC SDL_Colorspace SDLCALL SDL_GetSurfaceColorspace(SDL_Surface *surface); + +/** + * Create a palette and associate it with a surface. + * + * This function creates a palette compatible with the provided surface. The + * palette is then returned for you to modify, and the surface will + * automatically use the new palette in future operations. You do not need to + * destroy the returned palette, it will be freed when the reference count + * reaches 0, usually when the surface is destroyed. + * + * Bitmap surfaces (with format SDL_PIXELFORMAT_INDEX1LSB or + * SDL_PIXELFORMAT_INDEX1MSB) will have the palette initialized with 0 as + * white and 1 as black. Other surfaces will get a palette initialized with + * white in every entry. + * + * If this function is called for a surface that already has a palette, a new + * palette will be created to replace it. + * + * \param surface the SDL_Surface structure to update. + * \returns a new SDL_Palette structure on success or NULL on failure (e.g. if + * the surface didn't have an index format); call SDL_GetError() for + * more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetPaletteColors + */ +extern SDL_DECLSPEC SDL_Palette * SDLCALL SDL_CreateSurfacePalette(SDL_Surface *surface); + +/** + * Set the palette used by a surface. + * + * A single palette can be shared with many surfaces. + * + * \param surface the SDL_Surface structure to update. + * \param palette the SDL_Palette structure to use. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreatePalette + * \sa SDL_GetSurfacePalette + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetSurfacePalette(SDL_Surface *surface, SDL_Palette *palette); + +/** + * Get the palette used by a surface. + * + * \param surface the SDL_Surface structure to query. + * \returns a pointer to the palette used by the surface, or NULL if there is + * no palette used. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetSurfacePalette + */ +extern SDL_DECLSPEC SDL_Palette * SDLCALL SDL_GetSurfacePalette(SDL_Surface *surface); + +/** + * Add an alternate version of a surface. + * + * This function adds an alternate version of this surface, usually used for + * content with high DPI representations like cursors or icons. The size, + * format, and content do not need to match the original surface, and these + * alternate versions will not be updated when the original surface changes. + * + * This function adds a reference to the alternate version, so you should call + * SDL_DestroySurface() on the image after this call. + * + * \param surface the SDL_Surface structure to update. + * \param image a pointer to an alternate SDL_Surface to associate with this + * surface. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RemoveSurfaceAlternateImages + * \sa SDL_GetSurfaceImages + * \sa SDL_SurfaceHasAlternateImages + */ +extern SDL_DECLSPEC bool SDLCALL SDL_AddSurfaceAlternateImage(SDL_Surface *surface, SDL_Surface *image); + +/** + * Return whether a surface has alternate versions available. + * + * \param surface the SDL_Surface structure to query. + * \returns true if alternate versions are available or false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddSurfaceAlternateImage + * \sa SDL_RemoveSurfaceAlternateImages + * \sa SDL_GetSurfaceImages + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SurfaceHasAlternateImages(SDL_Surface *surface); + +/** + * Get an array including all versions of a surface. + * + * This returns all versions of a surface, with the surface being queried as + * the first element in the returned array. + * + * Freeing the array of surfaces does not affect the surfaces in the array. + * They are still referenced by the surface being queried and will be cleaned + * up normally. + * + * \param surface the SDL_Surface structure to query. + * \param count a pointer filled in with the number of surface pointers + * returned, may be NULL. + * \returns a NULL terminated array of SDL_Surface pointers or NULL on + * failure; call SDL_GetError() for more information. This should be + * freed with SDL_free() when it is no longer needed. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddSurfaceAlternateImage + * \sa SDL_RemoveSurfaceAlternateImages + * \sa SDL_SurfaceHasAlternateImages + */ +extern SDL_DECLSPEC SDL_Surface ** SDLCALL SDL_GetSurfaceImages(SDL_Surface *surface, int *count); + +/** + * Remove all alternate versions of a surface. + * + * This function removes a reference from all the alternative versions, + * destroying them if this is the last reference to them. + * + * \param surface the SDL_Surface structure to update. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddSurfaceAlternateImage + * \sa SDL_GetSurfaceImages + * \sa SDL_SurfaceHasAlternateImages + */ +extern SDL_DECLSPEC void SDLCALL SDL_RemoveSurfaceAlternateImages(SDL_Surface *surface); + +/** + * Set up a surface for directly accessing the pixels. + * + * Between calls to SDL_LockSurface() / SDL_UnlockSurface(), you can write to + * and read from `surface->pixels`, using the pixel format stored in + * `surface->format`. Once you are done accessing the surface, you should use + * SDL_UnlockSurface() to release it. + * + * Not all surfaces require locking. If `SDL_MUSTLOCK(surface)` evaluates to + * 0, then you can read and write to the surface at any time, and the pixel + * format of the surface will not change. + * + * \param surface the SDL_Surface structure to be locked. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. The locking referred to by + * this function is making the pixels available for direct + * access, not thread-safe locking. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_MUSTLOCK + * \sa SDL_UnlockSurface + */ +extern SDL_DECLSPEC bool SDLCALL SDL_LockSurface(SDL_Surface *surface); + +/** + * Release a surface after directly accessing the pixels. + * + * \param surface the SDL_Surface structure to be unlocked. + * + * \threadsafety This function is not thread safe. The locking referred to by + * this function is making the pixels available for direct + * access, not thread-safe locking. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LockSurface + */ +extern SDL_DECLSPEC void SDLCALL SDL_UnlockSurface(SDL_Surface *surface); + +/** + * Load a BMP image from a seekable SDL data stream. + * + * The new surface should be freed with SDL_DestroySurface(). Not doing so + * will result in a memory leak. + * + * \param src the data stream for the surface. + * \param closeio if true, calls SDL_CloseIO() on `src` before returning, even + * in the case of an error. + * \returns a pointer to a new SDL_Surface structure or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroySurface + * \sa SDL_LoadBMP + * \sa SDL_SaveBMP_IO + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_LoadBMP_IO(SDL_IOStream *src, bool closeio); + +/** + * Load a BMP image from a file. + * + * The new surface should be freed with SDL_DestroySurface(). Not doing so + * will result in a memory leak. + * + * \param file the BMP file to load. + * \returns a pointer to a new SDL_Surface structure or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroySurface + * \sa SDL_LoadBMP_IO + * \sa SDL_SaveBMP + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_LoadBMP(const char *file); + +/** + * Save a surface to a seekable SDL data stream in BMP format. + * + * Surfaces with a 24-bit, 32-bit and paletted 8-bit format get saved in the + * BMP directly. Other RGB formats with 8-bit or higher get converted to a + * 24-bit surface or, if they have an alpha mask or a colorkey, to a 32-bit + * surface before they are saved. YUV and paletted 1-bit and 4-bit formats are + * not supported. + * + * \param surface the SDL_Surface structure containing the image to be saved. + * \param dst a data stream to save to. + * \param closeio if true, calls SDL_CloseIO() on `dst` before returning, even + * in the case of an error. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LoadBMP_IO + * \sa SDL_SaveBMP + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SaveBMP_IO(SDL_Surface *surface, SDL_IOStream *dst, bool closeio); + +/** + * Save a surface to a file. + * + * Surfaces with a 24-bit, 32-bit and paletted 8-bit format get saved in the + * BMP directly. Other RGB formats with 8-bit or higher get converted to a + * 24-bit surface or, if they have an alpha mask or a colorkey, to a 32-bit + * surface before they are saved. YUV and paletted 1-bit and 4-bit formats are + * not supported. + * + * \param surface the SDL_Surface structure containing the image to be saved. + * \param file a file to save to. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_LoadBMP + * \sa SDL_SaveBMP_IO + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SaveBMP(SDL_Surface *surface, const char *file); + +/** + * Set the RLE acceleration hint for a surface. + * + * If RLE is enabled, color key and alpha blending blits are much faster, but + * the surface must be locked before directly accessing the pixels. + * + * \param surface the SDL_Surface structure to optimize. + * \param enabled true to enable RLE acceleration, false to disable it. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BlitSurface + * \sa SDL_LockSurface + * \sa SDL_UnlockSurface + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetSurfaceRLE(SDL_Surface *surface, bool enabled); + +/** + * Returns whether the surface is RLE enabled. + * + * It is safe to pass a NULL `surface` here; it will return false. + * + * \param surface the SDL_Surface structure to query. + * \returns true if the surface is RLE enabled, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetSurfaceRLE + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SurfaceHasRLE(SDL_Surface *surface); + +/** + * Set the color key (transparent pixel) in a surface. + * + * The color key defines a pixel value that will be treated as transparent in + * a blit. For example, one can use this to specify that cyan pixels should be + * considered transparent, and therefore not rendered. + * + * It is a pixel of the format used by the surface, as generated by + * SDL_MapRGB(). + * + * \param surface the SDL_Surface structure to update. + * \param enabled true to enable color key, false to disable color key. + * \param key the transparent pixel. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetSurfaceColorKey + * \sa SDL_SetSurfaceRLE + * \sa SDL_SurfaceHasColorKey + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetSurfaceColorKey(SDL_Surface *surface, bool enabled, Uint32 key); + +/** + * Returns whether the surface has a color key. + * + * It is safe to pass a NULL `surface` here; it will return false. + * + * \param surface the SDL_Surface structure to query. + * \returns true if the surface has a color key, false otherwise. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetSurfaceColorKey + * \sa SDL_GetSurfaceColorKey + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SurfaceHasColorKey(SDL_Surface *surface); + +/** + * Get the color key (transparent pixel) for a surface. + * + * The color key is a pixel of the format used by the surface, as generated by + * SDL_MapRGB(). + * + * If the surface doesn't have color key enabled this function returns false. + * + * \param surface the SDL_Surface structure to query. + * \param key a pointer filled in with the transparent pixel. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetSurfaceColorKey + * \sa SDL_SurfaceHasColorKey + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetSurfaceColorKey(SDL_Surface *surface, Uint32 *key); + +/** + * Set an additional color value multiplied into blit operations. + * + * When this surface is blitted, during the blit operation each source color + * channel is modulated by the appropriate color value according to the + * following formula: + * + * `srcC = srcC * (color / 255)` + * + * \param surface the SDL_Surface structure to update. + * \param r the red color value multiplied into blit operations. + * \param g the green color value multiplied into blit operations. + * \param b the blue color value multiplied into blit operations. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetSurfaceColorMod + * \sa SDL_SetSurfaceAlphaMod + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetSurfaceColorMod(SDL_Surface *surface, Uint8 r, Uint8 g, Uint8 b); + + +/** + * Get the additional color value multiplied into blit operations. + * + * \param surface the SDL_Surface structure to query. + * \param r a pointer filled in with the current red color value. + * \param g a pointer filled in with the current green color value. + * \param b a pointer filled in with the current blue color value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetSurfaceAlphaMod + * \sa SDL_SetSurfaceColorMod + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetSurfaceColorMod(SDL_Surface *surface, Uint8 *r, Uint8 *g, Uint8 *b); + +/** + * Set an additional alpha value used in blit operations. + * + * When this surface is blitted, during the blit operation the source alpha + * value is modulated by this alpha value according to the following formula: + * + * `srcA = srcA * (alpha / 255)` + * + * \param surface the SDL_Surface structure to update. + * \param alpha the alpha value multiplied into blit operations. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetSurfaceAlphaMod + * \sa SDL_SetSurfaceColorMod + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetSurfaceAlphaMod(SDL_Surface *surface, Uint8 alpha); + +/** + * Get the additional alpha value used in blit operations. + * + * \param surface the SDL_Surface structure to query. + * \param alpha a pointer filled in with the current alpha value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetSurfaceColorMod + * \sa SDL_SetSurfaceAlphaMod + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetSurfaceAlphaMod(SDL_Surface *surface, Uint8 *alpha); + +/** + * Set the blend mode used for blit operations. + * + * To copy a surface to another surface (or texture) without blending with the + * existing data, the blendmode of the SOURCE surface should be set to + * `SDL_BLENDMODE_NONE`. + * + * \param surface the SDL_Surface structure to update. + * \param blendMode the SDL_BlendMode to use for blit blending. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetSurfaceBlendMode + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetSurfaceBlendMode(SDL_Surface *surface, SDL_BlendMode blendMode); + +/** + * Get the blend mode used for blit operations. + * + * \param surface the SDL_Surface structure to query. + * \param blendMode a pointer filled in with the current SDL_BlendMode. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetSurfaceBlendMode + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetSurfaceBlendMode(SDL_Surface *surface, SDL_BlendMode *blendMode); + +/** + * Set the clipping rectangle for a surface. + * + * When `surface` is the destination of a blit, only the area within the clip + * rectangle is drawn into. + * + * Note that blits are automatically clipped to the edges of the source and + * destination surfaces. + * + * \param surface the SDL_Surface structure to be clipped. + * \param rect the SDL_Rect structure representing the clipping rectangle, or + * NULL to disable clipping. + * \returns true if the rectangle intersects the surface, otherwise false and + * blits will be completely clipped. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetSurfaceClipRect + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetSurfaceClipRect(SDL_Surface *surface, const SDL_Rect *rect); + +/** + * Get the clipping rectangle for a surface. + * + * When `surface` is the destination of a blit, only the area within the clip + * rectangle is drawn into. + * + * \param surface the SDL_Surface structure representing the surface to be + * clipped. + * \param rect an SDL_Rect structure filled in with the clipping rectangle for + * the surface. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetSurfaceClipRect + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetSurfaceClipRect(SDL_Surface *surface, SDL_Rect *rect); + +/** + * Flip a surface vertically or horizontally. + * + * \param surface the surface to flip. + * \param flip the direction to flip. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_FlipSurface(SDL_Surface *surface, SDL_FlipMode flip); + +/** + * Creates a new surface identical to the existing surface. + * + * If the original surface has alternate images, the new surface will have a + * reference to them as well. + * + * The returned surface should be freed with SDL_DestroySurface(). + * + * \param surface the surface to duplicate. + * \returns a copy of the surface or NULL on failure; call SDL_GetError() for + * more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroySurface + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_DuplicateSurface(SDL_Surface *surface); + +/** + * Creates a new surface identical to the existing surface, scaled to the + * desired size. + * + * The returned surface should be freed with SDL_DestroySurface(). + * + * \param surface the surface to duplicate and scale. + * \param width the width of the new surface. + * \param height the height of the new surface. + * \param scaleMode the SDL_ScaleMode to be used. + * \returns a copy of the surface or NULL on failure; call SDL_GetError() for + * more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroySurface + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_ScaleSurface(SDL_Surface *surface, int width, int height, SDL_ScaleMode scaleMode); + +/** + * Copy an existing surface to a new surface of the specified format. + * + * This function is used to optimize images for faster *repeat* blitting. This + * is accomplished by converting the original and storing the result as a new + * surface. The new, optimized surface can then be used as the source for + * future blits, making them faster. + * + * If you are converting to an indexed surface and want to map colors to a + * palette, you can use SDL_ConvertSurfaceAndColorspace() instead. + * + * If the original surface has alternate images, the new surface will have a + * reference to them as well. + * + * \param surface the existing SDL_Surface structure to convert. + * \param format the new pixel format. + * \returns the new SDL_Surface structure that is created or NULL on failure; + * call SDL_GetError() for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ConvertSurfaceAndColorspace + * \sa SDL_DestroySurface + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_ConvertSurface(SDL_Surface *surface, SDL_PixelFormat format); + +/** + * Copy an existing surface to a new surface of the specified format and + * colorspace. + * + * This function converts an existing surface to a new format and colorspace + * and returns the new surface. This will perform any pixel format and + * colorspace conversion needed. + * + * If the original surface has alternate images, the new surface will have a + * reference to them as well. + * + * \param surface the existing SDL_Surface structure to convert. + * \param format the new pixel format. + * \param palette an optional palette to use for indexed formats, may be NULL. + * \param colorspace the new colorspace. + * \param props an SDL_PropertiesID with additional color properties, or 0. + * \returns the new SDL_Surface structure that is created or NULL on failure; + * call SDL_GetError() for more information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ConvertSurface + * \sa SDL_DestroySurface + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_ConvertSurfaceAndColorspace(SDL_Surface *surface, SDL_PixelFormat format, SDL_Palette *palette, SDL_Colorspace colorspace, SDL_PropertiesID props); + +/** + * Copy a block of pixels of one format to another format. + * + * \param width the width of the block to copy, in pixels. + * \param height the height of the block to copy, in pixels. + * \param src_format an SDL_PixelFormat value of the `src` pixels format. + * \param src a pointer to the source pixels. + * \param src_pitch the pitch of the source pixels, in bytes. + * \param dst_format an SDL_PixelFormat value of the `dst` pixels format. + * \param dst a pointer to be filled in with new pixel data. + * \param dst_pitch the pitch of the destination pixels, in bytes. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety The same destination pixels should not be used from two + * threads at once. It is safe to use the same source pixels + * from multiple threads. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ConvertPixelsAndColorspace + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ConvertPixels(int width, int height, SDL_PixelFormat src_format, const void *src, int src_pitch, SDL_PixelFormat dst_format, void *dst, int dst_pitch); + +/** + * Copy a block of pixels of one format and colorspace to another format and + * colorspace. + * + * \param width the width of the block to copy, in pixels. + * \param height the height of the block to copy, in pixels. + * \param src_format an SDL_PixelFormat value of the `src` pixels format. + * \param src_colorspace an SDL_Colorspace value describing the colorspace of + * the `src` pixels. + * \param src_properties an SDL_PropertiesID with additional source color + * properties, or 0. + * \param src a pointer to the source pixels. + * \param src_pitch the pitch of the source pixels, in bytes. + * \param dst_format an SDL_PixelFormat value of the `dst` pixels format. + * \param dst_colorspace an SDL_Colorspace value describing the colorspace of + * the `dst` pixels. + * \param dst_properties an SDL_PropertiesID with additional destination color + * properties, or 0. + * \param dst a pointer to be filled in with new pixel data. + * \param dst_pitch the pitch of the destination pixels, in bytes. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety The same destination pixels should not be used from two + * threads at once. It is safe to use the same source pixels + * from multiple threads. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ConvertPixels + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ConvertPixelsAndColorspace(int width, int height, SDL_PixelFormat src_format, SDL_Colorspace src_colorspace, SDL_PropertiesID src_properties, const void *src, int src_pitch, SDL_PixelFormat dst_format, SDL_Colorspace dst_colorspace, SDL_PropertiesID dst_properties, void *dst, int dst_pitch); + +/** + * Premultiply the alpha on a block of pixels. + * + * This is safe to use with src == dst, but not for other overlapping areas. + * + * \param width the width of the block to convert, in pixels. + * \param height the height of the block to convert, in pixels. + * \param src_format an SDL_PixelFormat value of the `src` pixels format. + * \param src a pointer to the source pixels. + * \param src_pitch the pitch of the source pixels, in bytes. + * \param dst_format an SDL_PixelFormat value of the `dst` pixels format. + * \param dst a pointer to be filled in with premultiplied pixel data. + * \param dst_pitch the pitch of the destination pixels, in bytes. + * \param linear true to convert from sRGB to linear space for the alpha + * multiplication, false to do multiplication in sRGB space. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety The same destination pixels should not be used from two + * threads at once. It is safe to use the same source pixels + * from multiple threads. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_PremultiplyAlpha(int width, int height, SDL_PixelFormat src_format, const void *src, int src_pitch, SDL_PixelFormat dst_format, void *dst, int dst_pitch, bool linear); + +/** + * Premultiply the alpha in a surface. + * + * This is safe to use with src == dst, but not for other overlapping areas. + * + * \param surface the surface to modify. + * \param linear true to convert from sRGB to linear space for the alpha + * multiplication, false to do multiplication in sRGB space. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_PremultiplySurfaceAlpha(SDL_Surface *surface, bool linear); + +/** + * Clear a surface with a specific color, with floating point precision. + * + * This function handles all surface formats, and ignores any clip rectangle. + * + * If the surface is YUV, the color is assumed to be in the sRGB colorspace, + * otherwise the color is assumed to be in the colorspace of the suface. + * + * \param surface the SDL_Surface to clear. + * \param r the red component of the pixel, normally in the range 0-1. + * \param g the green component of the pixel, normally in the range 0-1. + * \param b the blue component of the pixel, normally in the range 0-1. + * \param a the alpha component of the pixel, normally in the range 0-1. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ClearSurface(SDL_Surface *surface, float r, float g, float b, float a); + +/** + * Perform a fast fill of a rectangle with a specific color. + * + * `color` should be a pixel of the format used by the surface, and can be + * generated by SDL_MapRGB() or SDL_MapRGBA(). If the color value contains an + * alpha component then the destination is simply filled with that alpha + * information, no blending takes place. + * + * If there is a clip rectangle set on the destination (set via + * SDL_SetSurfaceClipRect()), then this function will fill based on the + * intersection of the clip rectangle and `rect`. + * + * \param dst the SDL_Surface structure that is the drawing target. + * \param rect the SDL_Rect structure representing the rectangle to fill, or + * NULL to fill the entire surface. + * \param color the color to fill with. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_FillSurfaceRects + */ +extern SDL_DECLSPEC bool SDLCALL SDL_FillSurfaceRect(SDL_Surface *dst, const SDL_Rect *rect, Uint32 color); + +/** + * Perform a fast fill of a set of rectangles with a specific color. + * + * `color` should be a pixel of the format used by the surface, and can be + * generated by SDL_MapRGB() or SDL_MapRGBA(). If the color value contains an + * alpha component then the destination is simply filled with that alpha + * information, no blending takes place. + * + * If there is a clip rectangle set on the destination (set via + * SDL_SetSurfaceClipRect()), then this function will fill based on the + * intersection of the clip rectangle and `rect`. + * + * \param dst the SDL_Surface structure that is the drawing target. + * \param rects an array of SDL_Rects representing the rectangles to fill. + * \param count the number of rectangles in the array. + * \param color the color to fill with. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_FillSurfaceRect + */ +extern SDL_DECLSPEC bool SDLCALL SDL_FillSurfaceRects(SDL_Surface *dst, const SDL_Rect *rects, int count, Uint32 color); + +/** + * Performs a fast blit from the source surface to the destination surface + * with clipping. + * + * If either `srcrect` or `dstrect` are NULL, the entire surface (`src` or + * `dst`) is copied while ensuring clipping to `dst->clip_rect`. + * + * The blit function should not be called on a locked surface. + * + * The blit semantics for surfaces with and without blending and colorkey are + * defined as follows: + * + * ``` + * RGBA->RGB: + * Source surface blend mode set to SDL_BLENDMODE_BLEND: + * alpha-blend (using the source alpha-channel and per-surface alpha) + * SDL_SRCCOLORKEY ignored. + * Source surface blend mode set to SDL_BLENDMODE_NONE: + * copy RGB. + * if SDL_SRCCOLORKEY set, only copy the pixels that do not match the + * RGB values of the source color key, ignoring alpha in the + * comparison. + * + * RGB->RGBA: + * Source surface blend mode set to SDL_BLENDMODE_BLEND: + * alpha-blend (using the source per-surface alpha) + * Source surface blend mode set to SDL_BLENDMODE_NONE: + * copy RGB, set destination alpha to source per-surface alpha value. + * both: + * if SDL_SRCCOLORKEY set, only copy the pixels that do not match the + * source color key. + * + * RGBA->RGBA: + * Source surface blend mode set to SDL_BLENDMODE_BLEND: + * alpha-blend (using the source alpha-channel and per-surface alpha) + * SDL_SRCCOLORKEY ignored. + * Source surface blend mode set to SDL_BLENDMODE_NONE: + * copy all of RGBA to the destination. + * if SDL_SRCCOLORKEY set, only copy the pixels that do not match the + * RGB values of the source color key, ignoring alpha in the + * comparison. + * + * RGB->RGB: + * Source surface blend mode set to SDL_BLENDMODE_BLEND: + * alpha-blend (using the source per-surface alpha) + * Source surface blend mode set to SDL_BLENDMODE_NONE: + * copy RGB. + * both: + * if SDL_SRCCOLORKEY set, only copy the pixels that do not match the + * source color key. + * ``` + * + * \param src the SDL_Surface structure to be copied from. + * \param srcrect the SDL_Rect structure representing the rectangle to be + * copied, or NULL to copy the entire surface. + * \param dst the SDL_Surface structure that is the blit target. + * \param dstrect the SDL_Rect structure representing the x and y position in + * the destination surface, or NULL for (0,0). The width and + * height are ignored, and are copied from `srcrect`. If you + * want a specific width and height, you should use + * SDL_BlitSurfaceScaled(). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety Only one thread should be using the `src` and `dst` surfaces + * at any given time. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BlitSurfaceScaled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_BlitSurface(SDL_Surface *src, const SDL_Rect *srcrect, SDL_Surface *dst, const SDL_Rect *dstrect); + +/** + * Perform low-level surface blitting only. + * + * This is a semi-private blit function and it performs low-level surface + * blitting, assuming the input rectangles have already been clipped. + * + * \param src the SDL_Surface structure to be copied from. + * \param srcrect the SDL_Rect structure representing the rectangle to be + * copied, may not be NULL. + * \param dst the SDL_Surface structure that is the blit target. + * \param dstrect the SDL_Rect structure representing the target rectangle in + * the destination surface, may not be NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety Only one thread should be using the `src` and `dst` surfaces + * at any given time. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BlitSurface + */ +extern SDL_DECLSPEC bool SDLCALL SDL_BlitSurfaceUnchecked(SDL_Surface *src, const SDL_Rect *srcrect, SDL_Surface *dst, const SDL_Rect *dstrect); + +/** + * Perform a scaled blit to a destination surface, which may be of a different + * format. + * + * \param src the SDL_Surface structure to be copied from. + * \param srcrect the SDL_Rect structure representing the rectangle to be + * copied, or NULL to copy the entire surface. + * \param dst the SDL_Surface structure that is the blit target. + * \param dstrect the SDL_Rect structure representing the target rectangle in + * the destination surface, or NULL to fill the entire + * destination surface. + * \param scaleMode the SDL_ScaleMode to be used. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety Only one thread should be using the `src` and `dst` surfaces + * at any given time. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BlitSurface + */ +extern SDL_DECLSPEC bool SDLCALL SDL_BlitSurfaceScaled(SDL_Surface *src, const SDL_Rect *srcrect, SDL_Surface *dst, const SDL_Rect *dstrect, SDL_ScaleMode scaleMode); + +/** + * Perform low-level surface scaled blitting only. + * + * This is a semi-private function and it performs low-level surface blitting, + * assuming the input rectangles have already been clipped. + * + * \param src the SDL_Surface structure to be copied from. + * \param srcrect the SDL_Rect structure representing the rectangle to be + * copied, may not be NULL. + * \param dst the SDL_Surface structure that is the blit target. + * \param dstrect the SDL_Rect structure representing the target rectangle in + * the destination surface, may not be NULL. + * \param scaleMode the SDL_ScaleMode to be used. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety Only one thread should be using the `src` and `dst` surfaces + * at any given time. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BlitSurfaceScaled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_BlitSurfaceUncheckedScaled(SDL_Surface *src, const SDL_Rect *srcrect, SDL_Surface *dst, const SDL_Rect *dstrect, SDL_ScaleMode scaleMode); + +/** + * Perform a stretched pixel copy from one surface to another. + * + * \param src the SDL_Surface structure to be copied from. + * \param srcrect the SDL_Rect structure representing the rectangle to be + * copied, or NULL to copy the entire surface. + * \param dst the SDL_Surface structure that is the blit target. + * \param dstrect the SDL_Rect structure representing the target rectangle in + * the destination surface, or NULL to fill the entire + * destination surface. + * \param scaleMode the SDL_ScaleMode to be used. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety Only one thread should be using the `src` and `dst` surfaces + * at any given time. + * + * \since This function is available since SDL 3.4.0. + * + * \sa SDL_BlitSurfaceScaled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_StretchSurface(SDL_Surface *src, const SDL_Rect *srcrect, SDL_Surface *dst, const SDL_Rect *dstrect, SDL_ScaleMode scaleMode); + +/** + * Perform a tiled blit to a destination surface, which may be of a different + * format. + * + * The pixels in `srcrect` will be repeated as many times as needed to + * completely fill `dstrect`. + * + * \param src the SDL_Surface structure to be copied from. + * \param srcrect the SDL_Rect structure representing the rectangle to be + * copied, or NULL to copy the entire surface. + * \param dst the SDL_Surface structure that is the blit target. + * \param dstrect the SDL_Rect structure representing the target rectangle in + * the destination surface, or NULL to fill the entire surface. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety Only one thread should be using the `src` and `dst` surfaces + * at any given time. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BlitSurface + */ +extern SDL_DECLSPEC bool SDLCALL SDL_BlitSurfaceTiled(SDL_Surface *src, const SDL_Rect *srcrect, SDL_Surface *dst, const SDL_Rect *dstrect); + +/** + * Perform a scaled and tiled blit to a destination surface, which may be of a + * different format. + * + * The pixels in `srcrect` will be scaled and repeated as many times as needed + * to completely fill `dstrect`. + * + * \param src the SDL_Surface structure to be copied from. + * \param srcrect the SDL_Rect structure representing the rectangle to be + * copied, or NULL to copy the entire surface. + * \param scale the scale used to transform srcrect into the destination + * rectangle, e.g. a 32x32 texture with a scale of 2 would fill + * 64x64 tiles. + * \param scaleMode scale algorithm to be used. + * \param dst the SDL_Surface structure that is the blit target. + * \param dstrect the SDL_Rect structure representing the target rectangle in + * the destination surface, or NULL to fill the entire surface. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety Only one thread should be using the `src` and `dst` surfaces + * at any given time. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BlitSurface + */ +extern SDL_DECLSPEC bool SDLCALL SDL_BlitSurfaceTiledWithScale(SDL_Surface *src, const SDL_Rect *srcrect, float scale, SDL_ScaleMode scaleMode, SDL_Surface *dst, const SDL_Rect *dstrect); + +/** + * Perform a scaled blit using the 9-grid algorithm to a destination surface, + * which may be of a different format. + * + * The pixels in the source surface are split into a 3x3 grid, using the + * different corner sizes for each corner, and the sides and center making up + * the remaining pixels. The corners are then scaled using `scale` and fit + * into the corners of the destination rectangle. The sides and center are + * then stretched into place to cover the remaining destination rectangle. + * + * \param src the SDL_Surface structure to be copied from. + * \param srcrect the SDL_Rect structure representing the rectangle to be used + * for the 9-grid, or NULL to use the entire surface. + * \param left_width the width, in pixels, of the left corners in `srcrect`. + * \param right_width the width, in pixels, of the right corners in `srcrect`. + * \param top_height the height, in pixels, of the top corners in `srcrect`. + * \param bottom_height the height, in pixels, of the bottom corners in + * `srcrect`. + * \param scale the scale used to transform the corner of `srcrect` into the + * corner of `dstrect`, or 0.0f for an unscaled blit. + * \param scaleMode scale algorithm to be used. + * \param dst the SDL_Surface structure that is the blit target. + * \param dstrect the SDL_Rect structure representing the target rectangle in + * the destination surface, or NULL to fill the entire surface. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety Only one thread should be using the `src` and `dst` surfaces + * at any given time. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_BlitSurface + */ +extern SDL_DECLSPEC bool SDLCALL SDL_BlitSurface9Grid(SDL_Surface *src, const SDL_Rect *srcrect, int left_width, int right_width, int top_height, int bottom_height, float scale, SDL_ScaleMode scaleMode, SDL_Surface *dst, const SDL_Rect *dstrect); + +/** + * Map an RGB triple to an opaque pixel value for a surface. + * + * This function maps the RGB color value to the specified pixel format and + * returns the pixel value best approximating the given RGB color value for + * the given pixel format. + * + * If the surface has a palette, the index of the closest matching color in + * the palette will be returned. + * + * If the surface pixel format has an alpha component it will be returned as + * all 1 bits (fully opaque). + * + * If the pixel format bpp (color depth) is less than 32-bpp then the unused + * upper bits of the return value can safely be ignored (e.g., with a 16-bpp + * format the return value can be assigned to a Uint16, and similarly a Uint8 + * for an 8-bpp format). + * + * \param surface the surface to use for the pixel format and palette. + * \param r the red component of the pixel in the range 0-255. + * \param g the green component of the pixel in the range 0-255. + * \param b the blue component of the pixel in the range 0-255. + * \returns a pixel value. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_MapSurfaceRGBA + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_MapSurfaceRGB(SDL_Surface *surface, Uint8 r, Uint8 g, Uint8 b); + +/** + * Map an RGBA quadruple to a pixel value for a surface. + * + * This function maps the RGBA color value to the specified pixel format and + * returns the pixel value best approximating the given RGBA color value for + * the given pixel format. + * + * If the surface pixel format has no alpha component the alpha value will be + * ignored (as it will be in formats with a palette). + * + * If the surface has a palette, the index of the closest matching color in + * the palette will be returned. + * + * If the pixel format bpp (color depth) is less than 32-bpp then the unused + * upper bits of the return value can safely be ignored (e.g., with a 16-bpp + * format the return value can be assigned to a Uint16, and similarly a Uint8 + * for an 8-bpp format). + * + * \param surface the surface to use for the pixel format and palette. + * \param r the red component of the pixel in the range 0-255. + * \param g the green component of the pixel in the range 0-255. + * \param b the blue component of the pixel in the range 0-255. + * \param a the alpha component of the pixel in the range 0-255. + * \returns a pixel value. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_MapSurfaceRGB + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_MapSurfaceRGBA(SDL_Surface *surface, Uint8 r, Uint8 g, Uint8 b, Uint8 a); + +/** + * Retrieves a single pixel from a surface. + * + * This function prioritizes correctness over speed: it is suitable for unit + * tests, but is not intended for use in a game engine. + * + * Like SDL_GetRGBA, this uses the entire 0..255 range when converting color + * components from pixel formats with less than 8 bits per RGB component. + * + * \param surface the surface to read. + * \param x the horizontal coordinate, 0 <= x < width. + * \param y the vertical coordinate, 0 <= y < height. + * \param r a pointer filled in with the red channel, 0-255, or NULL to ignore + * this channel. + * \param g a pointer filled in with the green channel, 0-255, or NULL to + * ignore this channel. + * \param b a pointer filled in with the blue channel, 0-255, or NULL to + * ignore this channel. + * \param a a pointer filled in with the alpha channel, 0-255, or NULL to + * ignore this channel. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadSurfacePixel(SDL_Surface *surface, int x, int y, Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a); + +/** + * Retrieves a single pixel from a surface. + * + * This function prioritizes correctness over speed: it is suitable for unit + * tests, but is not intended for use in a game engine. + * + * \param surface the surface to read. + * \param x the horizontal coordinate, 0 <= x < width. + * \param y the vertical coordinate, 0 <= y < height. + * \param r a pointer filled in with the red channel, normally in the range + * 0-1, or NULL to ignore this channel. + * \param g a pointer filled in with the green channel, normally in the range + * 0-1, or NULL to ignore this channel. + * \param b a pointer filled in with the blue channel, normally in the range + * 0-1, or NULL to ignore this channel. + * \param a a pointer filled in with the alpha channel, normally in the range + * 0-1, or NULL to ignore this channel. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ReadSurfacePixelFloat(SDL_Surface *surface, int x, int y, float *r, float *g, float *b, float *a); + +/** + * Writes a single pixel to a surface. + * + * This function prioritizes correctness over speed: it is suitable for unit + * tests, but is not intended for use in a game engine. + * + * Like SDL_MapRGBA, this uses the entire 0..255 range when converting color + * components from pixel formats with less than 8 bits per RGB component. + * + * \param surface the surface to write. + * \param x the horizontal coordinate, 0 <= x < width. + * \param y the vertical coordinate, 0 <= y < height. + * \param r the red channel value, 0-255. + * \param g the green channel value, 0-255. + * \param b the blue channel value, 0-255. + * \param a the alpha channel value, 0-255. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteSurfacePixel(SDL_Surface *surface, int x, int y, Uint8 r, Uint8 g, Uint8 b, Uint8 a); + +/** + * Writes a single pixel to a surface. + * + * This function prioritizes correctness over speed: it is suitable for unit + * tests, but is not intended for use in a game engine. + * + * \param surface the surface to write. + * \param x the horizontal coordinate, 0 <= x < width. + * \param y the vertical coordinate, 0 <= y < height. + * \param r the red channel value, normally in the range 0-1. + * \param g the green channel value, normally in the range 0-1. + * \param b the blue channel value, normally in the range 0-1. + * \param a the alpha channel value, normally in the range 0-1. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function is not thread safe. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WriteSurfacePixelFloat(SDL_Surface *surface, int x, int y, float r, float g, float b, float a); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_surface_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_system.h b/thirdparty/sdl/include/SDL3/SDL_system.h new file mode 100644 index 00000000000..294089ff4a3 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_system.h @@ -0,0 +1,818 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategorySystem + * + * Platform-specific SDL API functions. These are functions that deal with + * needs of specific operating systems, that didn't make sense to offer as + * platform-independent, generic APIs. + * + * Most apps can make do without these functions, but they can be useful for + * integrating with other parts of a specific system, adding platform-specific + * polish to an app, or solving problems that only affect one target. + */ + +#ifndef SDL_system_h_ +#define SDL_system_h_ + +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + + +/* + * Platform specific functions for Windows + */ +#if defined(SDL_PLATFORM_WINDOWS) + +typedef struct tagMSG MSG; + +/** + * A callback to be used with SDL_SetWindowsMessageHook. + * + * This callback may modify the message, and should return true if the message + * should continue to be processed, or false to prevent further processing. + * + * As this is processing a message directly from the Windows event loop, this + * callback should do the minimum required work and return quickly. + * + * \param userdata the app-defined pointer provided to + * SDL_SetWindowsMessageHook. + * \param msg a pointer to a Win32 event structure to process. + * \returns true to let event continue on, false to drop it. + * + * \threadsafety This may only be called (by SDL) from the thread handling the + * Windows event loop. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_SetWindowsMessageHook + * \sa SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP + */ +typedef bool (SDLCALL *SDL_WindowsMessageHook)(void *userdata, MSG *msg); + +/** + * Set a callback for every Windows message, run before TranslateMessage(). + * + * The callback may modify the message, and should return true if the message + * should continue to be processed, or false to prevent further processing. + * + * \param callback the SDL_WindowsMessageHook function to call. + * \param userdata a pointer to pass to every iteration of `callback`. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_WindowsMessageHook + * \sa SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetWindowsMessageHook(SDL_WindowsMessageHook callback, void *userdata); + +#endif /* defined(SDL_PLATFORM_WINDOWS) */ + +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) + +/** + * Get the D3D9 adapter index that matches the specified display. + * + * The returned adapter index can be passed to `IDirect3D9::CreateDevice` and + * controls on which monitor a full screen application will appear. + * + * \param displayID the instance of the display to query. + * \returns the D3D9 adapter index on success or -1 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetDirect3D9AdapterIndex(SDL_DisplayID displayID); + +/** + * Get the DXGI Adapter and Output indices for the specified display. + * + * The DXGI Adapter and Output indices can be passed to `EnumAdapters` and + * `EnumOutputs` respectively to get the objects required to create a DX10 or + * DX11 device and swap chain. + * + * \param displayID the instance of the display to query. + * \param adapterIndex a pointer to be filled in with the adapter index. + * \param outputIndex a pointer to be filled in with the output index. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetDXGIOutputInfo(SDL_DisplayID displayID, int *adapterIndex, int *outputIndex); + +#endif /* defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) */ + + +/* + * Platform specific functions for UNIX + */ + +/* this is defined in Xlib's headers, just need a simple declaration here. */ +typedef union _XEvent XEvent; + +/** + * A callback to be used with SDL_SetX11EventHook. + * + * This callback may modify the event, and should return true if the event + * should continue to be processed, or false to prevent further processing. + * + * As this is processing an event directly from the X11 event loop, this + * callback should do the minimum required work and return quickly. + * + * \param userdata the app-defined pointer provided to SDL_SetX11EventHook. + * \param xevent a pointer to an Xlib XEvent union to process. + * \returns true to let event continue on, false to drop it. + * + * \threadsafety This may only be called (by SDL) from the thread handling the + * X11 event loop. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_SetX11EventHook + */ +typedef bool (SDLCALL *SDL_X11EventHook)(void *userdata, XEvent *xevent); + +/** + * Set a callback for every X11 event. + * + * The callback may modify the event, and should return true if the event + * should continue to be processed, or false to prevent further processing. + * + * \param callback the SDL_X11EventHook function to call. + * \param userdata a pointer to pass to every iteration of `callback`. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetX11EventHook(SDL_X11EventHook callback, void *userdata); + +/* Platform specific functions for Linux*/ +#ifdef SDL_PLATFORM_LINUX + +/** + * Sets the UNIX nice value for a thread. + * + * This uses setpriority() if possible, and RealtimeKit if available. + * + * \param threadID the Unix thread ID to change priority of. + * \param priority the new, Unix-specific, priority value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetLinuxThreadPriority(Sint64 threadID, int priority); + +/** + * Sets the priority (not nice level) and scheduling policy for a thread. + * + * This uses setpriority() if possible, and RealtimeKit if available. + * + * \param threadID the Unix thread ID to change priority of. + * \param sdlPriority the new SDL_ThreadPriority value. + * \param schedPolicy the new scheduling policy (SCHED_FIFO, SCHED_RR, + * SCHED_OTHER, etc...). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetLinuxThreadPriorityAndPolicy(Sint64 threadID, int sdlPriority, int schedPolicy); + +#endif /* SDL_PLATFORM_LINUX */ + +/* + * Platform specific functions for iOS + */ +#ifdef SDL_PLATFORM_IOS + +/** + * The prototype for an Apple iOS animation callback. + * + * This datatype is only useful on Apple iOS. + * + * After passing a function pointer of this type to + * SDL_SetiOSAnimationCallback, the system will call that function pointer at + * a regular interval. + * + * \param userdata what was passed as `callbackParam` to + * SDL_SetiOSAnimationCallback as `callbackParam`. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_SetiOSAnimationCallback + */ +typedef void (SDLCALL *SDL_iOSAnimationCallback)(void *userdata); + +/** + * Use this function to set the animation callback on Apple iOS. + * + * The function prototype for `callback` is: + * + * ```c + * void callback(void *callbackParam); + * ``` + * + * Where its parameter, `callbackParam`, is what was passed as `callbackParam` + * to SDL_SetiOSAnimationCallback(). + * + * This function is only available on Apple iOS. + * + * For more information see: + * + * https://wiki.libsdl.org/SDL3/README/ios + * + * Note that if you use the "main callbacks" instead of a standard C `main` + * function, you don't have to use this API, as SDL will manage this for you. + * + * Details on main callbacks are here: + * + * https://wiki.libsdl.org/SDL3/README/main-functions + * + * \param window the window for which the animation callback should be set. + * \param interval the number of frames after which **callback** will be + * called. + * \param callback the function to call for every frame. + * \param callbackParam a pointer that is passed to `callback`. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetiOSEventPump + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetiOSAnimationCallback(SDL_Window *window, int interval, SDL_iOSAnimationCallback callback, void *callbackParam); + +/** + * Use this function to enable or disable the SDL event pump on Apple iOS. + * + * This function is only available on Apple iOS. + * + * \param enabled true to enable the event pump, false to disable it. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetiOSAnimationCallback + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetiOSEventPump(bool enabled); + +#endif /* SDL_PLATFORM_IOS */ + + +/* + * Platform specific functions for Android + */ +#ifdef SDL_PLATFORM_ANDROID + +/** + * Get the Android Java Native Interface Environment of the current thread. + * + * This is the JNIEnv one needs to access the Java virtual machine from native + * code, and is needed for many Android APIs to be usable from C. + * + * The prototype of the function in SDL's code actually declare a void* return + * type, even if the implementation returns a pointer to a JNIEnv. The + * rationale being that the SDL headers can avoid including jni.h. + * + * \returns a pointer to Java native interface object (JNIEnv) to which the + * current thread is attached, or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAndroidActivity + */ +extern SDL_DECLSPEC void * SDLCALL SDL_GetAndroidJNIEnv(void); + +/** + * Retrieve the Java instance of the Android activity class. + * + * The prototype of the function in SDL's code actually declares a void* + * return type, even if the implementation returns a jobject. The rationale + * being that the SDL headers can avoid including jni.h. + * + * The jobject returned by the function is a local reference and must be + * released by the caller. See the PushLocalFrame() and PopLocalFrame() or + * DeleteLocalRef() functions of the Java native interface: + * + * https://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html + * + * \returns the jobject representing the instance of the Activity class of the + * Android application, or NULL on failure; call SDL_GetError() for + * more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAndroidJNIEnv + */ +extern SDL_DECLSPEC void * SDLCALL SDL_GetAndroidActivity(void); + +/** + * Query Android API level of the current device. + * + * - API level 35: Android 15 (VANILLA_ICE_CREAM) + * - API level 34: Android 14 (UPSIDE_DOWN_CAKE) + * - API level 33: Android 13 (TIRAMISU) + * - API level 32: Android 12L (S_V2) + * - API level 31: Android 12 (S) + * - API level 30: Android 11 (R) + * - API level 29: Android 10 (Q) + * - API level 28: Android 9 (P) + * - API level 27: Android 8.1 (O_MR1) + * - API level 26: Android 8.0 (O) + * - API level 25: Android 7.1 (N_MR1) + * - API level 24: Android 7.0 (N) + * - API level 23: Android 6.0 (M) + * - API level 22: Android 5.1 (LOLLIPOP_MR1) + * - API level 21: Android 5.0 (LOLLIPOP, L) + * - API level 20: Android 4.4W (KITKAT_WATCH) + * - API level 19: Android 4.4 (KITKAT) + * - API level 18: Android 4.3 (JELLY_BEAN_MR2) + * - API level 17: Android 4.2 (JELLY_BEAN_MR1) + * - API level 16: Android 4.1 (JELLY_BEAN) + * - API level 15: Android 4.0.3 (ICE_CREAM_SANDWICH_MR1) + * - API level 14: Android 4.0 (ICE_CREAM_SANDWICH) + * - API level 13: Android 3.2 (HONEYCOMB_MR2) + * - API level 12: Android 3.1 (HONEYCOMB_MR1) + * - API level 11: Android 3.0 (HONEYCOMB) + * - API level 10: Android 2.3.3 (GINGERBREAD_MR1) + * + * \returns the Android API level. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetAndroidSDKVersion(void); + +/** + * Query if the application is running on a Chromebook. + * + * \returns true if this is a Chromebook, false otherwise. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsChromebook(void); + +/** + * Query if the application is running on a Samsung DeX docking station. + * + * \returns true if this is a DeX docking station, false otherwise. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsDeXMode(void); + +/** + * Trigger the Android system back button behavior. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_SendAndroidBackButton(void); + +/** + * See the official Android developer guide for more information: + * http://developer.android.com/guide/topics/data/data-storage.html + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ANDROID_EXTERNAL_STORAGE_READ 0x01 + +/** + * See the official Android developer guide for more information: + * http://developer.android.com/guide/topics/data/data-storage.html + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_ANDROID_EXTERNAL_STORAGE_WRITE 0x02 + +/** + * Get the path used for internal storage for this Android application. + * + * This path is unique to your application and cannot be written to by other + * applications. + * + * Your internal storage path is typically: + * `/data/data/your.app.package/files`. + * + * This is a C wrapper over `android.content.Context.getFilesDir()`: + * + * https://developer.android.com/reference/android/content/Context#getFilesDir() + * + * \returns the path used for internal storage or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAndroidExternalStoragePath + * \sa SDL_GetAndroidCachePath + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetAndroidInternalStoragePath(void); + +/** + * Get the current state of external storage for this Android application. + * + * The current state of external storage, a bitmask of these values: + * `SDL_ANDROID_EXTERNAL_STORAGE_READ`, `SDL_ANDROID_EXTERNAL_STORAGE_WRITE`. + * + * If external storage is currently unavailable, this will return 0. + * + * \returns the current state of external storage, or 0 if external storage is + * currently unavailable. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAndroidExternalStoragePath + */ +extern SDL_DECLSPEC Uint32 SDLCALL SDL_GetAndroidExternalStorageState(void); + +/** + * Get the path used for external storage for this Android application. + * + * This path is unique to your application, but is public and can be written + * to by other applications. + * + * Your external storage path is typically: + * `/storage/sdcard0/Android/data/your.app.package/files`. + * + * This is a C wrapper over `android.content.Context.getExternalFilesDir()`: + * + * https://developer.android.com/reference/android/content/Context#getExternalFilesDir() + * + * \returns the path used for external storage for this application on success + * or NULL on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAndroidExternalStorageState + * \sa SDL_GetAndroidInternalStoragePath + * \sa SDL_GetAndroidCachePath + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetAndroidExternalStoragePath(void); + +/** + * Get the path used for caching data for this Android application. + * + * This path is unique to your application, but is public and can be written + * to by other applications. + * + * Your cache path is typically: `/data/data/your.app.package/cache/`. + * + * This is a C wrapper over `android.content.Context.getCacheDir()`: + * + * https://developer.android.com/reference/android/content/Context#getCacheDir() + * + * \returns the path used for caches for this application on success or NULL + * on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetAndroidInternalStoragePath + * \sa SDL_GetAndroidExternalStoragePath + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetAndroidCachePath(void); + +/** + * Callback that presents a response from a SDL_RequestAndroidPermission call. + * + * \param userdata an app-controlled pointer that is passed to the callback. + * \param permission the Android-specific permission name that was requested. + * \param granted true if permission is granted, false if denied. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_RequestAndroidPermission + */ +typedef void (SDLCALL *SDL_RequestAndroidPermissionCallback)(void *userdata, const char *permission, bool granted); + +/** + * Request permissions at runtime, asynchronously. + * + * You do not need to call this for built-in functionality of SDL; recording + * from a microphone or reading images from a camera, using standard SDL APIs, + * will manage permission requests for you. + * + * This function never blocks. Instead, the app-supplied callback will be + * called when a decision has been made. This callback may happen on a + * different thread, and possibly much later, as it might wait on a user to + * respond to a system dialog. If permission has already been granted for a + * specific entitlement, the callback will still fire, probably on the current + * thread and before this function returns. + * + * If the request submission fails, this function returns -1 and the callback + * will NOT be called, but this should only happen in catastrophic conditions, + * like memory running out. Normally there will be a yes or no to the request + * through the callback. + * + * For the `permission` parameter, choose a value from here: + * + * https://developer.android.com/reference/android/Manifest.permission + * + * \param permission the permission to request. + * \param cb the callback to trigger when the request has a response. + * \param userdata an app-controlled pointer that is passed to the callback. + * \returns true if the request was submitted, false if there was an error + * submitting. The result of the request is only ever reported + * through the callback, not this return value. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RequestAndroidPermission(const char *permission, SDL_RequestAndroidPermissionCallback cb, void *userdata); + +/** + * Shows an Android toast notification. + * + * Toasts are a sort of lightweight notification that are unique to Android. + * + * https://developer.android.com/guide/topics/ui/notifiers/toasts + * + * Shows toast in UI thread. + * + * For the `gravity` parameter, choose a value from here, or -1 if you don't + * have a preference: + * + * https://developer.android.com/reference/android/view/Gravity + * + * \param message text message to be shown. + * \param duration 0=short, 1=long. + * \param gravity where the notification should appear on the screen. + * \param xoffset set this parameter only when gravity >=0. + * \param yoffset set this parameter only when gravity >=0. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ShowAndroidToast(const char *message, int duration, int gravity, int xoffset, int yoffset); + +/** + * Send a user command to SDLActivity. + * + * Override "boolean onUnhandledMessage(Message msg)" to handle the message. + * + * \param command user command that must be greater or equal to 0x8000. + * \param param user parameter. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SendAndroidMessage(Uint32 command, int param); + +#endif /* SDL_PLATFORM_ANDROID */ + +/** + * Query if the current device is a tablet. + * + * If SDL can't determine this, it will return false. + * + * \returns true if the device is a tablet, false otherwise. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsTablet(void); + +/** + * Query if the current device is a TV. + * + * If SDL can't determine this, it will return false. + * + * \returns true if the device is a TV, false otherwise. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_IsTV(void); + +/** + * Application sandbox environment. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_Sandbox +{ + SDL_SANDBOX_NONE = 0, + SDL_SANDBOX_UNKNOWN_CONTAINER, + SDL_SANDBOX_FLATPAK, + SDL_SANDBOX_SNAP, + SDL_SANDBOX_MACOS +} SDL_Sandbox; + +/** + * Get the application sandbox environment, if any. + * + * \returns the application sandbox environment or SDL_SANDBOX_NONE if the + * application is not running in a sandbox environment. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Sandbox SDLCALL SDL_GetSandbox(void); + + +/* Functions used by iOS app delegates to notify SDL about state changes. */ + +/** + * Let iOS apps with external event handling report + * onApplicationWillTerminate. + * + * This functions allows iOS apps that have their own event handling to hook + * into SDL to generate SDL events. This maps directly to an iOS-specific + * event, but since it doesn't do anything iOS-specific internally, it is + * available on all platforms, in case it might be useful for some specific + * paradigm. Most apps do not need to use this directly; SDL's internal event + * code will handle all this for windows created by SDL_CreateWindow! + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_OnApplicationWillTerminate(void); + +/** + * Let iOS apps with external event handling report + * onApplicationDidReceiveMemoryWarning. + * + * This functions allows iOS apps that have their own event handling to hook + * into SDL to generate SDL events. This maps directly to an iOS-specific + * event, but since it doesn't do anything iOS-specific internally, it is + * available on all platforms, in case it might be useful for some specific + * paradigm. Most apps do not need to use this directly; SDL's internal event + * code will handle all this for windows created by SDL_CreateWindow! + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_OnApplicationDidReceiveMemoryWarning(void); + +/** + * Let iOS apps with external event handling report + * onApplicationWillResignActive. + * + * This functions allows iOS apps that have their own event handling to hook + * into SDL to generate SDL events. This maps directly to an iOS-specific + * event, but since it doesn't do anything iOS-specific internally, it is + * available on all platforms, in case it might be useful for some specific + * paradigm. Most apps do not need to use this directly; SDL's internal event + * code will handle all this for windows created by SDL_CreateWindow! + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_OnApplicationWillEnterBackground(void); + +/** + * Let iOS apps with external event handling report + * onApplicationDidEnterBackground. + * + * This functions allows iOS apps that have their own event handling to hook + * into SDL to generate SDL events. This maps directly to an iOS-specific + * event, but since it doesn't do anything iOS-specific internally, it is + * available on all platforms, in case it might be useful for some specific + * paradigm. Most apps do not need to use this directly; SDL's internal event + * code will handle all this for windows created by SDL_CreateWindow! + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_OnApplicationDidEnterBackground(void); + +/** + * Let iOS apps with external event handling report + * onApplicationWillEnterForeground. + * + * This functions allows iOS apps that have their own event handling to hook + * into SDL to generate SDL events. This maps directly to an iOS-specific + * event, but since it doesn't do anything iOS-specific internally, it is + * available on all platforms, in case it might be useful for some specific + * paradigm. Most apps do not need to use this directly; SDL's internal event + * code will handle all this for windows created by SDL_CreateWindow! + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_OnApplicationWillEnterForeground(void); + +/** + * Let iOS apps with external event handling report + * onApplicationDidBecomeActive. + * + * This functions allows iOS apps that have their own event handling to hook + * into SDL to generate SDL events. This maps directly to an iOS-specific + * event, but since it doesn't do anything iOS-specific internally, it is + * available on all platforms, in case it might be useful for some specific + * paradigm. Most apps do not need to use this directly; SDL's internal event + * code will handle all this for windows created by SDL_CreateWindow! + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_OnApplicationDidEnterForeground(void); + +#ifdef SDL_PLATFORM_IOS + +/** + * Let iOS apps with external event handling report + * onApplicationDidChangeStatusBarOrientation. + * + * This functions allows iOS apps that have their own event handling to hook + * into SDL to generate SDL events. This maps directly to an iOS-specific + * event, but since it doesn't do anything iOS-specific internally, it is + * available on all platforms, in case it might be useful for some specific + * paradigm. Most apps do not need to use this directly; SDL's internal event + * code will handle all this for windows created by SDL_CreateWindow! + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_OnApplicationDidChangeStatusBarOrientation(void); +#endif + +/* + * Functions used only by GDK + */ +#ifdef SDL_PLATFORM_GDK +typedef struct XTaskQueueObject *XTaskQueueHandle; +typedef struct XUser *XUserHandle; + +/** + * Gets a reference to the global async task queue handle for GDK, + * initializing if needed. + * + * Once you are done with the task queue, you should call + * XTaskQueueCloseHandle to reduce the reference count to avoid a resource + * leak. + * + * \param outTaskQueue a pointer to be filled in with task queue handle. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetGDKTaskQueue(XTaskQueueHandle *outTaskQueue); + +/** + * Gets a reference to the default user handle for GDK. + * + * This is effectively a synchronous version of XUserAddAsync, which always + * prefers the default user and allows a sign-in UI. + * + * \param outUserHandle a pointer to be filled in with the default user + * handle. + * \returns true if success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetGDKDefaultUser(XUserHandle *outUserHandle); + +#endif + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_system_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_thread.h b/thirdparty/sdl/include/SDL3/SDL_thread.h new file mode 100644 index 00000000000..e981b542932 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_thread.h @@ -0,0 +1,578 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_thread_h_ +#define SDL_thread_h_ + +/** + * # CategoryThread + * + * SDL offers cross-platform thread management functions. These are mostly + * concerned with starting threads, setting their priority, and dealing with + * their termination. + * + * In addition, there is support for Thread Local Storage (data that is unique + * to each thread, but accessed from a single key). + * + * On platforms without thread support (such as Emscripten when built without + * pthreads), these functions still exist, but things like SDL_CreateThread() + * will report failure without doing anything. + * + * If you're going to work with threads, you almost certainly need to have a + * good understanding of [CategoryMutex](CategoryMutex) as well. + */ + +#include +#include +#include + +/* Thread synchronization primitives */ +#include + +#if defined(SDL_PLATFORM_WINDOWS) +#include /* _beginthreadex() and _endthreadex() */ +#endif + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The SDL thread object. + * + * These are opaque data. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_CreateThread + * \sa SDL_WaitThread + */ +typedef struct SDL_Thread SDL_Thread; + +/** + * A unique numeric ID that identifies a thread. + * + * These are different from SDL_Thread objects, which are generally what an + * application will operate on, but having a way to uniquely identify a thread + * can be useful at times. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_GetThreadID + * \sa SDL_GetCurrentThreadID + */ +typedef Uint64 SDL_ThreadID; + +/** + * Thread local storage ID. + * + * 0 is the invalid ID. An app can create these and then set data for these + * IDs that is unique to each thread. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_GetTLS + * \sa SDL_SetTLS + */ +typedef SDL_AtomicInt SDL_TLSID; + +/** + * The SDL thread priority. + * + * SDL will make system changes as necessary in order to apply the thread + * priority. Code which attempts to control thread state related to priority + * should be aware that calling SDL_SetCurrentThreadPriority may alter such + * state. SDL_HINT_THREAD_PRIORITY_POLICY can be used to control aspects of + * this behavior. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_ThreadPriority { + SDL_THREAD_PRIORITY_LOW, + SDL_THREAD_PRIORITY_NORMAL, + SDL_THREAD_PRIORITY_HIGH, + SDL_THREAD_PRIORITY_TIME_CRITICAL +} SDL_ThreadPriority; + +/** + * The SDL thread state. + * + * The current state of a thread can be checked by calling SDL_GetThreadState. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_GetThreadState + */ +typedef enum SDL_ThreadState +{ + SDL_THREAD_UNKNOWN, /**< The thread is not valid */ + SDL_THREAD_ALIVE, /**< The thread is currently running */ + SDL_THREAD_DETACHED, /**< The thread is detached and can't be waited on */ + SDL_THREAD_COMPLETE /**< The thread has finished and should be cleaned up with SDL_WaitThread() */ +} SDL_ThreadState; + +/** + * The function passed to SDL_CreateThread() as the new thread's entry point. + * + * \param data what was passed as `data` to SDL_CreateThread(). + * \returns a value that can be reported through SDL_WaitThread(). + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef int (SDLCALL *SDL_ThreadFunction) (void *data); + + +#ifdef SDL_WIKI_DOCUMENTATION_SECTION + +/* + * Note that these aren't the correct function signatures in this block, but + * this is what the API reference manual should look like for all intents and + * purposes. + * + * Technical details, not for the wiki (hello, header readers!)... + * + * On Windows (and maybe other platforms), a program might use a different + * C runtime than its libraries. Or, in SDL's case, it might use a C runtime + * while SDL uses none at all. + * + * C runtimes expect to initialize thread-specific details when a new thread + * is created, but to do this in SDL_CreateThread would require SDL to know + * intimate details about the caller's C runtime, which is not possible. + * + * So SDL_CreateThread has two extra parameters, which are + * hidden at compile time by macros: the C runtime's `_beginthreadex` and + * `_endthreadex` entry points. If these are not NULL, they are used to spin + * and terminate the new thread; otherwise the standard Win32 `CreateThread` + * function is used. When `SDL_CreateThread` is called from a compiler that + * needs this C runtime thread init function, macros insert the appropriate + * function pointers for SDL_CreateThread's caller (which might be a different + * compiler with a different runtime in different calls to SDL_CreateThread!). + * + * SDL_BeginThreadFunction defaults to `_beginthreadex` on Windows (and NULL + * everywhere else), but apps that have extremely specific special needs can + * define this to something else and the SDL headers will use it, passing the + * app-defined value to SDL_CreateThread calls. Redefine this with caution! + * + * Platforms that don't need _beginthread stuff (most everything) will fail + * SDL_CreateThread with an error if these pointers _aren't_ NULL. + * + * Unless you are doing something extremely complicated, like perhaps a + * language binding, **you should never deal with this directly**. Let SDL's + * macros handle this platform-specific detail transparently! + */ + +/** + * Create a new thread with a default stack size. + * + * This is a convenience function, equivalent to calling + * SDL_CreateThreadWithProperties with the following properties set: + * + * - `SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER`: `fn` + * - `SDL_PROP_THREAD_CREATE_NAME_STRING`: `name` + * - `SDL_PROP_THREAD_CREATE_USERDATA_POINTER`: `data` + * + * Note that this "function" is actually a macro that calls an internal + * function with two extra parameters not listed here; they are hidden through + * preprocessor macros and are needed to support various C runtimes at the + * point of the function call. Language bindings that aren't using the C + * headers will need to deal with this. + * + * Usually, apps should just call this function the same way on every platform + * and let the macros hide the details. + * + * \param fn the SDL_ThreadFunction function to call in the new thread. + * \param name the name of the thread. + * \param data a pointer that is passed to `fn`. + * \returns an opaque pointer to the new thread object on success, NULL if the + * new thread could not be created; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateThreadWithProperties + * \sa SDL_WaitThread + */ +extern SDL_DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data); + +/** + * Create a new thread with with the specified properties. + * + * These are the supported properties: + * + * - `SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER`: an SDL_ThreadFunction + * value that will be called at the start of the new thread's life. + * Required. + * - `SDL_PROP_THREAD_CREATE_NAME_STRING`: the name of the new thread, which + * might be available to debuggers. Optional, defaults to NULL. + * - `SDL_PROP_THREAD_CREATE_USERDATA_POINTER`: an arbitrary app-defined + * pointer, which is passed to the entry function on the new thread, as its + * only parameter. Optional, defaults to NULL. + * - `SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER`: the size, in bytes, of the new + * thread's stack. Optional, defaults to 0 (system-defined default). + * + * SDL makes an attempt to report `SDL_PROP_THREAD_CREATE_NAME_STRING` to the + * system, so that debuggers can display it. Not all platforms support this. + * + * Thread naming is a little complicated: Most systems have very small limits + * for the string length (Haiku has 32 bytes, Linux currently has 16, Visual + * C++ 6.0 has _nine_!), and possibly other arbitrary rules. You'll have to + * see what happens with your system's debugger. The name should be UTF-8 (but + * using the naming limits of C identifiers is a better bet). There are no + * requirements for thread naming conventions, so long as the string is + * null-terminated UTF-8, but these guidelines are helpful in choosing a name: + * + * https://stackoverflow.com/questions/149932/naming-conventions-for-threads + * + * If a system imposes requirements, SDL will try to munge the string for it + * (truncate, etc), but the original string contents will be available from + * SDL_GetThreadName(). + * + * The size (in bytes) of the new stack can be specified with + * `SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER`. Zero means "use the system + * default" which might be wildly different between platforms. x86 Linux + * generally defaults to eight megabytes, an embedded device might be a few + * kilobytes instead. You generally need to specify a stack that is a multiple + * of the system's page size (in many cases, this is 4 kilobytes, but check + * your system documentation). + * + * Note that this "function" is actually a macro that calls an internal + * function with two extra parameters not listed here; they are hidden through + * preprocessor macros and are needed to support various C runtimes at the + * point of the function call. Language bindings that aren't using the C + * headers will need to deal with this. + * + * The actual symbol in SDL is `SDL_CreateThreadWithPropertiesRuntime`, so + * there is no symbol clash, but trying to load an SDL shared library and look + * for "SDL_CreateThreadWithProperties" will fail. + * + * Usually, apps should just call this function the same way on every platform + * and let the macros hide the details. + * + * \param props the properties to use. + * \returns an opaque pointer to the new thread object on success, NULL if the + * new thread could not be created; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateThread + * \sa SDL_WaitThread + */ +extern SDL_DECLSPEC SDL_Thread * SDLCALL SDL_CreateThreadWithProperties(SDL_PropertiesID props); + +#define SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER "SDL.thread.create.entry_function" +#define SDL_PROP_THREAD_CREATE_NAME_STRING "SDL.thread.create.name" +#define SDL_PROP_THREAD_CREATE_USERDATA_POINTER "SDL.thread.create.userdata" +#define SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER "SDL.thread.create.stacksize" + +/* end wiki documentation for macros that are meant to look like functions. */ +#endif + + +/* The real implementation, hidden from the wiki, so it can show this as real functions that don't have macro magic. */ +#ifndef SDL_WIKI_DOCUMENTATION_SECTION +# if defined(SDL_PLATFORM_WINDOWS) +# ifndef SDL_BeginThreadFunction +# define SDL_BeginThreadFunction _beginthreadex +# endif +# ifndef SDL_EndThreadFunction +# define SDL_EndThreadFunction _endthreadex +# endif +# endif +#endif + +/* currently no other platforms than Windows use _beginthreadex/_endthreadex things. */ +#ifndef SDL_WIKI_DOCUMENTATION_SECTION +# ifndef SDL_BeginThreadFunction +# define SDL_BeginThreadFunction NULL +# endif +#endif + +#ifndef SDL_WIKI_DOCUMENTATION_SECTION +# ifndef SDL_EndThreadFunction +# define SDL_EndThreadFunction NULL +# endif +#endif + +#ifndef SDL_WIKI_DOCUMENTATION_SECTION +/* These are the actual functions exported from SDL! Don't use them directly! Use the SDL_CreateThread and SDL_CreateThreadWithProperties macros! */ +/** + * The actual entry point for SDL_CreateThread. + * + * \param fn the SDL_ThreadFunction function to call in the new thread + * \param name the name of the thread + * \param data a pointer that is passed to `fn` + * \param pfnBeginThread the C runtime's _beginthreadex (or whatnot). Can be NULL. + * \param pfnEndThread the C runtime's _endthreadex (or whatnot). Can be NULL. + * \returns an opaque pointer to the new thread object on success, NULL if the + * new thread could not be created; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Thread * SDLCALL SDL_CreateThreadRuntime(SDL_ThreadFunction fn, const char *name, void *data, SDL_FunctionPointer pfnBeginThread, SDL_FunctionPointer pfnEndThread); + +/** + * The actual entry point for SDL_CreateThreadWithProperties. + * + * \param props the properties to use + * \param pfnBeginThread the C runtime's _beginthreadex (or whatnot). Can be NULL. + * \param pfnEndThread the C runtime's _endthreadex (or whatnot). Can be NULL. + * \returns an opaque pointer to the new thread object on success, NULL if the + * new thread could not be created; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Thread * SDLCALL SDL_CreateThreadWithPropertiesRuntime(SDL_PropertiesID props, SDL_FunctionPointer pfnBeginThread, SDL_FunctionPointer pfnEndThread); + +#define SDL_CreateThread(fn, name, data) SDL_CreateThreadRuntime((fn), (name), (data), (SDL_FunctionPointer) (SDL_BeginThreadFunction), (SDL_FunctionPointer) (SDL_EndThreadFunction)) +#define SDL_CreateThreadWithProperties(props) SDL_CreateThreadWithPropertiesRuntime((props), (SDL_FunctionPointer) (SDL_BeginThreadFunction), (SDL_FunctionPointer) (SDL_EndThreadFunction)) +#define SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER "SDL.thread.create.entry_function" +#define SDL_PROP_THREAD_CREATE_NAME_STRING "SDL.thread.create.name" +#define SDL_PROP_THREAD_CREATE_USERDATA_POINTER "SDL.thread.create.userdata" +#define SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER "SDL.thread.create.stacksize" +#endif + + +/** + * Get the thread name as it was specified in SDL_CreateThread(). + * + * \param thread the thread to query. + * \returns a pointer to a UTF-8 string that names the specified thread, or + * NULL if it doesn't have a name. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetThreadName(SDL_Thread *thread); + +/** + * Get the thread identifier for the current thread. + * + * This thread identifier is as reported by the underlying operating system. + * If SDL is running on a platform that does not support threads the return + * value will always be zero. + * + * This function also returns a valid thread ID when called from the main + * thread. + * + * \returns the ID of the current thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetThreadID + */ +extern SDL_DECLSPEC SDL_ThreadID SDLCALL SDL_GetCurrentThreadID(void); + +/** + * Get the thread identifier for the specified thread. + * + * This thread identifier is as reported by the underlying operating system. + * If SDL is running on a platform that does not support threads the return + * value will always be zero. + * + * \param thread the thread to query. + * \returns the ID of the specified thread, or the ID of the current thread if + * `thread` is NULL. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetCurrentThreadID + */ +extern SDL_DECLSPEC SDL_ThreadID SDLCALL SDL_GetThreadID(SDL_Thread *thread); + +/** + * Set the priority for the current thread. + * + * Note that some platforms will not let you alter the priority (or at least, + * promote the thread to a higher priority) at all, and some require you to be + * an administrator account. Be prepared for this to fail. + * + * \param priority the SDL_ThreadPriority to set. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetCurrentThreadPriority(SDL_ThreadPriority priority); + +/** + * Wait for a thread to finish. + * + * Threads that haven't been detached will remain until this function cleans + * them up. Not doing so is a resource leak. + * + * Once a thread has been cleaned up through this function, the SDL_Thread + * that references it becomes invalid and should not be referenced again. As + * such, only one thread may call SDL_WaitThread() on another. + * + * The return code from the thread function is placed in the area pointed to + * by `status`, if `status` is not NULL. + * + * You may not wait on a thread that has been used in a call to + * SDL_DetachThread(). Use either that function or this one, but not both, or + * behavior is undefined. + * + * It is safe to pass a NULL thread to this function; it is a no-op. + * + * Note that the thread pointer is freed by this function and is not valid + * afterward. + * + * \param thread the SDL_Thread pointer that was returned from the + * SDL_CreateThread() call that started this thread. + * \param status a pointer filled in with the value returned from the thread + * function by its 'return', or -1 if the thread has been + * detached or isn't valid, may be NULL. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateThread + * \sa SDL_DetachThread + */ +extern SDL_DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread *thread, int *status); + +/** + * Get the current state of a thread. + * + * \param thread the thread to query. + * \returns the current state of a thread, or SDL_THREAD_UNKNOWN if the thread + * isn't valid. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ThreadState + */ +extern SDL_DECLSPEC SDL_ThreadState SDLCALL SDL_GetThreadState(SDL_Thread *thread); + +/** + * Let a thread clean up on exit without intervention. + * + * A thread may be "detached" to signify that it should not remain until + * another thread has called SDL_WaitThread() on it. Detaching a thread is + * useful for long-running threads that nothing needs to synchronize with or + * further manage. When a detached thread is done, it simply goes away. + * + * There is no way to recover the return code of a detached thread. If you + * need this, don't detach the thread and instead use SDL_WaitThread(). + * + * Once a thread is detached, you should usually assume the SDL_Thread isn't + * safe to reference again, as it will become invalid immediately upon the + * detached thread's exit, instead of remaining until someone has called + * SDL_WaitThread() to finally clean it up. As such, don't detach the same + * thread more than once. + * + * If a thread has already exited when passed to SDL_DetachThread(), it will + * stop waiting for a call to SDL_WaitThread() and clean up immediately. It is + * not safe to detach a thread that might be used with SDL_WaitThread(). + * + * You may not call SDL_WaitThread() on a thread that has been detached. Use + * either that function or this one, but not both, or behavior is undefined. + * + * It is safe to pass NULL to this function; it is a no-op. + * + * \param thread the SDL_Thread pointer that was returned from the + * SDL_CreateThread() call that started this thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateThread + * \sa SDL_WaitThread + */ +extern SDL_DECLSPEC void SDLCALL SDL_DetachThread(SDL_Thread *thread); + +/** + * Get the current thread's value associated with a thread local storage ID. + * + * \param id a pointer to the thread local storage ID, may not be NULL. + * \returns the value associated with the ID for the current thread or NULL if + * no value has been set; call SDL_GetError() for more information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetTLS + */ +extern SDL_DECLSPEC void * SDLCALL SDL_GetTLS(SDL_TLSID *id); + +/** + * The callback used to cleanup data passed to SDL_SetTLS. + * + * This is called when a thread exits, to allow an app to free any resources. + * + * \param value a pointer previously handed to SDL_SetTLS. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_SetTLS + */ +typedef void (SDLCALL *SDL_TLSDestructorCallback)(void *value); + +/** + * Set the current thread's value associated with a thread local storage ID. + * + * If the thread local storage ID is not initialized (the value is 0), a new + * ID will be created in a thread-safe way, so all calls using a pointer to + * the same ID will refer to the same local storage. + * + * Note that replacing a value from a previous call to this function on the + * same thread does _not_ call the previous value's destructor! + * + * `destructor` can be NULL; it is assumed that `value` does not need to be + * cleaned up if so. + * + * \param id a pointer to the thread local storage ID, may not be NULL. + * \param value the value to associate with the ID for the current thread. + * \param destructor a function called when the thread exits, to free the + * value, may be NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTLS + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetTLS(SDL_TLSID *id, const void *value, SDL_TLSDestructorCallback destructor); + +/** + * Cleanup all TLS data for this thread. + * + * If you are creating your threads outside of SDL and then calling SDL + * functions, you should call this function before your thread exits, to + * properly clean up SDL memory. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_CleanupTLS(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_thread_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_time.h b/thirdparty/sdl/include/SDL3/SDL_time.h new file mode 100644 index 00000000000..b6d3f6d0d80 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_time.h @@ -0,0 +1,231 @@ +/* +Simple DirectMedia Layer +Copyright (C) 1997-2025 Sam Lantinga + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_time_h_ +#define SDL_time_h_ + +/** + * # CategoryTime + * + * SDL realtime clock and date/time routines. + * + * There are two data types that are used in this category: SDL_Time, which + * represents the nanoseconds since a specific moment (an "epoch"), and + * SDL_DateTime, which breaks time down into human-understandable components: + * years, months, days, hours, etc. + * + * Much of the functionality is involved in converting those two types to + * other useful forms. + */ + +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A structure holding a calendar date and time broken down into its + * components. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_DateTime +{ + int year; /**< Year */ + int month; /**< Month [01-12] */ + int day; /**< Day of the month [01-31] */ + int hour; /**< Hour [0-23] */ + int minute; /**< Minute [0-59] */ + int second; /**< Seconds [0-60] */ + int nanosecond; /**< Nanoseconds [0-999999999] */ + int day_of_week; /**< Day of the week [0-6] (0 being Sunday) */ + int utc_offset; /**< Seconds east of UTC */ +} SDL_DateTime; + +/** + * The preferred date format of the current system locale. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_GetDateTimeLocalePreferences + */ +typedef enum SDL_DateFormat +{ + SDL_DATE_FORMAT_YYYYMMDD = 0, /**< Year/Month/Day */ + SDL_DATE_FORMAT_DDMMYYYY = 1, /**< Day/Month/Year */ + SDL_DATE_FORMAT_MMDDYYYY = 2 /**< Month/Day/Year */ +} SDL_DateFormat; + +/** + * The preferred time format of the current system locale. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_GetDateTimeLocalePreferences + */ +typedef enum SDL_TimeFormat +{ + SDL_TIME_FORMAT_24HR = 0, /**< 24 hour time */ + SDL_TIME_FORMAT_12HR = 1 /**< 12 hour time */ +} SDL_TimeFormat; + +/** + * Gets the current preferred date and time format for the system locale. + * + * This might be a "slow" call that has to query the operating system. It's + * best to ask for this once and save the results. However, the preferred + * formats can change, usually because the user has changed a system + * preference outside of your program. + * + * \param dateFormat a pointer to the SDL_DateFormat to hold the returned date + * format, may be NULL. + * \param timeFormat a pointer to the SDL_TimeFormat to hold the returned time + * format, may be NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetDateTimeLocalePreferences(SDL_DateFormat *dateFormat, SDL_TimeFormat *timeFormat); + +/** + * Gets the current value of the system realtime clock in nanoseconds since + * Jan 1, 1970 in Universal Coordinated Time (UTC). + * + * \param ticks the SDL_Time to hold the returned tick count. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetCurrentTime(SDL_Time *ticks); + +/** + * Converts an SDL_Time in nanoseconds since the epoch to a calendar time in + * the SDL_DateTime format. + * + * \param ticks the SDL_Time to be converted. + * \param dt the resulting SDL_DateTime. + * \param localTime the resulting SDL_DateTime will be expressed in local time + * if true, otherwise it will be in Universal Coordinated + * Time (UTC). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_TimeToDateTime(SDL_Time ticks, SDL_DateTime *dt, bool localTime); + +/** + * Converts a calendar time to an SDL_Time in nanoseconds since the epoch. + * + * This function ignores the day_of_week member of the SDL_DateTime struct, so + * it may remain unset. + * + * \param dt the source SDL_DateTime. + * \param ticks the resulting SDL_Time. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_DateTimeToTime(const SDL_DateTime *dt, SDL_Time *ticks); + +/** + * Converts an SDL time into a Windows FILETIME (100-nanosecond intervals + * since January 1, 1601). + * + * This function fills in the two 32-bit values of the FILETIME structure. + * + * \param ticks the time to convert. + * \param dwLowDateTime a pointer filled in with the low portion of the + * Windows FILETIME value. + * \param dwHighDateTime a pointer filled in with the high portion of the + * Windows FILETIME value. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_TimeToWindows(SDL_Time ticks, Uint32 *dwLowDateTime, Uint32 *dwHighDateTime); + +/** + * Converts a Windows FILETIME (100-nanosecond intervals since January 1, + * 1601) to an SDL time. + * + * This function takes the two 32-bit values of the FILETIME structure as + * parameters. + * + * \param dwLowDateTime the low portion of the Windows FILETIME value. + * \param dwHighDateTime the high portion of the Windows FILETIME value. + * \returns the converted SDL time. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Time SDLCALL SDL_TimeFromWindows(Uint32 dwLowDateTime, Uint32 dwHighDateTime); + +/** + * Get the number of days in a month for a given year. + * + * \param year the year. + * \param month the month [1-12]. + * \returns the number of days in the requested month or -1 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetDaysInMonth(int year, int month); + +/** + * Get the day of year for a calendar date. + * + * \param year the year component of the date. + * \param month the month component of the date. + * \param day the day component of the date. + * \returns the day of year [0-365] if the date is valid or -1 on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetDayOfYear(int year, int month, int day); + +/** + * Get the day of week for a calendar date. + * + * \param year the year component of the date. + * \param month the month component of the date. + * \param day the day component of the date. + * \returns a value between 0 and 6 (0 being Sunday) if the date is valid or + * -1 on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetDayOfWeek(int year, int month, int day); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_time_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_timer.h b/thirdparty/sdl/include/SDL3/SDL_timer.h new file mode 100644 index 00000000000..cf94881d570 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_timer.h @@ -0,0 +1,450 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_timer_h_ +#define SDL_timer_h_ + +/** + * # CategoryTimer + * + * SDL provides time management functionality. It is useful for dealing with + * (usually) small durations of time. + * + * This is not to be confused with _calendar time_ management, which is + * provided by [CategoryTime](CategoryTime). + * + * This category covers measuring time elapsed (SDL_GetTicks(), + * SDL_GetPerformanceCounter()), putting a thread to sleep for a certain + * amount of time (SDL_Delay(), SDL_DelayNS(), SDL_DelayPrecise()), and firing + * a callback function after a certain amount of time has elasped + * (SDL_AddTimer(), etc). + * + * There are also useful macros to convert between time units, like + * SDL_SECONDS_TO_NS() and such. + */ + +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* SDL time constants */ + +/** + * Number of milliseconds in a second. + * + * This is always 1000. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_MS_PER_SECOND 1000 + +/** + * Number of microseconds in a second. + * + * This is always 1000000. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_US_PER_SECOND 1000000 + +/** + * Number of nanoseconds in a second. + * + * This is always 1000000000. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NS_PER_SECOND 1000000000LL + +/** + * Number of nanoseconds in a millisecond. + * + * This is always 1000000. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NS_PER_MS 1000000 + +/** + * Number of nanoseconds in a microsecond. + * + * This is always 1000. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NS_PER_US 1000 + +/** + * Convert seconds to nanoseconds. + * + * This only converts whole numbers, not fractional seconds. + * + * \param S the number of seconds to convert. + * \returns S, expressed in nanoseconds. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_SECONDS_TO_NS(S) (((Uint64)(S)) * SDL_NS_PER_SECOND) + +/** + * Convert nanoseconds to seconds. + * + * This performs a division, so the results can be dramatically different if + * `NS` is an integer or floating point value. + * + * \param NS the number of nanoseconds to convert. + * \returns NS, expressed in seconds. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NS_TO_SECONDS(NS) ((NS) / SDL_NS_PER_SECOND) + +/** + * Convert milliseconds to nanoseconds. + * + * This only converts whole numbers, not fractional milliseconds. + * + * \param MS the number of milliseconds to convert. + * \returns MS, expressed in nanoseconds. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_MS_TO_NS(MS) (((Uint64)(MS)) * SDL_NS_PER_MS) + +/** + * Convert nanoseconds to milliseconds. + * + * This performs a division, so the results can be dramatically different if + * `NS` is an integer or floating point value. + * + * \param NS the number of nanoseconds to convert. + * \returns NS, expressed in milliseconds. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NS_TO_MS(NS) ((NS) / SDL_NS_PER_MS) + +/** + * Convert microseconds to nanoseconds. + * + * This only converts whole numbers, not fractional microseconds. + * + * \param US the number of microseconds to convert. + * \returns US, expressed in nanoseconds. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_US_TO_NS(US) (((Uint64)(US)) * SDL_NS_PER_US) + +/** + * Convert nanoseconds to microseconds. + * + * This performs a division, so the results can be dramatically different if + * `NS` is an integer or floating point value. + * + * \param NS the number of nanoseconds to convert. + * \returns NS, expressed in microseconds. + * + * \threadsafety It is safe to call this macro from any thread. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_NS_TO_US(NS) ((NS) / SDL_NS_PER_US) + +/** + * Get the number of milliseconds since SDL library initialization. + * + * \returns an unsigned 64-bit value representing the number of milliseconds + * since the SDL library initialized. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint64 SDLCALL SDL_GetTicks(void); + +/** + * Get the number of nanoseconds since SDL library initialization. + * + * \returns an unsigned 64-bit value representing the number of nanoseconds + * since the SDL library initialized. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC Uint64 SDLCALL SDL_GetTicksNS(void); + +/** + * Get the current value of the high resolution counter. + * + * This function is typically used for profiling. + * + * The counter values are only meaningful relative to each other. Differences + * between values can be converted to times by using + * SDL_GetPerformanceFrequency(). + * + * \returns the current counter value. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPerformanceFrequency + */ +extern SDL_DECLSPEC Uint64 SDLCALL SDL_GetPerformanceCounter(void); + +/** + * Get the count per second of the high resolution counter. + * + * \returns a platform-specific count per second. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetPerformanceCounter + */ +extern SDL_DECLSPEC Uint64 SDLCALL SDL_GetPerformanceFrequency(void); + +/** + * Wait a specified number of milliseconds before returning. + * + * This function waits a specified number of milliseconds before returning. It + * waits at least the specified time, but possibly longer due to OS + * scheduling. + * + * \param ms the number of milliseconds to delay. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DelayNS + * \sa SDL_DelayPrecise + */ +extern SDL_DECLSPEC void SDLCALL SDL_Delay(Uint32 ms); + +/** + * Wait a specified number of nanoseconds before returning. + * + * This function waits a specified number of nanoseconds before returning. It + * waits at least the specified time, but possibly longer due to OS + * scheduling. + * + * \param ns the number of nanoseconds to delay. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Delay + * \sa SDL_DelayPrecise + */ +extern SDL_DECLSPEC void SDLCALL SDL_DelayNS(Uint64 ns); + +/** + * Wait a specified number of nanoseconds before returning. + * + * This function waits a specified number of nanoseconds before returning. It + * will attempt to wait as close to the requested time as possible, busy + * waiting if necessary, but could return later due to OS scheduling. + * + * \param ns the number of nanoseconds to delay. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_Delay + * \sa SDL_DelayNS + */ +extern SDL_DECLSPEC void SDLCALL SDL_DelayPrecise(Uint64 ns); + +/** + * Definition of the timer ID type. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_TimerID; + +/** + * Function prototype for the millisecond timer callback function. + * + * The callback function is passed the current timer interval and returns the + * next timer interval, in milliseconds. If the returned value is the same as + * the one passed in, the periodic alarm continues, otherwise a new alarm is + * scheduled. If the callback returns 0, the periodic alarm is canceled and + * will be removed. + * + * \param userdata an arbitrary pointer provided by the app through + * SDL_AddTimer, for its own use. + * \param timerID the current timer being processed. + * \param interval the current callback time interval. + * \returns the new callback time interval, or 0 to disable further runs of + * the callback. + * + * \threadsafety SDL may call this callback at any time from a background + * thread; the application is responsible for locking resources + * the callback touches that need to be protected. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_AddTimer + */ +typedef Uint32 (SDLCALL *SDL_TimerCallback)(void *userdata, SDL_TimerID timerID, Uint32 interval); + +/** + * Call a callback function at a future time. + * + * The callback function is passed the current timer interval and the user + * supplied parameter from the SDL_AddTimer() call and should return the next + * timer interval. If the value returned from the callback is 0, the timer is + * canceled and will be removed. + * + * The callback is run on a separate thread, and for short timeouts can + * potentially be called before this function returns. + * + * Timers take into account the amount of time it took to execute the + * callback. For example, if the callback took 250 ms to execute and returned + * 1000 (ms), the timer would only wait another 750 ms before its next + * iteration. + * + * Timing may be inexact due to OS scheduling. Be sure to note the current + * time with SDL_GetTicksNS() or SDL_GetPerformanceCounter() in case your + * callback needs to adjust for variances. + * + * \param interval the timer delay, in milliseconds, passed to `callback`. + * \param callback the SDL_TimerCallback function to call when the specified + * `interval` elapses. + * \param userdata a pointer that is passed to `callback`. + * \returns a timer ID or 0 on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddTimerNS + * \sa SDL_RemoveTimer + */ +extern SDL_DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *userdata); + +/** + * Function prototype for the nanosecond timer callback function. + * + * The callback function is passed the current timer interval and returns the + * next timer interval, in nanoseconds. If the returned value is the same as + * the one passed in, the periodic alarm continues, otherwise a new alarm is + * scheduled. If the callback returns 0, the periodic alarm is canceled and + * will be removed. + * + * \param userdata an arbitrary pointer provided by the app through + * SDL_AddTimer, for its own use. + * \param timerID the current timer being processed. + * \param interval the current callback time interval. + * \returns the new callback time interval, or 0 to disable further runs of + * the callback. + * + * \threadsafety SDL may call this callback at any time from a background + * thread; the application is responsible for locking resources + * the callback touches that need to be protected. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_AddTimerNS + */ +typedef Uint64 (SDLCALL *SDL_NSTimerCallback)(void *userdata, SDL_TimerID timerID, Uint64 interval); + +/** + * Call a callback function at a future time. + * + * The callback function is passed the current timer interval and the user + * supplied parameter from the SDL_AddTimerNS() call and should return the + * next timer interval. If the value returned from the callback is 0, the + * timer is canceled and will be removed. + * + * The callback is run on a separate thread, and for short timeouts can + * potentially be called before this function returns. + * + * Timers take into account the amount of time it took to execute the + * callback. For example, if the callback took 250 ns to execute and returned + * 1000 (ns), the timer would only wait another 750 ns before its next + * iteration. + * + * Timing may be inexact due to OS scheduling. Be sure to note the current + * time with SDL_GetTicksNS() or SDL_GetPerformanceCounter() in case your + * callback needs to adjust for variances. + * + * \param interval the timer delay, in nanoseconds, passed to `callback`. + * \param callback the SDL_TimerCallback function to call when the specified + * `interval` elapses. + * \param userdata a pointer that is passed to `callback`. + * \returns a timer ID or 0 on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddTimer + * \sa SDL_RemoveTimer + */ +extern SDL_DECLSPEC SDL_TimerID SDLCALL SDL_AddTimerNS(Uint64 interval, SDL_NSTimerCallback callback, void *userdata); + +/** + * Remove a timer created with SDL_AddTimer(). + * + * \param id the ID of the timer to remove. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety It is safe to call this function from any thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_AddTimer + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RemoveTimer(SDL_TimerID id); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_timer_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_touch.h b/thirdparty/sdl/include/SDL3/SDL_touch.h new file mode 100644 index 00000000000..64845a15682 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_touch.h @@ -0,0 +1,184 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryTouch + * + * SDL offers touch input, on platforms that support it. It can manage + * multiple touch devices and track multiple fingers on those devices. + * + * Touches are mostly dealt with through the event system, in the + * SDL_EVENT_FINGER_DOWN, SDL_EVENT_FINGER_MOTION, and SDL_EVENT_FINGER_UP + * events, but there are also functions to query for hardware details, etc. + * + * The touch system, by default, will also send virtual mouse events; this can + * be useful for making a some desktop apps work on a phone without + * significant changes. For apps that care about mouse and touch input + * separately, they should ignore mouse events that have a `which` field of + * SDL_TOUCH_MOUSEID. + */ + +#ifndef SDL_touch_h_ +#define SDL_touch_h_ + +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A unique ID for a touch device. + * + * This ID is valid for the time the device is connected to the system, and is + * never reused for the lifetime of the application. + * + * The value 0 is an invalid ID. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint64 SDL_TouchID; + +/** + * A unique ID for a single finger on a touch device. + * + * This ID is valid for the time the finger (stylus, etc) is touching and will + * be unique for all fingers currently in contact, so this ID tracks the + * lifetime of a single continuous touch. This value may represent an index, a + * pointer, or some other unique ID, depending on the platform. + * + * The value 0 is an invalid ID. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint64 SDL_FingerID; + +/** + * An enum that describes the type of a touch device. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_TouchDeviceType +{ + SDL_TOUCH_DEVICE_INVALID = -1, + SDL_TOUCH_DEVICE_DIRECT, /**< touch screen with window-relative coordinates */ + SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE, /**< trackpad with absolute device coordinates */ + SDL_TOUCH_DEVICE_INDIRECT_RELATIVE /**< trackpad with screen cursor-relative coordinates */ +} SDL_TouchDeviceType; + +/** + * Data about a single finger in a multitouch event. + * + * Each touch event is a collection of fingers that are simultaneously in + * contact with the touch device (so a "touch" can be a "multitouch," in + * reality), and this struct reports details of the specific fingers. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_GetTouchFingers + */ +typedef struct SDL_Finger +{ + SDL_FingerID id; /**< the finger ID */ + float x; /**< the x-axis location of the touch event, normalized (0...1) */ + float y; /**< the y-axis location of the touch event, normalized (0...1) */ + float pressure; /**< the quantity of pressure applied, normalized (0...1) */ +} SDL_Finger; + +/** + * The SDL_MouseID for mouse events simulated with touch input. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_TOUCH_MOUSEID ((SDL_MouseID)-1) + +/** + * The SDL_TouchID for touch events simulated with mouse input. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_MOUSE_TOUCHID ((SDL_TouchID)-1) + + +/** + * Get a list of registered touch devices. + * + * On some platforms SDL first sees the touch device if it was actually used. + * Therefore the returned list might be empty, although devices are available. + * After using all devices at least once the number will be correct. + * + * \param count a pointer filled in with the number of devices returned, may + * be NULL. + * \returns a 0 terminated array of touch device IDs or NULL on failure; call + * SDL_GetError() for more information. This should be freed with + * SDL_free() when it is no longer needed. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_TouchID * SDLCALL SDL_GetTouchDevices(int *count); + +/** + * Get the touch device name as reported from the driver. + * + * \param touchID the touch device instance ID. + * \returns touch device name, or NULL on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetTouchDeviceName(SDL_TouchID touchID); + +/** + * Get the type of the given touch device. + * + * \param touchID the ID of a touch device. + * \returns touch device type. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_TouchDeviceType SDLCALL SDL_GetTouchDeviceType(SDL_TouchID touchID); + +/** + * Get a list of active fingers for a given touch device. + * + * \param touchID the ID of a touch device. + * \param count a pointer filled in with the number of fingers returned, can + * be NULL. + * \returns a NULL terminated array of SDL_Finger pointers or NULL on failure; + * call SDL_GetError() for more information. This is a single + * allocation that should be freed with SDL_free() when it is no + * longer needed. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Finger ** SDLCALL SDL_GetTouchFingers(SDL_TouchID touchID, int *count); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_touch_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_tray.h b/thirdparty/sdl/include/SDL3/SDL_tray.h new file mode 100644 index 00000000000..1780b0ba52b --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_tray.h @@ -0,0 +1,544 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryTray + * + * SDL offers a way to add items to the "system tray" (more correctly called + * the "notification area" on Windows). On platforms that offer this concept, + * an SDL app can add a tray icon, submenus, checkboxes, and clickable + * entries, and register a callback that is fired when the user clicks on + * these pieces. + */ + +#ifndef SDL_tray_h_ +#define SDL_tray_h_ + +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * An opaque handle representing a toplevel system tray object. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_Tray SDL_Tray; + +/** + * An opaque handle representing a menu/submenu on a system tray object. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_TrayMenu SDL_TrayMenu; + +/** + * An opaque handle representing an entry on a system tray object. + * + * \since This struct is available since SDL 3.2.0. + */ +typedef struct SDL_TrayEntry SDL_TrayEntry; + +/** + * Flags that control the creation of system tray entries. + * + * Some of these flags are required; exactly one of them must be specified at + * the time a tray entry is created. Other flags are optional; zero or more of + * those can be OR'ed together with the required flag. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_InsertTrayEntryAt + */ +typedef Uint32 SDL_TrayEntryFlags; + +#define SDL_TRAYENTRY_BUTTON 0x00000001u /**< Make the entry a simple button. Required. */ +#define SDL_TRAYENTRY_CHECKBOX 0x00000002u /**< Make the entry a checkbox. Required. */ +#define SDL_TRAYENTRY_SUBMENU 0x00000004u /**< Prepare the entry to have a submenu. Required */ +#define SDL_TRAYENTRY_DISABLED 0x80000000u /**< Make the entry disabled. Optional. */ +#define SDL_TRAYENTRY_CHECKED 0x40000000u /**< Make the entry checked. This is valid only for checkboxes. Optional. */ + +/** + * A callback that is invoked when a tray entry is selected. + * + * \param userdata an optional pointer to pass extra data to the callback when + * it will be invoked. + * \param entry the tray entry that was selected. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_SetTrayEntryCallback + */ +typedef void (SDLCALL *SDL_TrayCallback)(void *userdata, SDL_TrayEntry *entry); + +/** + * Create an icon to be placed in the operating system's tray, or equivalent. + * + * Many platforms advise not using a system tray unless persistence is a + * necessary feature. Avoid needlessly creating a tray icon, as the user may + * feel like it clutters their interface. + * + * Using tray icons require the video subsystem. + * + * \param icon a surface to be used as icon. May be NULL. + * \param tooltip a tooltip to be displayed when the mouse hovers the icon in + * UTF-8 encoding. Not supported on all platforms. May be NULL. + * \returns The newly created system tray icon. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTrayMenu + * \sa SDL_GetTrayMenu + * \sa SDL_DestroyTray + */ +extern SDL_DECLSPEC SDL_Tray * SDLCALL SDL_CreateTray(SDL_Surface *icon, const char *tooltip); + +/** + * Updates the system tray icon's icon. + * + * \param tray the tray icon to be updated. + * \param icon the new icon. May be NULL. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTray + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetTrayIcon(SDL_Tray *tray, SDL_Surface *icon); + +/** + * Updates the system tray icon's tooltip. + * + * \param tray the tray icon to be updated. + * \param tooltip the new tooltip in UTF-8 encoding. May be NULL. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTray + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetTrayTooltip(SDL_Tray *tray, const char *tooltip); + +/** + * Create a menu for a system tray. + * + * This should be called at most once per tray icon. + * + * This function does the same thing as SDL_CreateTraySubmenu(), except that + * it takes a SDL_Tray instead of a SDL_TrayEntry. + * + * A menu does not need to be destroyed; it will be destroyed with the tray. + * + * \param tray the tray to bind the menu to. + * \returns the newly created menu. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTray + * \sa SDL_GetTrayMenu + * \sa SDL_GetTrayMenuParentTray + */ +extern SDL_DECLSPEC SDL_TrayMenu * SDLCALL SDL_CreateTrayMenu(SDL_Tray *tray); + +/** + * Create a submenu for a system tray entry. + * + * This should be called at most once per tray entry. + * + * This function does the same thing as SDL_CreateTrayMenu, except that it + * takes a SDL_TrayEntry instead of a SDL_Tray. + * + * A menu does not need to be destroyed; it will be destroyed with the tray. + * + * \param entry the tray entry to bind the menu to. + * \returns the newly created menu. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_InsertTrayEntryAt + * \sa SDL_GetTraySubmenu + * \sa SDL_GetTrayMenuParentEntry + */ +extern SDL_DECLSPEC SDL_TrayMenu * SDLCALL SDL_CreateTraySubmenu(SDL_TrayEntry *entry); + +/** + * Gets a previously created tray menu. + * + * You should have called SDL_CreateTrayMenu() on the tray object. This + * function allows you to fetch it again later. + * + * This function does the same thing as SDL_GetTraySubmenu(), except that it + * takes a SDL_Tray instead of a SDL_TrayEntry. + * + * A menu does not need to be destroyed; it will be destroyed with the tray. + * + * \param tray the tray entry to bind the menu to. + * \returns the newly created menu. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTray + * \sa SDL_CreateTrayMenu + */ +extern SDL_DECLSPEC SDL_TrayMenu * SDLCALL SDL_GetTrayMenu(SDL_Tray *tray); + +/** + * Gets a previously created tray entry submenu. + * + * You should have called SDL_CreateTraySubmenu() on the entry object. This + * function allows you to fetch it again later. + * + * This function does the same thing as SDL_GetTrayMenu(), except that it + * takes a SDL_TrayEntry instead of a SDL_Tray. + * + * A menu does not need to be destroyed; it will be destroyed with the tray. + * + * \param entry the tray entry to bind the menu to. + * \returns the newly created menu. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_InsertTrayEntryAt + * \sa SDL_CreateTraySubmenu + */ +extern SDL_DECLSPEC SDL_TrayMenu * SDLCALL SDL_GetTraySubmenu(SDL_TrayEntry *entry); + +/** + * Returns a list of entries in the menu, in order. + * + * \param menu The menu to get entries from. + * \param count An optional pointer to obtain the number of entries in the + * menu. + * \returns a NULL-terminated list of entries within the given menu. The + * pointer becomes invalid when any function that inserts or deletes + * entries in the menu is called. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_RemoveTrayEntry + * \sa SDL_InsertTrayEntryAt + */ +extern SDL_DECLSPEC const SDL_TrayEntry ** SDLCALL SDL_GetTrayEntries(SDL_TrayMenu *menu, int *count); + +/** + * Removes a tray entry. + * + * \param entry The entry to be deleted. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTrayEntries + * \sa SDL_InsertTrayEntryAt + */ +extern SDL_DECLSPEC void SDLCALL SDL_RemoveTrayEntry(SDL_TrayEntry *entry); + +/** + * Insert a tray entry at a given position. + * + * If label is NULL, the entry will be a separator. Many functions won't work + * for an entry that is a separator. + * + * An entry does not need to be destroyed; it will be destroyed with the tray. + * + * \param menu the menu to append the entry to. + * \param pos the desired position for the new entry. Entries at or following + * this place will be moved. If pos is -1, the entry is appended. + * \param label the text to be displayed on the entry, in UTF-8 encoding, or + * NULL for a separator. + * \param flags a combination of flags, some of which are mandatory. + * \returns the newly created entry, or NULL if pos is out of bounds. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_TrayEntryFlags + * \sa SDL_GetTrayEntries + * \sa SDL_RemoveTrayEntry + * \sa SDL_GetTrayEntryParent + */ +extern SDL_DECLSPEC SDL_TrayEntry * SDLCALL SDL_InsertTrayEntryAt(SDL_TrayMenu *menu, int pos, const char *label, SDL_TrayEntryFlags flags); + +/** + * Sets the label of an entry. + * + * An entry cannot change between a separator and an ordinary entry; that is, + * it is not possible to set a non-NULL label on an entry that has a NULL + * label (separators), or to set a NULL label to an entry that has a non-NULL + * label. The function will silently fail if that happens. + * + * \param entry the entry to be updated. + * \param label the new label for the entry in UTF-8 encoding. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTrayEntries + * \sa SDL_InsertTrayEntryAt + * \sa SDL_GetTrayEntryLabel + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetTrayEntryLabel(SDL_TrayEntry *entry, const char *label); + +/** + * Gets the label of an entry. + * + * If the returned value is NULL, the entry is a separator. + * + * \param entry the entry to be read. + * \returns the label of the entry in UTF-8 encoding. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTrayEntries + * \sa SDL_InsertTrayEntryAt + * \sa SDL_SetTrayEntryLabel + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetTrayEntryLabel(SDL_TrayEntry *entry); + +/** + * Sets whether or not an entry is checked. + * + * The entry must have been created with the SDL_TRAYENTRY_CHECKBOX flag. + * + * \param entry the entry to be updated. + * \param checked true if the entry should be checked; false otherwise. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTrayEntries + * \sa SDL_InsertTrayEntryAt + * \sa SDL_GetTrayEntryChecked + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetTrayEntryChecked(SDL_TrayEntry *entry, bool checked); + +/** + * Gets whether or not an entry is checked. + * + * The entry must have been created with the SDL_TRAYENTRY_CHECKBOX flag. + * + * \param entry the entry to be read. + * \returns true if the entry is checked; false otherwise. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTrayEntries + * \sa SDL_InsertTrayEntryAt + * \sa SDL_SetTrayEntryChecked + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetTrayEntryChecked(SDL_TrayEntry *entry); + +/** + * Sets whether or not an entry is enabled. + * + * \param entry the entry to be updated. + * \param enabled true if the entry should be enabled; false otherwise. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTrayEntries + * \sa SDL_InsertTrayEntryAt + * \sa SDL_GetTrayEntryEnabled + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetTrayEntryEnabled(SDL_TrayEntry *entry, bool enabled); + +/** + * Gets whether or not an entry is enabled. + * + * \param entry the entry to be read. + * \returns true if the entry is enabled; false otherwise. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTrayEntries + * \sa SDL_InsertTrayEntryAt + * \sa SDL_SetTrayEntryEnabled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetTrayEntryEnabled(SDL_TrayEntry *entry); + +/** + * Sets a callback to be invoked when the entry is selected. + * + * \param entry the entry to be updated. + * \param callback a callback to be invoked when the entry is selected. + * \param userdata an optional pointer to pass extra data to the callback when + * it will be invoked. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetTrayEntries + * \sa SDL_InsertTrayEntryAt + */ +extern SDL_DECLSPEC void SDLCALL SDL_SetTrayEntryCallback(SDL_TrayEntry *entry, SDL_TrayCallback callback, void *userdata); + +/** + * Simulate a click on a tray entry. + * + * \param entry The entry to activate. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_ClickTrayEntry(SDL_TrayEntry *entry); + +/** + * Destroys a tray object. + * + * This also destroys all associated menus and entries. + * + * \param tray the tray icon to be destroyed. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTray + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyTray(SDL_Tray *tray); + +/** + * Gets the menu containing a certain tray entry. + * + * \param entry the entry for which to get the parent menu. + * \returns the parent menu. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_InsertTrayEntryAt + */ +extern SDL_DECLSPEC SDL_TrayMenu * SDLCALL SDL_GetTrayEntryParent(SDL_TrayEntry *entry); + +/** + * Gets the entry for which the menu is a submenu, if the current menu is a + * submenu. + * + * Either this function or SDL_GetTrayMenuParentTray() will return non-NULL + * for any given menu. + * + * \param menu the menu for which to get the parent entry. + * \returns the parent entry, or NULL if this menu is not a submenu. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTraySubmenu + * \sa SDL_GetTrayMenuParentTray + */ +extern SDL_DECLSPEC SDL_TrayEntry * SDLCALL SDL_GetTrayMenuParentEntry(SDL_TrayMenu *menu); + +/** + * Gets the tray for which this menu is the first-level menu, if the current + * menu isn't a submenu. + * + * Either this function or SDL_GetTrayMenuParentEntry() will return non-NULL + * for any given menu. + * + * \param menu the menu for which to get the parent enttrayry. + * \returns the parent tray, or NULL if this menu is a submenu. + * + * \threadsafety This function should be called on the thread that created the + * tray. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateTrayMenu + * \sa SDL_GetTrayMenuParentEntry + */ +extern SDL_DECLSPEC SDL_Tray * SDLCALL SDL_GetTrayMenuParentTray(SDL_TrayMenu *menu); + +/** + * Update the trays. + * + * This is called automatically by the event loop and is only needed if you're + * using trays but aren't handling SDL events. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_UpdateTrays(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_tray_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_version.h b/thirdparty/sdl/include/SDL3/SDL_version.h new file mode 100644 index 00000000000..435b3f95fe7 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_version.h @@ -0,0 +1,183 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryVersion + * + * Functionality to query the current SDL version, both as headers the app was + * compiled against, and a library the app is linked to. + */ + +#ifndef SDL_version_h_ +#define SDL_version_h_ + +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The current major version of SDL headers. + * + * If this were SDL version 3.2.1, this value would be 3. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_MAJOR_VERSION 3 + +/** + * The current minor version of the SDL headers. + * + * If this were SDL version 3.2.1, this value would be 2. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_MINOR_VERSION 2 + +/** + * The current micro (or patchlevel) version of the SDL headers. + * + * If this were SDL version 3.2.1, this value would be 1. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_MICRO_VERSION 16 + +/** + * This macro turns the version numbers into a numeric value. + * + * (1,2,3) becomes 1002003. + * + * \param major the major version number. + * \param minor the minorversion number. + * \param patch the patch version number. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_VERSIONNUM(major, minor, patch) \ + ((major) * 1000000 + (minor) * 1000 + (patch)) + +/** + * This macro extracts the major version from a version number + * + * 1002003 becomes 1. + * + * \param version the version number. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_VERSIONNUM_MAJOR(version) ((version) / 1000000) + +/** + * This macro extracts the minor version from a version number + * + * 1002003 becomes 2. + * + * \param version the version number. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_VERSIONNUM_MINOR(version) (((version) / 1000) % 1000) + +/** + * This macro extracts the micro version from a version number + * + * 1002003 becomes 3. + * + * \param version the version number. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_VERSIONNUM_MICRO(version) ((version) % 1000) + +/** + * This is the version number macro for the current SDL version. + * + * \since This macro is available since SDL 3.2.0. + * + * \sa SDL_GetVersion + */ +#define SDL_VERSION \ + SDL_VERSIONNUM(SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_MICRO_VERSION) + +/** + * This macro will evaluate to true if compiled with SDL at least X.Y.Z. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_VERSION_ATLEAST(X, Y, Z) \ + (SDL_VERSION >= SDL_VERSIONNUM(X, Y, Z)) + +/** + * Get the version of SDL that is linked against your program. + * + * If you are linking to SDL dynamically, then it is possible that the current + * version will be different than the version you compiled against. This + * function returns the current version, while SDL_VERSION is the version you + * compiled with. + * + * This function may be called safely at any time, even before SDL_Init(). + * + * \returns the version of the linked library. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRevision + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetVersion(void); + +/** + * Get the code revision of SDL that is linked against your program. + * + * This value is the revision of the code you are linked with and may be + * different from the code you are compiling with, which is found in the + * constant SDL_REVISION. + * + * The revision is arbitrary string (a hash value) uniquely identifying the + * exact revision of the SDL library in use, and is only useful in comparing + * against other revisions. It is NOT an incrementing number. + * + * If SDL wasn't built from a git repository with the appropriate tools, this + * will return an empty string. + * + * You shouldn't use this function for anything but logging it for debugging + * purposes. The string is not intended to be reliable in any way. + * + * \returns an arbitrary string, uniquely identifying the exact revision of + * the SDL library in use. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetVersion + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetRevision(void); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_version_h_ */ diff --git a/thirdparty/sdl/include/SDL3/SDL_video.h b/thirdparty/sdl/include/SDL3/SDL_video.h new file mode 100644 index 00000000000..877b9adde59 --- /dev/null +++ b/thirdparty/sdl/include/SDL3/SDL_video.h @@ -0,0 +1,3298 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryVideo + * + * SDL's video subsystem is largely interested in abstracting window + * management from the underlying operating system. You can create windows, + * manage them in various ways, set them fullscreen, and get events when + * interesting things happen with them, such as the mouse or keyboard + * interacting with a window. + * + * The video subsystem is also interested in abstracting away some + * platform-specific differences in OpenGL: context creation, swapping + * buffers, etc. This may be crucial to your app, but also you are not + * required to use OpenGL at all. In fact, SDL can provide rendering to those + * windows as well, either with an easy-to-use + * [2D API](https://wiki.libsdl.org/SDL3/CategoryRender) + * or with a more-powerful + * [GPU API](https://wiki.libsdl.org/SDL3/CategoryGPU) + * . Of course, it can simply get out of your way and give you the window + * handles you need to use Vulkan, Direct3D, Metal, or whatever else you like + * directly, too. + * + * The video subsystem covers a lot of functionality, out of necessity, so it + * is worth perusing the list of functions just to see what's available, but + * most apps can get by with simply creating a window and listening for + * events, so start with SDL_CreateWindow() and SDL_PollEvent(). + */ + +#ifndef SDL_video_h_ +#define SDL_video_h_ + +#include +#include +#include +#include +#include +#include + +#include +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * This is a unique ID for a display for the time it is connected to the + * system, and is never reused for the lifetime of the application. + * + * If the display is disconnected and reconnected, it will get a new ID. + * + * The value 0 is an invalid ID. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_DisplayID; + +/** + * This is a unique ID for a window. + * + * The value 0 is an invalid ID. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_WindowID; + +/* Global video properties... */ + +/** + * The pointer to the global `wl_display` object used by the Wayland video + * backend. + * + * Can be set before the video subsystem is initialized to import an external + * `wl_display` object from an application or toolkit for use in SDL, or read + * after initialization to export the `wl_display` used by the Wayland video + * backend. Setting this property after the video subsystem has been + * initialized has no effect, and reading it when the video subsystem is + * uninitialized will either return the user provided value, if one was set + * prior to initialization, or NULL. See docs/README-wayland.md for more + * information. + */ +#define SDL_PROP_GLOBAL_VIDEO_WAYLAND_WL_DISPLAY_POINTER "SDL.video.wayland.wl_display" + +/** + * System theme. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_SystemTheme +{ + SDL_SYSTEM_THEME_UNKNOWN, /**< Unknown system theme */ + SDL_SYSTEM_THEME_LIGHT, /**< Light colored system theme */ + SDL_SYSTEM_THEME_DARK /**< Dark colored system theme */ +} SDL_SystemTheme; + +/** + * Internal display mode data. + * + * This lives as a field in SDL_DisplayMode, as opaque data. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_DisplayMode + */ +typedef struct SDL_DisplayModeData SDL_DisplayModeData; + +/** + * The structure that defines a display mode. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_GetFullscreenDisplayModes + * \sa SDL_GetDesktopDisplayMode + * \sa SDL_GetCurrentDisplayMode + * \sa SDL_SetWindowFullscreenMode + * \sa SDL_GetWindowFullscreenMode + */ +typedef struct SDL_DisplayMode +{ + SDL_DisplayID displayID; /**< the display this mode is associated with */ + SDL_PixelFormat format; /**< pixel format */ + int w; /**< width */ + int h; /**< height */ + float pixel_density; /**< scale converting size to pixels (e.g. a 1920x1080 mode with 2.0 scale would have 3840x2160 pixels) */ + float refresh_rate; /**< refresh rate (or 0.0f for unspecified) */ + int refresh_rate_numerator; /**< precise refresh rate numerator (or 0 for unspecified) */ + int refresh_rate_denominator; /**< precise refresh rate denominator */ + + SDL_DisplayModeData *internal; /**< Private */ + +} SDL_DisplayMode; + +/** + * Display orientation values; the way a display is rotated. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_DisplayOrientation +{ + SDL_ORIENTATION_UNKNOWN, /**< The display orientation can't be determined */ + SDL_ORIENTATION_LANDSCAPE, /**< The display is in landscape mode, with the right side up, relative to portrait mode */ + SDL_ORIENTATION_LANDSCAPE_FLIPPED, /**< The display is in landscape mode, with the left side up, relative to portrait mode */ + SDL_ORIENTATION_PORTRAIT, /**< The display is in portrait mode */ + SDL_ORIENTATION_PORTRAIT_FLIPPED /**< The display is in portrait mode, upside down */ +} SDL_DisplayOrientation; + +/** + * The struct used as an opaque handle to a window. + * + * \since This struct is available since SDL 3.2.0. + * + * \sa SDL_CreateWindow + */ +typedef struct SDL_Window SDL_Window; + +/** + * The flags on a window. + * + * These cover a lot of true/false, or on/off, window state. Some of it is + * immutable after being set through SDL_CreateWindow(), some of it can be + * changed on existing windows by the app, and some of it might be altered by + * the user or system outside of the app's control. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_GetWindowFlags + */ +typedef Uint64 SDL_WindowFlags; + +#define SDL_WINDOW_FULLSCREEN SDL_UINT64_C(0x0000000000000001) /**< window is in fullscreen mode */ +#define SDL_WINDOW_OPENGL SDL_UINT64_C(0x0000000000000002) /**< window usable with OpenGL context */ +#define SDL_WINDOW_OCCLUDED SDL_UINT64_C(0x0000000000000004) /**< window is occluded */ +#define SDL_WINDOW_HIDDEN SDL_UINT64_C(0x0000000000000008) /**< window is neither mapped onto the desktop nor shown in the taskbar/dock/window list; SDL_ShowWindow() is required for it to become visible */ +#define SDL_WINDOW_BORDERLESS SDL_UINT64_C(0x0000000000000010) /**< no window decoration */ +#define SDL_WINDOW_RESIZABLE SDL_UINT64_C(0x0000000000000020) /**< window can be resized */ +#define SDL_WINDOW_MINIMIZED SDL_UINT64_C(0x0000000000000040) /**< window is minimized */ +#define SDL_WINDOW_MAXIMIZED SDL_UINT64_C(0x0000000000000080) /**< window is maximized */ +#define SDL_WINDOW_MOUSE_GRABBED SDL_UINT64_C(0x0000000000000100) /**< window has grabbed mouse input */ +#define SDL_WINDOW_INPUT_FOCUS SDL_UINT64_C(0x0000000000000200) /**< window has input focus */ +#define SDL_WINDOW_MOUSE_FOCUS SDL_UINT64_C(0x0000000000000400) /**< window has mouse focus */ +#define SDL_WINDOW_EXTERNAL SDL_UINT64_C(0x0000000000000800) /**< window not created by SDL */ +#define SDL_WINDOW_MODAL SDL_UINT64_C(0x0000000000001000) /**< window is modal */ +#define SDL_WINDOW_HIGH_PIXEL_DENSITY SDL_UINT64_C(0x0000000000002000) /**< window uses high pixel density back buffer if possible */ +#define SDL_WINDOW_MOUSE_CAPTURE SDL_UINT64_C(0x0000000000004000) /**< window has mouse captured (unrelated to MOUSE_GRABBED) */ +#define SDL_WINDOW_MOUSE_RELATIVE_MODE SDL_UINT64_C(0x0000000000008000) /**< window has relative mode enabled */ +#define SDL_WINDOW_ALWAYS_ON_TOP SDL_UINT64_C(0x0000000000010000) /**< window should always be above others */ +#define SDL_WINDOW_UTILITY SDL_UINT64_C(0x0000000000020000) /**< window should be treated as a utility window, not showing in the task bar and window list */ +#define SDL_WINDOW_TOOLTIP SDL_UINT64_C(0x0000000000040000) /**< window should be treated as a tooltip and does not get mouse or keyboard focus, requires a parent window */ +#define SDL_WINDOW_POPUP_MENU SDL_UINT64_C(0x0000000000080000) /**< window should be treated as a popup menu, requires a parent window */ +#define SDL_WINDOW_KEYBOARD_GRABBED SDL_UINT64_C(0x0000000000100000) /**< window has grabbed keyboard input */ +#define SDL_WINDOW_VULKAN SDL_UINT64_C(0x0000000010000000) /**< window usable for Vulkan surface */ +#define SDL_WINDOW_METAL SDL_UINT64_C(0x0000000020000000) /**< window usable for Metal view */ +#define SDL_WINDOW_TRANSPARENT SDL_UINT64_C(0x0000000040000000) /**< window with transparent buffer */ +#define SDL_WINDOW_NOT_FOCUSABLE SDL_UINT64_C(0x0000000080000000) /**< window should not be focusable */ + + +/** + * A magic value used with SDL_WINDOWPOS_UNDEFINED. + * + * Generally this macro isn't used directly, but rather through + * SDL_WINDOWPOS_UNDEFINED or SDL_WINDOWPOS_UNDEFINED_DISPLAY. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WINDOWPOS_UNDEFINED_MASK 0x1FFF0000u + +/** + * Used to indicate that you don't care what the window position is. + * + * If you _really_ don't care, SDL_WINDOWPOS_UNDEFINED is the same, but always + * uses the primary display instead of specifying one. + * + * \param X the SDL_DisplayID of the display to use. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WINDOWPOS_UNDEFINED_DISPLAY(X) (SDL_WINDOWPOS_UNDEFINED_MASK|(X)) + +/** + * Used to indicate that you don't care what the window position/display is. + * + * This always uses the primary display. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WINDOWPOS_UNDEFINED SDL_WINDOWPOS_UNDEFINED_DISPLAY(0) + +/** + * A macro to test if the window position is marked as "undefined." + * + * \param X the window position value. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WINDOWPOS_ISUNDEFINED(X) (((X)&0xFFFF0000) == SDL_WINDOWPOS_UNDEFINED_MASK) + +/** + * A magic value used with SDL_WINDOWPOS_CENTERED. + * + * Generally this macro isn't used directly, but rather through + * SDL_WINDOWPOS_CENTERED or SDL_WINDOWPOS_CENTERED_DISPLAY. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WINDOWPOS_CENTERED_MASK 0x2FFF0000u + +/** + * Used to indicate that the window position should be centered. + * + * SDL_WINDOWPOS_CENTERED is the same, but always uses the primary display + * instead of specifying one. + * + * \param X the SDL_DisplayID of the display to use. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WINDOWPOS_CENTERED_DISPLAY(X) (SDL_WINDOWPOS_CENTERED_MASK|(X)) + +/** + * Used to indicate that the window position should be centered. + * + * This always uses the primary display. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WINDOWPOS_CENTERED SDL_WINDOWPOS_CENTERED_DISPLAY(0) + +/** + * A macro to test if the window position is marked as "centered." + * + * \param X the window position value. + * + * \since This macro is available since SDL 3.2.0. + */ +#define SDL_WINDOWPOS_ISCENTERED(X) \ + (((X)&0xFFFF0000) == SDL_WINDOWPOS_CENTERED_MASK) + + +/** + * Window flash operation. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_FlashOperation +{ + SDL_FLASH_CANCEL, /**< Cancel any window flash state */ + SDL_FLASH_BRIEFLY, /**< Flash the window briefly to get attention */ + SDL_FLASH_UNTIL_FOCUSED /**< Flash the window until it gets focus */ +} SDL_FlashOperation; + +/** + * An opaque handle to an OpenGL context. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_GL_CreateContext + */ +typedef struct SDL_GLContextState *SDL_GLContext; + +/** + * Opaque type for an EGL display. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef void *SDL_EGLDisplay; + +/** + * Opaque type for an EGL config. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef void *SDL_EGLConfig; + +/** + * Opaque type for an EGL surface. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef void *SDL_EGLSurface; + +/** + * An EGL attribute, used when creating an EGL context. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef intptr_t SDL_EGLAttrib; + +/** + * An EGL integer attribute, used when creating an EGL surface. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef int SDL_EGLint; + +/** + * EGL platform attribute initialization callback. + * + * This is called when SDL is attempting to create an EGL context, to let the + * app add extra attributes to its eglGetPlatformDisplay() call. + * + * The callback should return a pointer to an EGL attribute array terminated + * with `EGL_NONE`. If this function returns NULL, the SDL_CreateWindow + * process will fail gracefully. + * + * The returned pointer should be allocated with SDL_malloc() and will be + * passed to SDL_free(). + * + * The arrays returned by each callback will be appended to the existing + * attribute arrays defined by SDL. + * + * \param userdata an app-controlled pointer that is passed to the callback. + * \returns a newly-allocated array of attributes, terminated with `EGL_NONE`. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_EGL_SetAttributeCallbacks + */ +typedef SDL_EGLAttrib *(SDLCALL *SDL_EGLAttribArrayCallback)(void *userdata); + +/** + * EGL surface/context attribute initialization callback types. + * + * This is called when SDL is attempting to create an EGL surface, to let the + * app add extra attributes to its eglCreateWindowSurface() or + * eglCreateContext calls. + * + * For convenience, the EGLDisplay and EGLConfig to use are provided to the + * callback. + * + * The callback should return a pointer to an EGL attribute array terminated + * with `EGL_NONE`. If this function returns NULL, the SDL_CreateWindow + * process will fail gracefully. + * + * The returned pointer should be allocated with SDL_malloc() and will be + * passed to SDL_free(). + * + * The arrays returned by each callback will be appended to the existing + * attribute arrays defined by SDL. + * + * \param userdata an app-controlled pointer that is passed to the callback. + * \param display the EGL display to be used. + * \param config the EGL config to be used. + * \returns a newly-allocated array of attributes, terminated with `EGL_NONE`. + * + * \since This datatype is available since SDL 3.2.0. + * + * \sa SDL_EGL_SetAttributeCallbacks + */ +typedef SDL_EGLint *(SDLCALL *SDL_EGLIntArrayCallback)(void *userdata, SDL_EGLDisplay display, SDL_EGLConfig config); + +/** + * An enumeration of OpenGL configuration attributes. + * + * While you can set most OpenGL attributes normally, the attributes listed + * above must be known before SDL creates the window that will be used with + * the OpenGL context. These attributes are set and read with + * SDL_GL_SetAttribute() and SDL_GL_GetAttribute(). + * + * In some cases, these attributes are minimum requests; the GL does not + * promise to give you exactly what you asked for. It's possible to ask for a + * 16-bit depth buffer and get a 24-bit one instead, for example, or to ask + * for no stencil buffer and still have one available. Context creation should + * fail if the GL can't provide your requested attributes at a minimum, but + * you should check to see exactly what you got. + * + * \since This enum is available since SDL 3.2.0. + */ +typedef enum SDL_GLAttr +{ + SDL_GL_RED_SIZE, /**< the minimum number of bits for the red channel of the color buffer; defaults to 8. */ + SDL_GL_GREEN_SIZE, /**< the minimum number of bits for the green channel of the color buffer; defaults to 8. */ + SDL_GL_BLUE_SIZE, /**< the minimum number of bits for the blue channel of the color buffer; defaults to 8. */ + SDL_GL_ALPHA_SIZE, /**< the minimum number of bits for the alpha channel of the color buffer; defaults to 8. */ + SDL_GL_BUFFER_SIZE, /**< the minimum number of bits for frame buffer size; defaults to 0. */ + SDL_GL_DOUBLEBUFFER, /**< whether the output is single or double buffered; defaults to double buffering on. */ + SDL_GL_DEPTH_SIZE, /**< the minimum number of bits in the depth buffer; defaults to 16. */ + SDL_GL_STENCIL_SIZE, /**< the minimum number of bits in the stencil buffer; defaults to 0. */ + SDL_GL_ACCUM_RED_SIZE, /**< the minimum number of bits for the red channel of the accumulation buffer; defaults to 0. */ + SDL_GL_ACCUM_GREEN_SIZE, /**< the minimum number of bits for the green channel of the accumulation buffer; defaults to 0. */ + SDL_GL_ACCUM_BLUE_SIZE, /**< the minimum number of bits for the blue channel of the accumulation buffer; defaults to 0. */ + SDL_GL_ACCUM_ALPHA_SIZE, /**< the minimum number of bits for the alpha channel of the accumulation buffer; defaults to 0. */ + SDL_GL_STEREO, /**< whether the output is stereo 3D; defaults to off. */ + SDL_GL_MULTISAMPLEBUFFERS, /**< the number of buffers used for multisample anti-aliasing; defaults to 0. */ + SDL_GL_MULTISAMPLESAMPLES, /**< the number of samples used around the current pixel used for multisample anti-aliasing. */ + SDL_GL_ACCELERATED_VISUAL, /**< set to 1 to require hardware acceleration, set to 0 to force software rendering; defaults to allow either. */ + SDL_GL_RETAINED_BACKING, /**< not used (deprecated). */ + SDL_GL_CONTEXT_MAJOR_VERSION, /**< OpenGL context major version. */ + SDL_GL_CONTEXT_MINOR_VERSION, /**< OpenGL context minor version. */ + SDL_GL_CONTEXT_FLAGS, /**< some combination of 0 or more of elements of the SDL_GLContextFlag enumeration; defaults to 0. */ + SDL_GL_CONTEXT_PROFILE_MASK, /**< type of GL context (Core, Compatibility, ES). See SDL_GLProfile; default value depends on platform. */ + SDL_GL_SHARE_WITH_CURRENT_CONTEXT, /**< OpenGL context sharing; defaults to 0. */ + SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, /**< requests sRGB capable visual; defaults to 0. */ + SDL_GL_CONTEXT_RELEASE_BEHAVIOR, /**< sets context the release behavior. See SDL_GLContextReleaseFlag; defaults to FLUSH. */ + SDL_GL_CONTEXT_RESET_NOTIFICATION, /**< set context reset notification. See SDL_GLContextResetNotification; defaults to NO_NOTIFICATION. */ + SDL_GL_CONTEXT_NO_ERROR, + SDL_GL_FLOATBUFFERS, + SDL_GL_EGL_PLATFORM +} SDL_GLAttr; + +/** + * Possible values to be set for the SDL_GL_CONTEXT_PROFILE_MASK attribute. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_GLProfile; + +#define SDL_GL_CONTEXT_PROFILE_CORE 0x0001 /**< OpenGL Core Profile context */ +#define SDL_GL_CONTEXT_PROFILE_COMPATIBILITY 0x0002 /**< OpenGL Compatibility Profile context */ +#define SDL_GL_CONTEXT_PROFILE_ES 0x0004 /**< GLX_CONTEXT_ES2_PROFILE_BIT_EXT */ + + +/** + * Possible flags to be set for the SDL_GL_CONTEXT_FLAGS attribute. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_GLContextFlag; + +#define SDL_GL_CONTEXT_DEBUG_FLAG 0x0001 +#define SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG 0x0002 +#define SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG 0x0004 +#define SDL_GL_CONTEXT_RESET_ISOLATION_FLAG 0x0008 + + +/** + * Possible values to be set for the SDL_GL_CONTEXT_RELEASE_BEHAVIOR + * attribute. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_GLContextReleaseFlag; + +#define SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE 0x0000 +#define SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH 0x0001 + + +/** + * Possible values to be set SDL_GL_CONTEXT_RESET_NOTIFICATION attribute. + * + * \since This datatype is available since SDL 3.2.0. + */ +typedef Uint32 SDL_GLContextResetNotification; + +#define SDL_GL_CONTEXT_RESET_NO_NOTIFICATION 0x0000 +#define SDL_GL_CONTEXT_RESET_LOSE_CONTEXT 0x0001 + + +/* Function prototypes */ + +/** + * Get the number of video drivers compiled into SDL. + * + * \returns the number of built in video drivers. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetVideoDriver + */ +extern SDL_DECLSPEC int SDLCALL SDL_GetNumVideoDrivers(void); + +/** + * Get the name of a built in video driver. + * + * The video drivers are presented in the order in which they are normally + * checked during initialization. + * + * The names of drivers are all simple, low-ASCII identifiers, like "cocoa", + * "x11" or "windows". These never have Unicode characters, and are not meant + * to be proper names. + * + * \param index the index of a video driver. + * \returns the name of the video driver with the given **index**. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumVideoDrivers + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetVideoDriver(int index); + +/** + * Get the name of the currently initialized video driver. + * + * The names of drivers are all simple, low-ASCII identifiers, like "cocoa", + * "x11" or "windows". These never have Unicode characters, and are not meant + * to be proper names. + * + * \returns the name of the current video driver or NULL if no driver has been + * initialized. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetNumVideoDrivers + * \sa SDL_GetVideoDriver + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetCurrentVideoDriver(void); + +/** + * Get the current system theme. + * + * \returns the current system theme, light, dark, or unknown. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_SystemTheme SDLCALL SDL_GetSystemTheme(void); + +/** + * Get a list of currently connected displays. + * + * \param count a pointer filled in with the number of displays returned, may + * be NULL. + * \returns a 0 terminated array of display instance IDs or NULL on failure; + * call SDL_GetError() for more information. This should be freed + * with SDL_free() when it is no longer needed. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_DisplayID * SDLCALL SDL_GetDisplays(int *count); + +/** + * Return the primary display. + * + * \returns the instance ID of the primary display on success or 0 on failure; + * call SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC SDL_DisplayID SDLCALL SDL_GetPrimaryDisplay(void); + +/** + * Get the properties associated with a display. + * + * The following read-only properties are provided by SDL: + * + * - `SDL_PROP_DISPLAY_HDR_ENABLED_BOOLEAN`: true if the display has HDR + * headroom above the SDR white point. This is for informational and + * diagnostic purposes only, as not all platforms provide this information + * at the display level. + * + * On KMS/DRM: + * + * - `SDL_PROP_DISPLAY_KMSDRM_PANEL_ORIENTATION_NUMBER`: the "panel + * orientation" property for the display in degrees of clockwise rotation. + * Note that this is provided only as a hint, and the application is + * responsible for any coordinate transformations needed to conform to the + * requested display orientation. + * + * \param displayID the instance ID of the display to query. + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetDisplayProperties(SDL_DisplayID displayID); + +#define SDL_PROP_DISPLAY_HDR_ENABLED_BOOLEAN "SDL.display.HDR_enabled" +#define SDL_PROP_DISPLAY_KMSDRM_PANEL_ORIENTATION_NUMBER "SDL.display.KMSDRM.panel_orientation" + +/** + * Get the name of a display in UTF-8 encoding. + * + * \param displayID the instance ID of the display to query. + * \returns the name of a display or NULL on failure; call SDL_GetError() for + * more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetDisplayName(SDL_DisplayID displayID); + +/** + * Get the desktop area represented by a display. + * + * The primary display is often located at (0,0), but may be placed at a + * different location depending on monitor layout. + * + * \param displayID the instance ID of the display to query. + * \param rect the SDL_Rect structure filled in with the display bounds. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplayUsableBounds + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetDisplayBounds(SDL_DisplayID displayID, SDL_Rect *rect); + +/** + * Get the usable desktop area represented by a display, in screen + * coordinates. + * + * This is the same area as SDL_GetDisplayBounds() reports, but with portions + * reserved by the system removed. For example, on Apple's macOS, this + * subtracts the area occupied by the menu bar and dock. + * + * Setting a window to be fullscreen generally bypasses these unusable areas, + * so these are good guidelines for the maximum space available to a + * non-fullscreen window. + * + * \param displayID the instance ID of the display to query. + * \param rect the SDL_Rect structure filled in with the display bounds. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplayBounds + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetDisplayUsableBounds(SDL_DisplayID displayID, SDL_Rect *rect); + +/** + * Get the orientation of a display when it is unrotated. + * + * \param displayID the instance ID of the display to query. + * \returns the SDL_DisplayOrientation enum value of the display, or + * `SDL_ORIENTATION_UNKNOWN` if it isn't available. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC SDL_DisplayOrientation SDLCALL SDL_GetNaturalDisplayOrientation(SDL_DisplayID displayID); + +/** + * Get the orientation of a display. + * + * \param displayID the instance ID of the display to query. + * \returns the SDL_DisplayOrientation enum value of the display, or + * `SDL_ORIENTATION_UNKNOWN` if it isn't available. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC SDL_DisplayOrientation SDLCALL SDL_GetCurrentDisplayOrientation(SDL_DisplayID displayID); + +/** + * Get the content scale of a display. + * + * The content scale is the expected scale for content based on the DPI + * settings of the display. For example, a 4K display might have a 2.0 (200%) + * display scale, which means that the user expects UI elements to be twice as + * big on this display, to aid in readability. + * + * After window creation, SDL_GetWindowDisplayScale() should be used to query + * the content scale factor for individual windows instead of querying the + * display for a window and calling this function, as the per-window content + * scale factor may differ from the base value of the display it is on, + * particularly on high-DPI and/or multi-monitor desktop configurations. + * + * \param displayID the instance ID of the display to query. + * \returns the content scale of the display, or 0.0f on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowDisplayScale + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC float SDLCALL SDL_GetDisplayContentScale(SDL_DisplayID displayID); + +/** + * Get a list of fullscreen display modes available on a display. + * + * The display modes are sorted in this priority: + * + * - w -> largest to smallest + * - h -> largest to smallest + * - bits per pixel -> more colors to fewer colors + * - packed pixel layout -> largest to smallest + * - refresh rate -> highest to lowest + * - pixel density -> lowest to highest + * + * \param displayID the instance ID of the display to query. + * \param count a pointer filled in with the number of display modes returned, + * may be NULL. + * \returns a NULL terminated array of display mode pointers or NULL on + * failure; call SDL_GetError() for more information. This is a + * single allocation that should be freed with SDL_free() when it is + * no longer needed. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC SDL_DisplayMode ** SDLCALL SDL_GetFullscreenDisplayModes(SDL_DisplayID displayID, int *count); + +/** + * Get the closest match to the requested display mode. + * + * The available display modes are scanned and `closest` is filled in with the + * closest mode matching the requested mode and returned. The mode format and + * refresh rate default to the desktop mode if they are set to 0. The modes + * are scanned with size being first priority, format being second priority, + * and finally checking the refresh rate. If all the available modes are too + * small, then false is returned. + * + * \param displayID the instance ID of the display to query. + * \param w the width in pixels of the desired display mode. + * \param h the height in pixels of the desired display mode. + * \param refresh_rate the refresh rate of the desired display mode, or 0.0f + * for the desktop refresh rate. + * \param include_high_density_modes boolean to include high density modes in + * the search. + * \param closest a pointer filled in with the closest display mode equal to + * or larger than the desired mode. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplays + * \sa SDL_GetFullscreenDisplayModes + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetClosestFullscreenDisplayMode(SDL_DisplayID displayID, int w, int h, float refresh_rate, bool include_high_density_modes, SDL_DisplayMode *closest); + +/** + * Get information about the desktop's display mode. + * + * There's a difference between this function and SDL_GetCurrentDisplayMode() + * when SDL runs fullscreen and has changed the resolution. In that case this + * function will return the previous native display mode, and not the current + * display mode. + * + * \param displayID the instance ID of the display to query. + * \returns a pointer to the desktop display mode or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetCurrentDisplayMode + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC const SDL_DisplayMode * SDLCALL SDL_GetDesktopDisplayMode(SDL_DisplayID displayID); + +/** + * Get information about the current display mode. + * + * There's a difference between this function and SDL_GetDesktopDisplayMode() + * when SDL runs fullscreen and has changed the resolution. In that case this + * function will return the current display mode, and not the previous native + * display mode. + * + * \param displayID the instance ID of the display to query. + * \returns a pointer to the desktop display mode or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDesktopDisplayMode + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC const SDL_DisplayMode * SDLCALL SDL_GetCurrentDisplayMode(SDL_DisplayID displayID); + +/** + * Get the display containing a point. + * + * \param point the point to query. + * \returns the instance ID of the display containing the point or 0 on + * failure; call SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplayBounds + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC SDL_DisplayID SDLCALL SDL_GetDisplayForPoint(const SDL_Point *point); + +/** + * Get the display primarily containing a rect. + * + * \param rect the rect to query. + * \returns the instance ID of the display entirely containing the rect or + * closest to the center of the rect on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplayBounds + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC SDL_DisplayID SDLCALL SDL_GetDisplayForRect(const SDL_Rect *rect); + +/** + * Get the display associated with a window. + * + * \param window the window to query. + * \returns the instance ID of the display containing the center of the window + * on success or 0 on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetDisplayBounds + * \sa SDL_GetDisplays + */ +extern SDL_DECLSPEC SDL_DisplayID SDLCALL SDL_GetDisplayForWindow(SDL_Window *window); + +/** + * Get the pixel density of a window. + * + * This is a ratio of pixel size to window size. For example, if the window is + * 1920x1080 and it has a high density back buffer of 3840x2160 pixels, it + * would have a pixel density of 2.0. + * + * \param window the window to query. + * \returns the pixel density or 0.0f on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowDisplayScale + */ +extern SDL_DECLSPEC float SDLCALL SDL_GetWindowPixelDensity(SDL_Window *window); + +/** + * Get the content display scale relative to a window's pixel size. + * + * This is a combination of the window pixel density and the display content + * scale, and is the expected scale for displaying content in this window. For + * example, if a 3840x2160 window had a display scale of 2.0, the user expects + * the content to take twice as many pixels and be the same physical size as + * if it were being displayed in a 1920x1080 window with a display scale of + * 1.0. + * + * Conceptually this value corresponds to the scale display setting, and is + * updated when that setting is changed, or the window moves to a display with + * a different scale setting. + * + * \param window the window to query. + * \returns the display scale, or 0.0f on failure; call SDL_GetError() for + * more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC float SDLCALL SDL_GetWindowDisplayScale(SDL_Window *window); + +/** + * Set the display mode to use when a window is visible and fullscreen. + * + * This only affects the display mode used when the window is fullscreen. To + * change the window size when the window is not fullscreen, use + * SDL_SetWindowSize(). + * + * If the window is currently in the fullscreen state, this request is + * asynchronous on some windowing systems and the new mode dimensions may not + * be applied immediately upon the return of this function. If an immediate + * change is required, call SDL_SyncWindow() to block until the changes have + * taken effect. + * + * When the new mode takes effect, an SDL_EVENT_WINDOW_RESIZED and/or an + * SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED event will be emitted with the new mode + * dimensions. + * + * \param window the window to affect. + * \param mode a pointer to the display mode to use, which can be NULL for + * borderless fullscreen desktop mode, or one of the fullscreen + * modes returned by SDL_GetFullscreenDisplayModes() to set an + * exclusive fullscreen mode. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowFullscreenMode + * \sa SDL_SetWindowFullscreen + * \sa SDL_SyncWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowFullscreenMode(SDL_Window *window, const SDL_DisplayMode *mode); + +/** + * Query the display mode to use when a window is visible at fullscreen. + * + * \param window the window to query. + * \returns a pointer to the exclusive fullscreen mode to use or NULL for + * borderless fullscreen desktop mode. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowFullscreenMode + * \sa SDL_SetWindowFullscreen + */ +extern SDL_DECLSPEC const SDL_DisplayMode * SDLCALL SDL_GetWindowFullscreenMode(SDL_Window *window); + +/** + * Get the raw ICC profile data for the screen the window is currently on. + * + * \param window the window to query. + * \param size the size of the ICC profile. + * \returns the raw ICC profile data on success or NULL on failure; call + * SDL_GetError() for more information. This should be freed with + * SDL_free() when it is no longer needed. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void * SDLCALL SDL_GetWindowICCProfile(SDL_Window *window, size_t *size); + +/** + * Get the pixel format associated with the window. + * + * \param window the window to query. + * \returns the pixel format of the window on success or + * SDL_PIXELFORMAT_UNKNOWN on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PixelFormat SDLCALL SDL_GetWindowPixelFormat(SDL_Window *window); + +/** + * Get a list of valid windows. + * + * \param count a pointer filled in with the number of windows returned, may + * be NULL. + * \returns a NULL terminated array of SDL_Window pointers or NULL on failure; + * call SDL_GetError() for more information. This is a single + * allocation that should be freed with SDL_free() when it is no + * longer needed. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Window ** SDLCALL SDL_GetWindows(int *count); + +/** + * Create a window with the specified dimensions and flags. + * + * The window size is a request and may be different than expected based on + * the desktop layout and window manager policies. Your application should be + * prepared to handle a window of any size. + * + * `flags` may be any of the following OR'd together: + * + * - `SDL_WINDOW_FULLSCREEN`: fullscreen window at desktop resolution + * - `SDL_WINDOW_OPENGL`: window usable with an OpenGL context + * - `SDL_WINDOW_OCCLUDED`: window partially or completely obscured by another + * window + * - `SDL_WINDOW_HIDDEN`: window is not visible + * - `SDL_WINDOW_BORDERLESS`: no window decoration + * - `SDL_WINDOW_RESIZABLE`: window can be resized + * - `SDL_WINDOW_MINIMIZED`: window is minimized + * - `SDL_WINDOW_MAXIMIZED`: window is maximized + * - `SDL_WINDOW_MOUSE_GRABBED`: window has grabbed mouse focus + * - `SDL_WINDOW_INPUT_FOCUS`: window has input focus + * - `SDL_WINDOW_MOUSE_FOCUS`: window has mouse focus + * - `SDL_WINDOW_EXTERNAL`: window not created by SDL + * - `SDL_WINDOW_MODAL`: window is modal + * - `SDL_WINDOW_HIGH_PIXEL_DENSITY`: window uses high pixel density back + * buffer if possible + * - `SDL_WINDOW_MOUSE_CAPTURE`: window has mouse captured (unrelated to + * MOUSE_GRABBED) + * - `SDL_WINDOW_ALWAYS_ON_TOP`: window should always be above others + * - `SDL_WINDOW_UTILITY`: window should be treated as a utility window, not + * showing in the task bar and window list + * - `SDL_WINDOW_TOOLTIP`: window should be treated as a tooltip and does not + * get mouse or keyboard focus, requires a parent window + * - `SDL_WINDOW_POPUP_MENU`: window should be treated as a popup menu, + * requires a parent window + * - `SDL_WINDOW_KEYBOARD_GRABBED`: window has grabbed keyboard input + * - `SDL_WINDOW_VULKAN`: window usable with a Vulkan instance + * - `SDL_WINDOW_METAL`: window usable with a Metal instance + * - `SDL_WINDOW_TRANSPARENT`: window with transparent buffer + * - `SDL_WINDOW_NOT_FOCUSABLE`: window should not be focusable + * + * The SDL_Window is implicitly shown if SDL_WINDOW_HIDDEN is not set. + * + * On Apple's macOS, you **must** set the NSHighResolutionCapable Info.plist + * property to YES, otherwise you will not receive a High-DPI OpenGL canvas. + * + * The window pixel size may differ from its window coordinate size if the + * window is on a high pixel density display. Use SDL_GetWindowSize() to query + * the client area's size in window coordinates, and + * SDL_GetWindowSizeInPixels() or SDL_GetRenderOutputSize() to query the + * drawable size in pixels. Note that the drawable size can vary after the + * window is created and should be queried again if you get an + * SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED event. + * + * If the window is created with any of the SDL_WINDOW_OPENGL or + * SDL_WINDOW_VULKAN flags, then the corresponding LoadLibrary function + * (SDL_GL_LoadLibrary or SDL_Vulkan_LoadLibrary) is called and the + * corresponding UnloadLibrary function is called by SDL_DestroyWindow(). + * + * If SDL_WINDOW_VULKAN is specified and there isn't a working Vulkan driver, + * SDL_CreateWindow() will fail, because SDL_Vulkan_LoadLibrary() will fail. + * + * If SDL_WINDOW_METAL is specified on an OS that does not support Metal, + * SDL_CreateWindow() will fail. + * + * If you intend to use this window with an SDL_Renderer, you should use + * SDL_CreateWindowAndRenderer() instead of this function, to avoid window + * flicker. + * + * On non-Apple devices, SDL requires you to either not link to the Vulkan + * loader or link to a dynamic library version. This limitation may be removed + * in a future version of SDL. + * + * \param title the title of the window, in UTF-8 encoding. + * \param w the width of the window. + * \param h the height of the window. + * \param flags 0, or one or more SDL_WindowFlags OR'd together. + * \returns the window that was created or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateWindowAndRenderer + * \sa SDL_CreatePopupWindow + * \sa SDL_CreateWindowWithProperties + * \sa SDL_DestroyWindow + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_CreateWindow(const char *title, int w, int h, SDL_WindowFlags flags); + +/** + * Create a child popup window of the specified parent window. + * + * The window size is a request and may be different than expected based on + * the desktop layout and window manager policies. Your application should be + * prepared to handle a window of any size. + * + * The flags parameter **must** contain at least one of the following: + * + * - `SDL_WINDOW_TOOLTIP`: The popup window is a tooltip and will not pass any + * input events. + * - `SDL_WINDOW_POPUP_MENU`: The popup window is a popup menu. The topmost + * popup menu will implicitly gain the keyboard focus. + * + * The following flags are not relevant to popup window creation and will be + * ignored: + * + * - `SDL_WINDOW_MINIMIZED` + * - `SDL_WINDOW_MAXIMIZED` + * - `SDL_WINDOW_FULLSCREEN` + * - `SDL_WINDOW_BORDERLESS` + * + * The following flags are incompatible with popup window creation and will + * cause it to fail: + * + * - `SDL_WINDOW_UTILITY` + * - `SDL_WINDOW_MODAL` + * + * The parent parameter **must** be non-null and a valid window. The parent of + * a popup window can be either a regular, toplevel window, or another popup + * window. + * + * Popup windows cannot be minimized, maximized, made fullscreen, raised, + * flash, be made a modal window, be the parent of a toplevel window, or grab + * the mouse and/or keyboard. Attempts to do so will fail. + * + * Popup windows implicitly do not have a border/decorations and do not appear + * on the taskbar/dock or in lists of windows such as alt-tab menus. + * + * If a parent window is hidden or destroyed, any child popup windows will be + * recursively hidden or destroyed as well. Child popup windows not explicitly + * hidden will be restored when the parent is shown. + * + * \param parent the parent of the window, must not be NULL. + * \param offset_x the x position of the popup window relative to the origin + * of the parent. + * \param offset_y the y position of the popup window relative to the origin + * of the parent window. + * \param w the width of the window. + * \param h the height of the window. + * \param flags SDL_WINDOW_TOOLTIP or SDL_WINDOW_POPUP_MENU, and zero or more + * additional SDL_WindowFlags OR'd together. + * \returns the window that was created or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateWindow + * \sa SDL_CreateWindowWithProperties + * \sa SDL_DestroyWindow + * \sa SDL_GetWindowParent + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_CreatePopupWindow(SDL_Window *parent, int offset_x, int offset_y, int w, int h, SDL_WindowFlags flags); + +/** + * Create a window with the specified properties. + * + * The window size is a request and may be different than expected based on + * the desktop layout and window manager policies. Your application should be + * prepared to handle a window of any size. + * + * These are the supported properties: + * + * - `SDL_PROP_WINDOW_CREATE_ALWAYS_ON_TOP_BOOLEAN`: true if the window should + * be always on top + * - `SDL_PROP_WINDOW_CREATE_BORDERLESS_BOOLEAN`: true if the window has no + * window decoration + * - `SDL_PROP_WINDOW_CREATE_EXTERNAL_GRAPHICS_CONTEXT_BOOLEAN`: true if the + * window will be used with an externally managed graphics context. + * - `SDL_PROP_WINDOW_CREATE_FOCUSABLE_BOOLEAN`: true if the window should + * accept keyboard input (defaults true) + * - `SDL_PROP_WINDOW_CREATE_FULLSCREEN_BOOLEAN`: true if the window should + * start in fullscreen mode at desktop resolution + * - `SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER`: the height of the window + * - `SDL_PROP_WINDOW_CREATE_HIDDEN_BOOLEAN`: true if the window should start + * hidden + * - `SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN`: true if the window + * uses a high pixel density buffer if possible + * - `SDL_PROP_WINDOW_CREATE_MAXIMIZED_BOOLEAN`: true if the window should + * start maximized + * - `SDL_PROP_WINDOW_CREATE_MENU_BOOLEAN`: true if the window is a popup menu + * - `SDL_PROP_WINDOW_CREATE_METAL_BOOLEAN`: true if the window will be used + * with Metal rendering + * - `SDL_PROP_WINDOW_CREATE_MINIMIZED_BOOLEAN`: true if the window should + * start minimized + * - `SDL_PROP_WINDOW_CREATE_MODAL_BOOLEAN`: true if the window is modal to + * its parent + * - `SDL_PROP_WINDOW_CREATE_MOUSE_GRABBED_BOOLEAN`: true if the window starts + * with grabbed mouse focus + * - `SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN`: true if the window will be used + * with OpenGL rendering + * - `SDL_PROP_WINDOW_CREATE_PARENT_POINTER`: an SDL_Window that will be the + * parent of this window, required for windows with the "tooltip", "menu", + * and "modal" properties + * - `SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN`: true if the window should be + * resizable + * - `SDL_PROP_WINDOW_CREATE_TITLE_STRING`: the title of the window, in UTF-8 + * encoding + * - `SDL_PROP_WINDOW_CREATE_TRANSPARENT_BOOLEAN`: true if the window show + * transparent in the areas with alpha of 0 + * - `SDL_PROP_WINDOW_CREATE_TOOLTIP_BOOLEAN`: true if the window is a tooltip + * - `SDL_PROP_WINDOW_CREATE_UTILITY_BOOLEAN`: true if the window is a utility + * window, not showing in the task bar and window list + * - `SDL_PROP_WINDOW_CREATE_VULKAN_BOOLEAN`: true if the window will be used + * with Vulkan rendering + * - `SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER`: the width of the window + * - `SDL_PROP_WINDOW_CREATE_X_NUMBER`: the x position of the window, or + * `SDL_WINDOWPOS_CENTERED`, defaults to `SDL_WINDOWPOS_UNDEFINED`. This is + * relative to the parent for windows with the "tooltip" or "menu" property + * set. + * - `SDL_PROP_WINDOW_CREATE_Y_NUMBER`: the y position of the window, or + * `SDL_WINDOWPOS_CENTERED`, defaults to `SDL_WINDOWPOS_UNDEFINED`. This is + * relative to the parent for windows with the "tooltip" or "menu" property + * set. + * + * These are additional supported properties on macOS: + * + * - `SDL_PROP_WINDOW_CREATE_COCOA_WINDOW_POINTER`: the + * `(__unsafe_unretained)` NSWindow associated with the window, if you want + * to wrap an existing window. + * - `SDL_PROP_WINDOW_CREATE_COCOA_VIEW_POINTER`: the `(__unsafe_unretained)` + * NSView associated with the window, defaults to `[window contentView]` + * + * These are additional supported properties on Wayland: + * + * - `SDL_PROP_WINDOW_CREATE_WAYLAND_SURFACE_ROLE_CUSTOM_BOOLEAN` - true if + * the application wants to use the Wayland surface for a custom role and + * does not want it attached to an XDG toplevel window. See + * [README/wayland](README/wayland) for more information on using custom + * surfaces. + * - `SDL_PROP_WINDOW_CREATE_WAYLAND_CREATE_EGL_WINDOW_BOOLEAN` - true if the + * application wants an associated `wl_egl_window` object to be created and + * attached to the window, even if the window does not have the OpenGL + * property or `SDL_WINDOW_OPENGL` flag set. + * - `SDL_PROP_WINDOW_CREATE_WAYLAND_WL_SURFACE_POINTER` - the wl_surface + * associated with the window, if you want to wrap an existing window. See + * [README/wayland](README/wayland) for more information. + * + * These are additional supported properties on Windows: + * + * - `SDL_PROP_WINDOW_CREATE_WIN32_HWND_POINTER`: the HWND associated with the + * window, if you want to wrap an existing window. + * - `SDL_PROP_WINDOW_CREATE_WIN32_PIXEL_FORMAT_HWND_POINTER`: optional, + * another window to share pixel format with, useful for OpenGL windows + * + * These are additional supported properties with X11: + * + * - `SDL_PROP_WINDOW_CREATE_X11_WINDOW_NUMBER`: the X11 Window associated + * with the window, if you want to wrap an existing window. + * + * The window is implicitly shown if the "hidden" property is not set. + * + * Windows with the "tooltip" and "menu" properties are popup windows and have + * the behaviors and guidelines outlined in SDL_CreatePopupWindow(). + * + * If this window is being created to be used with an SDL_Renderer, you should + * not add a graphics API specific property + * (`SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN`, etc), as SDL will handle that + * internally when it chooses a renderer. However, SDL might need to recreate + * your window at that point, which may cause the window to appear briefly, + * and then flicker as it is recreated. The correct approach to this is to + * create the window with the `SDL_PROP_WINDOW_CREATE_HIDDEN_BOOLEAN` property + * set to true, then create the renderer, then show the window with + * SDL_ShowWindow(). + * + * \param props the properties to use. + * \returns the window that was created or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateProperties + * \sa SDL_CreateWindow + * \sa SDL_DestroyWindow + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_CreateWindowWithProperties(SDL_PropertiesID props); + +#define SDL_PROP_WINDOW_CREATE_ALWAYS_ON_TOP_BOOLEAN "SDL.window.create.always_on_top" +#define SDL_PROP_WINDOW_CREATE_BORDERLESS_BOOLEAN "SDL.window.create.borderless" +#define SDL_PROP_WINDOW_CREATE_FOCUSABLE_BOOLEAN "SDL.window.create.focusable" +#define SDL_PROP_WINDOW_CREATE_EXTERNAL_GRAPHICS_CONTEXT_BOOLEAN "SDL.window.create.external_graphics_context" +#define SDL_PROP_WINDOW_CREATE_FLAGS_NUMBER "SDL.window.create.flags" +#define SDL_PROP_WINDOW_CREATE_FULLSCREEN_BOOLEAN "SDL.window.create.fullscreen" +#define SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER "SDL.window.create.height" +#define SDL_PROP_WINDOW_CREATE_HIDDEN_BOOLEAN "SDL.window.create.hidden" +#define SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN "SDL.window.create.high_pixel_density" +#define SDL_PROP_WINDOW_CREATE_MAXIMIZED_BOOLEAN "SDL.window.create.maximized" +#define SDL_PROP_WINDOW_CREATE_MENU_BOOLEAN "SDL.window.create.menu" +#define SDL_PROP_WINDOW_CREATE_METAL_BOOLEAN "SDL.window.create.metal" +#define SDL_PROP_WINDOW_CREATE_MINIMIZED_BOOLEAN "SDL.window.create.minimized" +#define SDL_PROP_WINDOW_CREATE_MODAL_BOOLEAN "SDL.window.create.modal" +#define SDL_PROP_WINDOW_CREATE_MOUSE_GRABBED_BOOLEAN "SDL.window.create.mouse_grabbed" +#define SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN "SDL.window.create.opengl" +#define SDL_PROP_WINDOW_CREATE_PARENT_POINTER "SDL.window.create.parent" +#define SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN "SDL.window.create.resizable" +#define SDL_PROP_WINDOW_CREATE_TITLE_STRING "SDL.window.create.title" +#define SDL_PROP_WINDOW_CREATE_TRANSPARENT_BOOLEAN "SDL.window.create.transparent" +#define SDL_PROP_WINDOW_CREATE_TOOLTIP_BOOLEAN "SDL.window.create.tooltip" +#define SDL_PROP_WINDOW_CREATE_UTILITY_BOOLEAN "SDL.window.create.utility" +#define SDL_PROP_WINDOW_CREATE_VULKAN_BOOLEAN "SDL.window.create.vulkan" +#define SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER "SDL.window.create.width" +#define SDL_PROP_WINDOW_CREATE_X_NUMBER "SDL.window.create.x" +#define SDL_PROP_WINDOW_CREATE_Y_NUMBER "SDL.window.create.y" +#define SDL_PROP_WINDOW_CREATE_COCOA_WINDOW_POINTER "SDL.window.create.cocoa.window" +#define SDL_PROP_WINDOW_CREATE_COCOA_VIEW_POINTER "SDL.window.create.cocoa.view" +#define SDL_PROP_WINDOW_CREATE_WAYLAND_SURFACE_ROLE_CUSTOM_BOOLEAN "SDL.window.create.wayland.surface_role_custom" +#define SDL_PROP_WINDOW_CREATE_WAYLAND_CREATE_EGL_WINDOW_BOOLEAN "SDL.window.create.wayland.create_egl_window" +#define SDL_PROP_WINDOW_CREATE_WAYLAND_WL_SURFACE_POINTER "SDL.window.create.wayland.wl_surface" +#define SDL_PROP_WINDOW_CREATE_WIN32_HWND_POINTER "SDL.window.create.win32.hwnd" +#define SDL_PROP_WINDOW_CREATE_WIN32_PIXEL_FORMAT_HWND_POINTER "SDL.window.create.win32.pixel_format_hwnd" +#define SDL_PROP_WINDOW_CREATE_X11_WINDOW_NUMBER "SDL.window.create.x11.window" + +/** + * Get the numeric ID of a window. + * + * The numeric ID is what SDL_WindowEvent references, and is necessary to map + * these events to specific SDL_Window objects. + * + * \param window the window to query. + * \returns the ID of the window on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowFromID + */ +extern SDL_DECLSPEC SDL_WindowID SDLCALL SDL_GetWindowID(SDL_Window *window); + +/** + * Get a window from a stored ID. + * + * The numeric ID is what SDL_WindowEvent references, and is necessary to map + * these events to specific SDL_Window objects. + * + * \param id the ID of the window. + * \returns the window associated with `id` or NULL if it doesn't exist; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowID + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GetWindowFromID(SDL_WindowID id); + +/** + * Get parent of a window. + * + * \param window the window to query. + * \returns the parent of the window on success or NULL if the window has no + * parent. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreatePopupWindow + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GetWindowParent(SDL_Window *window); + +/** + * Get the properties associated with a window. + * + * The following read-only properties are provided by SDL: + * + * - `SDL_PROP_WINDOW_SHAPE_POINTER`: the surface associated with a shaped + * window + * - `SDL_PROP_WINDOW_HDR_ENABLED_BOOLEAN`: true if the window has HDR + * headroom above the SDR white point. This property can change dynamically + * when SDL_EVENT_WINDOW_HDR_STATE_CHANGED is sent. + * - `SDL_PROP_WINDOW_SDR_WHITE_LEVEL_FLOAT`: the value of SDR white in the + * SDL_COLORSPACE_SRGB_LINEAR colorspace. On Windows this corresponds to the + * SDR white level in scRGB colorspace, and on Apple platforms this is + * always 1.0 for EDR content. This property can change dynamically when + * SDL_EVENT_WINDOW_HDR_STATE_CHANGED is sent. + * - `SDL_PROP_WINDOW_HDR_HEADROOM_FLOAT`: the additional high dynamic range + * that can be displayed, in terms of the SDR white point. When HDR is not + * enabled, this will be 1.0. This property can change dynamically when + * SDL_EVENT_WINDOW_HDR_STATE_CHANGED is sent. + * + * On Android: + * + * - `SDL_PROP_WINDOW_ANDROID_WINDOW_POINTER`: the ANativeWindow associated + * with the window + * - `SDL_PROP_WINDOW_ANDROID_SURFACE_POINTER`: the EGLSurface associated with + * the window + * + * On iOS: + * + * - `SDL_PROP_WINDOW_UIKIT_WINDOW_POINTER`: the `(__unsafe_unretained)` + * UIWindow associated with the window + * - `SDL_PROP_WINDOW_UIKIT_METAL_VIEW_TAG_NUMBER`: the NSInteger tag + * associated with metal views on the window + * - `SDL_PROP_WINDOW_UIKIT_OPENGL_FRAMEBUFFER_NUMBER`: the OpenGL view's + * framebuffer object. It must be bound when rendering to the screen using + * OpenGL. + * - `SDL_PROP_WINDOW_UIKIT_OPENGL_RENDERBUFFER_NUMBER`: the OpenGL view's + * renderbuffer object. It must be bound when SDL_GL_SwapWindow is called. + * - `SDL_PROP_WINDOW_UIKIT_OPENGL_RESOLVE_FRAMEBUFFER_NUMBER`: the OpenGL + * view's resolve framebuffer, when MSAA is used. + * + * On KMS/DRM: + * + * - `SDL_PROP_WINDOW_KMSDRM_DEVICE_INDEX_NUMBER`: the device index associated + * with the window (e.g. the X in /dev/dri/cardX) + * - `SDL_PROP_WINDOW_KMSDRM_DRM_FD_NUMBER`: the DRM FD associated with the + * window + * - `SDL_PROP_WINDOW_KMSDRM_GBM_DEVICE_POINTER`: the GBM device associated + * with the window + * + * On macOS: + * + * - `SDL_PROP_WINDOW_COCOA_WINDOW_POINTER`: the `(__unsafe_unretained)` + * NSWindow associated with the window + * - `SDL_PROP_WINDOW_COCOA_METAL_VIEW_TAG_NUMBER`: the NSInteger tag + * assocated with metal views on the window + * + * On OpenVR: + * + * - `SDL_PROP_WINDOW_OPENVR_OVERLAY_ID`: the OpenVR Overlay Handle ID for the + * associated overlay window. + * + * On Vivante: + * + * - `SDL_PROP_WINDOW_VIVANTE_DISPLAY_POINTER`: the EGLNativeDisplayType + * associated with the window + * - `SDL_PROP_WINDOW_VIVANTE_WINDOW_POINTER`: the EGLNativeWindowType + * associated with the window + * - `SDL_PROP_WINDOW_VIVANTE_SURFACE_POINTER`: the EGLSurface associated with + * the window + * + * On Windows: + * + * - `SDL_PROP_WINDOW_WIN32_HWND_POINTER`: the HWND associated with the window + * - `SDL_PROP_WINDOW_WIN32_HDC_POINTER`: the HDC associated with the window + * - `SDL_PROP_WINDOW_WIN32_INSTANCE_POINTER`: the HINSTANCE associated with + * the window + * + * On Wayland: + * + * Note: The `xdg_*` window objects do not internally persist across window + * show/hide calls. They will be null if the window is hidden and must be + * queried each time it is shown. + * + * - `SDL_PROP_WINDOW_WAYLAND_DISPLAY_POINTER`: the wl_display associated with + * the window + * - `SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER`: the wl_surface associated with + * the window + * - `SDL_PROP_WINDOW_WAYLAND_VIEWPORT_POINTER`: the wp_viewport associated + * with the window + * - `SDL_PROP_WINDOW_WAYLAND_EGL_WINDOW_POINTER`: the wl_egl_window + * associated with the window + * - `SDL_PROP_WINDOW_WAYLAND_XDG_SURFACE_POINTER`: the xdg_surface associated + * with the window + * - `SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_POINTER`: the xdg_toplevel role + * associated with the window + * - 'SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_EXPORT_HANDLE_STRING': the export + * handle associated with the window + * - `SDL_PROP_WINDOW_WAYLAND_XDG_POPUP_POINTER`: the xdg_popup role + * associated with the window + * - `SDL_PROP_WINDOW_WAYLAND_XDG_POSITIONER_POINTER`: the xdg_positioner + * associated with the window, in popup mode + * + * On X11: + * + * - `SDL_PROP_WINDOW_X11_DISPLAY_POINTER`: the X11 Display associated with + * the window + * - `SDL_PROP_WINDOW_X11_SCREEN_NUMBER`: the screen number associated with + * the window + * - `SDL_PROP_WINDOW_X11_WINDOW_NUMBER`: the X11 Window associated with the + * window + * + * \param window the window to query. + * \returns a valid property ID on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetWindowProperties(SDL_Window *window); + +#define SDL_PROP_WINDOW_SHAPE_POINTER "SDL.window.shape" +#define SDL_PROP_WINDOW_HDR_ENABLED_BOOLEAN "SDL.window.HDR_enabled" +#define SDL_PROP_WINDOW_SDR_WHITE_LEVEL_FLOAT "SDL.window.SDR_white_level" +#define SDL_PROP_WINDOW_HDR_HEADROOM_FLOAT "SDL.window.HDR_headroom" +#define SDL_PROP_WINDOW_ANDROID_WINDOW_POINTER "SDL.window.android.window" +#define SDL_PROP_WINDOW_ANDROID_SURFACE_POINTER "SDL.window.android.surface" +#define SDL_PROP_WINDOW_UIKIT_WINDOW_POINTER "SDL.window.uikit.window" +#define SDL_PROP_WINDOW_UIKIT_METAL_VIEW_TAG_NUMBER "SDL.window.uikit.metal_view_tag" +#define SDL_PROP_WINDOW_UIKIT_OPENGL_FRAMEBUFFER_NUMBER "SDL.window.uikit.opengl.framebuffer" +#define SDL_PROP_WINDOW_UIKIT_OPENGL_RENDERBUFFER_NUMBER "SDL.window.uikit.opengl.renderbuffer" +#define SDL_PROP_WINDOW_UIKIT_OPENGL_RESOLVE_FRAMEBUFFER_NUMBER "SDL.window.uikit.opengl.resolve_framebuffer" +#define SDL_PROP_WINDOW_KMSDRM_DEVICE_INDEX_NUMBER "SDL.window.kmsdrm.dev_index" +#define SDL_PROP_WINDOW_KMSDRM_DRM_FD_NUMBER "SDL.window.kmsdrm.drm_fd" +#define SDL_PROP_WINDOW_KMSDRM_GBM_DEVICE_POINTER "SDL.window.kmsdrm.gbm_dev" +#define SDL_PROP_WINDOW_COCOA_WINDOW_POINTER "SDL.window.cocoa.window" +#define SDL_PROP_WINDOW_COCOA_METAL_VIEW_TAG_NUMBER "SDL.window.cocoa.metal_view_tag" +#define SDL_PROP_WINDOW_OPENVR_OVERLAY_ID "SDL.window.openvr.overlay_id" +#define SDL_PROP_WINDOW_VIVANTE_DISPLAY_POINTER "SDL.window.vivante.display" +#define SDL_PROP_WINDOW_VIVANTE_WINDOW_POINTER "SDL.window.vivante.window" +#define SDL_PROP_WINDOW_VIVANTE_SURFACE_POINTER "SDL.window.vivante.surface" +#define SDL_PROP_WINDOW_WIN32_HWND_POINTER "SDL.window.win32.hwnd" +#define SDL_PROP_WINDOW_WIN32_HDC_POINTER "SDL.window.win32.hdc" +#define SDL_PROP_WINDOW_WIN32_INSTANCE_POINTER "SDL.window.win32.instance" +#define SDL_PROP_WINDOW_WAYLAND_DISPLAY_POINTER "SDL.window.wayland.display" +#define SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER "SDL.window.wayland.surface" +#define SDL_PROP_WINDOW_WAYLAND_VIEWPORT_POINTER "SDL.window.wayland.viewport" +#define SDL_PROP_WINDOW_WAYLAND_EGL_WINDOW_POINTER "SDL.window.wayland.egl_window" +#define SDL_PROP_WINDOW_WAYLAND_XDG_SURFACE_POINTER "SDL.window.wayland.xdg_surface" +#define SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_POINTER "SDL.window.wayland.xdg_toplevel" +#define SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_EXPORT_HANDLE_STRING "SDL.window.wayland.xdg_toplevel_export_handle" +#define SDL_PROP_WINDOW_WAYLAND_XDG_POPUP_POINTER "SDL.window.wayland.xdg_popup" +#define SDL_PROP_WINDOW_WAYLAND_XDG_POSITIONER_POINTER "SDL.window.wayland.xdg_positioner" +#define SDL_PROP_WINDOW_X11_DISPLAY_POINTER "SDL.window.x11.display" +#define SDL_PROP_WINDOW_X11_SCREEN_NUMBER "SDL.window.x11.screen" +#define SDL_PROP_WINDOW_X11_WINDOW_NUMBER "SDL.window.x11.window" + +/** + * Get the window flags. + * + * \param window the window to query. + * \returns a mask of the SDL_WindowFlags associated with `window`. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateWindow + * \sa SDL_HideWindow + * \sa SDL_MaximizeWindow + * \sa SDL_MinimizeWindow + * \sa SDL_SetWindowFullscreen + * \sa SDL_SetWindowMouseGrab + * \sa SDL_ShowWindow + */ +extern SDL_DECLSPEC SDL_WindowFlags SDLCALL SDL_GetWindowFlags(SDL_Window *window); + +/** + * Set the title of a window. + * + * This string is expected to be in UTF-8 encoding. + * + * \param window the window to change. + * \param title the desired window title in UTF-8 format. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowTitle + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowTitle(SDL_Window *window, const char *title); + +/** + * Get the title of a window. + * + * \param window the window to query. + * \returns the title of the window in UTF-8 format or "" if there is no + * title. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowTitle + */ +extern SDL_DECLSPEC const char * SDLCALL SDL_GetWindowTitle(SDL_Window *window); + +/** + * Set the icon for a window. + * + * If this function is passed a surface with alternate representations, the + * surface will be interpreted as the content to be used for 100% display + * scale, and the alternate representations will be used for high DPI + * situations. For example, if the original surface is 32x32, then on a 2x + * macOS display or 200% display scale on Windows, a 64x64 version of the + * image will be used, if available. If a matching version of the image isn't + * available, the closest larger size image will be downscaled to the + * appropriate size and be used instead, if available. Otherwise, the closest + * smaller image will be upscaled and be used instead. + * + * \param window the window to change. + * \param icon an SDL_Surface structure containing the icon for the window. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowIcon(SDL_Window *window, SDL_Surface *icon); + +/** + * Request that the window's position be set. + * + * If the window is in an exclusive fullscreen or maximized state, this + * request has no effect. + * + * This can be used to reposition fullscreen-desktop windows onto a different + * display, however, as exclusive fullscreen windows are locked to a specific + * display, they can only be repositioned programmatically via + * SDL_SetWindowFullscreenMode(). + * + * On some windowing systems this request is asynchronous and the new + * coordinates may not have have been applied immediately upon the return of + * this function. If an immediate change is required, call SDL_SyncWindow() to + * block until the changes have taken effect. + * + * When the window position changes, an SDL_EVENT_WINDOW_MOVED event will be + * emitted with the window's new coordinates. Note that the new coordinates + * may not match the exact coordinates requested, as some windowing systems + * can restrict the position of the window in certain scenarios (e.g. + * constraining the position so the window is always within desktop bounds). + * Additionally, as this is just a request, it can be denied by the windowing + * system. + * + * \param window the window to reposition. + * \param x the x coordinate of the window, or `SDL_WINDOWPOS_CENTERED` or + * `SDL_WINDOWPOS_UNDEFINED`. + * \param y the y coordinate of the window, or `SDL_WINDOWPOS_CENTERED` or + * `SDL_WINDOWPOS_UNDEFINED`. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowPosition + * \sa SDL_SyncWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowPosition(SDL_Window *window, int x, int y); + +/** + * Get the position of a window. + * + * This is the current position of the window as last reported by the + * windowing system. + * + * If you do not need the value for one of the positions a NULL may be passed + * in the `x` or `y` parameter. + * + * \param window the window to query. + * \param x a pointer filled in with the x position of the window, may be + * NULL. + * \param y a pointer filled in with the y position of the window, may be + * NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowPosition + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowPosition(SDL_Window *window, int *x, int *y); + +/** + * Request that the size of a window's client area be set. + * + * If the window is in a fullscreen or maximized state, this request has no + * effect. + * + * To change the exclusive fullscreen mode of a window, use + * SDL_SetWindowFullscreenMode(). + * + * On some windowing systems, this request is asynchronous and the new window + * size may not have have been applied immediately upon the return of this + * function. If an immediate change is required, call SDL_SyncWindow() to + * block until the changes have taken effect. + * + * When the window size changes, an SDL_EVENT_WINDOW_RESIZED event will be + * emitted with the new window dimensions. Note that the new dimensions may + * not match the exact size requested, as some windowing systems can restrict + * the window size in certain scenarios (e.g. constraining the size of the + * content area to remain within the usable desktop bounds). Additionally, as + * this is just a request, it can be denied by the windowing system. + * + * \param window the window to change. + * \param w the width of the window, must be > 0. + * \param h the height of the window, must be > 0. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowSize + * \sa SDL_SetWindowFullscreenMode + * \sa SDL_SyncWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowSize(SDL_Window *window, int w, int h); + +/** + * Get the size of a window's client area. + * + * The window pixel size may differ from its window coordinate size if the + * window is on a high pixel density display. Use SDL_GetWindowSizeInPixels() + * or SDL_GetRenderOutputSize() to get the real client area size in pixels. + * + * \param window the window to query the width and height from. + * \param w a pointer filled in with the width of the window, may be NULL. + * \param h a pointer filled in with the height of the window, may be NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetRenderOutputSize + * \sa SDL_GetWindowSizeInPixels + * \sa SDL_SetWindowSize + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowSize(SDL_Window *window, int *w, int *h); + +/** + * Get the safe area for this window. + * + * Some devices have portions of the screen which are partially obscured or + * not interactive, possibly due to on-screen controls, curved edges, camera + * notches, TV overscan, etc. This function provides the area of the window + * which is safe to have interactable content. You should continue rendering + * into the rest of the window, but it should not contain visually important + * or interactible content. + * + * \param window the window to query. + * \param rect a pointer filled in with the client area that is safe for + * interactive content. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowSafeArea(SDL_Window *window, SDL_Rect *rect); + +/** + * Request that the aspect ratio of a window's client area be set. + * + * The aspect ratio is the ratio of width divided by height, e.g. 2560x1600 + * would be 1.6. Larger aspect ratios are wider and smaller aspect ratios are + * narrower. + * + * If, at the time of this request, the window in a fixed-size state, such as + * maximized or fullscreen, the request will be deferred until the window + * exits this state and becomes resizable again. + * + * On some windowing systems, this request is asynchronous and the new window + * aspect ratio may not have have been applied immediately upon the return of + * this function. If an immediate change is required, call SDL_SyncWindow() to + * block until the changes have taken effect. + * + * When the window size changes, an SDL_EVENT_WINDOW_RESIZED event will be + * emitted with the new window dimensions. Note that the new dimensions may + * not match the exact aspect ratio requested, as some windowing systems can + * restrict the window size in certain scenarios (e.g. constraining the size + * of the content area to remain within the usable desktop bounds). + * Additionally, as this is just a request, it can be denied by the windowing + * system. + * + * \param window the window to change. + * \param min_aspect the minimum aspect ratio of the window, or 0.0f for no + * limit. + * \param max_aspect the maximum aspect ratio of the window, or 0.0f for no + * limit. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowAspectRatio + * \sa SDL_SyncWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowAspectRatio(SDL_Window *window, float min_aspect, float max_aspect); + +/** + * Get the size of a window's client area. + * + * \param window the window to query the width and height from. + * \param min_aspect a pointer filled in with the minimum aspect ratio of the + * window, may be NULL. + * \param max_aspect a pointer filled in with the maximum aspect ratio of the + * window, may be NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowAspectRatio + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowAspectRatio(SDL_Window *window, float *min_aspect, float *max_aspect); + +/** + * Get the size of a window's borders (decorations) around the client area. + * + * Note: If this function fails (returns false), the size values will be + * initialized to 0, 0, 0, 0 (if a non-NULL pointer is provided), as if the + * window in question was borderless. + * + * Note: This function may fail on systems where the window has not yet been + * decorated by the display server (for example, immediately after calling + * SDL_CreateWindow). It is recommended that you wait at least until the + * window has been presented and composited, so that the window system has a + * chance to decorate the window and provide the border dimensions to SDL. + * + * This function also returns false if getting the information is not + * supported. + * + * \param window the window to query the size values of the border + * (decorations) from. + * \param top pointer to variable for storing the size of the top border; NULL + * is permitted. + * \param left pointer to variable for storing the size of the left border; + * NULL is permitted. + * \param bottom pointer to variable for storing the size of the bottom + * border; NULL is permitted. + * \param right pointer to variable for storing the size of the right border; + * NULL is permitted. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowSize + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowBordersSize(SDL_Window *window, int *top, int *left, int *bottom, int *right); + +/** + * Get the size of a window's client area, in pixels. + * + * \param window the window from which the drawable size should be queried. + * \param w a pointer to variable for storing the width in pixels, may be + * NULL. + * \param h a pointer to variable for storing the height in pixels, may be + * NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreateWindow + * \sa SDL_GetWindowSize + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowSizeInPixels(SDL_Window *window, int *w, int *h); + +/** + * Set the minimum size of a window's client area. + * + * \param window the window to change. + * \param min_w the minimum width of the window, or 0 for no limit. + * \param min_h the minimum height of the window, or 0 for no limit. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowMinimumSize + * \sa SDL_SetWindowMaximumSize + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowMinimumSize(SDL_Window *window, int min_w, int min_h); + +/** + * Get the minimum size of a window's client area. + * + * \param window the window to query. + * \param w a pointer filled in with the minimum width of the window, may be + * NULL. + * \param h a pointer filled in with the minimum height of the window, may be + * NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowMaximumSize + * \sa SDL_SetWindowMinimumSize + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowMinimumSize(SDL_Window *window, int *w, int *h); + +/** + * Set the maximum size of a window's client area. + * + * \param window the window to change. + * \param max_w the maximum width of the window, or 0 for no limit. + * \param max_h the maximum height of the window, or 0 for no limit. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowMaximumSize + * \sa SDL_SetWindowMinimumSize + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowMaximumSize(SDL_Window *window, int max_w, int max_h); + +/** + * Get the maximum size of a window's client area. + * + * \param window the window to query. + * \param w a pointer filled in with the maximum width of the window, may be + * NULL. + * \param h a pointer filled in with the maximum height of the window, may be + * NULL. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowMinimumSize + * \sa SDL_SetWindowMaximumSize + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowMaximumSize(SDL_Window *window, int *w, int *h); + +/** + * Set the border state of a window. + * + * This will add or remove the window's `SDL_WINDOW_BORDERLESS` flag and add + * or remove the border from the actual window. This is a no-op if the + * window's border already matches the requested state. + * + * You can't change the border state of a fullscreen window. + * + * \param window the window of which to change the border state. + * \param bordered false to remove border, true to add border. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowFlags + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowBordered(SDL_Window *window, bool bordered); + +/** + * Set the user-resizable state of a window. + * + * This will add or remove the window's `SDL_WINDOW_RESIZABLE` flag and + * allow/disallow user resizing of the window. This is a no-op if the window's + * resizable state already matches the requested state. + * + * You can't change the resizable state of a fullscreen window. + * + * \param window the window of which to change the resizable state. + * \param resizable true to allow resizing, false to disallow. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowFlags + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowResizable(SDL_Window *window, bool resizable); + +/** + * Set the window to always be above the others. + * + * This will add or remove the window's `SDL_WINDOW_ALWAYS_ON_TOP` flag. This + * will bring the window to the front and keep the window above the rest. + * + * \param window the window of which to change the always on top state. + * \param on_top true to set the window always on top, false to disable. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowFlags + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowAlwaysOnTop(SDL_Window *window, bool on_top); + +/** + * Show a window. + * + * \param window the window to show. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_HideWindow + * \sa SDL_RaiseWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ShowWindow(SDL_Window *window); + +/** + * Hide a window. + * + * \param window the window to hide. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_ShowWindow + * \sa SDL_WINDOW_HIDDEN + */ +extern SDL_DECLSPEC bool SDLCALL SDL_HideWindow(SDL_Window *window); + +/** + * Request that a window be raised above other windows and gain the input + * focus. + * + * The result of this request is subject to desktop window manager policy, + * particularly if raising the requested window would result in stealing focus + * from another application. If the window is successfully raised and gains + * input focus, an SDL_EVENT_WINDOW_FOCUS_GAINED event will be emitted, and + * the window will have the SDL_WINDOW_INPUT_FOCUS flag set. + * + * \param window the window to raise. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RaiseWindow(SDL_Window *window); + +/** + * Request that the window be made as large as possible. + * + * Non-resizable windows can't be maximized. The window must have the + * SDL_WINDOW_RESIZABLE flag set, or this will have no effect. + * + * On some windowing systems this request is asynchronous and the new window + * state may not have have been applied immediately upon the return of this + * function. If an immediate change is required, call SDL_SyncWindow() to + * block until the changes have taken effect. + * + * When the window state changes, an SDL_EVENT_WINDOW_MAXIMIZED event will be + * emitted. Note that, as this is just a request, the windowing system can + * deny the state change. + * + * When maximizing a window, whether the constraints set via + * SDL_SetWindowMaximumSize() are honored depends on the policy of the window + * manager. Win32 and macOS enforce the constraints when maximizing, while X11 + * and Wayland window managers may vary. + * + * \param window the window to maximize. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_MinimizeWindow + * \sa SDL_RestoreWindow + * \sa SDL_SyncWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_MaximizeWindow(SDL_Window *window); + +/** + * Request that the window be minimized to an iconic representation. + * + * If the window is in a fullscreen state, this request has no direct effect. + * It may alter the state the window is returned to when leaving fullscreen. + * + * On some windowing systems this request is asynchronous and the new window + * state may not have been applied immediately upon the return of this + * function. If an immediate change is required, call SDL_SyncWindow() to + * block until the changes have taken effect. + * + * When the window state changes, an SDL_EVENT_WINDOW_MINIMIZED event will be + * emitted. Note that, as this is just a request, the windowing system can + * deny the state change. + * + * \param window the window to minimize. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_MaximizeWindow + * \sa SDL_RestoreWindow + * \sa SDL_SyncWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_MinimizeWindow(SDL_Window *window); + +/** + * Request that the size and position of a minimized or maximized window be + * restored. + * + * If the window is in a fullscreen state, this request has no direct effect. + * It may alter the state the window is returned to when leaving fullscreen. + * + * On some windowing systems this request is asynchronous and the new window + * state may not have have been applied immediately upon the return of this + * function. If an immediate change is required, call SDL_SyncWindow() to + * block until the changes have taken effect. + * + * When the window state changes, an SDL_EVENT_WINDOW_RESTORED event will be + * emitted. Note that, as this is just a request, the windowing system can + * deny the state change. + * + * \param window the window to restore. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_MaximizeWindow + * \sa SDL_MinimizeWindow + * \sa SDL_SyncWindow + */ +extern SDL_DECLSPEC bool SDLCALL SDL_RestoreWindow(SDL_Window *window); + +/** + * Request that the window's fullscreen state be changed. + * + * By default a window in fullscreen state uses borderless fullscreen desktop + * mode, but a specific exclusive display mode can be set using + * SDL_SetWindowFullscreenMode(). + * + * On some windowing systems this request is asynchronous and the new + * fullscreen state may not have have been applied immediately upon the return + * of this function. If an immediate change is required, call SDL_SyncWindow() + * to block until the changes have taken effect. + * + * When the window state changes, an SDL_EVENT_WINDOW_ENTER_FULLSCREEN or + * SDL_EVENT_WINDOW_LEAVE_FULLSCREEN event will be emitted. Note that, as this + * is just a request, it can be denied by the windowing system. + * + * \param window the window to change. + * \param fullscreen true for fullscreen mode, false for windowed mode. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowFullscreenMode + * \sa SDL_SetWindowFullscreenMode + * \sa SDL_SyncWindow + * \sa SDL_WINDOW_FULLSCREEN + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowFullscreen(SDL_Window *window, bool fullscreen); + +/** + * Block until any pending window state is finalized. + * + * On asynchronous windowing systems, this acts as a synchronization barrier + * for pending window state. It will attempt to wait until any pending window + * state has been applied and is guaranteed to return within finite time. Note + * that for how long it can potentially block depends on the underlying window + * system, as window state changes may involve somewhat lengthy animations + * that must complete before the window is in its final requested state. + * + * On windowing systems where changes are immediate, this does nothing. + * + * \param window the window for which to wait for the pending state to be + * applied. + * \returns true on success or false if the operation timed out before the + * window was in the requested state. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowSize + * \sa SDL_SetWindowPosition + * \sa SDL_SetWindowFullscreen + * \sa SDL_MinimizeWindow + * \sa SDL_MaximizeWindow + * \sa SDL_RestoreWindow + * \sa SDL_HINT_VIDEO_SYNC_WINDOW_OPERATIONS + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SyncWindow(SDL_Window *window); + +/** + * Return whether the window has a surface associated with it. + * + * \param window the window to query. + * \returns true if there is a surface associated with the window, or false + * otherwise. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowSurface + */ +extern SDL_DECLSPEC bool SDLCALL SDL_WindowHasSurface(SDL_Window *window); + +/** + * Get the SDL surface associated with the window. + * + * A new surface will be created with the optimal format for the window, if + * necessary. This surface will be freed when the window is destroyed. Do not + * free this surface. + * + * This surface will be invalidated if the window is resized. After resizing a + * window this function must be called again to return a valid surface. + * + * You may not combine this with 3D or the rendering API on this window. + * + * This function is affected by `SDL_HINT_FRAMEBUFFER_ACCELERATION`. + * + * \param window the window to query. + * \returns the surface associated with the window, or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DestroyWindowSurface + * \sa SDL_WindowHasSurface + * \sa SDL_UpdateWindowSurface + * \sa SDL_UpdateWindowSurfaceRects + */ +extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_GetWindowSurface(SDL_Window *window); + +/** + * Toggle VSync for the window surface. + * + * When a window surface is created, vsync defaults to + * SDL_WINDOW_SURFACE_VSYNC_DISABLED. + * + * The `vsync` parameter can be 1 to synchronize present with every vertical + * refresh, 2 to synchronize present with every second vertical refresh, etc., + * SDL_WINDOW_SURFACE_VSYNC_ADAPTIVE for late swap tearing (adaptive vsync), + * or SDL_WINDOW_SURFACE_VSYNC_DISABLED to disable. Not every value is + * supported by every driver, so you should check the return value to see + * whether the requested setting is supported. + * + * \param window the window. + * \param vsync the vertical refresh sync interval. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowSurfaceVSync + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowSurfaceVSync(SDL_Window *window, int vsync); + +#define SDL_WINDOW_SURFACE_VSYNC_DISABLED 0 +#define SDL_WINDOW_SURFACE_VSYNC_ADAPTIVE (-1) + +/** + * Get VSync for the window surface. + * + * \param window the window to query. + * \param vsync an int filled with the current vertical refresh sync interval. + * See SDL_SetWindowSurfaceVSync() for the meaning of the value. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowSurfaceVSync + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowSurfaceVSync(SDL_Window *window, int *vsync); + +/** + * Copy the window surface to the screen. + * + * This is the function you use to reflect any changes to the surface on the + * screen. + * + * This function is equivalent to the SDL 1.2 API SDL_Flip(). + * + * \param window the window to update. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowSurface + * \sa SDL_UpdateWindowSurfaceRects + */ +extern SDL_DECLSPEC bool SDLCALL SDL_UpdateWindowSurface(SDL_Window *window); + +/** + * Copy areas of the window surface to the screen. + * + * This is the function you use to reflect changes to portions of the surface + * on the screen. + * + * This function is equivalent to the SDL 1.2 API SDL_UpdateRects(). + * + * Note that this function will update _at least_ the rectangles specified, + * but this is only intended as an optimization; in practice, this might + * update more of the screen (or all of the screen!), depending on what method + * SDL uses to send pixels to the system. + * + * \param window the window to update. + * \param rects an array of SDL_Rect structures representing areas of the + * surface to copy, in pixels. + * \param numrects the number of rectangles. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowSurface + * \sa SDL_UpdateWindowSurface + */ +extern SDL_DECLSPEC bool SDLCALL SDL_UpdateWindowSurfaceRects(SDL_Window *window, const SDL_Rect *rects, int numrects); + +/** + * Destroy the surface associated with the window. + * + * \param window the window to update. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowSurface + * \sa SDL_WindowHasSurface + */ +extern SDL_DECLSPEC bool SDLCALL SDL_DestroyWindowSurface(SDL_Window *window); + +/** + * Set a window's keyboard grab mode. + * + * Keyboard grab enables capture of system keyboard shortcuts like Alt+Tab or + * the Meta/Super key. Note that not all system keyboard shortcuts can be + * captured by applications (one example is Ctrl+Alt+Del on Windows). + * + * This is primarily intended for specialized applications such as VNC clients + * or VM frontends. Normal games should not use keyboard grab. + * + * When keyboard grab is enabled, SDL will continue to handle Alt+Tab when the + * window is full-screen to ensure the user is not trapped in your + * application. If you have a custom keyboard shortcut to exit fullscreen + * mode, you may suppress this behavior with + * `SDL_HINT_ALLOW_ALT_TAB_WHILE_GRABBED`. + * + * If the caller enables a grab while another window is currently grabbed, the + * other window loses its grab in favor of the caller's window. + * + * \param window the window for which the keyboard grab mode should be set. + * \param grabbed this is true to grab keyboard, and false to release. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowKeyboardGrab + * \sa SDL_SetWindowMouseGrab + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowKeyboardGrab(SDL_Window *window, bool grabbed); + +/** + * Set a window's mouse grab mode. + * + * Mouse grab confines the mouse cursor to the window. + * + * \param window the window for which the mouse grab mode should be set. + * \param grabbed this is true to grab mouse, and false to release. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowMouseRect + * \sa SDL_SetWindowMouseRect + * \sa SDL_SetWindowMouseGrab + * \sa SDL_SetWindowKeyboardGrab + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowMouseGrab(SDL_Window *window, bool grabbed); + +/** + * Get a window's keyboard grab mode. + * + * \param window the window to query. + * \returns true if keyboard is grabbed, and false otherwise. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowKeyboardGrab + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowKeyboardGrab(SDL_Window *window); + +/** + * Get a window's mouse grab mode. + * + * \param window the window to query. + * \returns true if mouse is grabbed, and false otherwise. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowMouseRect + * \sa SDL_SetWindowMouseRect + * \sa SDL_SetWindowMouseGrab + * \sa SDL_SetWindowKeyboardGrab + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowMouseGrab(SDL_Window *window); + +/** + * Get the window that currently has an input grab enabled. + * + * \returns the window if input is grabbed or NULL otherwise. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowMouseGrab + * \sa SDL_SetWindowKeyboardGrab + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GetGrabbedWindow(void); + +/** + * Confines the cursor to the specified area of a window. + * + * Note that this does NOT grab the cursor, it only defines the area a cursor + * is restricted to when the window has mouse focus. + * + * \param window the window that will be associated with the barrier. + * \param rect a rectangle area in window-relative coordinates. If NULL the + * barrier for the specified window will be destroyed. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowMouseRect + * \sa SDL_GetWindowMouseGrab + * \sa SDL_SetWindowMouseGrab + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowMouseRect(SDL_Window *window, const SDL_Rect *rect); + +/** + * Get the mouse confinement rectangle of a window. + * + * \param window the window to query. + * \returns a pointer to the mouse confinement rectangle of a window, or NULL + * if there isn't one. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowMouseRect + * \sa SDL_GetWindowMouseGrab + * \sa SDL_SetWindowMouseGrab + */ +extern SDL_DECLSPEC const SDL_Rect * SDLCALL SDL_GetWindowMouseRect(SDL_Window *window); + +/** + * Set the opacity for a window. + * + * The parameter `opacity` will be clamped internally between 0.0f + * (transparent) and 1.0f (opaque). + * + * This function also returns false if setting the opacity isn't supported. + * + * \param window the window which will be made transparent or opaque. + * \param opacity the opacity value (0.0f - transparent, 1.0f - opaque). + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GetWindowOpacity + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowOpacity(SDL_Window *window, float opacity); + +/** + * Get the opacity of a window. + * + * If transparency isn't supported on this platform, opacity will be returned + * as 1.0f without error. + * + * \param window the window to get the current opacity value from. + * \returns the opacity, (0.0f - transparent, 1.0f - opaque), or -1.0f on + * failure; call SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowOpacity + */ +extern SDL_DECLSPEC float SDLCALL SDL_GetWindowOpacity(SDL_Window *window); + +/** + * Set the window as a child of a parent window. + * + * If the window is already the child of an existing window, it will be + * reparented to the new owner. Setting the parent window to NULL unparents + * the window and removes child window status. + * + * If a parent window is hidden or destroyed, the operation will be + * recursively applied to child windows. Child windows hidden with the parent + * that did not have their hidden status explicitly set will be restored when + * the parent is shown. + * + * Attempting to set the parent of a window that is currently in the modal + * state will fail. Use SDL_SetWindowModal() to cancel the modal status before + * attempting to change the parent. + * + * Popup windows cannot change parents and attempts to do so will fail. + * + * Setting a parent window that is currently the sibling or descendent of the + * child window results in undefined behavior. + * + * \param window the window that should become the child of a parent. + * \param parent the new parent window for the child window. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowModal + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowParent(SDL_Window *window, SDL_Window *parent); + +/** + * Toggle the state of the window as modal. + * + * To enable modal status on a window, the window must currently be the child + * window of a parent, or toggling modal status on will fail. + * + * \param window the window on which to set the modal state. + * \param modal true to toggle modal status on, false to toggle it off. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_SetWindowParent + * \sa SDL_WINDOW_MODAL + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowModal(SDL_Window *window, bool modal); + +/** + * Set whether the window may have input focus. + * + * \param window the window to set focusable state. + * \param focusable true to allow input focus, false to not allow input focus. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowFocusable(SDL_Window *window, bool focusable); + + +/** + * Display the system-level window menu. + * + * This default window menu is provided by the system and on some platforms + * provides functionality for setting or changing privileged state on the + * window, such as moving it between workspaces or displays, or toggling the + * always-on-top property. + * + * On platforms or desktops where this is unsupported, this function does + * nothing. + * + * \param window the window for which the menu will be displayed. + * \param x the x coordinate of the menu, relative to the origin (top-left) of + * the client area. + * \param y the y coordinate of the menu, relative to the origin (top-left) of + * the client area. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ShowWindowSystemMenu(SDL_Window *window, int x, int y); + +/** + * Possible return values from the SDL_HitTest callback. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This enum is available since SDL 3.2.0. + * + * \sa SDL_HitTest + */ +typedef enum SDL_HitTestResult +{ + SDL_HITTEST_NORMAL, /**< Region is normal. No special properties. */ + SDL_HITTEST_DRAGGABLE, /**< Region can drag entire window. */ + SDL_HITTEST_RESIZE_TOPLEFT, /**< Region is the resizable top-left corner border. */ + SDL_HITTEST_RESIZE_TOP, /**< Region is the resizable top border. */ + SDL_HITTEST_RESIZE_TOPRIGHT, /**< Region is the resizable top-right corner border. */ + SDL_HITTEST_RESIZE_RIGHT, /**< Region is the resizable right border. */ + SDL_HITTEST_RESIZE_BOTTOMRIGHT, /**< Region is the resizable bottom-right corner border. */ + SDL_HITTEST_RESIZE_BOTTOM, /**< Region is the resizable bottom border. */ + SDL_HITTEST_RESIZE_BOTTOMLEFT, /**< Region is the resizable bottom-left corner border. */ + SDL_HITTEST_RESIZE_LEFT /**< Region is the resizable left border. */ +} SDL_HitTestResult; + +/** + * Callback used for hit-testing. + * + * \param win the SDL_Window where hit-testing was set on. + * \param area an SDL_Point which should be hit-tested. + * \param data what was passed as `callback_data` to SDL_SetWindowHitTest(). + * \returns an SDL_HitTestResult value. + * + * \sa SDL_SetWindowHitTest + */ +typedef SDL_HitTestResult (SDLCALL *SDL_HitTest)(SDL_Window *win, + const SDL_Point *area, + void *data); + +/** + * Provide a callback that decides if a window region has special properties. + * + * Normally windows are dragged and resized by decorations provided by the + * system window manager (a title bar, borders, etc), but for some apps, it + * makes sense to drag them from somewhere else inside the window itself; for + * example, one might have a borderless window that wants to be draggable from + * any part, or simulate its own title bar, etc. + * + * This function lets the app provide a callback that designates pieces of a + * given window as special. This callback is run during event processing if we + * need to tell the OS to treat a region of the window specially; the use of + * this callback is known as "hit testing." + * + * Mouse input may not be delivered to your application if it is within a + * special area; the OS will often apply that input to moving the window or + * resizing the window and not deliver it to the application. + * + * Specifying NULL for a callback disables hit-testing. Hit-testing is + * disabled by default. + * + * Platforms that don't support this functionality will return false + * unconditionally, even if you're attempting to disable hit-testing. + * + * Your callback may fire at any time, and its firing does not indicate any + * specific behavior (for example, on Windows, this certainly might fire when + * the OS is deciding whether to drag your window, but it fires for lots of + * other reasons, too, some unrelated to anything you probably care about _and + * when the mouse isn't actually at the location it is testing_). Since this + * can fire at any time, you should try to keep your callback efficient, + * devoid of allocations, etc. + * + * \param window the window to set hit-testing on. + * \param callback the function to call when doing a hit-test. + * \param callback_data an app-defined void pointer passed to **callback**. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowHitTest(SDL_Window *window, SDL_HitTest callback, void *callback_data); + +/** + * Set the shape of a transparent window. + * + * This sets the alpha channel of a transparent window and any fully + * transparent areas are also transparent to mouse clicks. If you are using + * something besides the SDL render API, then you are responsible for drawing + * the alpha channel of the window to match the shape alpha channel to get + * consistent cross-platform results. + * + * The shape is copied inside this function, so you can free it afterwards. If + * your shape surface changes, you should call SDL_SetWindowShape() again to + * update the window. This is an expensive operation, so should be done + * sparingly. + * + * The window must have been created with the SDL_WINDOW_TRANSPARENT flag. + * + * \param window the window. + * \param shape the surface representing the shape of the window, or NULL to + * remove any current shape. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowShape(SDL_Window *window, SDL_Surface *shape); + +/** + * Request a window to demand attention from the user. + * + * \param window the window to be flashed. + * \param operation the operation to perform. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_FlashWindow(SDL_Window *window, SDL_FlashOperation operation); + +/** + * Destroy a window. + * + * Any child windows owned by the window will be recursively destroyed as + * well. + * + * Note that on some platforms, the visible window may not actually be removed + * from the screen until the SDL event loop is pumped again, even though the + * SDL_Window is no longer valid after this call. + * + * \param window the window to destroy. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_CreatePopupWindow + * \sa SDL_CreateWindow + * \sa SDL_CreateWindowWithProperties + */ +extern SDL_DECLSPEC void SDLCALL SDL_DestroyWindow(SDL_Window *window); + + +/** + * Check whether the screensaver is currently enabled. + * + * The screensaver is disabled by default. + * + * The default can also be changed using `SDL_HINT_VIDEO_ALLOW_SCREENSAVER`. + * + * \returns true if the screensaver is enabled, false if it is disabled. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DisableScreenSaver + * \sa SDL_EnableScreenSaver + */ +extern SDL_DECLSPEC bool SDLCALL SDL_ScreenSaverEnabled(void); + +/** + * Allow the screen to be blanked by a screen saver. + * + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_DisableScreenSaver + * \sa SDL_ScreenSaverEnabled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_EnableScreenSaver(void); + +/** + * Prevent the screen from being blanked by a screen saver. + * + * If you disable the screensaver, it is automatically re-enabled when SDL + * quits. + * + * The screensaver is disabled by default, but this may by changed by + * SDL_HINT_VIDEO_ALLOW_SCREENSAVER. + * + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_EnableScreenSaver + * \sa SDL_ScreenSaverEnabled + */ +extern SDL_DECLSPEC bool SDLCALL SDL_DisableScreenSaver(void); + + +/** + * \name OpenGL support functions + */ +/* @{ */ + +/** + * Dynamically load an OpenGL library. + * + * This should be done after initializing the video driver, but before + * creating any OpenGL windows. If no OpenGL library is loaded, the default + * library will be loaded upon creation of the first OpenGL window. + * + * If you do this, you need to retrieve all of the GL functions used in your + * program from the dynamic library using SDL_GL_GetProcAddress(). + * + * \param path the platform dependent OpenGL library name, or NULL to open the + * default OpenGL library. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_GetProcAddress + * \sa SDL_GL_UnloadLibrary + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GL_LoadLibrary(const char *path); + +/** + * Get an OpenGL function by name. + * + * If the GL library is loaded at runtime with SDL_GL_LoadLibrary(), then all + * GL functions must be retrieved this way. Usually this is used to retrieve + * function pointers to OpenGL extensions. + * + * There are some quirks to looking up OpenGL functions that require some + * extra care from the application. If you code carefully, you can handle + * these quirks without any platform-specific code, though: + * + * - On Windows, function pointers are specific to the current GL context; + * this means you need to have created a GL context and made it current + * before calling SDL_GL_GetProcAddress(). If you recreate your context or + * create a second context, you should assume that any existing function + * pointers aren't valid to use with it. This is (currently) a + * Windows-specific limitation, and in practice lots of drivers don't suffer + * this limitation, but it is still the way the wgl API is documented to + * work and you should expect crashes if you don't respect it. Store a copy + * of the function pointers that comes and goes with context lifespan. + * - On X11, function pointers returned by this function are valid for any + * context, and can even be looked up before a context is created at all. + * This means that, for at least some common OpenGL implementations, if you + * look up a function that doesn't exist, you'll get a non-NULL result that + * is _NOT_ safe to call. You must always make sure the function is actually + * available for a given GL context before calling it, by checking for the + * existence of the appropriate extension with SDL_GL_ExtensionSupported(), + * or verifying that the version of OpenGL you're using offers the function + * as core functionality. + * - Some OpenGL drivers, on all platforms, *will* return NULL if a function + * isn't supported, but you can't count on this behavior. Check for + * extensions you use, and if you get a NULL anyway, act as if that + * extension wasn't available. This is probably a bug in the driver, but you + * can code defensively for this scenario anyhow. + * - Just because you're on Linux/Unix, don't assume you'll be using X11. + * Next-gen display servers are waiting to replace it, and may or may not + * make the same promises about function pointers. + * - OpenGL function pointers must be declared `APIENTRY` as in the example + * code. This will ensure the proper calling convention is followed on + * platforms where this matters (Win32) thereby avoiding stack corruption. + * + * \param proc the name of an OpenGL function. + * \returns a pointer to the named OpenGL function. The returned pointer + * should be cast to the appropriate function signature. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_ExtensionSupported + * \sa SDL_GL_LoadLibrary + * \sa SDL_GL_UnloadLibrary + */ +extern SDL_DECLSPEC SDL_FunctionPointer SDLCALL SDL_GL_GetProcAddress(const char *proc); + +/** + * Get an EGL library function by name. + * + * If an EGL library is loaded, this function allows applications to get entry + * points for EGL functions. This is useful to provide to an EGL API and + * extension loader. + * + * \param proc the name of an EGL function. + * \returns a pointer to the named EGL function. The returned pointer should + * be cast to the appropriate function signature. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_EGL_GetCurrentDisplay + */ +extern SDL_DECLSPEC SDL_FunctionPointer SDLCALL SDL_EGL_GetProcAddress(const char *proc); + +/** + * Unload the OpenGL library previously loaded by SDL_GL_LoadLibrary(). + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_LoadLibrary + */ +extern SDL_DECLSPEC void SDLCALL SDL_GL_UnloadLibrary(void); + +/** + * Check if an OpenGL extension is supported for the current context. + * + * This function operates on the current GL context; you must have created a + * context and it must be current before calling this function. Do not assume + * that all contexts you create will have the same set of extensions + * available, or that recreating an existing context will offer the same + * extensions again. + * + * While it's probably not a massive overhead, this function is not an O(1) + * operation. Check the extensions you care about after creating the GL + * context and save that information somewhere instead of calling the function + * every time you need to know. + * + * \param extension the name of the extension to check. + * \returns true if the extension is supported, false otherwise. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GL_ExtensionSupported(const char *extension); + +/** + * Reset all previously set OpenGL context attributes to their default values. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_GetAttribute + * \sa SDL_GL_SetAttribute + */ +extern SDL_DECLSPEC void SDLCALL SDL_GL_ResetAttributes(void); + +/** + * Set an OpenGL window attribute before window creation. + * + * This function sets the OpenGL attribute `attr` to `value`. The requested + * attributes should be set before creating an OpenGL window. You should use + * SDL_GL_GetAttribute() to check the values after creating the OpenGL + * context, since the values obtained can differ from the requested ones. + * + * \param attr an SDL_GLAttr enum value specifying the OpenGL attribute to + * set. + * \param value the desired value for the attribute. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_GetAttribute + * \sa SDL_GL_ResetAttributes + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GL_SetAttribute(SDL_GLAttr attr, int value); + +/** + * Get the actual value for an attribute from the current context. + * + * \param attr an SDL_GLAttr enum value specifying the OpenGL attribute to + * get. + * \param value a pointer filled in with the current value of `attr`. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_ResetAttributes + * \sa SDL_GL_SetAttribute + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GL_GetAttribute(SDL_GLAttr attr, int *value); + +/** + * Create an OpenGL context for an OpenGL window, and make it current. + * + * Windows users new to OpenGL should note that, for historical reasons, GL + * functions added after OpenGL version 1.1 are not available by default. + * Those functions must be loaded at run-time, either with an OpenGL + * extension-handling library or with SDL_GL_GetProcAddress() and its related + * functions. + * + * SDL_GLContext is opaque to the application. + * + * \param window the window to associate with the context. + * \returns the OpenGL context associated with `window` or NULL on failure; + * call SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_DestroyContext + * \sa SDL_GL_MakeCurrent + */ +extern SDL_DECLSPEC SDL_GLContext SDLCALL SDL_GL_CreateContext(SDL_Window *window); + +/** + * Set up an OpenGL context for rendering into an OpenGL window. + * + * The context must have been created with a compatible window. + * + * \param window the window to associate with the context. + * \param context the OpenGL context to associate with the window. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_CreateContext + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GL_MakeCurrent(SDL_Window *window, SDL_GLContext context); + +/** + * Get the currently active OpenGL window. + * + * \returns the currently active OpenGL window on success or NULL on failure; + * call SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GL_GetCurrentWindow(void); + +/** + * Get the currently active OpenGL context. + * + * \returns the currently active OpenGL context or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_MakeCurrent + */ +extern SDL_DECLSPEC SDL_GLContext SDLCALL SDL_GL_GetCurrentContext(void); + +/** + * Get the currently active EGL display. + * + * \returns the currently active EGL display or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_EGLDisplay SDLCALL SDL_EGL_GetCurrentDisplay(void); + +/** + * Get the currently active EGL config. + * + * \returns the currently active EGL config or NULL on failure; call + * SDL_GetError() for more information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_EGLConfig SDLCALL SDL_EGL_GetCurrentConfig(void); + +/** + * Get the EGL surface associated with the window. + * + * \param window the window to query. + * \returns the EGLSurface pointer associated with the window, or NULL on + * failure. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC SDL_EGLSurface SDLCALL SDL_EGL_GetWindowSurface(SDL_Window *window); + +/** + * Sets the callbacks for defining custom EGLAttrib arrays for EGL + * initialization. + * + * Callbacks that aren't needed can be set to NULL. + * + * NOTE: These callback pointers will be reset after SDL_GL_ResetAttributes. + * + * \param platformAttribCallback callback for attributes to pass to + * eglGetPlatformDisplay. May be NULL. + * \param surfaceAttribCallback callback for attributes to pass to + * eglCreateSurface. May be NULL. + * \param contextAttribCallback callback for attributes to pass to + * eglCreateContext. May be NULL. + * \param userdata a pointer that is passed to the callbacks. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC void SDLCALL SDL_EGL_SetAttributeCallbacks(SDL_EGLAttribArrayCallback platformAttribCallback, + SDL_EGLIntArrayCallback surfaceAttribCallback, + SDL_EGLIntArrayCallback contextAttribCallback, void *userdata); + +/** + * Set the swap interval for the current OpenGL context. + * + * Some systems allow specifying -1 for the interval, to enable adaptive + * vsync. Adaptive vsync works the same as vsync, but if you've already missed + * the vertical retrace for a given frame, it swaps buffers immediately, which + * might be less jarring for the user during occasional framerate drops. If an + * application requests adaptive vsync and the system does not support it, + * this function will fail and return false. In such a case, you should + * probably retry the call with 1 for the interval. + * + * Adaptive vsync is implemented for some glX drivers with + * GLX_EXT_swap_control_tear, and for some Windows drivers with + * WGL_EXT_swap_control_tear. + * + * Read more on the Khronos wiki: + * https://www.khronos.org/opengl/wiki/Swap_Interval#Adaptive_Vsync + * + * \param interval 0 for immediate updates, 1 for updates synchronized with + * the vertical retrace, -1 for adaptive vsync. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_GetSwapInterval + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GL_SetSwapInterval(int interval); + +/** + * Get the swap interval for the current OpenGL context. + * + * If the system can't determine the swap interval, or there isn't a valid + * current context, this function will set *interval to 0 as a safe default. + * + * \param interval output interval value. 0 if there is no vertical retrace + * synchronization, 1 if the buffer swap is synchronized with + * the vertical retrace, and -1 if late swaps happen + * immediately instead of waiting for the next retrace. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_SetSwapInterval + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GL_GetSwapInterval(int *interval); + +/** + * Update a window with OpenGL rendering. + * + * This is used with double-buffered OpenGL contexts, which are the default. + * + * On macOS, make sure you bind 0 to the draw framebuffer before swapping the + * window, otherwise nothing will happen. If you aren't using + * glBindFramebuffer(), this is the default and you won't have to do anything + * extra. + * + * \param window the window to change. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GL_SwapWindow(SDL_Window *window); + +/** + * Delete an OpenGL context. + * + * \param context the OpenGL context to be deleted. + * \returns true on success or false on failure; call SDL_GetError() for more + * information. + * + * \threadsafety This function should only be called on the main thread. + * + * \since This function is available since SDL 3.2.0. + * + * \sa SDL_GL_CreateContext + */ +extern SDL_DECLSPEC bool SDLCALL SDL_GL_DestroyContext(SDL_GLContext context); + +/* @} *//* OpenGL support functions */ + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include + +#endif /* SDL_video_h_ */ diff --git a/thirdparty/sdl/include/build_config/SDL_build_config.h b/thirdparty/sdl/include/build_config/SDL_build_config.h new file mode 100644 index 00000000000..83031b70cc0 --- /dev/null +++ b/thirdparty/sdl/include/build_config/SDL_build_config.h @@ -0,0 +1,57 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_build_config_h_ +#define SDL_build_config_h_ + +#include + +/** + * \file SDL_build_config.h + * + * This is a set of defines to configure the SDL features + */ + +/* Add any platform that doesn't build using the configure system. */ +#if defined(SDL_PLATFORM_PRIVATE) +#include "SDL_build_config_private.h" +#elif defined(SDL_PLATFORM_WIN32) +#include "SDL_build_config_windows.h" +#elif defined(SDL_PLATFORM_WINGDK) +#include "SDL_build_config_wingdk.h" +#elif defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) +#include "SDL_build_config_xbox.h" +#elif defined(SDL_PLATFORM_MACOS) +#include "SDL_build_config_macos.h" +#elif defined(SDL_PLATFORM_IOS) +#include "SDL_build_config_ios.h" +#elif defined(SDL_PLATFORM_ANDROID) +#include "SDL_build_config_android.h" +#else +/* This is a minimal configuration just to get SDL running on new platforms. */ +#include "SDL_build_config_minimal.h" +#endif /* platform config */ + +#ifdef USING_GENERATED_CONFIG_H +#error Wrong SDL_build_config.h, check your include path? +#endif + +#endif /* SDL_build_config_h_ */ diff --git a/thirdparty/sdl/io/SDL_iostream.c b/thirdparty/sdl/io/SDL_iostream.c new file mode 100644 index 00000000000..989f3b9c4c0 --- /dev/null +++ b/thirdparty/sdl/io/SDL_iostream.c @@ -0,0 +1,1657 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(SDL_PLATFORM_WINDOWS) +#include "../core/windows/SDL_windows.h" +#else +#include +#endif + +#ifdef HAVE_STDIO_H +#include +#include +#include +#endif +#ifdef HAVE_LIMITS_H +#include +#endif + +#ifdef SDL_PLATFORM_APPLE +#include +#endif + +#include "SDL_iostream_c.h" + +/* This file provides a general interface for SDL to read and write + data sources. It can easily be extended to files, memory, etc. +*/ + +struct SDL_IOStream +{ + SDL_IOStreamInterface iface; + void *userdata; + SDL_IOStatus status; + SDL_PropertiesID props; +}; + +#ifdef SDL_PLATFORM_3DS +#include "n3ds/SDL_iostreamromfs.h" +#endif // SDL_PLATFORM_3DS + +#ifdef SDL_PLATFORM_ANDROID +#include +#include "../core/android/SDL_android.h" +#endif + +#if defined(SDL_PLATFORM_WINDOWS) + +typedef struct IOStreamWindowsData +{ + HANDLE h; + void *data; + size_t size; + size_t left; + bool append; + bool autoclose; +} IOStreamWindowsData; + + +// Functions to read/write Win32 API file pointers +#ifndef INVALID_SET_FILE_POINTER +#define INVALID_SET_FILE_POINTER 0xFFFFFFFF +#endif + +#define READAHEAD_BUFFER_SIZE 1024 + +static HANDLE SDLCALL windows_file_open(const char *filename, const char *mode) +{ +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + UINT old_error_mode; +#endif + HANDLE h; + DWORD r_right, w_right; + DWORD must_exist, truncate; + int a_mode; + + // "r" = reading, file must exist + // "w" = writing, truncate existing, file may not exist + // "r+"= reading or writing, file must exist + // "a" = writing, append file may not exist + // "a+"= append + read, file may not exist + // "w+" = read, write, truncate. file may not exist + + must_exist = (SDL_strchr(mode, 'r') != NULL) ? OPEN_EXISTING : 0; + truncate = (SDL_strchr(mode, 'w') != NULL) ? CREATE_ALWAYS : 0; + r_right = (SDL_strchr(mode, '+') != NULL || must_exist) ? GENERIC_READ : 0; + a_mode = (SDL_strchr(mode, 'a') != NULL) ? OPEN_ALWAYS : 0; + w_right = (a_mode || SDL_strchr(mode, '+') || truncate) ? GENERIC_WRITE : 0; + + if (!r_right && !w_right) { + return INVALID_HANDLE_VALUE; // inconsistent mode + } + // failed (invalid call) + +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + // Do not open a dialog box if failure + old_error_mode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS); +#endif + + { + LPWSTR str = WIN_UTF8ToStringW(filename); + h = CreateFileW(str, + (w_right | r_right), + (w_right) ? 0 : FILE_SHARE_READ, + NULL, + (must_exist | truncate | a_mode), + FILE_ATTRIBUTE_NORMAL, + NULL); + SDL_free(str); + } + +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + // restore old behavior + SetErrorMode(old_error_mode); +#endif + + if (h == INVALID_HANDLE_VALUE) { + char *error; + if (SDL_asprintf(&error, "Couldn't open %s", filename) > 0) { + WIN_SetError(error); + SDL_free(error); + } else { + SDL_SetError("Couldn't open %s", filename); + } + } + return h; +} + +static Sint64 SDLCALL windows_file_size(void *userdata) +{ + IOStreamWindowsData *iodata = (IOStreamWindowsData *) userdata; + LARGE_INTEGER size; + + if (!GetFileSizeEx(iodata->h, &size)) { + return WIN_SetError("windows_file_size"); + } + + return size.QuadPart; +} + +static Sint64 SDLCALL windows_file_seek(void *userdata, Sint64 offset, SDL_IOWhence whence) +{ + IOStreamWindowsData *iodata = (IOStreamWindowsData *) userdata; + DWORD windowswhence; + LARGE_INTEGER windowsoffset; + + // FIXME: We may be able to satisfy the seek within buffered data + if ((whence == SDL_IO_SEEK_CUR) && (iodata->left)) { + offset -= iodata->left; + } + iodata->left = 0; + + switch (whence) { + case SDL_IO_SEEK_SET: + windowswhence = FILE_BEGIN; + break; + case SDL_IO_SEEK_CUR: + windowswhence = FILE_CURRENT; + break; + case SDL_IO_SEEK_END: + windowswhence = FILE_END; + break; + default: + SDL_SetError("windows_file_seek: Unknown value for 'whence'"); + return -1; + } + + windowsoffset.QuadPart = offset; + if (!SetFilePointerEx(iodata->h, windowsoffset, &windowsoffset, windowswhence)) { + return WIN_SetError("Error seeking in datastream"); + } + return windowsoffset.QuadPart; +} + +static size_t SDLCALL windows_file_read(void *userdata, void *ptr, size_t size, SDL_IOStatus *status) +{ + IOStreamWindowsData *iodata = (IOStreamWindowsData *) userdata; + size_t total_need = size; + size_t total_read = 0; + size_t read_ahead; + DWORD bytes; + + if (iodata->left > 0) { + void *data = (char *)iodata->data + + iodata->size - + iodata->left; + read_ahead = SDL_min(total_need, iodata->left); + SDL_memcpy(ptr, data, read_ahead); + iodata->left -= read_ahead; + + if (read_ahead == total_need) { + return size; + } + ptr = (char *)ptr + read_ahead; + total_need -= read_ahead; + total_read += read_ahead; + } + + if (total_need < READAHEAD_BUFFER_SIZE) { + if (!ReadFile(iodata->h, iodata->data, READAHEAD_BUFFER_SIZE, &bytes, NULL)) { + DWORD error = GetLastError(); + switch (error) { + case ERROR_BROKEN_PIPE: + case ERROR_HANDLE_EOF: + break; + case ERROR_NO_DATA: + *status = SDL_IO_STATUS_NOT_READY; + break; + default: + WIN_SetError("Error reading from datastream"); + break; + } + return 0; + } + read_ahead = SDL_min(total_need, bytes); + SDL_memcpy(ptr, iodata->data, read_ahead); + iodata->size = bytes; + iodata->left = bytes - read_ahead; + total_read += read_ahead; + } else { + if (!ReadFile(iodata->h, ptr, (DWORD)total_need, &bytes, NULL)) { + DWORD error = GetLastError(); + switch (error) { + case ERROR_BROKEN_PIPE: + case ERROR_HANDLE_EOF: + break; + case ERROR_NO_DATA: + *status = SDL_IO_STATUS_NOT_READY; + break; + default: + WIN_SetError("Error reading from datastream"); + break; + } + return 0; + } + total_read += bytes; + } + return total_read; +} + +static size_t SDLCALL windows_file_write(void *userdata, const void *ptr, size_t size, SDL_IOStatus *status) +{ + IOStreamWindowsData *iodata = (IOStreamWindowsData *) userdata; + DWORD bytes; + + if (iodata->left) { + if (!SetFilePointer(iodata->h, -(LONG)iodata->left, NULL, FILE_CURRENT)) { + WIN_SetError("Error seeking in datastream"); + return 0; + } + iodata->left = 0; + } + + // if in append mode, we must go to the EOF before write + if (iodata->append) { + LARGE_INTEGER windowsoffset; + windowsoffset.QuadPart = 0; + if (!SetFilePointerEx(iodata->h, windowsoffset, &windowsoffset, FILE_END)) { + WIN_SetError("Error seeking in datastream"); + return 0; + } + } + + if (!WriteFile(iodata->h, ptr, (DWORD)size, &bytes, NULL)) { + WIN_SetError("Error writing to datastream"); + return 0; + } + if (bytes == 0 && size > 0) { + *status = SDL_IO_STATUS_NOT_READY; + } + return bytes; +} + +static bool SDLCALL windows_file_flush(void *userdata, SDL_IOStatus *status) +{ + IOStreamWindowsData *iodata = (IOStreamWindowsData *) userdata; + if (!FlushFileBuffers(iodata->h)) { + return WIN_SetError("Error flushing datastream"); + } + return true; +} + +static bool SDLCALL windows_file_close(void *userdata) +{ + IOStreamWindowsData *iodata = (IOStreamWindowsData *) userdata; + if (iodata->h != INVALID_HANDLE_VALUE) { + if (iodata->autoclose) { + CloseHandle(iodata->h); + } + iodata->h = INVALID_HANDLE_VALUE; // to be sure + } + SDL_free(iodata->data); + SDL_free(iodata); + return true; +} + +SDL_IOStream *SDL_IOFromHandle(HANDLE handle, const char *mode, bool autoclose) +{ + IOStreamWindowsData *iodata = (IOStreamWindowsData *) SDL_calloc(1, sizeof (*iodata)); + if (!iodata) { + if (autoclose) { + CloseHandle(handle); + } + return NULL; + } + + SDL_IOStreamInterface iface; + SDL_INIT_INTERFACE(&iface); + if (GetFileType(handle) == FILE_TYPE_DISK) { + iface.size = windows_file_size; + iface.seek = windows_file_seek; + } + iface.read = windows_file_read; + iface.write = windows_file_write; + iface.flush = windows_file_flush; + iface.close = windows_file_close; + + iodata->h = handle; + iodata->append = (SDL_strchr(mode, 'a') != NULL); + iodata->autoclose = autoclose; + + iodata->data = (char *)SDL_malloc(READAHEAD_BUFFER_SIZE); + if (!iodata->data) { + iface.close(iodata); + return NULL; + } + + SDL_IOStream *iostr = SDL_OpenIO(&iface, iodata); + if (!iostr) { + iface.close(iodata); + } else { + const SDL_PropertiesID props = SDL_GetIOProperties(iostr); + if (props) { + SDL_SetPointerProperty(props, SDL_PROP_IOSTREAM_WINDOWS_HANDLE_POINTER, iodata->h); + } + } + + return iostr; +} +#endif // defined(SDL_PLATFORM_WINDOWS) + +#if !defined(SDL_PLATFORM_WINDOWS) + +// Functions to read/write file descriptors. Not used for windows. + +typedef struct IOStreamFDData +{ + int fd; + bool autoclose; + bool regular_file; +} IOStreamFDData; + +static int SDL_fdatasync(int fd) +{ + int result = 0; + +#if defined(SDL_PLATFORM_APPLE) // Apple doesn't have fdatasync (rather, the symbol exists as an incompatible system call). + result = fcntl(fd, F_FULLFSYNC); +#elif defined(SDL_PLATFORM_HAIKU) + result = fsync(fd); +#elif defined(HAVE_FDATASYNC) + result = fdatasync(fd); +#endif + return result; +} + +static Sint64 SDLCALL fd_seek(void *userdata, Sint64 offset, SDL_IOWhence whence) +{ + IOStreamFDData *iodata = (IOStreamFDData *) userdata; + int fdwhence; + + switch (whence) { + case SDL_IO_SEEK_SET: + fdwhence = SEEK_SET; + break; + case SDL_IO_SEEK_CUR: + fdwhence = SEEK_CUR; + break; + case SDL_IO_SEEK_END: + fdwhence = SEEK_END; + break; + default: + SDL_SetError("Unknown value for 'whence'"); + return -1; + } + + off_t result = lseek(iodata->fd, (off_t)offset, fdwhence); + if (result < 0) { + SDL_SetError("Couldn't get stream offset: %s", strerror(errno)); + } + return result; +} + +static size_t SDLCALL fd_read(void *userdata, void *ptr, size_t size, SDL_IOStatus *status) +{ + IOStreamFDData *iodata = (IOStreamFDData *) userdata; + ssize_t bytes; + do { + bytes = read(iodata->fd, ptr, size); + } while (bytes < 0 && errno == EINTR); + + if (bytes < 0) { + if (errno == EAGAIN) { + *status = SDL_IO_STATUS_NOT_READY; + } else { + SDL_SetError("Error reading from datastream: %s", strerror(errno)); + } + bytes = 0; + } + return (size_t)bytes; +} + +static size_t SDLCALL fd_write(void *userdata, const void *ptr, size_t size, SDL_IOStatus *status) +{ + IOStreamFDData *iodata = (IOStreamFDData *) userdata; + ssize_t bytes; + do { + bytes = write(iodata->fd, ptr, size); + } while (bytes < 0 && errno == EINTR); + + if (bytes < 0) { + if (errno == EAGAIN) { + *status = SDL_IO_STATUS_NOT_READY; + } else { + SDL_SetError("Error writing to datastream: %s", strerror(errno)); + } + bytes = 0; + } + return (size_t)bytes; +} + +static bool SDLCALL fd_flush(void *userdata, SDL_IOStatus *status) +{ + IOStreamFDData *iodata = (IOStreamFDData *) userdata; + int result; + do { + result = SDL_fdatasync(iodata->fd); + } while (result < 0 && errno == EINTR); + + if (result < 0) { + return SDL_SetError("Error flushing datastream: %s", strerror(errno)); + } + return true; +} + +static bool SDLCALL fd_close(void *userdata) +{ + IOStreamFDData *iodata = (IOStreamFDData *) userdata; + bool status = true; + if (iodata->autoclose) { + if (close(iodata->fd) < 0) { + status = SDL_SetError("Error closing datastream: %s", strerror(errno)); + } + } + SDL_free(iodata); + return status; +} + +SDL_IOStream *SDL_IOFromFD(int fd, bool autoclose) +{ + IOStreamFDData *iodata = (IOStreamFDData *) SDL_calloc(1, sizeof (*iodata)); + if (!iodata) { + if (autoclose) { + close(fd); + } + return NULL; + } + + SDL_IOStreamInterface iface; + SDL_INIT_INTERFACE(&iface); + // There's no fd_size because SDL_GetIOSize emulates it the same way we'd do it for fd anyhow. + iface.seek = fd_seek; + iface.read = fd_read; + iface.write = fd_write; + iface.flush = fd_flush; + iface.close = fd_close; + + iodata->fd = fd; + iodata->autoclose = autoclose; + + struct stat st; + iodata->regular_file = ((fstat(fd, &st) == 0) && S_ISREG(st.st_mode)); + + SDL_IOStream *iostr = SDL_OpenIO(&iface, iodata); + if (!iostr) { + iface.close(iodata); + } else { + const SDL_PropertiesID props = SDL_GetIOProperties(iostr); + if (props) { + SDL_SetNumberProperty(props, SDL_PROP_IOSTREAM_FILE_DESCRIPTOR_NUMBER, fd); + } + } + + return iostr; +} +#endif // !defined(SDL_PLATFORM_WINDOWS) + +#if defined(HAVE_STDIO_H) && !defined(SDL_PLATFORM_WINDOWS) + +// Functions to read/write stdio file pointers. Not used for windows. + +typedef struct IOStreamStdioData +{ + FILE *fp; + bool autoclose; + bool regular_file; +} IOStreamStdioData; + +#ifdef HAVE_FOPEN64 +#define fopen fopen64 +#endif +#ifdef HAVE_FSEEKO64 +#define fseek_off_t off64_t +#define fseek fseeko64 +#define ftell ftello64 +#elif defined(HAVE_FSEEKO) +#if defined(OFF_MIN) && defined(OFF_MAX) +#define FSEEK_OFF_MIN OFF_MIN +#define FSEEK_OFF_MAX OFF_MAX +#elif defined(HAVE_LIMITS_H) +/* POSIX doesn't specify the minimum and maximum macros for off_t so + * we have to improvise and dance around implementation-defined + * behavior. This may fail if the off_t type has padding bits or + * is not a two's-complement representation. The compilers will detect + * and eliminate the dead code if off_t has 64 bits. + */ +#define FSEEK_OFF_MAX (((((off_t)1 << (sizeof(off_t) * CHAR_BIT - 2)) - 1) << 1) + 1) +#define FSEEK_OFF_MIN (-(FSEEK_OFF_MAX)-1) +#endif +#define fseek_off_t off_t +#define fseek fseeko +#define ftell ftello +#elif defined(HAVE__FSEEKI64) +#define fseek_off_t __int64 +#define fseek _fseeki64 +#define ftell _ftelli64 +#else +#ifdef HAVE_LIMITS_H +#define FSEEK_OFF_MIN LONG_MIN +#define FSEEK_OFF_MAX LONG_MAX +#endif +#define fseek_off_t long +#endif + +static Sint64 SDLCALL stdio_seek(void *userdata, Sint64 offset, SDL_IOWhence whence) +{ + IOStreamStdioData *iodata = (IOStreamStdioData *) userdata; + int stdiowhence; + + switch (whence) { + case SDL_IO_SEEK_SET: + stdiowhence = SEEK_SET; + break; + case SDL_IO_SEEK_CUR: + stdiowhence = SEEK_CUR; + break; + case SDL_IO_SEEK_END: + stdiowhence = SEEK_END; + break; + default: + SDL_SetError("Unknown value for 'whence'"); + return -1; + } + +#if defined(FSEEK_OFF_MIN) && defined(FSEEK_OFF_MAX) + if (offset < (Sint64)(FSEEK_OFF_MIN) || offset > (Sint64)(FSEEK_OFF_MAX)) { + SDL_SetError("Seek offset out of range"); + return -1; + } +#endif + + // don't make a possibly-costly API call for the noop seek from SDL_TellIO + const bool is_noop = (whence == SDL_IO_SEEK_CUR) && (offset == 0); + + if (is_noop || fseek(iodata->fp, (fseek_off_t)offset, stdiowhence) == 0) { + const Sint64 pos = ftell(iodata->fp); + if (pos < 0) { + SDL_SetError("Couldn't get stream offset: %s", strerror(errno)); + return -1; + } + return pos; + } + SDL_SetError("Error seeking in datastream: %s", strerror(errno)); + return -1; +} + +static size_t SDLCALL stdio_read(void *userdata, void *ptr, size_t size, SDL_IOStatus *status) +{ + IOStreamStdioData *iodata = (IOStreamStdioData *) userdata; + const size_t bytes = fread(ptr, 1, size, iodata->fp); + if (bytes == 0 && ferror(iodata->fp)) { + if (errno == EAGAIN) { + *status = SDL_IO_STATUS_NOT_READY; + clearerr(iodata->fp); + } else { + SDL_SetError("Error reading from datastream: %s", strerror(errno)); + } + } + return bytes; +} + +static size_t SDLCALL stdio_write(void *userdata, const void *ptr, size_t size, SDL_IOStatus *status) +{ + IOStreamStdioData *iodata = (IOStreamStdioData *) userdata; + const size_t bytes = fwrite(ptr, 1, size, iodata->fp); + if (bytes == 0 && ferror(iodata->fp)) { + if (errno == EAGAIN) { + *status = SDL_IO_STATUS_NOT_READY; + clearerr(iodata->fp); + } else { + SDL_SetError("Error writing to datastream: %s", strerror(errno)); + } + } + return bytes; +} + +static bool SDLCALL stdio_flush(void *userdata, SDL_IOStatus *status) +{ + IOStreamStdioData *iodata = (IOStreamStdioData *) userdata; + if (fflush(iodata->fp) != 0) { + if (errno == EAGAIN) { + *status = SDL_IO_STATUS_NOT_READY; + return false; + } else { + return SDL_SetError("Error flushing datastream: %s", strerror(errno)); + } + } + + int result; + int fd = fileno(iodata->fp); + do { + result = SDL_fdatasync(fd); + } while (result < 0 && errno == EINTR); + + if (result < 0) { + return SDL_SetError("Error flushing datastream: %s", strerror(errno)); + } + return true; +} + +static bool SDLCALL stdio_close(void *userdata) +{ + IOStreamStdioData *iodata = (IOStreamStdioData *) userdata; + bool status = true; + if (iodata->autoclose) { + if (fclose(iodata->fp) != 0) { + status = SDL_SetError("Error closing datastream: %s", strerror(errno)); + } + } + SDL_free(iodata); + return status; +} + +SDL_IOStream *SDL_IOFromFP(FILE *fp, bool autoclose) +{ + IOStreamStdioData *iodata = (IOStreamStdioData *) SDL_calloc(1, sizeof (*iodata)); + if (!iodata) { + if (autoclose) { + fclose(fp); + } + return NULL; + } + + SDL_IOStreamInterface iface; + SDL_INIT_INTERFACE(&iface); + // There's no stdio_size because SDL_GetIOSize emulates it the same way we'd do it for stdio anyhow. + iface.seek = stdio_seek; + iface.read = stdio_read; + iface.write = stdio_write; + iface.flush = stdio_flush; + iface.close = stdio_close; + + iodata->fp = fp; + iodata->autoclose = autoclose; + + struct stat st; + iodata->regular_file = ((fstat(fileno(fp), &st) == 0) && S_ISREG(st.st_mode)); + + SDL_IOStream *iostr = SDL_OpenIO(&iface, iodata); + if (!iostr) { + iface.close(iodata); + } else { + const SDL_PropertiesID props = SDL_GetIOProperties(iostr); + if (props) { + SDL_SetPointerProperty(props, SDL_PROP_IOSTREAM_STDIO_FILE_POINTER, fp); + SDL_SetNumberProperty(props, SDL_PROP_IOSTREAM_FILE_DESCRIPTOR_NUMBER, fileno(fp)); + } + } + + return iostr; +} +#endif // !HAVE_STDIO_H && !defined(SDL_PLATFORM_WINDOWS) + +// Functions to read/write memory pointers + +typedef struct IOStreamMemData +{ + Uint8 *base; + Uint8 *here; + Uint8 *stop; +} IOStreamMemData; + +static Sint64 SDLCALL mem_size(void *userdata) +{ + const IOStreamMemData *iodata = (IOStreamMemData *) userdata; + return (iodata->stop - iodata->base); +} + +static Sint64 SDLCALL mem_seek(void *userdata, Sint64 offset, SDL_IOWhence whence) +{ + IOStreamMemData *iodata = (IOStreamMemData *) userdata; + Uint8 *newpos; + + switch (whence) { + case SDL_IO_SEEK_SET: + newpos = iodata->base + offset; + break; + case SDL_IO_SEEK_CUR: + newpos = iodata->here + offset; + break; + case SDL_IO_SEEK_END: + newpos = iodata->stop + offset; + break; + default: + SDL_SetError("Unknown value for 'whence'"); + return -1; + } + if (newpos < iodata->base) { + newpos = iodata->base; + } + if (newpos > iodata->stop) { + newpos = iodata->stop; + } + iodata->here = newpos; + return (Sint64)(iodata->here - iodata->base); +} + +static size_t mem_io(void *userdata, void *dst, const void *src, size_t size) +{ + IOStreamMemData *iodata = (IOStreamMemData *) userdata; + const size_t mem_available = (iodata->stop - iodata->here); + if (size > mem_available) { + size = mem_available; + } + SDL_memcpy(dst, src, size); + iodata->here += size; + return size; +} + +static size_t SDLCALL mem_read(void *userdata, void *ptr, size_t size, SDL_IOStatus *status) +{ + IOStreamMemData *iodata = (IOStreamMemData *) userdata; + return mem_io(userdata, ptr, iodata->here, size); +} + +static size_t SDLCALL mem_write(void *userdata, const void *ptr, size_t size, SDL_IOStatus *status) +{ + IOStreamMemData *iodata = (IOStreamMemData *) userdata; + return mem_io(userdata, iodata->here, ptr, size); +} + +static bool SDLCALL mem_close(void *userdata) +{ + SDL_free(userdata); + return true; +} + +// Functions to create SDL_IOStream structures from various data sources + +#if defined(HAVE_STDIO_H) && !defined(SDL_PLATFORM_WINDOWS) +static bool IsRegularFileOrPipe(FILE *f) +{ +#ifndef SDL_PLATFORM_EMSCRIPTEN + struct stat st; + if (fstat(fileno(f), &st) < 0 || !(S_ISREG(st.st_mode) || S_ISFIFO(st.st_mode))) { + return false; + } +#endif // !SDL_PLATFORM_EMSCRIPTEN + + return true; +} +#endif + +SDL_IOStream *SDL_IOFromFile(const char *file, const char *mode) +{ + SDL_IOStream *iostr = NULL; + + if (!file || !*file) { + SDL_InvalidParamError("file"); + return NULL; + } + if (!mode || !*mode) { + SDL_InvalidParamError("mode"); + return NULL; + } + +#ifdef SDL_PLATFORM_ANDROID +#ifdef HAVE_STDIO_H + // Try to open the file on the filesystem first + if (*file == '/') { + FILE *fp = fopen(file, mode); + if (fp) { + if (!IsRegularFileOrPipe(fp)) { + fclose(fp); + SDL_SetError("%s is not a regular file or pipe", file); + return NULL; + } + return SDL_IOFromFP(fp, true); + } + } else if (SDL_strncmp(file, "content://", 10) == 0) { + // Try opening content:// URI + int fd = Android_JNI_OpenFileDescriptor(file, mode); + if (fd == -1) { + // SDL error is already set. + return NULL; + } + + FILE *fp = fdopen(fd, mode); + if (!fp) { + close(fd); + SDL_SetError("Unable to open file descriptor (%d) from URI %s: %s", fd, file, strerror(errno)); + return NULL; + } + + return SDL_IOFromFP(fp, true); + } else { + // Try opening it from internal storage if it's a relative path + char *path = NULL; + SDL_asprintf(&path, "%s/%s", SDL_GetAndroidInternalStoragePath(), file); + if (path) { + FILE *fp = fopen(path, mode); + SDL_free(path); + if (fp) { + if (!IsRegularFileOrPipe(fp)) { + fclose(fp); + SDL_SetError("%s is not a regular file or pipe", path); + return NULL; + } + return SDL_IOFromFP(fp, true); + } + } + } +#endif // HAVE_STDIO_H + + // Try to open the file from the asset system + + void *iodata = NULL; + if (!Android_JNI_FileOpen(&iodata, file, mode)) { + return NULL; + } + + SDL_IOStreamInterface iface; + SDL_INIT_INTERFACE(&iface); + iface.size = Android_JNI_FileSize; + iface.seek = Android_JNI_FileSeek; + iface.read = Android_JNI_FileRead; + iface.write = Android_JNI_FileWrite; + iface.close = Android_JNI_FileClose; + + iostr = SDL_OpenIO(&iface, iodata); + if (!iostr) { + iface.close(iodata); + } else { + const SDL_PropertiesID props = SDL_GetIOProperties(iostr); + if (props) { + SDL_SetPointerProperty(props, SDL_PROP_IOSTREAM_ANDROID_AASSET_POINTER, iodata); + } + } + +#elif defined(SDL_PLATFORM_WINDOWS) + HANDLE handle = windows_file_open(file, mode); + if (handle != INVALID_HANDLE_VALUE) { + iostr = SDL_IOFromHandle(handle, mode, true); + } + +#elif defined(HAVE_STDIO_H) + { + #if defined(SDL_PLATFORM_3DS) + FILE *fp = N3DS_FileOpen(file, mode); + #else + FILE *fp = fopen(file, mode); + #endif + + if (!fp) { + SDL_SetError("Couldn't open %s: %s", file, strerror(errno)); + } else if (!IsRegularFileOrPipe(fp)) { + fclose(fp); + fp = NULL; + SDL_SetError("%s is not a regular file or pipe", file); + } else { + iostr = SDL_IOFromFP(fp, true); + } + } + +#else + SDL_SetError("SDL not compiled with stdio support"); +#endif // !HAVE_STDIO_H + + return iostr; +} + +SDL_IOStream *SDL_IOFromMem(void *mem, size_t size) +{ + if (!mem) { + SDL_InvalidParamError("mem"); + return NULL; + } else if (!size) { + SDL_InvalidParamError("size"); + return NULL; + } + + IOStreamMemData *iodata = (IOStreamMemData *) SDL_calloc(1, sizeof (*iodata)); + if (!iodata) { + return NULL; + } + + SDL_IOStreamInterface iface; + SDL_INIT_INTERFACE(&iface); + iface.size = mem_size; + iface.seek = mem_seek; + iface.read = mem_read; + iface.write = mem_write; + iface.close = mem_close; + + iodata->base = (Uint8 *)mem; + iodata->here = iodata->base; + iodata->stop = iodata->base + size; + + SDL_IOStream *iostr = SDL_OpenIO(&iface, iodata); + if (!iostr) { + SDL_free(iodata); + } else { + const SDL_PropertiesID props = SDL_GetIOProperties(iostr); + if (props) { + SDL_SetPointerProperty(props, SDL_PROP_IOSTREAM_MEMORY_POINTER, mem); + SDL_SetNumberProperty(props, SDL_PROP_IOSTREAM_MEMORY_SIZE_NUMBER, size); + } + } + return iostr; +} + +SDL_IOStream *SDL_IOFromConstMem(const void *mem, size_t size) +{ + if (!mem) { + SDL_InvalidParamError("mem"); + return NULL; + } else if (!size) { + SDL_InvalidParamError("size"); + return NULL; + } + + IOStreamMemData *iodata = (IOStreamMemData *) SDL_calloc(1, sizeof (*iodata)); + if (!iodata) { + return NULL; + } + + SDL_IOStreamInterface iface; + SDL_INIT_INTERFACE(&iface); + iface.size = mem_size; + iface.seek = mem_seek; + iface.read = mem_read; + // leave iface.write as NULL. + iface.close = mem_close; + + iodata->base = (Uint8 *)mem; + iodata->here = iodata->base; + iodata->stop = iodata->base + size; + + SDL_IOStream *iostr = SDL_OpenIO(&iface, iodata); + if (!iostr) { + SDL_free(iodata); + } else { + const SDL_PropertiesID props = SDL_GetIOProperties(iostr); + if (props) { + SDL_SetPointerProperty(props, SDL_PROP_IOSTREAM_MEMORY_POINTER, (void *)mem); + SDL_SetNumberProperty(props, SDL_PROP_IOSTREAM_MEMORY_SIZE_NUMBER, size); + } + } + return iostr; +} + +typedef struct IOStreamDynamicMemData +{ + SDL_IOStream *stream; + IOStreamMemData data; + Uint8 *end; +} IOStreamDynamicMemData; + +static Sint64 SDLCALL dynamic_mem_size(void *userdata) +{ + IOStreamDynamicMemData *iodata = (IOStreamDynamicMemData *) userdata; + return mem_size(&iodata->data); +} + +static Sint64 SDLCALL dynamic_mem_seek(void *userdata, Sint64 offset, SDL_IOWhence whence) +{ + IOStreamDynamicMemData *iodata = (IOStreamDynamicMemData *) userdata; + return mem_seek(&iodata->data, offset, whence); +} + +static size_t SDLCALL dynamic_mem_read(void *userdata, void *ptr, size_t size, SDL_IOStatus *status) +{ + IOStreamDynamicMemData *iodata = (IOStreamDynamicMemData *) userdata; + return mem_io(&iodata->data, ptr, iodata->data.here, size); +} + +static bool dynamic_mem_realloc(IOStreamDynamicMemData *iodata, size_t size) +{ + size_t chunksize = (size_t)SDL_GetNumberProperty(SDL_GetIOProperties(iodata->stream), SDL_PROP_IOSTREAM_DYNAMIC_CHUNKSIZE_NUMBER, 0); + if (!chunksize) { + chunksize = 1024; + } + + // We're intentionally allocating more memory than needed so it can be null terminated + size_t chunks = (((iodata->end - iodata->data.base) + size) / chunksize) + 1; + size_t length = (chunks * chunksize); + Uint8 *base = (Uint8 *)SDL_realloc(iodata->data.base, length); + if (!base) { + return false; + } + + size_t here_offset = (iodata->data.here - iodata->data.base); + size_t stop_offset = (iodata->data.stop - iodata->data.base); + iodata->data.base = base; + iodata->data.here = base + here_offset; + iodata->data.stop = base + stop_offset; + iodata->end = base + length; + return SDL_SetPointerProperty(SDL_GetIOProperties(iodata->stream), SDL_PROP_IOSTREAM_DYNAMIC_MEMORY_POINTER, base); +} + +static size_t SDLCALL dynamic_mem_write(void *userdata, const void *ptr, size_t size, SDL_IOStatus *status) +{ + IOStreamDynamicMemData *iodata = (IOStreamDynamicMemData *) userdata; + if (size > (size_t)(iodata->data.stop - iodata->data.here)) { + if (size > (size_t)(iodata->end - iodata->data.here)) { + if (!dynamic_mem_realloc(iodata, size)) { + return 0; + } + } + iodata->data.stop = iodata->data.here + size; + } + return mem_io(&iodata->data, iodata->data.here, ptr, size); +} + +static bool SDLCALL dynamic_mem_close(void *userdata) +{ + const IOStreamDynamicMemData *iodata = (IOStreamDynamicMemData *) userdata; + void *mem = SDL_GetPointerProperty(SDL_GetIOProperties(iodata->stream), SDL_PROP_IOSTREAM_DYNAMIC_MEMORY_POINTER, NULL); + if (mem) { + SDL_free(mem); + } + SDL_free(userdata); + return true; +} + +SDL_IOStream *SDL_IOFromDynamicMem(void) +{ + IOStreamDynamicMemData *iodata = (IOStreamDynamicMemData *) SDL_calloc(1, sizeof (*iodata)); + if (!iodata) { + return NULL; + } + + SDL_IOStreamInterface iface; + SDL_INIT_INTERFACE(&iface); + iface.size = dynamic_mem_size; + iface.seek = dynamic_mem_seek; + iface.read = dynamic_mem_read; + iface.write = dynamic_mem_write; + iface.close = dynamic_mem_close; + + SDL_IOStream *iostr = SDL_OpenIO(&iface, iodata); + if (iostr) { + iodata->stream = iostr; + } else { + SDL_free(iodata); + } + return iostr; +} + +SDL_IOStatus SDL_GetIOStatus(SDL_IOStream *context) +{ + if (!context) { + SDL_InvalidParamError("context"); + return SDL_IO_STATUS_ERROR; + } + return context->status; +} + +SDL_IOStream *SDL_OpenIO(const SDL_IOStreamInterface *iface, void *userdata) +{ + if (!iface) { + SDL_InvalidParamError("iface"); + return NULL; + } + if (iface->version < sizeof(*iface)) { + // Update this to handle older versions of this interface + SDL_SetError("Invalid interface, should be initialized with SDL_INIT_INTERFACE()"); + return NULL; + } + + SDL_IOStream *iostr = (SDL_IOStream *)SDL_calloc(1, sizeof(*iostr)); + if (iostr) { + SDL_copyp(&iostr->iface, iface); + iostr->userdata = userdata; + } + return iostr; +} + +bool SDL_CloseIO(SDL_IOStream *iostr) +{ + bool result = true; + if (iostr) { + if (iostr->iface.close) { + result = iostr->iface.close(iostr->userdata); + } + SDL_DestroyProperties(iostr->props); + SDL_free(iostr); + } + return result; +} + +// Load all the data from an SDL data stream +void *SDL_LoadFile_IO(SDL_IOStream *src, size_t *datasize, bool closeio) +{ + const int FILE_CHUNK_SIZE = 1024; + Sint64 size, size_total = 0; + size_t size_read; + char *data = NULL, *newdata; + bool loading_chunks = false; + + if (!src) { + SDL_InvalidParamError("src"); + goto done; + } + + size = SDL_GetIOSize(src); + if (size < 0) { + size = FILE_CHUNK_SIZE; + loading_chunks = true; + } + if (size >= SDL_SIZE_MAX - 1) { + goto done; + } + data = (char *)SDL_malloc((size_t)(size + 1)); + if (!data) { + goto done; + } + + size_total = 0; + for (;;) { + if (loading_chunks) { + if ((size_total + FILE_CHUNK_SIZE) > size) { + size = (size_total + FILE_CHUNK_SIZE); + if (size >= SDL_SIZE_MAX - 1) { + newdata = NULL; + } else { + newdata = (char *)SDL_realloc(data, (size_t)(size + 1)); + } + if (!newdata) { + SDL_free(data); + data = NULL; + goto done; + } + data = newdata; + } + } + + size_read = SDL_ReadIO(src, data + size_total, (size_t)(size - size_total)); + if (size_read > 0) { + size_total += size_read; + continue; + } else if (SDL_GetIOStatus(src) == SDL_IO_STATUS_NOT_READY) { + // Wait for the stream to be ready + SDL_Delay(1); + continue; + } + + // The stream status will remain set for the caller to check + break; + } + + data[size_total] = '\0'; + +done: + if (datasize) { + *datasize = (size_t)size_total; + } + if (closeio && src) { + SDL_CloseIO(src); + } + return data; +} + +void *SDL_LoadFile(const char *file, size_t *datasize) +{ + SDL_IOStream *stream = SDL_IOFromFile(file, "rb"); + if (!stream) { + if (datasize) { + *datasize = 0; + } + return NULL; + } + return SDL_LoadFile_IO(stream, datasize, true); +} + +bool SDL_SaveFile_IO(SDL_IOStream *src, const void *data, size_t datasize, bool closeio) +{ + size_t size_written = 0; + size_t size_total = 0; + bool success = true; + + if (!src) { + SDL_InvalidParamError("src"); + goto done; + } + + if (!data && datasize > 0) { + SDL_InvalidParamError("data"); + goto done; + } + + if (datasize > 0) { + while (size_total < datasize) { + size_written = SDL_WriteIO(src, ((const char *) data) + size_written, datasize - size_written); + + if (size_written <= 0) { + if (SDL_GetIOStatus(src) == SDL_IO_STATUS_NOT_READY) { + // Wait for the stream to be ready + SDL_Delay(1); + continue; + } else { + success = false; + goto done; + } + } + + size_total += size_written; + } + } + +done: + if (closeio && src) { + SDL_CloseIO(src); + } + + return success; +} + +bool SDL_SaveFile(const char *file, const void *data, size_t datasize) +{ + SDL_IOStream *stream = SDL_IOFromFile(file, "wb"); + if (!stream) { + return false; + } + return SDL_SaveFile_IO(stream, data, datasize, true); +} + +SDL_PropertiesID SDL_GetIOProperties(SDL_IOStream *context) +{ + if (!context) { + SDL_InvalidParamError("context"); + return 0; + } + + if (context->props == 0) { + context->props = SDL_CreateProperties(); + } + return context->props; +} + +Sint64 SDL_GetIOSize(SDL_IOStream *context) +{ + if (!context) { + return SDL_InvalidParamError("context"); + } + if (!context->iface.size) { + Sint64 pos, size; + + pos = SDL_SeekIO(context, 0, SDL_IO_SEEK_CUR); + if (pos < 0) { + return -1; + } + size = SDL_SeekIO(context, 0, SDL_IO_SEEK_END); + + SDL_SeekIO(context, pos, SDL_IO_SEEK_SET); + return size; + } + return context->iface.size(context->userdata); +} + +Sint64 SDL_SeekIO(SDL_IOStream *context, Sint64 offset, SDL_IOWhence whence) +{ + if (!context) { + SDL_InvalidParamError("context"); + return -1; + } else if (!context->iface.seek) { + SDL_Unsupported(); + return -1; + } + return context->iface.seek(context->userdata, offset, whence); +} + +Sint64 SDL_TellIO(SDL_IOStream *context) +{ + return SDL_SeekIO(context, 0, SDL_IO_SEEK_CUR); +} + +size_t SDL_ReadIO(SDL_IOStream *context, void *ptr, size_t size) +{ + size_t bytes; + + if (!context) { + SDL_InvalidParamError("context"); + return 0; + } else if (!context->iface.read) { + context->status = SDL_IO_STATUS_WRITEONLY; + SDL_Unsupported(); + return 0; + } + + context->status = SDL_IO_STATUS_READY; + SDL_ClearError(); + + if (size == 0) { + return 0; + } + + bytes = context->iface.read(context->userdata, ptr, size, &context->status); + if (bytes == 0 && context->status == SDL_IO_STATUS_READY) { + if (*SDL_GetError()) { + context->status = SDL_IO_STATUS_ERROR; + } else { + context->status = SDL_IO_STATUS_EOF; + } + } + return bytes; +} + +size_t SDL_WriteIO(SDL_IOStream *context, const void *ptr, size_t size) +{ + size_t bytes; + + if (!context) { + SDL_InvalidParamError("context"); + return 0; + } else if (!context->iface.write) { + context->status = SDL_IO_STATUS_READONLY; + SDL_Unsupported(); + return 0; + } + + context->status = SDL_IO_STATUS_READY; + SDL_ClearError(); + + if (size == 0) { + return 0; + } + + bytes = context->iface.write(context->userdata, ptr, size, &context->status); + if ((bytes == 0) && (context->status == SDL_IO_STATUS_READY)) { + context->status = SDL_IO_STATUS_ERROR; + } + return bytes; +} + +size_t SDL_IOprintf(SDL_IOStream *context, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + int size; + char *string; + size_t bytes; + + va_start(ap, fmt); + size = SDL_vasprintf(&string, fmt, ap); + va_end(ap); + if (size < 0) { + return 0; + } + + bytes = SDL_WriteIO(context, string, (size_t)size); + SDL_free(string); + return bytes; +} + +size_t SDL_IOvprintf(SDL_IOStream *context, SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) +{ + int size; + char *string; + size_t bytes; + + size = SDL_vasprintf(&string, fmt, ap); + if (size < 0) { + return 0; + } + + bytes = SDL_WriteIO(context, string, (size_t)size); + SDL_free(string); + return bytes; +} + +bool SDL_FlushIO(SDL_IOStream *context) +{ + bool result = true; + + if (!context) { + return SDL_InvalidParamError("context"); + } + + context->status = SDL_IO_STATUS_READY; + SDL_ClearError(); + + if (context->iface.flush) { + result = context->iface.flush(context->userdata, &context->status); + } + if (!result && (context->status == SDL_IO_STATUS_READY)) { + context->status = SDL_IO_STATUS_ERROR; + } + return result; +} + +// Functions for dynamically reading and writing endian-specific values + +bool SDL_ReadU8(SDL_IOStream *src, Uint8 *value) +{ + Uint8 data = 0; + bool result = false; + + if (SDL_ReadIO(src, &data, sizeof(data)) == sizeof(data)) { + result = true; + } + if (value) { + *value = data; + } + return result; +} + +bool SDL_ReadS8(SDL_IOStream *src, Sint8 *value) +{ + Sint8 data = 0; + bool result = false; + + if (SDL_ReadIO(src, &data, sizeof(data)) == sizeof(data)) { + result = true; + } + if (value) { + *value = data; + } + return result; +} + +bool SDL_ReadU16LE(SDL_IOStream *src, Uint16 *value) +{ + Uint16 data = 0; + bool result = false; + + if (SDL_ReadIO(src, &data, sizeof(data)) == sizeof(data)) { + result = true; + } + if (value) { + *value = SDL_Swap16LE(data); + } + return result; +} + +bool SDL_ReadS16LE(SDL_IOStream *src, Sint16 *value) +{ + return SDL_ReadU16LE(src, (Uint16 *)value); +} + +bool SDL_ReadU16BE(SDL_IOStream *src, Uint16 *value) +{ + Uint16 data = 0; + bool result = false; + + if (SDL_ReadIO(src, &data, sizeof(data)) == sizeof(data)) { + result = true; + } + if (value) { + *value = SDL_Swap16BE(data); + } + return result; +} + +bool SDL_ReadS16BE(SDL_IOStream *src, Sint16 *value) +{ + return SDL_ReadU16BE(src, (Uint16 *)value); +} + +bool SDL_ReadU32LE(SDL_IOStream *src, Uint32 *value) +{ + Uint32 data = 0; + bool result = false; + + if (SDL_ReadIO(src, &data, sizeof(data)) == sizeof(data)) { + result = true; + } + if (value) { + *value = SDL_Swap32LE(data); + } + return result; +} + +bool SDL_ReadS32LE(SDL_IOStream *src, Sint32 *value) +{ + return SDL_ReadU32LE(src, (Uint32 *)value); +} + +bool SDL_ReadU32BE(SDL_IOStream *src, Uint32 *value) +{ + Uint32 data = 0; + bool result = false; + + if (SDL_ReadIO(src, &data, sizeof(data)) == sizeof(data)) { + result = true; + } + if (value) { + *value = SDL_Swap32BE(data); + } + return result; +} + +bool SDL_ReadS32BE(SDL_IOStream *src, Sint32 *value) +{ + return SDL_ReadU32BE(src, (Uint32 *)value); +} + +bool SDL_ReadU64LE(SDL_IOStream *src, Uint64 *value) +{ + Uint64 data = 0; + bool result = false; + + if (SDL_ReadIO(src, &data, sizeof(data)) == sizeof(data)) { + result = true; + } + if (value) { + *value = SDL_Swap64LE(data); + } + return result; +} + +bool SDL_ReadS64LE(SDL_IOStream *src, Sint64 *value) +{ + return SDL_ReadU64LE(src, (Uint64 *)value); +} + +bool SDL_ReadU64BE(SDL_IOStream *src, Uint64 *value) +{ + Uint64 data = 0; + bool result = false; + + if (SDL_ReadIO(src, &data, sizeof(data)) == sizeof(data)) { + result = true; + } + if (value) { + *value = SDL_Swap64BE(data); + } + return result; +} + +bool SDL_ReadS64BE(SDL_IOStream *src, Sint64 *value) +{ + return SDL_ReadU64BE(src, (Uint64 *)value); +} + +bool SDL_WriteU8(SDL_IOStream *dst, Uint8 value) +{ + return (SDL_WriteIO(dst, &value, sizeof(value)) == sizeof(value)); +} + +bool SDL_WriteS8(SDL_IOStream *dst, Sint8 value) +{ + return (SDL_WriteIO(dst, &value, sizeof(value)) == sizeof(value)); +} + +bool SDL_WriteU16LE(SDL_IOStream *dst, Uint16 value) +{ + const Uint16 swapped = SDL_Swap16LE(value); + return (SDL_WriteIO(dst, &swapped, sizeof(swapped)) == sizeof(swapped)); +} + +bool SDL_WriteS16LE(SDL_IOStream *dst, Sint16 value) +{ + return SDL_WriteU16LE(dst, (Uint16)value); +} + +bool SDL_WriteU16BE(SDL_IOStream *dst, Uint16 value) +{ + const Uint16 swapped = SDL_Swap16BE(value); + return (SDL_WriteIO(dst, &swapped, sizeof(swapped)) == sizeof(swapped)); +} + +bool SDL_WriteS16BE(SDL_IOStream *dst, Sint16 value) +{ + return SDL_WriteU16BE(dst, (Uint16)value); +} + +bool SDL_WriteU32LE(SDL_IOStream *dst, Uint32 value) +{ + const Uint32 swapped = SDL_Swap32LE(value); + return (SDL_WriteIO(dst, &swapped, sizeof(swapped)) == sizeof(swapped)); +} + +bool SDL_WriteS32LE(SDL_IOStream *dst, Sint32 value) +{ + return SDL_WriteU32LE(dst, (Uint32)value); +} + +bool SDL_WriteU32BE(SDL_IOStream *dst, Uint32 value) +{ + const Uint32 swapped = SDL_Swap32BE(value); + return (SDL_WriteIO(dst, &swapped, sizeof(swapped)) == sizeof(swapped)); +} + +bool SDL_WriteS32BE(SDL_IOStream *dst, Sint32 value) +{ + return SDL_WriteU32BE(dst, (Uint32)value); +} + +bool SDL_WriteU64LE(SDL_IOStream *dst, Uint64 value) +{ + const Uint64 swapped = SDL_Swap64LE(value); + return (SDL_WriteIO(dst, &swapped, sizeof(swapped)) == sizeof(swapped)); +} + +bool SDL_WriteS64LE(SDL_IOStream *dst, Sint64 value) +{ + return SDL_WriteU64LE(dst, (Uint64)value); +} + +bool SDL_WriteU64BE(SDL_IOStream *dst, Uint64 value) +{ + const Uint64 swapped = SDL_Swap64BE(value); + return (SDL_WriteIO(dst, &swapped, sizeof(swapped)) == sizeof(swapped)); +} + +bool SDL_WriteS64BE(SDL_IOStream *dst, Sint64 value) +{ + return SDL_WriteU64BE(dst, (Uint64)value); +} diff --git a/thirdparty/sdl/io/SDL_iostream_c.h b/thirdparty/sdl/io/SDL_iostream_c.h new file mode 100644 index 00000000000..c04fe203f73 --- /dev/null +++ b/thirdparty/sdl/io/SDL_iostream_c.h @@ -0,0 +1,35 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_iostream_c_h_ +#define SDL_iostream_c_h_ + +#if defined(SDL_PLATFORM_WINDOWS) +SDL_IOStream *SDL_IOFromHandle(HANDLE handle, const char *mode, bool autoclose); +#else +#if defined(HAVE_STDIO_H) +extern SDL_IOStream *SDL_IOFromFP(FILE *fp, bool autoclose); +#endif +extern SDL_IOStream *SDL_IOFromFD(int fd, bool autoclose); +#endif + +#endif // SDL_iostream_c_h_ diff --git a/thirdparty/sdl/joystick/SDL_gamepad.c b/thirdparty/sdl/joystick/SDL_gamepad.c new file mode 100644 index 00000000000..385e890cf98 --- /dev/null +++ b/thirdparty/sdl/joystick/SDL_gamepad.c @@ -0,0 +1,3915 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This is the gamepad API for Simple DirectMedia Layer + +#include "SDL_sysjoystick.h" +#include "SDL_joystick_c.h" +#include "SDL_steam_virtual_gamepad.h" +#include "SDL_gamepad_c.h" +#include "SDL_gamepad_db.h" +#include "controller_type.h" +#include "usb_ids.h" +#include "hidapi/SDL_hidapi_nintendo.h" +#include "../events/SDL_events_c.h" + + +#ifdef SDL_PLATFORM_ANDROID +#endif + +// Many gamepads turn the center button into an instantaneous button press +#define SDL_MINIMUM_GUIDE_BUTTON_DELAY_MS 250 + +#define SDL_GAMEPAD_CRC_FIELD "crc:" +#define SDL_GAMEPAD_CRC_FIELD_SIZE 4 // hard-coded for speed +#define SDL_GAMEPAD_TYPE_FIELD "type:" +#define SDL_GAMEPAD_TYPE_FIELD_SIZE SDL_strlen(SDL_GAMEPAD_TYPE_FIELD) +#define SDL_GAMEPAD_FACE_FIELD "face:" +#define SDL_GAMEPAD_FACE_FIELD_SIZE 5 // hard-coded for speed +#define SDL_GAMEPAD_PLATFORM_FIELD "platform:" +#define SDL_GAMEPAD_PLATFORM_FIELD_SIZE SDL_strlen(SDL_GAMEPAD_PLATFORM_FIELD) +#define SDL_GAMEPAD_HINT_FIELD "hint:" +#define SDL_GAMEPAD_HINT_FIELD_SIZE SDL_strlen(SDL_GAMEPAD_HINT_FIELD) +#define SDL_GAMEPAD_SDKGE_FIELD "sdk>=:" +#define SDL_GAMEPAD_SDKGE_FIELD_SIZE SDL_strlen(SDL_GAMEPAD_SDKGE_FIELD) +#define SDL_GAMEPAD_SDKLE_FIELD "sdk<=:" +#define SDL_GAMEPAD_SDKLE_FIELD_SIZE SDL_strlen(SDL_GAMEPAD_SDKLE_FIELD) + +static bool SDL_gamepads_initialized; +static SDL_Gamepad *SDL_gamepads SDL_GUARDED_BY(SDL_joystick_lock) = NULL; + +// The face button style of a gamepad +typedef enum +{ + SDL_GAMEPAD_FACE_STYLE_UNKNOWN, + SDL_GAMEPAD_FACE_STYLE_ABXY, + SDL_GAMEPAD_FACE_STYLE_BAYX, + SDL_GAMEPAD_FACE_STYLE_SONY, +} SDL_GamepadFaceStyle; + +// our hard coded list of mapping support +typedef enum +{ + SDL_GAMEPAD_MAPPING_PRIORITY_DEFAULT, + SDL_GAMEPAD_MAPPING_PRIORITY_API, + SDL_GAMEPAD_MAPPING_PRIORITY_USER, +} SDL_GamepadMappingPriority; + +#define _guarded SDL_GUARDED_BY(SDL_joystick_lock) + +typedef struct GamepadMapping_t +{ + SDL_GUID guid _guarded; + char *name _guarded; + char *mapping _guarded; + SDL_GamepadMappingPriority priority _guarded; + struct GamepadMapping_t *next _guarded; +} GamepadMapping_t; + +typedef struct +{ + int refcount _guarded; + SDL_JoystickID *joysticks _guarded; + GamepadMapping_t **joystick_mappings _guarded; + + int num_changed_mappings _guarded; + GamepadMapping_t **changed_mappings _guarded; + +} MappingChangeTracker; + +#undef _guarded + +static SDL_GUID s_zeroGUID; +static GamepadMapping_t *s_pSupportedGamepads SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static GamepadMapping_t *s_pDefaultMapping SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static GamepadMapping_t *s_pXInputMapping SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static MappingChangeTracker *s_mappingChangeTracker SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static SDL_HashTable *s_gamepadInstanceIDs SDL_GUARDED_BY(SDL_joystick_lock) = NULL; + +#define _guarded SDL_GUARDED_BY(SDL_joystick_lock) + +// The SDL gamepad structure +struct SDL_Gamepad +{ + SDL_Joystick *joystick _guarded; // underlying joystick device + int ref_count _guarded; + + const char *name _guarded; + SDL_GamepadType type _guarded; + SDL_GamepadFaceStyle face_style _guarded; + GamepadMapping_t *mapping _guarded; + int num_bindings _guarded; + SDL_GamepadBinding *bindings _guarded; + SDL_GamepadBinding **last_match_axis _guarded; + Uint8 *last_hat_mask _guarded; + Uint64 guide_button_down _guarded; + + struct SDL_Gamepad *next _guarded; // pointer to next gamepad we have allocated +}; + +#undef _guarded + +#define CHECK_GAMEPAD_MAGIC(gamepad, result) \ + if (!SDL_ObjectValid(gamepad, SDL_OBJECT_TYPE_GAMEPAD) || \ + !SDL_IsJoystickValid(gamepad->joystick)) { \ + SDL_InvalidParamError("gamepad"); \ + SDL_UnlockJoysticks(); \ + return result; \ + } + +static SDL_vidpid_list SDL_allowed_gamepads = { + SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT, 0, 0, NULL, + NULL, 0, 0, NULL, + 0, NULL, + false +}; +static SDL_vidpid_list SDL_ignored_gamepads = { + SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES, 0, 0, NULL, + NULL, 0, 0, NULL, + 0, NULL, + false +}; + +static GamepadMapping_t *SDL_PrivateAddMappingForGUID(SDL_GUID jGUID, const char *mappingString, bool *existing, SDL_GamepadMappingPriority priority); +static void SDL_PrivateLoadButtonMapping(SDL_Gamepad *gamepad, GamepadMapping_t *pGamepadMapping); +static GamepadMapping_t *SDL_PrivateGetGamepadMapping(SDL_JoystickID instance_id, bool create_mapping); +static void SDL_SendGamepadAxis(Uint64 timestamp, SDL_Gamepad *gamepad, SDL_GamepadAxis axis, Sint16 value); +static void SDL_SendGamepadButton(Uint64 timestamp, SDL_Gamepad *gamepad, SDL_GamepadButton button, bool down); + +static bool HasSameOutput(SDL_GamepadBinding *a, SDL_GamepadBinding *b) +{ + if (a->output_type != b->output_type) { + return false; + } + + if (a->output_type == SDL_GAMEPAD_BINDTYPE_AXIS) { + return a->output.axis.axis == b->output.axis.axis; + } else { + return a->output.button == b->output.button; + } +} + +static void ResetOutput(Uint64 timestamp, SDL_Gamepad *gamepad, SDL_GamepadBinding *bind) +{ + if (bind->output_type == SDL_GAMEPAD_BINDTYPE_AXIS) { + SDL_SendGamepadAxis(timestamp, gamepad, bind->output.axis.axis, 0); + } else { + SDL_SendGamepadButton(timestamp, gamepad, bind->output.button, false); + } +} + +static void HandleJoystickAxis(Uint64 timestamp, SDL_Gamepad *gamepad, int axis, int value) +{ + int i; + SDL_GamepadBinding *last_match; + SDL_GamepadBinding *match = NULL; + + SDL_AssertJoysticksLocked(); + + last_match = gamepad->last_match_axis[axis]; + for (i = 0; i < gamepad->num_bindings; ++i) { + SDL_GamepadBinding *binding = &gamepad->bindings[i]; + if (binding->input_type == SDL_GAMEPAD_BINDTYPE_AXIS && + axis == binding->input.axis.axis) { + if (binding->input.axis.axis_min < binding->input.axis.axis_max) { + if (value >= binding->input.axis.axis_min && + value <= binding->input.axis.axis_max) { + match = binding; + break; + } + } else { + if (value >= binding->input.axis.axis_max && + value <= binding->input.axis.axis_min) { + match = binding; + break; + } + } + } + } + + if (last_match && (!match || !HasSameOutput(last_match, match))) { + // Clear the last input that this axis generated + ResetOutput(timestamp, gamepad, last_match); + } + + if (match) { + if (match->output_type == SDL_GAMEPAD_BINDTYPE_AXIS) { + if (match->input.axis.axis_min != match->output.axis.axis_min || match->input.axis.axis_max != match->output.axis.axis_max) { + float normalized_value = (float)(value - match->input.axis.axis_min) / (match->input.axis.axis_max - match->input.axis.axis_min); + value = match->output.axis.axis_min + (int)(normalized_value * (match->output.axis.axis_max - match->output.axis.axis_min)); + } + SDL_SendGamepadAxis(timestamp, gamepad, match->output.axis.axis, (Sint16)value); + } else { + bool down; + int threshold = match->input.axis.axis_min + (match->input.axis.axis_max - match->input.axis.axis_min) / 2; + if (match->input.axis.axis_max < match->input.axis.axis_min) { + down = (value <= threshold); + } else { + down = (value >= threshold); + } + SDL_SendGamepadButton(timestamp, gamepad, match->output.button, down); + } + } + gamepad->last_match_axis[axis] = match; +} + +static void HandleJoystickButton(Uint64 timestamp, SDL_Gamepad *gamepad, int button, bool down) +{ + int i; + + SDL_AssertJoysticksLocked(); + + for (i = 0; i < gamepad->num_bindings; ++i) { + SDL_GamepadBinding *binding = &gamepad->bindings[i]; + if (binding->input_type == SDL_GAMEPAD_BINDTYPE_BUTTON && + button == binding->input.button) { + if (binding->output_type == SDL_GAMEPAD_BINDTYPE_AXIS) { + int value = down ? binding->output.axis.axis_max : binding->output.axis.axis_min; + SDL_SendGamepadAxis(timestamp, gamepad, binding->output.axis.axis, (Sint16)value); + } else { + SDL_SendGamepadButton(timestamp, gamepad, binding->output.button, down); + } + break; + } + } +} + +static void HandleJoystickHat(Uint64 timestamp, SDL_Gamepad *gamepad, int hat, Uint8 value) +{ + int i; + Uint8 last_mask, changed_mask; + + SDL_AssertJoysticksLocked(); + + last_mask = gamepad->last_hat_mask[hat]; + changed_mask = (last_mask ^ value); + for (i = 0; i < gamepad->num_bindings; ++i) { + SDL_GamepadBinding *binding = &gamepad->bindings[i]; + if (binding->input_type == SDL_GAMEPAD_BINDTYPE_HAT && hat == binding->input.hat.hat) { + if ((changed_mask & binding->input.hat.hat_mask) != 0) { + if (value & binding->input.hat.hat_mask) { + if (binding->output_type == SDL_GAMEPAD_BINDTYPE_AXIS) { + SDL_SendGamepadAxis(timestamp, gamepad, binding->output.axis.axis, (Sint16)binding->output.axis.axis_max); + } else { + SDL_SendGamepadButton(timestamp, gamepad, binding->output.button, true); + } + } else { + ResetOutput(timestamp, gamepad, binding); + } + } + } + } + gamepad->last_hat_mask[hat] = value; +} + +/* The joystick layer will _also_ send events to recenter before disconnect, + but it has to make (sometimes incorrect) guesses at what being "centered" + is. The gamepad layer, however, can set a definite logical idle + position, so set them all here. If we happened to already be at the + center thanks to the joystick layer or idle hands, this won't generate + duplicate events. */ +static void RecenterGamepad(SDL_Gamepad *gamepad) +{ + int i; + Uint64 timestamp = SDL_GetTicksNS(); + + for (i = 0; i < SDL_GAMEPAD_BUTTON_COUNT; ++i) { + SDL_GamepadButton button = (SDL_GamepadButton)i; + if (SDL_GetGamepadButton(gamepad, button)) { + SDL_SendGamepadButton(timestamp, gamepad, button, false); + } + } + + for (i = 0; i < SDL_GAMEPAD_AXIS_COUNT; ++i) { + SDL_GamepadAxis axis = (SDL_GamepadAxis)i; + if (SDL_GetGamepadAxis(gamepad, axis) != 0) { + SDL_SendGamepadAxis(timestamp, gamepad, axis, 0); + } + } +} + +void SDL_PrivateGamepadAdded(SDL_JoystickID instance_id) +{ + SDL_Event event; + + if (!SDL_gamepads_initialized) { + return; + } + + event.type = SDL_EVENT_GAMEPAD_ADDED; + event.common.timestamp = 0; + event.gdevice.which = instance_id; + SDL_PushEvent(&event); +} + +void SDL_PrivateGamepadRemoved(SDL_JoystickID instance_id) +{ + SDL_Event event; + SDL_Gamepad *gamepad; + + SDL_AssertJoysticksLocked(); + + if (!SDL_gamepads_initialized) { + return; + } + + for (gamepad = SDL_gamepads; gamepad; gamepad = gamepad->next) { + if (gamepad->joystick->instance_id == instance_id) { + RecenterGamepad(gamepad); + break; + } + } + + event.type = SDL_EVENT_GAMEPAD_REMOVED; + event.common.timestamp = 0; + event.gdevice.which = instance_id; + SDL_PushEvent(&event); +} + +static void SDL_PrivateGamepadRemapped(SDL_JoystickID instance_id) +{ + SDL_Event event; + + if (!SDL_gamepads_initialized || SDL_IsJoystickBeingAdded()) { + return; + } + + event.type = SDL_EVENT_GAMEPAD_REMAPPED; + event.common.timestamp = 0; + event.gdevice.which = instance_id; + SDL_PushEvent(&event); +} + +/* + * Event filter to fire gamepad events from joystick ones + */ +static bool SDLCALL SDL_GamepadEventWatcher(void *userdata, SDL_Event *event) +{ + SDL_Gamepad *gamepad; + + switch (event->type) { + case SDL_EVENT_JOYSTICK_AXIS_MOTION: + { + SDL_AssertJoysticksLocked(); + + for (gamepad = SDL_gamepads; gamepad; gamepad = gamepad->next) { + if (gamepad->joystick->instance_id == event->jaxis.which) { + HandleJoystickAxis(event->common.timestamp, gamepad, event->jaxis.axis, event->jaxis.value); + break; + } + } + } break; + case SDL_EVENT_JOYSTICK_BUTTON_DOWN: + case SDL_EVENT_JOYSTICK_BUTTON_UP: + { + SDL_AssertJoysticksLocked(); + + for (gamepad = SDL_gamepads; gamepad; gamepad = gamepad->next) { + if (gamepad->joystick->instance_id == event->jbutton.which) { + HandleJoystickButton(event->common.timestamp, gamepad, event->jbutton.button, event->jbutton.down); + break; + } + } + } break; + case SDL_EVENT_JOYSTICK_HAT_MOTION: + { + SDL_AssertJoysticksLocked(); + + for (gamepad = SDL_gamepads; gamepad; gamepad = gamepad->next) { + if (gamepad->joystick->instance_id == event->jhat.which) { + HandleJoystickHat(event->common.timestamp, gamepad, event->jhat.hat, event->jhat.value); + break; + } + } + } break; + case SDL_EVENT_JOYSTICK_UPDATE_COMPLETE: + { + SDL_AssertJoysticksLocked(); + + if (SDL_EventEnabled(SDL_EVENT_GAMEPAD_UPDATE_COMPLETE)) { + for (gamepad = SDL_gamepads; gamepad; gamepad = gamepad->next) { + if (gamepad->joystick->instance_id == event->jdevice.which) { + SDL_Event deviceevent; + + deviceevent.type = SDL_EVENT_GAMEPAD_UPDATE_COMPLETE; + deviceevent.common.timestamp = event->jdevice.timestamp; + deviceevent.gdevice.which = event->jdevice.which; + SDL_PushEvent(&deviceevent); + break; + } + } + } + } break; + default: + break; + } + + return true; +} + +/* SDL defines sensor orientation relative to the device natural + orientation, so when it's changed orientation to be used as a + gamepad, change the sensor orientation to match. + */ +static void AdjustSensorOrientation(const SDL_Joystick *joystick, const float *src, float *dst) +{ + unsigned int i, j; + + SDL_AssertJoysticksLocked(); + + for (i = 0; i < 3; ++i) { + dst[i] = 0.0f; + for (j = 0; j < 3; ++j) { + dst[i] += joystick->sensor_transform[i][j] * src[j]; + } + } +} + +/* + * Event filter to fire gamepad sensor events from system sensor events + * + * We don't use SDL_GamepadEventWatcher() for this because we want to + * deliver gamepad sensor events when system sensor events are disabled, + * and we also need to avoid a potential deadlock where joystick event + * delivery locks the joysticks and then the event queue, but sensor + * event delivery would lock the event queue and then from within the + * event watcher function lock the joysticks. + */ +void SDL_GamepadSensorWatcher(Uint64 timestamp, SDL_SensorID sensor, Uint64 sensor_timestamp, float *data, int num_values) +{ + SDL_Gamepad *gamepad; + + SDL_LockJoysticks(); + for (gamepad = SDL_gamepads; gamepad; gamepad = gamepad->next) { + if (gamepad->joystick->accel && gamepad->joystick->accel_sensor == sensor) { + float gamepad_data[3]; + AdjustSensorOrientation(gamepad->joystick, data, gamepad_data); + SDL_SendJoystickSensor(timestamp, gamepad->joystick, SDL_SENSOR_ACCEL, sensor_timestamp, gamepad_data, SDL_arraysize(gamepad_data)); + } + if (gamepad->joystick->gyro && gamepad->joystick->gyro_sensor == sensor) { + float gamepad_data[3]; + AdjustSensorOrientation(gamepad->joystick, data, gamepad_data); + SDL_SendJoystickSensor(timestamp, gamepad->joystick, SDL_SENSOR_GYRO, sensor_timestamp, gamepad_data, SDL_arraysize(gamepad_data)); + } + } + SDL_UnlockJoysticks(); +} + +static void PushMappingChangeTracking(void) +{ + MappingChangeTracker *tracker; + int i, num_joysticks; + + SDL_AssertJoysticksLocked(); + + if (s_mappingChangeTracker) { + ++s_mappingChangeTracker->refcount; + return; + } + s_mappingChangeTracker = (MappingChangeTracker *)SDL_calloc(1, sizeof(*tracker)); + s_mappingChangeTracker->refcount = 1; + + // Save the list of joysticks and associated mappings + tracker = s_mappingChangeTracker; + tracker->joysticks = SDL_GetJoysticks(&num_joysticks); + if (!tracker->joysticks) { + return; + } + if (num_joysticks == 0) { + return; + } + tracker->joystick_mappings = (GamepadMapping_t **)SDL_malloc(num_joysticks * sizeof(*tracker->joystick_mappings)); + if (!tracker->joystick_mappings) { + return; + } + for (i = 0; i < num_joysticks; ++i) { + tracker->joystick_mappings[i] = SDL_PrivateGetGamepadMapping(tracker->joysticks[i], false); + } +} + +static void AddMappingChangeTracking(GamepadMapping_t *mapping) +{ + MappingChangeTracker *tracker; + int num_mappings; + GamepadMapping_t **new_mappings; + + SDL_AssertJoysticksLocked(); + + SDL_assert(s_mappingChangeTracker != NULL); + tracker = s_mappingChangeTracker; + num_mappings = tracker->num_changed_mappings; + new_mappings = (GamepadMapping_t **)SDL_realloc(tracker->changed_mappings, (num_mappings + 1) * sizeof(*new_mappings)); + if (new_mappings) { + tracker->changed_mappings = new_mappings; + tracker->changed_mappings[num_mappings] = mapping; + tracker->num_changed_mappings = (num_mappings + 1); + } +} + +static bool HasMappingChangeTracking(MappingChangeTracker *tracker, GamepadMapping_t *mapping) +{ + int i; + + SDL_AssertJoysticksLocked(); + + for (i = 0; i < tracker->num_changed_mappings; ++i) { + if (tracker->changed_mappings[i] == mapping) { + return true; + } + } + return false; +} + +static void PopMappingChangeTracking(void) +{ + int i; + MappingChangeTracker *tracker; + + SDL_AssertJoysticksLocked(); + + SDL_assert(s_mappingChangeTracker != NULL); + tracker = s_mappingChangeTracker; + --tracker->refcount; + if (tracker->refcount > 0) { + return; + } + s_mappingChangeTracker = NULL; + + // Now check to see what gamepads changed because of the mapping changes + if (tracker->joysticks && tracker->joystick_mappings) { + for (i = 0; tracker->joysticks[i]; ++i) { + // Looking up the new mapping might create one and associate it with the gamepad (and generate events) + SDL_JoystickID joystick = tracker->joysticks[i]; + SDL_Gamepad *gamepad = SDL_GetGamepadFromID(joystick); + GamepadMapping_t *new_mapping = SDL_PrivateGetGamepadMapping(joystick, false); + GamepadMapping_t *old_mapping = gamepad ? gamepad->mapping : tracker->joystick_mappings[i]; + + if (new_mapping && !old_mapping) { + SDL_InsertIntoHashTable(s_gamepadInstanceIDs, (void *)(uintptr_t)joystick, (const void *)true, true); + SDL_PrivateGamepadAdded(joystick); + } else if (old_mapping && !new_mapping) { + SDL_InsertIntoHashTable(s_gamepadInstanceIDs, (void *)(uintptr_t)joystick, (const void *)false, true); + SDL_PrivateGamepadRemoved(joystick); + } else if (old_mapping != new_mapping || HasMappingChangeTracking(tracker, new_mapping)) { + if (gamepad) { + SDL_PrivateLoadButtonMapping(gamepad, new_mapping); + } + SDL_PrivateGamepadRemapped(joystick); + } + } + } + + SDL_free(tracker->joysticks); + SDL_free(tracker->joystick_mappings); + SDL_free(tracker->changed_mappings); + SDL_free(tracker); +} + +#ifdef SDL_PLATFORM_ANDROID +/* + * Helper function to guess at a mapping based on the elements reported for this gamepad + */ +static GamepadMapping_t *SDL_CreateMappingForAndroidGamepad(SDL_GUID guid) +{ + const int face_button_mask = ((1 << SDL_GAMEPAD_BUTTON_SOUTH) | + (1 << SDL_GAMEPAD_BUTTON_EAST) | + (1 << SDL_GAMEPAD_BUTTON_WEST) | + (1 << SDL_GAMEPAD_BUTTON_NORTH)); + bool existing; + char mapping_string[1024]; + int button_mask; + int axis_mask; + + button_mask = SDL_Swap16LE(*(Uint16 *)(&guid.data[sizeof(guid.data) - 4])); + axis_mask = SDL_Swap16LE(*(Uint16 *)(&guid.data[sizeof(guid.data) - 2])); + if (!button_mask && !axis_mask) { + // Accelerometer, shouldn't have a gamepad mapping + return NULL; + } + if (!(button_mask & face_button_mask)) { + // We don't know what buttons or axes are supported, don't make up a mapping + return NULL; + } + + SDL_strlcpy(mapping_string, "none,*,", sizeof(mapping_string)); + + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_SOUTH)) { + SDL_strlcat(mapping_string, "a:b0,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_EAST)) { + SDL_strlcat(mapping_string, "b:b1,", sizeof(mapping_string)); + } else if (button_mask & (1 << SDL_GAMEPAD_BUTTON_BACK)) { + // Use the back button as "B" for easy UI navigation with TV remotes + SDL_strlcat(mapping_string, "b:b4,", sizeof(mapping_string)); + button_mask &= ~(1 << SDL_GAMEPAD_BUTTON_BACK); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_WEST)) { + SDL_strlcat(mapping_string, "x:b2,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_NORTH)) { + SDL_strlcat(mapping_string, "y:b3,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_BACK)) { + SDL_strlcat(mapping_string, "back:b4,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_GUIDE)) { + // The guide button generally isn't functional (or acts as a home button) on most Android gamepads before Android 11 + if (SDL_GetAndroidSDKVersion() >= 30 /* Android 11 */) { + SDL_strlcat(mapping_string, "guide:b5,", sizeof(mapping_string)); + } + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_START)) { + SDL_strlcat(mapping_string, "start:b6,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_LEFT_STICK)) { + SDL_strlcat(mapping_string, "leftstick:b7,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_RIGHT_STICK)) { + SDL_strlcat(mapping_string, "rightstick:b8,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_LEFT_SHOULDER)) { + SDL_strlcat(mapping_string, "leftshoulder:b9,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER)) { + SDL_strlcat(mapping_string, "rightshoulder:b10,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_DPAD_UP)) { + SDL_strlcat(mapping_string, "dpup:b11,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_DPAD_DOWN)) { + SDL_strlcat(mapping_string, "dpdown:b12,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_DPAD_LEFT)) { + SDL_strlcat(mapping_string, "dpleft:b13,", sizeof(mapping_string)); + } + if (button_mask & (1 << SDL_GAMEPAD_BUTTON_DPAD_RIGHT)) { + SDL_strlcat(mapping_string, "dpright:b14,", sizeof(mapping_string)); + } + if (axis_mask & (1 << SDL_GAMEPAD_AXIS_LEFTX)) { + SDL_strlcat(mapping_string, "leftx:a0,", sizeof(mapping_string)); + } + if (axis_mask & (1 << SDL_GAMEPAD_AXIS_LEFTY)) { + SDL_strlcat(mapping_string, "lefty:a1,", sizeof(mapping_string)); + } + if (axis_mask & (1 << SDL_GAMEPAD_AXIS_RIGHTX)) { + SDL_strlcat(mapping_string, "rightx:a2,", sizeof(mapping_string)); + } + if (axis_mask & (1 << SDL_GAMEPAD_AXIS_RIGHTY)) { + SDL_strlcat(mapping_string, "righty:a3,", sizeof(mapping_string)); + } + if (axis_mask & (1 << SDL_GAMEPAD_AXIS_LEFT_TRIGGER)) { + SDL_strlcat(mapping_string, "lefttrigger:a4,", sizeof(mapping_string)); + } + if (axis_mask & (1 << SDL_GAMEPAD_AXIS_RIGHT_TRIGGER)) { + SDL_strlcat(mapping_string, "righttrigger:a5,", sizeof(mapping_string)); + } + + return SDL_PrivateAddMappingForGUID(guid, mapping_string, &existing, SDL_GAMEPAD_MAPPING_PRIORITY_DEFAULT); +} +#endif // SDL_PLATFORM_ANDROID + +/* + * Helper function to guess at a mapping for HIDAPI gamepads + */ +static GamepadMapping_t *SDL_CreateMappingForHIDAPIGamepad(SDL_GUID guid) +{ + bool existing; + char mapping_string[1024]; + Uint16 vendor; + Uint16 product; + + SDL_strlcpy(mapping_string, "none,*,", sizeof(mapping_string)); + + SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL, NULL); + + if ((vendor == USB_VENDOR_NINTENDO && product == USB_PRODUCT_NINTENDO_GAMECUBE_ADAPTER) || + (vendor == USB_VENDOR_DRAGONRISE && + (product == USB_PRODUCT_EVORETRO_GAMECUBE_ADAPTER1 || + product == USB_PRODUCT_EVORETRO_GAMECUBE_ADAPTER2))) { + // GameCube driver has 12 buttons and 6 axes + SDL_strlcat(mapping_string, "a:b0,b:b1,dpdown:b6,dpleft:b4,dpright:b5,dpup:b7,lefttrigger:a4,leftx:a0,lefty:a1~,rightshoulder:b9,righttrigger:a5,rightx:a2,righty:a3~,start:b8,x:b2,y:b3,", sizeof(mapping_string)); + } else if (vendor == USB_VENDOR_NINTENDO && + (guid.data[15] == k_eSwitchDeviceInfoControllerType_HVCLeft || + guid.data[15] == k_eSwitchDeviceInfoControllerType_HVCRight || + guid.data[15] == k_eSwitchDeviceInfoControllerType_NESLeft || + guid.data[15] == k_eSwitchDeviceInfoControllerType_NESRight || + guid.data[15] == k_eSwitchDeviceInfoControllerType_SNES || + guid.data[15] == k_eSwitchDeviceInfoControllerType_N64 || + guid.data[15] == k_eSwitchDeviceInfoControllerType_SEGA_Genesis || + guid.data[15] == k_eWiiExtensionControllerType_None || + guid.data[15] == k_eWiiExtensionControllerType_Nunchuk || + guid.data[15] == k_eSwitchDeviceInfoControllerType_JoyConLeft || + guid.data[15] == k_eSwitchDeviceInfoControllerType_JoyConRight)) { + switch (guid.data[15]) { + case k_eSwitchDeviceInfoControllerType_HVCLeft: + SDL_strlcat(mapping_string, "a:b0,b:b1,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,rightshoulder:b10,start:b6,", sizeof(mapping_string)); + break; + case k_eSwitchDeviceInfoControllerType_HVCRight: + SDL_strlcat(mapping_string, "a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,rightshoulder:b10,", sizeof(mapping_string)); + break; + case k_eSwitchDeviceInfoControllerType_NESLeft: + case k_eSwitchDeviceInfoControllerType_NESRight: + SDL_strlcat(mapping_string, "a:b0,b:b1,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,rightshoulder:b10,start:b6,", sizeof(mapping_string)); + break; + case k_eSwitchDeviceInfoControllerType_SNES: + SDL_strlcat(mapping_string, "a:b0,b:b1,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,lefttrigger:a4,rightshoulder:b10,righttrigger:a5,start:b6,x:b2,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", sizeof(mapping_string)); + break; + case k_eSwitchDeviceInfoControllerType_N64: + SDL_strlcat(mapping_string, "a:b0,b:b1,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,righttrigger:a5,start:b6,x:b2,y:b3,misc1:b11,", sizeof(mapping_string)); + break; + case k_eSwitchDeviceInfoControllerType_SEGA_Genesis: + SDL_strlcat(mapping_string, "a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b9,rightshoulder:b10,righttrigger:a5,start:b6,x:b2,y:b3,misc1:b11,", sizeof(mapping_string)); + break; + case k_eWiiExtensionControllerType_None: + SDL_strlcat(mapping_string, "a:b0,b:b1,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,start:b6,x:b2,y:b3,", sizeof(mapping_string)); + break; + case k_eWiiExtensionControllerType_Nunchuk: + { + // FIXME: Should we map this to the left or right side? + const bool map_nunchuck_left_side = true; + + if (map_nunchuck_left_side) { + SDL_strlcat(mapping_string, "a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,lefttrigger:a4,leftx:a0,lefty:a1,start:b6,x:b2,y:b3,", sizeof(mapping_string)); + } else { + SDL_strlcat(mapping_string, "a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,rightshoulder:b9,righttrigger:a4,rightx:a0,righty:a1,start:b6,x:b2,y:b3,", sizeof(mapping_string)); + } + } break; + default: + if (SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_VERTICAL_JOY_CONS, false)) { + // Vertical mode + if (guid.data[15] == k_eSwitchDeviceInfoControllerType_JoyConLeft) { + SDL_strlcat(mapping_string, "back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,misc1:b11,paddle2:b13,paddle4:b15,", sizeof(mapping_string)); + } else { + SDL_strlcat(mapping_string, "a:b0,b:b1,guide:b5,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,paddle1:b12,paddle3:b14,", sizeof(mapping_string)); + } + } else { + // Mini gamepad mode + if (guid.data[15] == k_eSwitchDeviceInfoControllerType_JoyConLeft) { + SDL_strlcat(mapping_string, "a:b0,b:b1,guide:b5,leftshoulder:b9,leftstick:b7,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b2,y:b3,paddle2:b13,paddle4:b15,", sizeof(mapping_string)); + } else { + SDL_strlcat(mapping_string, "a:b0,b:b1,guide:b5,leftshoulder:b9,leftstick:b7,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b2,y:b3,paddle1:b12,paddle3:b14,", sizeof(mapping_string)); + } + } + break; + } + } else { + // All other gamepads have the standard set of 19 buttons and 6 axes + SDL_strlcat(mapping_string, "a:b0,b:b1,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", sizeof(mapping_string)); + + if (SDL_IsJoystickSteamController(vendor, product)) { + // Steam controllers have 2 back paddle buttons + SDL_strlcat(mapping_string, "paddle1:b12,paddle2:b11,", sizeof(mapping_string)); + } else if (SDL_IsJoystickNintendoSwitchPro(vendor, product) || + SDL_IsJoystickNintendoSwitchProInputOnly(vendor, product)) { + // Nintendo Switch Pro controllers have a screenshot button + SDL_strlcat(mapping_string, "misc1:b11,", sizeof(mapping_string)); + } else if (SDL_IsJoystickNintendoSwitchJoyConPair(vendor, product)) { + // The Nintendo Switch Joy-Con combined controllers has a share button and paddles + SDL_strlcat(mapping_string, "misc1:b11,paddle1:b12,paddle2:b13,paddle3:b14,paddle4:b15,", sizeof(mapping_string)); + } else if (SDL_IsJoystickAmazonLunaController(vendor, product)) { + // Amazon Luna Controller has a mic button under the guide button + SDL_strlcat(mapping_string, "misc1:b11,", sizeof(mapping_string)); + } else if (SDL_IsJoystickGoogleStadiaController(vendor, product)) { + // The Google Stadia controller has a share button and a Google Assistant button + SDL_strlcat(mapping_string, "misc1:b11,misc2:b12", sizeof(mapping_string)); + } else if (SDL_IsJoystickNVIDIASHIELDController(vendor, product)) { + // The NVIDIA SHIELD controller has a share button between back and start buttons + SDL_strlcat(mapping_string, "misc1:b11,", sizeof(mapping_string)); + + if (product == USB_PRODUCT_NVIDIA_SHIELD_CONTROLLER_V103) { + // The original SHIELD controller has a touchpad and plus/minus buttons as well + SDL_strlcat(mapping_string, "touchpad:b12,misc2:b13,misc3:b14", sizeof(mapping_string)); + } + } else if (SDL_IsJoystickHoriSteamController(vendor, product)) { + /* The Wireless HORIPad for Steam has QAM, Steam, Capsense L/R Sticks, 2 rear buttons, and 2 misc buttons */ + SDL_strlcat(mapping_string, "paddle1:b13,paddle2:b12,paddle3:b15,paddle4:b14,misc2:b11,misc3:b16,misc4:b17", sizeof(mapping_string)); + } else { + switch (SDL_GetGamepadTypeFromGUID(guid, NULL)) { + case SDL_GAMEPAD_TYPE_PS4: + // PS4 controllers have an additional touchpad button + SDL_strlcat(mapping_string, "touchpad:b11,", sizeof(mapping_string)); + break; + case SDL_GAMEPAD_TYPE_PS5: + // PS5 controllers have a microphone button and an additional touchpad button + SDL_strlcat(mapping_string, "touchpad:b11,misc1:b12,", sizeof(mapping_string)); + // DualSense Edge controllers have paddles + if (SDL_IsJoystickDualSenseEdge(vendor, product)) { + SDL_strlcat(mapping_string, "paddle1:b16,paddle2:b15,paddle3:b14,paddle4:b13,", sizeof(mapping_string)); + } + break; + case SDL_GAMEPAD_TYPE_XBOXONE: + if (SDL_IsJoystickXboxOneElite(vendor, product)) { + // XBox One Elite Controllers have 4 back paddle buttons + SDL_strlcat(mapping_string, "paddle1:b11,paddle2:b13,paddle3:b12,paddle4:b14,", sizeof(mapping_string)); + } else if (SDL_IsJoystickXboxSeriesX(vendor, product)) { + // XBox Series X Controllers have a share button under the guide button + SDL_strlcat(mapping_string, "misc1:b11,", sizeof(mapping_string)); + } + break; + default: + if (vendor == 0 && product == 0) { + // This is a Bluetooth Nintendo Switch Pro controller + SDL_strlcat(mapping_string, "misc1:b11,", sizeof(mapping_string)); + } + break; + } + } + } + + return SDL_PrivateAddMappingForGUID(guid, mapping_string, &existing, SDL_GAMEPAD_MAPPING_PRIORITY_DEFAULT); +} + +/* + * Helper function to guess at a mapping for RAWINPUT gamepads + */ +static GamepadMapping_t *SDL_CreateMappingForRAWINPUTGamepad(SDL_GUID guid) +{ + bool existing; + char mapping_string[1024]; + + SDL_strlcpy(mapping_string, "none,*,", sizeof(mapping_string)); + SDL_strlcat(mapping_string, "a:b0,b:b1,x:b2,y:b3,back:b6,guide:b10,start:b7,leftstick:b8,rightstick:b9,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a4,righttrigger:a5,", sizeof(mapping_string)); + + return SDL_PrivateAddMappingForGUID(guid, mapping_string, &existing, SDL_GAMEPAD_MAPPING_PRIORITY_DEFAULT); +} + +/* + * Helper function to guess at a mapping for WGI gamepads + */ +static GamepadMapping_t *SDL_CreateMappingForWGIGamepad(SDL_GUID guid) +{ + bool existing; + char mapping_string[1024]; + + if (guid.data[15] != SDL_JOYSTICK_TYPE_GAMEPAD) { + return NULL; + } + + SDL_strlcpy(mapping_string, "none,*,", sizeof(mapping_string)); + SDL_strlcat(mapping_string, "a:b0,b:b1,x:b2,y:b3,back:b6,start:b7,leftstick:b8,rightstick:b9,leftshoulder:b4,rightshoulder:b5,dpup:b10,dpdown:b12,dpleft:b13,dpright:b11,leftx:a1,lefty:a0~,rightx:a3,righty:a2~,lefttrigger:a4,righttrigger:a5,", sizeof(mapping_string)); + + return SDL_PrivateAddMappingForGUID(guid, mapping_string, &existing, SDL_GAMEPAD_MAPPING_PRIORITY_DEFAULT); +} + +/* + * Helper function to scan the mappings database for a gamepad with the specified GUID + */ +static GamepadMapping_t *SDL_PrivateMatchGamepadMappingForGUID(SDL_GUID guid, bool match_version, bool exact_match_crc) +{ + GamepadMapping_t *mapping, *best_match = NULL; + Uint16 crc = 0; + + SDL_AssertJoysticksLocked(); + + SDL_GetJoystickGUIDInfo(guid, NULL, NULL, NULL, &crc); + + // Clear the CRC from the GUID for matching, the mappings never include it in the GUID + SDL_SetJoystickGUIDCRC(&guid, 0); + + if (!match_version) { + SDL_SetJoystickGUIDVersion(&guid, 0); + } + + for (mapping = s_pSupportedGamepads; mapping; mapping = mapping->next) { + SDL_GUID mapping_guid; + + if (SDL_memcmp(&mapping->guid, &s_zeroGUID, sizeof(mapping->guid)) == 0) { + continue; + } + + SDL_memcpy(&mapping_guid, &mapping->guid, sizeof(mapping_guid)); + if (!match_version) { + SDL_SetJoystickGUIDVersion(&mapping_guid, 0); + } + + if (SDL_memcmp(&guid, &mapping_guid, sizeof(guid)) == 0) { + const char *crc_string = SDL_strstr(mapping->mapping, SDL_GAMEPAD_CRC_FIELD); + if (crc_string) { + Uint16 mapping_crc = (Uint16)SDL_strtol(crc_string + SDL_GAMEPAD_CRC_FIELD_SIZE, NULL, 16); + if (mapping_crc != crc) { + // This mapping specified a CRC and they don't match + continue; + } + + // An exact match, including CRC + return mapping; + } else if (crc && exact_match_crc) { + return NULL; + } + + if (!best_match) { + best_match = mapping; + } + } + } + return best_match; +} + +/* + * Helper function to scan the mappings database for a gamepad with the specified GUID + */ +static GamepadMapping_t *SDL_PrivateGetGamepadMappingForGUID(SDL_GUID guid, bool adding_mapping) +{ + GamepadMapping_t *mapping; + + mapping = SDL_PrivateMatchGamepadMappingForGUID(guid, true, adding_mapping); + if (mapping) { + return mapping; + } + + if (adding_mapping) { + // We didn't find an existing mapping + return NULL; + } + + // Try harder to get the best match, or create a mapping + + if (SDL_JoystickGUIDUsesVersion(guid)) { + // Try again, ignoring the version + mapping = SDL_PrivateMatchGamepadMappingForGUID(guid, false, false); + if (mapping) { + return mapping; + } + } + +#ifdef SDL_JOYSTICK_XINPUT + if (SDL_IsJoystickXInput(guid)) { + // This is an XInput device + return s_pXInputMapping; + } +#endif + if (SDL_IsJoystickHIDAPI(guid)) { + mapping = SDL_CreateMappingForHIDAPIGamepad(guid); + } else if (SDL_IsJoystickRAWINPUT(guid)) { + mapping = SDL_CreateMappingForRAWINPUTGamepad(guid); + } else if (SDL_IsJoystickWGI(guid)) { + mapping = SDL_CreateMappingForWGIGamepad(guid); + } else if (SDL_IsJoystickVIRTUAL(guid)) { + // We'll pick up a robust mapping in VIRTUAL_JoystickGetGamepadMapping +#ifdef SDL_PLATFORM_ANDROID + } else { + mapping = SDL_CreateMappingForAndroidGamepad(guid); +#endif + } + return mapping; +} + +static const char *map_StringForGamepadType[] = { + "unknown", + "standard", + "xbox360", + "xboxone", + "ps3", + "ps4", + "ps5", + "switchpro", + "joyconleft", + "joyconright", + "joyconpair" +}; +SDL_COMPILE_TIME_ASSERT(map_StringForGamepadType, SDL_arraysize(map_StringForGamepadType) == SDL_GAMEPAD_TYPE_COUNT); + +/* + * convert a string to its enum equivalent + */ +SDL_GamepadType SDL_GetGamepadTypeFromString(const char *str) +{ + int i; + + if (!str || str[0] == '\0') { + return SDL_GAMEPAD_TYPE_UNKNOWN; + } + + if (*str == '+' || *str == '-') { + ++str; + } + + for (i = 0; i < SDL_arraysize(map_StringForGamepadType); ++i) { + if (SDL_strcasecmp(str, map_StringForGamepadType[i]) == 0) { + return (SDL_GamepadType)i; + } + } + return SDL_GAMEPAD_TYPE_UNKNOWN; +} + +/* + * convert an enum to its string equivalent + */ +const char *SDL_GetGamepadStringForType(SDL_GamepadType type) +{ + if (type >= SDL_GAMEPAD_TYPE_STANDARD && type < SDL_GAMEPAD_TYPE_COUNT) { + return map_StringForGamepadType[type]; + } + return NULL; +} + +static const char *map_StringForGamepadAxis[] = { + "leftx", + "lefty", + "rightx", + "righty", + "lefttrigger", + "righttrigger" +}; +SDL_COMPILE_TIME_ASSERT(map_StringForGamepadAxis, SDL_arraysize(map_StringForGamepadAxis) == SDL_GAMEPAD_AXIS_COUNT); + +/* + * convert a string to its enum equivalent + */ +SDL_GamepadAxis SDL_GetGamepadAxisFromString(const char *str) +{ + int i; + + if (!str || str[0] == '\0') { + return SDL_GAMEPAD_AXIS_INVALID; + } + + if (*str == '+' || *str == '-') { + ++str; + } + + for (i = 0; i < SDL_arraysize(map_StringForGamepadAxis); ++i) { + if (SDL_strcasecmp(str, map_StringForGamepadAxis[i]) == 0) { + return (SDL_GamepadAxis)i; + } + } + return SDL_GAMEPAD_AXIS_INVALID; +} + +/* + * convert an enum to its string equivalent + */ +const char *SDL_GetGamepadStringForAxis(SDL_GamepadAxis axis) +{ + if (axis > SDL_GAMEPAD_AXIS_INVALID && axis < SDL_GAMEPAD_AXIS_COUNT) { + return map_StringForGamepadAxis[axis]; + } + return NULL; +} + +static const char *map_StringForGamepadButton[] = { + "a", + "b", + "x", + "y", + "back", + "guide", + "start", + "leftstick", + "rightstick", + "leftshoulder", + "rightshoulder", + "dpup", + "dpdown", + "dpleft", + "dpright", + "misc1", + "paddle1", + "paddle2", + "paddle3", + "paddle4", + "touchpad", + "misc2", + "misc3", + "misc4", + "misc5", + "misc6" +}; +SDL_COMPILE_TIME_ASSERT(map_StringForGamepadButton, SDL_arraysize(map_StringForGamepadButton) == SDL_GAMEPAD_BUTTON_COUNT); + +/* + * convert a string to its enum equivalent + */ +static SDL_GamepadButton SDL_PrivateGetGamepadButtonFromString(const char *str, bool baxy) +{ + int i; + + if (!str || str[0] == '\0') { + return SDL_GAMEPAD_BUTTON_INVALID; + } + + for (i = 0; i < SDL_arraysize(map_StringForGamepadButton); ++i) { + if (SDL_strcasecmp(str, map_StringForGamepadButton[i]) == 0) { + if (baxy) { + // Need to swap face buttons + switch (i) { + case SDL_GAMEPAD_BUTTON_SOUTH: + return SDL_GAMEPAD_BUTTON_EAST; + case SDL_GAMEPAD_BUTTON_EAST: + return SDL_GAMEPAD_BUTTON_SOUTH; + case SDL_GAMEPAD_BUTTON_WEST: + return SDL_GAMEPAD_BUTTON_NORTH; + case SDL_GAMEPAD_BUTTON_NORTH: + return SDL_GAMEPAD_BUTTON_WEST; + default: + break; + } + } + return (SDL_GamepadButton)i; + } + } + return SDL_GAMEPAD_BUTTON_INVALID; +} +SDL_GamepadButton SDL_GetGamepadButtonFromString(const char *str) +{ + return SDL_PrivateGetGamepadButtonFromString(str, false); +} + +/* + * convert an enum to its string equivalent + */ +const char *SDL_GetGamepadStringForButton(SDL_GamepadButton button) +{ + if (button > SDL_GAMEPAD_BUTTON_INVALID && button < SDL_GAMEPAD_BUTTON_COUNT) { + return map_StringForGamepadButton[button]; + } + return NULL; +} + +/* + * given a gamepad button name and a joystick name update our mapping structure with it + */ +static bool SDL_PrivateParseGamepadElement(SDL_Gamepad *gamepad, const char *szGameButton, const char *szJoystickButton) +{ + SDL_GamepadBinding bind; + SDL_GamepadButton button; + SDL_GamepadAxis axis; + bool invert_input = false; + char half_axis_input = 0; + char half_axis_output = 0; + int i; + SDL_GamepadBinding *new_bindings; + bool baxy_mapping = false; + + SDL_AssertJoysticksLocked(); + + SDL_zero(bind); + + if (*szGameButton == '+' || *szGameButton == '-') { + half_axis_output = *szGameButton++; + } + + if (SDL_strstr(gamepad->mapping->mapping, ",hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1") != NULL) { + baxy_mapping = true; + } + + axis = SDL_GetGamepadAxisFromString(szGameButton); + button = SDL_PrivateGetGamepadButtonFromString(szGameButton, baxy_mapping); + if (axis != SDL_GAMEPAD_AXIS_INVALID) { + bind.output_type = SDL_GAMEPAD_BINDTYPE_AXIS; + bind.output.axis.axis = axis; + if (axis == SDL_GAMEPAD_AXIS_LEFT_TRIGGER || axis == SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) { + bind.output.axis.axis_min = 0; + bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MAX; + } else { + if (half_axis_output == '+') { + bind.output.axis.axis_min = 0; + bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MAX; + } else if (half_axis_output == '-') { + bind.output.axis.axis_min = 0; + bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MIN; + } else { + bind.output.axis.axis_min = SDL_JOYSTICK_AXIS_MIN; + bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MAX; + } + } + } else if (button != SDL_GAMEPAD_BUTTON_INVALID) { + bind.output_type = SDL_GAMEPAD_BINDTYPE_BUTTON; + bind.output.button = button; + } else { + return false; + } + + if (*szJoystickButton == '+' || *szJoystickButton == '-') { + half_axis_input = *szJoystickButton++; + } + if (szJoystickButton[SDL_strlen(szJoystickButton) - 1] == '~') { + invert_input = true; + } + + if (szJoystickButton[0] == 'a' && SDL_isdigit((unsigned char)szJoystickButton[1])) { + bind.input_type = SDL_GAMEPAD_BINDTYPE_AXIS; + bind.input.axis.axis = SDL_atoi(&szJoystickButton[1]); + if (half_axis_input == '+') { + bind.input.axis.axis_min = 0; + bind.input.axis.axis_max = SDL_JOYSTICK_AXIS_MAX; + } else if (half_axis_input == '-') { + bind.input.axis.axis_min = 0; + bind.input.axis.axis_max = SDL_JOYSTICK_AXIS_MIN; + } else { + bind.input.axis.axis_min = SDL_JOYSTICK_AXIS_MIN; + bind.input.axis.axis_max = SDL_JOYSTICK_AXIS_MAX; + } + if (invert_input) { + int tmp = bind.input.axis.axis_min; + bind.input.axis.axis_min = bind.input.axis.axis_max; + bind.input.axis.axis_max = tmp; + } + } else if (szJoystickButton[0] == 'b' && SDL_isdigit((unsigned char)szJoystickButton[1])) { + bind.input_type = SDL_GAMEPAD_BINDTYPE_BUTTON; + bind.input.button = SDL_atoi(&szJoystickButton[1]); + } else if (szJoystickButton[0] == 'h' && SDL_isdigit((unsigned char)szJoystickButton[1]) && + szJoystickButton[2] == '.' && SDL_isdigit((unsigned char)szJoystickButton[3])) { + int hat = SDL_atoi(&szJoystickButton[1]); + int mask = SDL_atoi(&szJoystickButton[3]); + bind.input_type = SDL_GAMEPAD_BINDTYPE_HAT; + bind.input.hat.hat = hat; + bind.input.hat.hat_mask = mask; + } else { + return false; + } + + for (i = 0; i < gamepad->num_bindings; ++i) { + if (SDL_memcmp(&gamepad->bindings[i], &bind, sizeof(bind)) == 0) { + // We already have this binding, could be different face button names? + return true; + } + } + + ++gamepad->num_bindings; + new_bindings = (SDL_GamepadBinding *)SDL_realloc(gamepad->bindings, gamepad->num_bindings * sizeof(*gamepad->bindings)); + if (!new_bindings) { + SDL_free(gamepad->bindings); + gamepad->num_bindings = 0; + gamepad->bindings = NULL; + return false; + } + gamepad->bindings = new_bindings; + gamepad->bindings[gamepad->num_bindings - 1] = bind; + return true; +} + +/* + * given a gamepad mapping string update our mapping object + */ +static bool SDL_PrivateParseGamepadConfigString(SDL_Gamepad *gamepad, const char *pchString) +{ + char szGameButton[20]; + char szJoystickButton[20]; + bool bGameButton = true; + int i = 0; + const char *pchPos = pchString; + + SDL_zeroa(szGameButton); + SDL_zeroa(szJoystickButton); + + while (pchPos && *pchPos) { + if (*pchPos == ':') { + i = 0; + bGameButton = false; + } else if (*pchPos == ' ') { + + } else if (*pchPos == ',') { + i = 0; + bGameButton = true; + SDL_PrivateParseGamepadElement(gamepad, szGameButton, szJoystickButton); + SDL_zeroa(szGameButton); + SDL_zeroa(szJoystickButton); + + } else if (bGameButton) { + if (i >= sizeof(szGameButton)) { + szGameButton[sizeof(szGameButton) - 1] = '\0'; + return SDL_SetError("Button name too large: %s", szGameButton); + } + szGameButton[i] = *pchPos; + i++; + } else { + if (i >= sizeof(szJoystickButton)) { + szJoystickButton[sizeof(szJoystickButton) - 1] = '\0'; + return SDL_SetError("Joystick button name too large: %s", szJoystickButton); + } + szJoystickButton[i] = *pchPos; + i++; + } + pchPos++; + } + + // No more values if the string was terminated by a comma. Don't report an error. + if (szGameButton[0] != '\0' || szJoystickButton[0] != '\0') { + SDL_PrivateParseGamepadElement(gamepad, szGameButton, szJoystickButton); + } + return true; +} + +static void SDL_UpdateGamepadType(SDL_Gamepad *gamepad) +{ + char *type_string, *comma; + + SDL_AssertJoysticksLocked(); + + gamepad->type = SDL_GAMEPAD_TYPE_UNKNOWN; + + type_string = SDL_strstr(gamepad->mapping->mapping, SDL_GAMEPAD_TYPE_FIELD); + if (type_string) { + type_string += SDL_GAMEPAD_TYPE_FIELD_SIZE; + comma = SDL_strchr(type_string, ','); + if (comma) { + *comma = '\0'; + gamepad->type = SDL_GetGamepadTypeFromString(type_string); + *comma = ','; + } else { + gamepad->type = SDL_GetGamepadTypeFromString(type_string); + } + } + if (gamepad->type == SDL_GAMEPAD_TYPE_UNKNOWN) { + gamepad->type = SDL_GetRealGamepadTypeForID(gamepad->joystick->instance_id); + } +} + +static SDL_GamepadFaceStyle SDL_GetGamepadFaceStyleFromString(const char *string) +{ + if (SDL_strcmp(string, "abxy") == 0) { + return SDL_GAMEPAD_FACE_STYLE_ABXY; + } else if (SDL_strcmp(string, "bayx") == 0) { + return SDL_GAMEPAD_FACE_STYLE_BAYX; + } else if (SDL_strcmp(string, "sony") == 0) { + return SDL_GAMEPAD_FACE_STYLE_SONY; + } else { + return SDL_GAMEPAD_FACE_STYLE_UNKNOWN; + } +} + +static SDL_GamepadFaceStyle SDL_GetGamepadFaceStyleForGamepadType(SDL_GamepadType type) +{ + switch (type) { + case SDL_GAMEPAD_TYPE_PS3: + case SDL_GAMEPAD_TYPE_PS4: + case SDL_GAMEPAD_TYPE_PS5: + return SDL_GAMEPAD_FACE_STYLE_SONY; + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO: + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT: + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT: + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR: + return SDL_GAMEPAD_FACE_STYLE_BAYX; + default: + return SDL_GAMEPAD_FACE_STYLE_ABXY; + } +} + +static void SDL_UpdateGamepadFaceStyle(SDL_Gamepad *gamepad) +{ + char *face_string, *comma; + + SDL_AssertJoysticksLocked(); + + gamepad->face_style = SDL_GAMEPAD_FACE_STYLE_UNKNOWN; + + face_string = SDL_strstr(gamepad->mapping->mapping, SDL_GAMEPAD_FACE_FIELD); + if (face_string) { + face_string += SDL_GAMEPAD_TYPE_FIELD_SIZE; + comma = SDL_strchr(face_string, ','); + if (comma) { + *comma = '\0'; + gamepad->face_style = SDL_GetGamepadFaceStyleFromString(face_string); + *comma = ','; + } else { + gamepad->face_style = SDL_GetGamepadFaceStyleFromString(face_string); + } + } + + if (gamepad->face_style == SDL_GAMEPAD_FACE_STYLE_UNKNOWN && + SDL_strstr(gamepad->mapping->mapping, "SDL_GAMECONTROLLER_USE_BUTTON_LABELS") != NULL) { + // This controller uses Nintendo button style + gamepad->face_style = SDL_GAMEPAD_FACE_STYLE_BAYX; + } + if (gamepad->face_style == SDL_GAMEPAD_FACE_STYLE_UNKNOWN) { + gamepad->face_style = SDL_GetGamepadFaceStyleForGamepadType(gamepad->type); + } +} + +static void SDL_FixupHIDAPIMapping(SDL_Gamepad *gamepad) +{ + // Check to see if we need fixup + bool need_fixup = false; + for (int i = 0; i < gamepad->num_bindings; ++i) { + SDL_GamepadBinding *binding = &gamepad->bindings[i]; + if (binding->output_type == SDL_GAMEPAD_BINDTYPE_BUTTON && + binding->output.button >= SDL_GAMEPAD_BUTTON_DPAD_UP) { + if (binding->input_type == SDL_GAMEPAD_BINDTYPE_BUTTON && + binding->input.button == binding->output.button) { + // Old style binding + need_fixup = true; + } + break; + } + } + if (!need_fixup) { + return; + } + + for (int i = 0; i < gamepad->num_bindings; ++i) { + SDL_GamepadBinding *binding = &gamepad->bindings[i]; + if (binding->input_type == SDL_GAMEPAD_BINDTYPE_BUTTON && + binding->output_type == SDL_GAMEPAD_BINDTYPE_BUTTON) { + switch (binding->output.button) { + case SDL_GAMEPAD_BUTTON_DPAD_UP: + binding->input_type = SDL_GAMEPAD_BINDTYPE_HAT; + binding->input.hat.hat = 0; + binding->input.hat.hat_mask = SDL_HAT_UP; + break; + case SDL_GAMEPAD_BUTTON_DPAD_DOWN: + binding->input_type = SDL_GAMEPAD_BINDTYPE_HAT; + binding->input.hat.hat = 0; + binding->input.hat.hat_mask = SDL_HAT_DOWN; + break; + case SDL_GAMEPAD_BUTTON_DPAD_LEFT: + binding->input_type = SDL_GAMEPAD_BINDTYPE_HAT; + binding->input.hat.hat = 0; + binding->input.hat.hat_mask = SDL_HAT_LEFT; + break; + case SDL_GAMEPAD_BUTTON_DPAD_RIGHT: + binding->input_type = SDL_GAMEPAD_BINDTYPE_HAT; + binding->input.hat.hat = 0; + binding->input.hat.hat_mask = SDL_HAT_RIGHT; + break; + default: + if (binding->output.button > SDL_GAMEPAD_BUTTON_DPAD_RIGHT) { + binding->input.button -= 4; + } + break; + } + } + } +} + +/* + * Make a new button mapping struct + */ +static void SDL_PrivateLoadButtonMapping(SDL_Gamepad *gamepad, GamepadMapping_t *pGamepadMapping) +{ + int i; + + SDL_AssertJoysticksLocked(); + + gamepad->name = pGamepadMapping->name; + gamepad->num_bindings = 0; + gamepad->mapping = pGamepadMapping; + if (gamepad->joystick->naxes != 0 && gamepad->last_match_axis) { + SDL_memset(gamepad->last_match_axis, 0, gamepad->joystick->naxes * sizeof(*gamepad->last_match_axis)); + } + + SDL_UpdateGamepadType(gamepad); + SDL_UpdateGamepadFaceStyle(gamepad); + + SDL_PrivateParseGamepadConfigString(gamepad, pGamepadMapping->mapping); + + if (SDL_IsJoystickHIDAPI(pGamepadMapping->guid)) { + SDL_FixupHIDAPIMapping(gamepad); + } + + // Set the zero point for triggers + for (i = 0; i < gamepad->num_bindings; ++i) { + SDL_GamepadBinding *binding = &gamepad->bindings[i]; + if (binding->input_type == SDL_GAMEPAD_BINDTYPE_AXIS && + binding->output_type == SDL_GAMEPAD_BINDTYPE_AXIS && + (binding->output.axis.axis == SDL_GAMEPAD_AXIS_LEFT_TRIGGER || + binding->output.axis.axis == SDL_GAMEPAD_AXIS_RIGHT_TRIGGER)) { + if (binding->input.axis.axis < gamepad->joystick->naxes) { + gamepad->joystick->axes[binding->input.axis.axis].value = + gamepad->joystick->axes[binding->input.axis.axis].zero = (Sint16)binding->input.axis.axis_min; + } + } + } +} + +/* + * grab the guid string from a mapping string + */ +static char *SDL_PrivateGetGamepadGUIDFromMappingString(const char *pMapping) +{ + const char *pFirstComma = SDL_strchr(pMapping, ','); + if (pFirstComma) { + char *pchGUID = (char *)SDL_malloc(pFirstComma - pMapping + 1); + if (!pchGUID) { + return NULL; + } + SDL_memcpy(pchGUID, pMapping, pFirstComma - pMapping); + pchGUID[pFirstComma - pMapping] = '\0'; + + // Convert old style GUIDs to the new style in 2.0.5 +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) + if (SDL_strlen(pchGUID) == 32 && + SDL_memcmp(&pchGUID[20], "504944564944", 12) == 0) { + SDL_memcpy(&pchGUID[20], "000000000000", 12); + SDL_memcpy(&pchGUID[16], &pchGUID[4], 4); + SDL_memcpy(&pchGUID[8], &pchGUID[0], 4); + SDL_memcpy(&pchGUID[0], "03000000", 8); + } +#elif defined(SDL_PLATFORM_MACOS) + if (SDL_strlen(pchGUID) == 32 && + SDL_memcmp(&pchGUID[4], "000000000000", 12) == 0 && + SDL_memcmp(&pchGUID[20], "000000000000", 12) == 0) { + SDL_memcpy(&pchGUID[20], "000000000000", 12); + SDL_memcpy(&pchGUID[8], &pchGUID[0], 4); + SDL_memcpy(&pchGUID[0], "03000000", 8); + } +#endif + return pchGUID; + } + return NULL; +} + +/* + * grab the name string from a mapping string + */ +static char *SDL_PrivateGetGamepadNameFromMappingString(const char *pMapping) +{ + const char *pFirstComma, *pSecondComma; + char *pchName; + + pFirstComma = SDL_strchr(pMapping, ','); + if (!pFirstComma) { + return NULL; + } + + pSecondComma = SDL_strchr(pFirstComma + 1, ','); + if (!pSecondComma) { + return NULL; + } + + pchName = (char *)SDL_malloc(pSecondComma - pFirstComma); + if (!pchName) { + return NULL; + } + SDL_memcpy(pchName, pFirstComma + 1, pSecondComma - pFirstComma); + pchName[pSecondComma - pFirstComma - 1] = 0; + return pchName; +} + +/* + * grab the button mapping string from a mapping string + */ +static char *SDL_PrivateGetGamepadMappingFromMappingString(const char *pMapping) +{ + const char *pFirstComma, *pSecondComma; + char *result; + size_t length; + + pFirstComma = SDL_strchr(pMapping, ','); + if (!pFirstComma) { + return NULL; + } + + pSecondComma = SDL_strchr(pFirstComma + 1, ','); + if (!pSecondComma) { + return NULL; + } + + // Skip whitespace + while (SDL_isspace(pSecondComma[1])) { + ++pSecondComma; + } + + result = SDL_strdup(pSecondComma + 1); // mapping is everything after the 3rd comma + + // Trim whitespace + length = SDL_strlen(result); + while (length > 0 && SDL_isspace(result[length - 1])) { + --length; + } + result[length] = '\0'; + + return result; +} + +/* + * Helper function to add a mapping for a guid + */ +static GamepadMapping_t *SDL_PrivateAddMappingForGUID(SDL_GUID jGUID, const char *mappingString, bool *existing, SDL_GamepadMappingPriority priority) +{ + char *pchName; + char *pchMapping; + GamepadMapping_t *pGamepadMapping; + Uint16 crc; + + SDL_AssertJoysticksLocked(); + + pchName = SDL_PrivateGetGamepadNameFromMappingString(mappingString); + if (!pchName) { + SDL_SetError("Couldn't parse name from %s", mappingString); + return NULL; + } + + pchMapping = SDL_PrivateGetGamepadMappingFromMappingString(mappingString); + if (!pchMapping) { + SDL_free(pchName); + SDL_SetError("Couldn't parse %s", mappingString); + return NULL; + } + + // Fix up the GUID and the mapping with the CRC, if needed + SDL_GetJoystickGUIDInfo(jGUID, NULL, NULL, NULL, &crc); + if (crc) { + // Make sure the mapping has the CRC + char *new_mapping; + const char *optional_comma; + size_t mapping_length; + char *crc_end = ""; + char *crc_string = SDL_strstr(pchMapping, SDL_GAMEPAD_CRC_FIELD); + if (crc_string) { + crc_end = SDL_strchr(crc_string, ','); + if (crc_end) { + ++crc_end; + } else { + crc_end = ""; + } + *crc_string = '\0'; + } + + // Make sure there's a comma before the CRC + mapping_length = SDL_strlen(pchMapping); + if (mapping_length == 0 || pchMapping[mapping_length - 1] == ',') { + optional_comma = ""; + } else { + optional_comma = ","; + } + + if (SDL_asprintf(&new_mapping, "%s%s%s%.4x,%s", pchMapping, optional_comma, SDL_GAMEPAD_CRC_FIELD, crc, crc_end) >= 0) { + SDL_free(pchMapping); + pchMapping = new_mapping; + } + } else { + // Make sure the GUID has the CRC, for matching purposes + char *crc_string = SDL_strstr(pchMapping, SDL_GAMEPAD_CRC_FIELD); + if (crc_string) { + crc = (Uint16)SDL_strtol(crc_string + SDL_GAMEPAD_CRC_FIELD_SIZE, NULL, 16); + if (crc) { + SDL_SetJoystickGUIDCRC(&jGUID, crc); + } + } + } + + PushMappingChangeTracking(); + + pGamepadMapping = SDL_PrivateGetGamepadMappingForGUID(jGUID, true); + if (pGamepadMapping) { + // Only overwrite the mapping if the priority is the same or higher. + if (pGamepadMapping->priority <= priority) { + // Update existing mapping + SDL_free(pGamepadMapping->name); + pGamepadMapping->name = pchName; + SDL_free(pGamepadMapping->mapping); + pGamepadMapping->mapping = pchMapping; + pGamepadMapping->priority = priority; + } else { + SDL_free(pchName); + SDL_free(pchMapping); + } + if (existing) { + *existing = true; + } + AddMappingChangeTracking(pGamepadMapping); + } else { + pGamepadMapping = (GamepadMapping_t *)SDL_malloc(sizeof(*pGamepadMapping)); + if (!pGamepadMapping) { + PopMappingChangeTracking(); + SDL_free(pchName); + SDL_free(pchMapping); + return NULL; + } + // Clear the CRC, we've already added it to the mapping + if (crc) { + SDL_SetJoystickGUIDCRC(&jGUID, 0); + } + pGamepadMapping->guid = jGUID; + pGamepadMapping->name = pchName; + pGamepadMapping->mapping = pchMapping; + pGamepadMapping->next = NULL; + pGamepadMapping->priority = priority; + + if (s_pSupportedGamepads) { + // Add the mapping to the end of the list + GamepadMapping_t *pCurrMapping, *pPrevMapping; + + for (pPrevMapping = s_pSupportedGamepads, pCurrMapping = pPrevMapping->next; + pCurrMapping; + pPrevMapping = pCurrMapping, pCurrMapping = pCurrMapping->next) { + // continue; + } + pPrevMapping->next = pGamepadMapping; + } else { + s_pSupportedGamepads = pGamepadMapping; + } + if (existing) { + *existing = false; + } + } + + PopMappingChangeTracking(); + + return pGamepadMapping; +} + +/* + * Helper function to determine pre-calculated offset to certain joystick mappings + */ +static GamepadMapping_t *SDL_PrivateGetGamepadMappingForNameAndGUID(const char *name, SDL_GUID guid) +{ + GamepadMapping_t *mapping; + + SDL_AssertJoysticksLocked(); + + mapping = SDL_PrivateGetGamepadMappingForGUID(guid, false); +#ifdef SDL_PLATFORM_LINUX + if (!mapping && name) { + if (SDL_strstr(name, "Xbox 360 Wireless Receiver")) { + // The Linux driver xpad.c maps the wireless dpad to buttons + bool existing; + mapping = SDL_PrivateAddMappingForGUID(guid, + "none,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + &existing, SDL_GAMEPAD_MAPPING_PRIORITY_DEFAULT); + } + } +#endif // SDL_PLATFORM_LINUX + + return mapping; +} + +static void SDL_PrivateAppendToMappingString(char *mapping_string, + size_t mapping_string_len, + const char *input_name, + SDL_InputMapping *mapping) +{ + char buffer[16]; + if (mapping->kind == EMappingKind_None) { + return; + } + + SDL_strlcat(mapping_string, input_name, mapping_string_len); + SDL_strlcat(mapping_string, ":", mapping_string_len); + switch (mapping->kind) { + case EMappingKind_Button: + (void)SDL_snprintf(buffer, sizeof(buffer), "b%u", mapping->target); + break; + case EMappingKind_Axis: + (void)SDL_snprintf(buffer, sizeof(buffer), "%sa%u%s", + mapping->half_axis_positive ? "+" : + mapping->half_axis_negative ? "-" : "", + mapping->target, + mapping->axis_reversed ? "~" : ""); + break; + case EMappingKind_Hat: + (void)SDL_snprintf(buffer, sizeof(buffer), "h%i.%i", mapping->target >> 4, mapping->target & 0x0F); + break; + default: + SDL_assert(false); + } + + SDL_strlcat(mapping_string, buffer, mapping_string_len); + SDL_strlcat(mapping_string, ",", mapping_string_len); +} + +static GamepadMapping_t *SDL_PrivateGenerateAutomaticGamepadMapping(const char *name, + SDL_GUID guid, + SDL_GamepadMapping *raw_map) +{ + bool existing; + char name_string[128]; + char mapping[1024]; + + // Remove any commas in the name + SDL_strlcpy(name_string, name, sizeof(name_string)); + { + char *spot; + for (spot = name_string; *spot; ++spot) { + if (*spot == ',') { + *spot = ' '; + } + } + } + (void)SDL_snprintf(mapping, sizeof(mapping), "none,%s,", name_string); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "a", &raw_map->a); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "b", &raw_map->b); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "x", &raw_map->x); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "y", &raw_map->y); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "back", &raw_map->back); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "guide", &raw_map->guide); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "start", &raw_map->start); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "leftstick", &raw_map->leftstick); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "rightstick", &raw_map->rightstick); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "leftshoulder", &raw_map->leftshoulder); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "rightshoulder", &raw_map->rightshoulder); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "dpup", &raw_map->dpup); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "dpdown", &raw_map->dpdown); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "dpleft", &raw_map->dpleft); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "dpright", &raw_map->dpright); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "misc1", &raw_map->misc1); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "misc2", &raw_map->misc2); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "misc3", &raw_map->misc3); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "misc4", &raw_map->misc4); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "misc5", &raw_map->misc5); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "misc6", &raw_map->misc6); + /* Keep using paddle1-4 in the generated mapping so that it can be + * reused with SDL2 */ + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "paddle1", &raw_map->right_paddle1); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "paddle2", &raw_map->left_paddle1); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "paddle3", &raw_map->right_paddle2); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "paddle4", &raw_map->left_paddle2); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "leftx", &raw_map->leftx); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "lefty", &raw_map->lefty); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "rightx", &raw_map->rightx); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "righty", &raw_map->righty); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "lefttrigger", &raw_map->lefttrigger); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "righttrigger", &raw_map->righttrigger); + SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "touchpad", &raw_map->touchpad); + + return SDL_PrivateAddMappingForGUID(guid, mapping, &existing, SDL_GAMEPAD_MAPPING_PRIORITY_DEFAULT); +} + +static GamepadMapping_t *SDL_PrivateGetGamepadMapping(SDL_JoystickID instance_id, bool create_mapping) +{ + const char *name; + SDL_GUID guid; + GamepadMapping_t *mapping; + + SDL_AssertJoysticksLocked(); + + name = SDL_GetJoystickNameForID(instance_id); + guid = SDL_GetJoystickGUIDForID(instance_id); + mapping = SDL_PrivateGetGamepadMappingForNameAndGUID(name, guid); + if (!mapping && create_mapping) { + SDL_GamepadMapping raw_map; + + SDL_zero(raw_map); + if (SDL_PrivateJoystickGetAutoGamepadMapping(instance_id, &raw_map)) { + mapping = SDL_PrivateGenerateAutomaticGamepadMapping(name, guid, &raw_map); + } + } + + if (!mapping) { + mapping = s_pDefaultMapping; + } + return mapping; +} + +/* + * Add or update an entry into the Mappings Database + */ +int SDL_AddGamepadMappingsFromIO(SDL_IOStream *src, bool closeio) +{ + const char *platform = SDL_GetPlatform(); + int gamepads = 0; + char *buf, *line, *line_end, *tmp, *comma, line_platform[64]; + size_t db_size; + size_t platform_len; + + buf = (char *)SDL_LoadFile_IO(src, &db_size, closeio); + if (!buf) { + SDL_SetError("Could not allocate space to read DB into memory"); + return -1; + } + line = buf; + + SDL_LockJoysticks(); + + PushMappingChangeTracking(); + + while (line < buf + db_size) { + line_end = SDL_strchr(line, '\n'); + if (line_end) { + *line_end = '\0'; + } else { + line_end = buf + db_size; + } + + // Extract and verify the platform + tmp = SDL_strstr(line, SDL_GAMEPAD_PLATFORM_FIELD); + if (tmp) { + tmp += SDL_GAMEPAD_PLATFORM_FIELD_SIZE; + comma = SDL_strchr(tmp, ','); + if (comma) { + platform_len = comma - tmp + 1; + if (platform_len + 1 < SDL_arraysize(line_platform)) { + SDL_strlcpy(line_platform, tmp, platform_len); + if (SDL_strncasecmp(line_platform, platform, platform_len) == 0 && + SDL_AddGamepadMapping(line) > 0) { + gamepads++; + } + } + } + } + + line = line_end + 1; + } + + PopMappingChangeTracking(); + + SDL_UnlockJoysticks(); + + SDL_free(buf); + return gamepads; +} + +int SDL_AddGamepadMappingsFromFile(const char *file) +{ + return SDL_AddGamepadMappingsFromIO(SDL_IOFromFile(file, "rb"), true); +} + +bool SDL_ReloadGamepadMappings(void) +{ + SDL_Gamepad *gamepad; + + SDL_LockJoysticks(); + + PushMappingChangeTracking(); + + for (gamepad = SDL_gamepads; gamepad; gamepad = gamepad->next) { + AddMappingChangeTracking(gamepad->mapping); + } + + SDL_QuitGamepadMappings(); + SDL_InitGamepadMappings(); + + PopMappingChangeTracking(); + + SDL_UnlockJoysticks(); + + return true; +} + +static char *SDL_ConvertMappingToPositional(const char *mapping) +{ + // Add space for '!' and null terminator + size_t length = SDL_strlen(mapping) + 1 + 1; + char *remapped = (char *)SDL_malloc(length); + if (remapped) { + char *button_A; + char *button_B; + char *button_X; + char *button_Y; + char *hint; + + SDL_strlcpy(remapped, mapping, length); + button_A = SDL_strstr(remapped, "a:"); + button_B = SDL_strstr(remapped, "b:"); + button_X = SDL_strstr(remapped, "x:"); + button_Y = SDL_strstr(remapped, "y:"); + hint = SDL_strstr(remapped, "hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS"); + + if (button_A) { + *button_A = 'b'; + } + if (button_B) { + *button_B = 'a'; + } + if (button_X) { + *button_X = 'y'; + } + if (button_Y) { + *button_Y = 'x'; + } + if (hint) { + hint += 5; + SDL_memmove(hint + 1, hint, SDL_strlen(hint) + 1); + *hint = '!'; + } + } + return remapped; +} + +/* + * Add or update an entry into the Mappings Database with a priority + */ +static int SDL_PrivateAddGamepadMapping(const char *mappingString, SDL_GamepadMappingPriority priority) +{ + char *remapped = NULL; + char *pchGUID; + SDL_GUID jGUID; + bool is_default_mapping = false; + bool is_xinput_mapping = false; + bool existing = false; + GamepadMapping_t *pGamepadMapping; + int result = -1; + + SDL_AssertJoysticksLocked(); + + if (!mappingString) { + SDL_InvalidParamError("mappingString"); + return -1; + } + + { // Extract and verify the hint field + const char *tmp; + + tmp = SDL_strstr(mappingString, SDL_GAMEPAD_HINT_FIELD); + if (tmp) { + bool default_value, value, negate; + int len; + char hint[128]; + + tmp += SDL_GAMEPAD_HINT_FIELD_SIZE; + + if (*tmp == '!') { + negate = true; + ++tmp; + } else { + negate = false; + } + + len = 0; + while (*tmp && *tmp != ',' && *tmp != ':' && len < (sizeof(hint) - 1)) { + hint[len++] = *tmp++; + } + hint[len] = '\0'; + + if (tmp[0] == ':' && tmp[1] == '=') { + tmp += 2; + default_value = SDL_atoi(tmp); + } else { + default_value = false; + } + + if (SDL_strcmp(hint, "SDL_GAMECONTROLLER_USE_BUTTON_LABELS") == 0) { + // This hint is used to signal whether the mapping uses positional buttons or not + if (negate) { + // This mapping uses positional buttons, we can use it as-is + } else { + // This mapping uses labeled buttons, we need to swap them to positional + remapped = SDL_ConvertMappingToPositional(mappingString); + if (!remapped) { + goto done; + } + mappingString = remapped; + } + } else { + value = SDL_GetHintBoolean(hint, default_value); + if (negate) { + value = !value; + } + if (!value) { + result = 0; + goto done; + } + } + } + } + +#ifdef ANDROID + { // Extract and verify the SDK version + const char *tmp; + + tmp = SDL_strstr(mappingString, SDL_GAMEPAD_SDKGE_FIELD); + if (tmp) { + tmp += SDL_GAMEPAD_SDKGE_FIELD_SIZE; + if (!(SDL_GetAndroidSDKVersion() >= SDL_atoi(tmp))) { + SDL_SetError("SDK version %d < minimum version %d", SDL_GetAndroidSDKVersion(), SDL_atoi(tmp)); + goto done; + } + } + tmp = SDL_strstr(mappingString, SDL_GAMEPAD_SDKLE_FIELD); + if (tmp) { + tmp += SDL_GAMEPAD_SDKLE_FIELD_SIZE; + if (!(SDL_GetAndroidSDKVersion() <= SDL_atoi(tmp))) { + SDL_SetError("SDK version %d > maximum version %d", SDL_GetAndroidSDKVersion(), SDL_atoi(tmp)); + goto done; + } + } + } +#endif + + pchGUID = SDL_PrivateGetGamepadGUIDFromMappingString(mappingString); + if (!pchGUID) { + SDL_SetError("Couldn't parse GUID from %s", mappingString); + goto done; + } + if (!SDL_strcasecmp(pchGUID, "default")) { + is_default_mapping = true; + } else if (!SDL_strcasecmp(pchGUID, "xinput")) { + is_xinput_mapping = true; + } + jGUID = SDL_StringToGUID(pchGUID); + SDL_free(pchGUID); + + pGamepadMapping = SDL_PrivateAddMappingForGUID(jGUID, mappingString, &existing, priority); + if (!pGamepadMapping) { + goto done; + } + + if (existing) { + result = 0; + } else { + if (is_default_mapping) { + s_pDefaultMapping = pGamepadMapping; + } else if (is_xinput_mapping) { + s_pXInputMapping = pGamepadMapping; + } + result = 1; + } +done: + if (remapped) { + SDL_free(remapped); + } + return result; +} + +/* + * Add or update an entry into the Mappings Database + */ +int SDL_AddGamepadMapping(const char *mapping) +{ + int result; + + SDL_LockJoysticks(); + { + result = SDL_PrivateAddGamepadMapping(mapping, SDL_GAMEPAD_MAPPING_PRIORITY_API); + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Create a mapping string for a mapping + */ +static char *CreateMappingString(GamepadMapping_t *mapping, SDL_GUID guid) +{ + char *pMappingString, *pPlatformString; + char pchGUID[33]; + size_t needed; + bool need_platform = false; + const char *platform = NULL; + + SDL_AssertJoysticksLocked(); + + SDL_GUIDToString(guid, pchGUID, sizeof(pchGUID)); + + // allocate enough memory for GUID + ',' + name + ',' + mapping + \0 + needed = SDL_strlen(pchGUID) + 1 + SDL_strlen(mapping->name) + 1 + SDL_strlen(mapping->mapping) + 1; + + if (!SDL_strstr(mapping->mapping, SDL_GAMEPAD_PLATFORM_FIELD)) { + // add memory for ',' + platform:PLATFORM + need_platform = true; + if (mapping->mapping[SDL_strlen(mapping->mapping) - 1] != ',') { + needed += 1; + } + platform = SDL_GetPlatform(); + needed += SDL_GAMEPAD_PLATFORM_FIELD_SIZE + SDL_strlen(platform) + 1; + } + + pMappingString = (char *)SDL_malloc(needed); + if (!pMappingString) { + return NULL; + } + + (void)SDL_snprintf(pMappingString, needed, "%s,%s,%s", pchGUID, mapping->name, mapping->mapping); + + if (need_platform) { + if (mapping->mapping[SDL_strlen(mapping->mapping) - 1] != ',') { + SDL_strlcat(pMappingString, ",", needed); + } + SDL_strlcat(pMappingString, SDL_GAMEPAD_PLATFORM_FIELD, needed); + SDL_strlcat(pMappingString, platform, needed); + SDL_strlcat(pMappingString, ",", needed); + } + + // Make sure multiple platform strings haven't made their way into the mapping + pPlatformString = SDL_strstr(pMappingString, SDL_GAMEPAD_PLATFORM_FIELD); + if (pPlatformString) { + pPlatformString = SDL_strstr(pPlatformString + 1, SDL_GAMEPAD_PLATFORM_FIELD); + if (pPlatformString) { + *pPlatformString = '\0'; + } + } + return pMappingString; +} + +char **SDL_GetGamepadMappings(int *count) +{ + int num_mappings = 0; + char **result = NULL; + char **mappings = NULL; + + if (count) { + *count = 0; + } + + SDL_LockJoysticks(); + + for (GamepadMapping_t *mapping = s_pSupportedGamepads; mapping; mapping = mapping->next) { + if (SDL_memcmp(&mapping->guid, &s_zeroGUID, sizeof(mapping->guid)) == 0) { + continue; + } + num_mappings++; + } + + size_t final_allocation = sizeof (char *); // for the NULL terminator element. + bool failed = false; + mappings = (char **) SDL_calloc(num_mappings + 1, sizeof (char *)); + if (!mappings) { + failed = true; + } else { + int i = 0; + for (GamepadMapping_t *mapping = s_pSupportedGamepads; mapping; mapping = mapping->next) { + if (SDL_memcmp(&mapping->guid, &s_zeroGUID, sizeof(mapping->guid)) == 0) { + continue; + } + + char *mappingstr = CreateMappingString(mapping, mapping->guid); + if (!mappingstr) { + failed = true; + break; // error string is already set. + } + + SDL_assert(i < num_mappings); + mappings[i++] = mappingstr; + + final_allocation += SDL_strlen(mappingstr) + 1 + sizeof (char *); + } + } + + SDL_UnlockJoysticks(); + + if (!failed) { + result = (char **) SDL_malloc(final_allocation); + if (result) { + final_allocation -= (sizeof (char *) * num_mappings + 1); + char *strptr = (char *) (result + (num_mappings + 1)); + for (int i = 0; i < num_mappings; i++) { + result[i] = strptr; + const size_t slen = SDL_strlcpy(strptr, mappings[i], final_allocation) + 1; + SDL_assert(final_allocation >= slen); + final_allocation -= slen; + strptr += slen; + } + result[num_mappings] = NULL; + + if (count) { + *count = num_mappings; + } + } + } + + if (mappings) { + for (int i = 0; i < num_mappings; i++) { + SDL_free(mappings[i]); + } + SDL_free(mappings); + } + + return result; +} + +/* + * Get the mapping string for this GUID + */ +char *SDL_GetGamepadMappingForGUID(SDL_GUID guid) +{ + char *result; + + SDL_LockJoysticks(); + { + GamepadMapping_t *mapping = SDL_PrivateGetGamepadMappingForGUID(guid, false); + if (mapping) { + result = CreateMappingString(mapping, guid); + } else { + SDL_SetError("Mapping not available"); + result = NULL; + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the mapping string for this device + */ +char *SDL_GetGamepadMapping(SDL_Gamepad *gamepad) +{ + char *result; + + SDL_LockJoysticks(); + { + CHECK_GAMEPAD_MAGIC(gamepad, NULL); + + result = CreateMappingString(gamepad->mapping, gamepad->joystick->guid); + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Set the mapping string for this device + */ +bool SDL_SetGamepadMapping(SDL_JoystickID instance_id, const char *mapping) +{ + SDL_GUID guid = SDL_GetJoystickGUIDForID(instance_id); + bool result = false; + + if (SDL_memcmp(&guid, &s_zeroGUID, sizeof(guid)) == 0) { + return SDL_InvalidParamError("instance_id"); + } + + if (!mapping) { + mapping = "*,*,"; + } + + SDL_LockJoysticks(); + { + if (SDL_PrivateAddMappingForGUID(guid, mapping, NULL, SDL_GAMEPAD_MAPPING_PRIORITY_API)) { + result = true; + } + } + SDL_UnlockJoysticks(); + + return result; +} + +static void SDL_LoadGamepadHints(void) +{ + const char *hint = SDL_GetHint(SDL_HINT_GAMECONTROLLERCONFIG); + if (hint && hint[0]) { + char *pTempMappings = SDL_strdup(hint); + char *pUserMappings = pTempMappings; + + PushMappingChangeTracking(); + + while (pUserMappings) { + char *pchNewLine = NULL; + + pchNewLine = SDL_strchr(pUserMappings, '\n'); + if (pchNewLine) { + *pchNewLine = '\0'; + } + + SDL_PrivateAddGamepadMapping(pUserMappings, SDL_GAMEPAD_MAPPING_PRIORITY_USER); + + if (pchNewLine) { + pUserMappings = pchNewLine + 1; + } else { + pUserMappings = NULL; + } + } + + PopMappingChangeTracking(); + + SDL_free(pTempMappings); + } +} + +/* + * Fill the given buffer with the expected gamepad mapping filepath. + * Usually this will just be SDL_HINT_GAMECONTROLLERCONFIG_FILE, but for + * Android, we want to get the internal storage path. + */ +static bool SDL_GetGamepadMappingFilePath(char *path, size_t size) +{ + const char *hint = SDL_GetHint(SDL_HINT_GAMECONTROLLERCONFIG_FILE); + if (hint && *hint) { + return SDL_strlcpy(path, hint, size) < size; + } + +#ifdef SDL_PLATFORM_ANDROID + return SDL_snprintf(path, size, "%s/gamepad_map.txt", SDL_GetAndroidInternalStoragePath()) < size; +#else + return false; +#endif +} + +/* + * Initialize the gamepad system, mostly load our DB of gamepad config mappings + */ +bool SDL_InitGamepadMappings(void) +{ + char szGamepadMapPath[1024]; + int i = 0; + const char *pMappingString = NULL; + + SDL_AssertJoysticksLocked(); + + PushMappingChangeTracking(); + + pMappingString = s_GamepadMappings[i]; + while (pMappingString) { + SDL_PrivateAddGamepadMapping(pMappingString, SDL_GAMEPAD_MAPPING_PRIORITY_DEFAULT); + + i++; + pMappingString = s_GamepadMappings[i]; + } + + if (SDL_GetGamepadMappingFilePath(szGamepadMapPath, sizeof(szGamepadMapPath))) { + SDL_AddGamepadMappingsFromFile(szGamepadMapPath); + } + + // load in any user supplied config + SDL_LoadGamepadHints(); + + SDL_LoadVIDPIDList(&SDL_allowed_gamepads); + SDL_LoadVIDPIDList(&SDL_ignored_gamepads); + + PopMappingChangeTracking(); + + return true; +} + +bool SDL_InitGamepads(void) +{ + int i; + SDL_JoystickID *joysticks; + + SDL_gamepads_initialized = true; + + // Watch for joystick events and fire gamepad ones if needed + SDL_AddEventWatch(SDL_GamepadEventWatcher, NULL); + + // Send added events for gamepads currently attached + joysticks = SDL_GetJoysticks(NULL); + if (joysticks) { + for (i = 0; joysticks[i]; ++i) { + if (SDL_IsGamepad(joysticks[i])) { + SDL_PrivateGamepadAdded(joysticks[i]); + } + } + SDL_free(joysticks); + } + + return true; +} + +bool SDL_HasGamepad(void) +{ + int num_joysticks = 0; + int num_gamepads = 0; + SDL_JoystickID *joysticks = SDL_GetJoysticks(&num_joysticks); + if (joysticks) { + int i; + for (i = num_joysticks - 1; i >= 0 && num_gamepads == 0; --i) { + if (SDL_IsGamepad(joysticks[i])) { + ++num_gamepads; + } + } + SDL_free(joysticks); + } + if (num_gamepads > 0) { + return true; + } + return false; +} + +SDL_JoystickID *SDL_GetGamepads(int *count) +{ + int num_joysticks = 0; + int num_gamepads = 0; + SDL_JoystickID *joysticks = SDL_GetJoysticks(&num_joysticks); + if (joysticks) { + int i; + for (i = num_joysticks - 1; i >= 0; --i) { + if (SDL_IsGamepad(joysticks[i])) { + ++num_gamepads; + } else { + SDL_memmove(&joysticks[i], &joysticks[i+1], (num_gamepads + 1) * sizeof(joysticks[i])); + } + } + } + if (count) { + *count = num_gamepads; + } + return joysticks; +} + +const char *SDL_GetGamepadNameForID(SDL_JoystickID instance_id) +{ + const char *result = NULL; + + SDL_LockJoysticks(); + { + GamepadMapping_t *mapping = SDL_PrivateGetGamepadMapping(instance_id, true); + if (mapping) { + if (SDL_strcmp(mapping->name, "*") == 0) { + result = SDL_GetJoystickNameForID(instance_id); + } else { + result = SDL_GetPersistentString(mapping->name); + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +const char *SDL_GetGamepadPathForID(SDL_JoystickID instance_id) +{ + return SDL_GetJoystickPathForID(instance_id); +} + +int SDL_GetGamepadPlayerIndexForID(SDL_JoystickID instance_id) +{ + return SDL_GetJoystickPlayerIndexForID(instance_id); +} + +SDL_GUID SDL_GetGamepadGUIDForID(SDL_JoystickID instance_id) +{ + return SDL_GetJoystickGUIDForID(instance_id); +} + +Uint16 SDL_GetGamepadVendorForID(SDL_JoystickID instance_id) +{ + return SDL_GetJoystickVendorForID(instance_id); +} + +Uint16 SDL_GetGamepadProductForID(SDL_JoystickID instance_id) +{ + return SDL_GetJoystickProductForID(instance_id); +} + +Uint16 SDL_GetGamepadProductVersionForID(SDL_JoystickID instance_id) +{ + return SDL_GetJoystickProductVersionForID(instance_id); +} + +SDL_GamepadType SDL_GetGamepadTypeForID(SDL_JoystickID instance_id) +{ + SDL_GamepadType type = SDL_GAMEPAD_TYPE_UNKNOWN; + + SDL_LockJoysticks(); + { + GamepadMapping_t *mapping = SDL_PrivateGetGamepadMapping(instance_id, true); + if (mapping) { + char *type_string, *comma; + + type_string = SDL_strstr(mapping->mapping, SDL_GAMEPAD_TYPE_FIELD); + if (type_string) { + type_string += SDL_GAMEPAD_TYPE_FIELD_SIZE; + comma = SDL_strchr(type_string, ','); + if (comma) { + *comma = '\0'; + type = SDL_GetGamepadTypeFromString(type_string); + *comma = ','; + } + } + } + } + SDL_UnlockJoysticks(); + + if (type != SDL_GAMEPAD_TYPE_UNKNOWN) { + return type; + } + return SDL_GetRealGamepadTypeForID(instance_id); +} + +SDL_GamepadType SDL_GetRealGamepadTypeForID(SDL_JoystickID instance_id) +{ + SDL_GamepadType type = SDL_GAMEPAD_TYPE_UNKNOWN; + const SDL_SteamVirtualGamepadInfo *info; + + SDL_LockJoysticks(); + { + info = SDL_GetJoystickVirtualGamepadInfoForID(instance_id); + if (info) { + type = info->type; + } else { + type = SDL_GetGamepadTypeFromGUID(SDL_GetJoystickGUIDForID(instance_id), SDL_GetJoystickNameForID(instance_id)); + } + } + SDL_UnlockJoysticks(); + + return type; +} + +char *SDL_GetGamepadMappingForID(SDL_JoystickID instance_id) +{ + char *result = NULL; + + SDL_LockJoysticks(); + { + GamepadMapping_t *mapping = SDL_PrivateGetGamepadMapping(instance_id, true); + if (mapping) { + char pchGUID[33]; + SDL_GUID guid = SDL_GetJoystickGUIDForID(instance_id); + SDL_GUIDToString(guid, pchGUID, sizeof(pchGUID)); + SDL_asprintf(&result, "%s,%s,%s", pchGUID, mapping->name, mapping->mapping); + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Return 1 if the joystick with this name and GUID is a supported gamepad + */ +bool SDL_IsGamepadNameAndGUID(const char *name, SDL_GUID guid) +{ + bool result; + + SDL_LockJoysticks(); + { + if (s_pDefaultMapping || SDL_PrivateGetGamepadMappingForNameAndGUID(name, guid) != NULL) { + result = true; + } else { + result = false; + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Return 1 if the joystick at this device index is a supported gamepad + */ +bool SDL_IsGamepad(SDL_JoystickID instance_id) +{ + bool result; + + SDL_LockJoysticks(); + { + const void *value; + if (SDL_FindInHashTable(s_gamepadInstanceIDs, (void *)(uintptr_t)instance_id, &value)) { + result = (bool)(uintptr_t)value; + } else { + if (SDL_PrivateGetGamepadMapping(instance_id, true) != NULL) { + result = true; + } else { + result = false; + } + + if (!s_gamepadInstanceIDs) { + s_gamepadInstanceIDs = SDL_CreateHashTable(0, false, SDL_HashID, SDL_KeyMatchID, NULL, NULL); + } + SDL_InsertIntoHashTable(s_gamepadInstanceIDs, (void *)(uintptr_t)instance_id, (void *)(uintptr_t)result, true); + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Return 1 if the gamepad should be ignored by SDL + */ +bool SDL_ShouldIgnoreGamepad(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ +#ifdef SDL_PLATFORM_LINUX + if (SDL_endswith(name, " Motion Sensors")) { + // Don't treat the PS3 and PS4 motion controls as a separate gamepad + return true; + } + if (SDL_strncmp(name, "Nintendo ", 9) == 0 && SDL_strstr(name, " IMU") != NULL) { + // Don't treat the Nintendo IMU as a separate gamepad + return true; + } + if (SDL_endswith(name, " Accelerometer") || + SDL_endswith(name, " IR") || + SDL_endswith(name, " Motion Plus") || + SDL_endswith(name, " Nunchuk")) { + // Don't treat the Wii extension controls as a separate gamepad + return true; + } +#endif + + if (name && SDL_strcmp(name, "uinput-fpc") == 0) { + // The Google Pixel fingerprint sensor reports itself as a joystick + return true; + } + +#ifdef SDL_PLATFORM_WIN32 + if (SDL_GetHintBoolean("SDL_GAMECONTROLLER_ALLOW_STEAM_VIRTUAL_GAMEPAD", false) && + SDL_GetHintBoolean("STEAM_COMPAT_PROTON", false)) { + // We are launched by Steam and running under Proton + // We can't tell whether this controller is a Steam Virtual Gamepad, + // so assume that Proton is doing the appropriate filtering of controllers + // and anything we see here is fine to use. + return false; + } +#endif // SDL_PLATFORM_WIN32 + + if (SDL_IsJoystickSteamVirtualGamepad(vendor_id, product_id, version)) { + return !SDL_GetHintBoolean("SDL_GAMECONTROLLER_ALLOW_STEAM_VIRTUAL_GAMEPAD", false); + } + + if (SDL_allowed_gamepads.num_included_entries > 0) { + if (SDL_VIDPIDInList(vendor_id, product_id, &SDL_allowed_gamepads)) { + return false; + } + return true; + } else { + if (SDL_VIDPIDInList(vendor_id, product_id, &SDL_ignored_gamepads)) { + return true; + } + return false; + } +} + +/* + * Open a gamepad for use + * + * This function returns a gamepad identifier, or NULL if an error occurred. + */ +SDL_Gamepad *SDL_OpenGamepad(SDL_JoystickID instance_id) +{ + SDL_Gamepad *gamepad; + SDL_Gamepad *gamepadlist; + GamepadMapping_t *pSupportedGamepad = NULL; + + SDL_LockJoysticks(); + + gamepadlist = SDL_gamepads; + // If the gamepad is already open, return it + while (gamepadlist) { + if (instance_id == gamepadlist->joystick->instance_id) { + gamepad = gamepadlist; + ++gamepad->ref_count; + SDL_UnlockJoysticks(); + return gamepad; + } + gamepadlist = gamepadlist->next; + } + + // Find a gamepad mapping + pSupportedGamepad = SDL_PrivateGetGamepadMapping(instance_id, true); + if (!pSupportedGamepad) { + SDL_SetError("Couldn't find mapping for device (%" SDL_PRIu32 ")", instance_id); + SDL_UnlockJoysticks(); + return NULL; + } + + // Create and initialize the gamepad + gamepad = (SDL_Gamepad *)SDL_calloc(1, sizeof(*gamepad)); + if (!gamepad) { + SDL_UnlockJoysticks(); + return NULL; + } + SDL_SetObjectValid(gamepad, SDL_OBJECT_TYPE_GAMEPAD, true); + + gamepad->joystick = SDL_OpenJoystick(instance_id); + if (!gamepad->joystick) { + SDL_SetObjectValid(gamepad, SDL_OBJECT_TYPE_GAMEPAD, false); + SDL_free(gamepad); + SDL_UnlockJoysticks(); + return NULL; + } + + if (gamepad->joystick->naxes) { + gamepad->last_match_axis = (SDL_GamepadBinding **)SDL_calloc(gamepad->joystick->naxes, sizeof(*gamepad->last_match_axis)); + if (!gamepad->last_match_axis) { + SDL_SetObjectValid(gamepad, SDL_OBJECT_TYPE_GAMEPAD, false); + SDL_CloseJoystick(gamepad->joystick); + SDL_free(gamepad); + SDL_UnlockJoysticks(); + return NULL; + } + } + if (gamepad->joystick->nhats) { + gamepad->last_hat_mask = (Uint8 *)SDL_calloc(gamepad->joystick->nhats, sizeof(*gamepad->last_hat_mask)); + if (!gamepad->last_hat_mask) { + SDL_SetObjectValid(gamepad, SDL_OBJECT_TYPE_GAMEPAD, false); + SDL_CloseJoystick(gamepad->joystick); + SDL_free(gamepad->last_match_axis); + SDL_free(gamepad); + SDL_UnlockJoysticks(); + return NULL; + } + } + + SDL_PrivateLoadButtonMapping(gamepad, pSupportedGamepad); + + // Add the gamepad to list + ++gamepad->ref_count; + // Link the gamepad in the list + gamepad->next = SDL_gamepads; + SDL_gamepads = gamepad; + + SDL_UnlockJoysticks(); + + return gamepad; +} + +/* + * Manually pump for gamepad updates. + */ +void SDL_UpdateGamepads(void) +{ + // Just for API completeness; the joystick API does all the work. + SDL_UpdateJoysticks(); +} + +/** + * Return whether a gamepad has a given axis + */ +bool SDL_GamepadHasAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis) +{ + bool result = false; + + SDL_LockJoysticks(); + { + int i; + + CHECK_GAMEPAD_MAGIC(gamepad, false); + + for (i = 0; i < gamepad->num_bindings; ++i) { + const SDL_GamepadBinding *binding = &gamepad->bindings[i]; + if (binding->output_type == SDL_GAMEPAD_BINDTYPE_AXIS && binding->output.axis.axis == axis) { + result = true; + break; + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the current state of an axis control on a gamepad + */ +Sint16 SDL_GetGamepadAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis) +{ + Sint16 result = 0; + + SDL_LockJoysticks(); + { + int i; + + CHECK_GAMEPAD_MAGIC(gamepad, 0); + + for (i = 0; i < gamepad->num_bindings; ++i) { + const SDL_GamepadBinding *binding = &gamepad->bindings[i]; + if (binding->output_type == SDL_GAMEPAD_BINDTYPE_AXIS && binding->output.axis.axis == axis) { + int value = 0; + bool valid_input_range; + bool valid_output_range; + + if (binding->input_type == SDL_GAMEPAD_BINDTYPE_AXIS) { + value = SDL_GetJoystickAxis(gamepad->joystick, binding->input.axis.axis); + if (binding->input.axis.axis_min < binding->input.axis.axis_max) { + valid_input_range = (value >= binding->input.axis.axis_min && value <= binding->input.axis.axis_max); + } else { + valid_input_range = (value >= binding->input.axis.axis_max && value <= binding->input.axis.axis_min); + } + if (valid_input_range) { + if (binding->input.axis.axis_min != binding->output.axis.axis_min || binding->input.axis.axis_max != binding->output.axis.axis_max) { + float normalized_value = (float)(value - binding->input.axis.axis_min) / (binding->input.axis.axis_max - binding->input.axis.axis_min); + value = binding->output.axis.axis_min + (int)(normalized_value * (binding->output.axis.axis_max - binding->output.axis.axis_min)); + } + } else { + value = 0; + } + } else if (binding->input_type == SDL_GAMEPAD_BINDTYPE_BUTTON) { + if (SDL_GetJoystickButton(gamepad->joystick, binding->input.button)) { + value = binding->output.axis.axis_max; + } + } else if (binding->input_type == SDL_GAMEPAD_BINDTYPE_HAT) { + int hat_mask = SDL_GetJoystickHat(gamepad->joystick, binding->input.hat.hat); + if (hat_mask & binding->input.hat.hat_mask) { + value = binding->output.axis.axis_max; + } + } + + if (binding->output.axis.axis_min < binding->output.axis.axis_max) { + valid_output_range = (value >= binding->output.axis.axis_min && value <= binding->output.axis.axis_max); + } else { + valid_output_range = (value >= binding->output.axis.axis_max && value <= binding->output.axis.axis_min); + } + // If the value is zero, there might be another binding that makes it non-zero + if (value != 0 && valid_output_range) { + result = (Sint16)value; + break; + } + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/** + * Return whether a gamepad has a given button + */ +bool SDL_GamepadHasButton(SDL_Gamepad *gamepad, SDL_GamepadButton button) +{ + bool result = false; + + SDL_LockJoysticks(); + { + int i; + + CHECK_GAMEPAD_MAGIC(gamepad, false); + + for (i = 0; i < gamepad->num_bindings; ++i) { + const SDL_GamepadBinding *binding = &gamepad->bindings[i]; + if (binding->output_type == SDL_GAMEPAD_BINDTYPE_BUTTON && binding->output.button == button) { + result = true; + break; + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the current state of a button on a gamepad + */ +bool SDL_GetGamepadButton(SDL_Gamepad *gamepad, SDL_GamepadButton button) +{ + bool result = false; + + SDL_LockJoysticks(); + { + int i; + + CHECK_GAMEPAD_MAGIC(gamepad, false); + + for (i = 0; i < gamepad->num_bindings; ++i) { + const SDL_GamepadBinding *binding = &gamepad->bindings[i]; + if (binding->output_type == SDL_GAMEPAD_BINDTYPE_BUTTON && binding->output.button == button) { + if (binding->input_type == SDL_GAMEPAD_BINDTYPE_AXIS) { + bool valid_input_range; + + int value = SDL_GetJoystickAxis(gamepad->joystick, binding->input.axis.axis); + int threshold = binding->input.axis.axis_min + (binding->input.axis.axis_max - binding->input.axis.axis_min) / 2; + if (binding->input.axis.axis_min < binding->input.axis.axis_max) { + valid_input_range = (value >= binding->input.axis.axis_min && value <= binding->input.axis.axis_max); + if (valid_input_range) { + result |= (value >= threshold); + } + } else { + valid_input_range = (value >= binding->input.axis.axis_max && value <= binding->input.axis.axis_min); + if (valid_input_range) { + result |= (value <= threshold); + } + } + } else if (binding->input_type == SDL_GAMEPAD_BINDTYPE_BUTTON) { + result |= SDL_GetJoystickButton(gamepad->joystick, binding->input.button); + } else if (binding->input_type == SDL_GAMEPAD_BINDTYPE_HAT) { + int hat_mask = SDL_GetJoystickHat(gamepad->joystick, binding->input.hat.hat); + result |= ((hat_mask & binding->input.hat.hat_mask) != 0); + } + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/** + * Get the label of a button on a gamepad. + */ +static SDL_GamepadButtonLabel SDL_GetGamepadButtonLabelForFaceStyle(SDL_GamepadFaceStyle face_style, SDL_GamepadButton button) +{ + SDL_GamepadButtonLabel label = SDL_GAMEPAD_BUTTON_LABEL_UNKNOWN; + + switch (face_style) { + case SDL_GAMEPAD_FACE_STYLE_ABXY: + switch (button) { + case SDL_GAMEPAD_BUTTON_SOUTH: + label = SDL_GAMEPAD_BUTTON_LABEL_A; + break; + case SDL_GAMEPAD_BUTTON_EAST: + label = SDL_GAMEPAD_BUTTON_LABEL_B; + break; + case SDL_GAMEPAD_BUTTON_WEST: + label = SDL_GAMEPAD_BUTTON_LABEL_X; + break; + case SDL_GAMEPAD_BUTTON_NORTH: + label = SDL_GAMEPAD_BUTTON_LABEL_Y; + break; + default: + break; + } + break; + case SDL_GAMEPAD_FACE_STYLE_BAYX: + switch (button) { + case SDL_GAMEPAD_BUTTON_SOUTH: + label = SDL_GAMEPAD_BUTTON_LABEL_B; + break; + case SDL_GAMEPAD_BUTTON_EAST: + label = SDL_GAMEPAD_BUTTON_LABEL_A; + break; + case SDL_GAMEPAD_BUTTON_WEST: + label = SDL_GAMEPAD_BUTTON_LABEL_Y; + break; + case SDL_GAMEPAD_BUTTON_NORTH: + label = SDL_GAMEPAD_BUTTON_LABEL_X; + break; + default: + break; + } + break; + case SDL_GAMEPAD_FACE_STYLE_SONY: + switch (button) { + case SDL_GAMEPAD_BUTTON_SOUTH: + label = SDL_GAMEPAD_BUTTON_LABEL_CROSS; + break; + case SDL_GAMEPAD_BUTTON_EAST: + label = SDL_GAMEPAD_BUTTON_LABEL_CIRCLE; + break; + case SDL_GAMEPAD_BUTTON_WEST: + label = SDL_GAMEPAD_BUTTON_LABEL_SQUARE; + break; + case SDL_GAMEPAD_BUTTON_NORTH: + label = SDL_GAMEPAD_BUTTON_LABEL_TRIANGLE; + break; + default: + break; + } + break; + default: + break; + } + return label; +} + +/** + * Get the label of a button on a gamepad. + */ +SDL_GamepadButtonLabel SDL_GetGamepadButtonLabelForType(SDL_GamepadType type, SDL_GamepadButton button) +{ + return SDL_GetGamepadButtonLabelForFaceStyle(SDL_GetGamepadFaceStyleForGamepadType(type), button); +} + +/** + * Get the label of a button on a gamepad. + */ +SDL_GamepadButtonLabel SDL_GetGamepadButtonLabel(SDL_Gamepad *gamepad, SDL_GamepadButton button) +{ + SDL_GamepadFaceStyle face_style; + + SDL_LockJoysticks(); + { + CHECK_GAMEPAD_MAGIC(gamepad, SDL_GAMEPAD_BUTTON_LABEL_UNKNOWN); + + face_style = gamepad->face_style; + } + SDL_UnlockJoysticks(); + + return SDL_GetGamepadButtonLabelForFaceStyle(face_style, button); +} + +/** + * Get the number of touchpads on a gamepad. + */ +int SDL_GetNumGamepadTouchpads(SDL_Gamepad *gamepad) +{ + int result = 0; + + SDL_LockJoysticks(); + { + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + if (joystick) { + result = joystick->ntouchpads; + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/** + * Get the number of supported simultaneous fingers on a touchpad on a gamepad. + */ +int SDL_GetNumGamepadTouchpadFingers(SDL_Gamepad *gamepad, int touchpad) +{ + int result = 0; + + SDL_LockJoysticks(); + { + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + if (joystick) { + if (touchpad >= 0 && touchpad < joystick->ntouchpads) { + result = joystick->touchpads[touchpad].nfingers; + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/** + * Get the current state of a finger on a touchpad on a gamepad. + */ +bool SDL_GetGamepadTouchpadFinger(SDL_Gamepad *gamepad, int touchpad, int finger, bool *down, float *x, float *y, float *pressure) +{ + bool result = false; + + SDL_LockJoysticks(); + { + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + if (joystick) { + if (touchpad >= 0 && touchpad < joystick->ntouchpads) { + SDL_JoystickTouchpadInfo *touchpad_info = &joystick->touchpads[touchpad]; + if (finger >= 0 && finger < touchpad_info->nfingers) { + SDL_JoystickTouchpadFingerInfo *info = &touchpad_info->fingers[finger]; + + if (down) { + *down = info->down; + } + if (x) { + *x = info->x; + } + if (y) { + *y = info->y; + } + if (pressure) { + *pressure = info->pressure; + } + result = true; + } else { + result = SDL_InvalidParamError("finger"); + } + } else { + result = SDL_InvalidParamError("touchpad"); + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/** + * Return whether a gamepad has a particular sensor. + */ +bool SDL_GamepadHasSensor(SDL_Gamepad *gamepad, SDL_SensorType type) +{ + bool result = false; + + SDL_LockJoysticks(); + { + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + if (joystick) { + int i; + for (i = 0; i < joystick->nsensors; ++i) { + if (joystick->sensors[i].type == type) { + result = true; + break; + } + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Set whether data reporting for a gamepad sensor is enabled + */ +bool SDL_SetGamepadSensorEnabled(SDL_Gamepad *gamepad, SDL_SensorType type, bool enabled) +{ + SDL_LockJoysticks(); + { + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + if (joystick) { + int i; + for (i = 0; i < joystick->nsensors; ++i) { + SDL_JoystickSensorInfo *sensor = &joystick->sensors[i]; + + if (sensor->type == type) { + if (sensor->enabled == (enabled != false)) { + SDL_UnlockJoysticks(); + return true; + } + + if (type == SDL_SENSOR_ACCEL && joystick->accel_sensor) { + if (enabled) { + joystick->accel = SDL_OpenSensor(joystick->accel_sensor); + if (!joystick->accel) { + SDL_UnlockJoysticks(); + return false; + } + } else { + if (joystick->accel) { + SDL_CloseSensor(joystick->accel); + joystick->accel = NULL; + } + } + } else if (type == SDL_SENSOR_GYRO && joystick->gyro_sensor) { + if (enabled) { + joystick->gyro = SDL_OpenSensor(joystick->gyro_sensor); + if (!joystick->gyro) { + SDL_UnlockJoysticks(); + return false; + } + } else { + if (joystick->gyro) { + SDL_CloseSensor(joystick->gyro); + joystick->gyro = NULL; + } + } + } else { + if (enabled) { + if (joystick->nsensors_enabled == 0) { + if (!joystick->driver->SetSensorsEnabled(joystick, true)) { + SDL_UnlockJoysticks(); + return false; + } + } + ++joystick->nsensors_enabled; + } else { + if (joystick->nsensors_enabled == 1) { + if (!joystick->driver->SetSensorsEnabled(joystick, false)) { + SDL_UnlockJoysticks(); + return false; + } + } + --joystick->nsensors_enabled; + } + } + + sensor->enabled = enabled; + SDL_UnlockJoysticks(); + return true; + } + } + } + } + SDL_UnlockJoysticks(); + + return SDL_Unsupported(); +} + +/* + * Query whether sensor data reporting is enabled for a gamepad + */ +bool SDL_GamepadSensorEnabled(SDL_Gamepad *gamepad, SDL_SensorType type) +{ + bool result = false; + + SDL_LockJoysticks(); + { + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + if (joystick) { + int i; + for (i = 0; i < joystick->nsensors; ++i) { + if (joystick->sensors[i].type == type) { + result = joystick->sensors[i].enabled; + break; + } + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the data rate of a gamepad sensor. + */ +float SDL_GetGamepadSensorDataRate(SDL_Gamepad *gamepad, SDL_SensorType type) +{ + float result = 0.0f; + + SDL_LockJoysticks(); + { + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + if (joystick) { + int i; + for (i = 0; i < joystick->nsensors; ++i) { + SDL_JoystickSensorInfo *sensor = &joystick->sensors[i]; + + if (sensor->type == type) { + result = sensor->rate; + break; + } + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the current state of a gamepad sensor. + */ +bool SDL_GetGamepadSensorData(SDL_Gamepad *gamepad, SDL_SensorType type, float *data, int num_values) +{ + SDL_LockJoysticks(); + { + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + if (joystick) { + int i; + for (i = 0; i < joystick->nsensors; ++i) { + SDL_JoystickSensorInfo *sensor = &joystick->sensors[i]; + + if (sensor->type == type) { + num_values = SDL_min(num_values, SDL_arraysize(sensor->data)); + SDL_memcpy(data, sensor->data, num_values * sizeof(*data)); + SDL_UnlockJoysticks(); + return true; + } + } + } + } + SDL_UnlockJoysticks(); + + return SDL_Unsupported(); +} + +SDL_JoystickID SDL_GetGamepadID(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return 0; + } + return SDL_GetJoystickID(joystick); +} + +SDL_PropertiesID SDL_GetGamepadProperties(SDL_Gamepad *gamepad) +{ + SDL_PropertiesID result = 0; + + SDL_LockJoysticks(); + { + CHECK_GAMEPAD_MAGIC(gamepad, 0); + + result = SDL_GetJoystickProperties(gamepad->joystick); + } + SDL_UnlockJoysticks(); + + return result; +} + +const char *SDL_GetGamepadName(SDL_Gamepad *gamepad) +{ + const char *result = NULL; + + SDL_LockJoysticks(); + { + CHECK_GAMEPAD_MAGIC(gamepad, NULL); + + if (SDL_strcmp(gamepad->name, "*") == 0 || + gamepad->joystick->steam_handle != 0) { + result = SDL_GetJoystickName(gamepad->joystick); + } else { + result = SDL_GetPersistentString(gamepad->name); + } + } + SDL_UnlockJoysticks(); + + return result; +} + +const char *SDL_GetGamepadPath(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return NULL; + } + return SDL_GetJoystickPath(joystick); +} + +SDL_GamepadType SDL_GetGamepadType(SDL_Gamepad *gamepad) +{ + SDL_GamepadType type; + const SDL_SteamVirtualGamepadInfo *info; + + SDL_LockJoysticks(); + { + CHECK_GAMEPAD_MAGIC(gamepad, SDL_GAMEPAD_TYPE_UNKNOWN); + + info = SDL_GetJoystickVirtualGamepadInfoForID(gamepad->joystick->instance_id); + if (info) { + type = info->type; + } else { + type = gamepad->type; + } + } + SDL_UnlockJoysticks(); + + return type; +} + +SDL_GamepadType SDL_GetRealGamepadType(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return SDL_GAMEPAD_TYPE_UNKNOWN; + } + return SDL_GetGamepadTypeFromGUID(SDL_GetJoystickGUID(joystick), SDL_GetJoystickName(joystick)); +} + +int SDL_GetGamepadPlayerIndex(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return -1; + } + return SDL_GetJoystickPlayerIndex(joystick); +} + +/** + * Set the player index of an opened gamepad + */ +bool SDL_SetGamepadPlayerIndex(SDL_Gamepad *gamepad, int player_index) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + // SDL_SetError() will have been called already by SDL_GetGamepadJoystick() + return false; + } + return SDL_SetJoystickPlayerIndex(joystick, player_index); +} + +Uint16 SDL_GetGamepadVendor(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return 0; + } + return SDL_GetJoystickVendor(joystick); +} + +Uint16 SDL_GetGamepadProduct(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return 0; + } + return SDL_GetJoystickProduct(joystick); +} + +Uint16 SDL_GetGamepadProductVersion(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return 0; + } + return SDL_GetJoystickProductVersion(joystick); +} + +Uint16 SDL_GetGamepadFirmwareVersion(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return 0; + } + return SDL_GetJoystickFirmwareVersion(joystick); +} + +const char * SDL_GetGamepadSerial(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return NULL; + } + return SDL_GetJoystickSerial(joystick); + +} + +Uint64 SDL_GetGamepadSteamHandle(SDL_Gamepad *gamepad) +{ + Uint64 handle = 0; + + SDL_LockJoysticks(); + { + CHECK_GAMEPAD_MAGIC(gamepad, 0); + + handle = gamepad->joystick->steam_handle; + } + SDL_UnlockJoysticks(); + + return handle; +} + +SDL_JoystickConnectionState SDL_GetGamepadConnectionState(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return SDL_JOYSTICK_CONNECTION_INVALID; + } + return SDL_GetJoystickConnectionState(joystick); +} + +SDL_PowerState SDL_GetGamepadPowerInfo(SDL_Gamepad *gamepad, int *percent) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (percent) { + *percent = -1; + } + if (!joystick) { + return SDL_POWERSTATE_ERROR; + } + return SDL_GetJoystickPowerInfo(joystick, percent); +} + +/* + * Return if the gamepad in question is currently attached to the system, + * \return 0 if not plugged in, 1 if still present. + */ +bool SDL_GamepadConnected(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return false; + } + return SDL_JoystickConnected(joystick); +} + +/* + * Get the joystick for this gamepad + */ +SDL_Joystick *SDL_GetGamepadJoystick(SDL_Gamepad *gamepad) +{ + SDL_Joystick *joystick; + + SDL_LockJoysticks(); + { + CHECK_GAMEPAD_MAGIC(gamepad, NULL); + + joystick = gamepad->joystick; + } + SDL_UnlockJoysticks(); + + return joystick; +} + +/* + * Return the SDL_Gamepad associated with an instance id. + */ +SDL_Gamepad *SDL_GetGamepadFromID(SDL_JoystickID joyid) +{ + SDL_Gamepad *gamepad; + + SDL_LockJoysticks(); + gamepad = SDL_gamepads; + while (gamepad) { + if (gamepad->joystick->instance_id == joyid) { + SDL_UnlockJoysticks(); + return gamepad; + } + gamepad = gamepad->next; + } + SDL_UnlockJoysticks(); + return NULL; +} + +/** + * Return the SDL_Gamepad associated with a player index. + */ +SDL_Gamepad *SDL_GetGamepadFromPlayerIndex(int player_index) +{ + SDL_Gamepad *result = NULL; + + SDL_LockJoysticks(); + { + SDL_Joystick *joystick = SDL_GetJoystickFromPlayerIndex(player_index); + if (joystick) { + result = SDL_GetGamepadFromID(joystick->instance_id); + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the SDL joystick layer bindings for this gamepad + */ +SDL_GamepadBinding **SDL_GetGamepadBindings(SDL_Gamepad *gamepad, int *count) +{ + SDL_GamepadBinding **bindings = NULL; + + if (count) { + *count = 0; + } + + SDL_LockJoysticks(); + { + CHECK_GAMEPAD_MAGIC(gamepad, NULL); + + size_t pointers_size = ((gamepad->num_bindings + 1) * sizeof(SDL_GamepadBinding *)); + size_t elements_size = (gamepad->num_bindings * sizeof(SDL_GamepadBinding)); + bindings = (SDL_GamepadBinding **)SDL_malloc(pointers_size + elements_size); + if (bindings) { + SDL_GamepadBinding *binding = (SDL_GamepadBinding *)((Uint8 *)bindings + pointers_size); + int i; + for (i = 0; i < gamepad->num_bindings; ++i, ++binding) { + bindings[i] = binding; + SDL_copyp(binding, &gamepad->bindings[i]); + } + bindings[i] = NULL; + + if (count) { + *count = gamepad->num_bindings; + } + } + } + SDL_UnlockJoysticks(); + + return bindings; +} + +bool SDL_RumbleGamepad(SDL_Gamepad *gamepad, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return false; + } + return SDL_RumbleJoystick(joystick, low_frequency_rumble, high_frequency_rumble, duration_ms); +} + +bool SDL_RumbleGamepadTriggers(SDL_Gamepad *gamepad, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return false; + } + return SDL_RumbleJoystickTriggers(joystick, left_rumble, right_rumble, duration_ms); +} + +bool SDL_SetGamepadLED(SDL_Gamepad *gamepad, Uint8 red, Uint8 green, Uint8 blue) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return false; + } + return SDL_SetJoystickLED(joystick, red, green, blue); +} + +bool SDL_SendGamepadEffect(SDL_Gamepad *gamepad, const void *data, int size) +{ + SDL_Joystick *joystick = SDL_GetGamepadJoystick(gamepad); + + if (!joystick) { + return false; + } + return SDL_SendJoystickEffect(joystick, data, size); +} + +void SDL_CloseGamepad(SDL_Gamepad *gamepad) +{ + SDL_Gamepad *gamepadlist, *gamepadlistprev; + + SDL_LockJoysticks(); + + if (!SDL_ObjectValid(gamepad, SDL_OBJECT_TYPE_GAMEPAD)) { + SDL_UnlockJoysticks(); + return; + } + + // First decrement ref count + if (--gamepad->ref_count > 0) { + SDL_UnlockJoysticks(); + return; + } + + SDL_CloseJoystick(gamepad->joystick); + + gamepadlist = SDL_gamepads; + gamepadlistprev = NULL; + while (gamepadlist) { + if (gamepad == gamepadlist) { + if (gamepadlistprev) { + // unlink this entry + gamepadlistprev->next = gamepadlist->next; + } else { + SDL_gamepads = gamepad->next; + } + break; + } + gamepadlistprev = gamepadlist; + gamepadlist = gamepadlist->next; + } + + SDL_SetObjectValid(gamepad, SDL_OBJECT_TYPE_GAMEPAD, false); + SDL_free(gamepad->bindings); + SDL_free(gamepad->last_match_axis); + SDL_free(gamepad->last_hat_mask); + SDL_free(gamepad); + + SDL_UnlockJoysticks(); +} + +/* + * Quit the gamepad subsystem + */ +void SDL_QuitGamepads(void) +{ + SDL_Gamepad *gamepad; + + SDL_LockJoysticks(); + + for (gamepad = SDL_gamepads; gamepad; gamepad = gamepad->next) { + SDL_PrivateGamepadRemoved(gamepad->joystick->instance_id); + } + + SDL_gamepads_initialized = false; + + SDL_RemoveEventWatch(SDL_GamepadEventWatcher, NULL); + + while (SDL_gamepads) { + SDL_gamepads->ref_count = 1; + SDL_CloseGamepad(SDL_gamepads); + } + + SDL_UnlockJoysticks(); +} + +void SDL_QuitGamepadMappings(void) +{ + GamepadMapping_t *pGamepadMap; + + SDL_AssertJoysticksLocked(); + + while (s_pSupportedGamepads) { + pGamepadMap = s_pSupportedGamepads; + s_pSupportedGamepads = s_pSupportedGamepads->next; + SDL_free(pGamepadMap->name); + SDL_free(pGamepadMap->mapping); + SDL_free(pGamepadMap); + } + + SDL_FreeVIDPIDList(&SDL_allowed_gamepads); + SDL_FreeVIDPIDList(&SDL_ignored_gamepads); + + if (s_gamepadInstanceIDs) { + SDL_DestroyHashTable(s_gamepadInstanceIDs); + s_gamepadInstanceIDs = NULL; + } +} + +/* + * Event filter to transform joystick events into appropriate gamepad ones + */ +static void SDL_SendGamepadAxis(Uint64 timestamp, SDL_Gamepad *gamepad, SDL_GamepadAxis axis, Sint16 value) +{ + SDL_AssertJoysticksLocked(); + + // translate the event, if desired + if (SDL_EventEnabled(SDL_EVENT_GAMEPAD_AXIS_MOTION)) { + SDL_Event event; + event.type = SDL_EVENT_GAMEPAD_AXIS_MOTION; + event.common.timestamp = timestamp; + event.gaxis.which = gamepad->joystick->instance_id; + event.gaxis.axis = axis; + event.gaxis.value = value; + SDL_PushEvent(&event); + } +} + +static void SDL_SendGamepadButton(Uint64 timestamp, SDL_Gamepad *gamepad, SDL_GamepadButton button, bool down) +{ + SDL_Event event; + + SDL_AssertJoysticksLocked(); + + if (button == SDL_GAMEPAD_BUTTON_INVALID) { + return; + } + + if (down) { + event.type = SDL_EVENT_GAMEPAD_BUTTON_DOWN; + } else { + event.type = SDL_EVENT_GAMEPAD_BUTTON_UP; + } + + if (button == SDL_GAMEPAD_BUTTON_GUIDE) { + Uint64 now = SDL_GetTicks(); + if (down) { + gamepad->guide_button_down = now; + + if (gamepad->joystick->delayed_guide_button) { + // Skip duplicate press + return; + } + } else { + if (now < (gamepad->guide_button_down + SDL_MINIMUM_GUIDE_BUTTON_DELAY_MS)) { + gamepad->joystick->delayed_guide_button = true; + return; + } + gamepad->joystick->delayed_guide_button = false; + } + } + + // translate the event, if desired + if (SDL_EventEnabled(event.type)) { + event.common.timestamp = timestamp; + event.gbutton.which = gamepad->joystick->instance_id; + event.gbutton.button = button; + event.gbutton.down = down; + SDL_PushEvent(&event); + } +} + +static const Uint32 SDL_gamepad_event_list[] = { + SDL_EVENT_GAMEPAD_AXIS_MOTION, + SDL_EVENT_GAMEPAD_BUTTON_DOWN, + SDL_EVENT_GAMEPAD_BUTTON_UP, + SDL_EVENT_GAMEPAD_ADDED, + SDL_EVENT_GAMEPAD_REMOVED, + SDL_EVENT_GAMEPAD_REMAPPED, + SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN, + SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION, + SDL_EVENT_GAMEPAD_TOUCHPAD_UP, + SDL_EVENT_GAMEPAD_SENSOR_UPDATE, +}; + +void SDL_SetGamepadEventsEnabled(bool enabled) +{ + unsigned int i; + + for (i = 0; i < SDL_arraysize(SDL_gamepad_event_list); ++i) { + SDL_SetEventEnabled(SDL_gamepad_event_list[i], enabled); + } +} + +bool SDL_GamepadEventsEnabled(void) +{ + bool enabled = false; + unsigned int i; + + for (i = 0; i < SDL_arraysize(SDL_gamepad_event_list); ++i) { + enabled = SDL_EventEnabled(SDL_gamepad_event_list[i]); + if (enabled) { + break; + } + } + return enabled; +} + +void SDL_GamepadHandleDelayedGuideButton(SDL_Joystick *joystick) +{ + SDL_Gamepad *gamepad; + + SDL_AssertJoysticksLocked(); + + for (gamepad = SDL_gamepads; gamepad; gamepad = gamepad->next) { + if (gamepad->joystick == joystick) { + SDL_SendGamepadButton(0, gamepad, SDL_GAMEPAD_BUTTON_GUIDE, false); + + // Make sure we send an update complete event for this change + if (!gamepad->joystick->update_complete) { + gamepad->joystick->update_complete = SDL_GetTicksNS(); + } + break; + } + } +} + +const char *SDL_GetGamepadAppleSFSymbolsNameForButton(SDL_Gamepad *gamepad, SDL_GamepadButton button) +{ + const char *result = NULL; +#ifdef SDL_JOYSTICK_MFI + const char *IOS_GetAppleSFSymbolsNameForButton(SDL_Gamepad *gamepad, SDL_GamepadButton button); + + SDL_LockJoysticks(); + { + CHECK_GAMEPAD_MAGIC(gamepad, NULL); + + result = IOS_GetAppleSFSymbolsNameForButton(gamepad, button); + } + SDL_UnlockJoysticks(); +#endif + return result; +} + +const char *SDL_GetGamepadAppleSFSymbolsNameForAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis) +{ + const char *result = NULL; +#ifdef SDL_JOYSTICK_MFI + const char *IOS_GetAppleSFSymbolsNameForAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis); + + SDL_LockJoysticks(); + { + CHECK_GAMEPAD_MAGIC(gamepad, NULL); + + result = IOS_GetAppleSFSymbolsNameForAxis(gamepad, axis); + } + SDL_UnlockJoysticks(); +#endif + return result; +} diff --git a/thirdparty/sdl/joystick/SDL_gamepad_c.h b/thirdparty/sdl/joystick/SDL_gamepad_c.h new file mode 100644 index 00000000000..f1b1d10e158 --- /dev/null +++ b/thirdparty/sdl/joystick/SDL_gamepad_c.h @@ -0,0 +1,50 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_gamepad_c_h_ +#define SDL_gamepad_c_h_ + +#include "SDL_internal.h" + +// Useful functions and variables from SDL_gamepad.c + +// Initialization and shutdown functions +extern bool SDL_InitGamepadMappings(void); +extern void SDL_QuitGamepadMappings(void); +extern bool SDL_InitGamepads(void); +extern void SDL_QuitGamepads(void); + +extern void SDL_PrivateGamepadAdded(SDL_JoystickID instance_id); +extern void SDL_PrivateGamepadRemoved(SDL_JoystickID instance_id); + +// Function to return whether a joystick name and GUID is a gamepad +extern bool SDL_IsGamepadNameAndGUID(const char *name, SDL_GUID guid); + +// Function to return whether a gamepad should be ignored +extern bool SDL_ShouldIgnoreGamepad(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name); + +// Handle delayed guide button on a gamepad +extern void SDL_GamepadHandleDelayedGuideButton(SDL_Joystick *joystick); + +// Handle system sensor data +extern void SDL_GamepadSensorWatcher(Uint64 timestamp, SDL_SensorID sensor, Uint64 sensor_timestamp, float *data, int num_values); + +#endif // SDL_gamepad_c_h_ diff --git a/thirdparty/sdl/joystick/SDL_gamepad_db.h b/thirdparty/sdl/joystick/SDL_gamepad_db.h new file mode 100644 index 00000000000..a0f8ea8e891 --- /dev/null +++ b/thirdparty/sdl/joystick/SDL_gamepad_db.h @@ -0,0 +1,913 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +/* Default mappings we support + + The easiest way to generate a new mapping is to start Steam in Big Picture + mode, configure your joystick and then look in config/config.vdf in your + Steam installation directory for the "SDL_GamepadBind" entry. + + Alternatively, you can use the app located in test/controllermap + */ +static const char *s_GamepadMappings[] = { +#ifdef SDL_JOYSTICK_PRIVATE + SDL_PRIVATE_GAMEPAD_DEFINITIONS +#endif +#ifdef SDL_JOYSTICK_XINPUT + "xinput,*,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", +#endif +#ifdef SDL_JOYSTICK_WGI + "03000000491900001904000000007700,Amazon Luna Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,misc1:b9,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b7,x:b2,y:b3,", + "03000000d11800000094000000007700,Google Stadia Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b12,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", + "030000007e0500000920000000007701,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000004c050000c405000000007701,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000e60c000000007700,PS5 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,misc1:b14,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "0300000032150000000a000000007703,Razer Atrox Arcade Stick,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b11,dpup:b10,leftshoulder:b4,lefttrigger:b8,rightshoulder:b5,righttrigger:b9,x:b2,y:b3,", + "03000000de280000ff11000000007701,Steam Virtual Gamepad,a:b0,b:b1,back:b6,dpdown:b12,dpleft:b13,dpright:b11,dpup:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a4,leftx:a1,lefty:a0~,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a2~,start:b7,x:b2,y:b3,", +#endif +#ifdef SDL_JOYSTICK_DINPUT + "03000000fa2d00000100000000000000,3DRUDDER,leftx:a0,lefty:a1,rightx:a5,righty:a2,", + "03000000c82d00000090000000000000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00001038000000000000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000650000000000000,8BitDo M30 Gamepad,a:b0,b:b1,back:b10,guide:b2,leftshoulder:b8,lefttrigger:b9,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:b7,start:b11,x:b3,y:b4,", + "03000000c82d00005106000000000000,8BitDo M30 Gamepad,+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b10,guide:b2,leftshoulder:b8,lefttrigger:b9,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:b7,start:b11,x:b3,y:b4,", + "03000000c82d00002090000000000000,8BitDo Micro gamepad,a:b1,b:b0,back:b10,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,guide:b12,leftshoulder:b6,lefttrigger:b8,rightshoulder:b7,righttrigger:b9,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00001590000000000000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00006528000000000000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000003512000012ab000000000000,8BitDo NES30 Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000022000000090000000000000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000203800000900000000000000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00002038000000000000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000660000000000000,8BitDo Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000060000000000000,8BitDo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000061000000000000,8BitDo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000102800000900000000000000,8BitDo SFC30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00001290000000000000,8BitDo SN30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00006228000000000000,8BitDo SN30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000260000000000000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000261000000000000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000160000000000000,8BitDo SN30 Pro,crc:769e,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", /* Firmware v2.00, USB */ + "03000000c82d00000160000000000000,8BitDo SN30 Pro,crc:fa59,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", /* Firmware v1.26, USB */ + "03000000c82d00000161000000000000,8BitDo SN30 Pro,crc:190b,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", /* Bluetooth, firmware v1.26 uses b2 for guide, firmware v2.00 uses b12 for guide */ + "030000003512000020ab000000000000,8BitDo SNES30 Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00001b30000000000000,8BitDo Ultimate 2C Wireless,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a2,paddle1:b5,paddle2:b2,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a5,start:b11,x:b3,y:b4,", /* Bluetooth */ + "03000000c82d00001130000000000000,8BitDo Ultimate Wired Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,misc1:b26,paddle1:b24,paddle2:b25,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000c82d00001330000000000000,8BitDo Ultimate Wireless Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,misc1:b26,paddle1:b23,paddle2:b19,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000c82d00001890000000000000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00003032000000000000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000a00500003232000000000000,8BitDo Zero Gamepad,a:b1,b:b0,back:b10,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000050b00000579000000000000,ASUS ROG Kunai 3 Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000050b00000679000000000000,ASUS ROG Kunai 3 Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,misc1:b15,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "030000008f0e00001200000000000000,Acme GA-02,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", + "03000000fa190000f0ff000000000000,Acteck AGJ-3200,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000341a00003608000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006f0e00000263000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006f0e00001101000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006f0e00001401000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006f0e00001402000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006f0e00001901000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006f0e00001a01000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000d62000001d57000000000000,Airflo PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000491900001904000000000000,Amazon Luna Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,misc1:b9,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b7,x:b2,y:b3,", + "03000000d62000002a79000000000000,BDA PS4 Fightpad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000d81d00000b00000000000000,BUFFALO BSGP1601 Series ,a:b5,b:b3,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b8,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b9,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b13,x:b4,y:b2,", + "03000000d6200000e557000000000000,Batarang,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000c01100001352000000000000,Battalife Joystick,a:b6,b:b7,back:b2,leftshoulder:b0,leftx:a0,lefty:a1,rightshoulder:b1,start:b3,x:b4,y:b5,", + "030000006f0e00003201000000000000,Battlefield 4 PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000bc2000006012000000000000,Betop 2126F,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000bc2000000055000000000000,Betop BFM Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000bc2000006312000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000bc2000006412000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000c01100000555000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000c01100000655000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000790000000700000000000000,Betop Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,", + "03000000808300000300000000000000,Betop Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,", + "030000006b1400000055000000000000,Bigben PS3 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "030000006b1400000103000000000000,Bigben PS3 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,", + "0300000066f700000500000000000000,BrutalLegendTest,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b3,", + "03000000e82000006058000000000000,Cideko AK08b,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000260900008888000000000000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a4,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,", + "03000000a306000022f6000000000000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", + "03000000451300000830000000000000,Defender Game Racer X7,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000790000000600000000000000,Defender Joystick Cobra R4,crc:c77a,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2~,righty:a3~,start:b9,x:b3,y:b0,", + "03000000791d00000103000000000000,Dual Box WII,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000bd12000002e0000000000000,Dual USB Vibration Joystick,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a3,righty:a2,start:b11,x:b3,y:b0,", + "030000006f0e00003001000000000000,EA SPORTS PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000341a00000108000000000000,EXEQ RF USB Gamepad 8206,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "030000008f0e00000f31000000000000,EXEQ,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,", + "03000000b80500000410000000000000,Elecom Gamepad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b1,", + "03000000b80500000610000000000000,Elecom Gamepad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b1,", + "03000000852100000201000000000000,FF-GP1,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00002700000000000000,FIGHTING STICK V3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000008f0e00000d31000000000000,GAMEPAD 3 TURBO,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000300f00000b01000000000000,GGE909 Recoil Pad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", + "03000000790000002201000000000000,Game Controller for PC,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "0300000066f700000100000000000000,Game VIB Joystick,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,start:b11,x:b0,y:b1,", + "03000000491900000204000000000000,GameSir T4 Pro,crc:1aa4,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000ac0500003d03000000000000,GameSir,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000ac0500004d04000000000000,GameSir,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000ac0500001a06000000000000,GameSir-T3 2.02,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000ffff00000000000000000000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000c01100000140000000000000,GameStop PS4 Fun Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000260900002625000000000000,Gamecube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,lefttrigger:a4,leftx:a0,lefty:a1,righttrigger:a5,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", + "03000000280400000140000000000000,Gamepad Pro USB,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000005c1a00003330000000000000,Genius MaxFire Grandias 12V,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b4,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", + "030000008305000031b0000000000000,Genius Maxfire Blaze 3,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000451300000010000000000000,Genius Maxfire Grandias 12,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "030000008305000009a0000000000000,Genius,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000f025000021c1000000000000,Gioteck PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000f0250000c383000000000000,Gioteck VX2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000f0250000c483000000000000,Gioteck VX2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000f0250000c283000000000000,Gioteck,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000d11800000094000000000000,Google Stadia Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:b12,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:b11,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", + "03000000632500002605000000000000,HJD-X,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "030000000d0f00008400000000000000,HORI Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00008500000000000000,HORI Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00008800000000000000,HORI Fighting Stick mini 4 (PS3),a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b8,x:b0,y:b3,", + "030000000d0f00008700000000000000,HORI Fighting Stick mini 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000000d0f00006e00000000000000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00006600000000000000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f0000ee00000000000000,HORIPAD mini4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000250900000017000000000000,HRAP2 on PS/SS/N64 Joypad to USB BOX,a:b2,b:b1,back:b9,leftshoulder:b5,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b6,start:b8,x:b3,y:b0,", + "03000000341a00000302000000000000,Hama Scorpad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00004900000000000000,Hatsune Miku Sho Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000d81400000862000000000000,HitBox Edition Cthulhu+,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,lefttrigger:b4,rightshoulder:b7,righttrigger:b6,start:b9,x:b0,y:b3,", + "030000000d0f00005f00000000000000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00005e00000000000000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00004000000000000000,Hori Fighting Stick Mini 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,lefttrigger:b4,rightshoulder:b7,righttrigger:b6,start:b9,x:b0,y:b3,", + "030000000d0f00000900000000000000,Hori Pad 3 Turbo,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00005400000000000000,Hori Pad 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00004d00000000000000,Hori Pad A,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00009200000000000000,Hori Pokken Tournament DX Pro Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000000d0f0000c100000000000000,Horipad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000008f0e00001330000000000000,HuiJia SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b9,x:b3,y:b0,", + "030000006f0e00002401000000000000,INJUSTICE FightStick PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "03000000ac0500002c02000000000000,IPEGA,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b8,leftstick:b13,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b9,rightstick:b14,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000b50700001403000000000000,Impact Black,a:b2,b:b3,back:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", + "03000000491900000204000000000000,Ipega PG-9023,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "030000006e0500000520000000000000,JC-P301U,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,", + "030000006e0500000320000000000000,JC-U3613M (DInput),a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,", + "030000006e0500000720000000000000,JC-W01U,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b1,", + "03000000790000000200000000000000,King PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,", + "030000006d040000d1ca000000000000,Logitech ChillStream,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d040000d2ca000000000000,Logitech Cordless Precision,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d04000011c2000000000000,Logitech Cordless Wingman,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,leftstick:b5,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b2,righttrigger:b7,rightx:a3,righty:a4,x:b4,", + "030000006d04000016c2000000000000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d04000018c2000000000000,Logitech F510 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d04000019c2000000000000,Logitech F710 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */ + "030000006d0400001ac2000000000000,Logitech Precision Gamepad,a:b1,b:b2,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "03000000380700008081000000000000,MADCATZ SFV Arcade FightStick Alpha PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000380700006382000000000000,MLG Gamepad PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000c62400002a89000000000000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000c62400002b89000000000000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000c62400001a89000000000000,MOGA XP5-X Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000c62400001b89000000000000,MOGA XP5-X Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000250900006688000000000000,MP-8866 Super Dual Box,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", + "03000000380700006652000000000000,Mad Catz C.T.R.L.R,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,", + "03000000380700005032000000000000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700005082000000000000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000380700008433000000000000,Mad Catz FightStick TE S+ (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700008483000000000000,Mad Catz FightStick TE S+ (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000380700008134000000000000,Mad Catz FightStick TE2+ PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b7,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b4,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700008184000000000000,Mad Catz FightStick TE2+ PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,leftstick:b10,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b4,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000380700006252000000000000,Mad Catz Micro C.T.R.L.R,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,", + "03000000380700008034000000000000,Mad Catz TE2 PS3 Fightstick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700008084000000000000,Mad Catz TE2 PS4 Fightstick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000380700001888000000000000,MadCatz SFIV FightStick PS3,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b4,righttrigger:b6,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000380700008532000000000000,Madcatz Arcade Fightstick TE S PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700003888000000000000,Madcatz Arcade Fightstick TE S+ PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000002a0600001024000000000000,Matricom,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", + "03000000250900000128000000000000,Mayflash Arcade Stick,a:b1,b:b2,back:b8,leftshoulder:b0,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b3,righttrigger:b7,start:b9,x:b5,y:b6,", + "03000000790000004418000000000000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,", + "030000008f0e00001030000000000000,Mayflash USB Adapter for original Sega Saturn controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,lefttrigger:b5,rightshoulder:b2,righttrigger:b7,start:b9,x:b3,y:b4,", + "0300000025090000e803000000000000,Mayflash Wii Classic Controller,a:b1,b:b0,back:b8,dpdown:b13,dpleft:b12,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,", + "03000000790000000018000000000000,Mayflash WiiU Pro Game Controller Adapter (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000efbe0000edfe000000000000,Monect Virtual Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b0,", + "030000006b140000010c000000000000,NACON GC-400ES,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "030000001008000001e5000000000000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,", + "03000000152000000182000000000000,NGDS,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,", + "030000005509000000b4000000000000,NVIDIA Virtual Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000004b120000014d000000000000,NYKO AIRFLO EX,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", + "03000000790000004318000000000000,Nintendo GameCube Controller,a:b1,b:b0,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b2,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000bd12000015d0000000000000,Nintendo Retrolink USB Super SNES Classic Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,start:b9,x:b3,y:b0,", + "030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000000d0500000308000000000000,Nostromo N45,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b12,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b10,x:b2,y:b3,", + "03000000d62000006d57000000000000,OPP PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000362800000100000000000000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:b13,rightx:a3,righty:a4,x:b1,y:b2,", + "03000000782300000a10000000000000,Onlive Wireless Controller,a:b15,b:b14,back:b7,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b11,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b13,y:b12,", + "030000006b14000001a1000000000000,Orange Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b2,y:b3,", + "0300000009120000072f000000000000,OrangeFox86 DreamPicoPort,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:-a2,leftx:a0,lefty:a1,rightx:a3,righty:a4,righttrigger:-a5,start:b11,x:b3,y:b4,", + "03000000120c0000f60e000000000000,P4 Wired Gamepad,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b5,lefttrigger:b7,rightshoulder:b4,righttrigger:b6,start:b9,x:b0,y:b3,", + "030000006f0e00000901000000000000,PDP Versus Fighting Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "03000000632500002306000000000000,PS Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000e30500009605000000000000,PS to USB convert cable,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", + "03000000100800000100000000000000,PS1 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", + "030000008f0e00007530000000000000,PS1 Controller,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b1,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000100800000300000000000000,PS2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a4,righty:a2,start:b9,x:b3,y:b0,", + "03000000250900008888000000000000,PS2 Controller,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", + "03000000666600006706000000000000,PS2 Controller,a:b2,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a2,righty:a3,start:b11,x:b3,y:b0,", + "030000006b1400000303000000000000,PS2 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "030000009d0d00001330000000000000,PS2 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000250900000500000000000000,PS3 Controller,a:b2,b:b1,back:b9,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b0,y:b3,", + "030000004c0500006802000000000000,PS3 Controller,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b10,lefttrigger:a3~,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:a4~,rightx:a2,righty:a5,start:b8,x:b3,y:b0,", + "03000000632500007505000000000000,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000888800000803000000000000,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b9,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b0,y:b3,", + "030000008f0e00001431000000000000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000003807000056a8000000000000,PS3 RF pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000100000008200000000000000,PS360+ v1.66,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:h0.4,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000004c050000a00b000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000c405000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,touchpad:b13,x:b0,y:b3,", + "030000004c050000cc09000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000e60c000000000000,PS5 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,misc1:b13,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000008f0e00000300000000000000,Piranha xtreme,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", + "03000000d62000002640000000000000,PowerA OPS v1 Wireless Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000d62000003340000000000000,PowerA OPS v3 Pro Wireless Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000d62000006dca000000000000,PowerA Pro Ex,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000d62000009557000000000000,Pro Elite PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000d62000009f31000000000000,Pro Ex mini PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000d6200000c757000000000000,Pro Ex mini PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000222c00000020000000000000,QANBA DRONE ARCADE JOYSTICK,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,rightshoulder:b5,righttrigger:a4,start:b9,x:b0,y:b3,", + "03000000300f00000011000000000000,QanBa Arcade JoyStick 1008,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b10,x:b0,y:b3,", + "03000000300f00001611000000000000,QanBa Arcade JoyStick 4018,a:b1,b:b2,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b8,x:b0,y:b3,", + "03000000300f00001210000000000000,QanBa Joystick Plus,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b2,y:b3,", + "03000000341a00000104000000000000,QanBa Joystick Q4RAF,a:b5,b:b6,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b0,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b3,righttrigger:b7,start:b9,x:b1,y:b2,", + "03000000222c00000025000000000000,Qanba Dragon Arcade Joystick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000222c00000223000000000000,Qanba Obsidian Arcade Joystick (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000222c00000023000000000000,Qanba Obsidian Arcade Joystick (PS4),a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00001100000000000000,REAL ARCADE PRO.3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,rightstick:b11,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000000d0f00007000000000000000,REAL ARCADE PRO.4 VLX,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,rightstick:b11,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000000d0f00002200000000000000,REAL ARCADE Pro.V3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000050b00005819000000000000,ROG Chakram Core,a:b1,b:b0,leftx:a0,lefty:a1,x:b2,y:b3,", + "03000000050b0000181a000000000000,ROG Chakram X,a:b1,b:b0,leftx:a0,lefty:a1,x:b2,y:b3,", + "03000000050b00001a1a000000000000,ROG Chakram X,a:b1,b:b0,leftx:a0,lefty:a1,x:b2,y:b3,", + "03000000050b00001c1a000000000000,ROG Chakram X,a:b1,b:b0,leftx:a0,lefty:a1,x:b2,y:b3,", + "03000000050b0000e318000000000000,ROG Chakram,a:b1,b:b0,leftx:a0,lefty:a1,x:b2,y:b3,", + "03000000050b0000e518000000000000,ROG Chakram,a:b1,b:b0,leftx:a0,lefty:a1,x:b2,y:b3,", + "030000000d0f0000ad00000000000000,RX Gamepad,a:b0,b:b4,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b3,rightshoulder:b6,start:b9,x:b2,y:b1,", + "03000000321500000003000000000000,Razer Hydra,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000321500000204000000000000,Razer Panthera (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000321500000104000000000000,Razer Panthera (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000321500000507000000000000,Razer Raiju Mobile,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000321500000707000000000000,Razer Raiju Mobile,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000321500000011000000000000,Razer Raion Fightpad for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000321500000009000000000000,Razer Serval,+lefty:+a2,-lefty:-a1,a:b0,b:b1,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,leftx:a0,rightshoulder:b5,rightstick:b9,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000000d0f00006a00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00006b00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00008a00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00008b00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00005b00000000000000,Real Arcade Pro.V4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00005c00000000000000,Real Arcade Pro.V4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "0300000000f000000300000000000000,RetroUSB.com RetroPad,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,", + "0300000000f00000f100000000000000,RetroUSB.com Super RetroPort,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,", + "03000000790000001100000000000000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a4,dpleft:-a3,dpright:+a3,dpup:-a4,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000006b140000130d000000000000,Revolution Pro Controller 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000006b140000010d000000000000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000006f0e00001e01000000000000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006f0e00002801000000000000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006f0e00002f01000000000000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000341a00000208000000000000,SL-6555-SBK,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:-a4,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a4,rightx:a3,righty:a2,start:b7,x:b2,y:b3,", + "03000000341a00000908000000000000,SL-6566,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000790000000600000000000000,SPEEDLINK STRIKE Gamepad,crc:5811,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,", + "03000000790000001c18000000000000,STK-7024X,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000ff1100003133000000000000,SVEN X-PAD,a:b2,b:b3,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b9,rightx:a2,righty:a4,start:b5,x:b0,y:b1,", + "03000000457500002211000000000000,SZMY-POWER PC Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000a306000023f6000000000000,Saitek Cyborg V.1 Game pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", + "03000000a30600001af5000000000000,Saitek Cyborg,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,", + "03000000300f00001201000000000000,Saitek Dual Analog Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", + "03000000a30600000cff000000000000,Saitek P2500 Force Rumble Pad,a:b2,b:b3,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,x:b0,y:b1,", + "03000000a30600000c04000000000000,Saitek P2900,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b3,", + "03000000300f00001001000000000000,Saitek P480 Rumble Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", + "03000000a30600000b04000000010000,Saitek P990 Dual Analog Pad,a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b8,x:b0,y:b3,", + "03000000a30600000b04000000000000,Saitek P990,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b3,", + "03000000a30600002106000000000000,Saitek PS1000,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", + "03000000a306000020f6000000000000,Saitek PS2700,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", + "03000000300f00001101000000000000,Saitek Rumble Pad,a:b2,b:b3,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", + "0300000000050000289b000000000000,Saturn_Adapter_2.0,a:b1,b:b2,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b0,y:b3,", + "030000009b2800000500000000000000,Saturn_Adapter_2.0,a:b1,b:b2,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b0,y:b3,", + "030000008f0e00000800000000000000,SpeedLink Strike FX,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000c01100000591000000000000,Speedlink Torid,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "030000004c0500006802000000000000,SplitFish Game Controller,crc:5628,a:b0,b:b16,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,leftshoulder:b17,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b10,", + "03000000de280000ff11000000000000,Steam Virtual Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000110100003114000000000000,SteelSeries Stratus Duo,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000381000001814000000000000,SteelSeries Stratus XL,a:b0,b:b1,back:b18,dpdown:b13,dpleft:b14,dpright:b15,dpup:b12,guide:b19,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b2,y:b3,", + "03000000110100001914000000000000,SteelSeries,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:,leftstick:b13,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:,rightstick:b14,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000d620000011a7000000000000,Switch,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000004f04000007d0000000000000,T Mini Wireless,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000fa1900000706000000000000,Team 5,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000b50700001203000000000000,Techmobility X6-38V,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", + "030000004f0400000ed0000000000000,ThrustMaster eSwap PRO Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004f04000015b3000000000000,Thrustmaster Dual Analog 4,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", + "030000004f04000023b3000000000000,Thrustmaster Dual Trigger 3-in-1,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004f04000004b3000000000000,Thrustmaster Firestorm Dual Power 3,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", + "030000004f04000000b3000000000000,Thrustmaster Firestorm Dual Power,a:b0,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b11,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b10,x:b1,y:b3,", + "03000000666600000488000000000000,TigerGame PS/PS2 Game Controller Adapter,a:b2,b:b1,back:b9,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", + "03000000d62000006000000000000000,Tournament PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000005f140000c501000000000000,Trust Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000b80500000210000000000000,Trust Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000d90400000200000000000000,TwinShock PS2,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", + "03000000300f00000701000000000000,USB 4-Axis 12-Button Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", + "03000000341a00002308000000000000,USB Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "030000006b1400000203000000000000,USB Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000790000000a00000000000000,USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,", + "03000000f0250000c183000000000000,USB Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000ff1100004133000000000000,USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a4,righty:a2,start:b9,x:b3,y:b0,", + "03000000632500002305000000000000,USB Vibration Joystick (BM),a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000790000001b18000000000000,Venom Arcade Joystick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000006f0e00000302000000000000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000006f0e00000702000000000000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "03000000450c00002043000000000000,XEOX Gamepad SL-6556-BK,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000341a00000608000000000000,Xeox,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000172700004431000000000000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b20,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a7,rightx:a2,righty:a5,start:b11,x:b3,y:b4,", + "03000000c0160000e105000000000000,Xin-Mo Dual Arcade,crc:2246,a:b1,b:b2,back:b9,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,rightshoulder:b4,righttrigger:b5,start:b8,x:b0,y:b3,", /* Ultimate Atari Fight Stick */ + "03000000790000004f18000000000000,ZD-T Android,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", + "03000000120c0000101e000000000000,ZEROPLUS P4 Wired Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000d81d00000f00000000000000,iBUFFALO BSGP1204 Series,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000d81d00001000000000000000,iBUFFALO BSGP1204P Series,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000830500006020000000000000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000004f04000003d0000000000000,run'n'drive,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b7,leftshoulder:a3,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:a4,rightstick:b11,righttrigger:b5,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000101c0000171c000000000000,uRage Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", +#endif +#ifdef SDL_PLATFORM_MACOS + "03000000c82d00000090000001000000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00001038000000010000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000650000001000000,8BitDo M30 Gamepad,a:b1,b:b0,back:b10,guide:b2,leftshoulder:b6,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a5,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00005106000000010000,8BitDo M30 Gamepad,a:b1,b:b0,back:b10,guide:b2,leftshoulder:b6,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000ac05000004000000a8986d04,8BitDo Micro gamepad,a:b1,b:b0,back:b4,dpdown:b7,dpleft:b8,dpright:b9,dpup:b10,guide:b2,leftshoulder:b11,lefttrigger:b12,rightshoulder:b13,righttrigger:b14,start:b3,x:b6,y:b5,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00001590000001000000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00006528000000010000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000003512000012ab000001000000,8BitDo NES30 Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000022000000090000001000000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000203800000900000000010000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000660000000020000,8BitDo Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000102800000900000000000000,8BitDo SFC30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00001290000001000000,8BitDo SN30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000260000001000000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000261000000010000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000160000001000000,8BitDo SN30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00001b30000001000000,8BitDo Ultimate 2C Wireless,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,paddle1:b2,paddle2:b5,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", /* Bluetooth */ + "03000000c82d00001130000000020000,8BitDo Ultimate Wired Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b26,paddle1:b24,paddle2:b25,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000c82d00001330000000020000,8BitDo Ultimate Wireless Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b26,paddle1:b23,paddle2:b19,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000c82d00001890000001000000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00003032000000010000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000a00500003232000008010000,8BitDo Zero Gamepad,a:b1,b:b2,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000a00500003232000009010000,8BitDo Zero Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000050b00000579000000010000,ASUS ROG Kunai 3 Gamepad,a:b0,b:b1,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b14,leftshoulder:b6,leftstick:b15,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b42,paddle1:b9,paddle2:b11,rightshoulder:b7,rightstick:b16,righttrigger:a4,rightx:a2,righty:a3,start:b13,x:b3,y:b4,", + "03000000050b00000679000000010000,ASUS ROG Kunai 3 Gamepad,a:b0,b:b1,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b14,leftshoulder:b6,leftstick:b15,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b23,rightshoulder:b7,rightstick:b16,righttrigger:a4,rightx:a2,righty:a3,start:b13,x:b3,y:b4,", + "03000000491900001904000001010000,Amazon Luna Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,misc1:b9,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b7,x:b2,y:b3,", + "03000000710100001904000000010000,Amazon Luna Controller,a:b0,b:b1,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b9,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "03000000c62400001a89000000010000,BDA MOGA XP5-X Plus,a:b0,b:b1,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b14,leftshoulder:b6,leftstick:b15,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b16,righttrigger:a4,rightx:a2,righty:a3,start:b13,x:b3,y:b4,", + "03000000c62400001b89000000010000,BDA MOGA XP5-X Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000d62000002a79000000010000,BDA PS4 Fightpad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000008305000031b0000000000000,Cideko AK08b,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000260900008888000088020000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a5,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,", + "03000000a306000022f6000001030000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", + "030000000d0f00008400000000010000,Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00008500000000010000,Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000ac0500001a06000002020000,GameSir-T3 2.02,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000c01100000140000000010000,GameStop PS4 Fun Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000ad1b000001f9000000000000,Gamestop BB-070 X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "03000000d11800000094000000010000,Google Stadia Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", + "030000000d0f00005f00000000000000,HORI Fighting Commander 4 PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00005e00000000000000,HORI Fighting Commander 4 PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00008800000000010000,HORI Fighting Stick mini 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,rightstick:b11,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000000d0f00008700000000010000,HORI Fighting Stick mini 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,rightstick:b11,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000000d0f00004d00000000000000,HORI Gem Pad 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f0000aa00000072050000,HORI Real Arcade Pro,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "030000000d0f00006e00000000010000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00006600000000010000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00006600000000000000,HORIPAD FPS PLUS 4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00005f00000000010000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00005e00000000010000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000008f0e00001330000011010000,HuiJia SNES Controller,a:b4,b:b2,back:b16,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,leftshoulder:b12,rightshoulder:b14,start:b18,x:b6,y:b0,", + "030000006d04000016c2000000020000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d04000016c2000000030000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d04000016c2000014040000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d04000016c2000000000000,Logitech F310 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */ + "030000006d04000018c2000000000000,Logitech F510 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d0400001fc2000000000000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "030000006d04000019c2000000000000,Logitech Wireless Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* This includes F710 in DInput mode and the "Logitech Cordless RumblePad 2", at the very least. */ + "03000000d8140000cecf000000000000,MC Cthulhu,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "03000000c62400002a89000000010000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b21,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000c62400002b89000000010000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000380700005032000000010000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700005082000000010000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000380700008433000000010000,Mad Catz FightStick TE S+ (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700008483000000010000,Mad Catz FightStick TE S+ (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000790000004418000000010000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,", + "0300000025090000e803000000000000,Mayflash Wii Classic Controller,a:b1,b:b0,back:b8,dpdown:b13,dpleft:b12,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,", + "03000000790000000018000000000000,Mayflash WiiU Pro Game Controller Adapter (DInput),a:b4,b:b8,back:b32,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b16,leftstick:b40,lefttrigger:b24,leftx:a0,lefty:a4,rightshoulder:b20,rightstick:b44,righttrigger:b28,rightx:a8,righty:a12,start:b36,x:b0,y:b12,", + "030000001008000001e5000006010000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,", + "03000000550900001472000025050000,NVIDIA Controller v01.04,a:b0,b:b1,back:b17,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b4,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,", + "030000004b120000014d000000010000,NYKO AIRFLO EX,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", + "030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "050000007e05000009200000ff070000,Nintendo Switch Pro Controller,a:b1,b:b0,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "0300000009120000072f000000010000,OrangeFox86 DreamPicoPort,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a2,leftx:a0,lefty:a1,rightx:a3,righty:a4,righttrigger:a5,start:b11,x:b3,y:b4,", + "030000006f0e00000901000002010000,PDP Versus Fighting Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000004c0500006802000000000000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", + "030000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", + "030000004c050000a00b000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000c405000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000c405000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "050000004c050000e60c000000010000,PS5 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,misc1:b13,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000008f0e00000300000000000000,Piranha xtreme,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", + "03000000222c00000225000000010000,Qanba Dragon Arcade Joystick (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000008916000000fd000000000000,Razer Onza TE,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "03000000321500000204000000010000,Razer Panthera (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000321500000104000000010000,Razer Panthera (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000321500000010000000010000,Razer RAIJU,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000321500000507000001010000,Razer Raiju Mobile,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b21,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000321500000011000000010000,Razer Raion Fightpad for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000321500000009000000020000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", + "0300000032150000030a000000000000,Razer Wildcat,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "03000000790000001100000000000000,Retrolink Classic Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a3,lefty:a4,rightshoulder:b5,start:b9,x:b3,y:b0,", + "03000000790000001100000006010000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a4,dpleft:-a3,dpright:+a3,dpup:-a4,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000006b140000130d000000010000,Revolution Pro Controller 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000006b140000010d000000010000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000003512000021ab000000000000,SFC30 Joystick,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,", + "03000000457500002211000000010000,SZMY-POWER PC Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000b40400000a01000000000000,Sega Saturn USB Gamepad,a:b0,b:b1,back:b5,guide:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b8,x:b3,y:b4,", + "03000000811700007e05000000000000,Sega Saturn,a:b2,b:b4,dpdown:b16,dpleft:b15,dpright:b14,dpup:b17,leftshoulder:b8,lefttrigger:a5,leftx:a0,lefty:a2,rightshoulder:b9,righttrigger:a4,start:b13,x:b0,y:b6,", + "030000004c050000cc09000000000000,Sony DualShock 4 V2,a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000a00b000000000000,Sony DualShock 4 Wireless Adaptor,a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000005e0400008e02000001000000,Steam Virtual Gamepad,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "050000004e696d6275732b0000000000,SteelSeries Nimbus+,a:b0,b:b1,back:b15,dpdown:b11,dpleft:b13,dpright:b12,dpup:b10,guide:b16,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3~,start:b14,x:b2,y:b3,", + "03000000110100002014000000000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b12,x:b2,y:b3,", + "03000000110100002014000001000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,x:b2,y:b3,", + "03000000381000002014000001000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,x:b2,y:b3,", + "03000000110100001714000000000000,SteelSeries Stratus XL,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,start:b12,x:b2,y:b3,", + "03000000110100001714000020010000,SteelSeries Stratus XL,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,start:b12,x:b2,y:b3,", + "030000004f0400000ed0000000020000,ThrustMaster eSwap PRO Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004f04000015b3000000000000,Thrustmaster Dual Analog 3.2,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", + "030000004f04000000b3000000000000,Thrustmaster Firestorm Dual Power,a:b0,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b11,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:b7,rightx:a2,righty:a3,start:b10,x:b1,y:b3,", + "03000000bd12000015d0000000000000,Tomee SNES USB Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,start:b9,x:b3,y:b0,", + "03000000bd12000015d0000000010000,Tomee SNES USB Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,", + "03000000100800000100000000000000,Twin USB Joystick,a:b4,b:b2,back:b16,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b12,leftstick:b20,lefttrigger:b8,leftx:a0,lefty:a2,rightshoulder:b14,rightstick:b22,righttrigger:b10,rightx:a6,righty:a4,start:b18,x:b6,y:b0,", + "030000006f0e00000302000025040000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000006f0e00000702000003060000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "050000005769696d6f74652028303000,Wii Remote,a:b4,b:b5,back:b7,dpdown:b3,dpleft:b0,dpright:b1,dpup:b2,guide:b8,leftshoulder:b11,lefttrigger:b12,leftx:a0,lefty:a1,start:b6,x:b10,y:b9,", + "050000005769696d6f74652028313800,Wii U Pro Controller,a:b16,b:b15,back:b7,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b8,leftshoulder:b19,leftstick:b23,lefttrigger:b21,leftx:a0,lefty:a1,rightshoulder:b20,rightstick:b24,righttrigger:b22,rightx:a2,righty:a3,start:b6,x:b18,y:b17,", + "030000005e0400008e02000000000000,X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "03000000c6240000045d000000000000,Xbox 360 Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "030000005e040000050b000003090000,Xbox Elite Wireless Controller,a:b0,b:b1,back:b38,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "030000005e040000d102000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "030000005e040000dd02000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "030000005e040000e302000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "030000005e040000200b000011050000,Xbox Wireless Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "030000005e040000e002000000000000,Xbox Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e040000e002000003090000,Xbox Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e040000ea02000000000000,Xbox Wireless Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", + "030000005e040000fd02000003090000,Xbox Wireless Controller,a:b0,b:b1,back:b16,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000172700004431000029010000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a5,start:b11,x:b3,y:b4,", + "03000000c0160000e105000000040000,Xin-Mo Dual Arcade,crc:82d5,a:b2,b:b4,back:b18,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,rightshoulder:b8,righttrigger:b10,start:b16,x:b0,y:b6,", /* Ultimate Atari Fight Stick */ + "03000000120c0000100e000000010000,ZEROPLUS P4 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000120c0000101e000000010000,ZEROPLUS P4 Wired Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000830500006020000000010000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000830500006020000000000000,iBuffalo USB 2-axis 8-button Gamepad,a:b1,b:b0,back:b6,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,start:b7,x:b3,y:b2,", +#endif +#if defined(SDL_JOYSTICK_LINUX) || defined(SDL_PLATFORM_OPENBSD) + "03000000c82d00000090000011010000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00001038000000010000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00005106000000010000,8BitDo M30 Gamepad,a:b1,b:b0,back:b10,guide:b2,leftshoulder:b6,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00002090000000010000,8BitDo Micro gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,guide:b12,leftshoulder:b6,lefttrigger:b8,rightshoulder:b7,righttrigger:b9,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00001590000011010000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00006528000000010000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000003512000012ab000010010000,8BitDo NES30 Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000022000000090000011010000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000190000011010000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000203800000900000000010000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00002038000000010000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000020000000000000,8BitDo Pro 2 Wired Controller for Xbox,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "06000000c82d00000020000006010000,8BitDo Pro 2 Wired Controller for Xbox,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000c82d00000660000011010000,8BitDo Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00000660000000010000,8BitDo Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00000061000000010000,8BitDo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000102800000900000000010000,8BitDo SFC30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00003028000000010000,8BitDo SFC30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000260000011010000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00000261000000010000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000160000011010000,8BitDo SN30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000003512000020ab000010010000,8BitDo SNES30 Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000202800000900000000010000,8BitDo SNES30 Gamepad,a:b1,b:b0,back:b10,dpdown:b122,dpleft:b119,dpright:b120,dpup:b117,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00001b30000001000000,8BitDo Ultimate 2C Wireless,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,paddle1:b5,paddle2:b2,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", /* Bluetooth */ + "03000000c82d00001130000011010000,8BitDo Ultimate Wired Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b26,paddle1:b24,paddle2:b25,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000c82d00001330000011010000,8BitDo Ultimate Wireless Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b26,paddle1:b23,paddle2:b19,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000c82d00001890000011010000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00003032000000010000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000a00500003232000001000000,8BitDo Zero Gamepad,a:b1,b:b0,back:b10,dpdown:b122,dpleft:b119,dpright:b120,dpup:b117,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000a00500003232000008010000,8BitDo Zero Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000c82d00000031000011010000,8Bitdo Receiver,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,", + "03000000c82d00001290000011010000,8Bitdo SN30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d00006228000000010000,8Bitdo SN30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000050b00000045000031000000,ASUS Gamepad,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b10,x:b2,y:b3,", + "05000000050b00000045000040000000,ASUS Gamepad,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b10,x:b2,y:b3,", + "03000000050b00000579000011010000,ASUS ROG Kunai 3 Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b36,paddle1:b52,paddle2:b53,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "05000000050b00000679000000010000,ASUS ROG Kunai 3 Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b21,paddle1:b22,paddle2:b23,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "030000006f0e00003901000020060000,Afterglow Controller for Xbox One,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000006f0e00003901000000430000,Afterglow Prismatic Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000006f0e00001302000000010000,Afterglow,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000100000008200000011010000,Akishop Customs PS360+ v1.66,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "05000000491900000204000021000000,Amazon Fire Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b17,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b12,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000491900001904000011010000,Amazon Luna Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,misc1:b9,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b7,x:b2,y:b3,", + "05000000710100001904000000010000,Amazon Luna Controller,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b11,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "03000000790000003018000011010000,Arcade Fightstick F300,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "03000000503200000110000000000000,Atari Classic Controller,a:b0,back:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b4,start:b3,x:b1,", + "05000000503200000110000000000000,Atari Classic Controller,a:b0,back:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b4,start:b3,x:b1,", + "03000000503200000210000000000000,Atari Game Controller,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a4,rightx:a2,righty:a3,start:b8,x:b2,y:b3,", + "05000000503200000210000000000000,Atari Game Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b2,", + "05000000503200000210000000000000128804098,Atari Game Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b2,", + "030000005e0400008e02000047010000,Atari Xbox 360 Game Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000c62400001b89000011010000,BDA MOGA XP5-X Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000d62000002a79000011010000,BDA PS4 Fightpad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000120c0000f70e000011010000,Brook Universal Fighting Board,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:,lefty:,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:,righty:,start:b9,x:b0,y:b3,", + "03000000b40400000a01000000010000,CYPRESS USB Gamepad,a:b0,b:b1,back:b5,guide:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b8,x:b3,y:b4,", + "03000000ffff0000ffff000000010000,Chinese-made Xbox Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,", + "03000000e82000006058000001010000,Cideko AK08b,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000260900008888000000010000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a5,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,", + "03000000a306000022f6000011010000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", + "050000004c050000f20d000000010000,DualSense Edge Wireless Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000006f0e00003001000001010000,EA Sports PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000790000001100000010010000,Elecom Gamepad,crc:e86c,a:b2,b:b3,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b0,y:b1,", + "0300000079000000d418000000010000,GPD Win 2 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "0500000047532067616d657061640000,GS Gamepad,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000341a000005f7000010010000,GameCube {HuiJia USB box},a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,", + "03000000bc2000000055000011010000,GameSir G3w,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "0500000049190000020400001b010000,GameSir T4 Pro,crc:8283,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b23,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000373500009710000001020000,GameSir-K1 FLUX,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,misc1:b15,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000ac0500001a06000011010000,GameSir-T3 2.02,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000c01100000140000011010000,GameStop PS4 Fun Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000006f0e00000104000000010000,Gamestop Logic3 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000008f0e00000800000010010000,Gasia Co. Ltd PS(R) Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "030000006f0e00001304000000010000,Generic X-Box pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000f0250000c183000010010000,Goodbetterbest Ltd USB Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000d11800000094000011010000,Google Stadia Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", + "05000000d11800000094000000010000,Google Stadia Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", + "03000000280400000140000000010000,Gravis Gamepad Pro USB ,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000008f0e00000610000000010000,GreenAsia Electronics 4Axes 12Keys Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a3,righty:a2,start:b11,x:b3,y:b0,", + "030000008f0e00001200000010010000,GreenAsia Inc. USB Joystick,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", + "03000000c9110000f055000011010000,HJC Game GAMEPAD,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "030000000d0f00001000000011010000,HORI CO. LTD. FIGHTING STICK 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000000d0f00002200000011010000,HORI CO. LTD. REAL ARCADE Pro.V3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000000d0f00006a00000011010000,HORI CO. LTD. Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00006b00000011010000,HORI CO. LTD. Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00005001000009040000,HORI Fighting Commander OCTA,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000000d0f00008400000011010000,HORI Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00008500000010010000,HORI Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00008800000011010000,HORI Fighting Stick mini 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,rightstick:b11,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000000d0f00008700000011010000,HORI Fighting Stick mini 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,rightshoulder:b5,rightstick:b11,righttrigger:a4,start:b9,x:b0,y:b3,", + "030000000d0f0000d800000072056800,HORI Real Arcade Pro S,a:b0,b:b1,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "030000000d0f0000aa00000011010000,HORI Real Arcade Pro,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "030000000d0f00006e00000011010000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00006600000011010000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00006700000001010000,HORIPAD ONE,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "06000000adde0000efbe000002010000,Hidromancer Game Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000d81400000862000011010000,HitBox (PS3/PC) Analog Mode,a:b1,b:b2,back:b8,guide:b9,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b12,x:b0,y:b3,", + "030000000d0f00005f00000011010000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000000d0f00005e00000011010000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000000d0f00008600000002010000,Hori Fighting Commander,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000ad1b000001f5000033050000,Hori Pad EX Turbo 2,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000008f0e00001330000010010000,HuiJia SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b9,x:b3,y:b0,", + "03000000242e00008816000001010000,Hyperkin X91,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000d80400008200000003000000,IMS PCU#0 Gamepad Interface,a:b1,b:b0,back:b4,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,start:b5,x:b3,y:b2,", + "03000000fd0500000030000000010000,InterAct GoPad I-73000 (Fighting Game Layout),a:b3,b:b4,back:b6,leftx:a0,lefty:a1,rightshoulder:b2,righttrigger:b5,start:b7,x:b0,y:b1,", + "05000000491900000204000000000000,Ipega PG-9087S,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "030000006e0500000320000010010000,JC-U3613M - DirectInput Mode,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,", + "03000000300f00001001000010010000,Jess Tech Dual Analog Rumble Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", + "03000000ba2200002010000001010000,Jess Technology USB Game Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", + "030000006f0e00000103000000020000,Logic3 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000006d040000d1ca000011010000,Logitech Chillstream,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d04000019c2000010010000,Logitech Cordless RumblePad 2,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d04000016c2000010010000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d04000016c2000011010000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d0400001dc2000014400000,Logitech F310 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000006d0400001ec2000020200000,Logitech F510 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000006d04000019c2000011010000,Logitech F710 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */ + "030000006d0400001fc2000005030000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000006d04000018c2000010010000,Logitech RumblePad 2,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006d04000011c2000010010000,Logitech WingMan Cordless RumblePad,a:b0,b:b1,back:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b6,lefttrigger:b9,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b10,rightx:a3,righty:a4,start:b8,x:b3,y:b4,", + "03000000c62400002b89000011010000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "05000000c62400002a89000000010000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b22,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "05000000c62400001a89000000010000,MOGA XP5-X Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000250900006688000000010000,MP-8866 Super Dual Box,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", + "05000000380700006652000025010000,Mad Catz C.T.R.L.R ,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700005032000011010000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700005082000011010000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000380700008433000011010000,Mad Catz FightStick TE S+ (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700008483000011010000,Mad Catz FightStick TE S+ (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000ad1b00002ef0000090040000,Mad Catz Fightpad SFxT,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:a2,rightshoulder:b5,righttrigger:a5,start:b7,x:b2,y:b3,", + "03000000380700003847000090040000,Mad Catz Wired Xbox 360 Controller (SFIV),a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000380700001647000010040000,Mad Catz Wired Xbox 360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000ad1b000016f0000090040000,Mad Catz Xbox 360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000380700008034000011010000,Mad Catz fightstick (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700008084000011010000,Mad Catz fightstick (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000380700001888000010010000,MadCatz PC USB Wired Stick 8818,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000380700003888000010010000,MadCatz PC USB Wired Stick 8838,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:a0,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000790000004418000010010000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,", + "03000000780000000600000010010000,Microntek USB Joystick,a:b2,b:b1,back:b8,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,", + "030000005e0400000e00000000010000,Microsoft SideWinder,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,rightshoulder:b7,start:b8,x:b3,y:b4,", + "030000005e0400008e02000004010000,Microsoft X-Box 360 pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e0400008e02000062230000,Microsoft X-Box 360 pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e040000d102000003020000,Microsoft X-Box One pad v2,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e040000d102000001010000,Microsoft X-Box One pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e0400008502000000010000,Microsoft X-Box pad (Japan),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,", + "030000005e0400008902000021010000,Microsoft X-Box pad v2 (US),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,", + "030000005e0400008902000020010000,Microsoft Xbox Controller S,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,", + "05000000d6200000ad0d000001000000,Moga Pro,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "030000006b140000010c000010010000,NACON GC-400ES,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "030000001008000001e5000010010000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,", + "03000000550900001072000011010000,NVIDIA Controller v01.03,a:b0,b:b1,back:b14,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b4,leftstick:b8,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", + "03000000550900001472000011010000,NVIDIA Controller v01.04,a:b0,b:b1,back:b14,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b16,leftshoulder:b4,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,", + "05000000550900001472000001000000,NVIDIA Controller v01.04,a:b0,b:b1,back:b14,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b16,leftshoulder:b4,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,", + "030000004b120000014d000000010000,NYKO AIRFLO EX,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", + "03000000451300000830000010010000,NYKO CORE,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000790000004318000010010000,Nintendo GameCube Controller,a:b1,b:b0,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b2,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000007e0500001920000011810000,Nintendo N64 Controller,crc:d670,a:b0,b:b1,back:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b9,lefttrigger:b8,leftx:a0,lefty:a1,misc1:b5,rightshoulder:b7,righttrigger:b3,start:b11,x:b4,y:b10,", + "050000007e0500001920000001800000,Nintendo N64 Controller,crc:5e1c,a:b0,b:b1,back:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b9,lefttrigger:b8,leftx:a0,lefty:a1,misc1:b5,rightshoulder:b7,righttrigger:b3,start:b11,x:b4,y:b10,", + "030000007e0500001e20000011810000,Nintendo SEGA Genesis Controller,crc:bb22,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,misc1:b3,rightshoulder:b2,righttrigger:b4,start:b5,", + "050000007e0500001720000001800000,Nintendo SEGA Genesis Controller,crc:c1bf,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,misc1:b3,rightshoulder:b2,righttrigger:b4,start:b5,", + "030000007e0500001720000011810000,Nintendo SNES Controller,crc:f648,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e0500001720000001800000,Nintendo SNES Controller,crc:dbc0,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e0500000620000001800000,Nintendo Switch Joy-Con (L),a:b16,b:b15,guide:b4,leftshoulder:b6,leftstick:b12,leftx:a1,lefty:a0~,rightshoulder:b8,start:b9,x:b14,y:b17,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "060000007e0500000620000000000000,Nintendo Switch Joy-Con (L/R),a:b0,b:b1,back:b9,dpdown:b15,dpleft:b16,dpright:b17,dpup:b14,leftshoulder:b5,leftstick:b12,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b13,righttrigger:b8,rightx:a2,righty:a3,start:b10,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "060000007e0500000820000000000000,Nintendo Switch Joy-Con (L/R),a:b0,b:b1,back:b9,dpdown:b15,dpleft:b16,dpright:b17,dpup:b14,guide:b11,leftshoulder:b5,leftstick:b12,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b13,righttrigger:b8,rightx:a2,righty:a3,start:b10,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e0500000720000001800000,Nintendo Switch Joy-Con (R),a:b1,b:b2,guide:b9,leftshoulder:b4,leftstick:b10,leftx:a1~,lefty:a0,rightshoulder:b6,start:b8,x:b0,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000d620000013a7000011010000,Nintendo Switch PowerA Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "03000000d620000011a7000011010000,Nintendo Switch PowerA Core Plus Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000007e0500000920000011810000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b11,leftshoulder:b5,leftstick:b12,lefttrigger:b7,leftx:a0,lefty:a1,misc1:b4,rightshoulder:b6,rightstick:b13,righttrigger:b8,rightx:a2,righty:a3,start:b10,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000004c69632050726f20436f6e00,Nintendo Switch Pro Controller,crc:15b7,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,misc1:b13,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e0500000920000001000000,Nintendo Switch Pro Controller,a:b1,b:b0,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e0500000920000001800000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b11,leftshoulder:b5,leftstick:b12,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b13,righttrigger:b8,rightx:a2,righty:a3,start:b10,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e0500000603000000060000,Nintendo Wii Remote Classic Controller,crc:0d8a,a:b1,b:b0,back:b10,dpdown:b14,dpleft:b12,dpright:b13,dpup:b11,guide:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,start:b9,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e0500003003000001000000,Nintendo Wii Remote Pro Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e0500000603000000060000,Nintendo Wii Remote,crc:60be,a:b1,b:b0,back:b4,dpdown:b8,dpleft:b6,dpright:b7,dpup:b5,guide:b2,start:b3,x:b9,y:b10,", + "05000000010000000100000003000000,Nintendo Wiimote,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "030000000d0500000308000010010000,Nostromo n45 Dual Analog Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b12,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b10,x:b2,y:b3,", + "05000000362800000100000002010000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b1,y:b2,", + "05000000362800000100000003010000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b1,y:b2,", + "030000005e0400000202000000010000,Old Xbox pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,", + "03000000ff1100003133000010010000,PC Game Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "030000006f0e00006401000001010000,PDP Battlefield One,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000006f0e00000901000011010000,PDP Versus Fighting Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "03000000ff1100004133000010010000,PS2 Controller,a:b2,b:b1,back:b8,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,", + "03000000341a00003608000011010000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000004c0500006802000010010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", + "030000004c0500006802000010810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "030000004c0500006802000011010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:a12,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:a13,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", + "030000004c0500006802000011810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "030000006f0e00001402000011010000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000008f0e00000300000010010000,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "050000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:a12,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:a13,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", + "050000004c0500006802000000800000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "050000004c0500006802000000810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "05000000504c415953544154494f4e00,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", + "060000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", + "030000004c050000a00b000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000a00b000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "030000004c050000c405000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000c405000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "030000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000cc09000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000cc09000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "050000004c050000c405000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "050000004c050000c405000000810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "050000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "050000004c050000cc09000000810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "050000004c050000cc09000001800000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "030000004c050000e60c000000010000,PS5 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,misc1:b13,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000e60c000011010000,PS5 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,misc1:b13,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000e60c000011810000,PS5 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "050000004c050000e60c000000010000,PS5 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,misc1:b13,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "050000004c050000e60c000000810000,PS5 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", + "030000004c050000da0c000011010000,Playstation Controller,a:b2,b:b1,back:b8,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,", + "03000000c62400003a54000001010000,PowerA XBox One Controller,a:b0,b:b1,back:b6,dpdown:h0.7,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000c62400000053000000010000,PowerA,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000300f00001211000011010000,QanBa Arcade JoyStick,a:b2,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b5,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b6,start:b9,x:b1,y:b3,", + "03000000222c00000225000011010000,Qanba Dragon Arcade Joystick (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000222c00000025000011010000,Qanba Dragon Arcade Joystick (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000222c00001220000011010000,Qanba Drone 2 Arcade Joystick (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000222c00001020000011010000,Qanba Drone 2 Arcade Joystick (PS5),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000222c00000020000011010000,Qanba Drone Arcade Joystick (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,rightshoulder:b5,righttrigger:a4,start:b9,x:b0,y:b3,", + "03000000222c00000223000011010000,Qanba Obsidian Arcade Joystick (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000222c00000023000011010000,Qanba Obsidian Arcade Joystick (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000008916000001fd000024010000,Razer Onza Classic Edition,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000321500000204000011010000,Razer Panthera (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000321500000104000011010000,Razer Panthera (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000321500000010000011010000,Razer RAIJU,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000321500000507000000010000,Razer Raiju Mobile,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b21,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000321500000011000011010000,Razer Raion Fightpad for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000008916000000fe000024010000,Razer Sabertooth,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000c6240000045d000024010000,Razer Sabertooth,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000c6240000045d000025010000,Razer Sabertooth,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000321500000009000011010000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", + "050000003215000000090000163a0000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", + "0300000032150000030a000001010000,Razer Wildcat,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "0300000000f000000300000000010000,RetroPad,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,", + "03000000790000001100000010010000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "030000006b140000130d000011010000,Revolution Pro Controller 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000006b140000010d000011010000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000006f0e00001e01000011010000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000006f0e00004601000001010000,Rock Candy Xbox One Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000006f0e00001f01000000010000,Rock Candy,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000632500007505000010010000,SHANWAN PS3/PC Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000341a00000908000010010000,SL-6566,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "03000000457500002211000010010000,SZMY-POWER PC Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000a306000023f6000011010000,Saitek Cyborg V.1 Game Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", + "03000000a30600000cff000010010000,Saitek P2500 Force Rumble Pad,a:b2,b:b3,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,x:b0,y:b1,", + "03000000a30600000c04000011010000,Saitek P2900 Wireless Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b12,x:b0,y:b3,", + "03000000a30600000901000000010000,Saitek P880,a:b2,b:b3,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,x:b0,y:b1,", + "03000000a30600000b04000000010000,Saitek P990 Dual Analog Pad,a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b8,x:b0,y:b3,", + "03000000a306000018f5000010010000,Saitek PLC Saitek P3200 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,", + "03000000c01600008704000011010000,Serial/Keyboard/Mouse/Joystick,a:b12,b:b10,back:b4,dpdown:b2,dpleft:b3,dpright:b1,dpup:b0,leftshoulder:b9,leftstick:b14,lefttrigger:b6,leftx:a1,lefty:a0,rightshoulder:b8,rightstick:b15,righttrigger:b7,rightx:a2,righty:a3,start:b5,x:b13,y:b11,", + "03000000f025000021c1000010010000,ShanWan Gioteck PS3 Wired Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000632500002305000010010000,ShanWan USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", + "03000000250900000500000000010000,Sony PS2 pad with SmartJoy adapter,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", + "030000005e0400008e02000020200000,SpeedLink XEOX Pro Analog Gamepad pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e0400008e02000073050000,Speedlink TORID Wireless Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000de2800000112000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,paddle1:b11,paddle2:b10,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", + "03000000de2800000112000011010000,Steam Controller,a:b2,b:b3,back:b10,dpdown:+a5,dpleft:-a4,dpright:+a4,dpup:-a5,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a7,leftx:a0,lefty:a1,paddle1:b15,paddle2:b16,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a3,start:b11,x:b4,y:b5,", + "03000000de2800000211000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,paddle1:b11,paddle2:b10,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", + "03000000de2800000211000011010000,Steam Controller,a:b2,b:b3,back:b10,dpdown:+a5,dpleft:-a4,dpright:+a4,dpup:-a5,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a7,leftx:a0,lefty:a1,paddle1:b15,paddle2:b16,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a3,start:b11,x:b4,y:b5,", + "03000000de2800004211000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,paddle1:b11,paddle2:b10,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", + "03000000de2800004211000011010000,Steam Controller,a:b2,b:b3,back:b10,dpdown:+a5,dpleft:-a4,dpright:+a4,dpup:-a5,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a7,leftx:a0,lefty:a1,paddle1:b15,paddle2:b16,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a3,start:b11,x:b4,y:b5,", + "03000000de280000fc11000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "05000000de2800000212000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,paddle1:b11,paddle2:b10,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", + "05000000de2800000511000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,paddle1:b11,paddle2:b10,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", + "05000000de2800000611000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,paddle1:b11,paddle2:b10,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", + "03000000de2800000512000000016800,Steam Deck Controller,a:b0,b:b1,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,misc1:b11,paddle1:b12,paddle2:b13,paddle3:b14,paddle4:b15,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "03000000de2800000512000011010000,Steam Deck,a:b3,b:b4,back:b11,dpdown:b17,dpleft:b18,dpright:b19,dpup:b16,guide:b13,leftshoulder:b7,leftstick:b14,lefttrigger:a9,leftx:a0,lefty:a1,misc1:b2,paddle1:b21,paddle2:b20,paddle3:b23,paddle4:b22,rightshoulder:b8,rightstick:b15,righttrigger:a8,rightx:a2,righty:a3,start:b12,x:b5,y:b6,", + "03000000de280000ff11000001000000,Steam Virtual Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "0500000011010000311400001b010000,SteelSeries Stratus Duo,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b32,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "05000000110100001914000009010000,SteelSeries Stratus XL,a:b0,b:b1,back:b17,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b18,leftshoulder:b6,leftstick:b13,lefttrigger:+a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:+a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "03000000ad1b000038f0000090040000,Street Fighter IV FightStick TE,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000666600000488000000010000,Super Joy Box 5 Pro,a:b2,b:b1,back:b9,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", + "0300000000f00000f100000000010000,Super RetroPort,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,", + "030000004f0400000ed0000011010000,ThrustMaster eSwap PRO Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004f04000020b3000010010000,Thrustmaster 2 in 1 DT,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", + "030000004f04000015b3000001010000,Thrustmaster Dual Analog 3.2,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", + "030000004f04000015b3000010010000,Thrustmaster Dual Analog 4,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", + "030000004f04000023b3000000010000,Thrustmaster Dual Trigger 3-in-1,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004f04000000b3000010010000,Thrustmaster Firestorm Dual Power,a:b0,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b11,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b10,x:b1,y:b3,", + "030000004f04000009d0000000010000,Thrustmaster Run N Drive Wireless PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "030000004f04000008d0000000010000,Thrustmaster Run N Drive Wireless,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000bd12000015d0000010010000,Tomee SNES USB Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,", + "03000000d814000007cd000011010000,Toodles 2008 Chimp PC/PS3,a:b0,b:b1,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b3,y:b2,", + "03000000100800000100000010010000,Twin USB PS2 Adapter,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", + "03000000100800000300000010010000,USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", + "03000000790000001100000000010000,USB Gamepad1,a:b2,b:b1,back:b8,dpdown:a0,dpleft:a1,dpright:a2,dpup:a4,start:b9,", + "05000000ac0500003232000001000000,VR-BOX,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", + "030000006f0e00000302000011010000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000006f0e00000702000011010000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", + "030000000d0f0000ab01000011010000,Wireless HORIPAD For Steam,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,misc2:b2,misc3:b16,misc4:b17,paddle1:b19,paddle2:b18,paddle3:b15,paddle4:b5,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "050000000d0f00009601000091000000,Wireless HORIPAD For Steam,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,misc2:b2,misc3:b16,misc4:b17,paddle1:b19,paddle2:b18,paddle3:b15,paddle4:b5,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "030000005e0400008e02000010010000,X360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e0400008e02000014010000,X360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e0400001907000000010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e0400009102000007010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e040000a102000000010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "030000005e040000a102000007010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "03000000450c00002043000010010000,XEOX Gamepad SL-6556-BK,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", + "0000000058626f782033363020576900,Xbox 360 Wireless Controller,a:b0,b:b1,back:b14,dpdown:b11,dpleft:b12,dpright:b13,dpup:b10,guide:b7,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b2,y:b3,", + "030000005e040000a102000014010000,Xbox 360 Wireless Receiver (XBOX),a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "0000000058626f782047616d65706100,Xbox Gamepad (userspace driver),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", + "050000005e040000e002000003090000,Xbox One Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", + "050000005e040000fd02000003090000,Xbox One Wireless Controller,a:b0,b:b1,back:b15,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,guide:b16,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", + "05000000172700004431000029010000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b20,leftshoulder:b6,leftstick:b13,lefttrigger:a7,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a5,start:b11,x:b3,y:b4,", + "03000000c0160000e105000010010000,Xin-Mo Dual Arcade,crc:82d5,a:b1,b:b2,back:b9,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,rightshoulder:b4,righttrigger:b5,start:b8,x:b0,y:b3,", /* Ultimate Atari Fight Stick */ + "03000000120c0000100e000011010000,ZEROPLUS P4 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000120c0000101e000011010000,ZEROPLUS P4 Wired Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "03000000666600006706000000010000,boom PSX to PC Converter,a:b2,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a2,righty:a3,start:b11,x:b3,y:b0,", + "03000000830500006020000010010000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000006964726f69643a636f6e0000,idroid:con,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", + "03000000b50700001503000010010000,impact,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", + "030000009b2800008000000020020000,raphnet technologies 1-player WUSBMote v2.2,a:b1,b:b4,back:b2,dpdown:b13,dpleft:b14,dpright:b15,dpup:b12,leftshoulder:b6,rightshoulder:b7,start:b3,x:b0,y:b5,", + "030000009b2800000300000001010000,raphnet.net 4nes4snes v1.5,a:b0,b:b4,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b1,y:b5,", +#endif +#ifdef SDL_PLATFORM_OPENBSD + "030000004c050000c405000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000004c050000e60c000000010000,PS5 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", + "030000005e0400008e02000010010000,Xbox 360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1~,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4~,start:b7,x:b2,y:b3,", +#endif +#ifdef SDL_PLATFORM_ANDROID + "05000000c82d000006500000ffff3f00,8BitDo M30 Gamepad,a:b1,b:b0,back:b4,guide:b17,leftshoulder:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,righttrigger:a4,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000051060000ffff3f00,8BitDo M30 Gamepad,a:b1,b:b0,back:b4,guide:b17,leftshoulder:b9,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,righttrigger:a5,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000020900000ffff3f00,8BitDo Micro gamepad,a:b1,b:b0,back:b4,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,guide:b5,leftshoulder:b9,lefttrigger:a6,rightshoulder:b10,righttrigger:a7,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000015900000ffff3f00,8BitDo N30 Pro 2,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000065280000ffff3f00,8BitDo N30 Pro 2,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b17,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000000220000000900000ffff3f00,8BitDo NES30 Pro,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000002038000009000000ffff3f00,8BitDo NES30 Pro,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000000600000ffff3f00,8BitDo SF30 Pro,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:b15,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:b16,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000000610000ffff3f00,8BitDo SF30 Pro,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000012900000ffff3f00,8BitDo SN30 Gamepad,a:b1,b:b0,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000062280000ffff3f00,8BitDo SN30 Gamepad,a:b1,b:b0,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000002600000ffff0f00,8BitDo SN30 Pro+,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b17,leftshoulder:b9,leftstick:b7,lefttrigger:b15,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:b16,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000001600000ffff3f00,8BitDo SN30 Pro,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000002028000009000000ffff3f00,8BitDo SNES30 Gamepad,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000003512000020ab000000780f00,8BitDo SNES30 Gamepad,a:b21,b:b20,back:b30,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b26,rightshoulder:b27,start:b31,x:b24,y:b23,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000018900000ffff0f00,8BitDo Zero 2,a:b1,b:b0,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000c82d000030320000ffff0f00,8BitDo Zero 2,a:b1,b:b0,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000d6020000e5890000dfff3f80,GPD XD Plus,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a3,rightx:a4,righty:a5,start:b6,x:b2,y:b3,", + "0500000031366332860c44aadfff0f00,GS Gamepad,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:b15,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:b16,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "05000000bc20000000550000ffff3f00,GameSir G3w,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005509000003720000cf7f3f00,NVIDIA Controller v01.01,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005509000010720000ffff3f00,NVIDIA Controller v01.03,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005509000014720000df7f3f80,NVIDIA Controller v01.04,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a3,rightx:a4,righty:a5,start:b6,x:b2,y:b3,", + "050000007e05000009200000ffff0f00,Nintendo Switch Pro Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:b15,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:b16,rightx:a2,righty:a3,start:b6,x:b2,y:b3,sdk>=:29,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e05000009200000ffff0f00,Nintendo Switch Pro Controller,a:b1,b:b0,back:b15,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:b9,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:b10,rightx:a2,righty:a3,start:b16,x:b2,y:b17,sdk<=:28,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", /* Extremely slow in Bluetooth mode on Android */ + "050000004c05000068020000dfff3f00,PS3 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000004c050000c405000000783f00,PS4 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000004c050000c4050000fffe3f80,PS4 Controller,a:b1,b:b17,back:b15,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:+a3,rightx:a4,righty:a5,start:b16,x:b0,y:b2,", + "050000004c050000c4050000ffff3f00,PS4 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000004c050000cc090000fffe3f80,PS4 Controller,a:b1,b:b17,back:b15,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:a3,rightx:a4,righty:a5,start:b16,x:b0,y:b2,", + "050000004c050000cc090000ffff3f00,PS4 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000004c050000e60c0000fffe3f80,PS5 Controller,a:b0,b:b1,back:b15,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:a3,rightx:a4,righty:a5,start:b16,x:b2,y:b17,", + "050000004c050000e60c0000ffff3f00,PS5 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "05000000f8270000bf0b0000ffff3f00,Razer Kishi,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000003215000005070000ffff3f00,Razer Raiju Mobile,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000003215000007070000ffff3f00,Razer Raiju Mobile,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000003215000000090000bf7f3f00,Razer Serval,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,x:b2,y:b3,", + "050000004f0400000ed00000fffe3f00,ThrustMaster eSwap PRO Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005e0400008e02000000783f00,Xbox 360 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005e040000000b000000783f80,Xbox One Elite 2 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005e040000050b0000ffff3f00,Xbox One Elite 2 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a6,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005e040000e002000000783f00,Xbox One S Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005e040000ea02000000783f00,Xbox One S Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005e040000fd020000ff7f3f00,Xbox One S Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005e040000e00200000ffe3f80,Xbox One Wireless Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b3,leftstick:b15,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b16,righttrigger:a5,rightx:a2,righty:a3,start:b10,x:b17,y:b2,", + "050000005e040000fd020000ffff3f00,Xbox One Wireless Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005e040000120b000000783f80,Xbox Series X Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005e040000130b0000ffff3f00,Xbox Series X Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", + "050000005e04000091020000ff073f80,Xbox Wireless Controller,a:b0,b:b1,back:b4,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", /* The DPAD doesn't seem to work on this controller on Android TV? */ + "050000001727000044310000ffff3f80,XiaoMi Game Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a7,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a6,rightx:a4,righty:a5,start:b6,x:b2,y:b3,", + "0500000083050000602000000ffe0000,iBuffalo SNES Controller,a:b1,b:b0,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b15,rightshoulder:b16,start:b10,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", +#endif +#ifdef SDL_JOYSTICK_MFI + "05000000ac050000010000004f066d01,*,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a5,rightx:a3,righty:a4,x:b2,y:b3,", + "05000000ac05000001000000cf076d01,*,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b2,y:b3,", + "05000000ac05000001000000df076d01,*,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", + "05000000ac05000001000000ff076d01,*,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b2,y:b3,", + "05000000ac050000020000004f066d02,*,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,rightshoulder:b5,x:b2,y:b3,", + "05000000ac05000004000000a8986d04,8BitDo Micro gamepad,a:b1,b:b0,back:b4,dpdown:b7,dpleft:b8,dpright:b9,dpup:b10,guide:b2,leftshoulder:b11,lefttrigger:b12,rightshoulder:b13,righttrigger:b14,start:b3,x:b6,y:b5,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000ac05000004000000fd216d04,8BitDo Pro 2,crc:ac95,a:b3,b:b2,back:b6,dpdown:b9,dpleft:b10,dpright:b11,dpup:b12,guide:b4,leftshoulder:b13,leftstick:b14,lefttrigger:+a2,leftx:a0,lefty:a1~,paddle1:b1,paddle2:b0,rightshoulder:b16,rightstick:b17,righttrigger:+a5,rightx:a3,righty:a4~,start:b5,x:b8,y:b7,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000ac050000040000003b8a6d04,8BitDo SN30 Pro+,crc:3e00,a:b1,b:b0,back:b4,dpdown:b7,dpleft:b8,dpright:b9,dpup:b10,guide:b2,leftshoulder:b11,leftstick:b12,lefttrigger:b13,leftx:a0,lefty:a1~,rightshoulder:b14,rightstick:b15,righttrigger:b16,rightx:a2,righty:a3~,start:b3,x:b6,y:b5,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "05000000ac05000004000000209f6d04,8Bitdo SN30 Pro,crc:40d6,a:b1,b:b0,back:b4,dpdown:b7,dpleft:b8,dpright:b9,dpup:b10,guide:b2,leftshoulder:b11,leftstick:b12,lefttrigger:b13,leftx:a0,lefty:a1~,rightshoulder:b14,rightstick:b15,righttrigger:b16,rightx:a2,righty:a3~,start:b3,x:b6,y:b5,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000008a35000003010000ff070000,Backbone One,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b2,y:b3,", + "050000008a35000004010000ff070000,Backbone One,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b2,y:b3,", + "050000007e050000062000000f060000,Nintendo Switch Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b2,leftshoulder:b4,rightshoulder:b5,x:b1,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e050000062000004f060000,Nintendo Switch Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b2,guide:b6,leftshoulder:b4,rightshoulder:b5,x:b1,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e05000008200000df070000,Nintendo Switch Joy-Con (L/R),a:b1,b:b0,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e050000072000000f060000,Nintendo Switch Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b2,leftshoulder:b4,rightshoulder:b5,x:b1,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e050000072000004f060000,Nintendo Switch Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b2,guide:b6,leftshoulder:b4,rightshoulder:b5,x:b1,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e05000009200000df870000,Nintendo Switch Pro Controller,a:b1,b:b0,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,misc1:b10,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000007e05000009200000ff870000,Nintendo Switch Pro Controller,a:b1,b:b0,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,misc1:b11,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", + "050000004c050000cc090000df070000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", + "050000004c050000cc090000df870001,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", + "050000004c050000cc090000ff070000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b2,y:b3,", + "050000004c050000cc090000ff870001,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,touchpad:b11,x:b2,y:b3,", + "050000004c050000e60c0000df870000,PS5 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,touchpad:b10,x:b2,y:b3,", + "050000004c050000e60c0000ff870000,PS5 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,touchpad:b11,x:b2,y:b3,", + "05000000ac0500000300000043006d03,Remote,a:b0,b:b2,leftx:a0,lefty:a1,", + "050000005e040000050b0000df070001,Xbox Elite Wireless Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,paddle1:b10,paddle2:b12,paddle3:b11,paddle4:b13,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", + "050000005e040000050b0000ff070001,Xbox Elite Wireless Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,paddle1:b11,paddle2:b13,paddle3:b12,paddle4:b14,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b2,y:b3,", + "050000005e040000130b0000df870001,Xbox Series X Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,misc1:b10,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", + "050000005e040000130b0000ff870001,Xbox Series X Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,misc1:b11,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b2,y:b3,", + "050000005e040000e0020000df070000,Xbox Wireless Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", + "050000005e040000e0020000ff070000,Xbox Wireless Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b2,y:b3,", +#endif +#ifdef SDL_JOYSTICK_EMSCRIPTEN + "default,Standard Gamepad,a:b0,b:b1,back:b8,dpdown:b13,dpleft:b14,dpright:b15,dpup:b12,guide:b16,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", +#endif +#ifdef SDL_JOYSTICK_PS2 + "0000000050533220436f6e74726f6c00,PS2 Controller,crc:ed87,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", +#endif +#ifdef SDL_JOYSTICK_PSP + "00000000505350206275696c74696e00,PSP builtin joypad,crc:bb86,a:b2,b:b1,back:b10,dpdown:b6,dpleft:b7,dpright:b9,dpup:b8,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,rightx:a2,righty:a3,start:b11,x:b3,y:b0,", +#endif +#ifdef SDL_JOYSTICK_VITA + "0000000050535669746120436f6e7400,PSVita Controller,crc:d598,a:b2,b:b1,back:b10,dpdown:b6,dpleft:b7,dpright:b9,dpup:b8,leftshoulder:b4,leftstick:b14,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b15,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b3,y:b0,", +#endif +#ifdef SDL_JOYSTICK_N3DS + "000000004e696e74656e646f20334400,Nintendo 3DS,crc:3210,a:b1,b:b0,back:b2,dpdown:b7,dpleft:b5,dpright:b4,dpup:b6,leftshoulder:b9,lefttrigger:b14,leftx:a0,lefty:a1,rightshoulder:b8,righttrigger:b15,rightx:a2,righty:a3,start:b3,x:b11,y:b10,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", +#endif + NULL +}; diff --git a/thirdparty/sdl/joystick/SDL_joystick.c b/thirdparty/sdl/joystick/SDL_joystick.c new file mode 100644 index 00000000000..f36ca95baad --- /dev/null +++ b/thirdparty/sdl/joystick/SDL_joystick.c @@ -0,0 +1,3797 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This is the joystick API for Simple DirectMedia Layer + +#include "SDL_sysjoystick.h" +#include "../SDL_hints_c.h" +#include "SDL_gamepad_c.h" +#include "SDL_joystick_c.h" +#include "SDL_steam_virtual_gamepad.h" + +#include "../events/SDL_events_c.h" +//#include "../video/SDL_sysvideo.h" +#include "../sensor/SDL_sensor_c.h" +#include "hidapi/SDL_hidapijoystick_c.h" + +// This is included in only one place because it has a large static list of controllers +#include "controller_type.h" + +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) +// Needed for checking for input remapping programs +#include "../core/windows/SDL_windows.h" + +#undef UNICODE // We want ASCII functions +#include +#endif + +#ifdef SDL_JOYSTICK_VIRTUAL +#include "./virtual/SDL_virtualjoystick_c.h" +#endif + +static SDL_JoystickDriver *SDL_joystick_drivers[] = { +#ifdef SDL_JOYSTICK_HIDAPI // Highest priority driver for supported devices + &SDL_HIDAPI_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_PRIVATE + &SDL_PRIVATE_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_GAMEINPUT // Higher priority than other Windows drivers + &SDL_GAMEINPUT_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_RAWINPUT // Before WINDOWS driver, as WINDOWS wants to check if this driver is handling things + &SDL_RAWINPUT_JoystickDriver, +#endif +#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT) // Before WGI driver, as WGI wants to check if this driver is handling things + &SDL_WINDOWS_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_WGI + &SDL_WGI_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_WINMM + &SDL_WINMM_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_LINUX + &SDL_LINUX_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_IOKIT + &SDL_DARWIN_JoystickDriver, +#endif +#if (defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS) || defined(SDL_PLATFORM_TVOS)) && !defined(SDL_JOYSTICK_DISABLED) + &SDL_IOS_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_ANDROID + &SDL_ANDROID_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_EMSCRIPTEN + &SDL_EMSCRIPTEN_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_HAIKU + &SDL_HAIKU_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_USBHID /* !!! FIXME: "USBHID" is a generic name, and doubly-confusing with HIDAPI next to it. This is the *BSD interface, rename this. */ + &SDL_BSD_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_PS2 + &SDL_PS2_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_PSP + &SDL_PSP_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_VIRTUAL + &SDL_VIRTUAL_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_VITA + &SDL_VITA_JoystickDriver, +#endif +#ifdef SDL_JOYSTICK_N3DS + &SDL_N3DS_JoystickDriver, +#endif +#if defined(SDL_JOYSTICK_DUMMY) || defined(SDL_JOYSTICK_DISABLED) + &SDL_DUMMY_JoystickDriver +#endif +}; + +#ifndef SDL_THREAD_SAFETY_ANALYSIS +static +#endif +SDL_Mutex *SDL_joystick_lock = NULL; // This needs to support recursive locks +static SDL_AtomicInt SDL_joystick_lock_pending; +static int SDL_joysticks_locked; +static bool SDL_joysticks_initialized; +static bool SDL_joysticks_quitting; +static bool SDL_joystick_being_added; +static SDL_Joystick *SDL_joysticks SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static int SDL_joystick_player_count SDL_GUARDED_BY(SDL_joystick_lock) = 0; +static SDL_JoystickID *SDL_joystick_players SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static bool SDL_joystick_allows_background_events = false; + +static Uint32 initial_arcadestick_devices[] = { + MAKE_VIDPID(0x0079, 0x181a), // Venom Arcade Stick + MAKE_VIDPID(0x0079, 0x181b), // Venom Arcade Stick + MAKE_VIDPID(0x0c12, 0x0ef6), // Hitbox Arcade Stick + MAKE_VIDPID(0x0e6f, 0x0109), // PDP Versus Fighting Pad + MAKE_VIDPID(0x0f0d, 0x0016), // Hori Real Arcade Pro.EX + MAKE_VIDPID(0x0f0d, 0x001b), // Hori Real Arcade Pro VX + MAKE_VIDPID(0x0f0d, 0x0063), // Hori Real Arcade Pro Hayabusa (USA) Xbox One + MAKE_VIDPID(0x0f0d, 0x006a), // Real Arcade Pro 4 + MAKE_VIDPID(0x0f0d, 0x0078), // Hori Real Arcade Pro V Kai Xbox One + MAKE_VIDPID(0x0f0d, 0x008a), // HORI Real Arcade Pro 4 + MAKE_VIDPID(0x0f0d, 0x008c), // Hori Real Arcade Pro 4 + MAKE_VIDPID(0x0f0d, 0x00aa), // HORI Real Arcade Pro V Hayabusa in Switch Mode + MAKE_VIDPID(0x0f0d, 0x00ed), // Hori Fighting Stick mini 4 kai + MAKE_VIDPID(0x0f0d, 0x011c), // Hori Fighting Stick Alpha in PS4 Mode + MAKE_VIDPID(0x0f0d, 0x011e), // Hori Fighting Stick Alpha in PC Mode + MAKE_VIDPID(0x0f0d, 0x0184), // Hori Fighting Stick Alpha in PS5 Mode + MAKE_VIDPID(0x146b, 0x0604), // NACON Daija Arcade Stick + MAKE_VIDPID(0x1532, 0x0a00), // Razer Atrox Arcade Stick + MAKE_VIDPID(0x1bad, 0xf03d), // Street Fighter IV Arcade Stick TE - Chun Li + MAKE_VIDPID(0x1bad, 0xf502), // Hori Real Arcade Pro.VX SA + MAKE_VIDPID(0x1bad, 0xf504), // Hori Real Arcade Pro. EX + MAKE_VIDPID(0x1bad, 0xf506), // Hori Real Arcade Pro.EX Premium VLX + MAKE_VIDPID(0x20d6, 0xa715), // PowerA Nintendo Switch Fusion Arcade Stick + MAKE_VIDPID(0x24c6, 0x5000), // Razer Atrox Arcade Stick + MAKE_VIDPID(0x24c6, 0x5501), // Hori Real Arcade Pro VX-SA + MAKE_VIDPID(0x24c6, 0x550e), // Hori Real Arcade Pro V Kai 360 + MAKE_VIDPID(0x2c22, 0x2300), // Qanba Obsidian Arcade Joystick in PS4 Mode + MAKE_VIDPID(0x2c22, 0x2302), // Qanba Obsidian Arcade Joystick in PS3 Mode + MAKE_VIDPID(0x2c22, 0x2303), // Qanba Obsidian Arcade Joystick in PC Mode + MAKE_VIDPID(0x2c22, 0x2500), // Qanba Dragon Arcade Joystick in PS4 Mode + MAKE_VIDPID(0x2c22, 0x2502), // Qanba Dragon Arcade Joystick in PS3 Mode + MAKE_VIDPID(0x2c22, 0x2503), // Qanba Dragon Arcade Joystick in PC Mode +}; +static SDL_vidpid_list arcadestick_devices = { + SDL_HINT_JOYSTICK_ARCADESTICK_DEVICES, 0, 0, NULL, + SDL_HINT_JOYSTICK_ARCADESTICK_DEVICES_EXCLUDED, 0, 0, NULL, + SDL_arraysize(initial_arcadestick_devices), initial_arcadestick_devices, + false +}; + +/* This list is taken from: + https://raw.githubusercontent.com/denilsonsa/udev-joystick-blacklist/master/generate_rules.py + */ +static Uint32 initial_blacklist_devices[] = { + // Microsoft Microsoft Wireless Optical Desktop 2.10 + // Microsoft Wireless Desktop - Comfort Edition + MAKE_VIDPID(0x045e, 0x009d), + + // Microsoft Microsoft Digital Media Pro Keyboard + // Microsoft Corp. Digital Media Pro Keyboard + MAKE_VIDPID(0x045e, 0x00b0), + + // Microsoft Microsoft Digital Media Keyboard + // Microsoft Corp. Digital Media Keyboard 1.0A + MAKE_VIDPID(0x045e, 0x00b4), + + // Microsoft Microsoft Digital Media Keyboard 3000 + MAKE_VIDPID(0x045e, 0x0730), + + // Microsoft Microsoft 2.4GHz Transceiver v6.0 + // Microsoft Microsoft 2.4GHz Transceiver v8.0 + // Microsoft Corp. Nano Transceiver v1.0 for Bluetooth + // Microsoft Wireless Mobile Mouse 1000 + // Microsoft Wireless Desktop 3000 + MAKE_VIDPID(0x045e, 0x0745), + + // Microsoft SideWinder(TM) 2.4GHz Transceiver + MAKE_VIDPID(0x045e, 0x0748), + + // Microsoft Corp. Wired Keyboard 600 + MAKE_VIDPID(0x045e, 0x0750), + + // Microsoft Corp. Sidewinder X4 keyboard + MAKE_VIDPID(0x045e, 0x0768), + + // Microsoft Corp. Arc Touch Mouse Transceiver + MAKE_VIDPID(0x045e, 0x0773), + + // Microsoft 2.4GHz Transceiver v9.0 + // Microsoft Nano Transceiver v2.1 + // Microsoft Sculpt Ergonomic Keyboard (5KV-00001) + MAKE_VIDPID(0x045e, 0x07a5), + + // Microsoft Nano Transceiver v1.0 + // Microsoft Wireless Keyboard 800 + MAKE_VIDPID(0x045e, 0x07b2), + + // Microsoft Nano Transceiver v2.0 + MAKE_VIDPID(0x045e, 0x0800), + + MAKE_VIDPID(0x046d, 0xc30a), // Logitech, Inc. iTouch Composite keyboard + + MAKE_VIDPID(0x04d9, 0xa0df), // Tek Syndicate Mouse (E-Signal USB Gaming Mouse) + + // List of Wacom devices at: http://linuxwacom.sourceforge.net/wiki/index.php/Device_IDs + MAKE_VIDPID(0x056a, 0x0010), // Wacom ET-0405 Graphire + MAKE_VIDPID(0x056a, 0x0011), // Wacom ET-0405A Graphire2 (4x5) + MAKE_VIDPID(0x056a, 0x0012), // Wacom ET-0507A Graphire2 (5x7) + MAKE_VIDPID(0x056a, 0x0013), // Wacom CTE-430 Graphire3 (4x5) + MAKE_VIDPID(0x056a, 0x0014), // Wacom CTE-630 Graphire3 (6x8) + MAKE_VIDPID(0x056a, 0x0015), // Wacom CTE-440 Graphire4 (4x5) + MAKE_VIDPID(0x056a, 0x0016), // Wacom CTE-640 Graphire4 (6x8) + MAKE_VIDPID(0x056a, 0x0017), // Wacom CTE-450 Bamboo Fun (4x5) + MAKE_VIDPID(0x056a, 0x0018), // Wacom CTE-650 Bamboo Fun 6x8 + MAKE_VIDPID(0x056a, 0x0019), // Wacom CTE-631 Bamboo One + MAKE_VIDPID(0x056a, 0x00d1), // Wacom Bamboo Pen and Touch CTH-460 + MAKE_VIDPID(0x056a, 0x030e), // Wacom Intuos Pen (S) CTL-480 + + MAKE_VIDPID(0x09da, 0x054f), // A4 Tech Co., G7 750 mouse + MAKE_VIDPID(0x09da, 0x1410), // A4 Tech Co., Ltd Bloody AL9 mouse + MAKE_VIDPID(0x09da, 0x3043), // A4 Tech Co., Ltd Bloody R8A Gaming Mouse + MAKE_VIDPID(0x09da, 0x31b5), // A4 Tech Co., Ltd Bloody TL80 Terminator Laser Gaming Mouse + MAKE_VIDPID(0x09da, 0x3997), // A4 Tech Co., Ltd Bloody RT7 Terminator Wireless + MAKE_VIDPID(0x09da, 0x3f8b), // A4 Tech Co., Ltd Bloody V8 mouse + MAKE_VIDPID(0x09da, 0x51f4), // Modecom MC-5006 Keyboard + MAKE_VIDPID(0x09da, 0x5589), // A4 Tech Co., Ltd Terminator TL9 Laser Gaming Mouse + MAKE_VIDPID(0x09da, 0x7b22), // A4 Tech Co., Ltd Bloody V5 + MAKE_VIDPID(0x09da, 0x7f2d), // A4 Tech Co., Ltd Bloody R3 mouse + MAKE_VIDPID(0x09da, 0x8090), // A4 Tech Co., Ltd X-718BK Oscar Optical Gaming Mouse + MAKE_VIDPID(0x09da, 0x9033), // A4 Tech Co., X7 X-705K + MAKE_VIDPID(0x09da, 0x9066), // A4 Tech Co., Sharkoon Fireglider Optical + MAKE_VIDPID(0x09da, 0x9090), // A4 Tech Co., Ltd XL-730K / XL-750BK / XL-755BK Laser Mouse + MAKE_VIDPID(0x09da, 0x90c0), // A4 Tech Co., Ltd X7 G800V keyboard + MAKE_VIDPID(0x09da, 0xf012), // A4 Tech Co., Ltd Bloody V7 mouse + MAKE_VIDPID(0x09da, 0xf32a), // A4 Tech Co., Ltd Bloody B540 keyboard + MAKE_VIDPID(0x09da, 0xf613), // A4 Tech Co., Ltd Bloody V2 mouse + MAKE_VIDPID(0x09da, 0xf624), // A4 Tech Co., Ltd Bloody B120 Keyboard + + MAKE_VIDPID(0x1b1c, 0x1b3c), // Corsair Harpoon RGB gaming mouse + + MAKE_VIDPID(0x1d57, 0xad03), // [T3] 2.4GHz and IR Air Mouse Remote Control + + MAKE_VIDPID(0x1e7d, 0x2e4a), // Roccat Tyon Mouse + + MAKE_VIDPID(0x20a0, 0x422d), // Winkeyless.kr Keyboards + + MAKE_VIDPID(0x2516, 0x001f), // Cooler Master Storm Mizar Mouse + MAKE_VIDPID(0x2516, 0x0028), // Cooler Master Storm Alcor Mouse + + /*****************************************************************/ + // Additional entries + /*****************************************************************/ + + MAKE_VIDPID(0x04d9, 0x8008), // OBINLB USB-HID Keyboard (Anne Pro II) + MAKE_VIDPID(0x04d9, 0x8009), // OBINLB USB-HID Keyboard (Anne Pro II) + MAKE_VIDPID(0x04d9, 0xa292), // OBINLB USB-HID Keyboard (Anne Pro II) + MAKE_VIDPID(0x04d9, 0xa293), // OBINLB USB-HID Keyboard (Anne Pro II) + MAKE_VIDPID(0x1532, 0x0266), // Razer Huntsman V2 Analog, non-functional DInput device + MAKE_VIDPID(0x1532, 0x0282), // Razer Huntsman Mini Analog, non-functional DInput device + MAKE_VIDPID(0x26ce, 0x01a2), // ASRock LED Controller + MAKE_VIDPID(0x20d6, 0x0002), // PowerA Enhanced Wireless Controller for Nintendo Switch (charging port only) + MAKE_VIDPID(0x3434, 0x0211), // Keychron K1 Pro System Control +}; +static SDL_vidpid_list blacklist_devices = { + SDL_HINT_JOYSTICK_BLACKLIST_DEVICES, 0, 0, NULL, + SDL_HINT_JOYSTICK_BLACKLIST_DEVICES_EXCLUDED, 0, 0, NULL, + SDL_arraysize(initial_blacklist_devices), initial_blacklist_devices, + false +}; + +static Uint32 initial_flightstick_devices[] = { + MAKE_VIDPID(0x044f, 0x0402), // HOTAS Warthog Joystick + MAKE_VIDPID(0x044f, 0xb10a), // ThrustMaster, Inc. T.16000M Joystick + MAKE_VIDPID(0x046d, 0xc215), // Logitech Extreme 3D + MAKE_VIDPID(0x0583, 0x6258), // Padix USB joystick with viewfinder + MAKE_VIDPID(0x0583, 0x688f), // Padix QF-688uv Windstorm Pro + MAKE_VIDPID(0x0583, 0x7070), // Padix QF-707u Bazooka + MAKE_VIDPID(0x0583, 0xa019), // Padix USB vibration joystick with viewfinder + MAKE_VIDPID(0x0583, 0xa131), // Padix USB Wireless 2.4GHz + MAKE_VIDPID(0x0583, 0xa209), // Padix MetalStrike ForceFeedback + MAKE_VIDPID(0x0583, 0xb010), // Padix MetalStrike Pro + MAKE_VIDPID(0x0583, 0xb012), // Padix Wireless MetalStrike + MAKE_VIDPID(0x0583, 0xb013), // Padix USB Wireless 2.4GHZ + MAKE_VIDPID(0x0738, 0x2221), // Saitek Pro Flight X-56 Rhino Stick + MAKE_VIDPID(0x10f5, 0x7084), // Turtle Beach VelocityOne + MAKE_VIDPID(0x231d, 0x0126), // Gunfighter Mk.III 'Space Combat Edition' (right) + MAKE_VIDPID(0x231d, 0x0127), // Gunfighter Mk.III 'Space Combat Edition' (left) + MAKE_VIDPID(0x362c, 0x0001), // Yawman Arrow +}; +static SDL_vidpid_list flightstick_devices = { + SDL_HINT_JOYSTICK_FLIGHTSTICK_DEVICES, 0, 0, NULL, + SDL_HINT_JOYSTICK_FLIGHTSTICK_DEVICES_EXCLUDED, 0, 0, NULL, + SDL_arraysize(initial_flightstick_devices), initial_flightstick_devices, + false +}; + +static Uint32 initial_gamecube_devices[] = { + MAKE_VIDPID(0x0e6f, 0x0185), // PDP Wired Fight Pad Pro for Nintendo Switch + MAKE_VIDPID(0x20d6, 0xa711), // PowerA Wired Controller Nintendo GameCube Style +}; +static SDL_vidpid_list gamecube_devices = { + SDL_HINT_JOYSTICK_GAMECUBE_DEVICES, 0, 0, NULL, + SDL_HINT_JOYSTICK_GAMECUBE_DEVICES_EXCLUDED, 0, 0, NULL, + SDL_arraysize(initial_gamecube_devices), initial_gamecube_devices, + false +}; + +static Uint32 initial_rog_gamepad_mice[] = { + MAKE_VIDPID(0x0b05, 0x18e3), // ROG Chakram (wired) Mouse + MAKE_VIDPID(0x0b05, 0x18e5), // ROG Chakram (wireless) Mouse + MAKE_VIDPID(0x0b05, 0x1906), // ROG Pugio II + MAKE_VIDPID(0x0b05, 0x1958), // ROG Chakram Core Mouse + MAKE_VIDPID(0x0b05, 0x1a18), // ROG Chakram X (wired) Mouse + MAKE_VIDPID(0x0b05, 0x1a1a), // ROG Chakram X (wireless) Mouse + MAKE_VIDPID(0x0b05, 0x1a1c), // ROG Chakram X (Bluetooth) Mouse +}; +static SDL_vidpid_list rog_gamepad_mice = { + SDL_HINT_ROG_GAMEPAD_MICE, 0, 0, NULL, + SDL_HINT_ROG_GAMEPAD_MICE_EXCLUDED, 0, 0, NULL, + SDL_arraysize(initial_rog_gamepad_mice), initial_rog_gamepad_mice, + false +}; + +static Uint32 initial_throttle_devices[] = { + MAKE_VIDPID(0x044f, 0x0404), // HOTAS Warthog Throttle + MAKE_VIDPID(0x0738, 0xa221), // Saitek Pro Flight X-56 Rhino Throttle + MAKE_VIDPID(0x10f5, 0x7085), // Turtle Beach VelocityOne Throttle +}; +static SDL_vidpid_list throttle_devices = { + SDL_HINT_JOYSTICK_THROTTLE_DEVICES, 0, 0, NULL, + SDL_HINT_JOYSTICK_THROTTLE_DEVICES_EXCLUDED, 0, 0, NULL, + SDL_arraysize(initial_throttle_devices), initial_throttle_devices, + false +}; + +static Uint32 initial_wheel_devices[] = { + MAKE_VIDPID(0x0079, 0x1864), // DragonRise Inc. Wired Wheel (active mode) (also known as PXN V900 (PS3), Superdrive SV-750, or a Genesis Seaborg 400) + MAKE_VIDPID(0x044f, 0xb65d), // Thrustmaster Wheel FFB + MAKE_VIDPID(0x044f, 0xb65e), // Thrustmaster T500RS + MAKE_VIDPID(0x044f, 0xb664), // Thrustmaster TX (initial mode) + MAKE_VIDPID(0x044f, 0xb669), // Thrustmaster TX (active mode) + MAKE_VIDPID(0x044f, 0xb66d), // Thrustmaster T300RS (PS4 mode) + MAKE_VIDPID(0x044f, 0xb66d), // Thrustmaster Wheel FFB + MAKE_VIDPID(0x044f, 0xb66e), // Thrustmaster T300RS (normal mode) + MAKE_VIDPID(0x044f, 0xb66f), // Thrustmaster T300RS (advanced mode) + MAKE_VIDPID(0x044f, 0xb677), // Thrustmaster T150 + MAKE_VIDPID(0x044f, 0xb67f), // Thrustmaster TMX + MAKE_VIDPID(0x044f, 0xb691), // Thrustmaster TS-XW (initial mode) + MAKE_VIDPID(0x044f, 0xb692), // Thrustmaster TS-XW (active mode) + MAKE_VIDPID(0x044f, 0xb696), // Thrustmaster T248 + MAKE_VIDPID(0x046d, 0xc24f), // Logitech G29 (PS3) + MAKE_VIDPID(0x046d, 0xc260), // Logitech G29 (PS4) + MAKE_VIDPID(0x046d, 0xc261), // Logitech G920 (initial mode) + MAKE_VIDPID(0x046d, 0xc262), // Logitech G920 (active mode) + MAKE_VIDPID(0x046d, 0xc266), // Logitech G923 for Playstation 4 and PC (PC mode) + MAKE_VIDPID(0x046d, 0xc267), // Logitech G923 for Playstation 4 and PC (PS4 mode) + MAKE_VIDPID(0x046d, 0xc268), // Logitech PRO Racing Wheel (PC mode) + MAKE_VIDPID(0x046d, 0xc269), // Logitech PRO Racing Wheel (PS4/PS5 mode) + MAKE_VIDPID(0x046d, 0xc26d), // Logitech G923 (Xbox) + MAKE_VIDPID(0x046d, 0xc26e), // Logitech G923 + MAKE_VIDPID(0x046d, 0xc272), // Logitech PRO Racing Wheel for Xbox (PC mode) + MAKE_VIDPID(0x046d, 0xc294), // Logitech generic wheel + MAKE_VIDPID(0x046d, 0xc295), // Logitech Momo Force + MAKE_VIDPID(0x046d, 0xc298), // Logitech Driving Force Pro + MAKE_VIDPID(0x046d, 0xc299), // Logitech G25 + MAKE_VIDPID(0x046d, 0xc29a), // Logitech Driving Force GT + MAKE_VIDPID(0x046d, 0xc29b), // Logitech G27 + MAKE_VIDPID(0x046d, 0xca03), // Logitech Momo Racing + MAKE_VIDPID(0x0483, 0x0522), // Simagic Wheelbase (including M10, Alpha Mini, Alpha, Alpha U) + MAKE_VIDPID(0x0483, 0xa355), // VRS DirectForce Pro Wheel Base + MAKE_VIDPID(0x0583, 0xa132), // Padix USB Wireless 2.4GHz Wheelpad + MAKE_VIDPID(0x0583, 0xa133), // Padix USB Wireless 2.4GHz Wheel + MAKE_VIDPID(0x0583, 0xa202), // Padix Force Feedback Wheel + MAKE_VIDPID(0x0583, 0xb002), // Padix Vibration USB Wheel + MAKE_VIDPID(0x0583, 0xb005), // Padix USB Wheel + MAKE_VIDPID(0x0583, 0xb008), // Padix USB Wireless 2.4GHz Wheel + MAKE_VIDPID(0x0583, 0xb009), // Padix USB Wheel + MAKE_VIDPID(0x0583, 0xb018), // Padix TW6 Wheel + MAKE_VIDPID(0x0eb7, 0x0001), // Fanatec ClubSport Wheel Base V2 + MAKE_VIDPID(0x0eb7, 0x0004), // Fanatec ClubSport Wheel Base V2.5 + MAKE_VIDPID(0x0eb7, 0x0005), // Fanatec CSL Elite Wheel Base+ (PS4) + MAKE_VIDPID(0x0eb7, 0x0006), // Fanatec Podium Wheel Base DD1 + MAKE_VIDPID(0x0eb7, 0x0007), // Fanatec Podium Wheel Base DD2 + MAKE_VIDPID(0x0eb7, 0x0011), // Fanatec Forza Motorsport (CSR Wheel / CSR Elite Wheel) + MAKE_VIDPID(0x0eb7, 0x0020), // Fanatec generic wheel / CSL DD / GT DD Pro + MAKE_VIDPID(0x0eb7, 0x0197), // Fanatec Porsche Wheel (Turbo / GT3 RS / Turbo S / GT3 V2 / GT2) + MAKE_VIDPID(0x0eb7, 0x038e), // Fanatec ClubSport Wheel Base V1 + MAKE_VIDPID(0x0eb7, 0x0e03), // Fanatec CSL Elite Wheel Base + MAKE_VIDPID(0x11ff, 0x0511), // DragonRise Inc. Wired Wheel (initial mode) (also known as PXN V900 (PS3), Superdrive SV-750, or a Genesis Seaborg 400) + MAKE_VIDPID(0x1209, 0xffb0), // Generic FFBoard OpenFFBoard universal forcefeedback wheel + MAKE_VIDPID(0x16d0, 0x0d5a), // Simucube 1 Wheelbase + MAKE_VIDPID(0x16d0, 0x0d5f), // Simucube 2 Ultimate Wheelbase + MAKE_VIDPID(0x16d0, 0x0d60), // Simucube 2 Pro Wheelbase + MAKE_VIDPID(0x16d0, 0x0d61), // Simucube 2 Sport Wheelbase + MAKE_VIDPID(0x2433, 0xf300), // Asetek SimSports Invicta Wheelbase + MAKE_VIDPID(0x2433, 0xf301), // Asetek SimSports Forte Wheelbase + MAKE_VIDPID(0x2433, 0xf303), // Asetek SimSports La Prima Wheelbase + MAKE_VIDPID(0x2433, 0xf306), // Asetek SimSports Tony Kannan Wheelbase + MAKE_VIDPID(0x3416, 0x0301), // Cammus C5 Wheelbase + MAKE_VIDPID(0x3416, 0x0302), // Cammus C12 Wheelbase + MAKE_VIDPID(0x346e, 0x0000), // Moza R16/R21 Wheelbase + MAKE_VIDPID(0x346e, 0x0002), // Moza R9 Wheelbase + MAKE_VIDPID(0x346e, 0x0004), // Moza R5 Wheelbase + MAKE_VIDPID(0x346e, 0x0005), // Moza R3 Wheelbase + MAKE_VIDPID(0x346e, 0x0006), // Moza R12 Wheelbase +}; +static SDL_vidpid_list wheel_devices = { + SDL_HINT_JOYSTICK_WHEEL_DEVICES, 0, 0, NULL, + SDL_HINT_JOYSTICK_WHEEL_DEVICES_EXCLUDED, 0, 0, NULL, + SDL_arraysize(initial_wheel_devices), initial_wheel_devices, + false +}; + +static Uint32 initial_zero_centered_devices[] = { + MAKE_VIDPID(0x05a0, 0x3232), // 8Bitdo Zero Gamepad + MAKE_VIDPID(0x0e8f, 0x3013), // HuiJia SNES USB adapter +}; +static SDL_vidpid_list zero_centered_devices = { + SDL_HINT_JOYSTICK_ZERO_CENTERED_DEVICES, 0, 0, NULL, + NULL, 0, 0, NULL, + SDL_arraysize(initial_zero_centered_devices), initial_zero_centered_devices, + false +}; + +#define CHECK_JOYSTICK_MAGIC(joystick, result) \ + if (!SDL_ObjectValid(joystick, SDL_OBJECT_TYPE_JOYSTICK)) { \ + SDL_InvalidParamError("joystick"); \ + SDL_UnlockJoysticks(); \ + return result; \ + } + +#define CHECK_JOYSTICK_VIRTUAL(joystick, result) \ + if (!joystick->is_virtual) { \ + SDL_SetError("joystick isn't virtual"); \ + SDL_UnlockJoysticks(); \ + return result; \ + } + +bool SDL_JoysticksInitialized(void) +{ + return SDL_joysticks_initialized; +} + +bool SDL_JoysticksQuitting(void) +{ + return SDL_joysticks_quitting; +} + +void SDL_LockJoysticks(void) +{ + (void)SDL_AtomicIncRef(&SDL_joystick_lock_pending); + SDL_LockMutex(SDL_joystick_lock); + (void)SDL_AtomicDecRef(&SDL_joystick_lock_pending); + + ++SDL_joysticks_locked; +} + +void SDL_UnlockJoysticks(void) +{ + bool last_unlock = false; + + --SDL_joysticks_locked; + + if (!SDL_joysticks_initialized) { + // NOTE: There's a small window here where another thread could lock the mutex after we've checked for pending locks + if (!SDL_joysticks_locked && SDL_GetAtomicInt(&SDL_joystick_lock_pending) == 0) { + last_unlock = true; + } + } + + /* The last unlock after joysticks are uninitialized will cleanup the mutex, + * allowing applications to lock joysticks while reinitializing the system. + */ + if (last_unlock) { + SDL_Mutex *joystick_lock = SDL_joystick_lock; + + SDL_LockMutex(joystick_lock); + { + SDL_UnlockMutex(SDL_joystick_lock); + + SDL_joystick_lock = NULL; + } + SDL_UnlockMutex(joystick_lock); + SDL_DestroyMutex(joystick_lock); + } else { + SDL_UnlockMutex(SDL_joystick_lock); + } +} + +bool SDL_JoysticksLocked(void) +{ + return (SDL_joysticks_locked > 0); +} + +void SDL_AssertJoysticksLocked(void) +{ + SDL_assert(SDL_JoysticksLocked()); +} + +/* + * Get the driver and device index for a joystick instance ID + * This should be called while the joystick lock is held, to prevent another thread from updating the list + */ +static bool SDL_GetDriverAndJoystickIndex(SDL_JoystickID instance_id, SDL_JoystickDriver **driver, int *driver_index) +{ + int i, num_joysticks, device_index; + + SDL_AssertJoysticksLocked(); + + if (instance_id > 0) { + for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { + num_joysticks = SDL_joystick_drivers[i]->GetCount(); + for (device_index = 0; device_index < num_joysticks; ++device_index) { + SDL_JoystickID joystick_id = SDL_joystick_drivers[i]->GetDeviceInstanceID(device_index); + if (joystick_id == instance_id) { + *driver = SDL_joystick_drivers[i]; + *driver_index = device_index; + return true; + } + } + } + } + + SDL_SetError("Joystick %" SDL_PRIu32 " not found", instance_id); + return false; +} + +static int SDL_FindFreePlayerIndex(void) +{ + int player_index; + + SDL_AssertJoysticksLocked(); + + for (player_index = 0; player_index < SDL_joystick_player_count; ++player_index) { + if (SDL_joystick_players[player_index] == 0) { + break; + } + } + return player_index; +} + +static int SDL_GetPlayerIndexForJoystickID(SDL_JoystickID instance_id) +{ + int player_index; + + SDL_AssertJoysticksLocked(); + + for (player_index = 0; player_index < SDL_joystick_player_count; ++player_index) { + if (instance_id == SDL_joystick_players[player_index]) { + break; + } + } + if (player_index == SDL_joystick_player_count) { + player_index = -1; + } + return player_index; +} + +static SDL_JoystickID SDL_GetJoystickIDForPlayerIndex(int player_index) +{ + SDL_AssertJoysticksLocked(); + + if (player_index < 0 || player_index >= SDL_joystick_player_count) { + return 0; + } + return SDL_joystick_players[player_index]; +} + +static bool SDL_SetJoystickIDForPlayerIndex(int player_index, SDL_JoystickID instance_id) +{ + SDL_JoystickID existing_instance = SDL_GetJoystickIDForPlayerIndex(player_index); + SDL_JoystickDriver *driver; + int device_index; + int existing_player_index; + + SDL_AssertJoysticksLocked(); + + if (player_index >= SDL_joystick_player_count) { + SDL_JoystickID *new_players = (SDL_JoystickID *)SDL_realloc(SDL_joystick_players, (player_index + 1) * sizeof(*SDL_joystick_players)); + if (!new_players) { + return false; + } + + SDL_joystick_players = new_players; + SDL_memset(&SDL_joystick_players[SDL_joystick_player_count], 0, (player_index - SDL_joystick_player_count + 1) * sizeof(SDL_joystick_players[0])); + SDL_joystick_player_count = player_index + 1; + } else if (player_index >= 0 && SDL_joystick_players[player_index] == instance_id) { + // Joystick is already assigned the requested player index + return true; + } + + // Clear the old player index + existing_player_index = SDL_GetPlayerIndexForJoystickID(instance_id); + if (existing_player_index >= 0) { + SDL_joystick_players[existing_player_index] = 0; + } + + if (player_index >= 0) { + SDL_joystick_players[player_index] = instance_id; + } + + // Update the driver with the new index + if (SDL_GetDriverAndJoystickIndex(instance_id, &driver, &device_index)) { + driver->SetDevicePlayerIndex(device_index, player_index); + } + + // Move any existing joystick to another slot + if (existing_instance > 0) { + SDL_SetJoystickIDForPlayerIndex(SDL_FindFreePlayerIndex(), existing_instance); + } + return true; +} + +static void SDLCALL SDL_JoystickAllowBackgroundEventsChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + if (SDL_GetStringBoolean(hint, false)) { + SDL_joystick_allows_background_events = true; + } else { + SDL_joystick_allows_background_events = false; + } +} + +bool SDL_InitJoysticks(void) +{ + int i; + bool result = false; + + // Create the joystick list lock + if (SDL_joystick_lock == NULL) { + SDL_joystick_lock = SDL_CreateMutex(); + } + + if (!SDL_InitSubSystem(SDL_INIT_EVENTS)) { + return false; + } + + SDL_LockJoysticks(); + + SDL_joysticks_initialized = true; + + SDL_InitGamepadMappings(); + + SDL_LoadVIDPIDList(&arcadestick_devices); + SDL_LoadVIDPIDList(&blacklist_devices); + SDL_LoadVIDPIDList(&flightstick_devices); + SDL_LoadVIDPIDList(&gamecube_devices); + SDL_LoadVIDPIDList(&rog_gamepad_mice); + SDL_LoadVIDPIDList(&throttle_devices); + SDL_LoadVIDPIDList(&wheel_devices); + SDL_LoadVIDPIDList(&zero_centered_devices); + + // See if we should allow joystick events while in the background + SDL_AddHintCallback(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, + SDL_JoystickAllowBackgroundEventsChanged, NULL); + + SDL_InitSteamVirtualGamepadInfo(); + + for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { + if (SDL_joystick_drivers[i]->Init()) { + result = true; + } + } + SDL_UnlockJoysticks(); + + if (!result) { + SDL_QuitJoysticks(); + } + + return result; +} + +bool SDL_JoysticksOpened(void) +{ + bool opened; + + SDL_LockJoysticks(); + { + if (SDL_joysticks != NULL) { + opened = true; + } else { + opened = false; + } + } + SDL_UnlockJoysticks(); + + return opened; +} + +bool SDL_JoystickHandledByAnotherDriver(struct SDL_JoystickDriver *driver, Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ + int i; + bool result = false; + + SDL_LockJoysticks(); + { + for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { + if (driver == SDL_joystick_drivers[i]) { + // Higher priority drivers do not have this device + break; + } + if (SDL_joystick_drivers[i]->IsDevicePresent(vendor_id, product_id, version, name)) { + result = true; + break; + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +bool SDL_HasJoystick(void) +{ + int i; + int total_joysticks = 0; + + SDL_LockJoysticks(); + { + for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { + total_joysticks += SDL_joystick_drivers[i]->GetCount(); + } + } + SDL_UnlockJoysticks(); + + if (total_joysticks > 0) { + return true; + } + return false; +} + +SDL_JoystickID *SDL_GetJoysticks(int *count) +{ + int i, num_joysticks, device_index; + int joystick_index = 0, total_joysticks = 0; + SDL_JoystickID *joysticks; + + SDL_LockJoysticks(); + { + for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { + total_joysticks += SDL_joystick_drivers[i]->GetCount(); + } + + joysticks = (SDL_JoystickID *)SDL_malloc((total_joysticks + 1) * sizeof(*joysticks)); + if (joysticks) { + if (count) { + *count = total_joysticks; + } + + for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { + num_joysticks = SDL_joystick_drivers[i]->GetCount(); + for (device_index = 0; device_index < num_joysticks; ++device_index) { + SDL_assert(joystick_index < total_joysticks); + joysticks[joystick_index] = SDL_joystick_drivers[i]->GetDeviceInstanceID(device_index); + SDL_assert(joysticks[joystick_index] > 0); + ++joystick_index; + } + } + SDL_assert(joystick_index == total_joysticks); + joysticks[joystick_index] = 0; + } else { + if (count) { + *count = 0; + } + } + } + SDL_UnlockJoysticks(); + + return joysticks; +} + +const SDL_SteamVirtualGamepadInfo *SDL_GetJoystickVirtualGamepadInfoForID(SDL_JoystickID instance_id) +{ + SDL_JoystickDriver *driver; + int device_index; + const SDL_SteamVirtualGamepadInfo *info = NULL; + + if (SDL_SteamVirtualGamepadEnabled() && + SDL_GetDriverAndJoystickIndex(instance_id, &driver, &device_index)) { + info = SDL_GetSteamVirtualGamepadInfo(driver->GetDeviceSteamVirtualGamepadSlot(device_index)); + } + return info; +} + +/* + * Get the implementation dependent name of a joystick + */ +const char *SDL_GetJoystickNameForID(SDL_JoystickID instance_id) +{ + SDL_JoystickDriver *driver; + int device_index; + const char *name = NULL; + const SDL_SteamVirtualGamepadInfo *info; + + SDL_LockJoysticks(); + info = SDL_GetJoystickVirtualGamepadInfoForID(instance_id); + if (info) { + name = SDL_GetPersistentString(info->name); + } else if (SDL_GetDriverAndJoystickIndex(instance_id, &driver, &device_index)) { + name = SDL_GetPersistentString(driver->GetDeviceName(device_index)); + } + SDL_UnlockJoysticks(); + + return name; +} + +/* + * Get the implementation dependent path of a joystick + */ +const char *SDL_GetJoystickPathForID(SDL_JoystickID instance_id) +{ + SDL_JoystickDriver *driver; + int device_index; + const char *path = NULL; + + SDL_LockJoysticks(); + if (SDL_GetDriverAndJoystickIndex(instance_id, &driver, &device_index)) { + path = SDL_GetPersistentString(driver->GetDevicePath(device_index)); + } + SDL_UnlockJoysticks(); + + if (!path) { + SDL_Unsupported(); + } + return path; +} + +/* + * Get the player index of a joystick, or -1 if it's not available + */ +int SDL_GetJoystickPlayerIndexForID(SDL_JoystickID instance_id) +{ + int player_index; + + SDL_LockJoysticks(); + player_index = SDL_GetPlayerIndexForJoystickID(instance_id); + SDL_UnlockJoysticks(); + + return player_index; +} + +/* + * Return true if this joystick is known to have all axes centered at zero + * This isn't generally needed unless the joystick never generates an initial axis value near zero, + * e.g. it's emulating axes with digital buttons + */ +static bool SDL_JoystickAxesCenteredAtZero(SDL_Joystick *joystick) +{ + // printf("JOYSTICK '%s' VID/PID 0x%.4x/0x%.4x AXES: %d\n", joystick->name, vendor, product, joystick->naxes); + + if (joystick->naxes == 2) { + // Assume D-pad or thumbstick style axes are centered at 0 + return true; + } + + return SDL_VIDPIDInList(SDL_GetJoystickVendor(joystick), SDL_GetJoystickProduct(joystick), &zero_centered_devices); +} + +static bool IsROGAlly(SDL_Joystick *joystick) +{ + Uint16 vendor, product; + SDL_GUID guid = SDL_GetJoystickGUID(joystick); + + // The ROG Ally controller spoofs an Xbox 360 controller + SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL, NULL); + if (vendor == USB_VENDOR_MICROSOFT && product == USB_PRODUCT_XBOX360_WIRED_CONTROLLER) { + // Check to see if this system has the expected sensors + bool has_ally_accel = false; + bool has_ally_gyro = false; + + if (SDL_InitSubSystem(SDL_INIT_SENSOR)) { + SDL_SensorID *sensors = SDL_GetSensors(NULL); + if (sensors) { + int i; + for (i = 0; sensors[i]; ++i) { + SDL_SensorID sensor = sensors[i]; + + if (!has_ally_accel && SDL_GetSensorTypeForID(sensor) == SDL_SENSOR_ACCEL) { + const char *sensor_name = SDL_GetSensorNameForID(sensor); + if (sensor_name && SDL_strcmp(sensor_name, "Sensor BMI320 Acc") == 0) { + has_ally_accel = true; + } + } + if (!has_ally_gyro && SDL_GetSensorTypeForID(sensor) == SDL_SENSOR_GYRO) { + const char *sensor_name = SDL_GetSensorNameForID(sensor); + if (sensor_name && SDL_strcmp(sensor_name, "Sensor BMI320 Gyr") == 0) { + has_ally_gyro = true; + } + } + } + SDL_free(sensors); + } + SDL_QuitSubSystem(SDL_INIT_SENSOR); + } + if (has_ally_accel && has_ally_gyro) { + return true; + } + } + return false; +} + +static bool ShouldAttemptSensorFusion(SDL_Joystick *joystick, bool *invert_sensors) +{ + SDL_AssertJoysticksLocked(); + + *invert_sensors = false; + + // The SDL controller sensor API is only available for gamepads (at the moment) + if (!SDL_IsGamepad(joystick->instance_id)) { + return false; + } + + // If the controller already has sensors, use those + if (joystick->nsensors > 0) { + return false; + } + + const char *hint = SDL_GetHint(SDL_HINT_GAMECONTROLLER_SENSOR_FUSION); + if (hint && *hint) { + if (*hint == '@' || SDL_strncmp(hint, "0x", 2) == 0) { + SDL_vidpid_list gamepads; + SDL_GUID guid; + Uint16 vendor, product; + bool enabled; + SDL_zero(gamepads); + + // See if the gamepad is in our list of devices to enable + guid = SDL_GetJoystickGUID(joystick); + SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL, NULL); + SDL_LoadVIDPIDListFromHints(&gamepads, hint, NULL); + enabled = SDL_VIDPIDInList(vendor, product, &gamepads); + SDL_FreeVIDPIDList(&gamepads); + if (enabled) { + return true; + } + } else { + return SDL_GetStringBoolean(hint, false); + } + } + + // See if this is another known wraparound gamepad + if (joystick->name && + (SDL_strstr(joystick->name, "Backbone One") || + SDL_strstr(joystick->name, "Kishi"))) { + return true; + } + if (IsROGAlly(joystick)) { + /* I'm not sure if this is a Windows thing, or a quirk for ROG Ally, + * but we need to invert the sensor data on all axes. + */ + *invert_sensors = true; + return true; + } + return false; +} + +static void AttemptSensorFusion(SDL_Joystick *joystick, bool invert_sensors) +{ + SDL_SensorID *sensors; + unsigned int i, j; + + SDL_AssertJoysticksLocked(); + + if (!SDL_InitSubSystem(SDL_INIT_SENSOR)) { + return; + } + + sensors = SDL_GetSensors(NULL); + if (sensors) { + for (i = 0; sensors[i]; ++i) { + SDL_SensorID sensor = sensors[i]; + + if (!joystick->accel_sensor && SDL_GetSensorTypeForID(sensor) == SDL_SENSOR_ACCEL) { + // Increment the sensor subsystem reference count + SDL_InitSubSystem(SDL_INIT_SENSOR); + + joystick->accel_sensor = sensor; + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 0.0f); + } + if (!joystick->gyro_sensor && SDL_GetSensorTypeForID(sensor) == SDL_SENSOR_GYRO) { + // Increment the sensor subsystem reference count + SDL_InitSubSystem(SDL_INIT_SENSOR); + + joystick->gyro_sensor = sensor; + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, 0.0f); + } + } + SDL_free(sensors); + } + SDL_QuitSubSystem(SDL_INIT_SENSOR); + + /* SDL defines sensor orientation for phones relative to the natural + orientation, and for gamepads relative to being held in front of you. + When a phone is being used as a gamepad, its orientation changes, + so adjust sensor axes to match. + */ + //if (SDL_GetNaturalDisplayOrientation(SDL_GetPrimaryDisplay()) == SDL_ORIENTATION_LANDSCAPE) { + if (true) { + /* When a device in landscape orientation is laid flat, the axes change + orientation as follows: + -X to +X becomes -X to +X + -Y to +Y becomes +Z to -Z + -Z to +Z becomes -Y to +Y + */ + joystick->sensor_transform[0][0] = 1.0f; + joystick->sensor_transform[1][2] = 1.0f; + joystick->sensor_transform[2][1] = -1.0f; + } else { + /* When a device in portrait orientation is rotated left and laid flat, + the axes change orientation as follows: + -X to +X becomes +Z to -Z + -Y to +Y becomes +X to -X + -Z to +Z becomes -Y to +Y + */ + joystick->sensor_transform[0][1] = -1.0f; + joystick->sensor_transform[1][2] = 1.0f; + joystick->sensor_transform[2][0] = -1.0f; + } + + if (invert_sensors) { + for (i = 0; i < SDL_arraysize(joystick->sensor_transform); ++i) { + for (j = 0; j < SDL_arraysize(joystick->sensor_transform[i]); ++j) { + joystick->sensor_transform[i][j] *= -1.0f; + } + } + } +} + +static void CleanupSensorFusion(SDL_Joystick *joystick) +{ + SDL_AssertJoysticksLocked(); + + if (joystick->accel_sensor || joystick->gyro_sensor) { + if (joystick->accel_sensor) { + if (joystick->accel) { + SDL_CloseSensor(joystick->accel); + joystick->accel = NULL; + } + joystick->accel_sensor = 0; + + // Decrement the sensor subsystem reference count + SDL_QuitSubSystem(SDL_INIT_SENSOR); + } + if (joystick->gyro_sensor) { + if (joystick->gyro) { + SDL_CloseSensor(joystick->gyro); + joystick->gyro = NULL; + } + joystick->gyro_sensor = 0; + + // Decrement the sensor subsystem reference count + SDL_QuitSubSystem(SDL_INIT_SENSOR); + } + } +} + +static bool ShouldSwapFaceButtons(const SDL_SteamVirtualGamepadInfo *info) +{ + // When "Use Nintendo Button Layout" is enabled under Steam (the default) + // it will send button 0 for the A (east) button and button 1 for the + // B (south) button. This is done so that games that interpret the + // buttons as Xbox input will get button 0 for "A" as they expect. + // + // However, SDL reports positional buttons, so we need to swap + // the buttons so they show up in the correct position. This provides + // consistent behavior regardless of whether we're running under Steam, + // under the default settings. + if (info && + (info->type == SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO || + info->type == SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT || + info->type == SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT || + info->type == SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR)) { + return true; + } + return false; +} + +/* + * Open a joystick for use - the index passed as an argument refers to + * the N'th joystick on the system. This index is the value which will + * identify this joystick in future joystick events. + * + * This function returns a joystick identifier, or NULL if an error occurred. + */ +SDL_Joystick *SDL_OpenJoystick(SDL_JoystickID instance_id) +{ + SDL_JoystickDriver *driver; + int device_index; + SDL_Joystick *joystick; + SDL_Joystick *joysticklist; + const char *joystickname = NULL; + const char *joystickpath = NULL; + bool invert_sensors = false; + const SDL_SteamVirtualGamepadInfo *info; + + SDL_LockJoysticks(); + + if (!SDL_GetDriverAndJoystickIndex(instance_id, &driver, &device_index)) { + SDL_UnlockJoysticks(); + return NULL; + } + + joysticklist = SDL_joysticks; + /* If the joystick is already open, return it + * it is important that we have a single joystick for each instance id + */ + while (joysticklist) { + if (instance_id == joysticklist->instance_id) { + joystick = joysticklist; + ++joystick->ref_count; + SDL_UnlockJoysticks(); + return joystick; + } + joysticklist = joysticklist->next; + } + + // Create and initialize the joystick + joystick = (SDL_Joystick *)SDL_calloc(1, sizeof(*joystick)); + if (!joystick) { + SDL_UnlockJoysticks(); + return NULL; + } + SDL_SetObjectValid(joystick, SDL_OBJECT_TYPE_JOYSTICK, true); + joystick->driver = driver; + joystick->instance_id = instance_id; + joystick->attached = true; + joystick->led_expiration = SDL_GetTicks(); + joystick->battery_percent = -1; +#ifdef SDL_JOYSTICK_VIRTUAL + joystick->is_virtual = (driver == &SDL_VIRTUAL_JoystickDriver); +#else + joystick->is_virtual = false; +#endif + + if (!driver->Open(joystick, device_index)) { + SDL_SetObjectValid(joystick, SDL_OBJECT_TYPE_JOYSTICK, false); + SDL_free(joystick); + SDL_UnlockJoysticks(); + return NULL; + } + + joystickname = driver->GetDeviceName(device_index); + if (joystickname) { + joystick->name = SDL_strdup(joystickname); + } + + joystickpath = driver->GetDevicePath(device_index); + if (joystickpath) { + joystick->path = SDL_strdup(joystickpath); + } + + joystick->guid = driver->GetDeviceGUID(device_index); + + if (joystick->naxes > 0) { + joystick->axes = (SDL_JoystickAxisInfo *)SDL_calloc(joystick->naxes, sizeof(*joystick->axes)); + } + if (joystick->nballs > 0) { + joystick->balls = (SDL_JoystickBallData *)SDL_calloc(joystick->nballs, sizeof(*joystick->balls)); + } + if (joystick->nhats > 0) { + joystick->hats = (Uint8 *)SDL_calloc(joystick->nhats, sizeof(*joystick->hats)); + } + if (joystick->nbuttons > 0) { + joystick->buttons = (bool *)SDL_calloc(joystick->nbuttons, sizeof(*joystick->buttons)); + } + if (((joystick->naxes > 0) && !joystick->axes) || + ((joystick->nballs > 0) && !joystick->balls) || + ((joystick->nhats > 0) && !joystick->hats) || + ((joystick->nbuttons > 0) && !joystick->buttons)) { + SDL_CloseJoystick(joystick); + SDL_UnlockJoysticks(); + return NULL; + } + + // If this joystick is known to have all zero centered axes, skip the auto-centering code + if (SDL_JoystickAxesCenteredAtZero(joystick)) { + for (int i = 0; i < joystick->naxes; ++i) { + joystick->axes[i].has_initial_value = true; + } + } + + // We know the initial values for HIDAPI and XInput joysticks + if ((SDL_IsJoystickHIDAPI(joystick->guid) || + SDL_IsJoystickXInput(joystick->guid) || + SDL_IsJoystickRAWINPUT(joystick->guid) || + SDL_IsJoystickWGI(joystick->guid)) && + joystick->naxes >= SDL_GAMEPAD_AXIS_COUNT) { + int left_trigger, right_trigger; + if (SDL_IsJoystickXInput(joystick->guid)) { + left_trigger = 2; + right_trigger = 5; + } else { + left_trigger = SDL_GAMEPAD_AXIS_LEFT_TRIGGER; + right_trigger = SDL_GAMEPAD_AXIS_RIGHT_TRIGGER; + } + for (int i = 0; i < SDL_GAMEPAD_AXIS_COUNT; ++i) { + int initial_value; + if (i == left_trigger || i == right_trigger) { + initial_value = SDL_MIN_SINT16; + } else { + initial_value = 0; + } + joystick->axes[i].value = initial_value; + joystick->axes[i].zero = initial_value; + joystick->axes[i].initial_value = initial_value; + joystick->axes[i].has_initial_value = true; + } + } + + // Get the Steam Input API handle + info = SDL_GetJoystickVirtualGamepadInfoForID(instance_id); + if (info) { + joystick->steam_handle = info->handle; + joystick->swap_face_buttons = ShouldSwapFaceButtons(info); + } + + // Use system gyro and accelerometer if the gamepad doesn't have built-in sensors + if (ShouldAttemptSensorFusion(joystick, &invert_sensors)) { + AttemptSensorFusion(joystick, invert_sensors); + } + + // Add joystick to list + ++joystick->ref_count; + // Link the joystick in the list + joystick->next = SDL_joysticks; + SDL_joysticks = joystick; + + driver->Update(joystick); + + SDL_UnlockJoysticks(); + + return joystick; +} + +SDL_JoystickID SDL_AttachVirtualJoystick(const SDL_VirtualJoystickDesc *desc) +{ +#ifdef SDL_JOYSTICK_VIRTUAL + SDL_JoystickID result; + + SDL_LockJoysticks(); + result = SDL_JoystickAttachVirtualInner(desc); + SDL_UnlockJoysticks(); + return result; +#else + SDL_SetError("SDL not built with virtual-joystick support"); + return 0; +#endif +} + +bool SDL_DetachVirtualJoystick(SDL_JoystickID instance_id) +{ +#ifdef SDL_JOYSTICK_VIRTUAL + bool result; + + SDL_LockJoysticks(); + result = SDL_JoystickDetachVirtualInner(instance_id); + SDL_UnlockJoysticks(); + return result; +#else + return SDL_SetError("SDL not built with virtual-joystick support"); +#endif +} + +bool SDL_IsJoystickVirtual(SDL_JoystickID instance_id) +{ +#ifdef SDL_JOYSTICK_VIRTUAL + SDL_JoystickDriver *driver; + int device_index; + bool is_virtual = false; + + SDL_LockJoysticks(); + if (SDL_GetDriverAndJoystickIndex(instance_id, &driver, &device_index)) { + if (driver == &SDL_VIRTUAL_JoystickDriver) { + is_virtual = true; + } + } + SDL_UnlockJoysticks(); + + return is_virtual; +#else + return false; +#endif +} + +bool SDL_SetJoystickVirtualAxis(SDL_Joystick *joystick, int axis, Sint16 value) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + CHECK_JOYSTICK_VIRTUAL(joystick, false); + +#ifdef SDL_JOYSTICK_VIRTUAL + result = SDL_SetJoystickVirtualAxisInner(joystick, axis, value); +#else + result = SDL_SetError("SDL not built with virtual-joystick support"); +#endif + } + SDL_UnlockJoysticks(); + + return result; +} + +bool SDL_SetJoystickVirtualBall(SDL_Joystick *joystick, int ball, Sint16 xrel, Sint16 yrel) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + CHECK_JOYSTICK_VIRTUAL(joystick, false); + +#ifdef SDL_JOYSTICK_VIRTUAL + result = SDL_SetJoystickVirtualBallInner(joystick, ball, xrel, yrel); +#else + result = SDL_SetError("SDL not built with virtual-joystick support"); +#endif + } + SDL_UnlockJoysticks(); + + return result; +} + +bool SDL_SetJoystickVirtualButton(SDL_Joystick *joystick, int button, bool down) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + CHECK_JOYSTICK_VIRTUAL(joystick, false); + +#ifdef SDL_JOYSTICK_VIRTUAL + result = SDL_SetJoystickVirtualButtonInner(joystick, button, down); +#else + result = SDL_SetError("SDL not built with virtual-joystick support"); +#endif + } + SDL_UnlockJoysticks(); + + return result; +} + +bool SDL_SetJoystickVirtualHat(SDL_Joystick *joystick, int hat, Uint8 value) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + CHECK_JOYSTICK_VIRTUAL(joystick, false); + +#ifdef SDL_JOYSTICK_VIRTUAL + result = SDL_SetJoystickVirtualHatInner(joystick, hat, value); +#else + result = SDL_SetError("SDL not built with virtual-joystick support"); +#endif + } + SDL_UnlockJoysticks(); + + return result; +} + +bool SDL_SetJoystickVirtualTouchpad(SDL_Joystick *joystick, int touchpad, int finger, bool down, float x, float y, float pressure) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + CHECK_JOYSTICK_VIRTUAL(joystick, false); + +#ifdef SDL_JOYSTICK_VIRTUAL + result = SDL_SetJoystickVirtualTouchpadInner(joystick, touchpad, finger, down, x, y, pressure); +#else + result = SDL_SetError("SDL not built with virtual-joystick support"); +#endif + } + SDL_UnlockJoysticks(); + + return result; +} + +bool SDL_SendJoystickVirtualSensorData(SDL_Joystick *joystick, SDL_SensorType type, Uint64 sensor_timestamp, const float *data, int num_values) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + CHECK_JOYSTICK_VIRTUAL(joystick, false); + +#ifdef SDL_JOYSTICK_VIRTUAL + result = SDL_SendJoystickVirtualSensorDataInner(joystick, type, sensor_timestamp, data, num_values); +#else + result = SDL_SetError("SDL not built with virtual-joystick support"); +#endif + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Checks to make sure the joystick is valid. + */ +bool SDL_IsJoystickValid(SDL_Joystick *joystick) +{ + SDL_AssertJoysticksLocked(); + return SDL_ObjectValid(joystick, SDL_OBJECT_TYPE_JOYSTICK); +} + +bool SDL_PrivateJoystickGetAutoGamepadMapping(SDL_JoystickID instance_id, SDL_GamepadMapping *out) +{ + SDL_JoystickDriver *driver; + int device_index; + bool is_ok = false; + + SDL_LockJoysticks(); + if (SDL_GetDriverAndJoystickIndex(instance_id, &driver, &device_index)) { + is_ok = driver->GetGamepadMapping(device_index, out); + } + SDL_UnlockJoysticks(); + + return is_ok; +} + +/* + * Get the number of multi-dimensional axis controls on a joystick + */ +int SDL_GetNumJoystickAxes(SDL_Joystick *joystick) +{ + int result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, -1); + + result = joystick->naxes; + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the number of hats on a joystick + */ +int SDL_GetNumJoystickHats(SDL_Joystick *joystick) +{ + int result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, -1); + + result = joystick->nhats; + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the number of trackballs on a joystick + */ +int SDL_GetNumJoystickBalls(SDL_Joystick *joystick) +{ + CHECK_JOYSTICK_MAGIC(joystick, -1); + + return joystick->nballs; +} + +/* + * Get the number of buttons on a joystick + */ +int SDL_GetNumJoystickButtons(SDL_Joystick *joystick) +{ + int result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, -1); + + result = joystick->nbuttons; + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the current state of an axis control on a joystick + */ +Sint16 SDL_GetJoystickAxis(SDL_Joystick *joystick, int axis) +{ + Sint16 state; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, 0); + + if (axis < joystick->naxes) { + state = joystick->axes[axis].value; + } else { + SDL_SetError("Joystick only has %d axes", joystick->naxes); + state = 0; + } + } + SDL_UnlockJoysticks(); + + return state; +} + +/* + * Get the initial state of an axis control on a joystick + */ +bool SDL_GetJoystickAxisInitialState(SDL_Joystick *joystick, int axis, Sint16 *state) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + + if (axis >= joystick->naxes) { + SDL_SetError("Joystick only has %d axes", joystick->naxes); + result = false; + } else { + if (state) { + *state = joystick->axes[axis].initial_value; + } + result = joystick->axes[axis].has_initial_value; + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the current state of a hat on a joystick + */ +Uint8 SDL_GetJoystickHat(SDL_Joystick *joystick, int hat) +{ + Uint8 state; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, 0); + + if (hat < joystick->nhats) { + state = joystick->hats[hat]; + } else { + SDL_SetError("Joystick only has %d hats", joystick->nhats); + state = 0; + } + } + SDL_UnlockJoysticks(); + + return state; +} + +/* + * Get the ball axis change since the last poll + */ +bool SDL_GetJoystickBall(SDL_Joystick *joystick, int ball, int *dx, int *dy) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + + if (ball < joystick->nballs) { + if (dx) { + *dx = joystick->balls[ball].dx; + } + if (dy) { + *dy = joystick->balls[ball].dy; + } + joystick->balls[ball].dx = 0; + joystick->balls[ball].dy = 0; + result = true; + } else { + result = SDL_SetError("Joystick only has %d balls", joystick->nballs); + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the current state of a button on a joystick + */ +bool SDL_GetJoystickButton(SDL_Joystick *joystick, int button) +{ + bool down = false; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + + if (button < joystick->nbuttons) { + down = joystick->buttons[button]; + } else { + SDL_SetError("Joystick only has %d buttons", joystick->nbuttons); + } + } + SDL_UnlockJoysticks(); + + return down; +} + +/* + * Return if the joystick in question is currently attached to the system, + * \return false if not plugged in, true if still present. + */ +bool SDL_JoystickConnected(SDL_Joystick *joystick) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + + result = joystick->attached; + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the instance id for this opened joystick + */ +SDL_JoystickID SDL_GetJoystickID(SDL_Joystick *joystick) +{ + SDL_JoystickID result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, 0); + + result = joystick->instance_id; + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Return the SDL_Joystick associated with an instance id. + */ +SDL_Joystick *SDL_GetJoystickFromID(SDL_JoystickID instance_id) +{ + SDL_Joystick *joystick; + + SDL_LockJoysticks(); + for (joystick = SDL_joysticks; joystick; joystick = joystick->next) { + if (joystick->instance_id == instance_id) { + break; + } + } + SDL_UnlockJoysticks(); + return joystick; +} + +/** + * Return the SDL_Joystick associated with a player index. + */ +SDL_Joystick *SDL_GetJoystickFromPlayerIndex(int player_index) +{ + SDL_JoystickID instance_id; + SDL_Joystick *joystick; + + SDL_LockJoysticks(); + instance_id = SDL_GetJoystickIDForPlayerIndex(player_index); + for (joystick = SDL_joysticks; joystick; joystick = joystick->next) { + if (joystick->instance_id == instance_id) { + break; + } + } + SDL_UnlockJoysticks(); + return joystick; +} + +/* + * Get the properties associated with a joystick + */ +SDL_PropertiesID SDL_GetJoystickProperties(SDL_Joystick *joystick) +{ + SDL_PropertiesID result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, 0); + + if (joystick->props == 0) { + joystick->props = SDL_CreateProperties(); + } + result = joystick->props; + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the friendly name of this joystick + */ +const char *SDL_GetJoystickName(SDL_Joystick *joystick) +{ + const char *result; + const SDL_SteamVirtualGamepadInfo *info; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, NULL); + + info = SDL_GetJoystickVirtualGamepadInfoForID(joystick->instance_id); + if (info) { + result = SDL_GetPersistentString(info->name); + } else { + result = SDL_GetPersistentString(joystick->name); + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Get the implementation dependent path of this joystick + */ +const char *SDL_GetJoystickPath(SDL_Joystick *joystick) +{ + const char *result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, NULL); + + if (joystick->path) { + result = SDL_GetPersistentString(joystick->path); + } else { + SDL_Unsupported(); + result = NULL; + } + } + SDL_UnlockJoysticks(); + + return result; +} + +/** + * Get the player index of an opened joystick, or -1 if it's not available + */ +int SDL_GetJoystickPlayerIndex(SDL_Joystick *joystick) +{ + int result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, -1); + + result = SDL_GetPlayerIndexForJoystickID(joystick->instance_id); + } + SDL_UnlockJoysticks(); + + return result; +} + +/** + * Set the player index of an opened joystick + */ +bool SDL_SetJoystickPlayerIndex(SDL_Joystick *joystick, int player_index) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + + result = SDL_SetJoystickIDForPlayerIndex(player_index, joystick->instance_id); + } + SDL_UnlockJoysticks(); + + return result; +} + +bool SDL_RumbleJoystick(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + + if (low_frequency_rumble == joystick->low_frequency_rumble && + high_frequency_rumble == joystick->high_frequency_rumble) { + // Just update the expiration + result = true; + } else { + result = joystick->driver->Rumble(joystick, low_frequency_rumble, high_frequency_rumble); + if (result) { + joystick->rumble_resend = SDL_GetTicks() + SDL_RUMBLE_RESEND_MS; + if (joystick->rumble_resend == 0) { + joystick->rumble_resend = 1; + } + } else { + joystick->rumble_resend = 0; + } + } + + if (result) { + joystick->low_frequency_rumble = low_frequency_rumble; + joystick->high_frequency_rumble = high_frequency_rumble; + + if ((low_frequency_rumble || high_frequency_rumble) && duration_ms) { + joystick->rumble_expiration = SDL_GetTicks() + SDL_min(duration_ms, SDL_MAX_RUMBLE_DURATION_MS); + if (!joystick->rumble_expiration) { + joystick->rumble_expiration = 1; + } + } else { + joystick->rumble_expiration = 0; + joystick->rumble_resend = 0; + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +bool SDL_RumbleJoystickTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + + if (left_rumble == joystick->left_trigger_rumble && right_rumble == joystick->right_trigger_rumble) { + // Just update the expiration + result = true; + } else { + result = joystick->driver->RumbleTriggers(joystick, left_rumble, right_rumble); + if (result) { + joystick->trigger_rumble_resend = SDL_GetTicks() + SDL_RUMBLE_RESEND_MS; + if (joystick->trigger_rumble_resend == 0) { + joystick->trigger_rumble_resend = 1; + } + } else { + joystick->trigger_rumble_resend = 0; + } + } + + if (result) { + joystick->left_trigger_rumble = left_rumble; + joystick->right_trigger_rumble = right_rumble; + + if ((left_rumble || right_rumble) && duration_ms) { + joystick->trigger_rumble_expiration = SDL_GetTicks() + SDL_min(duration_ms, SDL_MAX_RUMBLE_DURATION_MS); + } else { + joystick->trigger_rumble_expiration = 0; + joystick->trigger_rumble_resend = 0; + } + } + } + SDL_UnlockJoysticks(); + + return result; +} + +bool SDL_SetJoystickLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + bool result; + bool isfreshvalue; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + + isfreshvalue = red != joystick->led_red || + green != joystick->led_green || + blue != joystick->led_blue; + + if (isfreshvalue || SDL_GetTicks() >= joystick->led_expiration) { + result = joystick->driver->SetLED(joystick, red, green, blue); + joystick->led_expiration = SDL_GetTicks() + SDL_LED_MIN_REPEAT_MS; + } else { + // Avoid spamming the driver + result = true; + } + + // Save the LED value regardless of success, so we don't spam the driver + joystick->led_red = red; + joystick->led_green = green; + joystick->led_blue = blue; + } + SDL_UnlockJoysticks(); + + return result; +} + +bool SDL_SendJoystickEffect(SDL_Joystick *joystick, const void *data, int size) +{ + bool result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, false); + + result = joystick->driver->SendEffect(joystick, data, size); + } + SDL_UnlockJoysticks(); + + return result; +} + +/* + * Close a joystick previously opened with SDL_OpenJoystick() + */ +void SDL_CloseJoystick(SDL_Joystick *joystick) +{ + SDL_Joystick *joysticklist; + SDL_Joystick *joysticklistprev; + int i; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick,); + + // First decrement ref count + if (--joystick->ref_count > 0) { + SDL_UnlockJoysticks(); + return; + } + + SDL_DestroyProperties(joystick->props); + + if (joystick->rumble_expiration) { + SDL_RumbleJoystick(joystick, 0, 0, 0); + } + if (joystick->trigger_rumble_expiration) { + SDL_RumbleJoystickTriggers(joystick, 0, 0, 0); + } + + CleanupSensorFusion(joystick); + + joystick->driver->Close(joystick); + joystick->hwdata = NULL; + SDL_SetObjectValid(joystick, SDL_OBJECT_TYPE_JOYSTICK, false); + + joysticklist = SDL_joysticks; + joysticklistprev = NULL; + while (joysticklist) { + if (joystick == joysticklist) { + if (joysticklistprev) { + // unlink this entry + joysticklistprev->next = joysticklist->next; + } else { + SDL_joysticks = joystick->next; + } + break; + } + joysticklistprev = joysticklist; + joysticklist = joysticklist->next; + } + + // Free the data associated with this joystick + SDL_free(joystick->name); + SDL_free(joystick->path); + SDL_free(joystick->serial); + SDL_free(joystick->axes); + SDL_free(joystick->balls); + SDL_free(joystick->hats); + SDL_free(joystick->buttons); + for (i = 0; i < joystick->ntouchpads; i++) { + SDL_JoystickTouchpadInfo *touchpad = &joystick->touchpads[i]; + SDL_free(touchpad->fingers); + } + SDL_free(joystick->touchpads); + SDL_free(joystick->sensors); + SDL_free(joystick); + } + SDL_UnlockJoysticks(); +} + +void SDL_QuitJoysticks(void) +{ + int i; + SDL_JoystickID *joysticks; + + SDL_LockJoysticks(); + + SDL_joysticks_quitting = true; + + joysticks = SDL_GetJoysticks(NULL); + if (joysticks) { + for (i = 0; joysticks[i]; ++i) { + SDL_PrivateJoystickRemoved(joysticks[i]); + } + SDL_free(joysticks); + } + + while (SDL_joysticks) { + SDL_joysticks->ref_count = 1; + SDL_CloseJoystick(SDL_joysticks); + } + + // Quit drivers in reverse order to avoid breaking dependencies between drivers + for (i = SDL_arraysize(SDL_joystick_drivers) - 1; i >= 0; --i) { + SDL_joystick_drivers[i]->Quit(); + } + + if (SDL_joystick_players) { + SDL_free(SDL_joystick_players); + SDL_joystick_players = NULL; + SDL_joystick_player_count = 0; + } + + SDL_QuitSubSystem(SDL_INIT_EVENTS); + + SDL_QuitSteamVirtualGamepadInfo(); + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, + SDL_JoystickAllowBackgroundEventsChanged, NULL); + + SDL_FreeVIDPIDList(&arcadestick_devices); + SDL_FreeVIDPIDList(&blacklist_devices); + SDL_FreeVIDPIDList(&flightstick_devices); + SDL_FreeVIDPIDList(&gamecube_devices); + SDL_FreeVIDPIDList(&rog_gamepad_mice); + SDL_FreeVIDPIDList(&throttle_devices); + SDL_FreeVIDPIDList(&wheel_devices); + SDL_FreeVIDPIDList(&zero_centered_devices); + + SDL_QuitGamepadMappings(); + + SDL_joysticks_quitting = false; + SDL_joysticks_initialized = false; + + SDL_UnlockJoysticks(); +} + +static bool SDL_PrivateJoystickShouldIgnoreEvent(void) +{ + if (SDL_joystick_allows_background_events) { + return false; + } + return false; +} + +// These are global for SDL_sysjoystick.c and SDL_events.c + +void SDL_PrivateJoystickAddTouchpad(SDL_Joystick *joystick, int nfingers) +{ + int ntouchpads; + SDL_JoystickTouchpadInfo *touchpads; + + SDL_AssertJoysticksLocked(); + + ntouchpads = joystick->ntouchpads + 1; + touchpads = (SDL_JoystickTouchpadInfo *)SDL_realloc(joystick->touchpads, (ntouchpads * sizeof(SDL_JoystickTouchpadInfo))); + if (touchpads) { + SDL_JoystickTouchpadInfo *touchpad = &touchpads[ntouchpads - 1]; + SDL_JoystickTouchpadFingerInfo *fingers = (SDL_JoystickTouchpadFingerInfo *)SDL_calloc(nfingers, sizeof(SDL_JoystickTouchpadFingerInfo)); + + if (fingers) { + touchpad->nfingers = nfingers; + touchpad->fingers = fingers; + } else { + // Out of memory, this touchpad won't be active + touchpad->nfingers = 0; + touchpad->fingers = NULL; + } + + joystick->ntouchpads = ntouchpads; + joystick->touchpads = touchpads; + } +} + +void SDL_PrivateJoystickAddSensor(SDL_Joystick *joystick, SDL_SensorType type, float rate) +{ + int nsensors; + SDL_JoystickSensorInfo *sensors; + + SDL_AssertJoysticksLocked(); + + nsensors = joystick->nsensors + 1; + sensors = (SDL_JoystickSensorInfo *)SDL_realloc(joystick->sensors, (nsensors * sizeof(SDL_JoystickSensorInfo))); + if (sensors) { + SDL_JoystickSensorInfo *sensor = &sensors[nsensors - 1]; + + SDL_zerop(sensor); + sensor->type = type; + sensor->rate = rate; + + joystick->nsensors = nsensors; + joystick->sensors = sensors; + } +} + +void SDL_PrivateJoystickSensorRate(SDL_Joystick *joystick, SDL_SensorType type, float rate) +{ + int i; + SDL_AssertJoysticksLocked(); + + for (i = 0; i < joystick->nsensors; ++i) { + if (joystick->sensors[i].type == type) { + joystick->sensors[i].rate = rate; + } + } +} + +void SDL_PrivateJoystickAdded(SDL_JoystickID instance_id) +{ + SDL_JoystickDriver *driver; + int device_index; + int player_index = -1; + + SDL_AssertJoysticksLocked(); + + if (SDL_JoysticksQuitting()) { + return; + } + + SDL_joystick_being_added = true; + + if (SDL_GetDriverAndJoystickIndex(instance_id, &driver, &device_index)) { + player_index = driver->GetDeviceSteamVirtualGamepadSlot(device_index); + if (player_index < 0) { + player_index = driver->GetDevicePlayerIndex(device_index); + } + } + if (player_index < 0 && SDL_IsGamepad(instance_id)) { + player_index = SDL_FindFreePlayerIndex(); + } + if (player_index >= 0) { + SDL_SetJoystickIDForPlayerIndex(player_index, instance_id); + } + + { + SDL_Event event; + + event.type = SDL_EVENT_JOYSTICK_ADDED; + event.common.timestamp = 0; + + if (SDL_EventEnabled(event.type)) { + event.jdevice.which = instance_id; + SDL_PushEvent(&event); + } + } + + SDL_joystick_being_added = false; + + if (SDL_IsGamepad(instance_id)) { + SDL_PrivateGamepadAdded(instance_id); + } +} + +bool SDL_IsJoystickBeingAdded(void) +{ + return SDL_joystick_being_added; +} + +void SDL_PrivateJoystickForceRecentering(SDL_Joystick *joystick) +{ + Uint8 i, j; + Uint64 timestamp = SDL_GetTicksNS(); + + SDL_AssertJoysticksLocked(); + + // Tell the app that everything is centered/unpressed... + for (i = 0; i < joystick->naxes; i++) { + if (joystick->axes[i].has_initial_value) { + SDL_SendJoystickAxis(timestamp, joystick, i, joystick->axes[i].zero); + } + } + + for (i = 0; i < joystick->nbuttons; i++) { + SDL_SendJoystickButton(timestamp, joystick, i, false); + } + + for (i = 0; i < joystick->nhats; i++) { + SDL_SendJoystickHat(timestamp, joystick, i, SDL_HAT_CENTERED); + } + + for (i = 0; i < joystick->ntouchpads; i++) { + SDL_JoystickTouchpadInfo *touchpad = &joystick->touchpads[i]; + + for (j = 0; j < touchpad->nfingers; ++j) { + SDL_SendJoystickTouchpad(timestamp, joystick, i, j, false, 0.0f, 0.0f, 0.0f); + } + } +} + +void SDL_PrivateJoystickRemoved(SDL_JoystickID instance_id) +{ + SDL_Joystick *joystick = NULL; + int player_index; + SDL_Event event; + + SDL_AssertJoysticksLocked(); + + // Find this joystick... + for (joystick = SDL_joysticks; joystick; joystick = joystick->next) { + if (joystick->instance_id == instance_id) { + SDL_PrivateJoystickForceRecentering(joystick); + joystick->attached = false; + break; + } + } + + if (SDL_IsGamepad(instance_id)) { + SDL_PrivateGamepadRemoved(instance_id); + } + + event.type = SDL_EVENT_JOYSTICK_REMOVED; + event.common.timestamp = 0; + + if (SDL_EventEnabled(event.type)) { + event.jdevice.which = instance_id; + SDL_PushEvent(&event); + } + + player_index = SDL_GetPlayerIndexForJoystickID(instance_id); + if (player_index >= 0) { + SDL_joystick_players[player_index] = 0; + } +} + +void SDL_SendJoystickAxis(Uint64 timestamp, SDL_Joystick *joystick, Uint8 axis, Sint16 value) +{ + SDL_JoystickAxisInfo *info; + + SDL_AssertJoysticksLocked(); + + // Make sure we're not getting garbage or duplicate events + if (axis >= joystick->naxes) { + return; + } + + info = &joystick->axes[axis]; + if (!info->has_initial_value || + (!info->has_second_value && (info->initial_value <= -32767 || info->initial_value == 32767) && SDL_abs(value) < (SDL_JOYSTICK_AXIS_MAX / 4))) { + info->initial_value = value; + info->value = value; + info->zero = value; + info->has_initial_value = true; + } else if (value == info->value && !info->sending_initial_value) { + return; + } else { + info->has_second_value = true; + } + if (!info->sent_initial_value) { + // Make sure we don't send motion until there's real activity on this axis + const int MAX_ALLOWED_JITTER = SDL_JOYSTICK_AXIS_MAX / 80; // ShanWan PS3 controller needed 96 + if (SDL_abs(value - info->value) <= MAX_ALLOWED_JITTER && + !SDL_IsJoystickVIRTUAL(joystick->guid)) { + return; + } + info->sent_initial_value = true; + info->sending_initial_value = true; + SDL_SendJoystickAxis(timestamp, joystick, axis, info->initial_value); + info->sending_initial_value = false; + } + + /* We ignore events if we don't have keyboard focus, except for centering + * events. + */ + if (SDL_PrivateJoystickShouldIgnoreEvent()) { + if (info->sending_initial_value || + (value > info->zero && value >= info->value) || + (value < info->zero && value <= info->value)) { + return; + } + } + + // Update internal joystick state + SDL_assert(timestamp != 0); + info->value = value; + joystick->update_complete = timestamp; + + // Post the event, if desired + if (SDL_EventEnabled(SDL_EVENT_JOYSTICK_AXIS_MOTION)) { + SDL_Event event; + event.type = SDL_EVENT_JOYSTICK_AXIS_MOTION; + event.common.timestamp = timestamp; + event.jaxis.which = joystick->instance_id; + event.jaxis.axis = axis; + event.jaxis.value = value; + SDL_PushEvent(&event); + } +} + +void SDL_SendJoystickBall(Uint64 timestamp, SDL_Joystick *joystick, Uint8 ball, Sint16 xrel, Sint16 yrel) +{ + SDL_AssertJoysticksLocked(); + + // Make sure we're not getting garbage events + if (ball >= joystick->nballs) { + return; + } + + // We ignore events if we don't have keyboard focus. + if (SDL_PrivateJoystickShouldIgnoreEvent()) { + return; + } + + // Update internal mouse state + joystick->balls[ball].dx += xrel; + joystick->balls[ball].dy += yrel; + + // Post the event, if desired + if (SDL_EventEnabled(SDL_EVENT_JOYSTICK_BALL_MOTION)) { + SDL_Event event; + event.type = SDL_EVENT_JOYSTICK_BALL_MOTION; + event.common.timestamp = timestamp; + event.jball.which = joystick->instance_id; + event.jball.ball = ball; + event.jball.xrel = xrel; + event.jball.yrel = yrel; + SDL_PushEvent(&event); + } +} + +void SDL_SendJoystickHat(Uint64 timestamp, SDL_Joystick *joystick, Uint8 hat, Uint8 value) +{ + SDL_AssertJoysticksLocked(); + + // Make sure we're not getting garbage or duplicate events + if (hat >= joystick->nhats) { + return; + } + if (value == joystick->hats[hat]) { + return; + } + + /* We ignore events if we don't have keyboard focus, except for centering + * events. + */ + if (SDL_PrivateJoystickShouldIgnoreEvent()) { + if (value != SDL_HAT_CENTERED) { + return; + } + } + + // Update internal joystick state + SDL_assert(timestamp != 0); + joystick->hats[hat] = value; + joystick->update_complete = timestamp; + + // Post the event, if desired + if (SDL_EventEnabled(SDL_EVENT_JOYSTICK_HAT_MOTION)) { + SDL_Event event; + event.type = SDL_EVENT_JOYSTICK_HAT_MOTION; + event.common.timestamp = timestamp; + event.jhat.which = joystick->instance_id; + event.jhat.hat = hat; + event.jhat.value = value; + SDL_PushEvent(&event); + } +} + +void SDL_SendJoystickButton(Uint64 timestamp, SDL_Joystick *joystick, Uint8 button, bool down) +{ + SDL_Event event; + + SDL_AssertJoysticksLocked(); + + if (down) { + event.type = SDL_EVENT_JOYSTICK_BUTTON_DOWN; + } else { + event.type = SDL_EVENT_JOYSTICK_BUTTON_UP; + } + + if (joystick->swap_face_buttons) { + switch (button) { + case 0: + button = 1; + break; + case 1: + button = 0; + break; + case 2: + button = 3; + break; + case 3: + button = 2; + break; + default: + break; + } + } + + // Make sure we're not getting garbage or duplicate events + if (button >= joystick->nbuttons) { + return; + } + if (down == joystick->buttons[button]) { + return; + } + + /* We ignore events if we don't have keyboard focus, except for button + * release. */ + if (SDL_PrivateJoystickShouldIgnoreEvent()) { + if (down) { + return; + } + } + + // Update internal joystick state + SDL_assert(timestamp != 0); + joystick->buttons[button] = down; + joystick->update_complete = timestamp; + + // Post the event, if desired + if (SDL_EventEnabled(event.type)) { + event.common.timestamp = timestamp; + event.jbutton.which = joystick->instance_id; + event.jbutton.button = button; + event.jbutton.down = down; + SDL_PushEvent(&event); + } +} + +static void SendSteamHandleUpdateEvents(void) +{ + SDL_Joystick *joystick; + const SDL_SteamVirtualGamepadInfo *info; + + // Check to see if any Steam handles changed + for (joystick = SDL_joysticks; joystick; joystick = joystick->next) { + bool changed = false; + + if (!SDL_IsGamepad(joystick->instance_id)) { + continue; + } + + info = SDL_GetJoystickVirtualGamepadInfoForID(joystick->instance_id); + if (info) { + if (joystick->steam_handle != info->handle) { + joystick->steam_handle = info->handle; + joystick->swap_face_buttons = ShouldSwapFaceButtons(info); + changed = true; + } + } else { + if (joystick->steam_handle != 0) { + joystick->steam_handle = 0; + joystick->swap_face_buttons = false; + changed = true; + } + } + if (changed) { + SDL_Event event; + + SDL_zero(event); + event.type = SDL_EVENT_GAMEPAD_STEAM_HANDLE_UPDATED; + event.common.timestamp = 0; + event.gdevice.which = joystick->instance_id; + SDL_PushEvent(&event); + } + } +} + +void SDL_UpdateJoysticks(void) +{ + int i; + Uint64 now; + SDL_Joystick *joystick; + + if (!SDL_WasInit(SDL_INIT_JOYSTICK)) { + return; + } + + SDL_LockJoysticks(); + + if (SDL_UpdateSteamVirtualGamepadInfo()) { + SendSteamHandleUpdateEvents(); + } + +#ifdef SDL_JOYSTICK_HIDAPI + // Special function for HIDAPI devices, as a single device can provide multiple SDL_Joysticks + HIDAPI_UpdateDevices(); +#endif // SDL_JOYSTICK_HIDAPI + + for (joystick = SDL_joysticks; joystick; joystick = joystick->next) { + if (!joystick->attached) { + continue; + } + + joystick->driver->Update(joystick); + + if (joystick->delayed_guide_button) { + SDL_GamepadHandleDelayedGuideButton(joystick); + } + + now = SDL_GetTicks(); + if (joystick->rumble_expiration && now >= joystick->rumble_expiration) { + SDL_RumbleJoystick(joystick, 0, 0, 0); + joystick->rumble_resend = 0; + } + + if (joystick->rumble_resend && now >= joystick->rumble_resend) { + joystick->driver->Rumble(joystick, joystick->low_frequency_rumble, joystick->high_frequency_rumble); + joystick->rumble_resend = now + SDL_RUMBLE_RESEND_MS; + if (joystick->rumble_resend == 0) { + joystick->rumble_resend = 1; + } + } + + if (joystick->trigger_rumble_expiration && now >= joystick->trigger_rumble_expiration) { + SDL_RumbleJoystickTriggers(joystick, 0, 0, 0); + joystick->trigger_rumble_resend = 0; + } + + if (joystick->trigger_rumble_resend && now >= joystick->trigger_rumble_resend) { + joystick->driver->RumbleTriggers(joystick, joystick->left_trigger_rumble, joystick->right_trigger_rumble); + joystick->trigger_rumble_resend = now + SDL_RUMBLE_RESEND_MS; + if (joystick->trigger_rumble_resend == 0) { + joystick->trigger_rumble_resend = 1; + } + } + } + + if (SDL_EventEnabled(SDL_EVENT_JOYSTICK_UPDATE_COMPLETE)) { + for (joystick = SDL_joysticks; joystick; joystick = joystick->next) { + if (joystick->update_complete) { + SDL_Event event; + + event.type = SDL_EVENT_JOYSTICK_UPDATE_COMPLETE; + event.common.timestamp = joystick->update_complete; + event.jdevice.which = joystick->instance_id; + SDL_PushEvent(&event); + + joystick->update_complete = 0; + } + } + } + + /* this needs to happen AFTER walking the joystick list above, so that any + dangling hardware data from removed devices can be free'd + */ + for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { + SDL_joystick_drivers[i]->Detect(); + } + + SDL_UnlockJoysticks(); +} + +static const Uint32 SDL_joystick_event_list[] = { + SDL_EVENT_JOYSTICK_AXIS_MOTION, + SDL_EVENT_JOYSTICK_BALL_MOTION, + SDL_EVENT_JOYSTICK_HAT_MOTION, + SDL_EVENT_JOYSTICK_BUTTON_DOWN, + SDL_EVENT_JOYSTICK_BUTTON_UP, + SDL_EVENT_JOYSTICK_ADDED, + SDL_EVENT_JOYSTICK_REMOVED, + SDL_EVENT_JOYSTICK_BATTERY_UPDATED +}; + +void SDL_SetJoystickEventsEnabled(bool enabled) +{ + unsigned int i; + + for (i = 0; i < SDL_arraysize(SDL_joystick_event_list); ++i) { + SDL_SetEventEnabled(SDL_joystick_event_list[i], enabled); + } +} + +bool SDL_JoystickEventsEnabled(void) +{ + bool enabled = false; + unsigned int i; + + for (i = 0; i < SDL_arraysize(SDL_joystick_event_list); ++i) { + enabled = SDL_EventEnabled(SDL_joystick_event_list[i]); + if (enabled) { + break; + } + } + return enabled; +} + +void SDL_GetJoystickGUIDInfo(SDL_GUID guid, Uint16 *vendor, Uint16 *product, Uint16 *version, Uint16 *crc16) +{ + Uint16 *guid16 = (Uint16 *)guid.data; + Uint16 bus = SDL_Swap16LE(guid16[0]); + + if ((bus < ' ' || bus == SDL_HARDWARE_BUS_VIRTUAL) && guid16[3] == 0x0000 && guid16[5] == 0x0000) { + /* This GUID fits the standard form: + * 16-bit bus + * 16-bit CRC16 of the joystick name (can be zero) + * 16-bit vendor ID + * 16-bit zero + * 16-bit product ID + * 16-bit zero + * 16-bit version + * 8-bit driver identifier ('h' for HIDAPI, 'x' for XInput, etc.) + * 8-bit driver-dependent type info + */ + if (vendor) { + *vendor = SDL_Swap16LE(guid16[2]); + } + if (product) { + *product = SDL_Swap16LE(guid16[4]); + } + if (version) { + *version = SDL_Swap16LE(guid16[6]); + } + if (crc16) { + *crc16 = SDL_Swap16LE(guid16[1]); + } + } else if (bus < ' ' || bus == SDL_HARDWARE_BUS_VIRTUAL) { + /* This GUID fits the unknown VID/PID form: + * 16-bit bus + * 16-bit CRC16 of the joystick name (can be zero) + * 11 characters of the joystick name, null terminated + */ + if (vendor) { + *vendor = 0; + } + if (product) { + *product = 0; + } + if (version) { + *version = 0; + } + if (crc16) { + *crc16 = SDL_Swap16LE(guid16[1]); + } + } else { + if (vendor) { + *vendor = 0; + } + if (product) { + *product = 0; + } + if (version) { + *version = 0; + } + if (crc16) { + *crc16 = 0; + } + } +} + +char *SDL_CreateJoystickName(Uint16 vendor, Uint16 product, const char *vendor_name, const char *product_name) +{ + const char *custom_name = GuessControllerName(vendor, product); + if (custom_name) { + return SDL_strdup(custom_name); + } + + return SDL_CreateDeviceName(vendor, product, vendor_name, product_name, "Controller"); +} + +SDL_GUID SDL_CreateJoystickGUID(Uint16 bus, Uint16 vendor, Uint16 product, Uint16 version, const char *vendor_name, const char *product_name, Uint8 driver_signature, Uint8 driver_data) +{ + SDL_GUID guid; + Uint16 *guid16 = (Uint16 *)guid.data; + Uint16 crc = 0; + + SDL_zero(guid); + + if (vendor_name && *vendor_name && product_name && *product_name) { + crc = SDL_crc16(crc, vendor_name, SDL_strlen(vendor_name)); + crc = SDL_crc16(crc, " ", 1); + crc = SDL_crc16(crc, product_name, SDL_strlen(product_name)); + } else if (product_name) { + crc = SDL_crc16(crc, product_name, SDL_strlen(product_name)); + } + + // We only need 16 bits for each of these; space them out to fill 128. + // Byteswap so devices get same GUID on little/big endian platforms. + *guid16++ = SDL_Swap16LE(bus); + *guid16++ = SDL_Swap16LE(crc); + + if (vendor) { + *guid16++ = SDL_Swap16LE(vendor); + *guid16++ = 0; + *guid16++ = SDL_Swap16LE(product); + *guid16++ = 0; + *guid16++ = SDL_Swap16LE(version); + guid.data[14] = driver_signature; + guid.data[15] = driver_data; + } else { + size_t available_space = sizeof(guid.data) - 4; + + if (driver_signature) { + available_space -= 2; + guid.data[14] = driver_signature; + guid.data[15] = driver_data; + } + if (product_name) { + SDL_strlcpy((char *)guid16, product_name, available_space); + } + } + return guid; +} + +SDL_GUID SDL_CreateJoystickGUIDForName(const char *name) +{ + return SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_UNKNOWN, 0, 0, 0, NULL, name, 0, 0); +} + +void SDL_SetJoystickGUIDVendor(SDL_GUID *guid, Uint16 vendor) +{ + Uint16 *guid16 = (Uint16 *)guid->data; + + guid16[2] = SDL_Swap16LE(vendor); +} + +void SDL_SetJoystickGUIDProduct(SDL_GUID *guid, Uint16 product) +{ + Uint16 *guid16 = (Uint16 *)guid->data; + + guid16[4] = SDL_Swap16LE(product); +} + +void SDL_SetJoystickGUIDVersion(SDL_GUID *guid, Uint16 version) +{ + Uint16 *guid16 = (Uint16 *)guid->data; + + guid16[6] = SDL_Swap16LE(version); +} + +void SDL_SetJoystickGUIDCRC(SDL_GUID *guid, Uint16 crc) +{ + Uint16 *guid16 = (Uint16 *)guid->data; + + guid16[1] = SDL_Swap16LE(crc); +} + +SDL_GamepadType SDL_GetGamepadTypeFromVIDPID(Uint16 vendor, Uint16 product, const char *name, bool forUI) +{ + SDL_GamepadType type = SDL_GAMEPAD_TYPE_STANDARD; + + if (vendor == 0x0000 && product == 0x0000) { + // Some devices are only identifiable by their name + if (name && + (SDL_strcmp(name, "Lic Pro Controller") == 0 || + SDL_strcmp(name, "Nintendo Wireless Gamepad") == 0 || + SDL_strcmp(name, "Wireless Gamepad") == 0)) { + // HORI or PowerA Switch Pro Controller clone + type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO; + } + + } else if (vendor == 0x0001 && product == 0x0001) { + type = SDL_GAMEPAD_TYPE_STANDARD; + + } else if (vendor == USB_VENDOR_NINTENDO && product == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT) { + type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT; + + } else if (vendor == USB_VENDOR_NINTENDO && product == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT) { + if (name && SDL_strstr(name, "NES Controller") != NULL) { + // We don't have a type for the Nintendo Online NES Controller + type = SDL_GAMEPAD_TYPE_STANDARD; + } else { + type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT; + } + + } else if (vendor == USB_VENDOR_NINTENDO && product == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP) { + if (name && SDL_strstr(name, "(L)") != NULL) { + type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT; + } else { + type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT; + } + + } else if (vendor == USB_VENDOR_NINTENDO && product == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR) { + type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR; + + } else if (forUI && SDL_IsJoystickGameCube(vendor, product)) { + // We don't have a type for the Nintendo GameCube controller + type = SDL_GAMEPAD_TYPE_STANDARD; + + } else { + switch (GuessControllerType(vendor, product)) { + case k_eControllerType_XBox360Controller: + type = SDL_GAMEPAD_TYPE_XBOX360; + break; + case k_eControllerType_XBoxOneController: + type = SDL_GAMEPAD_TYPE_XBOXONE; + break; + case k_eControllerType_PS3Controller: + type = SDL_GAMEPAD_TYPE_PS3; + break; + case k_eControllerType_PS4Controller: + type = SDL_GAMEPAD_TYPE_PS4; + break; + case k_eControllerType_PS5Controller: + type = SDL_GAMEPAD_TYPE_PS5; + break; + case k_eControllerType_XInputPS4Controller: + if (forUI) { + type = SDL_GAMEPAD_TYPE_PS4; + } else { + type = SDL_GAMEPAD_TYPE_STANDARD; + } + break; + case k_eControllerType_SwitchProController: + case k_eControllerType_SwitchInputOnlyController: + type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO; + break; + case k_eControllerType_XInputSwitchController: + if (forUI) { + type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO; + } else { + type = SDL_GAMEPAD_TYPE_STANDARD; + } + break; + default: + break; + } + } + return type; +} + +SDL_GamepadType SDL_GetGamepadTypeFromGUID(SDL_GUID guid, const char *name) +{ + SDL_GamepadType type; + Uint16 vendor, product; + + SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL, NULL); + type = SDL_GetGamepadTypeFromVIDPID(vendor, product, name, true); + if (type == SDL_GAMEPAD_TYPE_STANDARD) { + if (SDL_IsJoystickXInput(guid)) { + // This is probably an Xbox One controller + return SDL_GAMEPAD_TYPE_XBOXONE; + } +#ifdef SDL_JOYSTICK_HIDAPI + if (SDL_IsJoystickHIDAPI(guid)) { + return HIDAPI_GetGamepadTypeFromGUID(guid); + } +#endif // SDL_JOYSTICK_HIDAPI + } + return type; +} + +bool SDL_JoystickGUIDUsesVersion(SDL_GUID guid) +{ + Uint16 vendor, product; + + if (SDL_IsJoystickMFI(guid)) { + // The version bits are used as button capability mask + return false; + } + + SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL, NULL); + if (vendor && product) { + return true; + } + return false; +} + +bool SDL_IsJoystickXboxOne(Uint16 vendor_id, Uint16 product_id) +{ + EControllerType eType = GuessControllerType(vendor_id, product_id); + return eType == k_eControllerType_XBoxOneController; +} + +bool SDL_IsJoystickXboxOneElite(Uint16 vendor_id, Uint16 product_id) +{ + if (vendor_id == USB_VENDOR_MICROSOFT) { + if (product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_1 || + product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2 || + product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLUETOOTH || + product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLE) { + return true; + } + } + return false; +} + +bool SDL_IsJoystickXboxSeriesX(Uint16 vendor_id, Uint16 product_id) +{ + if (vendor_id == USB_VENDOR_MICROSOFT) { + if (product_id == USB_PRODUCT_XBOX_SERIES_X || + product_id == USB_PRODUCT_XBOX_SERIES_X_BLE) { + return true; + } + } + if (vendor_id == USB_VENDOR_PDP) { + if (product_id == USB_PRODUCT_XBOX_SERIES_X_VICTRIX_GAMBIT || + product_id == USB_PRODUCT_XBOX_SERIES_X_PDP_BLUE || + product_id == USB_PRODUCT_XBOX_SERIES_X_PDP_AFTERGLOW) { + return true; + } + } + if (vendor_id == USB_VENDOR_POWERA_ALT) { + if ((product_id >= 0x2001 && product_id <= 0x201a) || + product_id == USB_PRODUCT_XBOX_SERIES_X_POWERA_FUSION_PRO2 || + product_id == USB_PRODUCT_XBOX_SERIES_X_POWERA_FUSION_PRO4 || + product_id == USB_PRODUCT_XBOX_SERIES_X_POWERA_FUSION_PRO_WIRELESS_USB || + product_id == USB_PRODUCT_XBOX_SERIES_X_POWERA_FUSION_PRO_WIRELESS_DONGLE || + product_id == USB_PRODUCT_XBOX_SERIES_X_POWERA_MOGA_XP_ULTRA || + product_id == USB_PRODUCT_XBOX_SERIES_X_POWERA_SPECTRA) { + return true; + } + } + if (vendor_id == USB_VENDOR_HORI) { + if (product_id == USB_PRODUCT_HORI_FIGHTING_COMMANDER_OCTA_SERIES_X || + product_id == USB_PRODUCT_HORI_HORIPAD_PRO_SERIES_X || + product_id == USB_PRODUCT_HORI_TAIKO_DRUM_CONTROLLER) { + return true; + } + } + if (vendor_id == USB_VENDOR_HP) { + if (product_id == USB_PRODUCT_XBOX_SERIES_X_HP_HYPERX || + product_id == USB_PRODUCT_XBOX_SERIES_X_HP_HYPERX_RGB) { + return true; + } + } + if (vendor_id == USB_VENDOR_RAZER) { + if (product_id == USB_PRODUCT_RAZER_WOLVERINE_V2 || + product_id == USB_PRODUCT_RAZER_WOLVERINE_V2_CHROMA || + product_id == USB_PRODUCT_RAZER_WOLVERINE_V3_PRO) { + return true; + } + } + if (vendor_id == USB_VENDOR_THRUSTMASTER) { + if (product_id == USB_PRODUCT_THRUSTMASTER_ESWAPX_PRO_SERIES_X) { + return true; + } + } + if (vendor_id == USB_VENDOR_TURTLE_BEACH) { + if (product_id == USB_PRODUCT_TURTLE_BEACH_SERIES_X_REACT_R || + product_id == USB_PRODUCT_TURTLE_BEACH_SERIES_X_RECON) { + return true; + } + } + if (vendor_id == USB_VENDOR_8BITDO) { + if (product_id == USB_PRODUCT_8BITDO_XBOX_CONTROLLER1 || + product_id == USB_PRODUCT_8BITDO_XBOX_CONTROLLER2) { + return true; + } + } + if (vendor_id == USB_VENDOR_GAMESIR) { + if (product_id == USB_PRODUCT_GAMESIR_G7) { + return true; + } + } + if (vendor_id == USB_VENDOR_ASUS) { + if (product_id == USB_PRODUCT_ROG_RAIKIRI) { + return true; + } + } + return false; +} + +bool SDL_IsJoystickBluetoothXboxOne(Uint16 vendor_id, Uint16 product_id) +{ + if (vendor_id == USB_VENDOR_MICROSOFT) { + if (product_id == USB_PRODUCT_XBOX_ONE_ADAPTIVE_BLUETOOTH || + product_id == USB_PRODUCT_XBOX_ONE_ADAPTIVE_BLE || + product_id == USB_PRODUCT_XBOX_ONE_S_REV1_BLUETOOTH || + product_id == USB_PRODUCT_XBOX_ONE_S_REV2_BLUETOOTH || + product_id == USB_PRODUCT_XBOX_ONE_S_REV2_BLE || + product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLUETOOTH || + product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLE || + product_id == USB_PRODUCT_XBOX_SERIES_X_BLE) { + return true; + } + } + return false; +} + +bool SDL_IsJoystickPS4(Uint16 vendor_id, Uint16 product_id) +{ + EControllerType eType = GuessControllerType(vendor_id, product_id); + return eType == k_eControllerType_PS4Controller; +} + +bool SDL_IsJoystickPS5(Uint16 vendor_id, Uint16 product_id) +{ + EControllerType eType = GuessControllerType(vendor_id, product_id); + return eType == k_eControllerType_PS5Controller; +} + +bool SDL_IsJoystickDualSenseEdge(Uint16 vendor_id, Uint16 product_id) +{ + if (vendor_id == USB_VENDOR_SONY) { + if (product_id == USB_PRODUCT_SONY_DS5_EDGE) { + return true; + } + } + return false; +} + +bool SDL_IsJoystickNintendoSwitchPro(Uint16 vendor_id, Uint16 product_id) +{ + EControllerType eType = GuessControllerType(vendor_id, product_id); + return eType == k_eControllerType_SwitchProController || eType == k_eControllerType_SwitchInputOnlyController; +} + +bool SDL_IsJoystickNintendoSwitchProInputOnly(Uint16 vendor_id, Uint16 product_id) +{ + EControllerType eType = GuessControllerType(vendor_id, product_id); + return eType == k_eControllerType_SwitchInputOnlyController; +} + +bool SDL_IsJoystickNintendoSwitchJoyCon(Uint16 vendor_id, Uint16 product_id) +{ + EControllerType eType = GuessControllerType(vendor_id, product_id); + return eType == k_eControllerType_SwitchJoyConLeft || eType == k_eControllerType_SwitchJoyConRight; +} + +bool SDL_IsJoystickNintendoSwitchJoyConLeft(Uint16 vendor_id, Uint16 product_id) +{ + EControllerType eType = GuessControllerType(vendor_id, product_id); + return eType == k_eControllerType_SwitchJoyConLeft; +} + +bool SDL_IsJoystickNintendoSwitchJoyConRight(Uint16 vendor_id, Uint16 product_id) +{ + EControllerType eType = GuessControllerType(vendor_id, product_id); + return eType == k_eControllerType_SwitchJoyConRight; +} + +bool SDL_IsJoystickNintendoSwitchJoyConGrip(Uint16 vendor_id, Uint16 product_id) +{ + return vendor_id == USB_VENDOR_NINTENDO && product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP; +} + +bool SDL_IsJoystickNintendoSwitchJoyConPair(Uint16 vendor_id, Uint16 product_id) +{ + return vendor_id == USB_VENDOR_NINTENDO && product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR; +} + +bool SDL_IsJoystickGameCube(Uint16 vendor_id, Uint16 product_id) +{ + return SDL_VIDPIDInList(vendor_id, product_id, &gamecube_devices); +} + +bool SDL_IsJoystickAmazonLunaController(Uint16 vendor_id, Uint16 product_id) +{ + return ((vendor_id == USB_VENDOR_AMAZON && product_id == USB_PRODUCT_AMAZON_LUNA_CONTROLLER) || + (vendor_id == BLUETOOTH_VENDOR_AMAZON && product_id == BLUETOOTH_PRODUCT_LUNA_CONTROLLER)); +} + +bool SDL_IsJoystickGoogleStadiaController(Uint16 vendor_id, Uint16 product_id) +{ + return vendor_id == USB_VENDOR_GOOGLE && product_id == USB_PRODUCT_GOOGLE_STADIA_CONTROLLER; +} + +bool SDL_IsJoystickNVIDIASHIELDController(Uint16 vendor_id, Uint16 product_id) +{ + return (vendor_id == USB_VENDOR_NVIDIA && + (product_id == USB_PRODUCT_NVIDIA_SHIELD_CONTROLLER_V103 || + product_id == USB_PRODUCT_NVIDIA_SHIELD_CONTROLLER_V104)); +} + +bool SDL_IsJoystickSteamVirtualGamepad(Uint16 vendor_id, Uint16 product_id, Uint16 version) +{ +#ifdef SDL_PLATFORM_MACOS + return (vendor_id == USB_VENDOR_MICROSOFT && product_id == USB_PRODUCT_XBOX360_WIRED_CONTROLLER && version == 0); +#else + return (vendor_id == USB_VENDOR_VALVE && product_id == USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD); +#endif +} + +bool SDL_IsJoystickSteamController(Uint16 vendor_id, Uint16 product_id) +{ + EControllerType eType = GuessControllerType(vendor_id, product_id); + return eType == k_eControllerType_SteamController || eType == k_eControllerType_SteamControllerV2; +} + +bool SDL_IsJoystickHoriSteamController(Uint16 vendor_id, Uint16 product_id) +{ + return vendor_id == USB_VENDOR_HORI && (product_id == USB_PRODUCT_HORI_STEAM_CONTROLLER || product_id == USB_PRODUCT_HORI_STEAM_CONTROLLER_BT); +} + +bool SDL_IsJoystickSteamDeck(Uint16 vendor_id, Uint16 product_id) +{ + EControllerType eType = GuessControllerType(vendor_id, product_id); + return eType == k_eControllerType_SteamControllerNeptune; +} + +bool SDL_IsJoystickXInput(SDL_GUID guid) +{ + return (guid.data[14] == 'x') ? true : false; +} + +bool SDL_IsJoystickWGI(SDL_GUID guid) +{ + return (guid.data[14] == 'w') ? true : false; +} + +bool SDL_IsJoystickHIDAPI(SDL_GUID guid) +{ + return (guid.data[14] == 'h') ? true : false; +} + +bool SDL_IsJoystickMFI(SDL_GUID guid) +{ + return (guid.data[14] == 'm') ? true : false; +} + +bool SDL_IsJoystickRAWINPUT(SDL_GUID guid) +{ + return (guid.data[14] == 'r') ? true : false; +} + +bool SDL_IsJoystickVIRTUAL(SDL_GUID guid) +{ + return (guid.data[14] == 'v') ? true : false; +} + +static bool SDL_IsJoystickWheel(Uint16 vendor_id, Uint16 product_id) +{ + return SDL_VIDPIDInList(vendor_id, product_id, &wheel_devices); +} + +static bool SDL_IsJoystickArcadeStick(Uint16 vendor_id, Uint16 product_id) +{ + return SDL_VIDPIDInList(vendor_id, product_id, &arcadestick_devices); +} + +static bool SDL_IsJoystickFlightStick(Uint16 vendor_id, Uint16 product_id) +{ + return SDL_VIDPIDInList(vendor_id, product_id, &flightstick_devices); +} + +static bool SDL_IsJoystickThrottle(Uint16 vendor_id, Uint16 product_id) +{ + return SDL_VIDPIDInList(vendor_id, product_id, &throttle_devices); +} + +static SDL_JoystickType SDL_GetJoystickGUIDType(SDL_GUID guid) +{ + Uint16 vendor; + Uint16 product; + + SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL, NULL); + + if (SDL_IsJoystickWheel(vendor, product)) { + return SDL_JOYSTICK_TYPE_WHEEL; + } + + if (SDL_IsJoystickArcadeStick(vendor, product)) { + return SDL_JOYSTICK_TYPE_ARCADE_STICK; + } + + if (SDL_IsJoystickFlightStick(vendor, product)) { + return SDL_JOYSTICK_TYPE_FLIGHT_STICK; + } + + if (SDL_IsJoystickThrottle(vendor, product)) { + return SDL_JOYSTICK_TYPE_THROTTLE; + } + + if (SDL_IsJoystickXInput(guid)) { + // XInput GUID, get the type based on the XInput device subtype + switch (guid.data[15]) { + case 0x01: // XINPUT_DEVSUBTYPE_GAMEPAD + return SDL_JOYSTICK_TYPE_GAMEPAD; + case 0x02: // XINPUT_DEVSUBTYPE_WHEEL + return SDL_JOYSTICK_TYPE_WHEEL; + case 0x03: // XINPUT_DEVSUBTYPE_ARCADE_STICK + return SDL_JOYSTICK_TYPE_ARCADE_STICK; + case 0x04: // XINPUT_DEVSUBTYPE_FLIGHT_STICK + return SDL_JOYSTICK_TYPE_FLIGHT_STICK; + case 0x05: // XINPUT_DEVSUBTYPE_DANCE_PAD + return SDL_JOYSTICK_TYPE_DANCE_PAD; + case 0x06: // XINPUT_DEVSUBTYPE_GUITAR + case 0x07: // XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE + case 0x0B: // XINPUT_DEVSUBTYPE_GUITAR_BASS + return SDL_JOYSTICK_TYPE_GUITAR; + case 0x08: // XINPUT_DEVSUBTYPE_DRUM_KIT + return SDL_JOYSTICK_TYPE_DRUM_KIT; + case 0x13: // XINPUT_DEVSUBTYPE_ARCADE_PAD + return SDL_JOYSTICK_TYPE_ARCADE_PAD; + default: + return SDL_JOYSTICK_TYPE_UNKNOWN; + } + } + + if (SDL_IsJoystickWGI(guid)) { + return (SDL_JoystickType)guid.data[15]; + } + + if (SDL_IsJoystickVIRTUAL(guid)) { + return (SDL_JoystickType)guid.data[15]; + } + +#ifdef SDL_JOYSTICK_HIDAPI + if (SDL_IsJoystickHIDAPI(guid)) { + return HIDAPI_GetJoystickTypeFromGUID(guid); + } +#endif // SDL_JOYSTICK_HIDAPI + + if (GuessControllerType(vendor, product) != k_eControllerType_UnknownNonSteamController) { + return SDL_JOYSTICK_TYPE_GAMEPAD; + } + + return SDL_JOYSTICK_TYPE_UNKNOWN; +} + +bool SDL_ShouldIgnoreJoystick(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ + // Check the joystick blacklist + if (SDL_VIDPIDInList(vendor_id, product_id, &blacklist_devices)) { + return true; + } + if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_ROG_CHAKRAM, false)) { + if (SDL_VIDPIDInList(vendor_id, product_id, &rog_gamepad_mice)) { + return true; + } + } + + if (SDL_ShouldIgnoreGamepad(vendor_id, product_id, version, name)) { + return true; + } + + return false; +} + +// return the guid for this index +SDL_GUID SDL_GetJoystickGUIDForID(SDL_JoystickID instance_id) +{ + SDL_JoystickDriver *driver; + int device_index; + SDL_GUID guid; + + SDL_LockJoysticks(); + if (SDL_GetDriverAndJoystickIndex(instance_id, &driver, &device_index)) { + guid = driver->GetDeviceGUID(device_index); + } else { + SDL_zero(guid); + } + SDL_UnlockJoysticks(); + + return guid; +} + +Uint16 SDL_GetJoystickVendorForID(SDL_JoystickID instance_id) +{ + Uint16 vendor; + const SDL_SteamVirtualGamepadInfo *info; + + SDL_LockJoysticks(); + info = SDL_GetJoystickVirtualGamepadInfoForID(instance_id); + if (info) { + vendor = info->vendor_id; + } else { + SDL_GUID guid = SDL_GetJoystickGUIDForID(instance_id); + + SDL_GetJoystickGUIDInfo(guid, &vendor, NULL, NULL, NULL); + } + SDL_UnlockJoysticks(); + + return vendor; +} + +Uint16 SDL_GetJoystickProductForID(SDL_JoystickID instance_id) +{ + Uint16 product; + const SDL_SteamVirtualGamepadInfo *info; + + SDL_LockJoysticks(); + info = SDL_GetJoystickVirtualGamepadInfoForID(instance_id); + if (info) { + product = info->product_id; + } else { + SDL_GUID guid = SDL_GetJoystickGUIDForID(instance_id); + + SDL_GetJoystickGUIDInfo(guid, NULL, &product, NULL, NULL); + } + SDL_UnlockJoysticks(); + + return product; +} + +Uint16 SDL_GetJoystickProductVersionForID(SDL_JoystickID instance_id) +{ + Uint16 version; + SDL_GUID guid = SDL_GetJoystickGUIDForID(instance_id); + + SDL_GetJoystickGUIDInfo(guid, NULL, NULL, &version, NULL); + return version; +} + +SDL_JoystickType SDL_GetJoystickTypeForID(SDL_JoystickID instance_id) +{ + SDL_JoystickType type; + SDL_GUID guid = SDL_GetJoystickGUIDForID(instance_id); + + type = SDL_GetJoystickGUIDType(guid); + if (type == SDL_JOYSTICK_TYPE_UNKNOWN) { + if (SDL_IsGamepad(instance_id)) { + type = SDL_JOYSTICK_TYPE_GAMEPAD; + } + } + return type; +} + +SDL_GUID SDL_GetJoystickGUID(SDL_Joystick *joystick) +{ + SDL_GUID result; + + SDL_LockJoysticks(); + { + static SDL_GUID emptyGUID; + + CHECK_JOYSTICK_MAGIC(joystick, emptyGUID); + + result = joystick->guid; + } + SDL_UnlockJoysticks(); + + return result; +} + +Uint16 SDL_GetJoystickVendor(SDL_Joystick *joystick) +{ + Uint16 vendor; + const SDL_SteamVirtualGamepadInfo *info; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, 0); + + info = SDL_GetJoystickVirtualGamepadInfoForID(joystick->instance_id); + if (info) { + vendor = info->vendor_id; + } else { + SDL_GUID guid = SDL_GetJoystickGUID(joystick); + + SDL_GetJoystickGUIDInfo(guid, &vendor, NULL, NULL, NULL); + } + } + SDL_UnlockJoysticks(); + + return vendor; +} + +Uint16 SDL_GetJoystickProduct(SDL_Joystick *joystick) +{ + Uint16 product; + const SDL_SteamVirtualGamepadInfo *info; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, 0); + + info = SDL_GetJoystickVirtualGamepadInfoForID(joystick->instance_id); + if (info) { + product = info->product_id; + } else { + SDL_GUID guid = SDL_GetJoystickGUID(joystick); + + SDL_GetJoystickGUIDInfo(guid, NULL, &product, NULL, NULL); + } + } + SDL_UnlockJoysticks(); + + return product; +} + +Uint16 SDL_GetJoystickProductVersion(SDL_Joystick *joystick) +{ + Uint16 version; + SDL_GUID guid = SDL_GetJoystickGUID(joystick); + + SDL_GetJoystickGUIDInfo(guid, NULL, NULL, &version, NULL); + return version; +} + +Uint16 SDL_GetJoystickFirmwareVersion(SDL_Joystick *joystick) +{ + Uint16 result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, 0); + + result = joystick->firmware_version; + } + SDL_UnlockJoysticks(); + + return result; +} + +const char *SDL_GetJoystickSerial(SDL_Joystick *joystick) +{ + const char *result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, NULL); + + result = SDL_GetPersistentString(joystick->serial); + } + SDL_UnlockJoysticks(); + + return result; +} + +SDL_JoystickType SDL_GetJoystickType(SDL_Joystick *joystick) +{ + SDL_JoystickType type; + SDL_GUID guid = SDL_GetJoystickGUID(joystick); + + type = SDL_GetJoystickGUIDType(guid); + if (type == SDL_JOYSTICK_TYPE_UNKNOWN) { + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, SDL_JOYSTICK_TYPE_UNKNOWN); + + if (SDL_IsGamepad(joystick->instance_id)) { + type = SDL_JOYSTICK_TYPE_GAMEPAD; + } + } + SDL_UnlockJoysticks(); + } + return type; +} + +void SDL_SendJoystickPowerInfo(SDL_Joystick *joystick, SDL_PowerState state, int percent) +{ + SDL_AssertJoysticksLocked(); + + if (state != joystick->battery_state || percent != joystick->battery_percent) { + joystick->battery_state = state; + joystick->battery_percent = percent; + + if (SDL_EventEnabled(SDL_EVENT_JOYSTICK_BATTERY_UPDATED)) { + SDL_Event event; + event.type = SDL_EVENT_JOYSTICK_BATTERY_UPDATED; + event.common.timestamp = 0; + event.jbattery.which = joystick->instance_id; + event.jbattery.state = state; + event.jbattery.percent = percent; + SDL_PushEvent(&event); + } + } +} + +SDL_JoystickConnectionState SDL_GetJoystickConnectionState(SDL_Joystick *joystick) +{ + SDL_JoystickConnectionState result; + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, SDL_JOYSTICK_CONNECTION_INVALID); + + result = joystick->connection_state; + } + SDL_UnlockJoysticks(); + + return result; +} + +SDL_PowerState SDL_GetJoystickPowerInfo(SDL_Joystick *joystick, int *percent) +{ + SDL_PowerState result; + + if (percent) { + *percent = -1; + } + + SDL_LockJoysticks(); + { + CHECK_JOYSTICK_MAGIC(joystick, SDL_POWERSTATE_ERROR); + + result = joystick->battery_state; + + if (percent) { + *percent = joystick->battery_percent; + } + } + SDL_UnlockJoysticks(); + + return result; +} + +void SDL_SendJoystickTouchpad(Uint64 timestamp, SDL_Joystick *joystick, int touchpad, int finger, bool down, float x, float y, float pressure) +{ + SDL_JoystickTouchpadInfo *touchpad_info; + SDL_JoystickTouchpadFingerInfo *finger_info; + Uint32 event_type; + + SDL_AssertJoysticksLocked(); + + if (touchpad < 0 || touchpad >= joystick->ntouchpads) { + return; + } + + touchpad_info = &joystick->touchpads[touchpad]; + if (finger < 0 || finger >= touchpad_info->nfingers) { + return; + } + + finger_info = &touchpad_info->fingers[finger]; + + if (!down) { + if (x == 0.0f && y == 0.0f) { + x = finger_info->x; + y = finger_info->y; + } + pressure = 0.0f; + } + + if (x < 0.0f) { + x = 0.0f; + } else if (x > 1.0f) { + x = 1.0f; + } + if (y < 0.0f) { + y = 0.0f; + } else if (y > 1.0f) { + y = 1.0f; + } + if (pressure < 0.0f) { + pressure = 0.0f; + } else if (pressure > 1.0f) { + pressure = 1.0f; + } + + if (down == finger_info->down) { + if (!down || + (x == finger_info->x && y == finger_info->y && pressure == finger_info->pressure)) { + return; + } + } + + if (down == finger_info->down) { + event_type = SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION; + } else if (down) { + event_type = SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN; + } else { + event_type = SDL_EVENT_GAMEPAD_TOUCHPAD_UP; + } + + // We ignore events if we don't have keyboard focus, except for touch release + if (SDL_PrivateJoystickShouldIgnoreEvent()) { + if (event_type != SDL_EVENT_GAMEPAD_TOUCHPAD_UP) { + return; + } + } + + // Update internal joystick state + SDL_assert(timestamp != 0); + finger_info->down = down; + finger_info->x = x; + finger_info->y = y; + finger_info->pressure = pressure; + joystick->update_complete = timestamp; + + // Post the event, if desired + if (SDL_EventEnabled(event_type)) { + SDL_Event event; + event.type = event_type; + event.common.timestamp = timestamp; + event.gtouchpad.which = joystick->instance_id; + event.gtouchpad.touchpad = touchpad; + event.gtouchpad.finger = finger; + event.gtouchpad.x = x; + event.gtouchpad.y = y; + event.gtouchpad.pressure = pressure; + SDL_PushEvent(&event); + } +} + +void SDL_SendJoystickSensor(Uint64 timestamp, SDL_Joystick *joystick, SDL_SensorType type, Uint64 sensor_timestamp, const float *data, int num_values) +{ + SDL_AssertJoysticksLocked(); + + // We ignore events if we don't have keyboard focus + if (SDL_PrivateJoystickShouldIgnoreEvent()) { + return; + } + + for (int i = 0; i < joystick->nsensors; ++i) { + SDL_JoystickSensorInfo *sensor = &joystick->sensors[i]; + + if (sensor->type == type) { + if (sensor->enabled) { + num_values = SDL_min(num_values, SDL_arraysize(sensor->data)); + + // Update internal sensor state + SDL_memcpy(sensor->data, data, num_values * sizeof(*data)); + joystick->update_complete = timestamp; + + // Post the event, if desired + if (SDL_EventEnabled(SDL_EVENT_GAMEPAD_SENSOR_UPDATE)) { + SDL_Event event; + event.type = SDL_EVENT_GAMEPAD_SENSOR_UPDATE; + event.common.timestamp = timestamp; + event.gsensor.which = joystick->instance_id; + event.gsensor.sensor = type; + num_values = SDL_min(num_values, + SDL_arraysize(event.gsensor.data)); + SDL_memset(event.gsensor.data, 0, + sizeof(event.gsensor.data)); + SDL_memcpy(event.gsensor.data, data, + num_values * sizeof(*data)); + event.gsensor.sensor_timestamp = sensor_timestamp; + SDL_PushEvent(&event); + } + } + break; + } + } +} + +static void SDL_LoadVIDPIDListFromHint(const char *hint, int *num_entries, int *max_entries, Uint32 **entries) +{ + Uint32 entry; + char *spot; + char *file = NULL; + + if (hint && *hint == '@') { + spot = file = (char *)SDL_LoadFile(hint + 1, NULL); + } else { + spot = (char *)hint; + } + + if (!spot) { + return; + } + + while ((spot = SDL_strstr(spot, "0x")) != NULL) { + entry = (Uint16)SDL_strtol(spot, &spot, 0); + entry <<= 16; + spot = SDL_strstr(spot, "0x"); + if (!spot) { + break; + } + entry |= (Uint16)SDL_strtol(spot, &spot, 0); + + if (*num_entries == *max_entries) { + int new_max_entries = *max_entries + 16; + Uint32 *new_entries = (Uint32 *)SDL_realloc(*entries, new_max_entries * sizeof(**entries)); + if (!new_entries) { + // Out of memory, go with what we have already + break; + } + *entries = new_entries; + *max_entries = new_max_entries; + } + (*entries)[(*num_entries)++] = entry; + } + + if (file) { + SDL_free(file); + } +} + +void SDL_LoadVIDPIDListFromHints(SDL_vidpid_list *list, const char *included_list, const char *excluded_list) +{ + // Empty the list + list->num_included_entries = 0; + list->num_excluded_entries = 0; + + // Add the initial entries + if (list->num_initial_entries > 0) { + if (list->num_included_entries < list->num_initial_entries) { + Uint32 *entries = (Uint32 *)SDL_malloc(list->num_initial_entries * sizeof(*entries)); + if (entries) { + SDL_memcpy(entries, list->initial_entries, list->num_initial_entries * sizeof(*entries)); + list->included_entries = entries; + list->num_included_entries = list->num_initial_entries; + list->max_included_entries = list->num_initial_entries; + } + } + } + + // Add the included entries from the hint + SDL_LoadVIDPIDListFromHint(included_list, &list->num_included_entries, &list->max_included_entries, &list->included_entries); + + // Add the excluded entries from the hint + SDL_LoadVIDPIDListFromHint(excluded_list, &list->num_excluded_entries, &list->max_excluded_entries, &list->excluded_entries); +} + +static void SDLCALL SDL_VIDPIDIncludedHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_vidpid_list *list = (SDL_vidpid_list *)userdata; + const char *included_list = hint; + const char *excluded_list = NULL; + + if (!list->initialized) { + return; + } + + if (list->excluded_hint_name) { + excluded_list = SDL_GetHint(list->excluded_hint_name); + } + SDL_LoadVIDPIDListFromHints(list, included_list, excluded_list); +} + +static void SDLCALL SDL_VIDPIDExcludedHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_vidpid_list *list = (SDL_vidpid_list *)userdata; + const char *included_list = NULL; + const char *excluded_list = hint; + + if (!list->initialized) { + return; + } + + if (list->included_hint_name) { + included_list = SDL_GetHint(list->included_hint_name); + } + SDL_LoadVIDPIDListFromHints(list, included_list, excluded_list); +} + +void SDL_LoadVIDPIDList(SDL_vidpid_list *list) +{ + const char *included_list = NULL; + const char *excluded_list = NULL; + + if (list->included_hint_name) { + SDL_AddHintCallback(list->included_hint_name, SDL_VIDPIDIncludedHintChanged, list); + } + + if (list->excluded_hint_name) { + SDL_AddHintCallback(list->excluded_hint_name, SDL_VIDPIDExcludedHintChanged, list); + } + + list->initialized = true; + + if (list->included_hint_name) { + included_list = SDL_GetHint(list->included_hint_name); + } + if (list->excluded_hint_name) { + excluded_list = SDL_GetHint(list->excluded_hint_name); + } + SDL_LoadVIDPIDListFromHints(list, included_list, excluded_list); +} + +bool SDL_VIDPIDInList(Uint16 vendor_id, Uint16 product_id, const SDL_vidpid_list *list) +{ + int i; + Uint32 vidpid = MAKE_VIDPID(vendor_id, product_id); + + for (i = 0; i < list->num_excluded_entries; ++i) { + if (vidpid == list->excluded_entries[i]) { + return false; + } + } + for (i = 0; i < list->num_included_entries; ++i) { + if (vidpid == list->included_entries[i]) { + return true; + } + } + return false; +} + +void SDL_FreeVIDPIDList(SDL_vidpid_list *list) +{ + if (list->included_hint_name) { + SDL_RemoveHintCallback(list->included_hint_name, SDL_VIDPIDIncludedHintChanged, list); + } + + if (list->excluded_hint_name) { + SDL_RemoveHintCallback(list->excluded_hint_name, SDL_VIDPIDExcludedHintChanged, list); + } + + if (list->included_entries) { + SDL_free(list->included_entries); + list->included_entries = NULL; + list->num_included_entries = 0; + list->max_included_entries = 0; + } + + if (list->excluded_entries) { + SDL_free(list->excluded_entries); + list->excluded_entries = NULL; + list->num_excluded_entries = 0; + list->max_excluded_entries = 0; + } + + list->initialized = false; +} diff --git a/thirdparty/sdl/joystick/SDL_joystick_c.h b/thirdparty/sdl/joystick/SDL_joystick_c.h new file mode 100644 index 00000000000..d931cf7ed73 --- /dev/null +++ b/thirdparty/sdl/joystick/SDL_joystick_c.h @@ -0,0 +1,270 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_joystick_c_h_ +#define SDL_joystick_c_h_ + +#include "SDL_internal.h" + +// Useful functions and variables from SDL_joystick.c + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +struct SDL_JoystickDriver; +struct SDL_SteamVirtualGamepadInfo; + +// Initialization and shutdown functions +extern bool SDL_InitJoysticks(void); +extern void SDL_QuitJoysticks(void); + +// Return whether the joystick system is currently initialized +extern bool SDL_JoysticksInitialized(void); + +// Return whether the joystick system is shutting down +extern bool SDL_JoysticksQuitting(void); + +// Return whether the joysticks are currently locked +extern bool SDL_JoysticksLocked(void); + +// Make sure we currently have the joysticks locked +extern void SDL_AssertJoysticksLocked(void) SDL_ASSERT_CAPABILITY(SDL_joystick_lock); + +// Function to return whether there are any joysticks opened by the application +extern bool SDL_JoysticksOpened(void); + +// Function to determine whether a device is currently detected by this driver +extern bool SDL_JoystickHandledByAnotherDriver(struct SDL_JoystickDriver *driver, Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name); + +/* Function to standardize the name for a controller + This should be freed with SDL_free() when no longer needed + */ +extern char *SDL_CreateJoystickName(Uint16 vendor, Uint16 product, const char *vendor_name, const char *product_name); + +// Function to create a GUID for a joystick based on the VID/PID and name +extern SDL_GUID SDL_CreateJoystickGUID(Uint16 bus, Uint16 vendor, Uint16 product, Uint16 version, const char *vendor_name, const char *product_name, Uint8 driver_signature, Uint8 driver_data); + +// Function to create a GUID for a joystick based on the name, with no VID/PID information +extern SDL_GUID SDL_CreateJoystickGUIDForName(const char *name); + +// Function to set the vendor field of a joystick GUID +extern void SDL_SetJoystickGUIDVendor(SDL_GUID *guid, Uint16 vendor); + +// Function to set the product field of a joystick GUID +extern void SDL_SetJoystickGUIDProduct(SDL_GUID *guid, Uint16 product); + +// Function to set the version field of a joystick GUID +extern void SDL_SetJoystickGUIDVersion(SDL_GUID *guid, Uint16 version); + +// Function to set the CRC field of a joystick GUID +extern void SDL_SetJoystickGUIDCRC(SDL_GUID *guid, Uint16 crc); + +// Function to return the type of a controller +extern SDL_GamepadType SDL_GetGamepadTypeFromVIDPID(Uint16 vendor, Uint16 product, const char *name, bool forUI); +extern SDL_GamepadType SDL_GetGamepadTypeFromGUID(SDL_GUID guid, const char *name); + +// Function to return whether a joystick GUID uses the version field +extern bool SDL_JoystickGUIDUsesVersion(SDL_GUID guid); + +// Function to return whether a joystick is an Xbox One controller +extern bool SDL_IsJoystickXboxOne(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is an Xbox One Elite controller +extern bool SDL_IsJoystickXboxOneElite(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is an Xbox Series X controller +extern bool SDL_IsJoystickXboxSeriesX(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is an Xbox One controller connected via Bluetooth +extern bool SDL_IsJoystickBluetoothXboxOne(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is a PS4 controller +extern bool SDL_IsJoystickPS4(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is a PS5 controller +extern bool SDL_IsJoystickPS5(Uint16 vendor_id, Uint16 product_id); +extern bool SDL_IsJoystickDualSenseEdge(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is a Nintendo Switch Pro controller +extern bool SDL_IsJoystickNintendoSwitchPro(Uint16 vendor_id, Uint16 product_id); +extern bool SDL_IsJoystickNintendoSwitchProInputOnly(Uint16 vendor_id, Uint16 product_id); +extern bool SDL_IsJoystickNintendoSwitchJoyCon(Uint16 vendor_id, Uint16 product_id); +extern bool SDL_IsJoystickNintendoSwitchJoyConLeft(Uint16 vendor_id, Uint16 product_id); +extern bool SDL_IsJoystickNintendoSwitchJoyConRight(Uint16 vendor_id, Uint16 product_id); +extern bool SDL_IsJoystickNintendoSwitchJoyConGrip(Uint16 vendor_id, Uint16 product_id); +extern bool SDL_IsJoystickNintendoSwitchJoyConPair(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is a Nintendo GameCube style controller +extern bool SDL_IsJoystickGameCube(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is an Amazon Luna controller +extern bool SDL_IsJoystickAmazonLunaController(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is a Google Stadia controller +extern bool SDL_IsJoystickGoogleStadiaController(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is an NVIDIA SHIELD controller +extern bool SDL_IsJoystickNVIDIASHIELDController(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is a Steam Virtual Gamepad +extern bool SDL_IsJoystickSteamVirtualGamepad(Uint16 vendor_id, Uint16 product_id, Uint16 version); + +// Function to return whether a joystick is a Steam Controller +extern bool SDL_IsJoystickSteamController(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is a HORI Steam controller +extern bool SDL_IsJoystickHoriSteamController(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick is a Steam Deck +extern bool SDL_IsJoystickSteamDeck(Uint16 vendor_id, Uint16 product_id); + +// Function to return whether a joystick guid comes from the XInput driver +extern bool SDL_IsJoystickXInput(SDL_GUID guid); + +// Function to return whether a joystick guid comes from the WGI driver +extern bool SDL_IsJoystickWGI(SDL_GUID guid); + +// Function to return whether a joystick guid comes from the HIDAPI driver +extern bool SDL_IsJoystickHIDAPI(SDL_GUID guid); + +// Function to return whether a joystick guid comes from the MFI driver +extern bool SDL_IsJoystickMFI(SDL_GUID guid); + +// Function to return whether a joystick guid comes from the RAWINPUT driver +extern bool SDL_IsJoystickRAWINPUT(SDL_GUID guid); + +// Function to return whether a joystick guid comes from the Virtual driver +extern bool SDL_IsJoystickVIRTUAL(SDL_GUID guid); + +// Function to return whether a joystick should be ignored +extern bool SDL_ShouldIgnoreJoystick(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name); + +// Internal event queueing functions +extern void SDL_PrivateJoystickAddTouchpad(SDL_Joystick *joystick, int nfingers); +extern void SDL_PrivateJoystickAddSensor(SDL_Joystick *joystick, SDL_SensorType type, float rate); +extern void SDL_PrivateJoystickSensorRate(SDL_Joystick *joystick, SDL_SensorType type, float rate); +extern void SDL_PrivateJoystickAdded(SDL_JoystickID instance_id); +extern bool SDL_IsJoystickBeingAdded(void); +extern void SDL_PrivateJoystickRemoved(SDL_JoystickID instance_id); +extern void SDL_PrivateJoystickForceRecentering(SDL_Joystick *joystick); +extern void SDL_SendJoystickAxis(Uint64 timestamp, SDL_Joystick *joystick, Uint8 axis, Sint16 value); +extern void SDL_SendJoystickBall(Uint64 timestamp, SDL_Joystick *joystick, Uint8 ball, Sint16 xrel, Sint16 yrel); +extern void SDL_SendJoystickHat(Uint64 timestamp, SDL_Joystick *joystick, Uint8 hat, Uint8 value); +extern void SDL_SendJoystickButton(Uint64 timestamp, SDL_Joystick *joystick, Uint8 button, bool down); +extern void SDL_SendJoystickTouchpad(Uint64 timestamp, SDL_Joystick *joystick, int touchpad, int finger, bool down, float x, float y, float pressure); +extern void SDL_SendJoystickSensor(Uint64 timestamp, SDL_Joystick *joystick, SDL_SensorType type, Uint64 sensor_timestamp, const float *data, int num_values); +extern void SDL_SendJoystickPowerInfo(SDL_Joystick *joystick, SDL_PowerState state, int percent); + +// Function to get the Steam virtual gamepad info for a joystick +extern const struct SDL_SteamVirtualGamepadInfo *SDL_GetJoystickVirtualGamepadInfoForID(SDL_JoystickID instance_id); + +// Internal sanity checking functions +extern bool SDL_IsJoystickValid(SDL_Joystick *joystick); + +typedef enum +{ + EMappingKind_None, + EMappingKind_Button, + EMappingKind_Axis, + EMappingKind_Hat, +} EMappingKind; + +typedef struct SDL_InputMapping +{ + EMappingKind kind; + Uint8 target; + bool axis_reversed; + bool half_axis_positive; + bool half_axis_negative; +} SDL_InputMapping; + +typedef struct SDL_GamepadMapping +{ + SDL_InputMapping a; + SDL_InputMapping b; + SDL_InputMapping x; + SDL_InputMapping y; + SDL_InputMapping back; + SDL_InputMapping guide; + SDL_InputMapping start; + SDL_InputMapping leftstick; + SDL_InputMapping rightstick; + SDL_InputMapping leftshoulder; + SDL_InputMapping rightshoulder; + SDL_InputMapping dpup; + SDL_InputMapping dpdown; + SDL_InputMapping dpleft; + SDL_InputMapping dpright; + SDL_InputMapping misc1; + SDL_InputMapping misc2; + SDL_InputMapping misc3; + SDL_InputMapping misc4; + SDL_InputMapping misc5; + SDL_InputMapping misc6; + SDL_InputMapping right_paddle1; + SDL_InputMapping left_paddle1; + SDL_InputMapping right_paddle2; + SDL_InputMapping left_paddle2; + SDL_InputMapping leftx; + SDL_InputMapping lefty; + SDL_InputMapping rightx; + SDL_InputMapping righty; + SDL_InputMapping lefttrigger; + SDL_InputMapping righttrigger; + SDL_InputMapping touchpad; +} SDL_GamepadMapping; + +// Function to get autodetected gamepad controller mapping from the driver +extern bool SDL_PrivateJoystickGetAutoGamepadMapping(SDL_JoystickID instance_id, + SDL_GamepadMapping *out); + + +typedef struct +{ + const char *included_hint_name; + int num_included_entries; + int max_included_entries; + Uint32 *included_entries; + + const char *excluded_hint_name; + int num_excluded_entries; + int max_excluded_entries; + Uint32 *excluded_entries; + + int num_initial_entries; + Uint32 *initial_entries; + + bool initialized; +} SDL_vidpid_list; + +extern void SDL_LoadVIDPIDList(SDL_vidpid_list *list); +extern void SDL_LoadVIDPIDListFromHints(SDL_vidpid_list *list, const char *included_list, const char *excluded_list); +extern bool SDL_VIDPIDInList(Uint16 vendor_id, Uint16 product_id, const SDL_vidpid_list *list); +extern void SDL_FreeVIDPIDList(SDL_vidpid_list *list); + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif + +#endif // SDL_joystick_c_h_ diff --git a/thirdparty/sdl/joystick/SDL_steam_virtual_gamepad.c b/thirdparty/sdl/joystick/SDL_steam_virtual_gamepad.c new file mode 100644 index 00000000000..6b253de3a04 --- /dev/null +++ b/thirdparty/sdl/joystick/SDL_steam_virtual_gamepad.c @@ -0,0 +1,254 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_joystick_c.h" +#include "SDL_steam_virtual_gamepad.h" + +#ifdef SDL_PLATFORM_WIN32 +#include "../core/windows/SDL_windows.h" +#else +#include +#include +#endif + +#define SDL_HINT_STEAM_VIRTUAL_GAMEPAD_INFO_FILE "SteamVirtualGamepadInfo" + +static char *SDL_steam_virtual_gamepad_info_file SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static Uint64 SDL_steam_virtual_gamepad_info_file_mtime SDL_GUARDED_BY(SDL_joystick_lock) = 0; +static Uint64 SDL_steam_virtual_gamepad_info_check_time SDL_GUARDED_BY(SDL_joystick_lock) = 0; +static SDL_SteamVirtualGamepadInfo **SDL_steam_virtual_gamepad_info SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static int SDL_steam_virtual_gamepad_info_count SDL_GUARDED_BY(SDL_joystick_lock) = 0; + + +static Uint64 GetFileModificationTime(const char *file) +{ + Uint64 modification_time = 0; + +#ifdef SDL_PLATFORM_WIN32 + WCHAR *wFile = WIN_UTF8ToStringW(file); + if (wFile) { + HANDLE hFile = CreateFileW(wFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + if (hFile != INVALID_HANDLE_VALUE) { + FILETIME last_write_time; + if (GetFileTime(hFile, NULL, NULL, &last_write_time)) { + modification_time = last_write_time.dwHighDateTime; + modification_time <<= 32; + modification_time |= last_write_time.dwLowDateTime; + } + CloseHandle(hFile); + } + SDL_free(wFile); + } +#else + struct stat sb; + + if (stat(file, &sb) == 0) { + modification_time = (Uint64)sb.st_mtime; + } +#endif + return modification_time; +} + +static void SDL_FreeSteamVirtualGamepadInfo(void) +{ + int i; + + SDL_AssertJoysticksLocked(); + + for (i = 0; i < SDL_steam_virtual_gamepad_info_count; ++i) { + SDL_SteamVirtualGamepadInfo *entry = SDL_steam_virtual_gamepad_info[i]; + if (entry) { + SDL_free(entry->name); + SDL_free(entry); + } + } + SDL_free(SDL_steam_virtual_gamepad_info); + SDL_steam_virtual_gamepad_info = NULL; + SDL_steam_virtual_gamepad_info_count = 0; +} + +static void AddVirtualGamepadInfo(int slot, SDL_SteamVirtualGamepadInfo *info) +{ + SDL_SteamVirtualGamepadInfo *new_info; + + SDL_AssertJoysticksLocked(); + + if (slot < 0) { + return; + } + + if (slot >= SDL_steam_virtual_gamepad_info_count) { + SDL_SteamVirtualGamepadInfo **slots = (SDL_SteamVirtualGamepadInfo **)SDL_realloc(SDL_steam_virtual_gamepad_info, (slot + 1)*sizeof(*SDL_steam_virtual_gamepad_info)); + if (!slots) { + return; + } + while (SDL_steam_virtual_gamepad_info_count <= slot) { + slots[SDL_steam_virtual_gamepad_info_count++] = NULL; + } + SDL_steam_virtual_gamepad_info = slots; + } + + if (SDL_steam_virtual_gamepad_info[slot]) { + // We already have this slot info + return; + } + + new_info = (SDL_SteamVirtualGamepadInfo *)SDL_malloc(sizeof(*new_info)); + if (!new_info) { + return; + } + SDL_copyp(new_info, info); + SDL_steam_virtual_gamepad_info[slot] = new_info; + SDL_zerop(info); +} + +void SDL_InitSteamVirtualGamepadInfo(void) +{ + const char *file; + + SDL_AssertJoysticksLocked(); + + // The file isn't available inside the macOS sandbox + if (SDL_GetSandbox() == SDL_SANDBOX_MACOS) { + return; + } + + file = SDL_GetHint(SDL_HINT_STEAM_VIRTUAL_GAMEPAD_INFO_FILE); + if (file && *file) { + SDL_steam_virtual_gamepad_info_file = SDL_strdup(file); + } + SDL_UpdateSteamVirtualGamepadInfo(); +} + +bool SDL_SteamVirtualGamepadEnabled(void) +{ + SDL_AssertJoysticksLocked(); + + return (SDL_steam_virtual_gamepad_info != NULL); +} + +bool SDL_UpdateSteamVirtualGamepadInfo(void) +{ + const int UPDATE_CHECK_INTERVAL_MS = 3000; + Uint64 now; + Uint64 mtime; + char *data, *end, *next, *line, *value; + size_t size; + int slot, new_slot; + SDL_SteamVirtualGamepadInfo info; + + SDL_AssertJoysticksLocked(); + + if (!SDL_steam_virtual_gamepad_info_file) { + return false; + } + + now = SDL_GetTicks(); + if (SDL_steam_virtual_gamepad_info_check_time && + now < (SDL_steam_virtual_gamepad_info_check_time + UPDATE_CHECK_INTERVAL_MS)) { + return false; + } + SDL_steam_virtual_gamepad_info_check_time = now; + + mtime = GetFileModificationTime(SDL_steam_virtual_gamepad_info_file); + if (mtime == 0 || mtime == SDL_steam_virtual_gamepad_info_file_mtime) { + return false; + } + + data = (char *)SDL_LoadFile(SDL_steam_virtual_gamepad_info_file, &size); + if (!data) { + return false; + } + + SDL_FreeSteamVirtualGamepadInfo(); + + slot = -1; + SDL_zero(info); + + for (next = data, end = data + size; next < end; ) { + while (next < end && (*next == '\0' || *next == '\r' || *next == '\n')) { + ++next; + } + + line = next; + + while (next < end && (*next != '\r' && *next != '\n')) { + ++next; + } + *next = '\0'; + + if (SDL_sscanf(line, "[slot %d]", &new_slot) == 1) { + if (slot >= 0) { + AddVirtualGamepadInfo(slot, &info); + } + slot = new_slot; + } else { + value = SDL_strchr(line, '='); + if (value) { + *value++ = '\0'; + + if (SDL_strcmp(line, "name") == 0) { + SDL_free(info.name); + info.name = SDL_strdup(value); + } else if (SDL_strcmp(line, "VID") == 0) { + info.vendor_id = (Uint16)SDL_strtoul(value, NULL, 0); + } else if (SDL_strcmp(line, "PID") == 0) { + info.product_id = (Uint16)SDL_strtoul(value, NULL, 0); + } else if (SDL_strcmp(line, "type") == 0) { + info.type = SDL_GetGamepadTypeFromString(value); + } else if (SDL_strcmp(line, "handle") == 0) { + info.handle = (Uint64)SDL_strtoull(value, NULL, 0); + } + } + } + } + if (slot >= 0) { + AddVirtualGamepadInfo(slot, &info); + } + SDL_free(info.name); + SDL_free(data); + + SDL_steam_virtual_gamepad_info_file_mtime = mtime; + + return true; +} + +const SDL_SteamVirtualGamepadInfo *SDL_GetSteamVirtualGamepadInfo(int slot) +{ + SDL_AssertJoysticksLocked(); + + if (slot < 0 || slot >= SDL_steam_virtual_gamepad_info_count) { + return NULL; + } + return SDL_steam_virtual_gamepad_info[slot]; +} + +void SDL_QuitSteamVirtualGamepadInfo(void) +{ + SDL_AssertJoysticksLocked(); + + if (SDL_steam_virtual_gamepad_info_file) { + SDL_FreeSteamVirtualGamepadInfo(); + SDL_free(SDL_steam_virtual_gamepad_info_file); + SDL_steam_virtual_gamepad_info_file = NULL; + } +} diff --git a/thirdparty/sdl/joystick/SDL_steam_virtual_gamepad.h b/thirdparty/sdl/joystick/SDL_steam_virtual_gamepad.h new file mode 100644 index 00000000000..65696ea2876 --- /dev/null +++ b/thirdparty/sdl/joystick/SDL_steam_virtual_gamepad.h @@ -0,0 +1,36 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +typedef struct SDL_SteamVirtualGamepadInfo +{ + Uint64 handle; + char *name; + Uint16 vendor_id; + Uint16 product_id; + SDL_GamepadType type; +} SDL_SteamVirtualGamepadInfo; + +void SDL_InitSteamVirtualGamepadInfo(void); +bool SDL_SteamVirtualGamepadEnabled(void); +bool SDL_UpdateSteamVirtualGamepadInfo(void); +const SDL_SteamVirtualGamepadInfo *SDL_GetSteamVirtualGamepadInfo(int slot); +void SDL_QuitSteamVirtualGamepadInfo(void); diff --git a/thirdparty/sdl/joystick/SDL_sysjoystick.h b/thirdparty/sdl/joystick/SDL_sysjoystick.h new file mode 100644 index 00000000000..041ebc3b509 --- /dev/null +++ b/thirdparty/sdl/joystick/SDL_sysjoystick.h @@ -0,0 +1,272 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_sysjoystick_h_ +#define SDL_sysjoystick_h_ + +// This is the system specific header for the SDL joystick API +#include "SDL_joystick_c.h" + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +// The SDL joystick structure + +typedef struct SDL_JoystickAxisInfo +{ + Sint16 initial_value; // Initial axis state + Sint16 value; // Current axis state + Sint16 zero; // Zero point on the axis (-32768 for triggers) + bool has_initial_value; // Whether we've seen a value on the axis yet + bool has_second_value; // Whether we've seen a second value on the axis yet + bool sent_initial_value; // Whether we've sent the initial axis value + bool sending_initial_value; // Whether we are sending the initial axis value +} SDL_JoystickAxisInfo; + +typedef struct SDL_JoystickBallData +{ + int dx; + int dy; +} SDL_JoystickBallData; + +typedef struct SDL_JoystickTouchpadFingerInfo +{ + bool down; + float x; + float y; + float pressure; +} SDL_JoystickTouchpadFingerInfo; + +typedef struct SDL_JoystickTouchpadInfo +{ + int nfingers; + SDL_JoystickTouchpadFingerInfo *fingers; +} SDL_JoystickTouchpadInfo; + +typedef struct SDL_JoystickSensorInfo +{ + SDL_SensorType type; + bool enabled; + float rate; + float data[3]; // If this needs to expand, update SDL_GamepadSensorEvent +} SDL_JoystickSensorInfo; + +#define _guarded SDL_GUARDED_BY(SDL_joystick_lock) + +struct SDL_Joystick +{ + SDL_JoystickID instance_id _guarded; // Device instance, monotonically increasing from 0 + char *name _guarded; // Joystick name - system dependent + char *path _guarded; // Joystick path - system dependent + char *serial _guarded; // Joystick serial + SDL_GUID guid _guarded; // Joystick guid + Uint16 firmware_version _guarded; // Firmware version, if available + Uint64 steam_handle _guarded; // Steam controller API handle + bool swap_face_buttons _guarded; // Whether we should swap face buttons + bool is_virtual _guarded; // Whether this is a virtual joystick + + int naxes _guarded; // Number of axis controls on the joystick + SDL_JoystickAxisInfo *axes _guarded; + + int nballs _guarded; // Number of trackballs on the joystick + SDL_JoystickBallData *balls _guarded; // Current ball motion deltas + + int nhats _guarded; // Number of hats on the joystick + Uint8 *hats _guarded; // Current hat states + + int nbuttons _guarded; // Number of buttons on the joystick + bool *buttons _guarded; // Current button states + + int ntouchpads _guarded; // Number of touchpads on the joystick + SDL_JoystickTouchpadInfo *touchpads _guarded; // Current touchpad states + + int nsensors _guarded; // Number of sensors on the joystick + int nsensors_enabled _guarded; + SDL_JoystickSensorInfo *sensors _guarded; + + Uint16 low_frequency_rumble _guarded; + Uint16 high_frequency_rumble _guarded; + Uint64 rumble_expiration _guarded; + Uint64 rumble_resend _guarded; + + Uint16 left_trigger_rumble _guarded; + Uint16 right_trigger_rumble _guarded; + Uint64 trigger_rumble_expiration _guarded; + Uint64 trigger_rumble_resend _guarded; + + Uint8 led_red _guarded; + Uint8 led_green _guarded; + Uint8 led_blue _guarded; + Uint64 led_expiration _guarded; + + bool attached _guarded; + SDL_JoystickConnectionState connection_state _guarded; + SDL_PowerState battery_state _guarded; + int battery_percent _guarded; + + bool delayed_guide_button _guarded; // true if this device has the guide button event delayed + + SDL_SensorID accel_sensor _guarded; + SDL_Sensor *accel _guarded; + SDL_SensorID gyro_sensor _guarded; + SDL_Sensor *gyro _guarded; + float sensor_transform[3][3] _guarded; + + Uint64 update_complete _guarded; + + struct SDL_JoystickDriver *driver _guarded; + + struct joystick_hwdata *hwdata _guarded; // Driver dependent information + + SDL_PropertiesID props _guarded; + + int ref_count _guarded; // Reference count for multiple opens + + struct SDL_Joystick *next _guarded; // pointer to next joystick we have allocated +}; + +#undef _guarded + +// Device bus definitions +#define SDL_HARDWARE_BUS_UNKNOWN 0x00 +#define SDL_HARDWARE_BUS_USB 0x03 +#define SDL_HARDWARE_BUS_BLUETOOTH 0x05 +#define SDL_HARDWARE_BUS_VIRTUAL 0xFF + +// Macro to combine a USB vendor ID and product ID into a single Uint32 value +#define MAKE_VIDPID(VID, PID) (((Uint32)(VID)) << 16 | (PID)) + +typedef struct SDL_JoystickDriver +{ + /* Function to scan the system for joysticks. + * Joystick 0 should be the system default joystick. + * This function should return 0, or -1 on an unrecoverable error. + */ + bool (*Init)(void); + + // Function to return the number of joystick devices plugged in right now + int (*GetCount)(void); + + // Function to cause any queued joystick insertions to be processed + void (*Detect)(void); + + // Function to determine whether a device is currently detected by this driver + bool (*IsDevicePresent)(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name); + + // Function to get the device-dependent name of a joystick + const char *(*GetDeviceName)(int device_index); + + // Function to get the device-dependent path of a joystick + const char *(*GetDevicePath)(int device_index); + + // Function to get the Steam virtual gamepad slot of a joystick + int (*GetDeviceSteamVirtualGamepadSlot)(int device_index); + + // Function to get the player index of a joystick + int (*GetDevicePlayerIndex)(int device_index); + + // Function to set the player index of a joystick + void (*SetDevicePlayerIndex)(int device_index, int player_index); + + // Function to return the stable GUID for a plugged in device + SDL_GUID (*GetDeviceGUID)(int device_index); + + // Function to get the current instance id of the joystick located at device_index + SDL_JoystickID (*GetDeviceInstanceID)(int device_index); + + /* Function to open a joystick for use. + The joystick to open is specified by the device index. + This should fill the nbuttons and naxes fields of the joystick structure. + It returns 0, or -1 if there is an error. + */ + bool (*Open)(SDL_Joystick *joystick, int device_index); + + // Rumble functionality + bool (*Rumble)(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble); + bool (*RumbleTriggers)(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble); + + // LED functionality + bool (*SetLED)(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue); + + // General effects + bool (*SendEffect)(SDL_Joystick *joystick, const void *data, int size); + + // Sensor functionality + bool (*SetSensorsEnabled)(SDL_Joystick *joystick, bool enabled); + + /* Function to update the state of a joystick - called as a device poll. + * This function shouldn't update the joystick structure directly, + * but instead should call SDL_PrivateJoystick*() to deliver events + * and update joystick device state. + */ + void (*Update)(SDL_Joystick *joystick); + + // Function to close a joystick after use + void (*Close)(SDL_Joystick *joystick); + + // Function to perform any system-specific joystick related cleanup + void (*Quit)(void); + + // Function to get the autodetected controller mapping; returns false if there isn't any. + bool (*GetGamepadMapping)(int device_index, SDL_GamepadMapping *out); + +} SDL_JoystickDriver; + +// Windows and Mac OSX has a limit of MAX_DWORD / 1000, Linux kernel has a limit of 0xFFFF +#define SDL_MAX_RUMBLE_DURATION_MS 0xFFFF + +/* Dualshock4 only rumbles for about 5 seconds max, resend rumble command every 2 seconds + * to make long rumble work. */ +#define SDL_RUMBLE_RESEND_MS 2000 + +#define SDL_LED_MIN_REPEAT_MS 5000 + +// The available joystick drivers +extern SDL_JoystickDriver SDL_PRIVATE_JoystickDriver; +extern SDL_JoystickDriver SDL_ANDROID_JoystickDriver; +extern SDL_JoystickDriver SDL_BSD_JoystickDriver; +extern SDL_JoystickDriver SDL_DARWIN_JoystickDriver; +extern SDL_JoystickDriver SDL_DUMMY_JoystickDriver; +extern SDL_JoystickDriver SDL_EMSCRIPTEN_JoystickDriver; +extern SDL_JoystickDriver SDL_HAIKU_JoystickDriver; +extern SDL_JoystickDriver SDL_HIDAPI_JoystickDriver; +extern SDL_JoystickDriver SDL_RAWINPUT_JoystickDriver; +extern SDL_JoystickDriver SDL_IOS_JoystickDriver; +extern SDL_JoystickDriver SDL_LINUX_JoystickDriver; +extern SDL_JoystickDriver SDL_VIRTUAL_JoystickDriver; +extern SDL_JoystickDriver SDL_WGI_JoystickDriver; +extern SDL_JoystickDriver SDL_WINDOWS_JoystickDriver; +extern SDL_JoystickDriver SDL_WINMM_JoystickDriver; +extern SDL_JoystickDriver SDL_PS2_JoystickDriver; +extern SDL_JoystickDriver SDL_PSP_JoystickDriver; +extern SDL_JoystickDriver SDL_VITA_JoystickDriver; +extern SDL_JoystickDriver SDL_N3DS_JoystickDriver; +extern SDL_JoystickDriver SDL_GAMEINPUT_JoystickDriver; + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif + +#endif // SDL_sysjoystick_h_ diff --git a/thirdparty/sdl/joystick/apple/SDL_mfijoystick.m b/thirdparty/sdl/joystick/apple/SDL_mfijoystick.m new file mode 100644 index 00000000000..811a9f1ae76 --- /dev/null +++ b/thirdparty/sdl/joystick/apple/SDL_mfijoystick.m @@ -0,0 +1,1946 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This is the iOS implementation of the SDL joystick API +#include "../SDL_sysjoystick.h" +#include "../SDL_joystick_c.h" +#include "../hidapi/SDL_hidapijoystick_c.h" +#include "../usb_ids.h" +#include "../../events/SDL_events_c.h" + +#include "SDL_mfijoystick_c.h" + + +#if defined(SDL_PLATFORM_IOS) && !defined(SDL_PLATFORM_TVOS) +#import +#endif + +#ifdef SDL_PLATFORM_MACOS +#include +#include +#ifndef NSAppKitVersionNumber10_15 +#define NSAppKitVersionNumber10_15 1894 +#endif +#endif // SDL_PLATFORM_MACOS + +#import + +#ifdef SDL_JOYSTICK_MFI +static id connectObserver = nil; +static id disconnectObserver = nil; + +#include + +// Fix build errors when using an older SDK by defining these selectors +@interface GCController (SDL) +#if !((__IPHONE_OS_VERSION_MAX_ALLOWED >= 140500) || (__APPLETV_OS_VERSION_MAX_ALLOWED >= 140500) || (__MAC_OS_X_VERSION_MAX_ALLOWED >= 110300)) +@property(class, nonatomic, readwrite) BOOL shouldMonitorBackgroundEvents; +#endif +@end + +#import + +#endif // SDL_JOYSTICK_MFI + +static SDL_JoystickDeviceItem *deviceList = NULL; + +static int numjoysticks = 0; +int SDL_AppleTVRemoteOpenedAsJoystick = 0; + +static SDL_JoystickDeviceItem *GetDeviceForIndex(int device_index) +{ + SDL_JoystickDeviceItem *device = deviceList; + int i = 0; + + while (i < device_index) { + if (device == NULL) { + return NULL; + } + device = device->next; + i++; + } + + return device; +} + +#ifdef SDL_JOYSTICK_MFI +static bool IsControllerPS4(GCController *controller) +{ + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if ([controller.productCategory isEqualToString:@"DualShock 4"]) { + return true; + } + } else { + if ([controller.vendorName containsString:@"DUALSHOCK"]) { + return true; + } + } + return false; +} +static bool IsControllerPS5(GCController *controller) +{ + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if ([controller.productCategory isEqualToString:@"DualSense"]) { + return true; + } + } else { + if ([controller.vendorName containsString:@"DualSense"]) { + return true; + } + } + return false; +} +static bool IsControllerXbox(GCController *controller) +{ + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if ([controller.productCategory isEqualToString:@"Xbox One"]) { + return true; + } + } else { + if ([controller.vendorName containsString:@"Xbox"]) { + return true; + } + } + return false; +} +static bool IsControllerSwitchPro(GCController *controller) +{ + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if ([controller.productCategory isEqualToString:@"Switch Pro Controller"]) { + return true; + } + } + return false; +} +static bool IsControllerSwitchJoyConL(GCController *controller) +{ + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if ([controller.productCategory isEqualToString:@"Nintendo Switch Joy-Con (L)"]) { + return true; + } + } + return false; +} +static bool IsControllerSwitchJoyConR(GCController *controller) +{ + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if ([controller.productCategory isEqualToString:@"Nintendo Switch Joy-Con (R)"]) { + return true; + } + } + return false; +} +static bool IsControllerSwitchJoyConPair(GCController *controller) +{ + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if ([controller.productCategory isEqualToString:@"Nintendo Switch Joy-Con (L/R)"]) { + return true; + } + } + return false; +} +static bool IsControllerStadia(GCController *controller) +{ + if ([controller.vendorName hasPrefix:@"Stadia"]) { + return true; + } + return false; +} +static bool IsControllerBackboneOne(GCController *controller) +{ + if ([controller.vendorName hasPrefix:@"Backbone One"]) { + return true; + } + return false; +} +static void CheckControllerSiriRemote(GCController *controller, int *is_siri_remote) +{ + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if ([controller.productCategory hasPrefix:@"Siri Remote"]) { + *is_siri_remote = 1; + SDL_sscanf(controller.productCategory.UTF8String, "Siri Remote (%i%*s Generation)", is_siri_remote); + return; + } + } + *is_siri_remote = 0; +} + +static bool ElementAlreadyHandled(SDL_JoystickDeviceItem *device, NSString *element, NSDictionary *elements) +{ + if ([element isEqualToString:@"Left Thumbstick Left"] || + [element isEqualToString:@"Left Thumbstick Right"]) { + if (elements[@"Left Thumbstick X Axis"]) { + return true; + } + } + if ([element isEqualToString:@"Left Thumbstick Up"] || + [element isEqualToString:@"Left Thumbstick Down"]) { + if (elements[@"Left Thumbstick Y Axis"]) { + return true; + } + } + if ([element isEqualToString:@"Right Thumbstick Left"] || + [element isEqualToString:@"Right Thumbstick Right"]) { + if (elements[@"Right Thumbstick X Axis"]) { + return true; + } + } + if ([element isEqualToString:@"Right Thumbstick Up"] || + [element isEqualToString:@"Right Thumbstick Down"]) { + if (elements[@"Right Thumbstick Y Axis"]) { + return true; + } + } + if (device->is_siri_remote) { + if ([element isEqualToString:@"Direction Pad Left"] || + [element isEqualToString:@"Direction Pad Right"]) { + if (elements[@"Direction Pad X Axis"]) { + return true; + } + } + if ([element isEqualToString:@"Direction Pad Up"] || + [element isEqualToString:@"Direction Pad Down"]) { + if (elements[@"Direction Pad Y Axis"]) { + return true; + } + } + } else { + if ([element isEqualToString:@"Direction Pad X Axis"]) { + if (elements[@"Direction Pad Left"] && + elements[@"Direction Pad Right"]) { + return true; + } + } + if ([element isEqualToString:@"Direction Pad Y Axis"]) { + if (elements[@"Direction Pad Up"] && + elements[@"Direction Pad Down"]) { + return true; + } + } + } + if ([element isEqualToString:@"Cardinal Direction Pad X Axis"]) { + if (elements[@"Cardinal Direction Pad Left"] && + elements[@"Cardinal Direction Pad Right"]) { + return true; + } + } + if ([element isEqualToString:@"Cardinal Direction Pad Y Axis"]) { + if (elements[@"Cardinal Direction Pad Up"] && + elements[@"Cardinal Direction Pad Down"]) { + return true; + } + } + if ([element isEqualToString:@"Touchpad 1 X Axis"] || + [element isEqualToString:@"Touchpad 1 Y Axis"] || + [element isEqualToString:@"Touchpad 1 Left"] || + [element isEqualToString:@"Touchpad 1 Right"] || + [element isEqualToString:@"Touchpad 1 Up"] || + [element isEqualToString:@"Touchpad 1 Down"] || + [element isEqualToString:@"Touchpad 2 X Axis"] || + [element isEqualToString:@"Touchpad 2 Y Axis"] || + [element isEqualToString:@"Touchpad 2 Left"] || + [element isEqualToString:@"Touchpad 2 Right"] || + [element isEqualToString:@"Touchpad 2 Up"] || + [element isEqualToString:@"Touchpad 2 Down"]) { + // The touchpad is handled separately + return true; + } + if ([element isEqualToString:@"Button Home"]) { + if (device->is_switch_joycon_pair) { + // The Nintendo Switch JoyCon home button doesn't ever show as being held down + return true; + } +#ifdef SDL_PLATFORM_TVOS + // The OS uses the home button, it's not available to apps + return true; +#endif + } + if ([element isEqualToString:@"Button Share"]) { + if (device->is_backbone_one) { + // The Backbone app uses share button + return true; + } + } + return false; +} + +static bool IOS_AddMFIJoystickDevice(SDL_JoystickDeviceItem *device, GCController *controller) +{ + Uint16 vendor = 0; + Uint16 product = 0; + Uint8 subtype = 0; + const char *name = NULL; + + if (@available(macOS 11.3, iOS 14.5, tvOS 14.5, *)) { + if (!GCController.shouldMonitorBackgroundEvents) { + GCController.shouldMonitorBackgroundEvents = YES; + } + } + + /* Explicitly retain the controller because SDL_JoystickDeviceItem is a + * struct, and ARC doesn't work with structs. */ + device->controller = (__bridge GCController *)CFBridgingRetain(controller); + + if (controller.vendorName) { + name = controller.vendorName.UTF8String; + } + + if (!name) { + name = "MFi Gamepad"; + } + + device->name = SDL_CreateJoystickName(0, 0, NULL, name); + +#ifdef DEBUG_CONTROLLER_PROFILE + NSLog(@"Product name: %@\n", controller.vendorName); + NSLog(@"Product category: %@\n", controller.productCategory); + NSLog(@"Elements available:\n"); + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + NSDictionary *elements = controller.physicalInputProfile.elements; + for (id key in controller.physicalInputProfile.buttons) { + NSLog(@"\tButton: %@ (%s)\n", key, elements[key].analog ? "analog" : "digital"); + } + for (id key in controller.physicalInputProfile.axes) { + NSLog(@"\tAxis: %@\n", key); + } + for (id key in controller.physicalInputProfile.dpads) { + NSLog(@"\tHat: %@\n", key); + } + } +#endif // DEBUG_CONTROLLER_PROFILE + + device->is_xbox = IsControllerXbox(controller); + device->is_ps4 = IsControllerPS4(controller); + device->is_ps5 = IsControllerPS5(controller); + device->is_switch_pro = IsControllerSwitchPro(controller); + device->is_switch_joycon_pair = IsControllerSwitchJoyConPair(controller); + device->is_stadia = IsControllerStadia(controller); + device->is_backbone_one = IsControllerBackboneOne(controller); + device->is_switch_joyconL = IsControllerSwitchJoyConL(controller); + device->is_switch_joyconR = IsControllerSwitchJoyConR(controller); +#ifdef SDL_JOYSTICK_HIDAPI + if ((device->is_xbox && (HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_XBOXONE) || + HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_XBOX360))) || + (device->is_ps4 && HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_PS4)) || + (device->is_ps5 && HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_PS5)) || + (device->is_switch_pro && HIDAPI_IsDeviceTypePresent(SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO)) || + (device->is_switch_joycon_pair && HIDAPI_IsDevicePresent(USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR, 0, "")) || + (device->is_stadia && HIDAPI_IsDevicePresent(USB_VENDOR_GOOGLE, USB_PRODUCT_GOOGLE_STADIA_CONTROLLER, 0, "")) || + (device->is_switch_joyconL && HIDAPI_IsDevicePresent(USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT, 0, "")) || + (device->is_switch_joyconR && HIDAPI_IsDevicePresent(USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT, 0, ""))) { + // The HIDAPI driver is taking care of this device + return false; + } +#endif + if (device->is_xbox && SDL_strncmp(name, "GamePad-", 8) == 0) { + // This is a Steam Virtual Gamepad, which isn't supported by GCController + return false; + } + CheckControllerSiriRemote(controller, &device->is_siri_remote); + + if (device->is_siri_remote && !SDL_GetHintBoolean(SDL_HINT_TV_REMOTE_AS_JOYSTICK, true)) { + // Ignore remotes, they'll be handled as keyboard input + return false; + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + if (controller.physicalInputProfile.buttons[GCInputDualShockTouchpadButton] != nil) { + device->has_dualshock_touchpad = TRUE; + } + if (controller.physicalInputProfile.buttons[GCInputXboxPaddleOne] != nil) { + device->has_xbox_paddles = TRUE; + } + if (controller.physicalInputProfile.buttons[@"Button Share"] != nil) { + device->has_xbox_share_button = TRUE; + } + } + + if (device->is_backbone_one) { + vendor = USB_VENDOR_BACKBONE; + if (device->is_ps5) { + product = USB_PRODUCT_BACKBONE_ONE_IOS_PS5; + } else { + product = USB_PRODUCT_BACKBONE_ONE_IOS; + } + } else if (device->is_xbox) { + vendor = USB_VENDOR_MICROSOFT; + if (device->has_xbox_paddles) { + // Assume Xbox One Elite Series 2 Controller unless/until GCController flows VID/PID + product = USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLUETOOTH; + } else if (device->has_xbox_share_button) { + // Assume Xbox Series X Controller unless/until GCController flows VID/PID + product = USB_PRODUCT_XBOX_SERIES_X_BLE; + } else { + // Assume Xbox One S Bluetooth Controller unless/until GCController flows VID/PID + product = USB_PRODUCT_XBOX_ONE_S_REV1_BLUETOOTH; + } + } else if (device->is_ps4) { + // Assume DS4 Slim unless/until GCController flows VID/PID + vendor = USB_VENDOR_SONY; + product = USB_PRODUCT_SONY_DS4_SLIM; + if (device->has_dualshock_touchpad) { + subtype = 1; + } + } else if (device->is_ps5) { + vendor = USB_VENDOR_SONY; + product = USB_PRODUCT_SONY_DS5; + } else if (device->is_switch_pro) { + vendor = USB_VENDOR_NINTENDO; + product = USB_PRODUCT_NINTENDO_SWITCH_PRO; + device->has_nintendo_buttons = TRUE; + } else if (device->is_switch_joycon_pair) { + vendor = USB_VENDOR_NINTENDO; + product = USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR; + device->has_nintendo_buttons = TRUE; + } else if (device->is_switch_joyconL) { + vendor = USB_VENDOR_NINTENDO; + product = USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT; + } else if (device->is_switch_joyconR) { + vendor = USB_VENDOR_NINTENDO; + product = USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT; + } else if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + vendor = USB_VENDOR_APPLE; + product = 4; + subtype = 4; + } else if (controller.extendedGamepad) { + vendor = USB_VENDOR_APPLE; + product = 1; + subtype = 1; +#ifdef SDL_PLATFORM_TVOS + } else if (controller.microGamepad) { + vendor = USB_VENDOR_APPLE; + product = 3; + subtype = 3; +#endif + } else { + // We don't know how to get input events from this device + return false; + } + + if (SDL_ShouldIgnoreJoystick(vendor, product, 0, name)) { + return false; + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + NSDictionary *elements = controller.physicalInputProfile.elements; + + // Provide both axes and analog buttons as SDL axes + NSArray *axes = [[[elements allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)] + filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) { + if (ElementAlreadyHandled(device, (NSString *)object, elements)) { + return false; + } + + GCControllerElement *element = elements[object]; + if (element.analog) { + if ([element isKindOfClass:[GCControllerAxisInput class]] || + [element isKindOfClass:[GCControllerButtonInput class]]) { + return true; + } + } + return false; + }]]; + NSArray *buttons = [[[elements allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)] + filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) { + if (ElementAlreadyHandled(device, (NSString *)object, elements)) { + return false; + } + + GCControllerElement *element = elements[object]; + if ([element isKindOfClass:[GCControllerButtonInput class]]) { + return true; + } + return false; + }]]; + /* Explicitly retain the arrays because SDL_JoystickDeviceItem is a + * struct, and ARC doesn't work with structs. */ + device->naxes = (int)axes.count; + device->axes = (__bridge NSArray *)CFBridgingRetain(axes); + device->nbuttons = (int)buttons.count; + device->buttons = (__bridge NSArray *)CFBridgingRetain(buttons); + subtype = 4; + +#ifdef DEBUG_CONTROLLER_PROFILE + NSLog(@"Elements used:\n", controller.vendorName); + for (id key in device->buttons) { + NSLog(@"\tButton: %@ (%s)\n", key, elements[key].analog ? "analog" : "digital"); + } + for (id key in device->axes) { + NSLog(@"\tAxis: %@\n", key); + } +#endif // DEBUG_CONTROLLER_PROFILE + +#ifdef SDL_PLATFORM_TVOS + // tvOS turns the menu button into a system gesture, so we grab it here instead + if (elements[GCInputButtonMenu] && !elements[@"Button Home"]) { + device->pause_button_index = (int)[device->buttons indexOfObject:GCInputButtonMenu]; + } +#endif + } else if (controller.extendedGamepad) { + GCExtendedGamepad *gamepad = controller.extendedGamepad; + int nbuttons = 0; + BOOL has_direct_menu = FALSE; + + // These buttons are part of the original MFi spec + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_SOUTH); + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_EAST); + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_WEST); + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_NORTH); + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_LEFT_SHOULDER); + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER); + nbuttons += 6; + + // These buttons are available on some newer controllers + if (@available(macOS 10.14.1, iOS 12.1, tvOS 12.1, *)) { + if (gamepad.leftThumbstickButton) { + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_LEFT_STICK); + ++nbuttons; + } + if (gamepad.rightThumbstickButton) { + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_RIGHT_STICK); + ++nbuttons; + } + } + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if (gamepad.buttonOptions) { + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_BACK); + ++nbuttons; + } + } + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_START); + ++nbuttons; + + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if (gamepad.buttonMenu) { + has_direct_menu = TRUE; + } + } +#ifdef SDL_PLATFORM_TVOS + // The single menu button isn't very reliable, at least as of tvOS 16.1 + if ((device->button_mask & (1 << SDL_GAMEPAD_BUTTON_BACK)) == 0) { + has_direct_menu = FALSE; + } +#endif + if (!has_direct_menu) { + device->pause_button_index = (nbuttons - 1); + } + + device->naxes = 6; // 2 thumbsticks and 2 triggers + device->nhats = 1; // d-pad + device->nbuttons = nbuttons; + } +#ifdef SDL_PLATFORM_TVOS + else if (controller.microGamepad) { + int nbuttons = 0; + + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_SOUTH); + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_WEST); // Button X on microGamepad + device->button_mask |= (1 << SDL_GAMEPAD_BUTTON_EAST); + nbuttons += 3; + device->pause_button_index = (nbuttons - 1); + + device->naxes = 2; // treat the touch surface as two axes + device->nhats = 0; // apparently the touch surface-as-dpad is buggy + device->nbuttons = nbuttons; + + controller.microGamepad.allowsRotation = SDL_GetHintBoolean(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION, false); + } +#endif + else { + // We don't know how to get input events from this device + return false; + } + + Uint16 signature; + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + signature = 0; + signature = SDL_crc16(signature, device->name, SDL_strlen(device->name)); + for (id key in device->axes) { + const char *string = ((NSString *)key).UTF8String; + signature = SDL_crc16(signature, string, SDL_strlen(string)); + } + for (id key in device->buttons) { + const char *string = ((NSString *)key).UTF8String; + signature = SDL_crc16(signature, string, SDL_strlen(string)); + } + } else { + signature = device->button_mask; + } + device->guid = SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_BLUETOOTH, vendor, product, signature, NULL, name, 'm', subtype); + + /* This will be set when the first button press of the controller is + * detected. */ + controller.playerIndex = -1; + return true; +} +#endif // SDL_JOYSTICK_MFI + +#ifdef SDL_JOYSTICK_MFI +static void IOS_AddJoystickDevice(GCController *controller) +{ + SDL_JoystickDeviceItem *device = deviceList; + + while (device != NULL) { + if (device->controller == controller) { + return; + } + device = device->next; + } + + device = (SDL_JoystickDeviceItem *)SDL_calloc(1, sizeof(SDL_JoystickDeviceItem)); + if (device == NULL) { + return; + } + + device->instance_id = SDL_GetNextObjectID(); + device->pause_button_index = -1; + + if (controller) { +#ifdef SDL_JOYSTICK_MFI + if (!IOS_AddMFIJoystickDevice(device, controller)) { + SDL_free(device->name); + SDL_free(device); + return; + } +#else + SDL_free(device); + return; +#endif // SDL_JOYSTICK_MFI + } + + if (deviceList == NULL) { + deviceList = device; + } else { + SDL_JoystickDeviceItem *lastdevice = deviceList; + while (lastdevice->next != NULL) { + lastdevice = lastdevice->next; + } + lastdevice->next = device; + } + + ++numjoysticks; + + SDL_PrivateJoystickAdded(device->instance_id); +} +#endif // SDL_JOYSTICK_MFI + +static SDL_JoystickDeviceItem *IOS_RemoveJoystickDevice(SDL_JoystickDeviceItem *device) +{ + SDL_JoystickDeviceItem *prev = NULL; + SDL_JoystickDeviceItem *next = NULL; + SDL_JoystickDeviceItem *item = deviceList; + + if (device == NULL) { + return NULL; + } + + next = device->next; + + while (item != NULL) { + if (item == device) { + break; + } + prev = item; + item = item->next; + } + + // Unlink the device item from the device list. + if (prev) { + prev->next = device->next; + } else if (device == deviceList) { + deviceList = device->next; + } + + if (device->joystick) { + device->joystick->hwdata = NULL; + } + +#ifdef SDL_JOYSTICK_MFI + @autoreleasepool { + // These were explicitly retained in the struct, so they should be explicitly released before freeing the struct. + if (device->controller) { + GCController *controller = CFBridgingRelease((__bridge CFTypeRef)(device->controller)); + controller.controllerPausedHandler = nil; + device->controller = nil; + } + if (device->axes) { + CFRelease((__bridge CFTypeRef)device->axes); + device->axes = nil; + } + if (device->buttons) { + CFRelease((__bridge CFTypeRef)device->buttons); + device->buttons = nil; + } + } +#endif // SDL_JOYSTICK_MFI + + --numjoysticks; + + SDL_PrivateJoystickRemoved(device->instance_id); + + SDL_free(device->name); + SDL_free(device); + + return next; +} + +#ifdef SDL_PLATFORM_TVOS +static void SDLCALL SDL_AppleTVRemoteRotationHintChanged(void *udata, const char *name, const char *oldValue, const char *newValue) +{ + BOOL allowRotation = newValue != NULL && *newValue != '0'; + + @autoreleasepool { + for (GCController *controller in [GCController controllers]) { + if (controller.microGamepad) { + controller.microGamepad.allowsRotation = allowRotation; + } + } + } +} +#endif // SDL_PLATFORM_TVOS + +static bool IOS_JoystickInit(void) +{ + if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_MFI, true)) { + return true; + } + +#ifdef SDL_PLATFORM_MACOS + if (@available(macOS 10.16, *)) { + // Continue with initialization on macOS 11+ + } else { + return true; + } +#endif + + @autoreleasepool { +#ifdef SDL_JOYSTICK_MFI + NSNotificationCenter *center; +#endif + +#ifdef SDL_JOYSTICK_MFI + // GameController.framework was added in iOS 7. + if (![GCController class]) { + return true; + } + + /* For whatever reason, this always returns an empty array on + macOS 11.0.1 */ + for (GCController *controller in [GCController controllers]) { + IOS_AddJoystickDevice(controller); + } + +#ifdef SDL_PLATFORM_TVOS + SDL_AddHintCallback(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION, + SDL_AppleTVRemoteRotationHintChanged, NULL); +#endif // SDL_PLATFORM_TVOS + + center = [NSNotificationCenter defaultCenter]; + + connectObserver = [center addObserverForName:GCControllerDidConnectNotification + object:nil + queue:nil + usingBlock:^(NSNotification *note) { + GCController *controller = note.object; + SDL_LockJoysticks(); + IOS_AddJoystickDevice(controller); + SDL_UnlockJoysticks(); + }]; + + disconnectObserver = [center addObserverForName:GCControllerDidDisconnectNotification + object:nil + queue:nil + usingBlock:^(NSNotification *note) { + GCController *controller = note.object; + SDL_JoystickDeviceItem *device; + SDL_LockJoysticks(); + for (device = deviceList; device != NULL; device = device->next) { + if (device->controller == controller) { + IOS_RemoveJoystickDevice(device); + break; + } + } + SDL_UnlockJoysticks(); + }]; +#endif // SDL_JOYSTICK_MFI + } + + return true; +} + +static int IOS_JoystickGetCount(void) +{ + return numjoysticks; +} + +static void IOS_JoystickDetect(void) +{ +} + +static bool IOS_JoystickIsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ + // We don't override any other drivers through this method + return false; +} + +static const char *IOS_JoystickGetDeviceName(int device_index) +{ + SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); + return device ? device->name : "Unknown"; +} + +static const char *IOS_JoystickGetDevicePath(int device_index) +{ + return NULL; +} + +static int IOS_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index) +{ + return -1; +} + +static int IOS_JoystickGetDevicePlayerIndex(int device_index) +{ +#ifdef SDL_JOYSTICK_MFI + SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); + if (device && device->controller) { + return (int)device->controller.playerIndex; + } +#endif + return -1; +} + +static void IOS_JoystickSetDevicePlayerIndex(int device_index, int player_index) +{ +#ifdef SDL_JOYSTICK_MFI + SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); + if (device && device->controller) { + device->controller.playerIndex = player_index; + } +#endif +} + +static SDL_GUID IOS_JoystickGetDeviceGUID(int device_index) +{ + SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); + SDL_GUID guid; + if (device) { + guid = device->guid; + } else { + SDL_zero(guid); + } + return guid; +} + +static SDL_JoystickID IOS_JoystickGetDeviceInstanceID(int device_index) +{ + SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); + return device ? device->instance_id : 0; +} + +static bool IOS_JoystickOpen(SDL_Joystick *joystick, int device_index) +{ + SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); + if (device == NULL) { + return SDL_SetError("Could not open Joystick: no hardware device for the specified index"); + } + + joystick->hwdata = device; + + joystick->naxes = device->naxes; + joystick->nhats = device->nhats; + joystick->nbuttons = device->nbuttons; + + if (device->has_dualshock_touchpad) { + SDL_PrivateJoystickAddTouchpad(joystick, 2); + } + + device->joystick = joystick; + + @autoreleasepool { +#ifdef SDL_JOYSTICK_MFI + if (device->pause_button_index >= 0) { + GCController *controller = device->controller; + controller.controllerPausedHandler = ^(GCController *c) { + if (joystick->hwdata) { + joystick->hwdata->pause_button_pressed = SDL_GetTicks(); + } + }; + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + GCController *controller = joystick->hwdata->controller; + GCMotion *motion = controller.motion; + if (motion && motion.hasRotationRate) { + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, 0.0f); + } + if (motion && motion.hasGravityAndUserAcceleration) { + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 0.0f); + } + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + GCController *controller = joystick->hwdata->controller; + for (id key in controller.physicalInputProfile.buttons) { + GCControllerButtonInput *button = controller.physicalInputProfile.buttons[key]; + if ([button isBoundToSystemGesture]) { + button.preferredSystemGestureState = GCSystemGestureStateDisabled; + } + } + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + GCController *controller = device->controller; + if (controller.light) { + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN, true); + } + + if (controller.haptics) { + for (GCHapticsLocality locality in controller.haptics.supportedLocalities) { + if ([locality isEqualToString:GCHapticsLocalityHandles]) { + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true); + } else if ([locality isEqualToString:GCHapticsLocalityTriggers]) { + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN, true); + } + } + } + } +#endif // SDL_JOYSTICK_MFI + } + if (device->is_siri_remote) { + ++SDL_AppleTVRemoteOpenedAsJoystick; + } + + return true; +} + +#ifdef SDL_JOYSTICK_MFI +static Uint8 IOS_MFIJoystickHatStateForDPad(GCControllerDirectionPad *dpad) +{ + Uint8 hat = 0; + + if (dpad.up.isPressed) { + hat |= SDL_HAT_UP; + } else if (dpad.down.isPressed) { + hat |= SDL_HAT_DOWN; + } + + if (dpad.left.isPressed) { + hat |= SDL_HAT_LEFT; + } else if (dpad.right.isPressed) { + hat |= SDL_HAT_RIGHT; + } + + if (hat == 0) { + return SDL_HAT_CENTERED; + } + + return hat; +} +#endif + +static void IOS_MFIJoystickUpdate(SDL_Joystick *joystick) +{ +#ifdef SDL_JOYSTICK_MFI + @autoreleasepool { + SDL_JoystickDeviceItem *device = joystick->hwdata; + GCController *controller = device->controller; + Uint8 hatstate = SDL_HAT_CENTERED; + int i; + Uint64 timestamp = SDL_GetTicksNS(); + +#ifdef DEBUG_CONTROLLER_STATE + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + if (controller.physicalInputProfile) { + for (id key in controller.physicalInputProfile.buttons) { + GCControllerButtonInput *button = controller.physicalInputProfile.buttons[key]; + if (button.isPressed) + NSLog(@"Button %@ = %s\n", key, button.isPressed ? "pressed" : "released"); + } + for (id key in controller.physicalInputProfile.axes) { + GCControllerAxisInput *axis = controller.physicalInputProfile.axes[key]; + if (axis.value != 0.0f) + NSLog(@"Axis %@ = %g\n", key, axis.value); + } + for (id key in controller.physicalInputProfile.dpads) { + GCControllerDirectionPad *dpad = controller.physicalInputProfile.dpads[key]; + if (dpad.up.isPressed || dpad.down.isPressed || dpad.left.isPressed || dpad.right.isPressed) { + NSLog(@"Hat %@ =%s%s%s%s\n", key, + dpad.up.isPressed ? " UP" : "", + dpad.down.isPressed ? " DOWN" : "", + dpad.left.isPressed ? " LEFT" : "", + dpad.right.isPressed ? " RIGHT" : ""); + } + } + } + } +#endif // DEBUG_CONTROLLER_STATE + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + NSDictionary *elements = controller.physicalInputProfile.elements; + NSDictionary *buttons = controller.physicalInputProfile.buttons; + + int axis = 0; + for (id key in device->axes) { + Sint16 value; + GCControllerElement *element = elements[key]; + if ([element isKindOfClass:[GCControllerAxisInput class]]) { + value = (Sint16)([(GCControllerAxisInput *)element value] * 32767); + } else { + value = (Sint16)([(GCControllerButtonInput *)element value] * 32767); + } + SDL_SendJoystickAxis(timestamp, joystick, axis++, value); + } + + int button = 0; + for (id key in device->buttons) { + bool down; + if (button == device->pause_button_index) { + down = (device->pause_button_pressed > 0); + } else { + down = buttons[key].isPressed; + } + SDL_SendJoystickButton(timestamp, joystick, button++, down); + } + } else if (controller.extendedGamepad) { + bool isstack; + GCExtendedGamepad *gamepad = controller.extendedGamepad; + + // Axis order matches the XInput Windows mappings. + Sint16 axes[] = { + (Sint16)(gamepad.leftThumbstick.xAxis.value * 32767), + (Sint16)(gamepad.leftThumbstick.yAxis.value * -32767), + (Sint16)((gamepad.leftTrigger.value * 65535) - 32768), + (Sint16)(gamepad.rightThumbstick.xAxis.value * 32767), + (Sint16)(gamepad.rightThumbstick.yAxis.value * -32767), + (Sint16)((gamepad.rightTrigger.value * 65535) - 32768), + }; + + // Button order matches the XInput Windows mappings. + bool *buttons = SDL_small_alloc(bool, joystick->nbuttons, &isstack); + int button_count = 0; + + if (buttons == NULL) { + return; + } + + // These buttons are part of the original MFi spec + buttons[button_count++] = gamepad.buttonA.isPressed; + buttons[button_count++] = gamepad.buttonB.isPressed; + buttons[button_count++] = gamepad.buttonX.isPressed; + buttons[button_count++] = gamepad.buttonY.isPressed; + buttons[button_count++] = gamepad.leftShoulder.isPressed; + buttons[button_count++] = gamepad.rightShoulder.isPressed; + + // These buttons are available on some newer controllers + if (@available(macOS 10.14.1, iOS 12.1, tvOS 12.1, *)) { + if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_LEFT_STICK)) { + buttons[button_count++] = gamepad.leftThumbstickButton.isPressed; + } + if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_RIGHT_STICK)) { + buttons[button_count++] = gamepad.rightThumbstickButton.isPressed; + } + } + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_BACK)) { + buttons[button_count++] = gamepad.buttonOptions.isPressed; + } + } + if (device->button_mask & (1 << SDL_GAMEPAD_BUTTON_START)) { + if (device->pause_button_index >= 0) { + // Guaranteed if buttonMenu is not supported on this OS + buttons[button_count++] = (device->pause_button_pressed > 0); + } else { + if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)) { + buttons[button_count++] = gamepad.buttonMenu.isPressed; + } + } + } + + hatstate = IOS_MFIJoystickHatStateForDPad(gamepad.dpad); + + for (i = 0; i < SDL_arraysize(axes); i++) { + SDL_SendJoystickAxis(timestamp, joystick, i, axes[i]); + } + + for (i = 0; i < button_count; i++) { + SDL_SendJoystickButton(timestamp, joystick, i, buttons[i]); + } + + SDL_small_free(buttons, isstack); + } +#ifdef SDL_PLATFORM_TVOS + else if (controller.microGamepad) { + GCMicroGamepad *gamepad = controller.microGamepad; + + Sint16 axes[] = { + (Sint16)(gamepad.dpad.xAxis.value * 32767), + (Sint16)(gamepad.dpad.yAxis.value * -32767), + }; + + for (i = 0; i < SDL_arraysize(axes); i++) { + SDL_SendJoystickAxis(timestamp, joystick, i, axes[i]); + } + + bool buttons[joystick->nbuttons]; + int button_count = 0; + buttons[button_count++] = gamepad.buttonA.isPressed; + buttons[button_count++] = gamepad.buttonX.isPressed; + buttons[button_count++] = (device->pause_button_pressed > 0); + + for (i = 0; i < button_count; i++) { + SDL_SendJoystickButton(timestamp, joystick, i, buttons[i]); + } + } +#endif // SDL_PLATFORM_TVOS + + if (joystick->nhats > 0) { + SDL_SendJoystickHat(timestamp, joystick, 0, hatstate); + } + + if (device->pause_button_pressed) { + // The pause callback is instantaneous, so we extend the duration to allow "holding down" by pressing it repeatedly + const int PAUSE_BUTTON_PRESS_DURATION_MS = 250; + if (SDL_GetTicks() >= device->pause_button_pressed + PAUSE_BUTTON_PRESS_DURATION_MS) { + device->pause_button_pressed = 0; + } + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + if (device->has_dualshock_touchpad) { + GCControllerDirectionPad *dpad; + + dpad = controller.physicalInputProfile.dpads[GCInputDualShockTouchpadOne]; + if (dpad.xAxis.value != 0.f || dpad.yAxis.value != 0.f) { + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, true, (1.0f + dpad.xAxis.value) * 0.5f, 1.0f - (1.0f + dpad.yAxis.value) * 0.5f, 1.0f); + } else { + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, false, 0.0f, 0.0f, 1.0f); + } + + dpad = controller.physicalInputProfile.dpads[GCInputDualShockTouchpadTwo]; + if (dpad.xAxis.value != 0.f || dpad.yAxis.value != 0.f) { + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 1, true, (1.0f + dpad.xAxis.value) * 0.5f, 1.0f - (1.0f + dpad.yAxis.value) * 0.5f, 1.0f); + } else { + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 1, false, 0.0f, 0.0f, 1.0f); + } + } + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + GCMotion *motion = controller.motion; + if (motion && motion.sensorsActive) { + float data[3]; + + if (motion.hasRotationRate) { + GCRotationRate rate = motion.rotationRate; + data[0] = rate.x; + data[1] = rate.z; + data[2] = -rate.y; + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, timestamp, data, 3); + } + if (motion.hasGravityAndUserAcceleration) { + GCAcceleration accel = motion.acceleration; + data[0] = -accel.x * SDL_STANDARD_GRAVITY; + data[1] = -accel.y * SDL_STANDARD_GRAVITY; + data[2] = -accel.z * SDL_STANDARD_GRAVITY; + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, timestamp, data, 3); + } + } + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + GCDeviceBattery *battery = controller.battery; + if (battery) { + SDL_PowerState state = SDL_POWERSTATE_UNKNOWN; + int percent = (int)SDL_roundf(battery.batteryLevel * 100.0f); + + switch (battery.batteryState) { + case GCDeviceBatteryStateDischarging: + state = SDL_POWERSTATE_ON_BATTERY; + break; + case GCDeviceBatteryStateCharging: + state = SDL_POWERSTATE_CHARGING; + break; + case GCDeviceBatteryStateFull: + state = SDL_POWERSTATE_CHARGED; + break; + default: + break; + } + + SDL_SendJoystickPowerInfo(joystick, state, percent); + } + } + } +#endif // SDL_JOYSTICK_MFI +} + +#ifdef SDL_JOYSTICK_MFI +@interface SDL3_RumbleMotor : NSObject +@property(nonatomic, strong) CHHapticEngine *engine API_AVAILABLE(macos(10.16), ios(13.0), tvos(14.0)); +@property(nonatomic, strong) id player API_AVAILABLE(macos(10.16), ios(13.0), tvos(14.0)); +@property bool active; +@end + +@implementation SDL3_RumbleMotor +{ +} + +- (void)cleanup +{ + @autoreleasepool { + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + if (self.player != nil) { + [self.player cancelAndReturnError:nil]; + self.player = nil; + } + if (self.engine != nil) { + [self.engine stopWithCompletionHandler:nil]; + self.engine = nil; + } + } + } +} + +- (bool)setIntensity:(float)intensity +{ + @autoreleasepool { + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + NSError *error = nil; + CHHapticDynamicParameter *param; + + if (self.engine == nil) { + return SDL_SetError("Haptics engine was stopped"); + } + + if (intensity == 0.0f) { + if (self.player && self.active) { + [self.player stopAtTime:0 error:&error]; + } + self.active = false; + return true; + } + + if (self.player == nil) { + CHHapticEventParameter *event_param = [[CHHapticEventParameter alloc] initWithParameterID:CHHapticEventParameterIDHapticIntensity value:1.0f]; + CHHapticEvent *event = [[CHHapticEvent alloc] initWithEventType:CHHapticEventTypeHapticContinuous parameters:[NSArray arrayWithObjects:event_param, nil] relativeTime:0 duration:GCHapticDurationInfinite]; + CHHapticPattern *pattern = [[CHHapticPattern alloc] initWithEvents:[NSArray arrayWithObject:event] parameters:[[NSArray alloc] init] error:&error]; + if (error != nil) { + return SDL_SetError("Couldn't create haptic pattern: %s", [error.localizedDescription UTF8String]); + } + + self.player = [self.engine createPlayerWithPattern:pattern error:&error]; + if (error != nil) { + return SDL_SetError("Couldn't create haptic player: %s", [error.localizedDescription UTF8String]); + } + self.active = false; + } + + param = [[CHHapticDynamicParameter alloc] initWithParameterID:CHHapticDynamicParameterIDHapticIntensityControl value:intensity relativeTime:0]; + [self.player sendParameters:[NSArray arrayWithObject:param] atTime:0 error:&error]; + if (error != nil) { + return SDL_SetError("Couldn't update haptic player: %s", [error.localizedDescription UTF8String]); + } + + if (!self.active) { + [self.player startAtTime:0 error:&error]; + self.active = true; + } + } + + return true; + } +} + +- (id)initWithController:(GCController *)controller locality:(GCHapticsLocality)locality API_AVAILABLE(macos(10.16), ios(14.0), tvos(14.0)) +{ + @autoreleasepool { + NSError *error; + __weak __typeof(self) weakSelf; + self = [super init]; + weakSelf = self; + + self.engine = [controller.haptics createEngineWithLocality:locality]; + if (self.engine == nil) { + SDL_SetError("Couldn't create haptics engine"); + return nil; + } + + [self.engine startAndReturnError:&error]; + if (error != nil) { + SDL_SetError("Couldn't start haptics engine"); + return nil; + } + + self.engine.stoppedHandler = ^(CHHapticEngineStoppedReason stoppedReason) { + SDL3_RumbleMotor *_this = weakSelf; + if (_this == nil) { + return; + } + + _this.player = nil; + _this.engine = nil; + }; + self.engine.resetHandler = ^{ + SDL3_RumbleMotor *_this = weakSelf; + if (_this == nil) { + return; + } + + _this.player = nil; + [_this.engine startAndReturnError:nil]; + }; + + return self; + } +} + +@end + +@interface SDL3_RumbleContext : NSObject +@property(nonatomic, strong) SDL3_RumbleMotor *lowFrequencyMotor; +@property(nonatomic, strong) SDL3_RumbleMotor *highFrequencyMotor; +@property(nonatomic, strong) SDL3_RumbleMotor *leftTriggerMotor; +@property(nonatomic, strong) SDL3_RumbleMotor *rightTriggerMotor; +@end + +@implementation SDL3_RumbleContext +{ +} + +- (id)initWithLowFrequencyMotor:(SDL3_RumbleMotor *)low_frequency_motor + HighFrequencyMotor:(SDL3_RumbleMotor *)high_frequency_motor + LeftTriggerMotor:(SDL3_RumbleMotor *)left_trigger_motor + RightTriggerMotor:(SDL3_RumbleMotor *)right_trigger_motor +{ + self = [super init]; + self.lowFrequencyMotor = low_frequency_motor; + self.highFrequencyMotor = high_frequency_motor; + self.leftTriggerMotor = left_trigger_motor; + self.rightTriggerMotor = right_trigger_motor; + return self; +} + +- (bool)rumbleWithLowFrequency:(Uint16)low_frequency_rumble andHighFrequency:(Uint16)high_frequency_rumble +{ + bool result = true; + + result &= [self.lowFrequencyMotor setIntensity:((float)low_frequency_rumble / 65535.0f)]; + result &= [self.highFrequencyMotor setIntensity:((float)high_frequency_rumble / 65535.0f)]; + return result; +} + +- (bool)rumbleLeftTrigger:(Uint16)left_rumble andRightTrigger:(Uint16)right_rumble +{ + bool result = false; + + if (self.leftTriggerMotor && self.rightTriggerMotor) { + result &= [self.leftTriggerMotor setIntensity:((float)left_rumble / 65535.0f)]; + result &= [self.rightTriggerMotor setIntensity:((float)right_rumble / 65535.0f)]; + } else { + result = SDL_Unsupported(); + } + return result; +} + +- (void)cleanup +{ + [self.lowFrequencyMotor cleanup]; + [self.highFrequencyMotor cleanup]; +} + +@end + +static SDL3_RumbleContext *IOS_JoystickInitRumble(GCController *controller) +{ + @autoreleasepool { + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + SDL3_RumbleMotor *low_frequency_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityLeftHandle]; + SDL3_RumbleMotor *high_frequency_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityRightHandle]; + SDL3_RumbleMotor *left_trigger_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityLeftTrigger]; + SDL3_RumbleMotor *right_trigger_motor = [[SDL3_RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityRightTrigger]; + if (low_frequency_motor && high_frequency_motor) { + return [[SDL3_RumbleContext alloc] initWithLowFrequencyMotor:low_frequency_motor + HighFrequencyMotor:high_frequency_motor + LeftTriggerMotor:left_trigger_motor + RightTriggerMotor:right_trigger_motor]; + } + } + } + return nil; +} + +#endif // SDL_JOYSTICK_MFI + +static bool IOS_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ +#ifdef SDL_JOYSTICK_MFI + SDL_JoystickDeviceItem *device = joystick->hwdata; + + if (device == NULL) { + return SDL_SetError("Controller is no longer connected"); + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + if (!device->rumble && device->controller && device->controller.haptics) { + SDL3_RumbleContext *rumble = IOS_JoystickInitRumble(device->controller); + if (rumble) { + device->rumble = (void *)CFBridgingRetain(rumble); + } + } + } + + if (device->rumble) { + SDL3_RumbleContext *rumble = (__bridge SDL3_RumbleContext *)device->rumble; + return [rumble rumbleWithLowFrequency:low_frequency_rumble andHighFrequency:high_frequency_rumble]; + } +#endif + return SDL_Unsupported(); +} + +static bool IOS_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ +#ifdef SDL_JOYSTICK_MFI + SDL_JoystickDeviceItem *device = joystick->hwdata; + + if (device == NULL) { + return SDL_SetError("Controller is no longer connected"); + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + if (!device->rumble && device->controller && device->controller.haptics) { + SDL3_RumbleContext *rumble = IOS_JoystickInitRumble(device->controller); + if (rumble) { + device->rumble = (void *)CFBridgingRetain(rumble); + } + } + } + + if (device->rumble) { + SDL3_RumbleContext *rumble = (__bridge SDL3_RumbleContext *)device->rumble; + return [rumble rumbleLeftTrigger:left_rumble andRightTrigger:right_rumble]; + } +#endif + return SDL_Unsupported(); +} + +static bool IOS_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + @autoreleasepool { + SDL_JoystickDeviceItem *device = joystick->hwdata; + + if (device == NULL) { + return SDL_SetError("Controller is no longer connected"); + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + GCController *controller = device->controller; + GCDeviceLight *light = controller.light; + if (light) { + light.color = [[GCColor alloc] initWithRed:(float)red / 255.0f + green:(float)green / 255.0f + blue:(float)blue / 255.0f]; + return true; + } + } + } + return SDL_Unsupported(); +} + +static bool IOS_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool IOS_JoystickSetSensorsEnabled(SDL_Joystick *joystick, bool enabled) +{ + @autoreleasepool { + SDL_JoystickDeviceItem *device = joystick->hwdata; + + if (device == NULL) { + return SDL_SetError("Controller is no longer connected"); + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + GCController *controller = device->controller; + GCMotion *motion = controller.motion; + if (motion) { + motion.sensorsActive = enabled ? YES : NO; + return true; + } + } + } + + return SDL_Unsupported(); +} + +static void IOS_JoystickUpdate(SDL_Joystick *joystick) +{ + SDL_JoystickDeviceItem *device = joystick->hwdata; + + if (device == NULL) { + return; + } + + if (device->controller) { + IOS_MFIJoystickUpdate(joystick); + } +} + +static void IOS_JoystickClose(SDL_Joystick *joystick) +{ + SDL_JoystickDeviceItem *device = joystick->hwdata; + + if (device == NULL) { + return; + } + + device->joystick = NULL; + +#ifdef SDL_JOYSTICK_MFI + @autoreleasepool { + if (device->rumble) { + SDL3_RumbleContext *rumble = (__bridge SDL3_RumbleContext *)device->rumble; + + [rumble cleanup]; + CFRelease(device->rumble); + device->rumble = NULL; + } + + if (device->controller) { + GCController *controller = device->controller; + controller.controllerPausedHandler = nil; + controller.playerIndex = -1; + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + for (id key in controller.physicalInputProfile.buttons) { + GCControllerButtonInput *button = controller.physicalInputProfile.buttons[key]; + if ([button isBoundToSystemGesture]) { + button.preferredSystemGestureState = GCSystemGestureStateEnabled; + } + } + } + } + } +#endif // SDL_JOYSTICK_MFI + + if (device->is_siri_remote) { + --SDL_AppleTVRemoteOpenedAsJoystick; + } +} + +static void IOS_JoystickQuit(void) +{ + @autoreleasepool { +#ifdef SDL_JOYSTICK_MFI + NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; + + if (connectObserver) { + [center removeObserver:connectObserver name:GCControllerDidConnectNotification object:nil]; + connectObserver = nil; + } + + if (disconnectObserver) { + [center removeObserver:disconnectObserver name:GCControllerDidDisconnectNotification object:nil]; + disconnectObserver = nil; + } + +#ifdef SDL_PLATFORM_TVOS + SDL_RemoveHintCallback(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION, + SDL_AppleTVRemoteRotationHintChanged, NULL); +#endif // SDL_PLATFORM_TVOS +#endif // SDL_JOYSTICK_MFI + + while (deviceList != NULL) { + IOS_RemoveJoystickDevice(deviceList); + } + } + + numjoysticks = 0; +} + +static bool IOS_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) +{ + SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); + if (device == NULL) { + return false; + } + + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + int axis = 0; + for (id key in device->axes) { + if ([(NSString *)key isEqualToString:@"Left Thumbstick X Axis"] || + [(NSString *)key isEqualToString:@"Direction Pad X Axis"]) { + out->leftx.kind = EMappingKind_Axis; + out->leftx.target = axis; + } else if ([(NSString *)key isEqualToString:@"Left Thumbstick Y Axis"] || + [(NSString *)key isEqualToString:@"Direction Pad Y Axis"]) { + out->lefty.kind = EMappingKind_Axis; + out->lefty.target = axis; + out->lefty.axis_reversed = true; + } else if ([(NSString *)key isEqualToString:@"Right Thumbstick X Axis"]) { + out->rightx.kind = EMappingKind_Axis; + out->rightx.target = axis; + } else if ([(NSString *)key isEqualToString:@"Right Thumbstick Y Axis"]) { + out->righty.kind = EMappingKind_Axis; + out->righty.target = axis; + out->righty.axis_reversed = true; + } else if ([(NSString *)key isEqualToString:GCInputLeftTrigger]) { + out->lefttrigger.kind = EMappingKind_Axis; + out->lefttrigger.target = axis; + out->lefttrigger.half_axis_positive = true; + } else if ([(NSString *)key isEqualToString:GCInputRightTrigger]) { + out->righttrigger.kind = EMappingKind_Axis; + out->righttrigger.target = axis; + out->righttrigger.half_axis_positive = true; + } + ++axis; + } + + int button = 0; + for (id key in device->buttons) { + SDL_InputMapping *mapping = NULL; + + if ([(NSString *)key isEqualToString:GCInputButtonA]) { + if (device->is_siri_remote > 1) { + // GCInputButtonA is triggered for any D-Pad press, ignore it in favor of "Button Center" + } else if (device->has_nintendo_buttons) { + mapping = &out->b; + } else { + mapping = &out->a; + } + } else if ([(NSString *)key isEqualToString:GCInputButtonB]) { + if (device->has_nintendo_buttons) { + mapping = &out->a; + } else if (device->is_switch_joyconL || device->is_switch_joyconR) { + mapping = &out->x; + } else { + mapping = &out->b; + } + } else if ([(NSString *)key isEqualToString:GCInputButtonX]) { + if (device->has_nintendo_buttons) { + mapping = &out->y; + } else if (device->is_switch_joyconL || device->is_switch_joyconR) { + mapping = &out->b; + } else { + mapping = &out->x; + } + } else if ([(NSString *)key isEqualToString:GCInputButtonY]) { + if (device->has_nintendo_buttons) { + mapping = &out->x; + } else { + mapping = &out->y; + } + } else if ([(NSString *)key isEqualToString:@"Direction Pad Left"]) { + mapping = &out->dpleft; + } else if ([(NSString *)key isEqualToString:@"Direction Pad Right"]) { + mapping = &out->dpright; + } else if ([(NSString *)key isEqualToString:@"Direction Pad Up"]) { + mapping = &out->dpup; + } else if ([(NSString *)key isEqualToString:@"Direction Pad Down"]) { + mapping = &out->dpdown; + } else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Left"]) { + mapping = &out->dpleft; + } else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Right"]) { + mapping = &out->dpright; + } else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Up"]) { + mapping = &out->dpup; + } else if ([(NSString *)key isEqualToString:@"Cardinal Direction Pad Down"]) { + mapping = &out->dpdown; + } else if ([(NSString *)key isEqualToString:GCInputLeftShoulder]) { + mapping = &out->leftshoulder; + } else if ([(NSString *)key isEqualToString:GCInputRightShoulder]) { + mapping = &out->rightshoulder; + } else if ([(NSString *)key isEqualToString:GCInputLeftThumbstickButton]) { + mapping = &out->leftstick; + } else if ([(NSString *)key isEqualToString:GCInputRightThumbstickButton]) { + mapping = &out->rightstick; + } else if ([(NSString *)key isEqualToString:@"Button Home"]) { + mapping = &out->guide; + } else if ([(NSString *)key isEqualToString:GCInputButtonMenu]) { + if (device->is_siri_remote) { + mapping = &out->b; + } else { + mapping = &out->start; + } + } else if ([(NSString *)key isEqualToString:GCInputButtonOptions]) { + mapping = &out->back; + } else if ([(NSString *)key isEqualToString:@"Button Share"]) { + mapping = &out->misc1; + } else if ([(NSString *)key isEqualToString:GCInputXboxPaddleOne]) { + mapping = &out->right_paddle1; + } else if ([(NSString *)key isEqualToString:GCInputXboxPaddleTwo]) { + mapping = &out->right_paddle2; + } else if ([(NSString *)key isEqualToString:GCInputXboxPaddleThree]) { + mapping = &out->left_paddle1; + } else if ([(NSString *)key isEqualToString:GCInputXboxPaddleFour]) { + mapping = &out->left_paddle2; + } else if ([(NSString *)key isEqualToString:GCInputLeftTrigger]) { + mapping = &out->lefttrigger; + } else if ([(NSString *)key isEqualToString:GCInputRightTrigger]) { + mapping = &out->righttrigger; + } else if ([(NSString *)key isEqualToString:GCInputDualShockTouchpadButton]) { + mapping = &out->touchpad; + } else if ([(NSString *)key isEqualToString:@"Button Center"]) { + mapping = &out->a; + } + if (mapping && mapping->kind == EMappingKind_None) { + mapping->kind = EMappingKind_Button; + mapping->target = button; + } + ++button; + } + + return true; + } + return false; +} + +#if defined(SDL_JOYSTICK_MFI) && defined(SDL_PLATFORM_MACOS) +bool IOS_SupportedHIDDevice(IOHIDDeviceRef device) +{ + if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_MFI, true)) { + return false; + } + + if (@available(macOS 10.16, *)) { + const int MAX_ATTEMPTS = 3; + for (int attempt = 0; attempt < MAX_ATTEMPTS; ++attempt) { + if ([GCController supportsHIDDevice:device]) { + return true; + } + + // The framework may not have seen the device yet + SDL_Delay(10); + } + } + return false; +} +#endif + +#ifdef SDL_JOYSTICK_MFI +/* NOLINTNEXTLINE(readability-non-const-parameter): getCString takes a non-const char* */ +static void GetAppleSFSymbolsNameForElement(GCControllerElement *element, char *name) +{ + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + if (element) { + [element.sfSymbolsName getCString:name maxLength:255 encoding:NSASCIIStringEncoding]; + } + } +} + +static GCControllerDirectionPad *GetDirectionalPadForController(GCController *controller) +{ + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + return controller.physicalInputProfile.dpads[GCInputDirectionPad]; + } + + if (controller.extendedGamepad) { + return controller.extendedGamepad.dpad; + } + + if (controller.microGamepad) { + return controller.microGamepad.dpad; + } + + return nil; +} +#endif // SDL_JOYSTICK_MFI + +const char *IOS_GetAppleSFSymbolsNameForButton(SDL_Gamepad *gamepad, SDL_GamepadButton button) +{ + char elementName[256]; + elementName[0] = '\0'; + +#ifdef SDL_JOYSTICK_MFI + if (gamepad && SDL_GetGamepadJoystick(gamepad)->driver == &SDL_IOS_JoystickDriver) { + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + GCController *controller = SDL_GetGamepadJoystick(gamepad)->hwdata->controller; + NSDictionary *elements = controller.physicalInputProfile.elements; + switch (button) { + case SDL_GAMEPAD_BUTTON_SOUTH: + GetAppleSFSymbolsNameForElement(elements[GCInputButtonA], elementName); + break; + case SDL_GAMEPAD_BUTTON_EAST: + GetAppleSFSymbolsNameForElement(elements[GCInputButtonB], elementName); + break; + case SDL_GAMEPAD_BUTTON_WEST: + GetAppleSFSymbolsNameForElement(elements[GCInputButtonX], elementName); + break; + case SDL_GAMEPAD_BUTTON_NORTH: + GetAppleSFSymbolsNameForElement(elements[GCInputButtonY], elementName); + break; + case SDL_GAMEPAD_BUTTON_BACK: + GetAppleSFSymbolsNameForElement(elements[GCInputButtonOptions], elementName); + break; + case SDL_GAMEPAD_BUTTON_GUIDE: + GetAppleSFSymbolsNameForElement(elements[@"Button Home"], elementName); + break; + case SDL_GAMEPAD_BUTTON_START: + GetAppleSFSymbolsNameForElement(elements[GCInputButtonMenu], elementName); + break; + case SDL_GAMEPAD_BUTTON_LEFT_STICK: + GetAppleSFSymbolsNameForElement(elements[GCInputLeftThumbstickButton], elementName); + break; + case SDL_GAMEPAD_BUTTON_RIGHT_STICK: + GetAppleSFSymbolsNameForElement(elements[GCInputRightThumbstickButton], elementName); + break; + case SDL_GAMEPAD_BUTTON_LEFT_SHOULDER: + GetAppleSFSymbolsNameForElement(elements[GCInputLeftShoulder], elementName); + break; + case SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER: + GetAppleSFSymbolsNameForElement(elements[GCInputRightShoulder], elementName); + break; + case SDL_GAMEPAD_BUTTON_DPAD_UP: + { + GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller); + if (dpad) { + GetAppleSFSymbolsNameForElement(dpad.up, elementName); + if (SDL_strlen(elementName) == 0) { + SDL_strlcpy(elementName, "dpad.up.fill", sizeof(elementName)); + } + } + break; + } + case SDL_GAMEPAD_BUTTON_DPAD_DOWN: + { + GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller); + if (dpad) { + GetAppleSFSymbolsNameForElement(dpad.down, elementName); + if (SDL_strlen(elementName) == 0) { + SDL_strlcpy(elementName, "dpad.down.fill", sizeof(elementName)); + } + } + break; + } + case SDL_GAMEPAD_BUTTON_DPAD_LEFT: + { + GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller); + if (dpad) { + GetAppleSFSymbolsNameForElement(dpad.left, elementName); + if (SDL_strlen(elementName) == 0) { + SDL_strlcpy(elementName, "dpad.left.fill", sizeof(elementName)); + } + } + break; + } + case SDL_GAMEPAD_BUTTON_DPAD_RIGHT: + { + GCControllerDirectionPad *dpad = GetDirectionalPadForController(controller); + if (dpad) { + GetAppleSFSymbolsNameForElement(dpad.right, elementName); + if (SDL_strlen(elementName) == 0) { + SDL_strlcpy(elementName, "dpad.right.fill", sizeof(elementName)); + } + } + break; + } + case SDL_GAMEPAD_BUTTON_MISC1: + GetAppleSFSymbolsNameForElement(elements[GCInputDualShockTouchpadButton], elementName); + break; + case SDL_GAMEPAD_BUTTON_RIGHT_PADDLE1: + GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleOne], elementName); + break; + case SDL_GAMEPAD_BUTTON_LEFT_PADDLE1: + GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleThree], elementName); + break; + case SDL_GAMEPAD_BUTTON_RIGHT_PADDLE2: + GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleTwo], elementName); + break; + case SDL_GAMEPAD_BUTTON_LEFT_PADDLE2: + GetAppleSFSymbolsNameForElement(elements[GCInputXboxPaddleFour], elementName); + break; + case SDL_GAMEPAD_BUTTON_TOUCHPAD: + GetAppleSFSymbolsNameForElement(elements[GCInputDualShockTouchpadButton], elementName); + break; + default: + break; + } + } + } +#endif // SDL_JOYSTICK_MFI + + return *elementName ? SDL_GetPersistentString(elementName) : NULL; +} + +const char *IOS_GetAppleSFSymbolsNameForAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis) +{ + char elementName[256]; + elementName[0] = '\0'; + +#ifdef SDL_JOYSTICK_MFI + if (gamepad && SDL_GetGamepadJoystick(gamepad)->driver == &SDL_IOS_JoystickDriver) { + if (@available(macOS 10.16, iOS 14.0, tvOS 14.0, *)) { + GCController *controller = SDL_GetGamepadJoystick(gamepad)->hwdata->controller; + NSDictionary *elements = controller.physicalInputProfile.elements; + switch (axis) { + case SDL_GAMEPAD_AXIS_LEFTX: + GetAppleSFSymbolsNameForElement(elements[GCInputLeftThumbstick], elementName); + break; + case SDL_GAMEPAD_AXIS_LEFTY: + GetAppleSFSymbolsNameForElement(elements[GCInputLeftThumbstick], elementName); + break; + case SDL_GAMEPAD_AXIS_RIGHTX: + GetAppleSFSymbolsNameForElement(elements[GCInputRightThumbstick], elementName); + break; + case SDL_GAMEPAD_AXIS_RIGHTY: + GetAppleSFSymbolsNameForElement(elements[GCInputRightThumbstick], elementName); + break; + case SDL_GAMEPAD_AXIS_LEFT_TRIGGER: + GetAppleSFSymbolsNameForElement(elements[GCInputLeftTrigger], elementName); + break; + case SDL_GAMEPAD_AXIS_RIGHT_TRIGGER: + GetAppleSFSymbolsNameForElement(elements[GCInputRightTrigger], elementName); + break; + default: + break; + } + } + } +#endif // SDL_JOYSTICK_MFI + + return *elementName ? SDL_GetPersistentString(elementName) : NULL; +} + +SDL_JoystickDriver SDL_IOS_JoystickDriver = { + IOS_JoystickInit, + IOS_JoystickGetCount, + IOS_JoystickDetect, + IOS_JoystickIsDevicePresent, + IOS_JoystickGetDeviceName, + IOS_JoystickGetDevicePath, + IOS_JoystickGetDeviceSteamVirtualGamepadSlot, + IOS_JoystickGetDevicePlayerIndex, + IOS_JoystickSetDevicePlayerIndex, + IOS_JoystickGetDeviceGUID, + IOS_JoystickGetDeviceInstanceID, + IOS_JoystickOpen, + IOS_JoystickRumble, + IOS_JoystickRumbleTriggers, + IOS_JoystickSetLED, + IOS_JoystickSendEffect, + IOS_JoystickSetSensorsEnabled, + IOS_JoystickUpdate, + IOS_JoystickClose, + IOS_JoystickQuit, + IOS_JoystickGetGamepadMapping +}; diff --git a/thirdparty/sdl/joystick/apple/SDL_mfijoystick_c.h b/thirdparty/sdl/joystick/apple/SDL_mfijoystick_c.h new file mode 100644 index 00000000000..783b3f488c9 --- /dev/null +++ b/thirdparty/sdl/joystick/apple/SDL_mfijoystick_c.h @@ -0,0 +1,73 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_JOYSTICK_IOS_H +#define SDL_JOYSTICK_IOS_H + +#include "../SDL_sysjoystick.h" + +#import +#import + +@class GCController; + +typedef struct joystick_hwdata +{ + GCController __unsafe_unretained *controller; + void *rumble; + int pause_button_index; + Uint64 pause_button_pressed; + + char *name; + SDL_Joystick *joystick; + SDL_JoystickID instance_id; + SDL_GUID guid; + + int naxes; + int nbuttons; + int nhats; + Uint32 button_mask; + bool is_xbox; + bool is_ps4; + bool is_ps5; + bool is_switch_pro; + bool is_switch_joycon_pair; + bool is_switch_joyconL; + bool is_switch_joyconR; + bool is_stadia; + bool is_backbone_one; + int is_siri_remote; + + NSArray __unsafe_unretained *axes; + NSArray __unsafe_unretained *buttons; + + bool has_dualshock_touchpad; + bool has_xbox_paddles; + bool has_xbox_share_button; + bool has_nintendo_buttons; + + struct joystick_hwdata *next; +} joystick_hwdata; + +typedef joystick_hwdata SDL_JoystickDeviceItem; + +#endif // SDL_JOYSTICK_IOS_H diff --git a/thirdparty/sdl/joystick/controller_list.h b/thirdparty/sdl/joystick/controller_list.h new file mode 100644 index 00000000000..5a62ece1c37 --- /dev/null +++ b/thirdparty/sdl/joystick/controller_list.h @@ -0,0 +1,609 @@ +/* + Copyright (C) Valve Corporation + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#define MAKE_CONTROLLER_ID( nVID, nPID ) (unsigned int)( (unsigned int)nVID << 16 | (unsigned int)nPID ) + +static const ControllerDescription_t arrControllers[] = { + { MAKE_CONTROLLER_ID( 0x0079, 0x181a ), k_eControllerType_PS3Controller, NULL }, // Venom Arcade Stick + { MAKE_CONTROLLER_ID( 0x0079, 0x1844 ), k_eControllerType_PS3Controller, NULL }, // From SDL + { MAKE_CONTROLLER_ID( 0x044f, 0xb315 ), k_eControllerType_PS3Controller, NULL }, // Firestorm Dual Analog 3 + { MAKE_CONTROLLER_ID( 0x044f, 0xd007 ), k_eControllerType_PS3Controller, NULL }, // Thrustmaster wireless 3-1 + { MAKE_CONTROLLER_ID( 0x046d, 0xcad1 ), k_eControllerType_PS3Controller, NULL }, // Logitech Chillstream + //{ MAKE_CONTROLLER_ID( 0x046d, 0xc24f ), k_eControllerType_PS3Controller, NULL }, // Logitech G29 (PS3) + { MAKE_CONTROLLER_ID( 0x054c, 0x0268 ), k_eControllerType_PS3Controller, NULL }, // Sony PS3 Controller + { MAKE_CONTROLLER_ID( 0x056e, 0x200f ), k_eControllerType_PS3Controller, NULL }, // From SDL + { MAKE_CONTROLLER_ID( 0x056e, 0x2013 ), k_eControllerType_PS3Controller, NULL }, // JC-U4113SBK + { MAKE_CONTROLLER_ID( 0x05b8, 0x1004 ), k_eControllerType_PS3Controller, NULL }, // From SDL + { MAKE_CONTROLLER_ID( 0x05b8, 0x1006 ), k_eControllerType_PS3Controller, NULL }, // JC-U3412SBK + { MAKE_CONTROLLER_ID( 0x06a3, 0xf622 ), k_eControllerType_PS3Controller, NULL }, // Cyborg V3 + { MAKE_CONTROLLER_ID( 0x0738, 0x3180 ), k_eControllerType_PS3Controller, NULL }, // Mad Catz Alpha PS3 mode + { MAKE_CONTROLLER_ID( 0x0738, 0x3250 ), k_eControllerType_PS3Controller, NULL }, // madcats fightpad pro ps3 + { MAKE_CONTROLLER_ID( 0x0738, 0x3481 ), k_eControllerType_PS3Controller, NULL }, // Mad Catz FightStick TE 2+ PS3 + { MAKE_CONTROLLER_ID( 0x0738, 0x8180 ), k_eControllerType_PS3Controller, NULL }, // Mad Catz Alpha PS4 mode (no touchpad on device) + { MAKE_CONTROLLER_ID( 0x0738, 0x8838 ), k_eControllerType_PS3Controller, NULL }, // Madcatz Fightstick Pro + { MAKE_CONTROLLER_ID( 0x0810, 0x0001 ), k_eControllerType_PS3Controller, NULL }, // actually ps2 - maybe break out later + { MAKE_CONTROLLER_ID( 0x0810, 0x0003 ), k_eControllerType_PS3Controller, NULL }, // actually ps2 - maybe break out later + { MAKE_CONTROLLER_ID( 0x0925, 0x0005 ), k_eControllerType_PS3Controller, NULL }, // Sony PS3 Controller + { MAKE_CONTROLLER_ID( 0x0925, 0x8866 ), k_eControllerType_PS3Controller, NULL }, // PS2 maybe break out later + { MAKE_CONTROLLER_ID( 0x0925, 0x8888 ), k_eControllerType_PS3Controller, NULL }, // Actually ps2 -maybe break out later Lakeview Research WiseGroup Ltd, MP-8866 Dual Joypad + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0109 ), k_eControllerType_PS3Controller, NULL }, // PDP Versus Fighting Pad + { MAKE_CONTROLLER_ID( 0x0e6f, 0x011e ), k_eControllerType_PS3Controller, NULL }, // Rock Candy PS4 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0128 ), k_eControllerType_PS3Controller, NULL }, // Rock Candy PS3 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0214 ), k_eControllerType_PS3Controller, NULL }, // afterglow ps3 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x1314 ), k_eControllerType_PS3Controller, NULL }, // PDP Afterglow Wireless PS3 controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x6302 ), k_eControllerType_PS3Controller, NULL }, // From SDL + { MAKE_CONTROLLER_ID( 0x0e8f, 0x0008 ), k_eControllerType_PS3Controller, NULL }, // Green Asia + { MAKE_CONTROLLER_ID( 0x0e8f, 0x3075 ), k_eControllerType_PS3Controller, NULL }, // SpeedLink Strike FX + { MAKE_CONTROLLER_ID( 0x0e8f, 0x310d ), k_eControllerType_PS3Controller, NULL }, // From SDL + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0009 ), k_eControllerType_PS3Controller, NULL }, // HORI BDA GP1 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x004d ), k_eControllerType_PS3Controller, NULL }, // Horipad 3 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x005f ), k_eControllerType_PS3Controller, NULL }, // HORI Fighting Commander 4 PS3 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x006a ), k_eControllerType_PS3Controller, NULL }, // Real Arcade Pro 4 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x006e ), k_eControllerType_PS3Controller, NULL }, // HORI horipad4 ps3 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0085 ), k_eControllerType_PS3Controller, NULL }, // HORI Fighting Commander PS3 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0086 ), k_eControllerType_PS3Controller, NULL }, // HORI Fighting Commander PC (Uses the Xbox 360 protocol, but has PS3 buttons) + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0088 ), k_eControllerType_PS3Controller, NULL }, // HORI Fighting Stick mini 4 + { MAKE_CONTROLLER_ID( 0x0f30, 0x1100 ), k_eControllerType_PS3Controller, NULL }, // Qanba Q1 fight stick + { MAKE_CONTROLLER_ID( 0x11ff, 0x3331 ), k_eControllerType_PS3Controller, NULL }, // SRXJ-PH2400 + { MAKE_CONTROLLER_ID( 0x1345, 0x1000 ), k_eControllerType_PS3Controller, NULL }, // PS2 ACME GA-D5 + { MAKE_CONTROLLER_ID( 0x1345, 0x6005 ), k_eControllerType_PS3Controller, NULL }, // ps2 maybe break out later + { MAKE_CONTROLLER_ID( 0x146b, 0x5500 ), k_eControllerType_PS3Controller, NULL }, // From SDL + { MAKE_CONTROLLER_ID( 0x1a34, 0x0836 ), k_eControllerType_PS3Controller, NULL }, // Afterglow PS3 + { MAKE_CONTROLLER_ID( 0x20bc, 0x5500 ), k_eControllerType_PS3Controller, NULL }, // ShanWan PS3 + { MAKE_CONTROLLER_ID( 0x20d6, 0x576d ), k_eControllerType_PS3Controller, NULL }, // Power A PS3 + { MAKE_CONTROLLER_ID( 0x20d6, 0xca6d ), k_eControllerType_PS3Controller, NULL }, // BDA Pro Ex + { MAKE_CONTROLLER_ID( 0x2563, 0x0523 ), k_eControllerType_PS3Controller, NULL }, // Digiflip GP006 + { MAKE_CONTROLLER_ID( 0x2563, 0x0575 ), k_eControllerType_PS3Controller, "Retro-bit Controller" }, // SWITCH CO., LTD. Retro-bit Controller + { MAKE_CONTROLLER_ID( 0x25f0, 0x83c3 ), k_eControllerType_PS3Controller, NULL }, // gioteck vx2 + { MAKE_CONTROLLER_ID( 0x25f0, 0xc121 ), k_eControllerType_PS3Controller, NULL }, // + { MAKE_CONTROLLER_ID( 0x2c22, 0x2003 ), k_eControllerType_PS3Controller, NULL }, // Qanba Drone + { MAKE_CONTROLLER_ID( 0x2c22, 0x2302 ), k_eControllerType_PS3Controller, NULL }, // Qanba Obsidian + { MAKE_CONTROLLER_ID( 0x2c22, 0x2502 ), k_eControllerType_PS3Controller, NULL }, // Qanba Dragon + { MAKE_CONTROLLER_ID( 0x8380, 0x0003 ), k_eControllerType_PS3Controller, NULL }, // BTP 2163 + { MAKE_CONTROLLER_ID( 0x8888, 0x0308 ), k_eControllerType_PS3Controller, NULL }, // Sony PS3 Controller + + { MAKE_CONTROLLER_ID( 0x0079, 0x181b ), k_eControllerType_PS4Controller, NULL }, // Venom Arcade Stick - XXX:this may not work and may need to be called a ps3 controller + //{ MAKE_CONTROLLER_ID( 0x046d, 0xc260 ), k_eControllerType_PS4Controller, NULL }, // Logitech G29 (PS4) + { MAKE_CONTROLLER_ID( 0x044f, 0xd00e ), k_eControllerType_PS4Controller, NULL }, // Thrustmaster Eswap Pro - No gyro and lightbar doesn't change color. Works otherwise + { MAKE_CONTROLLER_ID( 0x054c, 0x05c4 ), k_eControllerType_PS4Controller, NULL }, // Sony PS4 Controller + { MAKE_CONTROLLER_ID( 0x054c, 0x05c5 ), k_eControllerType_PS4Controller, NULL }, // STRIKEPAD PS4 Grip Add-on + { MAKE_CONTROLLER_ID( 0x054c, 0x09cc ), k_eControllerType_PS4Controller, NULL }, // Sony PS4 Slim Controller + { MAKE_CONTROLLER_ID( 0x054c, 0x0ba0 ), k_eControllerType_PS4Controller, NULL }, // Sony PS4 Controller (Wireless dongle) + { MAKE_CONTROLLER_ID( 0x0738, 0x8250 ), k_eControllerType_PS4Controller, NULL }, // Mad Catz FightPad Pro PS4 + { MAKE_CONTROLLER_ID( 0x0738, 0x8384 ), k_eControllerType_PS4Controller, NULL }, // Mad Catz FightStick TE S+ PS4 + { MAKE_CONTROLLER_ID( 0x0738, 0x8480 ), k_eControllerType_PS4Controller, NULL }, // Mad Catz FightStick TE 2 PS4 + { MAKE_CONTROLLER_ID( 0x0738, 0x8481 ), k_eControllerType_PS4Controller, NULL }, // Mad Catz FightStick TE 2+ PS4 + { MAKE_CONTROLLER_ID( 0x0c12, 0x0e10 ), k_eControllerType_PS4Controller, NULL }, // Armor Armor 3 Pad PS4 + { MAKE_CONTROLLER_ID( 0x0c12, 0x0e13 ), k_eControllerType_PS4Controller, NULL }, // ZEROPLUS P4 Wired Gamepad + { MAKE_CONTROLLER_ID( 0x0c12, 0x0e15 ), k_eControllerType_PS4Controller, NULL }, // Game:Pad 4 + { MAKE_CONTROLLER_ID( 0x0c12, 0x0e20 ), k_eControllerType_PS4Controller, NULL }, // Brook Mars Controller - needs FW update to show up as Ps4 controller on PC. Has Gyro but touchpad is a single button. + { MAKE_CONTROLLER_ID( 0x0c12, 0x0ef6 ), k_eControllerType_PS4Controller, NULL }, // Hitbox Arcade Stick + { MAKE_CONTROLLER_ID( 0x0c12, 0x1cf6 ), k_eControllerType_PS4Controller, NULL }, // EMIO PS4 Elite Controller + { MAKE_CONTROLLER_ID( 0x0c12, 0x1e10 ), k_eControllerType_PS4Controller, NULL }, // P4 Wired Gamepad generic knock off - lightbar but not trackpad or gyro + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0203 ), k_eControllerType_PS4Controller, NULL }, // Victrix Pro FS (PS4 peripheral but no trackpad/lightbar) + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0207 ), k_eControllerType_PS4Controller, NULL }, // Victrix Pro FS V2 w/ Touchpad for PS4 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x020a ), k_eControllerType_PS4Controller, NULL }, // Victrix Pro FS PS4/PS5 (PS4 mode) + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0055 ), k_eControllerType_PS4Controller, NULL }, // HORIPAD 4 FPS + { MAKE_CONTROLLER_ID( 0x0f0d, 0x005e ), k_eControllerType_PS4Controller, NULL }, // HORI Fighting Commander 4 PS4 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0066 ), k_eControllerType_PS4Controller, NULL }, // HORIPAD 4 FPS Plus + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0084 ), k_eControllerType_PS4Controller, NULL }, // HORI Fighting Commander PS4 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0087 ), k_eControllerType_PS4Controller, NULL }, // HORI Fighting Stick mini 4 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x008a ), k_eControllerType_PS4Controller, NULL }, // HORI Real Arcade Pro 4 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x009c ), k_eControllerType_PS4Controller, NULL }, // HORI TAC PRO mousething + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00a0 ), k_eControllerType_PS4Controller, NULL }, // HORI TAC4 mousething + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00ed ), k_eControllerType_XInputPS4Controller, NULL }, // Hori Fighting Stick mini 4 kai - becomes an Xbox 360 controller on PC + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00ee ), k_eControllerType_PS4Controller, NULL }, // Hori mini wired https://www.playstation.com/en-us/explore/accessories/gaming-controllers/mini-wired-gamepad/ + { MAKE_CONTROLLER_ID( 0x0f0d, 0x011c ), k_eControllerType_PS4Controller, NULL }, // Hori Fighting Stick α + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0123 ), k_eControllerType_PS4Controller, NULL }, // HORI Wireless Controller Light (Japan only) - only over bt- over usb is xbox and pid 0x0124 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0162 ), k_eControllerType_PS4Controller, NULL }, // HORI Fighting Commander OCTA + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0164 ), k_eControllerType_XInputPS4Controller, NULL }, // HORI Fighting Commander OCTA + { MAKE_CONTROLLER_ID( 0x11c0, 0x4001 ), k_eControllerType_PS4Controller, NULL }, // "PS4 Fun Controller" added from user log + { MAKE_CONTROLLER_ID( 0x146b, 0x0603 ), k_eControllerType_XInputPS4Controller, NULL }, // Nacon PS4 Compact Controller + { MAKE_CONTROLLER_ID( 0x146b, 0x0604 ), k_eControllerType_XInputPS4Controller, NULL }, // NACON Daija Arcade Stick + { MAKE_CONTROLLER_ID( 0x146b, 0x0605 ), k_eControllerType_XInputPS4Controller, NULL }, // NACON PS4 controller in Xbox mode - might also be other bigben brand xbox controllers + { MAKE_CONTROLLER_ID( 0x146b, 0x0606 ), k_eControllerType_XInputPS4Controller, NULL }, // NACON Unknown Controller + { MAKE_CONTROLLER_ID( 0x146b, 0x0609 ), k_eControllerType_XInputPS4Controller, NULL }, // NACON Wireless Controller for PS4 + { MAKE_CONTROLLER_ID( 0x146b, 0x0d01 ), k_eControllerType_PS4Controller, NULL }, // Nacon Revolution Pro Controller - has gyro + { MAKE_CONTROLLER_ID( 0x146b, 0x0d02 ), k_eControllerType_PS4Controller, NULL }, // Nacon Revolution Pro Controller v2 - has gyro + { MAKE_CONTROLLER_ID( 0x146b, 0x0d06 ), k_eControllerType_PS4Controller, NULL }, // NACON Asymmetric Controller Wireless Dongle -- show up as ps4 until you connect controller to it then it reboots into Xbox controller with different vvid/pid + { MAKE_CONTROLLER_ID( 0x146b, 0x0d08 ), k_eControllerType_PS4Controller, NULL }, // NACON Revolution Unlimited Wireless Dongle + { MAKE_CONTROLLER_ID( 0x146b, 0x0d09 ), k_eControllerType_PS4Controller, NULL }, // NACON Daija Fight Stick - touchpad but no gyro/rumble + { MAKE_CONTROLLER_ID( 0x146b, 0x0d10 ), k_eControllerType_PS4Controller, NULL }, // NACON Revolution Infinite - has gyro + { MAKE_CONTROLLER_ID( 0x146b, 0x0d10 ), k_eControllerType_PS4Controller, NULL }, // NACON Revolution Unlimited + { MAKE_CONTROLLER_ID( 0x146b, 0x0d13 ), k_eControllerType_PS4Controller, NULL }, // NACON Revolution Pro Controller 3 + { MAKE_CONTROLLER_ID( 0x146b, 0x1103 ), k_eControllerType_PS4Controller, NULL }, // NACON Asymmetric Controller -- on windows this doesn't enumerate + { MAKE_CONTROLLER_ID( 0x1532, 0X0401 ), k_eControllerType_PS4Controller, NULL }, // Razer Panthera PS4 Controller + { MAKE_CONTROLLER_ID( 0x1532, 0x1000 ), k_eControllerType_PS4Controller, NULL }, // Razer Raiju PS4 Controller + { MAKE_CONTROLLER_ID( 0x1532, 0x1004 ), k_eControllerType_PS4Controller, NULL }, // Razer Raiju 2 Ultimate USB + { MAKE_CONTROLLER_ID( 0x1532, 0x1007 ), k_eControllerType_PS4Controller, NULL }, // Razer Raiju 2 Tournament edition USB + { MAKE_CONTROLLER_ID( 0x1532, 0x1008 ), k_eControllerType_PS4Controller, NULL }, // Razer Panthera Evo Fightstick + { MAKE_CONTROLLER_ID( 0x1532, 0x1009 ), k_eControllerType_PS4Controller, NULL }, // Razer Raiju 2 Ultimate BT + { MAKE_CONTROLLER_ID( 0x1532, 0x100A ), k_eControllerType_PS4Controller, NULL }, // Razer Raiju 2 Tournament edition BT + { MAKE_CONTROLLER_ID( 0x1532, 0x1100 ), k_eControllerType_PS4Controller, NULL }, // Razer RAION Fightpad - Trackpad, no gyro, lightbar hardcoded to green + { MAKE_CONTROLLER_ID( 0x20d6, 0x792a ), k_eControllerType_PS4Controller, NULL }, // PowerA Fusion Fight Pad + { MAKE_CONTROLLER_ID( 0x2c22, 0x2000 ), k_eControllerType_PS4Controller, NULL }, // Qanba Drone + { MAKE_CONTROLLER_ID( 0x2c22, 0x2300 ), k_eControllerType_PS4Controller, NULL }, // Qanba Obsidian + { MAKE_CONTROLLER_ID( 0x2c22, 0x2303 ), k_eControllerType_XInputPS4Controller, NULL }, // Qanba Obsidian Arcade Joystick + { MAKE_CONTROLLER_ID( 0x2c22, 0x2500 ), k_eControllerType_PS4Controller, NULL }, // Qanba Dragon + { MAKE_CONTROLLER_ID( 0x2c22, 0x2503 ), k_eControllerType_XInputPS4Controller, NULL }, // Qanba Dragon Arcade Joystick + { MAKE_CONTROLLER_ID( 0x3285, 0x0d16 ), k_eControllerType_PS4Controller, NULL }, // NACON Revolution 5 Pro (PS4 mode with dongle) + { MAKE_CONTROLLER_ID( 0x3285, 0x0d17 ), k_eControllerType_PS4Controller, NULL }, // NACON Revolution 5 Pro (PS4 mode wired) + { MAKE_CONTROLLER_ID( 0x7545, 0x0104 ), k_eControllerType_PS4Controller, NULL }, // Armor 3 or Level Up Cobra - At least one variant has gyro + { MAKE_CONTROLLER_ID (0x9886, 0x0024 ), k_eControllerType_XInputPS4Controller, NULL }, // Astro C40 in Xbox 360 mode + { MAKE_CONTROLLER_ID( 0x9886, 0x0025 ), k_eControllerType_PS4Controller, NULL }, // Astro C40 + // Removing the Giotek because there were a bunch of help tickets from users w/ issues including from non-PS4 controller users. This VID/PID is probably used in different FW's +// { MAKE_CONTROLLER_ID( 0x7545, 0x1122 ), k_eControllerType_PS4Controller, NULL }, // Giotek VX4 - trackpad/gyro don't work. Had to not filter on interface info. Light bar is flaky, but works. + + { MAKE_CONTROLLER_ID( 0x054c, 0x0ce6 ), k_eControllerType_PS5Controller, NULL }, // Sony DualSense Controller + { MAKE_CONTROLLER_ID( 0x054c, 0x0df2 ), k_eControllerType_PS5Controller, NULL }, // Sony DualSense Edge Controller + { MAKE_CONTROLLER_ID( 0x054c, 0x0e5f ), k_eControllerType_PS5Controller, NULL }, // Access Controller for PS5 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0209 ), k_eControllerType_PS5Controller, NULL }, // Victrix Pro FS PS4/PS5 (PS5 mode) + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0163 ), k_eControllerType_PS5Controller, NULL }, // HORI Fighting Commander OCTA + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0184 ), k_eControllerType_PS5Controller, NULL }, // Hori Fighting Stick α + { MAKE_CONTROLLER_ID( 0x1532, 0x100b ), k_eControllerType_PS5Controller, NULL }, // Razer Wolverine V2 Pro (Wired) + { MAKE_CONTROLLER_ID( 0x1532, 0x100c ), k_eControllerType_PS5Controller, NULL }, // Razer Wolverine V2 Pro (Wireless) + { MAKE_CONTROLLER_ID( 0x1532, 0x1012 ), k_eControllerType_PS5Controller, NULL }, // Razer Kitsune + { MAKE_CONTROLLER_ID( 0x3285, 0x0d18 ), k_eControllerType_PS5Controller, NULL }, // NACON Revolution 5 Pro (PS5 mode with dongle) + { MAKE_CONTROLLER_ID( 0x3285, 0x0d19 ), k_eControllerType_PS5Controller, NULL }, // NACON Revolution 5 Pro (PS5 mode wired) + { MAKE_CONTROLLER_ID( 0x358a, 0x0104 ), k_eControllerType_PS5Controller, NULL }, // Backbone One PlayStation Edition for iOS + + { MAKE_CONTROLLER_ID( 0x0079, 0x0006 ), k_eControllerType_UnknownNonSteamController, NULL }, // DragonRise Generic USB PCB, sometimes configured as a PC Twin Shock Controller - looks like a DS3 but the face buttons are 1-4 instead of symbols + + { MAKE_CONTROLLER_ID( 0x0079, 0x18d4 ), k_eControllerType_XBox360Controller, NULL }, // GPD Win 2 X-Box Controller + { MAKE_CONTROLLER_ID( 0x03eb, 0xff02 ), k_eControllerType_XBox360Controller, NULL }, // Wooting Two + { MAKE_CONTROLLER_ID( 0x044f, 0xb326 ), k_eControllerType_XBox360Controller, NULL }, // Thrustmaster Gamepad GP XID + { MAKE_CONTROLLER_ID( 0x045e, 0x028e ), k_eControllerType_XBox360Controller, "Xbox 360 Controller" }, // Microsoft Xbox 360 Wired Controller + { MAKE_CONTROLLER_ID( 0x045e, 0x028f ), k_eControllerType_XBox360Controller, "Xbox 360 Controller" }, // Microsoft Xbox 360 Play and Charge Cable + { MAKE_CONTROLLER_ID( 0x045e, 0x0291 ), k_eControllerType_XBox360Controller, "Xbox 360 Wireless Controller" }, // X-box 360 Wireless Receiver (third party knockoff) + { MAKE_CONTROLLER_ID( 0x045e, 0x02a0 ), k_eControllerType_XBox360Controller, NULL }, // Microsoft Xbox 360 Big Button IR + { MAKE_CONTROLLER_ID( 0x045e, 0x02a1 ), k_eControllerType_XBox360Controller, "Xbox 360 Wireless Controller" }, // Microsoft Xbox 360 Wireless Controller with XUSB driver on Windows + { MAKE_CONTROLLER_ID( 0x045e, 0x02a9 ), k_eControllerType_XBox360Controller, "Xbox 360 Wireless Controller" }, // X-box 360 Wireless Receiver (third party knockoff) + { MAKE_CONTROLLER_ID( 0x045e, 0x0719 ), k_eControllerType_XBox360Controller, "Xbox 360 Wireless Controller" }, // Microsoft Xbox 360 Wireless Receiver + { MAKE_CONTROLLER_ID( 0x046d, 0xc21d ), k_eControllerType_XBox360Controller, NULL }, // Logitech Gamepad F310 + { MAKE_CONTROLLER_ID( 0x046d, 0xc21e ), k_eControllerType_XBox360Controller, NULL }, // Logitech Gamepad F510 + { MAKE_CONTROLLER_ID( 0x046d, 0xc21f ), k_eControllerType_XBox360Controller, NULL }, // Logitech Gamepad F710 + { MAKE_CONTROLLER_ID( 0x046d, 0xc242 ), k_eControllerType_XBox360Controller, NULL }, // Logitech Chillstream Controller + { MAKE_CONTROLLER_ID( 0x056e, 0x2004 ), k_eControllerType_XBox360Controller, NULL }, // Elecom JC-U3613M +// This isn't actually an Xbox 360 controller, it just looks like one +// { MAKE_CONTROLLER_ID( 0x06a3, 0xf51a ), k_eControllerType_XBox360Controller, NULL }, // Saitek P3600 + { MAKE_CONTROLLER_ID( 0x0738, 0x4716 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Wired Xbox 360 Controller + { MAKE_CONTROLLER_ID( 0x0738, 0x4718 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Street Fighter IV FightStick SE + { MAKE_CONTROLLER_ID( 0x0738, 0x4726 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Xbox 360 Controller + { MAKE_CONTROLLER_ID( 0x0738, 0x4728 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Street Fighter IV FightPad + { MAKE_CONTROLLER_ID( 0x0738, 0x4736 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz MicroCon Gamepad + { MAKE_CONTROLLER_ID( 0x0738, 0x4738 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Wired Xbox 360 Controller (SFIV) + { MAKE_CONTROLLER_ID( 0x0738, 0x4740 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Beat Pad + { MAKE_CONTROLLER_ID( 0x0738, 0xb726 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Xbox controller - MW2 + { MAKE_CONTROLLER_ID( 0x0738, 0xbeef ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz JOYTECH NEO SE Advanced GamePad + { MAKE_CONTROLLER_ID( 0x0738, 0xcb02 ), k_eControllerType_XBox360Controller, NULL }, // Saitek Cyborg Rumble Pad - PC/Xbox 360 + { MAKE_CONTROLLER_ID( 0x0738, 0xcb03 ), k_eControllerType_XBox360Controller, NULL }, // Saitek P3200 Rumble Pad - PC/Xbox 360 + { MAKE_CONTROLLER_ID( 0x0738, 0xf738 ), k_eControllerType_XBox360Controller, NULL }, // Super SFIV FightStick TE S + { MAKE_CONTROLLER_ID( 0x0955, 0x7210 ), k_eControllerType_XBox360Controller, NULL }, // Nvidia Shield local controller + { MAKE_CONTROLLER_ID( 0x0955, 0xb400 ), k_eControllerType_XBox360Controller, NULL }, // NVIDIA Shield streaming controller + { MAKE_CONTROLLER_ID( 0x0b05, 0x1b4c ), k_eControllerType_XBox360Controller, NULL }, // ASUS ROG Ally X built-in controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0105 ), k_eControllerType_XBox360Controller, NULL }, // HSM3 Xbox360 dancepad + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0113 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Afterglow" }, // PDP Afterglow Gamepad for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x011f ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Rock Candy" }, // PDP Rock Candy Gamepad for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0125 ), k_eControllerType_XBox360Controller, "PDP INJUSTICE FightStick" }, // PDP INJUSTICE FightStick for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0127 ), k_eControllerType_XBox360Controller, "PDP INJUSTICE FightPad" }, // PDP INJUSTICE FightPad for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0131 ), k_eControllerType_XBox360Controller, "PDP EA Soccer Controller" }, // PDP EA Soccer Gamepad + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0133 ), k_eControllerType_XBox360Controller, "PDP Battlefield 4 Controller" }, // PDP Battlefield 4 Gamepad + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0143 ), k_eControllerType_XBox360Controller, "PDP MK X Fight Stick" }, // PDP MK X Fight Stick for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0147 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Marvel Controller" }, // PDP Marvel Controller for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0201 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Controller" }, // PDP Gamepad for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0213 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Afterglow" }, // PDP Afterglow Gamepad for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x021f ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Rock Candy" }, // PDP Rock Candy Gamepad for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0301 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Controller" }, // PDP Gamepad for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0313 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Afterglow" }, // PDP Afterglow Gamepad for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0314 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Afterglow" }, // PDP Afterglow Gamepad for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0401 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Controller" }, // PDP Gamepad for Xbox 360 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0413 ), k_eControllerType_XBox360Controller, NULL }, // PDP Afterglow AX.1 (unlisted) + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0501 ), k_eControllerType_XBox360Controller, NULL }, // PDP Xbox 360 Controller (unlisted) + { MAKE_CONTROLLER_ID( 0x0e6f, 0xf900 ), k_eControllerType_XBox360Controller, NULL }, // PDP Afterglow AX.1 (unlisted) + { MAKE_CONTROLLER_ID( 0x0f0d, 0x000a ), k_eControllerType_XBox360Controller, NULL }, // Hori Co. DOA4 FightStick + { MAKE_CONTROLLER_ID( 0x0f0d, 0x000c ), k_eControllerType_XBox360Controller, NULL }, // Hori PadEX Turbo + { MAKE_CONTROLLER_ID( 0x0f0d, 0x000d ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Stick EX2 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0016 ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro.EX + { MAKE_CONTROLLER_ID( 0x0f0d, 0x001b ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro VX + { MAKE_CONTROLLER_ID( 0x0f0d, 0x008c ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro 4 + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00db ), k_eControllerType_XBox360Controller, "HORI Slime Controller" }, // Hori Dragon Quest Slime Controller + { MAKE_CONTROLLER_ID( 0x0f0d, 0x011e ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Stick α + { MAKE_CONTROLLER_ID( 0x1038, 0x1430 ), k_eControllerType_XBox360Controller, "SteelSeries Stratus Duo" }, // SteelSeries Stratus Duo + { MAKE_CONTROLLER_ID( 0x1038, 0x1431 ), k_eControllerType_XBox360Controller, "SteelSeries Stratus Duo" }, // SteelSeries Stratus Duo + { MAKE_CONTROLLER_ID( 0x1038, 0xb360 ), k_eControllerType_XBox360Controller, NULL }, // SteelSeries Nimbus/Stratus XL + { MAKE_CONTROLLER_ID( 0x11c9, 0x55f0 ), k_eControllerType_XBox360Controller, NULL }, // Nacon GC-100XF + { MAKE_CONTROLLER_ID( 0x12ab, 0x0004 ), k_eControllerType_XBox360Controller, NULL }, // Honey Bee Xbox360 dancepad + { MAKE_CONTROLLER_ID( 0x12ab, 0x0301 ), k_eControllerType_XBox360Controller, NULL }, // PDP AFTERGLOW AX.1 + { MAKE_CONTROLLER_ID( 0x12ab, 0x0303 ), k_eControllerType_XBox360Controller, NULL }, // Mortal Kombat Klassic FightStick + { MAKE_CONTROLLER_ID( 0x1430, 0x02a0 ), k_eControllerType_XBox360Controller, NULL }, // RedOctane Controller Adapter + { MAKE_CONTROLLER_ID( 0x1430, 0x4748 ), k_eControllerType_XBox360Controller, NULL }, // RedOctane Guitar Hero X-plorer + { MAKE_CONTROLLER_ID( 0x1430, 0xf801 ), k_eControllerType_XBox360Controller, NULL }, // RedOctane Controller + { MAKE_CONTROLLER_ID( 0x146b, 0x0601 ), k_eControllerType_XBox360Controller, NULL }, // BigBen Interactive XBOX 360 Controller +// { MAKE_CONTROLLER_ID( 0x1532, 0x0037 ), k_eControllerType_XBox360Controller, NULL }, // Razer Sabertooth + { MAKE_CONTROLLER_ID( 0x15e4, 0x3f00 ), k_eControllerType_XBox360Controller, NULL }, // Power A Mini Pro Elite + { MAKE_CONTROLLER_ID( 0x15e4, 0x3f0a ), k_eControllerType_XBox360Controller, NULL }, // Xbox Airflo wired controller + { MAKE_CONTROLLER_ID( 0x15e4, 0x3f10 ), k_eControllerType_XBox360Controller, NULL }, // Batarang Xbox 360 controller + { MAKE_CONTROLLER_ID( 0x162e, 0xbeef ), k_eControllerType_XBox360Controller, NULL }, // Joytech Neo-Se Take2 + { MAKE_CONTROLLER_ID( 0x1689, 0xfd00 ), k_eControllerType_XBox360Controller, NULL }, // Razer Onza Tournament Edition + { MAKE_CONTROLLER_ID( 0x1689, 0xfd01 ), k_eControllerType_XBox360Controller, NULL }, // Razer Onza Classic Edition + { MAKE_CONTROLLER_ID( 0x1689, 0xfe00 ), k_eControllerType_XBox360Controller, NULL }, // Razer Sabertooth + { MAKE_CONTROLLER_ID( 0x1949, 0x041a ), k_eControllerType_XBox360Controller, "Amazon Luna Controller" }, // Amazon Luna Controller + { MAKE_CONTROLLER_ID( 0x1bad, 0x0002 ), k_eControllerType_XBox360Controller, NULL }, // Harmonix Rock Band Guitar + { MAKE_CONTROLLER_ID( 0x1bad, 0x0003 ), k_eControllerType_XBox360Controller, NULL }, // Harmonix Rock Band Drumkit + { MAKE_CONTROLLER_ID( 0x1bad, 0xf016 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Xbox 360 Controller + { MAKE_CONTROLLER_ID( 0x1bad, 0xf018 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Street Fighter IV SE Fighting Stick + { MAKE_CONTROLLER_ID( 0x1bad, 0xf019 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Brawlstick for Xbox 360 + { MAKE_CONTROLLER_ID( 0x1bad, 0xf021 ), k_eControllerType_XBox360Controller, NULL }, // Mad Cats Ghost Recon FS GamePad + { MAKE_CONTROLLER_ID( 0x1bad, 0xf023 ), k_eControllerType_XBox360Controller, NULL }, // MLG Pro Circuit Controller (Xbox) + { MAKE_CONTROLLER_ID( 0x1bad, 0xf025 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Call Of Duty + { MAKE_CONTROLLER_ID( 0x1bad, 0xf027 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz FPS Pro + { MAKE_CONTROLLER_ID( 0x1bad, 0xf028 ), k_eControllerType_XBox360Controller, NULL }, // Street Fighter IV FightPad + { MAKE_CONTROLLER_ID( 0x1bad, 0xf02e ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Fightpad + { MAKE_CONTROLLER_ID( 0x1bad, 0xf036 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz MicroCon GamePad Pro + { MAKE_CONTROLLER_ID( 0x1bad, 0xf038 ), k_eControllerType_XBox360Controller, NULL }, // Street Fighter IV FightStick TE + { MAKE_CONTROLLER_ID( 0x1bad, 0xf039 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz MvC2 TE + { MAKE_CONTROLLER_ID( 0x1bad, 0xf03a ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz SFxT Fightstick Pro + { MAKE_CONTROLLER_ID( 0x1bad, 0xf03d ), k_eControllerType_XBox360Controller, NULL }, // Street Fighter IV Arcade Stick TE - Chun Li + { MAKE_CONTROLLER_ID( 0x1bad, 0xf03e ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz MLG FightStick TE + { MAKE_CONTROLLER_ID( 0x1bad, 0xf03f ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz FightStick SoulCaliber + { MAKE_CONTROLLER_ID( 0x1bad, 0xf042 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz FightStick TES+ + { MAKE_CONTROLLER_ID( 0x1bad, 0xf080 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz FightStick TE2 + { MAKE_CONTROLLER_ID( 0x1bad, 0xf501 ), k_eControllerType_XBox360Controller, NULL }, // HoriPad EX2 Turbo + { MAKE_CONTROLLER_ID( 0x1bad, 0xf502 ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro.VX SA + { MAKE_CONTROLLER_ID( 0x1bad, 0xf503 ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Stick VX + { MAKE_CONTROLLER_ID( 0x1bad, 0xf504 ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro. EX + { MAKE_CONTROLLER_ID( 0x1bad, 0xf505 ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Stick EX2B + { MAKE_CONTROLLER_ID( 0x1bad, 0xf506 ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro.EX Premium VLX + { MAKE_CONTROLLER_ID( 0x1bad, 0xf900 ), k_eControllerType_XBox360Controller, NULL }, // Harmonix Xbox 360 Controller + { MAKE_CONTROLLER_ID( 0x1bad, 0xf901 ), k_eControllerType_XBox360Controller, NULL }, // Gamestop Xbox 360 Controller + { MAKE_CONTROLLER_ID( 0x1bad, 0xf902 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Gamepad2 + { MAKE_CONTROLLER_ID( 0x1bad, 0xf903 ), k_eControllerType_XBox360Controller, NULL }, // Tron Xbox 360 controller + { MAKE_CONTROLLER_ID( 0x1bad, 0xf904 ), k_eControllerType_XBox360Controller, NULL }, // PDP Versus Fighting Pad + { MAKE_CONTROLLER_ID( 0x1bad, 0xf906 ), k_eControllerType_XBox360Controller, NULL }, // MortalKombat FightStick + { MAKE_CONTROLLER_ID( 0x1bad, 0xfa01 ), k_eControllerType_XBox360Controller, NULL }, // MadCatz GamePad + { MAKE_CONTROLLER_ID( 0x1bad, 0xfd00 ), k_eControllerType_XBox360Controller, NULL }, // Razer Onza TE + { MAKE_CONTROLLER_ID( 0x1bad, 0xfd01 ), k_eControllerType_XBox360Controller, NULL }, // Razer Onza + { MAKE_CONTROLLER_ID( 0x24c6, 0x5000 ), k_eControllerType_XBox360Controller, NULL }, // Razer Atrox Arcade Stick + { MAKE_CONTROLLER_ID( 0x24c6, 0x5300 ), k_eControllerType_XBox360Controller, NULL }, // PowerA MINI PROEX Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x5303 ), k_eControllerType_XBox360Controller, NULL }, // Xbox Airflo wired controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x530a ), k_eControllerType_XBox360Controller, NULL }, // Xbox 360 Pro EX Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x531a ), k_eControllerType_XBox360Controller, NULL }, // PowerA Pro Ex + { MAKE_CONTROLLER_ID( 0x24c6, 0x5397 ), k_eControllerType_XBox360Controller, NULL }, // FUS1ON Tournament Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x5500 ), k_eControllerType_XBox360Controller, NULL }, // Hori XBOX 360 EX 2 with Turbo + { MAKE_CONTROLLER_ID( 0x24c6, 0x5501 ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro VX-SA + { MAKE_CONTROLLER_ID( 0x24c6, 0x5502 ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Stick VX Alt + { MAKE_CONTROLLER_ID( 0x24c6, 0x5503 ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Edge + { MAKE_CONTROLLER_ID( 0x24c6, 0x5506 ), k_eControllerType_XBox360Controller, NULL }, // Hori SOULCALIBUR V Stick + { MAKE_CONTROLLER_ID( 0x24c6, 0x550d ), k_eControllerType_XBox360Controller, NULL }, // Hori GEM Xbox controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x550e ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro V Kai 360 + { MAKE_CONTROLLER_ID( 0x24c6, 0x5508 ), k_eControllerType_XBox360Controller, NULL }, // Hori PAD A + { MAKE_CONTROLLER_ID( 0x24c6, 0x5510 ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Commander ONE + { MAKE_CONTROLLER_ID( 0x24c6, 0x5b00 ), k_eControllerType_XBox360Controller, NULL }, // ThrustMaster Ferrari Italia 458 Racing Wheel + { MAKE_CONTROLLER_ID( 0x24c6, 0x5b02 ), k_eControllerType_XBox360Controller, NULL }, // Thrustmaster, Inc. GPX Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x5b03 ), k_eControllerType_XBox360Controller, NULL }, // Thrustmaster Ferrari 458 Racing Wheel + { MAKE_CONTROLLER_ID( 0x24c6, 0x5d04 ), k_eControllerType_XBox360Controller, NULL }, // Razer Sabertooth + { MAKE_CONTROLLER_ID( 0x24c6, 0xfafa ), k_eControllerType_XBox360Controller, NULL }, // Aplay Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0xfafb ), k_eControllerType_XBox360Controller, NULL }, // Aplay Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0xfafc ), k_eControllerType_XBox360Controller, NULL }, // Afterglow Gamepad 1 + { MAKE_CONTROLLER_ID( 0x24c6, 0xfafd ), k_eControllerType_XBox360Controller, NULL }, // Afterglow Gamepad 3 + { MAKE_CONTROLLER_ID( 0x24c6, 0xfafe ), k_eControllerType_XBox360Controller, NULL }, // Rock Candy Gamepad for Xbox 360 + + { MAKE_CONTROLLER_ID( 0x03f0, 0x0495 ), k_eControllerType_XBoxOneController, NULL }, // HP HyperX Clutch Gladiate + { MAKE_CONTROLLER_ID( 0x044f, 0xd012 ), k_eControllerType_XBoxOneController, NULL }, // ThrustMaster eSwap PRO Controller Xbox + { MAKE_CONTROLLER_ID( 0x045e, 0x02d1 ), k_eControllerType_XBoxOneController, "Xbox One Controller" }, // Microsoft Xbox One Controller + { MAKE_CONTROLLER_ID( 0x045e, 0x02dd ), k_eControllerType_XBoxOneController, "Xbox One Controller" }, // Microsoft Xbox One Controller (Firmware 2015) + { MAKE_CONTROLLER_ID( 0x045e, 0x02e0 ), k_eControllerType_XBoxOneController, "Xbox One S Controller" }, // Microsoft Xbox One S Controller (Bluetooth) + { MAKE_CONTROLLER_ID( 0x045e, 0x02e3 ), k_eControllerType_XBoxOneController, "Xbox One Elite Controller" }, // Microsoft Xbox One Elite Controller + { MAKE_CONTROLLER_ID( 0x045e, 0x02ea ), k_eControllerType_XBoxOneController, "Xbox One S Controller" }, // Microsoft Xbox One S Controller + { MAKE_CONTROLLER_ID( 0x045e, 0x02fd ), k_eControllerType_XBoxOneController, "Xbox One S Controller" }, // Microsoft Xbox One S Controller (Bluetooth) + { MAKE_CONTROLLER_ID( 0x045e, 0x02ff ), k_eControllerType_XBoxOneController, "Xbox One Controller" }, // Microsoft Xbox One Controller with XBOXGIP driver on Windows + { MAKE_CONTROLLER_ID( 0x045e, 0x0b00 ), k_eControllerType_XBoxOneController, "Xbox One Elite 2 Controller" }, // Microsoft Xbox One Elite Series 2 Controller + { MAKE_CONTROLLER_ID( 0x045e, 0x0b05 ), k_eControllerType_XBoxOneController, "Xbox One Elite 2 Controller" }, // Microsoft Xbox One Elite Series 2 Controller (Bluetooth) + { MAKE_CONTROLLER_ID( 0x045e, 0x0b0a ), k_eControllerType_XBoxOneController, "Xbox Adaptive Controller" }, // Microsoft Xbox Adaptive Controller + { MAKE_CONTROLLER_ID( 0x045e, 0x0b0c ), k_eControllerType_XBoxOneController, "Xbox Adaptive Controller" }, // Microsoft Xbox Adaptive Controller (Bluetooth) + { MAKE_CONTROLLER_ID( 0x045e, 0x0b12 ), k_eControllerType_XBoxOneController, "Xbox Series X Controller" }, // Microsoft Xbox Series X Controller + { MAKE_CONTROLLER_ID( 0x045e, 0x0b13 ), k_eControllerType_XBoxOneController, "Xbox Series X Controller" }, // Microsoft Xbox Series X Controller (BLE) + { MAKE_CONTROLLER_ID( 0x045e, 0x0b20 ), k_eControllerType_XBoxOneController, "Xbox One S Controller" }, // Microsoft Xbox One S Controller (BLE) + { MAKE_CONTROLLER_ID( 0x045e, 0x0b21 ), k_eControllerType_XBoxOneController, "Xbox Adaptive Controller" }, // Microsoft Xbox Adaptive Controller (BLE) + { MAKE_CONTROLLER_ID( 0x045e, 0x0b22 ), k_eControllerType_XBoxOneController, "Xbox One Elite 2 Controller" }, // Microsoft Xbox One Elite Series 2 Controller (BLE) + { MAKE_CONTROLLER_ID( 0x0738, 0x4a01 ), k_eControllerType_XBoxOneController, NULL }, // Mad Catz FightStick TE 2 + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0139 ), k_eControllerType_XBoxOneController, "PDP Xbox One Afterglow" }, // PDP Afterglow Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x013B ), k_eControllerType_XBoxOneController, "PDP Xbox One Face-Off Controller" }, // PDP Face-Off Gamepad for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x013a ), k_eControllerType_XBoxOneController, NULL }, // PDP Xbox One Controller (unlisted) + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0145 ), k_eControllerType_XBoxOneController, "PDP MK X Fight Pad" }, // PDP MK X Fight Pad for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0146 ), k_eControllerType_XBoxOneController, "PDP Xbox One Rock Candy" }, // PDP Rock Candy Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x015b ), k_eControllerType_XBoxOneController, "PDP Fallout 4 Vault Boy Controller" }, // PDP Fallout 4 Vault Boy Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x015c ), k_eControllerType_XBoxOneController, "PDP Xbox One @Play Controller" }, // PDP @Play Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x015d ), k_eControllerType_XBoxOneController, "PDP Mirror's Edge Controller" }, // PDP Mirror's Edge Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x015f ), k_eControllerType_XBoxOneController, "PDP Metallic Controller" }, // PDP Metallic Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0160 ), k_eControllerType_XBoxOneController, "PDP NFL Face-Off Controller" }, // PDP NFL Official Face-Off Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0161 ), k_eControllerType_XBoxOneController, "PDP Xbox One Camo" }, // PDP Camo Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0162 ), k_eControllerType_XBoxOneController, "PDP Xbox One Controller" }, // PDP Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0163 ), k_eControllerType_XBoxOneController, "PDP Deliverer of Truth" }, // PDP Legendary Collection: Deliverer of Truth + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0164 ), k_eControllerType_XBoxOneController, "PDP Battlefield 1 Controller" }, // PDP Battlefield 1 Official Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0165 ), k_eControllerType_XBoxOneController, "PDP Titanfall 2 Controller" }, // PDP Titanfall 2 Official Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0166 ), k_eControllerType_XBoxOneController, "PDP Mass Effect: Andromeda Controller" }, // PDP Mass Effect: Andromeda Official Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0167 ), k_eControllerType_XBoxOneController, "PDP Halo Wars 2 Face-Off Controller" }, // PDP Halo Wars 2 Official Face-Off Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0205 ), k_eControllerType_XBoxOneController, "PDP Victrix Pro Fight Stick" }, // PDP Victrix Pro Fight Stick + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0206 ), k_eControllerType_XBoxOneController, "PDP Mortal Kombat Controller" }, // PDP Mortal Kombat 25 Anniversary Edition Stick (Xbox One) + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0246 ), k_eControllerType_XBoxOneController, "PDP Xbox One Rock Candy" }, // PDP Rock Candy Wired Controller for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0261 ), k_eControllerType_XBoxOneController, "PDP Xbox One Camo" }, // PDP Camo Wired Controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0262 ), k_eControllerType_XBoxOneController, "PDP Xbox One Controller" }, // PDP Wired Controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a0 ), k_eControllerType_XBoxOneController, "PDP Xbox One Midnight Blue" }, // PDP Wired Controller for Xbox One - Midnight Blue + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a1 ), k_eControllerType_XBoxOneController, "PDP Xbox One Verdant Green" }, // PDP Wired Controller for Xbox One - Verdant Green + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a2 ), k_eControllerType_XBoxOneController, "PDP Xbox One Crimson Red" }, // PDP Wired Controller for Xbox One - Crimson Red + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a3 ), k_eControllerType_XBoxOneController, "PDP Xbox One Arctic White" }, // PDP Wired Controller for Xbox One - Arctic White + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a4 ), k_eControllerType_XBoxOneController, "PDP Xbox One Phantom Black" }, // PDP Wired Controller for Xbox One - Stealth Series | Phantom Black + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a5 ), k_eControllerType_XBoxOneController, "PDP Xbox One Ghost White" }, // PDP Wired Controller for Xbox One - Stealth Series | Ghost White + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a6 ), k_eControllerType_XBoxOneController, "PDP Xbox One Revenant Blue" }, // PDP Wired Controller for Xbox One - Stealth Series | Revenant Blue + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a7 ), k_eControllerType_XBoxOneController, "PDP Xbox One Raven Black" }, // PDP Wired Controller for Xbox One - Raven Black + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a8 ), k_eControllerType_XBoxOneController, "PDP Xbox One Arctic White" }, // PDP Wired Controller for Xbox One - Arctic White + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a9 ), k_eControllerType_XBoxOneController, "PDP Xbox One Midnight Blue" }, // PDP Wired Controller for Xbox One - Midnight Blue + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02aa ), k_eControllerType_XBoxOneController, "PDP Xbox One Verdant Green" }, // PDP Wired Controller for Xbox One - Verdant Green + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ab ), k_eControllerType_XBoxOneController, "PDP Xbox One Crimson Red" }, // PDP Wired Controller for Xbox One - Crimson Red + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ac ), k_eControllerType_XBoxOneController, "PDP Xbox One Ember Orange" }, // PDP Wired Controller for Xbox One - Ember Orange + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ad ), k_eControllerType_XBoxOneController, "PDP Xbox One Phantom Black" }, // PDP Wired Controller for Xbox One - Stealth Series | Phantom Black + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ae ), k_eControllerType_XBoxOneController, "PDP Xbox One Ghost White" }, // PDP Wired Controller for Xbox One - Stealth Series | Ghost White + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02af ), k_eControllerType_XBoxOneController, "PDP Xbox One Revenant Blue" }, // PDP Wired Controller for Xbox One - Stealth Series | Revenant Blue + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02b0 ), k_eControllerType_XBoxOneController, "PDP Xbox One Raven Black" }, // PDP Wired Controller for Xbox One - Raven Black + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02b1 ), k_eControllerType_XBoxOneController, "PDP Xbox One Arctic White" }, // PDP Wired Controller for Xbox One - Arctic White + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02b3 ), k_eControllerType_XBoxOneController, "PDP Xbox One Afterglow" }, // PDP Afterglow Prismatic Wired Controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02b5 ), k_eControllerType_XBoxOneController, "PDP Xbox One GAMEware Controller" }, // PDP GAMEware Wired Controller Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02b6 ), k_eControllerType_XBoxOneController, NULL }, // PDP One-Handed Joystick Adaptive Controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02bd ), k_eControllerType_XBoxOneController, "PDP Xbox One Royal Purple" }, // PDP Wired Controller for Xbox One - Royal Purple + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02be ), k_eControllerType_XBoxOneController, "PDP Xbox One Raven Black" }, // PDP Deluxe Wired Controller for Xbox One - Raven Black + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02bf ), k_eControllerType_XBoxOneController, "PDP Xbox One Midnight Blue" }, // PDP Deluxe Wired Controller for Xbox One - Midnight Blue + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c0 ), k_eControllerType_XBoxOneController, "PDP Xbox One Phantom Black" }, // PDP Deluxe Wired Controller for Xbox One - Stealth Series | Phantom Black + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c1 ), k_eControllerType_XBoxOneController, "PDP Xbox One Ghost White" }, // PDP Deluxe Wired Controller for Xbox One - Stealth Series | Ghost White + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c2 ), k_eControllerType_XBoxOneController, "PDP Xbox One Revenant Blue" }, // PDP Deluxe Wired Controller for Xbox One - Stealth Series | Revenant Blue + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c3 ), k_eControllerType_XBoxOneController, "PDP Xbox One Verdant Green" }, // PDP Deluxe Wired Controller for Xbox One - Verdant Green + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c4 ), k_eControllerType_XBoxOneController, "PDP Xbox One Ember Orange" }, // PDP Deluxe Wired Controller for Xbox One - Ember Orange + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c5 ), k_eControllerType_XBoxOneController, "PDP Xbox One Royal Purple" }, // PDP Deluxe Wired Controller for Xbox One - Royal Purple + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c6 ), k_eControllerType_XBoxOneController, "PDP Xbox One Crimson Red" }, // PDP Deluxe Wired Controller for Xbox One - Crimson Red + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c7 ), k_eControllerType_XBoxOneController, "PDP Xbox One Arctic White" }, // PDP Deluxe Wired Controller for Xbox One - Arctic White + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c8 ), k_eControllerType_XBoxOneController, "PDP Kingdom Hearts Controller" }, // PDP Kingdom Hearts Wired Controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c9 ), k_eControllerType_XBoxOneController, "PDP Xbox One Phantasm Red" }, // PDP Deluxe Wired Controller for Xbox One - Stealth Series | Phantasm Red + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ca ), k_eControllerType_XBoxOneController, "PDP Xbox One Specter Violet" }, // PDP Deluxe Wired Controller for Xbox One - Stealth Series | Specter Violet + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02cb ), k_eControllerType_XBoxOneController, "PDP Xbox One Specter Violet" }, // PDP Wired Controller for Xbox One - Stealth Series | Specter Violet + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02cd ), k_eControllerType_XBoxOneController, "PDP Xbox One Blu-merang" }, // PDP Rock Candy Wired Controller for Xbox One - Blu-merang + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ce ), k_eControllerType_XBoxOneController, "PDP Xbox One Cranblast" }, // PDP Rock Candy Wired Controller for Xbox One - Cranblast + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02cf ), k_eControllerType_XBoxOneController, "PDP Xbox One Aqualime" }, // PDP Rock Candy Wired Controller for Xbox One - Aqualime + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02d5 ), k_eControllerType_XBoxOneController, "PDP Xbox One Red Camo" }, // PDP Wired Controller for Xbox One - Red Camo + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0346 ), k_eControllerType_XBoxOneController, "PDP Xbox One RC Gamepad" }, // PDP RC Gamepad for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0446 ), k_eControllerType_XBoxOneController, "PDP Xbox One RC Gamepad" }, // PDP RC Gamepad for Xbox One + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02da ), k_eControllerType_XBoxOneController, "PDP Xbox Series X Afterglow" }, // PDP Xbox Series X Afterglow + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02d6 ), k_eControllerType_XBoxOneController, "Victrix Gambit Tournament Controller" }, // Victrix Gambit Tournament Controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x02d9 ), k_eControllerType_XBoxOneController, "PDP Xbox Series X Midnight Blue" }, // PDP Xbox Series X Midnight Blue + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0063 ), k_eControllerType_XBoxOneController, NULL }, // Hori Real Arcade Pro Hayabusa (USA) Xbox One + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0067 ), k_eControllerType_XBoxOneController, NULL }, // HORIPAD ONE + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0078 ), k_eControllerType_XBoxOneController, NULL }, // Hori Real Arcade Pro V Kai Xbox One + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00c5 ), k_eControllerType_XBoxOneController, NULL }, // HORI Fighting Commander + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0150 ), k_eControllerType_XBoxOneController, NULL }, // HORI Fighting Commander OCTA for Xbox Series X + { MAKE_CONTROLLER_ID( 0x10f5, 0x7009 ), k_eControllerType_XBoxOneController, NULL }, // Turtle Beach Recon Controller + { MAKE_CONTROLLER_ID( 0x10f5, 0x7013 ), k_eControllerType_XBoxOneController, NULL }, // Turtle Beach REACT-R + { MAKE_CONTROLLER_ID( 0x1532, 0x0a00 ), k_eControllerType_XBoxOneController, NULL }, // Razer Atrox Arcade Stick + { MAKE_CONTROLLER_ID( 0x1532, 0x0a03 ), k_eControllerType_XBoxOneController, NULL }, // Razer Wildcat + { MAKE_CONTROLLER_ID( 0x1532, 0x0a14 ), k_eControllerType_XBoxOneController, NULL }, // Razer Wolverine Ultimate + { MAKE_CONTROLLER_ID( 0x1532, 0x0a15 ), k_eControllerType_XBoxOneController, NULL }, // Razer Wolverine Tournament Edition + { MAKE_CONTROLLER_ID( 0x20d6, 0x2001 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller - Black Inline + { MAKE_CONTROLLER_ID( 0x20d6, 0x2002 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Gray/White Inline + { MAKE_CONTROLLER_ID( 0x20d6, 0x2003 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Green Inline + { MAKE_CONTROLLER_ID( 0x20d6, 0x2004 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Pink inline + { MAKE_CONTROLLER_ID( 0x20d6, 0x2005 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X Wired Controller Core - Black + { MAKE_CONTROLLER_ID( 0x20d6, 0x2006 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X Wired Controller Core - White + { MAKE_CONTROLLER_ID( 0x20d6, 0x2009 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Red inline + { MAKE_CONTROLLER_ID( 0x20d6, 0x200a ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Blue inline + { MAKE_CONTROLLER_ID( 0x20d6, 0x200b ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Camo Metallic Red + { MAKE_CONTROLLER_ID( 0x20d6, 0x200c ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Camo Metallic Blue + { MAKE_CONTROLLER_ID( 0x20d6, 0x200d ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Seafoam Fade + { MAKE_CONTROLLER_ID( 0x20d6, 0x200e ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Midnight Blue + { MAKE_CONTROLLER_ID( 0x20d6, 0x200f ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Soldier Green + { MAKE_CONTROLLER_ID( 0x20d6, 0x2011 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired - Metallic Ice + { MAKE_CONTROLLER_ID( 0x20d6, 0x2012 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X Cuphead EnWired Controller - Mugman + { MAKE_CONTROLLER_ID( 0x20d6, 0x2015 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller - Blue Hint + { MAKE_CONTROLLER_ID( 0x20d6, 0x2016 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller - Green Hint + { MAKE_CONTROLLER_ID( 0x20d6, 0x2017 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Cntroller - Arctic Camo + { MAKE_CONTROLLER_ID( 0x20d6, 0x2018 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Arc Lightning + { MAKE_CONTROLLER_ID( 0x20d6, 0x2019 ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Royal Purple + { MAKE_CONTROLLER_ID( 0x20d6, 0x201a ), k_eControllerType_XBoxOneController, "PowerA Xbox Series X Controller" }, // PowerA Xbox Series X EnWired Controller Nebula + { MAKE_CONTROLLER_ID( 0x20d6, 0x4001 ), k_eControllerType_XBoxOneController, "PowerA Fusion Pro 2 Controller" }, // PowerA Fusion Pro 2 Wired Controller (Xbox Series X style) + { MAKE_CONTROLLER_ID( 0x20d6, 0x4002 ), k_eControllerType_XBoxOneController, "PowerA Spectra Infinity Controller" }, // PowerA Spectra Infinity Wired Controller (Xbox Series X style) + { MAKE_CONTROLLER_ID( 0x20d6, 0x890b ), k_eControllerType_XBoxOneController, NULL }, // PowerA MOGA XP-Ultra Controller (Xbox Series X style) + { MAKE_CONTROLLER_ID( 0x24c6, 0x541a ), k_eControllerType_XBoxOneController, NULL }, // PowerA Xbox One Mini Wired Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x542a ), k_eControllerType_XBoxOneController, NULL }, // Xbox ONE spectra + { MAKE_CONTROLLER_ID( 0x24c6, 0x543a ), k_eControllerType_XBoxOneController, "PowerA Xbox One Controller" }, // PowerA Xbox ONE liquid metal controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x551a ), k_eControllerType_XBoxOneController, NULL }, // PowerA FUSION Pro Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x561a ), k_eControllerType_XBoxOneController, NULL }, // PowerA FUSION Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x581a ), k_eControllerType_XBoxOneController, NULL }, // BDA XB1 Classic Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x591a ), k_eControllerType_XBoxOneController, NULL }, // PowerA FUSION Pro Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x592a ), k_eControllerType_XBoxOneController, NULL }, // BDA XB1 Spectra Pro + { MAKE_CONTROLLER_ID( 0x24c6, 0x791a ), k_eControllerType_XBoxOneController, NULL }, // PowerA Fusion Fight Pad + { MAKE_CONTROLLER_ID( 0x2dc8, 0x2002 ), k_eControllerType_XBoxOneController, NULL }, // 8BitDo Ultimate Wired Controller for Xbox + { MAKE_CONTROLLER_ID( 0x2dc8, 0x3106 ), k_eControllerType_XBoxOneController, NULL }, // 8Bitdo Ultimate Wired Controller. Windows, Android, Switch. + { MAKE_CONTROLLER_ID( 0x2e24, 0x0652 ), k_eControllerType_XBoxOneController, NULL }, // Hyperkin Duke + { MAKE_CONTROLLER_ID( 0x2e24, 0x1618 ), k_eControllerType_XBoxOneController, NULL }, // Hyperkin Duke + { MAKE_CONTROLLER_ID( 0x2e24, 0x1688 ), k_eControllerType_XBoxOneController, NULL }, // Hyperkin X91 + { MAKE_CONTROLLER_ID( 0x146b, 0x0611 ), k_eControllerType_XBoxOneController, NULL }, // Xbox Controller Mode for NACON Revolution 3 + + // These have been added via Minidump for unrecognized Xinput controller assert + { MAKE_CONTROLLER_ID( 0x0000, 0x0000 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x045e, 0x02a2 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller - Microsoft VID + { MAKE_CONTROLLER_ID( 0x0e6f, 0x1414 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0159 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0xfaff ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0f0d, 0x006d ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00a4 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0079, 0x1832 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0079, 0x187f ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0079, 0x1883 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x03eb, 0xff01 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0c12, 0x0ef8 ), k_eControllerType_XBox360Controller, NULL }, // Homemade fightstick based on brook pcb (with XInput driver??) + { MAKE_CONTROLLER_ID( 0x046d, 0x1000 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x11ff, 0x0511 ), k_eControllerType_XBox360Controller, NULL }, // PXN V900 + { MAKE_CONTROLLER_ID( 0x1345, 0x6006 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + + { MAKE_CONTROLLER_ID( 0x056e, 0x2012 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x146b, 0x0602 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00ae ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x046d, 0x0401 ), k_eControllerType_XBox360Controller, NULL }, // logitech xinput + { MAKE_CONTROLLER_ID( 0x046d, 0x0301 ), k_eControllerType_XBox360Controller, NULL }, // logitech xinput + { MAKE_CONTROLLER_ID( 0x046d, 0xcaa3 ), k_eControllerType_XBox360Controller, NULL }, // logitech xinput + { MAKE_CONTROLLER_ID( 0x046d, 0xc261 ), k_eControllerType_XBox360Controller, NULL }, // logitech xinput + { MAKE_CONTROLLER_ID( 0x046d, 0x0291 ), k_eControllerType_XBox360Controller, NULL }, // logitech xinput + { MAKE_CONTROLLER_ID( 0x0079, 0x18d3 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00b1 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0001, 0x0001 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0079, 0x188e ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0079, 0x187c ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0079, 0x189c ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x0079, 0x1874 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller + + { MAKE_CONTROLLER_ID( 0x2f24, 0x0050 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x2f24, 0x2e ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x2f24, 0x91 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x1430, 0x719 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xf0d, 0xed ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xf0d, 0xc0 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x152 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2a7 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x46d, 0x1007 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2b8 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2a8 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x79, 0x18a1 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + + // Added from Minidumps 10-9-19 + { MAKE_CONTROLLER_ID( 0x0, 0x6686 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x12ab, 0x304 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x1430, 0x291 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x1430, 0x2a9 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x1430, 0x70b ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x1bad, 0x28e ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x1bad, 0x2a0 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x1bad, 0x5500 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x20ab, 0x55ef ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x24c6, 0x5509 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x2516, 0x69 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x25b1, 0x360 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x2c22, 0x2203 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x2f24, 0x11 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x2f24, 0x53 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x2f24, 0xb7 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x46d, 0x0 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x46d, 0x1004 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x46d, 0x1008 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x46d, 0xf301 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x738, 0x2a0 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x738, 0x7263 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x738, 0xb738 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x738, 0xcb29 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x738, 0xf401 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x79, 0x18c2 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x79, 0x18c8 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x79, 0x18cf ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xc12, 0xe17 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xc12, 0xe1c ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xc12, 0xe22 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xc12, 0xe30 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xd2d2, 0xd2d2 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xd62, 0x9a1a ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xd62, 0x9a1b ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe00, 0xe00 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x12a ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2a1 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2a2 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2a5 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2b2 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2bd ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2bf ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2c0 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0x2c6 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xf0d, 0x97 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xf0d, 0xba ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xf0d, 0xd8 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xfff, 0x2a1 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x45e, 0x867 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + // Added 12-17-2020 + { MAKE_CONTROLLER_ID( 0x16d0, 0xf3f ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0x2f24, 0x8f ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + { MAKE_CONTROLLER_ID( 0xe6f, 0xf501 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller + + //{ MAKE_CONTROLLER_ID( 0x1949, 0x0402 ), /*android*/, NULL }, // Unknown Controller + + { MAKE_CONTROLLER_ID( 0x05ac, 0x0001 ), k_eControllerType_AppleController, NULL }, // MFI Extended Gamepad (generic entry for iOS/tvOS) + { MAKE_CONTROLLER_ID( 0x05ac, 0x0002 ), k_eControllerType_AppleController, NULL }, // MFI Standard Gamepad (generic entry for iOS/tvOS) + + { MAKE_CONTROLLER_ID( 0x057e, 0x2006 ), k_eControllerType_SwitchJoyConLeft, NULL }, // Nintendo Switch Joy-Con (Left) + { MAKE_CONTROLLER_ID( 0x057e, 0x2007 ), k_eControllerType_SwitchJoyConRight, NULL }, // Nintendo Switch Joy-Con (Right) + { MAKE_CONTROLLER_ID( 0x057e, 0x2008 ), k_eControllerType_SwitchJoyConPair, NULL }, // Nintendo Switch Joy-Con (Left+Right Combined) + + // This same controller ID is spoofed by many 3rd-party Switch controllers. + // The ones we currently know of are: + // * Any 8bitdo controller with Switch support + // * ORTZ Gaming Wireless Pro Controller + // * ZhiXu Gamepad Wireless + // * Sunwaytek Wireless Motion Controller for Nintendo Switch + { MAKE_CONTROLLER_ID( 0x057e, 0x2009 ), k_eControllerType_SwitchProController, NULL }, // Nintendo Switch Pro Controller + //{ MAKE_CONTROLLER_ID( 0x057e, 0x2017 ), k_eControllerType_SwitchProController, NULL }, // Nintendo Online SNES Controller + //{ MAKE_CONTROLLER_ID( 0x057e, 0x2019 ), k_eControllerType_SwitchProController, NULL }, // Nintendo Online N64 Controller + //{ MAKE_CONTROLLER_ID( 0x057e, 0x201e ), k_eControllerType_SwitchProController, NULL }, // Nintendo Online SEGA Genesis Controller + + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00c1 ), k_eControllerType_SwitchInputOnlyController, NULL }, // HORIPAD for Nintendo Switch + { MAKE_CONTROLLER_ID( 0x0f0d, 0x0092 ), k_eControllerType_SwitchInputOnlyController, NULL }, // HORI Pokken Tournament DX Pro Pad + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00f6 ), k_eControllerType_SwitchProController, NULL }, // HORI Wireless Switch Pad + // The HORIPAD S, which comes in multiple styles: + // - NSW-108, classic GameCube controller + // - NSW-244, Fighting Commander arcade pad + // - NSW-278, Hori Pad Mini gamepad + // - NSW-326, HORIPAD FPS for Nintendo Switch + // + // The first two, at least, shouldn't have their buttons remapped, and since we + // can't tell which model we're actually using, we won't do any button remapping + // for any of them. + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00dc ), k_eControllerType_XInputSwitchController, NULL }, // HORIPAD S - Looks like a Switch controller but uses the Xbox 360 controller protocol, there is also a version of this that looks like a GameCube controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0180 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Faceoff Wired Pro Controller for Nintendo Switch + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0181 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Faceoff Deluxe Wired Pro Controller for Nintendo Switch + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0184 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Faceoff Wired Deluxe+ Audio Controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0185 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Wired Fight Pad Pro for Nintendo Switch + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0186 ), k_eControllerType_SwitchProController, NULL }, // PDP Afterglow Wireless Switch Controller - working gyro. USB is for charging only. Many later "Wireless" line devices w/ gyro also use this vid/pid + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0187 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Rockcandy Wired Controller + { MAKE_CONTROLLER_ID( 0x0e6f, 0x0188 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Afterglow Wired Deluxe+ Audio Controller + { MAKE_CONTROLLER_ID( 0x0f0d, 0x00aa ), k_eControllerType_SwitchInputOnlyController, NULL }, // HORI Real Arcade Pro V Hayabusa in Switch Mode + { MAKE_CONTROLLER_ID( 0x20d6, 0xa711 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PowerA Wired Controller Plus/PowerA Wired Controller Nintendo GameCube Style + { MAKE_CONTROLLER_ID( 0x20d6, 0xa712 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PowerA Nintendo Switch Fusion Fight Pad + { MAKE_CONTROLLER_ID( 0x20d6, 0xa713 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PowerA Super Mario Controller + { MAKE_CONTROLLER_ID( 0x20d6, 0xa714 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PowerA Nintendo Switch Spectra Controller + { MAKE_CONTROLLER_ID( 0x20d6, 0xa715 ), k_eControllerType_SwitchInputOnlyController, NULL }, // Power A Fusion Wireless Arcade Stick (USB Mode) Over BT is shows up as 057e 2009 + { MAKE_CONTROLLER_ID( 0x20d6, 0xa716 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PowerA Nintendo Switch Fusion Pro Controller - USB requires toggling switch on back of device + { MAKE_CONTROLLER_ID( 0x20d6, 0xa718 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PowerA Nintendo Switch Nano Wired Controller + { MAKE_CONTROLLER_ID( 0x33dd, 0x0001 ), k_eControllerType_SwitchInputOnlyController, NULL }, // ZUIKI MasCon for Nintendo Switch Black + { MAKE_CONTROLLER_ID( 0x33dd, 0x0002 ), k_eControllerType_SwitchInputOnlyController, NULL }, // ZUIKI MasCon for Nintendo Switch ?? + { MAKE_CONTROLLER_ID( 0x33dd, 0x0003 ), k_eControllerType_SwitchInputOnlyController, NULL }, // ZUIKI MasCon for Nintendo Switch Red + + // Valve products + { MAKE_CONTROLLER_ID( 0x0000, 0x11fb ), k_eControllerType_MobileTouch, NULL }, // Streaming mobile touch virtual controls + { MAKE_CONTROLLER_ID( 0x28de, 0x1101 ), k_eControllerType_SteamController, NULL }, // Valve Legacy Steam Controller (CHELL) + { MAKE_CONTROLLER_ID( 0x28de, 0x1102 ), k_eControllerType_SteamController, NULL }, // Valve wired Steam Controller (D0G) + { MAKE_CONTROLLER_ID( 0x28de, 0x1105 ), k_eControllerType_SteamController, NULL }, // Valve Bluetooth Steam Controller (D0G) + { MAKE_CONTROLLER_ID( 0x28de, 0x1106 ), k_eControllerType_SteamController, NULL }, // Valve Bluetooth Steam Controller (D0G) + { MAKE_CONTROLLER_ID( 0x28de, 0x11ff ), k_eControllerType_UnknownNonSteamController, NULL }, // Steam Virtual Gamepad + { MAKE_CONTROLLER_ID( 0x28de, 0x1142 ), k_eControllerType_SteamController, NULL }, // Valve wireless Steam Controller + { MAKE_CONTROLLER_ID( 0x28de, 0x1201 ), k_eControllerType_SteamControllerV2, NULL }, // Valve wired Steam Controller (HEADCRAB) + { MAKE_CONTROLLER_ID( 0x28de, 0x1202 ), k_eControllerType_SteamControllerV2, NULL }, // Valve Bluetooth Steam Controller (HEADCRAB) + { MAKE_CONTROLLER_ID( 0x28de, 0x1205 ), k_eControllerType_SteamControllerNeptune, NULL }, // Valve Steam Deck Builtin Controller +}; diff --git a/thirdparty/sdl/joystick/controller_type.c b/thirdparty/sdl/joystick/controller_type.c new file mode 100644 index 00000000000..f179d2731bc --- /dev/null +++ b/thirdparty/sdl/joystick/controller_type.c @@ -0,0 +1,140 @@ +/* + Copyright (C) Valve Corporation + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + + +#include "controller_type.h" +#include "controller_list.h" + + +static const char *GetControllerTypeOverride( int nVID, int nPID ) +{ + const char *hint = SDL_GetHint(SDL_HINT_GAMECONTROLLERTYPE); + if (hint) { + char key[32]; + const char *spot = NULL; + + SDL_snprintf(key, sizeof(key), "0x%.4x/0x%.4x=", nVID, nPID); + spot = SDL_strstr(hint, key); + if (!spot) { + SDL_snprintf(key, sizeof(key), "0x%.4X/0x%.4X=", nVID, nPID); + spot = SDL_strstr(hint, key); + } + if (spot) { + spot += SDL_strlen(key); + if (SDL_strncmp(spot, "k_eControllerType_", 18) == 0) { + spot += 18; + } + return spot; + } + } + return NULL; +} + + +EControllerType GuessControllerType( int nVID, int nPID ) +{ +#if 0//def _DEBUG + // Verify that there are no duplicates in the controller list + // If the list were sorted, we could do this much more efficiently, as well as improve lookup speed. + static bool s_bCheckedForDuplicates; + if ( !s_bCheckedForDuplicates ) + { + s_bCheckedForDuplicates = true; + int i, j; + for ( i = 0; i < sizeof( arrControllers ) / sizeof( arrControllers[ 0 ] ); ++i ) + { + for ( j = i + 1; j < sizeof( arrControllers ) / sizeof( arrControllers[ 0 ] ); ++j ) + { + if ( arrControllers[ i ].m_unDeviceID == arrControllers[ j ].m_unDeviceID ) + { + Log( "Duplicate controller entry found for VID 0x%.4x PID 0x%.4x\n", ( arrControllers[ i ].m_unDeviceID >> 16 ), arrControllers[ i ].m_unDeviceID & 0xFFFF ); + } + } + } + } +#endif // _DEBUG + + unsigned int unDeviceID = MAKE_CONTROLLER_ID( nVID, nPID ); + int iIndex; + + const char *pszOverride = GetControllerTypeOverride( nVID, nPID ); + if ( pszOverride ) + { + if ( SDL_strncasecmp( pszOverride, "Xbox360", 7 ) == 0 ) + { + return k_eControllerType_XBox360Controller; + } + if ( SDL_strncasecmp( pszOverride, "XboxOne", 7 ) == 0 ) + { + return k_eControllerType_XBoxOneController; + } + if ( SDL_strncasecmp( pszOverride, "PS3", 3 ) == 0 ) + { + return k_eControllerType_PS3Controller; + } + if ( SDL_strncasecmp( pszOverride, "PS4", 3 ) == 0 ) + { + return k_eControllerType_PS4Controller; + } + if ( SDL_strncasecmp( pszOverride, "PS5", 3 ) == 0 ) + { + return k_eControllerType_PS5Controller; + } + if ( SDL_strncasecmp( pszOverride, "SwitchPro", 9 ) == 0 ) + { + return k_eControllerType_SwitchProController; + } + if ( SDL_strncasecmp( pszOverride, "Steam", 5 ) == 0 ) + { + return k_eControllerType_SteamController; + } + return k_eControllerType_UnknownNonSteamController; + } + + for ( iIndex = 0; iIndex < sizeof( arrControllers ) / sizeof( arrControllers[0] ); ++iIndex ) + { + if ( unDeviceID == arrControllers[ iIndex ].m_unDeviceID ) + { + return arrControllers[ iIndex ].m_eControllerType; + } + } + + return k_eControllerType_UnknownNonSteamController; + +} + +const char *GuessControllerName( int nVID, int nPID ) +{ + unsigned int unDeviceID = MAKE_CONTROLLER_ID( nVID, nPID ); + int iIndex; + for ( iIndex = 0; iIndex < sizeof( arrControllers ) / sizeof( arrControllers[0] ); ++iIndex ) + { + if ( unDeviceID == arrControllers[ iIndex ].m_unDeviceID ) + { + return arrControllers[ iIndex ].m_pszName; + } + } + + return NULL; + +} + +#undef MAKE_CONTROLLER_ID diff --git a/thirdparty/sdl/joystick/controller_type.h b/thirdparty/sdl/joystick/controller_type.h new file mode 100644 index 00000000000..155c8ad11e1 --- /dev/null +++ b/thirdparty/sdl/joystick/controller_type.h @@ -0,0 +1,78 @@ +/* + Copyright (C) Valve Corporation + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef CONTROLLER_TYPE_H +#define CONTROLLER_TYPE_H +#ifdef _WIN32 +#pragma once +#endif + +//----------------------------------------------------------------------------- +// Purpose: Steam Controller models +// WARNING: DO NOT RENUMBER EXISTING VALUES - STORED IN A DATABASE +//----------------------------------------------------------------------------- +typedef enum +{ + k_eControllerType_None = -1, + k_eControllerType_Unknown = 0, + + // Steam Controllers + k_eControllerType_UnknownSteamController = 1, + k_eControllerType_SteamController = 2, + k_eControllerType_SteamControllerV2 = 3, + k_eControllerType_SteamControllerNeptune = 4, + + // Other Controllers + k_eControllerType_UnknownNonSteamController = 30, + k_eControllerType_XBox360Controller = 31, + k_eControllerType_XBoxOneController = 32, + k_eControllerType_PS3Controller = 33, + k_eControllerType_PS4Controller = 34, + k_eControllerType_WiiController = 35, + k_eControllerType_AppleController = 36, + k_eControllerType_AndroidController = 37, + k_eControllerType_SwitchProController = 38, + k_eControllerType_SwitchJoyConLeft = 39, + k_eControllerType_SwitchJoyConRight = 40, + k_eControllerType_SwitchJoyConPair = 41, + k_eControllerType_SwitchInputOnlyController = 42, + k_eControllerType_MobileTouch = 43, + k_eControllerType_XInputSwitchController = 44, // Client-side only, used to mark Nintendo Switch style controllers as using XInput instead of the Nintendo Switch protocol + k_eControllerType_PS5Controller = 45, + k_eControllerType_XInputPS4Controller = 46, // Client-side only, used to mark DualShock 4 style controllers using XInput instead of the DualShock 4 controller protocol + k_eControllerType_LastController, // Don't add game controllers below this enumeration - this enumeration can change value + + // Keyboards and Mice + k_eControllertype_GenericKeyboard = 400, + k_eControllertype_GenericMouse = 800, +} EControllerType; + +typedef struct +{ + unsigned int m_unDeviceID; + EControllerType m_eControllerType; + const char *m_pszName; +} ControllerDescription_t; + + +extern EControllerType GuessControllerType( int nVID, int nPID ); +extern const char *GuessControllerName( int nVID, int nPID ); + +#endif // CONTROLLER_TYPE_H diff --git a/thirdparty/sdl/joystick/darwin/SDL_iokitjoystick.c b/thirdparty/sdl/joystick/darwin/SDL_iokitjoystick.c new file mode 100644 index 00000000000..9327276a427 --- /dev/null +++ b/thirdparty/sdl/joystick/darwin/SDL_iokitjoystick.c @@ -0,0 +1,1089 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_IOKIT + +#include "../SDL_sysjoystick.h" +#include "../SDL_joystick_c.h" +#include "SDL_iokitjoystick_c.h" +#include "../hidapi/SDL_hidapijoystick_c.h" +#include "../../haptic/darwin/SDL_syshaptic_c.h" // For haptic hot plugging + +#define SDL_JOYSTICK_RUNLOOP_MODE CFSTR("SDLJoystick") + +#define CONVERT_MAGNITUDE(x) (((x)*10000) / 0x7FFF) + +// The base object of the HID Manager API +static IOHIDManagerRef hidman = NULL; + +// Linked list of all available devices +static recDevice *gpDeviceList = NULL; + +void FreeRumbleEffectData(FFEFFECT *effect) +{ + if (!effect) { + return; + } + SDL_free(effect->rgdwAxes); + SDL_free(effect->rglDirection); + SDL_free(effect->lpvTypeSpecificParams); + SDL_free(effect); +} + +FFEFFECT *CreateRumbleEffectData(Sint16 magnitude) +{ + FFEFFECT *effect; + FFPERIODIC *periodic; + + // Create the effect + effect = (FFEFFECT *)SDL_calloc(1, sizeof(*effect)); + if (!effect) { + return NULL; + } + effect->dwSize = sizeof(*effect); + effect->dwGain = 10000; + effect->dwFlags = FFEFF_OBJECTOFFSETS; + effect->dwDuration = SDL_MAX_RUMBLE_DURATION_MS * 1000; // In microseconds. + effect->dwTriggerButton = FFEB_NOTRIGGER; + + effect->cAxes = 2; + effect->rgdwAxes = (DWORD *)SDL_calloc(effect->cAxes, sizeof(DWORD)); + if (!effect->rgdwAxes) { + FreeRumbleEffectData(effect); + return NULL; + } + + effect->rglDirection = (LONG *)SDL_calloc(effect->cAxes, sizeof(LONG)); + if (!effect->rglDirection) { + FreeRumbleEffectData(effect); + return NULL; + } + effect->dwFlags |= FFEFF_CARTESIAN; + + periodic = (FFPERIODIC *)SDL_calloc(1, sizeof(*periodic)); + if (!periodic) { + FreeRumbleEffectData(effect); + return NULL; + } + periodic->dwMagnitude = CONVERT_MAGNITUDE(magnitude); + periodic->dwPeriod = 1000000; + + effect->cbTypeSpecificParams = sizeof(*periodic); + effect->lpvTypeSpecificParams = periodic; + + return effect; +} + +static recDevice *GetDeviceForIndex(int device_index) +{ + recDevice *device = gpDeviceList; + while (device) { + if (!device->removed) { + if (device_index == 0) { + break; + } + + --device_index; + } + device = device->pNext; + } + return device; +} + +static void FreeElementList(recElement *pElement) +{ + while (pElement) { + recElement *pElementNext = pElement->pNext; + SDL_free(pElement); + pElement = pElementNext; + } +} + +static recDevice *FreeDevice(recDevice *removeDevice) +{ + recDevice *pDeviceNext = NULL; + if (removeDevice) { + if (removeDevice->deviceRef) { + if (removeDevice->runLoopAttached) { + /* Calling IOHIDDeviceUnscheduleFromRunLoop without a prior, + * paired call to IOHIDDeviceScheduleWithRunLoop can lead + * to crashes in MacOS 10.14.x and earlier. This doesn't + * appear to be a problem in MacOS 10.15.x, but we'll + * do it anyways. (Part-of fix for Bug 5034) + */ + IOHIDDeviceUnscheduleFromRunLoop(removeDevice->deviceRef, CFRunLoopGetCurrent(), SDL_JOYSTICK_RUNLOOP_MODE); + } + CFRelease(removeDevice->deviceRef); + removeDevice->deviceRef = NULL; + } + + /* clear out any reference to removeDevice from an associated, + * live instance of SDL_Joystick (Part-of fix for Bug 5034) + */ + SDL_LockJoysticks(); + if (removeDevice->joystick) { + removeDevice->joystick->hwdata = NULL; + } + SDL_UnlockJoysticks(); + + // save next device prior to disposing of this device + pDeviceNext = removeDevice->pNext; + + if (gpDeviceList == removeDevice) { + gpDeviceList = pDeviceNext; + } else if (gpDeviceList) { + recDevice *device; + + for (device = gpDeviceList; device; device = device->pNext) { + if (device->pNext == removeDevice) { + device->pNext = pDeviceNext; + break; + } + } + } + removeDevice->pNext = NULL; + + // free element lists + FreeElementList(removeDevice->firstAxis); + FreeElementList(removeDevice->firstButton); + FreeElementList(removeDevice->firstHat); + + SDL_free(removeDevice); + } + return pDeviceNext; +} + +static bool GetHIDElementState(recDevice *pDevice, recElement *pElement, SInt32 *pValue) +{ + SInt32 value = 0; + bool result = false; + + if (pDevice && pDevice->deviceRef && pElement) { + IOHIDValueRef valueRef; + if (IOHIDDeviceGetValue(pDevice->deviceRef, pElement->elementRef, &valueRef) == kIOReturnSuccess) { + value = (SInt32)IOHIDValueGetIntegerValue(valueRef); + + // record min and max for auto calibration + if (value < pElement->minReport) { + pElement->minReport = value; + } + if (value > pElement->maxReport) { + pElement->maxReport = value; + } + *pValue = value; + + result = true; + } + } + return result; +} + +static bool GetHIDScaledCalibratedState(recDevice *pDevice, recElement *pElement, SInt32 min, SInt32 max, SInt32 *pValue) +{ + const float deviceScale = max - min; + const float readScale = pElement->maxReport - pElement->minReport; + bool result = false; + if (GetHIDElementState(pDevice, pElement, pValue)) { + if (readScale == 0) { + result = true; // no scaling at all + } else { + *pValue = (Sint32)(((*pValue - pElement->minReport) * deviceScale / readScale) + min); + result = true; + } + } + return result; +} + +static void JoystickDeviceWasRemovedCallback(void *ctx, IOReturn result, void *sender) +{ + recDevice *device = (recDevice *)ctx; + device->removed = true; + if (device->deviceRef) { + // deviceRef was invalidated due to the remove + CFRelease(device->deviceRef); + device->deviceRef = NULL; + } + if (device->ffeffect_ref) { + FFDeviceReleaseEffect(device->ffdevice, device->ffeffect_ref); + device->ffeffect_ref = NULL; + } + if (device->ffeffect) { + FreeRumbleEffectData(device->ffeffect); + device->ffeffect = NULL; + } + if (device->ffdevice) { + FFReleaseDevice(device->ffdevice); + device->ffdevice = NULL; + device->ff_initialized = false; + } +#ifdef SDL_HAPTIC_IOKIT + MacHaptic_MaybeRemoveDevice(device->ffservice); +#endif + + SDL_PrivateJoystickRemoved(device->instance_id); +} + +static void AddHIDElement(const void *value, void *parameter); + +// Call AddHIDElement() on all elements in an array of IOHIDElementRefs +static void AddHIDElements(CFArrayRef array, recDevice *pDevice) +{ + const CFRange range = { 0, CFArrayGetCount(array) }; + CFArrayApplyFunction(array, range, AddHIDElement, pDevice); +} + +static bool ElementAlreadyAdded(const IOHIDElementCookie cookie, const recElement *listitem) +{ + while (listitem) { + if (listitem->cookie == cookie) { + return true; + } + listitem = listitem->pNext; + } + return false; +} + +// See if we care about this HID element, and if so, note it in our recDevice. +static void AddHIDElement(const void *value, void *parameter) +{ + recDevice *pDevice = (recDevice *)parameter; + IOHIDElementRef refElement = (IOHIDElementRef)value; + const CFTypeID elementTypeID = refElement ? CFGetTypeID(refElement) : 0; + + if (refElement && (elementTypeID == IOHIDElementGetTypeID())) { + const IOHIDElementCookie cookie = IOHIDElementGetCookie(refElement); + const uint32_t usagePage = IOHIDElementGetUsagePage(refElement); + const uint32_t usage = IOHIDElementGetUsage(refElement); + recElement *element = NULL; + recElement **headElement = NULL; + + // look at types of interest + switch (IOHIDElementGetType(refElement)) { + case kIOHIDElementTypeInput_Misc: + case kIOHIDElementTypeInput_Button: + case kIOHIDElementTypeInput_Axis: + { + switch (usagePage) { // only interested in kHIDPage_GenericDesktop and kHIDPage_Button + case kHIDPage_GenericDesktop: + switch (usage) { + case kHIDUsage_GD_X: + case kHIDUsage_GD_Y: + case kHIDUsage_GD_Z: + case kHIDUsage_GD_Rx: + case kHIDUsage_GD_Ry: + case kHIDUsage_GD_Rz: + case kHIDUsage_GD_Slider: + case kHIDUsage_GD_Dial: + case kHIDUsage_GD_Wheel: + if (!ElementAlreadyAdded(cookie, pDevice->firstAxis)) { + element = (recElement *)SDL_calloc(1, sizeof(recElement)); + if (element) { + pDevice->axes++; + headElement = &(pDevice->firstAxis); + } + } + break; + + case kHIDUsage_GD_Hatswitch: + if (!ElementAlreadyAdded(cookie, pDevice->firstHat)) { + element = (recElement *)SDL_calloc(1, sizeof(recElement)); + if (element) { + pDevice->hats++; + headElement = &(pDevice->firstHat); + } + } + break; + case kHIDUsage_GD_DPadUp: + case kHIDUsage_GD_DPadDown: + case kHIDUsage_GD_DPadRight: + case kHIDUsage_GD_DPadLeft: + case kHIDUsage_GD_Start: + case kHIDUsage_GD_Select: + case kHIDUsage_GD_SystemMainMenu: + if (!ElementAlreadyAdded(cookie, pDevice->firstButton)) { + element = (recElement *)SDL_calloc(1, sizeof(recElement)); + if (element) { + pDevice->buttons++; + headElement = &(pDevice->firstButton); + } + } + break; + } + break; + + case kHIDPage_Simulation: + switch (usage) { + case kHIDUsage_Sim_Rudder: + case kHIDUsage_Sim_Throttle: + case kHIDUsage_Sim_Accelerator: + case kHIDUsage_Sim_Brake: + if (!ElementAlreadyAdded(cookie, pDevice->firstAxis)) { + element = (recElement *)SDL_calloc(1, sizeof(recElement)); + if (element) { + pDevice->axes++; + headElement = &(pDevice->firstAxis); + } + } + break; + + default: + break; + } + break; + + case kHIDPage_Button: + case kHIDPage_Consumer: // e.g. 'pause' button on Steelseries MFi gamepads. + if (!ElementAlreadyAdded(cookie, pDevice->firstButton)) { + element = (recElement *)SDL_calloc(1, sizeof(recElement)); + if (element) { + pDevice->buttons++; + headElement = &(pDevice->firstButton); + } + } + break; + + default: + break; + } + } break; + + case kIOHIDElementTypeCollection: + { + CFArrayRef array = IOHIDElementGetChildren(refElement); + if (array) { + AddHIDElements(array, pDevice); + } + } break; + + default: + break; + } + + if (element && headElement) { // add to list + recElement *elementPrevious = NULL; + recElement *elementCurrent = *headElement; + while (elementCurrent && usage >= elementCurrent->usage) { + elementPrevious = elementCurrent; + elementCurrent = elementCurrent->pNext; + } + if (elementPrevious) { + elementPrevious->pNext = element; + } else { + *headElement = element; + } + + element->elementRef = refElement; + element->usagePage = usagePage; + element->usage = usage; + element->pNext = elementCurrent; + + element->minReport = element->min = (SInt32)IOHIDElementGetLogicalMin(refElement); + element->maxReport = element->max = (SInt32)IOHIDElementGetLogicalMax(refElement); + element->cookie = IOHIDElementGetCookie(refElement); + + pDevice->elements++; + } + } +} + +static int GetSteamVirtualGamepadSlot(Uint16 vendor_id, Uint16 product_id, const char *product_string) +{ + int slot = -1; + + if (vendor_id == USB_VENDOR_MICROSOFT && product_id == USB_PRODUCT_XBOX360_WIRED_CONTROLLER) { + // Gamepad name is "GamePad-N", where N is slot + 1 + if (SDL_sscanf(product_string, "GamePad-%d", &slot) == 1) { + slot -= 1; + } + } + return slot; +} + +static bool GetDeviceInfo(IOHIDDeviceRef hidDevice, recDevice *pDevice) +{ + Sint32 vendor = 0; + Sint32 product = 0; + Sint32 version = 0; + char *name; + char manufacturer_string[256]; + char product_string[256]; + CFTypeRef refCF = NULL; + CFArrayRef array = NULL; + + // get usage page and usage + refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDPrimaryUsagePageKey)); + if (refCF) { + CFNumberGetValue(refCF, kCFNumberSInt32Type, &pDevice->usagePage); + } + if (pDevice->usagePage != kHIDPage_GenericDesktop) { + return false; // Filter device list to non-keyboard/mouse stuff + } + + refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDPrimaryUsageKey)); + if (refCF) { + CFNumberGetValue(refCF, kCFNumberSInt32Type, &pDevice->usage); + } + + if ((pDevice->usage != kHIDUsage_GD_Joystick && + pDevice->usage != kHIDUsage_GD_GamePad && + pDevice->usage != kHIDUsage_GD_MultiAxisController)) { + return false; // Filter device list to non-keyboard/mouse stuff + } + + /* Make sure we retain the use of the IOKit-provided device-object, + lest the device get disconnected and we try to use it. (Fixes + SDL-Bugzilla #4961, aka. https://bugzilla.libsdl.org/show_bug.cgi?id=4961 ) + */ + CFRetain(hidDevice); + + /* Now that we've CFRetain'ed the device-object (for our use), we'll + save the reference to it. + */ + pDevice->deviceRef = hidDevice; + + refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDVendorIDKey)); + if (refCF) { + CFNumberGetValue(refCF, kCFNumberSInt32Type, &vendor); + } + + refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDProductIDKey)); + if (refCF) { + CFNumberGetValue(refCF, kCFNumberSInt32Type, &product); + } + + refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDVersionNumberKey)); + if (refCF) { + CFNumberGetValue(refCF, kCFNumberSInt32Type, &version); + } + + if (SDL_IsJoystickXboxOne(vendor, product)) { + // We can't actually use this API for Xbox controllers + return false; + } + + // get device name + refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDManufacturerKey)); + if ((!refCF) || (!CFStringGetCString(refCF, manufacturer_string, sizeof(manufacturer_string), kCFStringEncodingUTF8))) { + manufacturer_string[0] = '\0'; + } + refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDProductKey)); + if ((!refCF) || (!CFStringGetCString(refCF, product_string, sizeof(product_string), kCFStringEncodingUTF8))) { + product_string[0] = '\0'; + } + name = SDL_CreateJoystickName(vendor, product, manufacturer_string, product_string); + if (name) { + SDL_strlcpy(pDevice->product, name, sizeof(pDevice->product)); + SDL_free(name); + } + + if (SDL_ShouldIgnoreJoystick(vendor, product, version, pDevice->product)) { + return false; + } + + if (SDL_JoystickHandledByAnotherDriver(&SDL_DARWIN_JoystickDriver, vendor, product, version, pDevice->product)) { + return false; + } + + pDevice->guid = SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_USB, (Uint16)vendor, (Uint16)product, (Uint16)version, manufacturer_string, product_string, 0, 0); + pDevice->steam_virtual_gamepad_slot = GetSteamVirtualGamepadSlot((Uint16)vendor, (Uint16)product, product_string); + + array = IOHIDDeviceCopyMatchingElements(hidDevice, NULL, kIOHIDOptionsTypeNone); + if (array) { + AddHIDElements(array, pDevice); + CFRelease(array); + } + + return true; +} + +static bool JoystickAlreadyKnown(IOHIDDeviceRef ioHIDDeviceObject) +{ + recDevice *i; + +#ifdef SDL_JOYSTICK_MFI + extern bool IOS_SupportedHIDDevice(IOHIDDeviceRef device); + if (IOS_SupportedHIDDevice(ioHIDDeviceObject)) { + return true; + } +#endif + + for (i = gpDeviceList; i; i = i->pNext) { + if (i->deviceRef == ioHIDDeviceObject) { + return true; + } + } + return false; +} + +static void JoystickDeviceWasAddedCallback(void *ctx, IOReturn res, void *sender, IOHIDDeviceRef ioHIDDeviceObject) +{ + recDevice *device; + io_service_t ioservice; + + if (res != kIOReturnSuccess) { + return; + } + + if (JoystickAlreadyKnown(ioHIDDeviceObject)) { + return; // IOKit sent us a duplicate. + } + + device = (recDevice *)SDL_calloc(1, sizeof(recDevice)); + if (!device) { + return; + } + + if (!GetDeviceInfo(ioHIDDeviceObject, device)) { + FreeDevice(device); + return; // not a device we care about, probably. + } + + // Get notified when this device is disconnected. + IOHIDDeviceRegisterRemovalCallback(ioHIDDeviceObject, JoystickDeviceWasRemovedCallback, device); + IOHIDDeviceScheduleWithRunLoop(ioHIDDeviceObject, CFRunLoopGetCurrent(), SDL_JOYSTICK_RUNLOOP_MODE); + device->runLoopAttached = true; + + // Allocate an instance ID for this device + device->instance_id = SDL_GetNextObjectID(); + + // We have to do some storage of the io_service_t for SDL_OpenHapticFromJoystick + ioservice = IOHIDDeviceGetService(ioHIDDeviceObject); + if ((ioservice) && (FFIsForceFeedback(ioservice) == FF_OK)) { + device->ffservice = ioservice; +#ifdef SDL_HAPTIC_IOKIT + MacHaptic_MaybeAddDevice(ioservice); +#endif + } + + // Add device to the end of the list + if (!gpDeviceList) { + gpDeviceList = device; + } else { + recDevice *curdevice; + + curdevice = gpDeviceList; + while (curdevice->pNext) { + curdevice = curdevice->pNext; + } + curdevice->pNext = device; + } + + SDL_PrivateJoystickAdded(device->instance_id); +} + +static bool ConfigHIDManager(CFArrayRef matchingArray) +{ + CFRunLoopRef runloop = CFRunLoopGetCurrent(); + + if (IOHIDManagerOpen(hidman, kIOHIDOptionsTypeNone) != kIOReturnSuccess) { + return false; + } + + IOHIDManagerSetDeviceMatchingMultiple(hidman, matchingArray); + IOHIDManagerRegisterDeviceMatchingCallback(hidman, JoystickDeviceWasAddedCallback, NULL); + IOHIDManagerScheduleWithRunLoop(hidman, runloop, SDL_JOYSTICK_RUNLOOP_MODE); + + while (CFRunLoopRunInMode(SDL_JOYSTICK_RUNLOOP_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) { + // no-op. Callback fires once per existing device. + } + + // future hotplug events will come through SDL_JOYSTICK_RUNLOOP_MODE now. + + return true; // good to go. +} + +static CFDictionaryRef CreateHIDDeviceMatchDictionary(const UInt32 page, const UInt32 usage, int *okay) +{ + CFDictionaryRef result = NULL; + CFNumberRef pageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page); + CFNumberRef usageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage); + const void *keys[2] = { (void *)CFSTR(kIOHIDDeviceUsagePageKey), (void *)CFSTR(kIOHIDDeviceUsageKey) }; + const void *vals[2] = { (void *)pageNumRef, (void *)usageNumRef }; + + if (pageNumRef && usageNumRef) { + result = CFDictionaryCreate(kCFAllocatorDefault, keys, vals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + } + + if (pageNumRef) { + CFRelease(pageNumRef); + } + if (usageNumRef) { + CFRelease(usageNumRef); + } + + if (!result) { + *okay = 0; + } + + return result; +} + +static bool CreateHIDManager(void) +{ + bool result = false; + int okay = 1; + const void *vals[] = { + (void *)CreateHIDDeviceMatchDictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Joystick, &okay), + (void *)CreateHIDDeviceMatchDictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_GamePad, &okay), + (void *)CreateHIDDeviceMatchDictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_MultiAxisController, &okay), + }; + const size_t numElements = SDL_arraysize(vals); + CFArrayRef array = okay ? CFArrayCreate(kCFAllocatorDefault, vals, numElements, &kCFTypeArrayCallBacks) : NULL; + size_t i; + + for (i = 0; i < numElements; i++) { + if (vals[i]) { + CFRelease((CFTypeRef)vals[i]); + } + } + + if (array) { + hidman = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); + if (hidman != NULL) { + result = ConfigHIDManager(array); + } + CFRelease(array); + } + + return result; +} + +static bool DARWIN_JoystickInit(void) +{ + if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_IOKIT, true)) { + return true; + } + + if (!CreateHIDManager()) { + return SDL_SetError("Joystick: Couldn't initialize HID Manager"); + } + + return true; +} + +static int DARWIN_JoystickGetCount(void) +{ + recDevice *device = gpDeviceList; + int nJoySticks = 0; + + while (device) { + if (!device->removed) { + nJoySticks++; + } + device = device->pNext; + } + + return nJoySticks; +} + +static void DARWIN_JoystickDetect(void) +{ + recDevice *device = gpDeviceList; + while (device) { + if (device->removed) { + device = FreeDevice(device); + } else { + device = device->pNext; + } + } + + if (hidman) { + /* run this after the checks above so we don't set device->removed and delete the device before + DARWIN_JoystickUpdate can run to clean up the SDL_Joystick object that owns this device */ + while (CFRunLoopRunInMode(SDL_JOYSTICK_RUNLOOP_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) { + // no-op. Pending callbacks will fire in CFRunLoopRunInMode(). + } + } +} + +static bool DARWIN_JoystickIsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ + // We don't override any other drivers + return false; +} + +static const char *DARWIN_JoystickGetDeviceName(int device_index) +{ + recDevice *device = GetDeviceForIndex(device_index); + return device ? device->product : "UNKNOWN"; +} + +static const char *DARWIN_JoystickGetDevicePath(int device_index) +{ + return NULL; +} + +static int DARWIN_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index) +{ + recDevice *device = GetDeviceForIndex(device_index); + return device ? device->steam_virtual_gamepad_slot : -1; +} + +static int DARWIN_JoystickGetDevicePlayerIndex(int device_index) +{ + return -1; +} + +static void DARWIN_JoystickSetDevicePlayerIndex(int device_index, int player_index) +{ +} + +static SDL_GUID DARWIN_JoystickGetDeviceGUID(int device_index) +{ + recDevice *device = GetDeviceForIndex(device_index); + SDL_GUID guid; + if (device) { + guid = device->guid; + } else { + SDL_zero(guid); + } + return guid; +} + +static SDL_JoystickID DARWIN_JoystickGetDeviceInstanceID(int device_index) +{ + recDevice *device = GetDeviceForIndex(device_index); + return device ? device->instance_id : 0; +} + +static bool DARWIN_JoystickOpen(SDL_Joystick *joystick, int device_index) +{ + recDevice *device = GetDeviceForIndex(device_index); + + joystick->hwdata = device; + device->joystick = joystick; + joystick->name = device->product; + + joystick->naxes = device->axes; + joystick->nhats = device->hats; + joystick->nbuttons = device->buttons; + + if (device->ffservice) { + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true); + } + + return true; +} + +/* + * Like strerror but for force feedback errors. + */ +static const char *FFStrError(unsigned int err) +{ + switch (err) { + case FFERR_DEVICEFULL: + return "device full"; + // This should be valid, but for some reason isn't defined... + /* case FFERR_DEVICENOTREG: + return "device not registered"; */ + case FFERR_DEVICEPAUSED: + return "device paused"; + case FFERR_DEVICERELEASED: + return "device released"; + case FFERR_EFFECTPLAYING: + return "effect playing"; + case FFERR_EFFECTTYPEMISMATCH: + return "effect type mismatch"; + case FFERR_EFFECTTYPENOTSUPPORTED: + return "effect type not supported"; + case FFERR_GENERIC: + return "undetermined error"; + case FFERR_HASEFFECTS: + return "device has effects"; + case FFERR_INCOMPLETEEFFECT: + return "incomplete effect"; + case FFERR_INTERNAL: + return "internal fault"; + case FFERR_INVALIDDOWNLOADID: + return "invalid download id"; + case FFERR_INVALIDPARAM: + return "invalid parameter"; + case FFERR_MOREDATA: + return "more data"; + case FFERR_NOINTERFACE: + return "interface not supported"; + case FFERR_NOTDOWNLOADED: + return "effect is not downloaded"; + case FFERR_NOTINITIALIZED: + return "object has not been initialized"; + case FFERR_OUTOFMEMORY: + return "out of memory"; + case FFERR_UNPLUGGED: + return "device is unplugged"; + case FFERR_UNSUPPORTED: + return "function call unsupported"; + case FFERR_UNSUPPORTEDAXIS: + return "axis unsupported"; + + default: + return "unknown error"; + } +} + +static bool DARWIN_JoystickInitRumble(recDevice *device, Sint16 magnitude) +{ + HRESULT result; + + if (!device->ffdevice) { + result = FFCreateDevice(device->ffservice, &device->ffdevice); + if (result != FF_OK) { + return SDL_SetError("Unable to create force feedback device from service: %s", FFStrError(result)); + } + } + + // Reset and then enable actuators + result = FFDeviceSendForceFeedbackCommand(device->ffdevice, FFSFFC_RESET); + if (result != FF_OK) { + return SDL_SetError("Unable to reset force feedback device: %s", FFStrError(result)); + } + + result = FFDeviceSendForceFeedbackCommand(device->ffdevice, FFSFFC_SETACTUATORSON); + if (result != FF_OK) { + return SDL_SetError("Unable to enable force feedback actuators: %s", FFStrError(result)); + } + + // Create the effect + device->ffeffect = CreateRumbleEffectData(magnitude); + if (!device->ffeffect) { + return false; + } + + result = FFDeviceCreateEffect(device->ffdevice, kFFEffectType_Sine_ID, + device->ffeffect, &device->ffeffect_ref); + if (result != FF_OK) { + return SDL_SetError("Haptic: Unable to create effect: %s", FFStrError(result)); + } + return true; +} + +static bool DARWIN_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + HRESULT result; + recDevice *device = joystick->hwdata; + + // Scale and average the two rumble strengths + Sint16 magnitude = (Sint16)(((low_frequency_rumble / 2) + (high_frequency_rumble / 2)) / 2); + + if (!device) { + return SDL_SetError("Rumble failed, device disconnected"); + } + + if (!device->ffservice) { + return SDL_Unsupported(); + } + + if (device->ff_initialized) { + FFPERIODIC *periodic = ((FFPERIODIC *)device->ffeffect->lpvTypeSpecificParams); + periodic->dwMagnitude = CONVERT_MAGNITUDE(magnitude); + + result = FFEffectSetParameters(device->ffeffect_ref, device->ffeffect, + (FFEP_DURATION | FFEP_TYPESPECIFICPARAMS)); + if (result != FF_OK) { + return SDL_SetError("Unable to update rumble effect: %s", FFStrError(result)); + } + } else { + if (!DARWIN_JoystickInitRumble(device, magnitude)) { + return false; + } + device->ff_initialized = true; + } + + result = FFEffectStart(device->ffeffect_ref, 1, 0); + if (result != FF_OK) { + return SDL_SetError("Unable to run the rumble effect: %s", FFStrError(result)); + } + return true; +} + +static bool DARWIN_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static bool DARWIN_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool DARWIN_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool DARWIN_JoystickSetSensorsEnabled(SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static void DARWIN_JoystickUpdate(SDL_Joystick *joystick) +{ + recDevice *device = joystick->hwdata; + recElement *element; + SInt32 value, range; + int i, goodRead = false; + Uint64 timestamp = SDL_GetTicksNS(); + + if (!device) { + return; + } + + if (device->removed) { // device was unplugged; ignore it. + if (joystick->hwdata) { + joystick->hwdata = NULL; + } + return; + } + + element = device->firstAxis; + i = 0; + + while (element) { + goodRead = GetHIDScaledCalibratedState(device, element, -32768, 32767, &value); + if (goodRead) { + SDL_SendJoystickAxis(timestamp, joystick, i, value); + } + + element = element->pNext; + ++i; + } + + element = device->firstButton; + i = 0; + while (element) { + goodRead = GetHIDElementState(device, element, &value); + if (goodRead) { + SDL_SendJoystickButton(timestamp, joystick, i, (value != 0)); + } + + element = element->pNext; + ++i; + } + + element = device->firstHat; + i = 0; + + while (element) { + Uint8 pos = 0; + + range = (element->max - element->min + 1); + goodRead = GetHIDElementState(device, element, &value); + if (goodRead) { + value -= element->min; + if (range == 4) { // 4 position hatswitch - scale up value + value *= 2; + } else if (range != 8) { // Neither a 4 nor 8 positions - fall back to default position (centered) + value = -1; + } + switch (value) { + case 0: + pos = SDL_HAT_UP; + break; + case 1: + pos = SDL_HAT_RIGHTUP; + break; + case 2: + pos = SDL_HAT_RIGHT; + break; + case 3: + pos = SDL_HAT_RIGHTDOWN; + break; + case 4: + pos = SDL_HAT_DOWN; + break; + case 5: + pos = SDL_HAT_LEFTDOWN; + break; + case 6: + pos = SDL_HAT_LEFT; + break; + case 7: + pos = SDL_HAT_LEFTUP; + break; + default: + /* Every other value is mapped to center. We do that because some + * joysticks use 8 and some 15 for this value, and apparently + * there are even more variants out there - so we try to be generous. + */ + pos = SDL_HAT_CENTERED; + break; + } + + SDL_SendJoystickHat(timestamp, joystick, i, pos); + } + + element = element->pNext; + ++i; + } +} + +static void DARWIN_JoystickClose(SDL_Joystick *joystick) +{ + recDevice *device = joystick->hwdata; + if (device) { + device->joystick = NULL; + } +} + +static void DARWIN_JoystickQuit(void) +{ + while (FreeDevice(gpDeviceList)) { + // spin + } + + if (hidman) { + IOHIDManagerUnscheduleFromRunLoop(hidman, CFRunLoopGetCurrent(), SDL_JOYSTICK_RUNLOOP_MODE); + IOHIDManagerClose(hidman, kIOHIDOptionsTypeNone); + CFRelease(hidman); + hidman = NULL; + } +} + +static bool DARWIN_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) +{ + return false; +} + +SDL_JoystickDriver SDL_DARWIN_JoystickDriver = { + DARWIN_JoystickInit, + DARWIN_JoystickGetCount, + DARWIN_JoystickDetect, + DARWIN_JoystickIsDevicePresent, + DARWIN_JoystickGetDeviceName, + DARWIN_JoystickGetDevicePath, + DARWIN_JoystickGetDeviceSteamVirtualGamepadSlot, + DARWIN_JoystickGetDevicePlayerIndex, + DARWIN_JoystickSetDevicePlayerIndex, + DARWIN_JoystickGetDeviceGUID, + DARWIN_JoystickGetDeviceInstanceID, + DARWIN_JoystickOpen, + DARWIN_JoystickRumble, + DARWIN_JoystickRumbleTriggers, + DARWIN_JoystickSetLED, + DARWIN_JoystickSendEffect, + DARWIN_JoystickSetSensorsEnabled, + DARWIN_JoystickUpdate, + DARWIN_JoystickClose, + DARWIN_JoystickQuit, + DARWIN_JoystickGetGamepadMapping +}; + +#endif // SDL_JOYSTICK_IOKIT diff --git a/thirdparty/sdl/joystick/darwin/SDL_iokitjoystick_c.h b/thirdparty/sdl/joystick/darwin/SDL_iokitjoystick_c.h new file mode 100644 index 00000000000..91deb240e47 --- /dev/null +++ b/thirdparty/sdl/joystick/darwin/SDL_iokitjoystick_c.h @@ -0,0 +1,80 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_JOYSTICK_IOKIT_H +#define SDL_JOYSTICK_IOKIT_H + +#include +#include +#include + +struct recElement +{ + IOHIDElementRef elementRef; + IOHIDElementCookie cookie; + uint32_t usagePage, usage; // HID usage + SInt32 min; // reported min value possible + SInt32 max; // reported max value possible + + // runtime variables used for auto-calibration + SInt32 minReport; // min returned value + SInt32 maxReport; // max returned value + + struct recElement *pNext; // next element in list +}; +typedef struct recElement recElement; + +struct joystick_hwdata +{ + IOHIDDeviceRef deviceRef; // HIDManager device handle + io_service_t ffservice; // Interface for force feedback, 0 = no ff + FFDeviceObjectReference ffdevice; + FFEFFECT *ffeffect; + FFEffectObjectReference ffeffect_ref; + bool ff_initialized; + + char product[256]; // name of product + uint32_t usage; // usage page from IOUSBHID Parser.h which defines general usage + uint32_t usagePage; // usage within above page from IOUSBHID Parser.h which defines specific usage + + int axes; // number of axis (calculated, not reported by device) + int buttons; // number of buttons (calculated, not reported by device) + int hats; // number of hat switches (calculated, not reported by device) + int elements; // number of total elements (should be total of above) (calculated, not reported by device) + + recElement *firstAxis; + recElement *firstButton; + recElement *firstHat; + + bool removed; + SDL_Joystick *joystick; + bool runLoopAttached; // is 'deviceRef' attached to a CFRunLoop? + + int instance_id; + SDL_GUID guid; + int steam_virtual_gamepad_slot; + + struct joystick_hwdata *pNext; // next device +}; +typedef struct joystick_hwdata recDevice; + +#endif // SDL_JOYSTICK_IOKIT_H diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_combined.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_combined.c new file mode 100644 index 00000000000..5426edbd71e --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_combined.c @@ -0,0 +1,236 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +// This driver supports the Nintendo Switch Joy-Cons pair controllers +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "SDL_hidapijoystick_c.h" +#include "../SDL_sysjoystick.h" + +static void HIDAPI_DriverCombined_RegisterHints(SDL_HintCallback callback, void *userdata) +{ +} + +static void HIDAPI_DriverCombined_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ +} + +static bool HIDAPI_DriverCombined_IsEnabled(void) +{ + return true; +} + +static bool HIDAPI_DriverCombined_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + // This is always explicitly created for combined devices + return false; +} + +static bool HIDAPI_DriverCombined_InitDevice(SDL_HIDAPI_Device *device) +{ + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverCombined_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverCombined_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ +} + +static bool HIDAPI_DriverCombined_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + int i; + char *serial = NULL, *new_serial; + size_t serial_length = 0, new_length; + + SDL_AssertJoysticksLocked(); + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + if (!child->driver->OpenJoystick(child, joystick)) { + child->broken = true; + + while (i-- > 0) { + child = device->children[i]; + child->driver->CloseJoystick(child, joystick); + } + if (serial) { + SDL_free(serial); + } + return false; + } + + // Extend the serial number with the child serial number + if (joystick->serial) { + new_length = serial_length + 1 + SDL_strlen(joystick->serial); + new_serial = (char *)SDL_realloc(serial, new_length); + if (new_serial) { + if (serial) { + SDL_strlcat(new_serial, ",", new_length); + SDL_strlcat(new_serial, joystick->serial, new_length); + } else { + SDL_strlcpy(new_serial, joystick->serial, new_length); + } + serial = new_serial; + serial_length = new_length; + } + SDL_free(joystick->serial); + joystick->serial = NULL; + } + } + + // Update the joystick with the combined serial numbers + if (joystick->serial) { + SDL_free(joystick->serial); + } + joystick->serial = serial; + + return true; +} + +static bool HIDAPI_DriverCombined_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + int i; + bool result = false; + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + if (child->driver->RumbleJoystick(child, joystick, low_frequency_rumble, high_frequency_rumble)) { + result = true; + } + } + return result; +} + +static bool HIDAPI_DriverCombined_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + int i; + bool result = false; + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + if (child->driver->RumbleJoystickTriggers(child, joystick, left_rumble, right_rumble)) { + result = true; + } + } + return result; +} + +static Uint32 HIDAPI_DriverCombined_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + int i; + Uint32 caps = 0; + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + caps |= child->driver->GetJoystickCapabilities(child, joystick); + } + return caps; +} + +static bool HIDAPI_DriverCombined_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + int i; + bool result = false; + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + if (child->driver->SetJoystickLED(child, joystick, red, green, blue)) { + result = true; + } + } + return result; +} + +static bool HIDAPI_DriverCombined_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverCombined_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + int i; + bool result = false; + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + if (child->driver->SetJoystickSensorsEnabled(child, joystick, enabled)) { + result = true; + } + } + return result; +} + +static bool HIDAPI_DriverCombined_UpdateDevice(SDL_HIDAPI_Device *device) +{ + int i; + int result = true; + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + if (!child->driver->UpdateDevice(child)) { + result = false; + } + } + return result; +} + +static void HIDAPI_DriverCombined_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + int i; + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + child->driver->CloseJoystick(child, joystick); + } +} + +static void HIDAPI_DriverCombined_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverCombined = { + "SDL_JOYSTICK_HIDAPI_COMBINED", + true, + HIDAPI_DriverCombined_RegisterHints, + HIDAPI_DriverCombined_UnregisterHints, + HIDAPI_DriverCombined_IsEnabled, + HIDAPI_DriverCombined_IsSupportedDevice, + HIDAPI_DriverCombined_InitDevice, + HIDAPI_DriverCombined_GetDevicePlayerIndex, + HIDAPI_DriverCombined_SetDevicePlayerIndex, + HIDAPI_DriverCombined_UpdateDevice, + HIDAPI_DriverCombined_OpenJoystick, + HIDAPI_DriverCombined_RumbleJoystick, + HIDAPI_DriverCombined_RumbleJoystickTriggers, + HIDAPI_DriverCombined_GetJoystickCapabilities, + HIDAPI_DriverCombined_SetJoystickLED, + HIDAPI_DriverCombined_SendJoystickEffect, + HIDAPI_DriverCombined_SetJoystickSensorsEnabled, + HIDAPI_DriverCombined_CloseJoystick, + HIDAPI_DriverCombined_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_gamecube.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_gamecube.c new file mode 100644 index 00000000000..4d45c7a264d --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_gamecube.c @@ -0,0 +1,534 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../../SDL_hints_c.h" +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" +#include "../../hidapi/SDL_hidapi_c.h" + +#ifdef SDL_JOYSTICK_HIDAPI_GAMECUBE + +// Define this if you want to log all packets from the controller +// #define DEBUG_GAMECUBE_PROTOCOL + +#define MAX_CONTROLLERS 4 + +typedef struct +{ + bool pc_mode; + SDL_JoystickID joysticks[MAX_CONTROLLERS]; + Uint8 wireless[MAX_CONTROLLERS]; + Uint8 min_axis[MAX_CONTROLLERS * SDL_GAMEPAD_AXIS_COUNT]; + Uint8 max_axis[MAX_CONTROLLERS * SDL_GAMEPAD_AXIS_COUNT]; + Uint8 rumbleAllowed[MAX_CONTROLLERS]; + Uint8 rumble[1 + MAX_CONTROLLERS]; + // Without this variable, hid_write starts to lag a TON + bool rumbleUpdate; + bool useRumbleBrake; +} SDL_DriverGameCube_Context; + +static void HIDAPI_DriverGameCube_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE, callback, userdata); +} + +static void HIDAPI_DriverGameCube_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE, callback, userdata); +} + +static bool HIDAPI_DriverGameCube_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE, + SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, + SDL_HIDAPI_DEFAULT)); +} + +static bool HIDAPI_DriverGameCube_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + if (vendor_id == USB_VENDOR_NINTENDO && product_id == USB_PRODUCT_NINTENDO_GAMECUBE_ADAPTER) { + // Nintendo Co., Ltd. Wii U GameCube Controller Adapter + return true; + } + if (vendor_id == USB_VENDOR_DRAGONRISE && + (product_id == USB_PRODUCT_EVORETRO_GAMECUBE_ADAPTER1 || + product_id == USB_PRODUCT_EVORETRO_GAMECUBE_ADAPTER2)) { + // EVORETRO GameCube Controller Adapter + return true; + } + return false; +} + +static void ResetAxisRange(SDL_DriverGameCube_Context *ctx, int joystick_index) +{ + SDL_memset(&ctx->min_axis[joystick_index * SDL_GAMEPAD_AXIS_COUNT], 128 - 88, SDL_GAMEPAD_AXIS_COUNT); + SDL_memset(&ctx->max_axis[joystick_index * SDL_GAMEPAD_AXIS_COUNT], 128 + 88, SDL_GAMEPAD_AXIS_COUNT); + + // Trigger axes may have a higher resting value + ctx->min_axis[joystick_index * SDL_GAMEPAD_AXIS_COUNT + SDL_GAMEPAD_AXIS_LEFT_TRIGGER] = 40; + ctx->min_axis[joystick_index * SDL_GAMEPAD_AXIS_COUNT + SDL_GAMEPAD_AXIS_RIGHT_TRIGGER] = 40; +} + +static void SDLCALL SDL_JoystickGameCubeRumbleBrakeHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + if (hint) { + SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)userdata; + ctx->useRumbleBrake = SDL_GetStringBoolean(hint, false); + } +} + +static bool HIDAPI_DriverGameCube_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverGameCube_Context *ctx; + Uint8 packet[37]; + Uint8 *curSlot; + Uint8 i; + int size; + Uint8 initMagic = 0x13; + Uint8 rumbleMagic = 0x11; + +#ifdef HAVE_ENABLE_GAMECUBE_ADAPTORS + SDL_EnableGameCubeAdaptors(); +#endif + + ctx = (SDL_DriverGameCube_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + device->context = ctx; + + ctx->joysticks[0] = 0; + ctx->joysticks[1] = 0; + ctx->joysticks[2] = 0; + ctx->joysticks[3] = 0; + ctx->rumble[0] = rumbleMagic; + ctx->useRumbleBrake = false; + + if (device->vendor_id != USB_VENDOR_NINTENDO) { + ctx->pc_mode = true; + } + + if (ctx->pc_mode) { + for (i = 0; i < MAX_CONTROLLERS; ++i) { + ResetAxisRange(ctx, i); + HIDAPI_JoystickConnected(device, &ctx->joysticks[i]); + } + } else { + // This is all that's needed to initialize the device. Really! + if (SDL_hid_write(device->dev, &initMagic, sizeof(initMagic)) != sizeof(initMagic)) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "HIDAPI_DriverGameCube_InitDevice(): Couldn't initialize WUP-028"); + return false; + } + + // Wait for the adapter to initialize + SDL_Delay(10); + + // Add all the applicable joysticks + while ((size = SDL_hid_read_timeout(device->dev, packet, sizeof(packet), 0)) > 0) { +#ifdef DEBUG_GAMECUBE_PROTOCOL + HIDAPI_DumpPacket("Nintendo GameCube packet: size = %d", packet, size); +#endif + if (size < 37 || packet[0] != 0x21) { + continue; // Nothing to do yet...? + } + + // Go through all 4 slots + curSlot = packet + 1; + for (i = 0; i < MAX_CONTROLLERS; i += 1, curSlot += 9) { + ctx->wireless[i] = (curSlot[0] & 0x20) != 0; + + // Only allow rumble if the adapter's second USB cable is connected + ctx->rumbleAllowed[i] = (curSlot[0] & 0x04) && !ctx->wireless[i]; + + if (curSlot[0] & 0x30) { // 0x10 - Wired, 0x20 - Wireless + if (ctx->joysticks[i] == 0) { + ResetAxisRange(ctx, i); + HIDAPI_JoystickConnected(device, &ctx->joysticks[i]); + } + } else { + if (ctx->joysticks[i] != 0) { + HIDAPI_JoystickDisconnected(device, ctx->joysticks[i]); + ctx->joysticks[i] = 0; + } + continue; + } + } + } + } + + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE_RUMBLE_BRAKE, + SDL_JoystickGameCubeRumbleBrakeHintChanged, ctx); + + HIDAPI_SetDeviceName(device, "Nintendo GameCube Controller"); + + return true; +} + +static int HIDAPI_DriverGameCube_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; + Uint8 i; + + for (i = 0; i < 4; ++i) { + if (instance_id == ctx->joysticks[i]) { + return i; + } + } + return -1; +} + +static void HIDAPI_DriverGameCube_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ +} + +static void HIDAPI_DriverGameCube_HandleJoystickPacket(SDL_HIDAPI_Device *device, SDL_DriverGameCube_Context *ctx, const Uint8 *packet, int size) +{ + SDL_Joystick *joystick; + Uint8 i, v; + Sint16 axis_value; + Uint64 timestamp = SDL_GetTicksNS(); + + if (size != 10) { + return; // How do we handle this packet? + } + + i = packet[0] - 1; + if (i >= MAX_CONTROLLERS) { + return; // How do we handle this packet? + } + + joystick = SDL_GetJoystickFromID(ctx->joysticks[i]); + if (!joystick) { + // Hasn't been opened yet, skip + return; + } + +#define READ_BUTTON(off, flag, button) \ + SDL_SendJoystickButton( \ + timestamp, \ + joystick, \ + button, \ + ((packet[off] & flag) != 0)); + READ_BUTTON(1, 0x02, 0) // A + READ_BUTTON(1, 0x04, 1) // B + READ_BUTTON(1, 0x08, 3) // Y + READ_BUTTON(1, 0x01, 2) // X + READ_BUTTON(2, 0x80, 4) // DPAD_LEFT + READ_BUTTON(2, 0x20, 5) // DPAD_RIGHT + READ_BUTTON(2, 0x40, 6) // DPAD_DOWN + READ_BUTTON(2, 0x10, 7) // DPAD_UP + READ_BUTTON(2, 0x02, 8) // START + READ_BUTTON(1, 0x80, 9) // RIGHTSHOULDER + /* These two buttons are for the bottoms of the analog triggers. + * More than likely, you're going to want to read the axes instead! + * -flibit + */ + READ_BUTTON(1, 0x20, 10) // TRIGGERRIGHT + READ_BUTTON(1, 0x10, 11) // TRIGGERLEFT +#undef READ_BUTTON + +#define READ_AXIS(off, axis, invert) \ + v = invert ? (0xff - packet[off]) : packet[off]; \ + if (v < ctx->min_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis]) \ + ctx->min_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis] = v; \ + if (v > ctx->max_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis]) \ + ctx->max_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis] = v; \ + axis_value = (Sint16)HIDAPI_RemapVal(v, ctx->min_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis], ctx->max_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis], SDL_MIN_SINT16, SDL_MAX_SINT16); \ + SDL_SendJoystickAxis( \ + timestamp, \ + joystick, \ + axis, axis_value); + READ_AXIS(3, SDL_GAMEPAD_AXIS_LEFTX, 0) + READ_AXIS(4, SDL_GAMEPAD_AXIS_LEFTY, 1) + READ_AXIS(6, SDL_GAMEPAD_AXIS_RIGHTX, 0) + READ_AXIS(5, SDL_GAMEPAD_AXIS_RIGHTY, 1) + READ_AXIS(7, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 0) + READ_AXIS(8, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 0) +#undef READ_AXIS +} + +static void HIDAPI_DriverGameCube_HandleNintendoPacket(SDL_HIDAPI_Device *device, SDL_DriverGameCube_Context *ctx, Uint8 *packet, int size) +{ + SDL_Joystick *joystick; + Uint8 *curSlot; + Uint8 i; + Sint16 axis_value; + Uint64 timestamp = SDL_GetTicksNS(); + + if (size < 37 || packet[0] != 0x21) { + return; // Nothing to do right now...? + } + + // Go through all 4 slots + curSlot = packet + 1; + for (i = 0; i < MAX_CONTROLLERS; i += 1, curSlot += 9) { + ctx->wireless[i] = (curSlot[0] & 0x20) != 0; + + // Only allow rumble if the adapter's second USB cable is connected + ctx->rumbleAllowed[i] = (curSlot[0] & 0x04) && !ctx->wireless[i]; + + if (curSlot[0] & 0x30) { // 0x10 - Wired, 0x20 - Wireless + if (ctx->joysticks[i] == 0) { + ResetAxisRange(ctx, i); + HIDAPI_JoystickConnected(device, &ctx->joysticks[i]); + } + joystick = SDL_GetJoystickFromID(ctx->joysticks[i]); + + // Hasn't been opened yet, skip + if (!joystick) { + continue; + } + } else { + if (ctx->joysticks[i] != 0) { + HIDAPI_JoystickDisconnected(device, ctx->joysticks[i]); + ctx->joysticks[i] = 0; + } + continue; + } + +#define READ_BUTTON(off, flag, button) \ + SDL_SendJoystickButton( \ + timestamp, \ + joystick, \ + button, \ + ((curSlot[off] & flag) != 0)); + READ_BUTTON(1, 0x01, 0) // A + READ_BUTTON(1, 0x02, 1) // B + READ_BUTTON(1, 0x04, 2) // X + READ_BUTTON(1, 0x08, 3) // Y + READ_BUTTON(1, 0x10, 4) // DPAD_LEFT + READ_BUTTON(1, 0x20, 5) // DPAD_RIGHT + READ_BUTTON(1, 0x40, 6) // DPAD_DOWN + READ_BUTTON(1, 0x80, 7) // DPAD_UP + READ_BUTTON(2, 0x01, 8) // START + READ_BUTTON(2, 0x02, 9) // RIGHTSHOULDER + /* These two buttons are for the bottoms of the analog triggers. + * More than likely, you're going to want to read the axes instead! + * -flibit + */ + READ_BUTTON(2, 0x04, 10) // TRIGGERRIGHT + READ_BUTTON(2, 0x08, 11) // TRIGGERLEFT +#undef READ_BUTTON + +#define READ_AXIS(off, axis) \ + if (curSlot[off] < ctx->min_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis]) \ + ctx->min_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis] = curSlot[off]; \ + if (curSlot[off] > ctx->max_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis]) \ + ctx->max_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis] = curSlot[off]; \ + axis_value = (Sint16)HIDAPI_RemapVal(curSlot[off], ctx->min_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis], ctx->max_axis[i * SDL_GAMEPAD_AXIS_COUNT + axis], SDL_MIN_SINT16, SDL_MAX_SINT16); \ + SDL_SendJoystickAxis( \ + timestamp, \ + joystick, \ + axis, axis_value); + READ_AXIS(3, SDL_GAMEPAD_AXIS_LEFTX) + READ_AXIS(4, SDL_GAMEPAD_AXIS_LEFTY) + READ_AXIS(5, SDL_GAMEPAD_AXIS_RIGHTX) + READ_AXIS(6, SDL_GAMEPAD_AXIS_RIGHTY) + READ_AXIS(7, SDL_GAMEPAD_AXIS_LEFT_TRIGGER) + READ_AXIS(8, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) +#undef READ_AXIS + } +} + +static bool HIDAPI_DriverGameCube_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; + Uint8 packet[USB_PACKET_LENGTH]; + int size; + + // Read input packet + while ((size = SDL_hid_read_timeout(device->dev, packet, sizeof(packet), 0)) > 0) { +#ifdef DEBUG_GAMECUBE_PROTOCOL + HIDAPI_DumpPacket("Nintendo GameCube packet: size = %d", packet, size); +#endif + if (ctx->pc_mode) { + HIDAPI_DriverGameCube_HandleJoystickPacket(device, ctx, packet, size); + } else { + HIDAPI_DriverGameCube_HandleNintendoPacket(device, ctx, packet, size); + } + } + + // Write rumble packet + if (ctx->rumbleUpdate) { + SDL_HIDAPI_SendRumble(device, ctx->rumble, sizeof(ctx->rumble)); + ctx->rumbleUpdate = false; + } + + // If we got here, nothing bad happened! + return true; +} + +static bool HIDAPI_DriverGameCube_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; + Uint8 i; + + SDL_AssertJoysticksLocked(); + + for (i = 0; i < MAX_CONTROLLERS; i += 1) { + if (joystick->instance_id == ctx->joysticks[i]) { + joystick->nbuttons = 12; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + if (ctx->wireless[i]) { + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRELESS; + } else { + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRED; + } + return true; + } + } + return false; // Should never get here! +} + +static bool HIDAPI_DriverGameCube_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; + Uint8 i, val; + + SDL_AssertJoysticksLocked(); + + if (ctx->pc_mode) { + return SDL_Unsupported(); + } + + for (i = 0; i < MAX_CONTROLLERS; i += 1) { + if (joystick->instance_id == ctx->joysticks[i]) { + if (ctx->wireless[i]) { + return SDL_SetError("Nintendo GameCube WaveBird controllers do not support rumble"); + } + if (!ctx->rumbleAllowed[i]) { + return SDL_SetError("Second USB cable for WUP-028 not connected"); + } + if (ctx->useRumbleBrake) { + if (low_frequency_rumble == 0 && high_frequency_rumble > 0) { + val = 0; // if only low is 0 we want to do a regular stop + } else if (low_frequency_rumble == 0 && high_frequency_rumble == 0) { + val = 2; // if both frequencies are 0 we want to do a hard stop + } else { + val = 1; // normal rumble + } + } else { + val = (low_frequency_rumble > 0 || high_frequency_rumble > 0); + } + if (val != ctx->rumble[i + 1]) { + ctx->rumble[i + 1] = val; + ctx->rumbleUpdate = true; + } + return true; + } + } + + // Should never get here! + return SDL_SetError("Couldn't find joystick"); +} + +static bool HIDAPI_DriverGameCube_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverGameCube_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; + Uint32 result = 0; + + SDL_AssertJoysticksLocked(); + + if (!ctx->pc_mode) { + Uint8 i; + + for (i = 0; i < MAX_CONTROLLERS; i += 1) { + if (joystick->instance_id == ctx->joysticks[i]) { + if (!ctx->wireless[i] && ctx->rumbleAllowed[i]) { + result |= SDL_JOYSTICK_CAP_RUMBLE; + break; + } + } + } + } + + return result; +} + +static bool HIDAPI_DriverGameCube_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverGameCube_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverGameCube_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static void HIDAPI_DriverGameCube_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; + + // Stop rumble activity + if (ctx->rumbleUpdate) { + SDL_HIDAPI_SendRumble(device, ctx->rumble, sizeof(ctx->rumble)); + ctx->rumbleUpdate = false; + } +} + +static void HIDAPI_DriverGameCube_FreeDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE_RUMBLE_BRAKE, + SDL_JoystickGameCubeRumbleBrakeHintChanged, ctx); +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverGameCube = { + SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE, + true, + HIDAPI_DriverGameCube_RegisterHints, + HIDAPI_DriverGameCube_UnregisterHints, + HIDAPI_DriverGameCube_IsEnabled, + HIDAPI_DriverGameCube_IsSupportedDevice, + HIDAPI_DriverGameCube_InitDevice, + HIDAPI_DriverGameCube_GetDevicePlayerIndex, + HIDAPI_DriverGameCube_SetDevicePlayerIndex, + HIDAPI_DriverGameCube_UpdateDevice, + HIDAPI_DriverGameCube_OpenJoystick, + HIDAPI_DriverGameCube_RumbleJoystick, + HIDAPI_DriverGameCube_RumbleJoystickTriggers, + HIDAPI_DriverGameCube_GetJoystickCapabilities, + HIDAPI_DriverGameCube_SetJoystickLED, + HIDAPI_DriverGameCube_SendJoystickEffect, + HIDAPI_DriverGameCube_SetJoystickSensorsEnabled, + HIDAPI_DriverGameCube_CloseJoystick, + HIDAPI_DriverGameCube_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_GAMECUBE + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_luna.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_luna.c new file mode 100644 index 00000000000..7c889a668fe --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_luna.c @@ -0,0 +1,421 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" + +#ifdef SDL_JOYSTICK_HIDAPI_LUNA + +// Define this if you want to log all packets from the controller +// #define DEBUG_LUNA_PROTOCOL + +// Sending rumble on macOS blocks for a long time and eventually fails +#ifndef SDL_PLATFORM_MACOS +#define ENABLE_LUNA_BLUETOOTH_RUMBLE +#endif + +enum +{ + SDL_GAMEPAD_BUTTON_LUNA_MICROPHONE = 11, + SDL_GAMEPAD_NUM_LUNA_BUTTONS, +}; + +typedef struct +{ + Uint8 last_state[USB_PACKET_LENGTH]; +} SDL_DriverLuna_Context; + +static void HIDAPI_DriverLuna_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_LUNA, callback, userdata); +} + +static void HIDAPI_DriverLuna_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_LUNA, callback, userdata); +} + +static bool HIDAPI_DriverLuna_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_LUNA, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)); +} + +static bool HIDAPI_DriverLuna_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + return SDL_IsJoystickAmazonLunaController(vendor_id, product_id); +} + +static bool HIDAPI_DriverLuna_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverLuna_Context *ctx; + + ctx = (SDL_DriverLuna_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + device->context = ctx; + + HIDAPI_SetDeviceName(device, "Amazon Luna Controller"); + + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverLuna_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverLuna_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ +} + +static bool HIDAPI_DriverLuna_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverLuna_Context *ctx = (SDL_DriverLuna_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + SDL_zeroa(ctx->last_state); + + // Initialize the joystick capabilities + joystick->nbuttons = SDL_GAMEPAD_NUM_LUNA_BUTTONS; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + + return true; +} + +static bool HIDAPI_DriverLuna_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ +#ifdef ENABLE_LUNA_BLUETOOTH_RUMBLE + if (device->product_id == BLUETOOTH_PRODUCT_LUNA_CONTROLLER) { + // Same packet as on Xbox One controllers connected via Bluetooth + Uint8 rumble_packet[] = { 0x03, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xEB }; + + // Magnitude is 1..100 so scale the 16-bit input here + rumble_packet[4] = (Uint8)(low_frequency_rumble / 655); + rumble_packet[5] = (Uint8)(high_frequency_rumble / 655); + + if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { + return SDL_SetError("Couldn't send rumble packet"); + } + + return true; + } +#endif // ENABLE_LUNA_BLUETOOTH_RUMBLE + + // There is currently no rumble packet over USB + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverLuna_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverLuna_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + Uint32 result = 0; + +#ifdef ENABLE_LUNA_BLUETOOTH_RUMBLE + if (device->product_id == BLUETOOTH_PRODUCT_LUNA_CONTROLLER) { + result |= SDL_JOYSTICK_CAP_RUMBLE; + } +#endif + + return result; +} + +static bool HIDAPI_DriverLuna_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverLuna_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverLuna_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static void HIDAPI_DriverLuna_HandleUSBStatePacket(SDL_Joystick *joystick, SDL_DriverLuna_Context *ctx, Uint8 *data, int size) +{ + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->last_state[1] != data[1]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[1] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[1] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[1] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[1] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[1] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[1] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[1] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[1] & 0x80) != 0)); + } + if (ctx->last_state[2] != data[2]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[2] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LUNA_MICROPHONE, ((data[2] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[2] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[2] & 0x08) != 0)); + } + + if (ctx->last_state[3] != data[3]) { + Uint8 hat; + + switch (data[3] & 0x0f) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + +#define READ_STICK_AXIS(offset) \ + (data[offset] == 0x7f ? 0 : (Sint16)HIDAPI_RemapVal((float)data[offset], 0x00, 0xff, SDL_MIN_SINT16, SDL_MAX_SINT16)) + { + Sint16 axis = READ_STICK_AXIS(4); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = READ_STICK_AXIS(5); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = READ_STICK_AXIS(6); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = READ_STICK_AXIS(7); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + } +#undef READ_STICK_AXIS + +#define READ_TRIGGER_AXIS(offset) \ + (Sint16) HIDAPI_RemapVal((float)data[offset], 0x00, 0xff, SDL_MIN_SINT16, SDL_MAX_SINT16) + { + Sint16 axis = READ_TRIGGER_AXIS(8); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + axis = READ_TRIGGER_AXIS(9); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + } +#undef READ_TRIGGER_AXIS + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static void HIDAPI_DriverLuna_HandleBluetoothStatePacket(SDL_Joystick *joystick, SDL_DriverLuna_Context *ctx, Uint8 *data, int size) +{ + Uint64 timestamp = SDL_GetTicksNS(); + + if (size >= 2 && data[0] == 0x02) { + // Home button has dedicated report + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[1] & 0x1) != 0)); + return; + } + + if (size >= 2 && data[0] == 0x04) { + // Battery level report + int percent = (int)SDL_roundf((data[1] / 255.0f) * 100.0f); + SDL_SendJoystickPowerInfo(joystick, SDL_POWERSTATE_ON_BATTERY, percent); + return; + } + + if (size < 17 || data[0] != 0x01) { + // We don't know how to handle this report + return; + } + + if (ctx->last_state[13] != data[13]) { + Uint8 hat; + + switch (data[13] & 0x0f) { + case 1: + hat = SDL_HAT_UP; + break; + case 2: + hat = SDL_HAT_RIGHTUP; + break; + case 3: + hat = SDL_HAT_RIGHT; + break; + case 4: + hat = SDL_HAT_RIGHTDOWN; + break; + case 5: + hat = SDL_HAT_DOWN; + break; + case 6: + hat = SDL_HAT_LEFTDOWN; + break; + case 7: + hat = SDL_HAT_LEFT; + break; + case 8: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + if (ctx->last_state[14] != data[14]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[14] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[14] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[14] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[14] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[14] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[14] & 0x80) != 0)); + } + if (ctx->last_state[15] != data[15]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[15] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[15] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[15] & 0x40) != 0)); + } + if (ctx->last_state[16] != data[16]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[16] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LUNA_MICROPHONE, ((data[16] & 0x02) != 0)); + } + +#define READ_STICK_AXIS(offset) \ + (data[offset] == 0x7f ? 0 : (Sint16)HIDAPI_RemapVal((float)data[offset], 0x00, 0xff, SDL_MIN_SINT16, SDL_MAX_SINT16)) + { + Sint16 axis = READ_STICK_AXIS(2); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = READ_STICK_AXIS(4); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = READ_STICK_AXIS(6); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = READ_STICK_AXIS(8); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + } +#undef READ_STICK_AXIS + +#define READ_TRIGGER_AXIS(offset) \ + (Sint16) HIDAPI_RemapVal((float)((int)(((data[offset] | (data[offset + 1] << 8)) & 0x3ff) - 0x200)), 0x00 - 0x200, 0x3ff - 0x200, SDL_MIN_SINT16, SDL_MAX_SINT16) + { + Sint16 axis = READ_TRIGGER_AXIS(9); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + axis = READ_TRIGGER_AXIS(11); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + } +#undef READ_TRIGGER_AXIS + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static bool HIDAPI_DriverLuna_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverLuna_Context *ctx = (SDL_DriverLuna_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH]; + int size = 0; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } else { + return false; + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { +#ifdef DEBUG_LUNA_PROTOCOL + HIDAPI_DumpPacket("Amazon Luna packet: size = %d", data, size); +#endif + if (!joystick) { + continue; + } + + switch (size) { + case 10: + HIDAPI_DriverLuna_HandleUSBStatePacket(joystick, ctx, data, size); + break; + default: + HIDAPI_DriverLuna_HandleBluetoothStatePacket(joystick, ctx, data, size); + break; + } + } + + if (size < 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverLuna_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ +} + +static void HIDAPI_DriverLuna_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverLuna = { + SDL_HINT_JOYSTICK_HIDAPI_LUNA, + true, + HIDAPI_DriverLuna_RegisterHints, + HIDAPI_DriverLuna_UnregisterHints, + HIDAPI_DriverLuna_IsEnabled, + HIDAPI_DriverLuna_IsSupportedDevice, + HIDAPI_DriverLuna_InitDevice, + HIDAPI_DriverLuna_GetDevicePlayerIndex, + HIDAPI_DriverLuna_SetDevicePlayerIndex, + HIDAPI_DriverLuna_UpdateDevice, + HIDAPI_DriverLuna_OpenJoystick, + HIDAPI_DriverLuna_RumbleJoystick, + HIDAPI_DriverLuna_RumbleJoystickTriggers, + HIDAPI_DriverLuna_GetJoystickCapabilities, + HIDAPI_DriverLuna_SetJoystickLED, + HIDAPI_DriverLuna_SendJoystickEffect, + HIDAPI_DriverLuna_SetJoystickSensorsEnabled, + HIDAPI_DriverLuna_CloseJoystick, + HIDAPI_DriverLuna_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_LUNA + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_nintendo.h b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_nintendo.h new file mode 100644 index 00000000000..0a5836fbbb1 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_nintendo.h @@ -0,0 +1,49 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +// These are values used in the controller type byte of the controller GUID + +// These values come directly out of the hardware, so don't change them +typedef enum +{ + k_eSwitchDeviceInfoControllerType_Unknown = 0, + k_eSwitchDeviceInfoControllerType_JoyConLeft = 1, + k_eSwitchDeviceInfoControllerType_JoyConRight = 2, + k_eSwitchDeviceInfoControllerType_ProController = 3, + k_eSwitchDeviceInfoControllerType_LicProController = 6, + k_eSwitchDeviceInfoControllerType_HVCLeft = 7, + k_eSwitchDeviceInfoControllerType_HVCRight = 8, + k_eSwitchDeviceInfoControllerType_NESLeft = 9, + k_eSwitchDeviceInfoControllerType_NESRight = 10, + k_eSwitchDeviceInfoControllerType_SNES = 11, + k_eSwitchDeviceInfoControllerType_N64 = 12, + k_eSwitchDeviceInfoControllerType_SEGA_Genesis = 13, +} ESwitchDeviceInfoControllerType; + +// These values are used internally but can be updated as needed +typedef enum +{ + k_eWiiExtensionControllerType_Unknown = 0, + k_eWiiExtensionControllerType_None = 128, + k_eWiiExtensionControllerType_Nunchuk = 129, + k_eWiiExtensionControllerType_Gamepad = 130, + k_eWiiExtensionControllerType_WiiUPro = 131, +} EWiiExtensionControllerType; diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps3.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps3.c new file mode 100644 index 00000000000..6c82647c0bc --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps3.c @@ -0,0 +1,1446 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../../SDL_hints_c.h" +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" + +#ifdef SDL_JOYSTICK_HIDAPI_PS3 + +// Define this if you want to log all packets from the controller +// #define DEBUG_PS3_PROTOCOL + +#define LOAD16(A, B) (Sint16)((Uint16)(A) | (((Uint16)(B)) << 8)) + +typedef enum +{ + k_EPS3ReportIdState = 1, + k_EPS3ReportIdEffects = 1, +} EPS3ReportId; + +typedef enum +{ + k_EPS3SonySixaxisReportIdState = 0, + k_EPS3SonySixaxisReportIdEffects = 0, +} EPS3SonySixaxisReportId; + +// Commands for Sony's sixaxis.sys Windows driver +// All commands must be sent using 49-byte buffer containing output report +// Byte 0 indicates reportId and must always be 0 +// Byte 1 indicates a command, supported values are specified below: +typedef enum +{ + // This command allows to set user LEDs. + // Bytes 5,6.7.8 contain mode for corresponding LED: 0 - LED is off, 1 - LED in on, 2 - LED is flashing. + // Bytes 9-16 specify 64-bit LED flash period in 100 ns units if some LED is flashing, otherwise not used. + k_EPS3SixaxisCommandSetLEDs = 1, + + // This command allows to set left and right motors. + // Byte 5 is right motor duration (0-255) and byte 6, if not zero, activates right motor. Zero value disables right motor. + // Byte 7 is left motor duration (0-255) and byte 8 is left motor amplitude (0-255). + k_EPS3SixaxisCommandSetMotors = 2, + + // This command allows to block/unblock setting device LEDs by applications. + // Byte 5 is used as parameter - any non-zero value blocks LEDs, zero value will unblock LEDs. + k_EPS3SixaxisCommandBlockLEDs = 3, + + // This command refreshes driver settings. No parameters used. + // When sixaxis driver loads it reads 'CurrentDriverSetting' binary value from 'HKLM\System\CurrentControlSet\Services\sixaxis\Parameters' registry key. + // If the key is not present then default values are used. Sending this command forces sixaxis driver to re-read the registry and update driver settings. + k_EPS3SixaxisCommandRefreshDriverSetting = 9, + + // This command clears current bluetooth pairing. No parameters used. + k_EPS3SixaxisCommandClearPairing = 10 +} EPS3SixaxisDriverCommands; + +typedef struct +{ + SDL_HIDAPI_Device *device; + SDL_Joystick *joystick; + bool is_shanwan; + bool has_analog_buttons; + bool report_sensors; + bool effects_updated; + int player_index; + Uint8 rumble_left; + Uint8 rumble_right; + Uint8 last_state[USB_PACKET_LENGTH]; +} SDL_DriverPS3_Context; + +static bool HIDAPI_DriverPS3_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *effect, int size); + +static void HIDAPI_DriverPS3_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS3, callback, userdata); +} + +static void HIDAPI_DriverPS3_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS3, callback, userdata); +} + +static bool HIDAPI_DriverPS3_IsEnabled(void) +{ + bool default_value; + +#ifdef SDL_PLATFORM_MACOS + // This works well on macOS + default_value = true; +#elif defined(SDL_PLATFORM_WIN32) + /* For official Sony driver (sixaxis.sys) use SDL_HINT_JOYSTICK_HIDAPI_PS3_SIXAXIS_DRIVER. + * + * See https://github.com/ViGEm/DsHidMini as an alternative driver + */ + default_value = false; +#elif defined(SDL_PLATFORM_LINUX) + /* Linux drivers do a better job of managing the transition between + * USB and Bluetooth. There are also some quirks in communicating + * with PS3 controllers that have been implemented in SDL's hidapi + * for libusb, but are not possible to support using hidraw if the + * kernel doesn't already know about them. + */ + default_value = false; +#else + // Untested, default off + default_value = false; +#endif + + if (default_value) { + default_value = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT); + } + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_PS3, default_value); +} + +static bool HIDAPI_DriverPS3_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + if (vendor_id == USB_VENDOR_SONY && product_id == USB_PRODUCT_SONY_DS3) { + return true; + } + if (vendor_id == USB_VENDOR_SHANWAN && product_id == USB_PRODUCT_SHANWAN_DS3) { + return true; + } + return false; +} + +static int ReadFeatureReport(SDL_hid_device *dev, Uint8 report_id, Uint8 *report, size_t length) +{ + SDL_memset(report, 0, length); + report[0] = report_id; + return SDL_hid_get_feature_report(dev, report, length); +} + +static int SendFeatureReport(SDL_hid_device *dev, Uint8 *report, size_t length) +{ + return SDL_hid_send_feature_report(dev, report, length); +} + +static bool HIDAPI_DriverPS3_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS3_Context *ctx; + bool is_shanwan = false; + + if (device->vendor_id == USB_VENDOR_SONY && + SDL_strncasecmp(device->name, "ShanWan", 7) == 0) { + is_shanwan = true; + } + if (device->vendor_id == USB_VENDOR_SHANWAN || + device->vendor_id == USB_VENDOR_SHANWAN_ALT) { + is_shanwan = true; + } + + ctx = (SDL_DriverPS3_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + ctx->is_shanwan = is_shanwan; + ctx->has_analog_buttons = true; + + device->context = ctx; + + // Set the controller into report mode over Bluetooth + if (device->is_bluetooth) { + Uint8 data[] = { 0xf4, 0x42, 0x03, 0x00, 0x00 }; + + SendFeatureReport(device->dev, data, sizeof(data)); + } + + // Set the controller into report mode over USB + if (!device->is_bluetooth) { + Uint8 data[USB_PACKET_LENGTH]; + + int size = ReadFeatureReport(device->dev, 0xf2, data, 17); + if (size < 0) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "HIDAPI_DriverPS3_InitDevice(): Couldn't read feature report 0xf2"); + return false; + } +#ifdef DEBUG_PS3_PROTOCOL + HIDAPI_DumpPacket("PS3 0xF2 packet: size = %d", data, size); +#endif + size = ReadFeatureReport(device->dev, 0xf5, data, 8); + if (size < 0) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "HIDAPI_DriverPS3_InitDevice(): Couldn't read feature report 0xf5"); + return false; + } +#ifdef DEBUG_PS3_PROTOCOL + HIDAPI_DumpPacket("PS3 0xF5 packet: size = %d", data, size); +#endif + if (!ctx->is_shanwan) { + // An output report could cause ShanWan controllers to rumble non-stop + SDL_hid_write(device->dev, data, 1); + } + } + + device->type = SDL_GAMEPAD_TYPE_PS3; + HIDAPI_SetDeviceName(device, "PS3 Controller"); + + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverPS3_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static bool HIDAPI_DriverPS3_UpdateEffects(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + Uint8 effects[] = { + 0x01, 0xff, 0x00, 0xff, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0xff, 0x27, 0x10, 0x00, 0x32, + 0xff, 0x27, 0x10, 0x00, 0x32, + 0xff, 0x27, 0x10, 0x00, 0x32, + 0xff, 0x27, 0x10, 0x00, 0x32, + 0x00, 0x00, 0x00, 0x00, 0x00 + }; + + effects[2] = ctx->rumble_right ? 1 : 0; + effects[4] = ctx->rumble_left; + + effects[9] = (0x01 << (1 + (ctx->player_index % 4))); + + return HIDAPI_DriverPS3_SendJoystickEffect(device, ctx->joystick, effects, sizeof(effects)); +} + +static void HIDAPI_DriverPS3_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + if (!ctx) { + return; + } + + ctx->player_index = player_index; + + // This will set the new LED state based on the new player index + HIDAPI_DriverPS3_UpdateEffects(device); +} + +static bool HIDAPI_DriverPS3_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + ctx->joystick = joystick; + ctx->effects_updated = false; + ctx->rumble_left = 0; + ctx->rumble_right = 0; + SDL_zeroa(ctx->last_state); + + // Initialize player index (needed for setting LEDs) + ctx->player_index = SDL_GetJoystickPlayerIndex(joystick); + + // Initialize the joystick capabilities + joystick->nbuttons = 11; + joystick->naxes = 6; + if (ctx->has_analog_buttons) { + joystick->naxes += 10; + } + joystick->nhats = 1; + + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 100.0f); + + return true; +} + +static bool HIDAPI_DriverPS3_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + ctx->rumble_left = (low_frequency_rumble >> 8); + ctx->rumble_right = (high_frequency_rumble >> 8); + + return HIDAPI_DriverPS3_UpdateEffects(device); +} + +static bool HIDAPI_DriverPS3_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverPS3_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + return SDL_JOYSTICK_CAP_RUMBLE; +} + +static bool HIDAPI_DriverPS3_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverPS3_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *effect, int size) +{ + Uint8 data[49]; + int report_size, offset; + + SDL_zeroa(data); + + data[0] = k_EPS3ReportIdEffects; + report_size = sizeof(data); + offset = 1; + SDL_memcpy(&data[offset], effect, SDL_min((sizeof(data) - offset), (size_t)size)); + + if (SDL_HIDAPI_SendRumble(device, data, report_size) != report_size) { + return SDL_SetError("Couldn't send rumble packet"); + } + return true; +} + +static bool HIDAPI_DriverPS3_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + ctx->report_sensors = enabled; + + return true; +} + +static float HIDAPI_DriverPS3_ScaleAccel(Sint16 value) +{ + // Accelerometer values are in big endian order + value = SDL_Swap16BE(value); + return ((float)(value - 511) / 113.0f) * SDL_STANDARD_GRAVITY; +} + +static void HIDAPI_DriverPS3_HandleMiniStatePacket(SDL_Joystick *joystick, SDL_DriverPS3_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->last_state[4] != data[4]) { + Uint8 hat; + + switch (data[4] & 0x0f) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[4] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[4] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[4] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[4] & 0x80) != 0)); + } + + if (ctx->last_state[5] != data[5]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[5] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[5] & 0x02) != 0)); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, (data[5] & 0x04) ? SDL_JOYSTICK_AXIS_MAX : SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, (data[5] & 0x08) ? SDL_JOYSTICK_AXIS_MAX : SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[5] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[5] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[5] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[5] & 0x80) != 0)); + } + + axis = ((int)data[2] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = ((int)data[3] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = ((int)data[0] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = ((int)data[1] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static void HIDAPI_DriverPS3_HandleStatePacket(SDL_Joystick *joystick, SDL_DriverPS3_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->last_state[2] != data[2]) { + Uint8 hat = 0; + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[2] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[2] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[2] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[2] & 0x08) != 0)); + + if (data[2] & 0x10) { + hat |= SDL_HAT_UP; + } + if (data[2] & 0x20) { + hat |= SDL_HAT_RIGHT; + } + if (data[2] & 0x40) { + hat |= SDL_HAT_DOWN; + } + if (data[2] & 0x80) { + hat |= SDL_HAT_LEFT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + if (ctx->last_state[3] != data[3]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[3] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[3] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[3] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[3] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[3] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[3] & 0x80) != 0)); + } + + if (ctx->last_state[4] != data[4]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[4] & 0x01) != 0)); + } + + axis = ((int)data[18] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + axis = ((int)data[19] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + axis = ((int)data[6] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = ((int)data[7] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = ((int)data[8] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = ((int)data[9] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + // Buttons are mapped as axes in the order they appear in the button enumeration + if (ctx->has_analog_buttons) { + static int button_axis_offsets[] = { + 24, // SDL_GAMEPAD_BUTTON_SOUTH + 23, // SDL_GAMEPAD_BUTTON_EAST + 25, // SDL_GAMEPAD_BUTTON_WEST + 22, // SDL_GAMEPAD_BUTTON_NORTH + 0, // SDL_GAMEPAD_BUTTON_BACK + 0, // SDL_GAMEPAD_BUTTON_GUIDE + 0, // SDL_GAMEPAD_BUTTON_START + 0, // SDL_GAMEPAD_BUTTON_LEFT_STICK + 0, // SDL_GAMEPAD_BUTTON_RIGHT_STICK + 20, // SDL_GAMEPAD_BUTTON_LEFT_SHOULDER + 21, // SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER + 14, // SDL_GAMEPAD_BUTTON_DPAD_UP + 16, // SDL_GAMEPAD_BUTTON_DPAD_DOWN + 17, // SDL_GAMEPAD_BUTTON_DPAD_LEFT + 15, // SDL_GAMEPAD_BUTTON_DPAD_RIGHT + }; + Uint8 i, axis_index = 6; + + for (i = 0; i < SDL_arraysize(button_axis_offsets); ++i) { + int offset = button_axis_offsets[i]; + if (!offset) { + // This button doesn't report as an axis + continue; + } + + axis = ((int)data[offset] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, axis_index, axis); + ++axis_index; + } + } + + if (ctx->report_sensors) { + float sensor_data[3]; + + sensor_data[0] = HIDAPI_DriverPS3_ScaleAccel(LOAD16(data[41], data[42])); + sensor_data[1] = -HIDAPI_DriverPS3_ScaleAccel(LOAD16(data[45], data[46])); + sensor_data[2] = -HIDAPI_DriverPS3_ScaleAccel(LOAD16(data[43], data[44])); + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, timestamp, sensor_data, SDL_arraysize(sensor_data)); + } + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static bool HIDAPI_DriverPS3_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH]; + int size; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } else { + return false; + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { +#ifdef DEBUG_PS3_PROTOCOL + HIDAPI_DumpPacket("PS3 packet: size = %d", data, size); +#endif + if (!joystick) { + continue; + } + + if (size == 7) { + // Seen on a ShanWan PS2 -> PS3 USB converter + HIDAPI_DriverPS3_HandleMiniStatePacket(joystick, ctx, data, size); + + // Wait for the first report to set the LED state after the controller stops blinking + if (!ctx->effects_updated) { + HIDAPI_DriverPS3_UpdateEffects(device); + ctx->effects_updated = true; + } + continue; + } + + switch (data[0]) { + case k_EPS3ReportIdState: + if (data[1] == 0xFF) { + // Invalid data packet, ignore + break; + } + HIDAPI_DriverPS3_HandleStatePacket(joystick, ctx, data, size); + + // Wait for the first report to set the LED state after the controller stops blinking + if (!ctx->effects_updated) { + HIDAPI_DriverPS3_UpdateEffects(device); + ctx->effects_updated = true; + } + break; + default: +#ifdef DEBUG_JOYSTICK + SDL_Log("Unknown PS3 packet: 0x%.2x", data[0]); +#endif + break; + } + } + + if (size < 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverPS3_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + ctx->joystick = NULL; +} + +static void HIDAPI_DriverPS3_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS3 = { + SDL_HINT_JOYSTICK_HIDAPI_PS3, + true, + HIDAPI_DriverPS3_RegisterHints, + HIDAPI_DriverPS3_UnregisterHints, + HIDAPI_DriverPS3_IsEnabled, + HIDAPI_DriverPS3_IsSupportedDevice, + HIDAPI_DriverPS3_InitDevice, + HIDAPI_DriverPS3_GetDevicePlayerIndex, + HIDAPI_DriverPS3_SetDevicePlayerIndex, + HIDAPI_DriverPS3_UpdateDevice, + HIDAPI_DriverPS3_OpenJoystick, + HIDAPI_DriverPS3_RumbleJoystick, + HIDAPI_DriverPS3_RumbleJoystickTriggers, + HIDAPI_DriverPS3_GetJoystickCapabilities, + HIDAPI_DriverPS3_SetJoystickLED, + HIDAPI_DriverPS3_SendJoystickEffect, + HIDAPI_DriverPS3_SetJoystickSensorsEnabled, + HIDAPI_DriverPS3_CloseJoystick, + HIDAPI_DriverPS3_FreeDevice, +}; + +static bool HIDAPI_DriverPS3ThirdParty_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_PS3, + SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, + SDL_HIDAPI_DEFAULT)); +} + +static bool HIDAPI_DriverPS3ThirdParty_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + Uint8 data[USB_PACKET_LENGTH]; + int size; + + if (vendor_id == USB_VENDOR_LOGITECH && + product_id == USB_PRODUCT_LOGITECH_CHILLSTREAM) { + return true; + } + + if ((type == SDL_GAMEPAD_TYPE_PS3 && vendor_id != USB_VENDOR_SONY) || + HIDAPI_SupportsPlaystationDetection(vendor_id, product_id)) { + if (device && device->dev) { + size = ReadFeatureReport(device->dev, 0x03, data, sizeof(data)); + if (size == 8 && data[2] == 0x26) { + // Supported third party controller + return true; + } else { + return false; + } + } else { + // Might be supported by this driver, enumerate and find out + return true; + } + } + return false; +} + +static bool HIDAPI_DriverPS3ThirdParty_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS3_Context *ctx; + + ctx = (SDL_DriverPS3_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + if (device->vendor_id == USB_VENDOR_SWITCH && device->product_id == USB_PRODUCT_SWITCH_RETROBIT_CONTROLLER) { + ctx->has_analog_buttons = false; + } else { + ctx->has_analog_buttons = true; + } + + device->context = ctx; + + device->type = SDL_GAMEPAD_TYPE_PS3; + + if (device->vendor_id == USB_VENDOR_LOGITECH && + device->product_id == USB_PRODUCT_LOGITECH_CHILLSTREAM) { + HIDAPI_SetDeviceName(device, "Logitech ChillStream"); + } + + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverPS3ThirdParty_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverPS3ThirdParty_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ +} + +static bool HIDAPI_DriverPS3ThirdParty_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + ctx->joystick = joystick; + SDL_zeroa(ctx->last_state); + + // Initialize the joystick capabilities + joystick->nbuttons = 11; + joystick->naxes = 6; + if (ctx->has_analog_buttons) { + joystick->naxes += 10; + } + joystick->nhats = 1; + + if (device->vendor_id == USB_VENDOR_SWITCH && device->product_id == USB_PRODUCT_SWITCH_RETROBIT_CONTROLLER) { + // This is a wireless controller using a USB dongle + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRELESS; + } + + return true; +} + +static bool HIDAPI_DriverPS3ThirdParty_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverPS3ThirdParty_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverPS3ThirdParty_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + return 0; +} + +static bool HIDAPI_DriverPS3ThirdParty_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverPS3ThirdParty_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *effect, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverPS3ThirdParty_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static void HIDAPI_DriverPS3ThirdParty_HandleStatePacket18(SDL_Joystick *joystick, SDL_DriverPS3_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->last_state[0] != data[0]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[0] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[0] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[0] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[0] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[0] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[0] & 0x20) != 0)); + } + + if (ctx->last_state[1] != data[1]) { + Uint8 hat; + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[1] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[1] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[1] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[1] & 0x08) != 0)); + + switch (data[1] >> 4) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + axis = ((int)data[16] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + axis = ((int)data[17] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + axis = ((int)data[2] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = ((int)data[3] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = ((int)data[4] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = ((int)data[5] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + // Buttons are mapped as axes in the order they appear in the button enumeration + if (ctx->has_analog_buttons) { + static int button_axis_offsets[] = { + 12, // SDL_GAMEPAD_BUTTON_SOUTH + 11, // SDL_GAMEPAD_BUTTON_EAST + 13, // SDL_GAMEPAD_BUTTON_WEST + 10, // SDL_GAMEPAD_BUTTON_NORTH + 0, // SDL_GAMEPAD_BUTTON_BACK + 0, // SDL_GAMEPAD_BUTTON_GUIDE + 0, // SDL_GAMEPAD_BUTTON_START + 0, // SDL_GAMEPAD_BUTTON_LEFT_STICK + 0, // SDL_GAMEPAD_BUTTON_RIGHT_STICK + 14, // SDL_GAMEPAD_BUTTON_LEFT_SHOULDER + 15, // SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER + 8, // SDL_GAMEPAD_BUTTON_DPAD_UP + 9, // SDL_GAMEPAD_BUTTON_DPAD_DOWN + 7, // SDL_GAMEPAD_BUTTON_DPAD_LEFT + 6, // SDL_GAMEPAD_BUTTON_DPAD_RIGHT + }; + Uint8 i, axis_index = 6; + + for (i = 0; i < SDL_arraysize(button_axis_offsets); ++i) { + int offset = button_axis_offsets[i]; + if (!offset) { + // This button doesn't report as an axis + continue; + } + + axis = ((int)data[offset] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, axis_index, axis); + ++axis_index; + } + } + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static void HIDAPI_DriverPS3ThirdParty_HandleStatePacket19(SDL_Joystick *joystick, SDL_DriverPS3_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->last_state[0] != data[0]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[0] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[0] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[0] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[0] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[0] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[0] & 0x20) != 0)); + } + + if (ctx->last_state[1] != data[1]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[1] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[1] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[1] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[1] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[1] & 0x10) != 0)); + } + + if (ctx->device->vendor_id == USB_VENDOR_SAITEK && ctx->device->product_id == USB_PRODUCT_SAITEK_CYBORG_V3) { + // Cyborg V.3 Rumble Pad doesn't set the dpad bits as expected, so use the axes instead + Uint8 hat = 0; + + if (data[7]) { + hat |= SDL_HAT_RIGHT; + } + if (data[8]) { + hat |= SDL_HAT_LEFT; + } + if (data[9]) { + hat |= SDL_HAT_UP; + } + if (data[10]) { + hat |= SDL_HAT_DOWN; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } else { + if (ctx->last_state[2] != data[2]) { + Uint8 hat; + + switch (data[2] & 0x0f) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + } + + if (data[0] & 0x40) { + axis = 32767; + } else { + axis = ((int)data[17] * 257) - 32768; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + if (data[0] & 0x80) { + axis = 32767; + } else { + axis = ((int)data[18] * 257) - 32768; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + axis = ((int)data[3] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = ((int)data[4] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = ((int)data[5] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = ((int)data[6] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + // Buttons are mapped as axes in the order they appear in the button enumeration + if (ctx->has_analog_buttons) { + static int button_axis_offsets[] = { + 13, // SDL_GAMEPAD_BUTTON_SOUTH + 12, // SDL_GAMEPAD_BUTTON_EAST + 14, // SDL_GAMEPAD_BUTTON_WEST + 11, // SDL_GAMEPAD_BUTTON_NORTH + 0, // SDL_GAMEPAD_BUTTON_BACK + 0, // SDL_GAMEPAD_BUTTON_GUIDE + 0, // SDL_GAMEPAD_BUTTON_START + 0, // SDL_GAMEPAD_BUTTON_LEFT_STICK + 0, // SDL_GAMEPAD_BUTTON_RIGHT_STICK + 15, // SDL_GAMEPAD_BUTTON_LEFT_SHOULDER + 16, // SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER + 9, // SDL_GAMEPAD_BUTTON_DPAD_UP + 10, // SDL_GAMEPAD_BUTTON_DPAD_DOWN + 8, // SDL_GAMEPAD_BUTTON_DPAD_LEFT + 7, // SDL_GAMEPAD_BUTTON_DPAD_RIGHT + }; + Uint8 i, axis_index = 6; + + for (i = 0; i < SDL_arraysize(button_axis_offsets); ++i) { + int offset = button_axis_offsets[i]; + if (!offset) { + // This button doesn't report as an axis + continue; + } + + axis = ((int)data[offset] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, axis_index, axis); + ++axis_index; + } + } + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static bool HIDAPI_DriverPS3ThirdParty_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH]; + int size; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } else { + return false; + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { +#ifdef DEBUG_PS3_PROTOCOL + HIDAPI_DumpPacket("PS3 packet: size = %d", data, size); +#endif + if (!joystick) { + continue; + } + + if (size >= 19) { + HIDAPI_DriverPS3ThirdParty_HandleStatePacket19(joystick, ctx, data, size); + } else if (size == 18) { + // This packet format was seen with the Logitech ChillStream + HIDAPI_DriverPS3ThirdParty_HandleStatePacket18(joystick, ctx, data, size); + } else { +#ifdef DEBUG_JOYSTICK + SDL_Log("Unknown PS3 packet, size %d", size); +#endif + } + } + + if (size < 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverPS3ThirdParty_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + ctx->joystick = NULL; +} + +static void HIDAPI_DriverPS3ThirdParty_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS3ThirdParty = { + SDL_HINT_JOYSTICK_HIDAPI_PS3, + true, + HIDAPI_DriverPS3_RegisterHints, + HIDAPI_DriverPS3_UnregisterHints, + HIDAPI_DriverPS3ThirdParty_IsEnabled, + HIDAPI_DriverPS3ThirdParty_IsSupportedDevice, + HIDAPI_DriverPS3ThirdParty_InitDevice, + HIDAPI_DriverPS3ThirdParty_GetDevicePlayerIndex, + HIDAPI_DriverPS3ThirdParty_SetDevicePlayerIndex, + HIDAPI_DriverPS3ThirdParty_UpdateDevice, + HIDAPI_DriverPS3ThirdParty_OpenJoystick, + HIDAPI_DriverPS3ThirdParty_RumbleJoystick, + HIDAPI_DriverPS3ThirdParty_RumbleJoystickTriggers, + HIDAPI_DriverPS3ThirdParty_GetJoystickCapabilities, + HIDAPI_DriverPS3ThirdParty_SetJoystickLED, + HIDAPI_DriverPS3ThirdParty_SendJoystickEffect, + HIDAPI_DriverPS3ThirdParty_SetJoystickSensorsEnabled, + HIDAPI_DriverPS3ThirdParty_CloseJoystick, + HIDAPI_DriverPS3ThirdParty_FreeDevice, +}; + +static bool HIDAPI_DriverPS3_UpdateRumbleSonySixaxis(SDL_HIDAPI_Device *device); +static bool HIDAPI_DriverPS3_UpdateLEDsSonySixaxis(SDL_HIDAPI_Device *device); + +static void HIDAPI_DriverPS3SonySixaxis_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS3_SIXAXIS_DRIVER, callback, userdata); +} + +static void HIDAPI_DriverPS3SonySixaxis_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS3_SIXAXIS_DRIVER, callback, userdata); +} + +static bool HIDAPI_DriverPS3SonySixaxis_IsEnabled(void) +{ +#ifdef SDL_PLATFORM_WIN32 + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_PS3_SIXAXIS_DRIVER, false); +#else + return false; +#endif +} + +static bool HIDAPI_DriverPS3SonySixaxis_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + if (vendor_id == USB_VENDOR_SONY && product_id == USB_PRODUCT_SONY_DS3) { + return true; + } + return false; +} + +static bool HIDAPI_DriverPS3SonySixaxis_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS3_Context *ctx; + + ctx = (SDL_DriverPS3_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + ctx->has_analog_buttons = true; + + device->context = ctx; + + Uint8 data[USB_PACKET_LENGTH]; + + int size = ReadFeatureReport(device->dev, 0xf2, data, sizeof(data)); + if (size < 0) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "HIDAPI_DriverPS3SonySixaxis_InitDevice(): Couldn't read feature report 0xf2. Trying again with 0x0."); + SDL_zeroa(data); + size = ReadFeatureReport(device->dev, 0x00, data, sizeof(data)); + if (size < 0) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "HIDAPI_DriverPS3SonySixaxis_InitDevice(): Couldn't read feature report 0x00."); + return false; + } +#ifdef DEBUG_PS3_PROTOCOL + HIDAPI_DumpPacket("PS3 0x0 packet: size = %d", data, size); +#endif + } +#ifdef DEBUG_PS3_PROTOCOL + HIDAPI_DumpPacket("PS3 0xF2 packet: size = %d", data, size); +#endif + + device->type = SDL_GAMEPAD_TYPE_PS3; + HIDAPI_SetDeviceName(device, "PS3 Controller"); + + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverPS3SonySixaxis_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverPS3SonySixaxis_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + if (!ctx) { + return; + } + + ctx->player_index = player_index; + + // This will set the new LED state based on the new player index + HIDAPI_DriverPS3_UpdateLEDsSonySixaxis(device); +} + +static bool HIDAPI_DriverPS3SonySixaxis_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + ctx->joystick = joystick; + ctx->effects_updated = false; + ctx->rumble_left = 0; + ctx->rumble_right = 0; + SDL_zeroa(ctx->last_state); + + // Initialize player index (needed for setting LEDs) + ctx->player_index = SDL_GetJoystickPlayerIndex(joystick); + + // Initialize the joystick capabilities + joystick->nbuttons = 11; + joystick->naxes = 6; + if (ctx->has_analog_buttons) { + joystick->naxes += 10; + } + joystick->nhats = 1; + + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 100.0f); + + return true; +} + +static bool HIDAPI_DriverPS3SonySixaxis_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + ctx->rumble_left = (low_frequency_rumble >> 8); + ctx->rumble_right = (high_frequency_rumble >> 8); + + return HIDAPI_DriverPS3_UpdateRumbleSonySixaxis(device); +} + +static bool HIDAPI_DriverPS3SonySixaxis_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverPS3SonySixaxis_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + return 0; +} + +static bool HIDAPI_DriverPS3SonySixaxis_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverPS3SonySixaxis_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *effect, int size) +{ + Uint8 data[49]; + int report_size; + + SDL_zeroa(data); + + data[0] = k_EPS3SonySixaxisReportIdEffects; + report_size = sizeof(data); + + // No offset with Sony sixaxis.sys driver + SDL_memcpy(&data, effect, SDL_min(sizeof(data), (size_t)size)); + + if (SDL_HIDAPI_SendRumble(device, data, report_size) != report_size) { + return SDL_SetError("Couldn't send rumble packet"); + } + return true; +} + +static bool HIDAPI_DriverPS3SonySixaxis_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + ctx->report_sensors = enabled; + + return true; +} + +static void HIDAPI_DriverPS3SonySixaxis_HandleStatePacket(SDL_Joystick *joystick, SDL_DriverPS3_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->last_state[2] != data[2]) { + Uint8 hat = 0; + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[2] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[2] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[2] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[2] & 0x08) != 0)); + + if (data[2] & 0x10) { + hat |= SDL_HAT_UP; + } + if (data[2] & 0x20) { + hat |= SDL_HAT_RIGHT; + } + if (data[2] & 0x40) { + hat |= SDL_HAT_DOWN; + } + if (data[2] & 0x80) { + hat |= SDL_HAT_LEFT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + if (ctx->last_state[3] != data[3]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[3] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[3] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[3] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[3] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[3] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[3] & 0x80) != 0)); + } + + if (ctx->last_state[4] != data[4]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[4] & 0x01) != 0)); + } + + axis = ((int)data[18] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + axis = ((int)data[19] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + axis = ((int)data[6] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = ((int)data[7] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = ((int)data[8] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = ((int)data[9] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + // Buttons are mapped as axes in the order they appear in the button enumeration + if (ctx->has_analog_buttons) { + static int button_axis_offsets[] = { + 24, // SDL_GAMEPAD_BUTTON_SOUTH + 23, // SDL_GAMEPAD_BUTTON_EAST + 25, // SDL_GAMEPAD_BUTTON_WEST + 22, // SDL_GAMEPAD_BUTTON_NORTH + 0, // SDL_GAMEPAD_BUTTON_BACK + 0, // SDL_GAMEPAD_BUTTON_GUIDE + 0, // SDL_GAMEPAD_BUTTON_START + 0, // SDL_GAMEPAD_BUTTON_LEFT_STICK + 0, // SDL_GAMEPAD_BUTTON_RIGHT_STICK + 20, // SDL_GAMEPAD_BUTTON_LEFT_SHOULDER + 21, // SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER + 14, // SDL_GAMEPAD_BUTTON_DPAD_UP + 16, // SDL_GAMEPAD_BUTTON_DPAD_DOWN + 17, // SDL_GAMEPAD_BUTTON_DPAD_LEFT + 15, // SDL_GAMEPAD_BUTTON_DPAD_RIGHT + }; + Uint8 i, axis_index = 6; + + for (i = 0; i < SDL_arraysize(button_axis_offsets); ++i) { + int offset = button_axis_offsets[i]; + if (!offset) { + // This button doesn't report as an axis + continue; + } + + axis = ((int)data[offset] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, axis_index, axis); + ++axis_index; + } + } + + if (ctx->report_sensors) { + float sensor_data[3]; + + sensor_data[0] = HIDAPI_DriverPS3_ScaleAccel(LOAD16(data[41], data[42])); + sensor_data[1] = -HIDAPI_DriverPS3_ScaleAccel(LOAD16(data[45], data[46])); + sensor_data[2] = -HIDAPI_DriverPS3_ScaleAccel(LOAD16(data[43], data[44])); + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, timestamp, sensor_data, SDL_arraysize(sensor_data)); + } + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static bool HIDAPI_DriverPS3SonySixaxis_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH]; + int size; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } else { + return false; + } + + if (!joystick) { + return false; + } + + // With sixaxis.sys driver we need to use hid_get_feature_report instead of hid_read + size = ReadFeatureReport(device->dev, 0x0, data, sizeof(data)); + if (size < 0) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "HIDAPI_DriverPS3SonySixaxis_UpdateDevice(): Couldn't read feature report 0x00"); + return false; + } + + switch (data[0]) { + case k_EPS3SonySixaxisReportIdState: + HIDAPI_DriverPS3SonySixaxis_HandleStatePacket(joystick, ctx, &data[1], size - 1); // report data starts in data[1] + + // Wait for the first report to set the LED state after the controller stops blinking + if (!ctx->effects_updated) { + HIDAPI_DriverPS3_UpdateLEDsSonySixaxis(device); + ctx->effects_updated = true; + } + + break; + default: +#ifdef DEBUG_JOYSTICK + SDL_Log("Unknown PS3 packet: 0x%.2x", data[0]); +#endif + break; + } + + if (size < 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverPS3SonySixaxis_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + ctx->joystick = NULL; +} + +static void HIDAPI_DriverPS3SonySixaxis_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +static bool HIDAPI_DriverPS3_UpdateRumbleSonySixaxis(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + Uint8 effects[] = { + 0x0, // Report Id + k_EPS3SixaxisCommandSetMotors, // 2 = Set Motors + 0x00, 0x00, 0x00, // padding + 0xff, // Small Motor duration - 0xff is forever + 0x00, // Small Motor off/on (0 or 1) + 0xff, // Large Motor duration - 0xff is forever + 0x00 // Large Motor force (0 to 255) + }; + + effects[6] = ctx->rumble_right ? 1 : 0; // Small motor + effects[8] = ctx->rumble_left; // Large motor + + return HIDAPI_DriverPS3SonySixaxis_SendJoystickEffect(device, ctx->joystick, effects, sizeof(effects)); +} + +static bool HIDAPI_DriverPS3_UpdateLEDsSonySixaxis(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS3_Context *ctx = (SDL_DriverPS3_Context *)device->context; + + Uint8 effects[] = { + 0x0, // Report Id + k_EPS3SixaxisCommandSetLEDs, // 1 = Set LEDs + 0x00, 0x00, 0x00, // padding + 0x00, 0x00, 0x00, 0x00 // LED #4, LED #3, LED #2, LED #1 (0 = Off, 1 = On, 2 = Flashing) + }; + + // Turn on LED light on DS3 Controller for relevant player (player_index 0 lights up LED #1, player_index 1 lights up LED #2, etc) + if (ctx->player_index < 4) { + effects[8 - ctx->player_index] = 1; + } + + return HIDAPI_DriverPS3SonySixaxis_SendJoystickEffect(device, ctx->joystick, effects, sizeof(effects)); +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS3SonySixaxis = { + SDL_HINT_JOYSTICK_HIDAPI_PS3_SIXAXIS_DRIVER, + true, + HIDAPI_DriverPS3SonySixaxis_RegisterHints, + HIDAPI_DriverPS3SonySixaxis_UnregisterHints, + HIDAPI_DriverPS3SonySixaxis_IsEnabled, + HIDAPI_DriverPS3SonySixaxis_IsSupportedDevice, + HIDAPI_DriverPS3SonySixaxis_InitDevice, + HIDAPI_DriverPS3SonySixaxis_GetDevicePlayerIndex, + HIDAPI_DriverPS3SonySixaxis_SetDevicePlayerIndex, + HIDAPI_DriverPS3SonySixaxis_UpdateDevice, + HIDAPI_DriverPS3SonySixaxis_OpenJoystick, + HIDAPI_DriverPS3SonySixaxis_RumbleJoystick, + HIDAPI_DriverPS3SonySixaxis_RumbleJoystickTriggers, + HIDAPI_DriverPS3SonySixaxis_GetJoystickCapabilities, + HIDAPI_DriverPS3SonySixaxis_SetJoystickLED, + HIDAPI_DriverPS3SonySixaxis_SendJoystickEffect, + HIDAPI_DriverPS3SonySixaxis_SetJoystickSensorsEnabled, + HIDAPI_DriverPS3SonySixaxis_CloseJoystick, + HIDAPI_DriverPS3SonySixaxis_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_PS3 + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps4.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps4.c new file mode 100644 index 00000000000..d4332df7b3b --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps4.c @@ -0,0 +1,1390 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +/* This driver supports both simplified reports and the extended input reports enabled by Steam. + Code and logic contributed by Valve Corporation under the SDL zlib license. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../../SDL_hints_c.h" +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" + +#ifdef SDL_JOYSTICK_HIDAPI_PS4 + +// Define this if you want to log all packets from the controller +#if 0 +#define DEBUG_PS4_PROTOCOL +#endif + +// Define this if you want to log calibration data +#if 0 +#define DEBUG_PS4_CALIBRATION +#endif + +#define BLUETOOTH_DISCONNECT_TIMEOUT_MS 500 + +#define LOAD16(A, B) (Sint16)((Uint16)(A) | (((Uint16)(B)) << 8)) +#define LOAD32(A, B, C, D) ((((Uint32)(A)) << 0) | \ + (((Uint32)(B)) << 8) | \ + (((Uint32)(C)) << 16) | \ + (((Uint32)(D)) << 24)) + +enum +{ + SDL_GAMEPAD_BUTTON_PS4_TOUCHPAD = 11 +}; + +typedef enum +{ + k_EPS4ReportIdUsbState = 1, + k_EPS4ReportIdUsbEffects = 5, + k_EPS4ReportIdBluetoothState1 = 17, + k_EPS4ReportIdBluetoothState2 = 18, + k_EPS4ReportIdBluetoothState3 = 19, + k_EPS4ReportIdBluetoothState4 = 20, + k_EPS4ReportIdBluetoothState5 = 21, + k_EPS4ReportIdBluetoothState6 = 22, + k_EPS4ReportIdBluetoothState7 = 23, + k_EPS4ReportIdBluetoothState8 = 24, + k_EPS4ReportIdBluetoothState9 = 25, + k_EPS4ReportIdBluetoothEffects = 17, + k_EPS4ReportIdDisconnectMessage = 226, +} EPS4ReportId; + +typedef enum +{ + k_ePS4FeatureReportIdGyroCalibration_USB = 0x02, + k_ePS4FeatureReportIdCapabilities = 0x03, + k_ePS4FeatureReportIdGyroCalibration_BT = 0x05, + k_ePS4FeatureReportIdSerialNumber = 0x12, +} EPS4FeatureReportID; + +typedef struct +{ + Uint8 ucLeftJoystickX; + Uint8 ucLeftJoystickY; + Uint8 ucRightJoystickX; + Uint8 ucRightJoystickY; + Uint8 rgucButtonsHatAndCounter[3]; + Uint8 ucTriggerLeft; + Uint8 ucTriggerRight; + Uint8 rgucTimestamp[2]; + Uint8 _rgucPad0[1]; + Uint8 rgucGyroX[2]; + Uint8 rgucGyroY[2]; + Uint8 rgucGyroZ[2]; + Uint8 rgucAccelX[2]; + Uint8 rgucAccelY[2]; + Uint8 rgucAccelZ[2]; + Uint8 _rgucPad1[5]; + Uint8 ucBatteryLevel; + Uint8 _rgucPad2[4]; + Uint8 ucTouchpadCounter1; + Uint8 rgucTouchpadData1[3]; + Uint8 ucTouchpadCounter2; + Uint8 rgucTouchpadData2[3]; +} PS4StatePacket_t; + +typedef struct +{ + Uint8 ucRumbleRight; + Uint8 ucRumbleLeft; + Uint8 ucLedRed; + Uint8 ucLedGreen; + Uint8 ucLedBlue; + Uint8 ucLedDelayOn; + Uint8 ucLedDelayOff; + Uint8 _rgucPad0[8]; + Uint8 ucVolumeLeft; + Uint8 ucVolumeRight; + Uint8 ucVolumeMic; + Uint8 ucVolumeSpeaker; +} DS4EffectsState_t; + +typedef struct +{ + Sint16 bias; + float scale; +} IMUCalibrationData; + +/* Rumble hint mode: + * "0": enhanced features are never used + * "1": enhanced features are always used + * "auto": enhanced features are advertised to the application, but SDL doesn't touch the controller state unless the application explicitly requests it. + */ +typedef enum +{ + PS4_ENHANCED_REPORT_HINT_OFF, + PS4_ENHANCED_REPORT_HINT_ON, + PS4_ENHANCED_REPORT_HINT_AUTO +} HIDAPI_PS4_EnhancedReportHint; + +typedef struct +{ + SDL_HIDAPI_Device *device; + SDL_Joystick *joystick; + bool is_dongle; + bool is_nacon_dongle; + bool official_controller; + bool sensors_supported; + bool lightbar_supported; + bool vibration_supported; + bool touchpad_supported; + bool effects_supported; + HIDAPI_PS4_EnhancedReportHint enhanced_report_hint; + bool enhanced_reports; + bool enhanced_mode; + bool enhanced_mode_available; + Uint8 report_interval; + bool report_sensors; + bool report_touchpad; + bool report_battery; + bool hardware_calibration; + IMUCalibrationData calibration[6]; + Uint64 last_packet; + int player_index; + Uint8 rumble_left; + Uint8 rumble_right; + bool color_set; + Uint8 led_red; + Uint8 led_green; + Uint8 led_blue; + Uint16 gyro_numerator; + Uint16 gyro_denominator; + Uint16 accel_numerator; + Uint16 accel_denominator; + Uint64 sensor_ticks; + Uint16 last_tick; + Uint16 valid_crc_packets; // wrapping counter + PS4StatePacket_t last_state; +} SDL_DriverPS4_Context; + +static bool HIDAPI_DriverPS4_InternalSendJoystickEffect(SDL_DriverPS4_Context *ctx, const void *effect, int size, bool application_usage); + +static void HIDAPI_DriverPS4_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4, callback, userdata); +} + +static void HIDAPI_DriverPS4_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4, callback, userdata); +} + +static bool HIDAPI_DriverPS4_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_PS4, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)); +} + +static int ReadFeatureReport(SDL_hid_device *dev, Uint8 report_id, Uint8 *report, size_t length) +{ + SDL_memset(report, 0, length); + report[0] = report_id; + return SDL_hid_get_feature_report(dev, report, length); +} + +static bool HIDAPI_DriverPS4_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + Uint8 data[USB_PACKET_LENGTH]; + int size; + + if (type == SDL_GAMEPAD_TYPE_PS4) { + return true; + } + + if (HIDAPI_SupportsPlaystationDetection(vendor_id, product_id)) { + if (device && device->dev) { + size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdCapabilities, data, sizeof(data)); + if (size == 48 && data[2] == 0x27) { + // Supported third party controller + return true; + } else { + return false; + } + } else { + // Might be supported by this driver, enumerate and find out + return true; + } + } + + return false; +} + +static void SetLedsForPlayerIndex(DS4EffectsState_t *effects, int player_index) +{ + /* This list is the same as what hid-sony.c uses in the Linux kernel. + The first 4 values correspond to what the PS4 assigns. + */ + static const Uint8 colors[7][3] = { + { 0x00, 0x00, 0x40 }, // Blue + { 0x40, 0x00, 0x00 }, // Red + { 0x00, 0x40, 0x00 }, // Green + { 0x20, 0x00, 0x20 }, // Pink + { 0x02, 0x01, 0x00 }, // Orange + { 0x00, 0x01, 0x01 }, // Teal + { 0x01, 0x01, 0x01 } // White + }; + + if (player_index >= 0) { + player_index %= SDL_arraysize(colors); + } else { + player_index = 0; + } + + effects->ucLedRed = colors[player_index][0]; + effects->ucLedGreen = colors[player_index][1]; + effects->ucLedBlue = colors[player_index][2]; +} + +static bool ReadWiredSerial(SDL_HIDAPI_Device *device, char *serial, size_t serial_size) +{ + Uint8 data[USB_PACKET_LENGTH]; + int size; + + size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdSerialNumber, data, sizeof(data)); + if (size >= 7 && (data[1] || data[2] || data[3] || data[4] || data[5] || data[6])) { + (void)SDL_snprintf(serial, serial_size, "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x", + data[6], data[5], data[4], data[3], data[2], data[1]); + return true; + } + return false; +} + +static bool HIDAPI_DriverPS4_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS4_Context *ctx; + Uint8 data[USB_PACKET_LENGTH]; + int size; + char serial[18]; + SDL_JoystickType joystick_type = SDL_JOYSTICK_TYPE_GAMEPAD; + + ctx = (SDL_DriverPS4_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + + ctx->gyro_numerator = 1; + ctx->gyro_denominator = 16; + ctx->accel_numerator = 1; + ctx->accel_denominator = 8192; + + device->context = ctx; + + if (device->serial && SDL_strlen(device->serial) == 12) { + int i, j; + + j = -1; + for (i = 0; i < 12; i += 2) { + j += 1; + SDL_memmove(&serial[j], &device->serial[i], 2); + j += 2; + serial[j] = '-'; + } + serial[j] = '\0'; + } else { + serial[0] = '\0'; + } + + // Check for type of connection + ctx->is_dongle = (device->vendor_id == USB_VENDOR_SONY && device->product_id == USB_PRODUCT_SONY_DS4_DONGLE); + if (ctx->is_dongle) { + ReadWiredSerial(device, serial, sizeof(serial)); + ctx->enhanced_reports = true; + } else if (device->vendor_id == USB_VENDOR_SONY && device->product_id == USB_PRODUCT_SONY_DS4_STRIKEPAD) { + ctx->enhanced_reports = true; + + } else if (device->vendor_id == USB_VENDOR_SONY) { + if (device->is_bluetooth) { + // Read a report to see if we're in enhanced mode + size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 16); +#ifdef DEBUG_PS4_PROTOCOL + if (size > 0) { + HIDAPI_DumpPacket("PS4 first packet: size = %d", data, size); + } else { + SDL_Log("PS4 first packet: size = %d", size); + } +#endif + if (size > 0 && + data[0] >= k_EPS4ReportIdBluetoothState1 && + data[0] <= k_EPS4ReportIdBluetoothState9) { + ctx->enhanced_reports = true; + } + } else { + ReadWiredSerial(device, serial, sizeof(serial)); + ctx->enhanced_reports = true; + } + } else { + // Third party controllers appear to all be wired + ctx->enhanced_reports = true; + } + + if (device->vendor_id == USB_VENDOR_SONY) { + ctx->official_controller = true; + ctx->sensors_supported = true; + ctx->lightbar_supported = true; + ctx->vibration_supported = true; + ctx->touchpad_supported = true; + } else { + // Third party controller capability request + size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdCapabilities, data, sizeof(data)); + // Get the device capabilities + if (size == 48 && data[2] == 0x27) { + Uint8 capabilities = data[4]; + Uint8 device_type = data[5]; + Uint16 gyro_numerator = LOAD16(data[10], data[11]); + Uint16 gyro_denominator = LOAD16(data[12], data[13]); + Uint16 accel_numerator = LOAD16(data[14], data[15]); + Uint16 accel_denominator = LOAD16(data[16], data[17]); + +#ifdef DEBUG_PS4_PROTOCOL + HIDAPI_DumpPacket("PS4 capabilities: size = %d", data, size); +#endif + if (capabilities & 0x02) { + ctx->sensors_supported = true; + } + if (capabilities & 0x04) { + ctx->lightbar_supported = true; + } + if (capabilities & 0x08) { + ctx->vibration_supported = true; + } + if (capabilities & 0x40) { + ctx->touchpad_supported = true; + } + + switch (device_type) { + case 0x00: + joystick_type = SDL_JOYSTICK_TYPE_GAMEPAD; + break; + case 0x01: + joystick_type = SDL_JOYSTICK_TYPE_GUITAR; + break; + case 0x02: + joystick_type = SDL_JOYSTICK_TYPE_DRUM_KIT; + break; + case 0x04: + joystick_type = SDL_JOYSTICK_TYPE_DANCE_PAD; + break; + case 0x06: + joystick_type = SDL_JOYSTICK_TYPE_WHEEL; + break; + case 0x07: + joystick_type = SDL_JOYSTICK_TYPE_ARCADE_STICK; + break; + case 0x08: + joystick_type = SDL_JOYSTICK_TYPE_FLIGHT_STICK; + break; + default: + joystick_type = SDL_JOYSTICK_TYPE_UNKNOWN; + break; + } + + if (gyro_numerator && gyro_denominator) { + ctx->gyro_numerator = gyro_numerator; + ctx->gyro_denominator = gyro_denominator; + } + if (accel_numerator && accel_denominator) { + ctx->accel_numerator = accel_numerator; + ctx->accel_denominator = accel_denominator; + } + } else if (device->vendor_id == USB_VENDOR_RAZER) { + // The Razer Raiju doesn't respond to the detection protocol, but has a touchpad and vibration + ctx->vibration_supported = true; + ctx->touchpad_supported = true; + } + } + ctx->effects_supported = (ctx->lightbar_supported || ctx->vibration_supported); + + if (device->vendor_id == USB_VENDOR_NACON_ALT && + device->product_id == USB_PRODUCT_NACON_REVOLUTION_5_PRO_PS4_WIRELESS) { + ctx->is_nacon_dongle = true; + } + + if (device->vendor_id == USB_VENDOR_PDP && + (device->product_id == USB_PRODUCT_VICTRIX_FS_PRO || + device->product_id == USB_PRODUCT_VICTRIX_FS_PRO_V2)) { + /* The Victrix FS Pro V2 reports that it has lightbar support, + * but it doesn't respond to the effects packet, and will hang + * on reboot if we send it. + */ + ctx->effects_supported = false; + } + + device->joystick_type = joystick_type; + device->type = SDL_GAMEPAD_TYPE_PS4; + if (ctx->official_controller) { + HIDAPI_SetDeviceName(device, "PS4 Controller"); + } + HIDAPI_SetDeviceSerial(device, serial); + + // Prefer the USB device over the Bluetooth device + if (device->is_bluetooth) { + if (HIDAPI_HasConnectedUSBDevice(device->serial)) { + return true; + } + } else { + HIDAPI_DisconnectBluetoothDevice(device->serial); + } + if ((ctx->is_dongle || ctx->is_nacon_dongle) && serial[0] == '\0') { + // Not yet connected + return true; + } + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverPS4_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static bool HIDAPI_DriverPS4_LoadOfficialCalibrationData(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + int i, tries, size; + bool have_data = false; + Uint8 data[USB_PACKET_LENGTH]; + + if (!ctx->official_controller) { +#ifdef DEBUG_PS4_CALIBRATION + SDL_Log("Not an official controller, ignoring calibration"); +#endif + return false; + } + + for (tries = 0; tries < 5; ++tries) { + // For Bluetooth controllers, this report switches them into advanced report mode + size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdGyroCalibration_USB, data, sizeof(data)); + if (size < 35) { +#ifdef DEBUG_PS4_CALIBRATION + SDL_Log("Short read of calibration data: %d, ignoring calibration", size); +#endif + return false; + } + + if (device->is_bluetooth) { + size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdGyroCalibration_BT, data, sizeof(data)); + if (size < 35) { +#ifdef DEBUG_PS4_CALIBRATION + SDL_Log("Short read of calibration data: %d, ignoring calibration", size); +#endif + return false; + } + } + + // In some cases this report returns all zeros. Usually immediately after connection with the PS4 Dongle + for (i = 0; i < size; ++i) { + if (data[i]) { + have_data = true; + break; + } + } + if (have_data) { + break; + } + + SDL_Delay(2); + } + + if (have_data) { + Sint16 sGyroPitchBias, sGyroYawBias, sGyroRollBias; + Sint16 sGyroPitchPlus, sGyroPitchMinus; + Sint16 sGyroYawPlus, sGyroYawMinus; + Sint16 sGyroRollPlus, sGyroRollMinus; + Sint16 sGyroSpeedPlus, sGyroSpeedMinus; + + Sint16 sAccXPlus, sAccXMinus; + Sint16 sAccYPlus, sAccYMinus; + Sint16 sAccZPlus, sAccZMinus; + + float flNumerator; + float flDenominator; + Sint16 sRange2g; + +#ifdef DEBUG_PS4_CALIBRATION + HIDAPI_DumpPacket("PS4 calibration packet: size = %d", data, size); +#endif + + sGyroPitchBias = LOAD16(data[1], data[2]); + sGyroYawBias = LOAD16(data[3], data[4]); + sGyroRollBias = LOAD16(data[5], data[6]); + + if (device->is_bluetooth || ctx->is_dongle) { + sGyroPitchPlus = LOAD16(data[7], data[8]); + sGyroYawPlus = LOAD16(data[9], data[10]); + sGyroRollPlus = LOAD16(data[11], data[12]); + sGyroPitchMinus = LOAD16(data[13], data[14]); + sGyroYawMinus = LOAD16(data[15], data[16]); + sGyroRollMinus = LOAD16(data[17], data[18]); + } else { + sGyroPitchPlus = LOAD16(data[7], data[8]); + sGyroPitchMinus = LOAD16(data[9], data[10]); + sGyroYawPlus = LOAD16(data[11], data[12]); + sGyroYawMinus = LOAD16(data[13], data[14]); + sGyroRollPlus = LOAD16(data[15], data[16]); + sGyroRollMinus = LOAD16(data[17], data[18]); + } + + sGyroSpeedPlus = LOAD16(data[19], data[20]); + sGyroSpeedMinus = LOAD16(data[21], data[22]); + + sAccXPlus = LOAD16(data[23], data[24]); + sAccXMinus = LOAD16(data[25], data[26]); + sAccYPlus = LOAD16(data[27], data[28]); + sAccYMinus = LOAD16(data[29], data[30]); + sAccZPlus = LOAD16(data[31], data[32]); + sAccZMinus = LOAD16(data[33], data[34]); + + flNumerator = (float)(sGyroSpeedPlus + sGyroSpeedMinus) * ctx->gyro_denominator / ctx->gyro_numerator; + flDenominator = (float)(SDL_abs(sGyroPitchPlus - sGyroPitchBias) + SDL_abs(sGyroPitchMinus - sGyroPitchBias)); + if (flDenominator != 0.0f) { + ctx->calibration[0].bias = sGyroPitchBias; + ctx->calibration[0].scale = flNumerator / flDenominator; + } + + flDenominator = (float)(SDL_abs(sGyroYawPlus - sGyroYawBias) + SDL_abs(sGyroYawMinus - sGyroYawBias)); + if (flDenominator != 0.0f) { + ctx->calibration[1].bias = sGyroYawBias; + ctx->calibration[1].scale = flNumerator / flDenominator; + } + + flDenominator = (float)(SDL_abs(sGyroRollPlus - sGyroRollBias) + SDL_abs(sGyroRollMinus - sGyroRollBias)); + if (flDenominator != 0.0f) { + ctx->calibration[2].bias = sGyroRollBias; + ctx->calibration[2].scale = flNumerator / flDenominator; + } + + sRange2g = sAccXPlus - sAccXMinus; + ctx->calibration[3].bias = sAccXPlus - sRange2g / 2; + ctx->calibration[3].scale = (2.0f * ctx->accel_denominator / ctx->accel_numerator) / sRange2g; + + sRange2g = sAccYPlus - sAccYMinus; + ctx->calibration[4].bias = sAccYPlus - sRange2g / 2; + ctx->calibration[4].scale = (2.0f * ctx->accel_denominator / ctx->accel_numerator) / sRange2g; + + sRange2g = sAccZPlus - sAccZMinus; + ctx->calibration[5].bias = sAccZPlus - sRange2g / 2; + ctx->calibration[5].scale = (2.0f * ctx->accel_denominator / ctx->accel_numerator) / sRange2g; + + ctx->hardware_calibration = true; + for (i = 0; i < 6; ++i) { +#ifdef DEBUG_PS4_CALIBRATION + SDL_Log("calibration[%d] bias = %d, sensitivity = %f", i, ctx->calibration[i].bias, ctx->calibration[i].scale); +#endif + // Some controllers have a bad calibration + if (SDL_abs(ctx->calibration[i].bias) > 1024 || SDL_fabsf(1.0f - ctx->calibration[i].scale) > 0.5f) { +#ifdef DEBUG_PS4_CALIBRATION + SDL_Log("invalid calibration, ignoring"); +#endif + ctx->hardware_calibration = false; + } + } + } else { +#ifdef DEBUG_PS4_CALIBRATION + SDL_Log("Calibration data not available"); +#endif + } + return ctx->hardware_calibration; +} + +static void HIDAPI_DriverPS4_LoadCalibrationData(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + int i; + + if (!HIDAPI_DriverPS4_LoadOfficialCalibrationData(device)) { + for (i = 0; i < SDL_arraysize(ctx->calibration); ++i) { + ctx->calibration[i].bias = 0; + ctx->calibration[i].scale = 1.0f; + } + } + + // Scale the raw data to the units expected by SDL + for (i = 0; i < SDL_arraysize(ctx->calibration); ++i) { + double scale = ctx->calibration[i].scale; + + if (i < 3) { + scale *= ((double)ctx->gyro_numerator / ctx->gyro_denominator) * SDL_PI_D / 180.0; + + if (device->vendor_id == USB_VENDOR_SONY && + device->product_id == USB_PRODUCT_SONY_DS4_STRIKEPAD) { + // The Armor-X Pro seems to only deliver half the rotation it should + scale *= 2.0; + } + } else { + scale *= ((double)ctx->accel_numerator / ctx->accel_denominator) * SDL_STANDARD_GRAVITY; + + if (device->vendor_id == USB_VENDOR_SONY && + device->product_id == USB_PRODUCT_SONY_DS4_STRIKEPAD) { + /* The Armor-X Pro seems to only deliver half the acceleration it should, + * and in the opposite direction on all axes */ + scale *= -2.0; + } + } + ctx->calibration[i].scale = (float)scale; + } +} + +static float HIDAPI_DriverPS4_ApplyCalibrationData(SDL_DriverPS4_Context *ctx, int index, Sint16 value) +{ + IMUCalibrationData *calibration = &ctx->calibration[index]; + + return ((float)value - calibration->bias) * calibration->scale; +} + +static bool HIDAPI_DriverPS4_UpdateEffects(SDL_DriverPS4_Context *ctx, bool application_usage) +{ + DS4EffectsState_t effects; + + SDL_zero(effects); + + if (ctx->vibration_supported) { + effects.ucRumbleLeft = ctx->rumble_left; + effects.ucRumbleRight = ctx->rumble_right; + } + + if (ctx->lightbar_supported) { + // Populate the LED state with the appropriate color from our lookup table + if (ctx->color_set) { + effects.ucLedRed = ctx->led_red; + effects.ucLedGreen = ctx->led_green; + effects.ucLedBlue = ctx->led_blue; + } else { + SetLedsForPlayerIndex(&effects, ctx->player_index); + } + } + return HIDAPI_DriverPS4_InternalSendJoystickEffect(ctx, &effects, sizeof(effects), application_usage); +} + +static void HIDAPI_DriverPS4_TickleBluetooth(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + + if (ctx->enhanced_reports) { + // This is just a dummy packet that should have no effect, since we don't set the CRC + Uint8 data[78]; + + SDL_zeroa(data); + + data[0] = k_EPS4ReportIdBluetoothEffects; + data[1] = 0xC0; // Magic value HID + CRC + + if (SDL_HIDAPI_LockRumble()) { + SDL_HIDAPI_SendRumbleAndUnlock(device, data, sizeof(data)); + } + } else { +#if 0 /* The 8BitDo Zero 2 has perfect emulation of a PS4 controller, except it + * only sends reports when the state changes, so we can't disconnect here. + */ + // We can't even send an invalid effects packet, or it will put the controller in enhanced mode + if (device->num_joysticks > 0) { + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } +#endif + } +} + +static void HIDAPI_DriverPS4_SetEnhancedModeAvailable(SDL_DriverPS4_Context *ctx) +{ + if (ctx->enhanced_mode_available) { + return; + } + ctx->enhanced_mode_available = true; + + if (ctx->touchpad_supported) { + SDL_PrivateJoystickAddTouchpad(ctx->joystick, 2); + ctx->report_touchpad = true; + } + + if (ctx->sensors_supported) { + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_GYRO, (float)(1000 / ctx->report_interval)); + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_ACCEL, (float)(1000 / ctx->report_interval)); + } + + if (ctx->official_controller) { + ctx->report_battery = true; + } + + HIDAPI_UpdateDeviceProperties(ctx->device); +} + +static void HIDAPI_DriverPS4_SetEnhancedMode(SDL_DriverPS4_Context *ctx) +{ + HIDAPI_DriverPS4_SetEnhancedModeAvailable(ctx); + + if (!ctx->enhanced_mode) { + ctx->enhanced_mode = true; + + // Switch into enhanced report mode + HIDAPI_DriverPS4_UpdateEffects(ctx, false); + } +} + +static void HIDAPI_DriverPS4_SetEnhancedReportHint(SDL_DriverPS4_Context *ctx, HIDAPI_PS4_EnhancedReportHint enhanced_report_hint) +{ + switch (enhanced_report_hint) { + case PS4_ENHANCED_REPORT_HINT_OFF: + // Nothing to do, enhanced mode is a one-way ticket + break; + case PS4_ENHANCED_REPORT_HINT_ON: + HIDAPI_DriverPS4_SetEnhancedMode(ctx); + break; + case PS4_ENHANCED_REPORT_HINT_AUTO: + HIDAPI_DriverPS4_SetEnhancedModeAvailable(ctx); + break; + } + ctx->enhanced_report_hint = enhanced_report_hint; +} + +static void HIDAPI_DriverPS4_UpdateEnhancedModeOnEnhancedReport(SDL_DriverPS4_Context *ctx) +{ + ctx->enhanced_reports = true; + + if (ctx->enhanced_report_hint == PS4_ENHANCED_REPORT_HINT_AUTO) { + HIDAPI_DriverPS4_SetEnhancedReportHint(ctx, PS4_ENHANCED_REPORT_HINT_ON); + } +} + +static void HIDAPI_DriverPS4_UpdateEnhancedModeOnApplicationUsage(SDL_DriverPS4_Context *ctx) +{ + if (ctx->enhanced_report_hint == PS4_ENHANCED_REPORT_HINT_AUTO) { + HIDAPI_DriverPS4_SetEnhancedReportHint(ctx, PS4_ENHANCED_REPORT_HINT_ON); + } +} + +static void SDLCALL SDL_PS4EnhancedReportsChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)userdata; + + if (ctx->device->is_bluetooth) { + if (hint && SDL_strcasecmp(hint, "auto") == 0) { + HIDAPI_DriverPS4_SetEnhancedReportHint(ctx, PS4_ENHANCED_REPORT_HINT_AUTO); + } else if (SDL_GetStringBoolean(hint, true)) { + HIDAPI_DriverPS4_SetEnhancedReportHint(ctx, PS4_ENHANCED_REPORT_HINT_ON); + } else { + HIDAPI_DriverPS4_SetEnhancedReportHint(ctx, PS4_ENHANCED_REPORT_HINT_OFF); + } + } else { + HIDAPI_DriverPS4_SetEnhancedReportHint(ctx, PS4_ENHANCED_REPORT_HINT_ON); + } +} + +static void SDLCALL SDL_PS4ReportIntervalHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + const int DEFAULT_REPORT_INTERVAL = 4; + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)userdata; + int new_report_interval = DEFAULT_REPORT_INTERVAL; + + if (hint) { + int report_interval = SDL_atoi(hint); + switch (report_interval) { + case 1: + case 2: + case 4: + // Valid values + new_report_interval = report_interval; + break; + default: + break; + } + } + + if (new_report_interval != ctx->report_interval) { + ctx->report_interval = (Uint8)new_report_interval; + + HIDAPI_DriverPS4_UpdateEffects(ctx, false); + SDL_LockJoysticks(); + SDL_PrivateJoystickSensorRate(ctx->joystick, SDL_SENSOR_GYRO, (float)(1000 / ctx->report_interval)); + SDL_PrivateJoystickSensorRate(ctx->joystick, SDL_SENSOR_ACCEL, (float)(1000 / ctx->report_interval)); + SDL_UnlockJoysticks(); + } +} + +static void HIDAPI_DriverPS4_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + + if (!ctx->joystick) { + return; + } + + ctx->player_index = player_index; + + // This will set the new LED state based on the new player index + // SDL automatically calls this, so it doesn't count as an application action to enable enhanced mode + HIDAPI_DriverPS4_UpdateEffects(ctx, false); +} + +static bool HIDAPI_DriverPS4_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + ctx->joystick = joystick; + ctx->last_packet = SDL_GetTicks(); + ctx->report_sensors = false; + ctx->report_touchpad = false; + ctx->rumble_left = 0; + ctx->rumble_right = 0; + ctx->color_set = false; + SDL_zero(ctx->last_state); + + // Initialize player index (needed for setting LEDs) + ctx->player_index = SDL_GetJoystickPlayerIndex(joystick); + + // Initialize the joystick capabilities + joystick->nbuttons = 11; + if (ctx->touchpad_supported) { + joystick->nbuttons += 1; + } + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4_REPORT_INTERVAL, + SDL_PS4ReportIntervalHintChanged, ctx); + SDL_AddHintCallback(SDL_HINT_JOYSTICK_ENHANCED_REPORTS, + SDL_PS4EnhancedReportsChanged, ctx); + return true; +} + +static bool HIDAPI_DriverPS4_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + + if (!ctx->vibration_supported) { + return SDL_Unsupported(); + } + + ctx->rumble_left = (low_frequency_rumble >> 8); + ctx->rumble_right = (high_frequency_rumble >> 8); + + return HIDAPI_DriverPS4_UpdateEffects(ctx, true); +} + +static bool HIDAPI_DriverPS4_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverPS4_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + Uint32 result = 0; + + if (ctx->enhanced_mode_available) { + if (ctx->lightbar_supported) { + result |= SDL_JOYSTICK_CAP_RGB_LED; + } + if (ctx->vibration_supported) { + result |= SDL_JOYSTICK_CAP_RUMBLE; + } + } + + return result; +} + +static bool HIDAPI_DriverPS4_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + + if (!ctx->lightbar_supported) { + return SDL_Unsupported(); + } + + ctx->color_set = true; + ctx->led_red = red; + ctx->led_green = green; + ctx->led_blue = blue; + + return HIDAPI_DriverPS4_UpdateEffects(ctx, true); +} + +static bool HIDAPI_DriverPS4_InternalSendJoystickEffect(SDL_DriverPS4_Context *ctx, const void *effect, int size, bool application_usage) +{ + Uint8 data[78]; + int report_size, offset; + + if (!ctx->effects_supported) { + // We shouldn't be sending packets to this controller + return SDL_Unsupported(); + } + + if (!ctx->enhanced_mode) { + if (application_usage) { + HIDAPI_DriverPS4_UpdateEnhancedModeOnApplicationUsage(ctx); + } + + if (!ctx->enhanced_mode) { + // We're not in enhanced mode, effects aren't allowed + return SDL_Unsupported(); + } + } + + SDL_zeroa(data); + + if (ctx->device->is_bluetooth && ctx->official_controller) { + data[0] = k_EPS4ReportIdBluetoothEffects; + data[1] = 0xC0 | ctx->report_interval; // Magic value HID + CRC, also sets update interval + data[3] = 0x03; // 0x1 is rumble, 0x2 is lightbar, 0x4 is the blink interval + + report_size = 78; + offset = 6; + } else { + data[0] = k_EPS4ReportIdUsbEffects; + data[1] = 0x07; // Magic value + + report_size = 32; + offset = 4; + } + + SDL_memcpy(&data[offset], effect, SDL_min((sizeof(data) - offset), (size_t)size)); + + if (ctx->device->is_bluetooth) { + // Bluetooth reports need a CRC at the end of the packet (at least on Linux) + Uint8 ubHdr = 0xA2; // hidp header is part of the CRC calculation + Uint32 unCRC; + unCRC = SDL_crc32(0, &ubHdr, 1); + unCRC = SDL_crc32(unCRC, data, (size_t)(report_size - sizeof(unCRC))); + SDL_memcpy(&data[report_size - sizeof(unCRC)], &unCRC, sizeof(unCRC)); + } + + if (SDL_HIDAPI_SendRumble(ctx->device, data, report_size) != report_size) { + return SDL_SetError("Couldn't send rumble packet"); + } + return true; +} + +static bool HIDAPI_DriverPS4_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *effect, int size) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + + return HIDAPI_DriverPS4_InternalSendJoystickEffect(ctx, effect, size, true); +} + +static bool HIDAPI_DriverPS4_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + + HIDAPI_DriverPS4_UpdateEnhancedModeOnApplicationUsage(ctx); + + if (!ctx->sensors_supported || (enabled && !ctx->enhanced_mode)) { + return SDL_Unsupported(); + } + + if (enabled) { + HIDAPI_DriverPS4_LoadCalibrationData(device); + } + ctx->report_sensors = enabled; + + return true; +} + +static void HIDAPI_DriverPS4_HandleStatePacket(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverPS4_Context *ctx, PS4StatePacket_t *packet, int size) +{ + static const float TOUCHPAD_SCALEX = 5.20833333e-4f; // 1.0f / 1920 + static const float TOUCHPAD_SCALEY = 1.08695652e-3f; // 1.0f / 920 // This is noted as being 944 resolution, but 920 feels better + Sint16 axis; + bool touchpad_down; + int touchpad_x, touchpad_y; + Uint64 timestamp = SDL_GetTicksNS(); + + if (size > 9 && ctx->report_touchpad && ctx->enhanced_reports) { + touchpad_down = ((packet->ucTouchpadCounter1 & 0x80) == 0); + touchpad_x = packet->rgucTouchpadData1[0] | (((int)packet->rgucTouchpadData1[1] & 0x0F) << 8); + touchpad_y = (packet->rgucTouchpadData1[1] >> 4) | ((int)packet->rgucTouchpadData1[2] << 4); + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, touchpad_down, touchpad_x * TOUCHPAD_SCALEX, touchpad_y * TOUCHPAD_SCALEY, touchpad_down ? 1.0f : 0.0f); + + touchpad_down = ((packet->ucTouchpadCounter2 & 0x80) == 0); + touchpad_x = packet->rgucTouchpadData2[0] | (((int)packet->rgucTouchpadData2[1] & 0x0F) << 8); + touchpad_y = (packet->rgucTouchpadData2[1] >> 4) | ((int)packet->rgucTouchpadData2[2] << 4); + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 1, touchpad_down, touchpad_x * TOUCHPAD_SCALEX, touchpad_y * TOUCHPAD_SCALEY, touchpad_down ? 1.0f : 0.0f); + } + + if (ctx->last_state.rgucButtonsHatAndCounter[0] != packet->rgucButtonsHatAndCounter[0]) { + { + Uint8 data = (packet->rgucButtonsHatAndCounter[0] >> 4); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data & 0x08) != 0)); + } + { + Uint8 hat; + Uint8 data = (packet->rgucButtonsHatAndCounter[0] & 0x0F); + + switch (data) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + } + + if (ctx->last_state.rgucButtonsHatAndCounter[1] != packet->rgucButtonsHatAndCounter[1]) { + Uint8 data = packet->rgucButtonsHatAndCounter[1]; + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x80) != 0)); + } + + /* Some fightsticks, ex: Victrix FS Pro will only this these digital trigger bits and not the analog values so this needs to run whenever the + trigger is evaluated + */ + if (packet->rgucButtonsHatAndCounter[1] & 0x0C) { + Uint8 data = packet->rgucButtonsHatAndCounter[1]; + packet->ucTriggerLeft = (data & 0x04) && packet->ucTriggerLeft == 0 ? 255 : packet->ucTriggerLeft; + packet->ucTriggerRight = (data & 0x08) && packet->ucTriggerRight == 0 ? 255 : packet->ucTriggerRight; + } + + if (ctx->last_state.rgucButtonsHatAndCounter[2] != packet->rgucButtonsHatAndCounter[2]) { + Uint8 data = (packet->rgucButtonsHatAndCounter[2] & 0x03); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_PS4_TOUCHPAD, ((data & 0x02) != 0)); + } + + axis = ((int)packet->ucTriggerLeft * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + axis = ((int)packet->ucTriggerRight * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + axis = ((int)packet->ucLeftJoystickX * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = ((int)packet->ucLeftJoystickY * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = ((int)packet->ucRightJoystickX * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = ((int)packet->ucRightJoystickY * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + if (size > 9 && ctx->report_battery && ctx->enhanced_reports) { + SDL_PowerState state; + int percent; + Uint8 level = (packet->ucBatteryLevel & 0x0F); + + if (packet->ucBatteryLevel & 0x10) { + if (level <= 10) { + state = SDL_POWERSTATE_CHARGING; + percent = SDL_min(level * 10 + 5, 100); + } else if (level == 11) { + state = SDL_POWERSTATE_CHARGED; + percent = 100; + } else { + state = SDL_POWERSTATE_UNKNOWN; + percent = 0; + } + } else { + state = SDL_POWERSTATE_ON_BATTERY; + percent = SDL_min(level * 10 + 5, 100); + } + SDL_SendJoystickPowerInfo(joystick, state, percent); + } + + if (size > 9 && ctx->report_sensors) { + Uint16 tick; + Uint16 delta; + Uint64 sensor_timestamp; + float data[3]; + + tick = LOAD16(packet->rgucTimestamp[0], packet->rgucTimestamp[1]); + if (ctx->last_tick < tick) { + delta = (tick - ctx->last_tick); + } else { + delta = (SDL_MAX_UINT16 - ctx->last_tick + tick + 1); + } + ctx->sensor_ticks += delta; + ctx->last_tick = tick; + + // Sensor timestamp is in 5.33us units + sensor_timestamp = (ctx->sensor_ticks * SDL_NS_PER_US * 16) / 3; + + data[0] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 0, LOAD16(packet->rgucGyroX[0], packet->rgucGyroX[1])); + data[1] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 1, LOAD16(packet->rgucGyroY[0], packet->rgucGyroY[1])); + data[2] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 2, LOAD16(packet->rgucGyroZ[0], packet->rgucGyroZ[1])); + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, sensor_timestamp, data, 3); + + data[0] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 3, LOAD16(packet->rgucAccelX[0], packet->rgucAccelX[1])); + data[1] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 4, LOAD16(packet->rgucAccelY[0], packet->rgucAccelY[1])); + data[2] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 5, LOAD16(packet->rgucAccelZ[0], packet->rgucAccelZ[1])); + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, sensor_timestamp, data, 3); + } + + SDL_memcpy(&ctx->last_state, packet, sizeof(ctx->last_state)); +} + +static bool VerifyCRC(Uint8 *data, int size) +{ + Uint8 ubHdr = 0xA1; // hidp header is part of the CRC calculation + Uint32 unCRC, unPacketCRC; + Uint8 *packetCRC = data + size - sizeof(unPacketCRC); + unCRC = SDL_crc32(0, &ubHdr, 1); + unCRC = SDL_crc32(unCRC, data, (size_t)(size - sizeof(unCRC))); + + unPacketCRC = LOAD32(packetCRC[0], + packetCRC[1], + packetCRC[2], + packetCRC[3]); + return (unCRC == unPacketCRC); +} + +static bool HIDAPI_DriverPS4_IsPacketValid(SDL_DriverPS4_Context *ctx, Uint8 *data, int size) +{ + switch (data[0]) { + case k_EPS4ReportIdUsbState: + if (size == 10) { + // This is non-enhanced mode, this packet is fine + return true; + } + + if (ctx->is_nacon_dongle && size >= (1 + sizeof(PS4StatePacket_t))) { + // The report timestamp doesn't change when the controller isn't connected + PS4StatePacket_t *packet = (PS4StatePacket_t *)&data[1]; + if (SDL_memcmp(packet->rgucTimestamp, ctx->last_state.rgucTimestamp, sizeof(packet->rgucTimestamp)) == 0) { + return false; + } + if (ctx->last_state.rgucAccelX[0] == 0 && ctx->last_state.rgucAccelX[1] == 0 && + ctx->last_state.rgucAccelY[0] == 0 && ctx->last_state.rgucAccelY[1] == 0 && + ctx->last_state.rgucAccelZ[0] == 0 && ctx->last_state.rgucAccelZ[1] == 0) { + // We don't have any state to compare yet, go ahead and copy it + SDL_memcpy(&ctx->last_state, &data[1], sizeof(PS4StatePacket_t)); + return false; + } + } + + /* In the case of a DS4 USB dongle, bit[2] of byte 31 indicates if a DS4 is actually connected (indicated by '0'). + * For non-dongle, this bit is always 0 (connected). + * This is usually the ID over USB, but the DS4v2 that started shipping with the PS4 Slim will also send this + * packet over BT with a size of 128 + */ + if (size >= 64 && !(data[31] & 0x04)) { + return true; + } + break; + case k_EPS4ReportIdBluetoothState1: + case k_EPS4ReportIdBluetoothState2: + case k_EPS4ReportIdBluetoothState3: + case k_EPS4ReportIdBluetoothState4: + case k_EPS4ReportIdBluetoothState5: + case k_EPS4ReportIdBluetoothState6: + case k_EPS4ReportIdBluetoothState7: + case k_EPS4ReportIdBluetoothState8: + case k_EPS4ReportIdBluetoothState9: + // Bluetooth state packets have two additional bytes at the beginning, the first notes if HID data is present + if (size >= 78 && (data[1] & 0x80)) { + if (VerifyCRC(data, 78)) { + ++ctx->valid_crc_packets; + } else { + if (ctx->valid_crc_packets > 0) { + --ctx->valid_crc_packets; + } + if (ctx->valid_crc_packets >= 3) { + // We're generally getting valid CRC, but failed one + return false; + } + } + return true; + } + break; + default: + break; + } + return false; +} + +static bool HIDAPI_DriverPS4_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH * 2]; + int size; + int packet_count = 0; + Uint64 now = SDL_GetTicks(); + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { +#ifdef DEBUG_PS4_PROTOCOL + HIDAPI_DumpPacket("PS4 packet: size = %d", data, size); +#endif + if (!HIDAPI_DriverPS4_IsPacketValid(ctx, data, size)) { + continue; + } + + ++packet_count; + ctx->last_packet = now; + + if (!joystick) { + continue; + } + + switch (data[0]) { + case k_EPS4ReportIdUsbState: + HIDAPI_DriverPS4_HandleStatePacket(joystick, device->dev, ctx, (PS4StatePacket_t *)&data[1], size - 1); + break; + case k_EPS4ReportIdBluetoothState1: + case k_EPS4ReportIdBluetoothState2: + case k_EPS4ReportIdBluetoothState3: + case k_EPS4ReportIdBluetoothState4: + case k_EPS4ReportIdBluetoothState5: + case k_EPS4ReportIdBluetoothState6: + case k_EPS4ReportIdBluetoothState7: + case k_EPS4ReportIdBluetoothState8: + case k_EPS4ReportIdBluetoothState9: + // This is the extended report, we can enable effects now in auto mode + HIDAPI_DriverPS4_UpdateEnhancedModeOnEnhancedReport(ctx); + + // Bluetooth state packets have two additional bytes at the beginning, the first notes if HID is present + HIDAPI_DriverPS4_HandleStatePacket(joystick, device->dev, ctx, (PS4StatePacket_t *)&data[3], size - 3); + break; + default: +#ifdef DEBUG_JOYSTICK + SDL_Log("Unknown PS4 packet: 0x%.2x", data[0]); +#endif + break; + } + } + + if (device->is_bluetooth) { + if (packet_count == 0) { + // Check to see if it looks like the device disconnected + if (now >= (ctx->last_packet + BLUETOOTH_DISCONNECT_TIMEOUT_MS)) { + // Send an empty output report to tickle the Bluetooth stack + HIDAPI_DriverPS4_TickleBluetooth(device); + ctx->last_packet = now; + } + } else { + // Reconnect the Bluetooth device once the USB device is gone + if (device->num_joysticks == 0 && + !HIDAPI_HasConnectedUSBDevice(device->serial)) { + HIDAPI_JoystickConnected(device, NULL); + } + } + } + + if (ctx->is_dongle || ctx->is_nacon_dongle) { + if (packet_count == 0) { + if (device->num_joysticks > 0) { + // Check to see if it looks like the device disconnected + if (now >= (ctx->last_packet + BLUETOOTH_DISCONNECT_TIMEOUT_MS)) { + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + } + } else { + if (device->num_joysticks == 0) { + char serial[18]; + size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdSerialNumber, data, sizeof(data)); + if (size >= 7 && (data[1] || data[2] || data[3] || data[4] || data[5] || data[6])) { + (void)SDL_snprintf(serial, sizeof(serial), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x", + data[6], data[5], data[4], data[3], data[2], data[1]); + HIDAPI_SetDeviceSerial(device, serial); + } + HIDAPI_JoystickConnected(device, NULL); + } + } + } + + if (packet_count == 0 && size < 0 && device->num_joysticks > 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverPS4_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4_REPORT_INTERVAL, + SDL_PS4ReportIntervalHintChanged, ctx); + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_ENHANCED_REPORTS, + SDL_PS4EnhancedReportsChanged, ctx); + + ctx->joystick = NULL; + + ctx->report_sensors = false; + ctx->enhanced_mode = false; + ctx->enhanced_mode_available = false; +} + +static void HIDAPI_DriverPS4_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS4 = { + SDL_HINT_JOYSTICK_HIDAPI_PS4, + true, + HIDAPI_DriverPS4_RegisterHints, + HIDAPI_DriverPS4_UnregisterHints, + HIDAPI_DriverPS4_IsEnabled, + HIDAPI_DriverPS4_IsSupportedDevice, + HIDAPI_DriverPS4_InitDevice, + HIDAPI_DriverPS4_GetDevicePlayerIndex, + HIDAPI_DriverPS4_SetDevicePlayerIndex, + HIDAPI_DriverPS4_UpdateDevice, + HIDAPI_DriverPS4_OpenJoystick, + HIDAPI_DriverPS4_RumbleJoystick, + HIDAPI_DriverPS4_RumbleJoystickTriggers, + HIDAPI_DriverPS4_GetJoystickCapabilities, + HIDAPI_DriverPS4_SetJoystickLED, + HIDAPI_DriverPS4_SendJoystickEffect, + HIDAPI_DriverPS4_SetJoystickSensorsEnabled, + HIDAPI_DriverPS4_CloseJoystick, + HIDAPI_DriverPS4_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_PS4 + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps5.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps5.c new file mode 100644 index 00000000000..e40170086e0 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps5.c @@ -0,0 +1,1624 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../../SDL_hints_c.h" +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" + +#ifdef SDL_JOYSTICK_HIDAPI_PS5 + +// Define this if you want to log all packets from the controller +#if 0 +#define DEBUG_PS5_PROTOCOL +#endif + +// Define this if you want to log calibration data +#if 0 +#define DEBUG_PS5_CALIBRATION +#endif + +#define GYRO_RES_PER_DEGREE 1024.0f +#define ACCEL_RES_PER_G 8192.0f +#define BLUETOOTH_DISCONNECT_TIMEOUT_MS 500 + +#define LOAD16(A, B) (Sint16)((Uint16)(A) | (((Uint16)(B)) << 8)) +#define LOAD32(A, B, C, D) ((((Uint32)(A)) << 0) | \ + (((Uint32)(B)) << 8) | \ + (((Uint32)(C)) << 16) | \ + (((Uint32)(D)) << 24)) + +enum +{ + SDL_GAMEPAD_BUTTON_PS5_TOUCHPAD = 11, + SDL_GAMEPAD_BUTTON_PS5_MICROPHONE, + SDL_GAMEPAD_BUTTON_PS5_LEFT_FUNCTION, + SDL_GAMEPAD_BUTTON_PS5_RIGHT_FUNCTION, + SDL_GAMEPAD_BUTTON_PS5_LEFT_PADDLE, + SDL_GAMEPAD_BUTTON_PS5_RIGHT_PADDLE +}; + +typedef enum +{ + k_EPS5ReportIdState = 0x01, + k_EPS5ReportIdUsbEffects = 0x02, + k_EPS5ReportIdBluetoothEffects = 0x31, + k_EPS5ReportIdBluetoothState = 0x31, +} EPS5ReportId; + +typedef enum +{ + k_EPS5FeatureReportIdCapabilities = 0x03, + k_EPS5FeatureReportIdCalibration = 0x05, + k_EPS5FeatureReportIdSerialNumber = 0x09, + k_EPS5FeatureReportIdFirmwareInfo = 0x20, +} EPS5FeatureReportId; + +typedef struct +{ + Uint8 ucLeftJoystickX; + Uint8 ucLeftJoystickY; + Uint8 ucRightJoystickX; + Uint8 ucRightJoystickY; + Uint8 rgucButtonsHatAndCounter[3]; + Uint8 ucTriggerLeft; + Uint8 ucTriggerRight; +} PS5SimpleStatePacket_t; + +typedef struct +{ + Uint8 ucLeftJoystickX; // 0 + Uint8 ucLeftJoystickY; // 1 + Uint8 ucRightJoystickX; // 2 + Uint8 ucRightJoystickY; // 3 + Uint8 ucTriggerLeft; // 4 + Uint8 ucTriggerRight; // 5 + Uint8 ucCounter; // 6 + Uint8 rgucButtonsAndHat[4]; // 7 + Uint8 rgucPacketSequence[4]; // 11 - 32 bit little endian + Uint8 rgucGyroX[2]; // 15 + Uint8 rgucGyroY[2]; // 17 + Uint8 rgucGyroZ[2]; // 19 + Uint8 rgucAccelX[2]; // 21 + Uint8 rgucAccelY[2]; // 23 + Uint8 rgucAccelZ[2]; // 25 + Uint8 rgucSensorTimestamp[4]; // 27 - 16/32 bit little endian + +} PS5StatePacketCommon_t; + +typedef struct +{ + Uint8 ucLeftJoystickX; // 0 + Uint8 ucLeftJoystickY; // 1 + Uint8 ucRightJoystickX; // 2 + Uint8 ucRightJoystickY; // 3 + Uint8 ucTriggerLeft; // 4 + Uint8 ucTriggerRight; // 5 + Uint8 ucCounter; // 6 + Uint8 rgucButtonsAndHat[4]; // 7 + Uint8 rgucPacketSequence[4]; // 11 - 32 bit little endian + Uint8 rgucGyroX[2]; // 15 + Uint8 rgucGyroY[2]; // 17 + Uint8 rgucGyroZ[2]; // 19 + Uint8 rgucAccelX[2]; // 21 + Uint8 rgucAccelY[2]; // 23 + Uint8 rgucAccelZ[2]; // 25 + Uint8 rgucSensorTimestamp[4]; // 27 - 32 bit little endian + Uint8 ucSensorTemp; // 31 + Uint8 ucTouchpadCounter1; // 32 - high bit clear + counter + Uint8 rgucTouchpadData1[3]; // 33 - X/Y, 12 bits per axis + Uint8 ucTouchpadCounter2; // 36 - high bit clear + counter + Uint8 rgucTouchpadData2[3]; // 37 - X/Y, 12 bits per axis + Uint8 rgucUnknown1[8]; // 40 + Uint8 rgucTimer2[4]; // 48 - 32 bit little endian + Uint8 ucBatteryLevel; // 52 + Uint8 ucConnectState; // 53 - 0x08 = USB, 0x01 = headphone + + // There's more unknown data at the end, and a 32-bit CRC on Bluetooth +} PS5StatePacket_t; + +typedef struct +{ + Uint8 ucLeftJoystickX; // 0 + Uint8 ucLeftJoystickY; // 1 + Uint8 ucRightJoystickX; // 2 + Uint8 ucRightJoystickY; // 3 + Uint8 ucTriggerLeft; // 4 + Uint8 ucTriggerRight; // 5 + Uint8 ucCounter; // 6 + Uint8 rgucButtonsAndHat[4]; // 7 + Uint8 rgucPacketSequence[4]; // 11 - 32 bit little endian + Uint8 rgucGyroX[2]; // 15 + Uint8 rgucGyroY[2]; // 17 + Uint8 rgucGyroZ[2]; // 19 + Uint8 rgucAccelX[2]; // 21 + Uint8 rgucAccelY[2]; // 23 + Uint8 rgucAccelZ[2]; // 25 + Uint8 rgucSensorTimestamp[2]; // 27 - 16 bit little endian + Uint8 ucBatteryLevel; // 29 + Uint8 ucUnknown; // 30 + Uint8 ucTouchpadCounter1; // 31 - high bit clear + counter + Uint8 rgucTouchpadData1[3]; // 32 - X/Y, 12 bits per axis + Uint8 ucTouchpadCounter2; // 35 - high bit clear + counter + Uint8 rgucTouchpadData2[3]; // 36 - X/Y, 12 bits per axis + + // There's more unknown data at the end, and a 32-bit CRC on Bluetooth +} PS5StatePacketAlt_t; + +typedef struct +{ + Uint8 ucEnableBits1; // 0 + Uint8 ucEnableBits2; // 1 + Uint8 ucRumbleRight; // 2 + Uint8 ucRumbleLeft; // 3 + Uint8 ucHeadphoneVolume; // 4 + Uint8 ucSpeakerVolume; // 5 + Uint8 ucMicrophoneVolume; // 6 + Uint8 ucAudioEnableBits; // 7 + Uint8 ucMicLightMode; // 8 + Uint8 ucAudioMuteBits; // 9 + Uint8 rgucRightTriggerEffect[11]; // 10 + Uint8 rgucLeftTriggerEffect[11]; // 21 + Uint8 rgucUnknown1[6]; // 32 + Uint8 ucEnableBits3; // 38 + Uint8 rgucUnknown2[2]; // 39 + Uint8 ucLedAnim; // 41 + Uint8 ucLedBrightness; // 42 + Uint8 ucPadLights; // 43 + Uint8 ucLedRed; // 44 + Uint8 ucLedGreen; // 45 + Uint8 ucLedBlue; // 46 +} DS5EffectsState_t; + +typedef enum +{ + k_EDS5EffectRumbleStart = (1 << 0), + k_EDS5EffectRumble = (1 << 1), + k_EDS5EffectLEDReset = (1 << 2), + k_EDS5EffectLED = (1 << 3), + k_EDS5EffectPadLights = (1 << 4), + k_EDS5EffectMicLight = (1 << 5) +} EDS5Effect; + +typedef enum +{ + k_EDS5LEDResetStateNone, + k_EDS5LEDResetStatePending, + k_EDS5LEDResetStateComplete, +} EDS5LEDResetState; + +typedef struct +{ + Sint16 bias; + float sensitivity; +} IMUCalibrationData; + +/* Rumble hint mode: + * "0": enhanced features are never used + * "1": enhanced features are always used + * "auto": enhanced features are advertised to the application, but SDL doesn't touch the controller state unless the application explicitly requests it. + */ +typedef enum +{ + PS5_ENHANCED_REPORT_HINT_OFF, + PS5_ENHANCED_REPORT_HINT_ON, + PS5_ENHANCED_REPORT_HINT_AUTO +} HIDAPI_PS5_EnhancedReportHint; + +typedef struct +{ + SDL_HIDAPI_Device *device; + SDL_Joystick *joystick; + bool is_nacon_dongle; + bool use_alternate_report; + bool sensors_supported; + bool lightbar_supported; + bool vibration_supported; + bool playerled_supported; + bool touchpad_supported; + bool effects_supported; + HIDAPI_PS5_EnhancedReportHint enhanced_report_hint; + bool enhanced_reports; + bool enhanced_mode; + bool enhanced_mode_available; + bool report_sensors; + bool report_touchpad; + bool report_battery; + bool hardware_calibration; + IMUCalibrationData calibration[6]; + Uint16 firmware_version; + Uint64 last_packet; + int player_index; + bool player_lights; + Uint8 rumble_left; + Uint8 rumble_right; + bool color_set; + Uint8 led_red; + Uint8 led_green; + Uint8 led_blue; + EDS5LEDResetState led_reset_state; + Uint64 sensor_ticks; + Uint32 last_tick; + union + { + PS5SimpleStatePacket_t simple; + PS5StatePacketCommon_t state; + PS5StatePacketAlt_t alt_state; + PS5StatePacket_t full_state; + Uint8 data[64]; + } last_state; +} SDL_DriverPS5_Context; + +static bool HIDAPI_DriverPS5_InternalSendJoystickEffect(SDL_DriverPS5_Context *ctx, const void *effect, int size, bool application_usage); + +static void HIDAPI_DriverPS5_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS5, callback, userdata); +} + +static void HIDAPI_DriverPS5_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS5, callback, userdata); +} + +static bool HIDAPI_DriverPS5_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_PS5, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)); +} + +static int ReadFeatureReport(SDL_hid_device *dev, Uint8 report_id, Uint8 *report, size_t length) +{ + SDL_memset(report, 0, length); + report[0] = report_id; + return SDL_hid_get_feature_report(dev, report, length); +} + +static bool HIDAPI_DriverPS5_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + Uint8 data[USB_PACKET_LENGTH]; + int size; + + if (type == SDL_GAMEPAD_TYPE_PS5) { + return true; + } + + if (HIDAPI_SupportsPlaystationDetection(vendor_id, product_id)) { + if (device && device->dev) { + size = ReadFeatureReport(device->dev, k_EPS5FeatureReportIdCapabilities, data, sizeof(data)); + if (size == 48 && data[2] == 0x28) { + // Supported third party controller + return true; + } else { + return false; + } + } else { + // Might be supported by this driver, enumerate and find out + return true; + } + } + return false; +} + +static void SetLedsForPlayerIndex(DS5EffectsState_t *effects, int player_index) +{ + /* This list is the same as what hid-sony.c uses in the Linux kernel. + The first 4 values correspond to what the PS4 assigns. + */ + static const Uint8 colors[7][3] = { + { 0x00, 0x00, 0x40 }, // Blue + { 0x40, 0x00, 0x00 }, // Red + { 0x00, 0x40, 0x00 }, // Green + { 0x20, 0x00, 0x20 }, // Pink + { 0x20, 0x10, 0x00 }, // Orange + { 0x00, 0x10, 0x10 }, // Teal + { 0x10, 0x10, 0x10 } // White + }; + + if (player_index >= 0) { + player_index %= SDL_arraysize(colors); + } else { + player_index = 0; + } + + effects->ucLedRed = colors[player_index][0]; + effects->ucLedGreen = colors[player_index][1]; + effects->ucLedBlue = colors[player_index][2]; +} + +static void SetLightsForPlayerIndex(DS5EffectsState_t *effects, int player_index) +{ + static const Uint8 lights[] = { + 0x04, + 0x0A, + 0x15, + 0x1B, + 0x1F + }; + + if (player_index >= 0) { + // Bitmask, 0x1F enables all lights, 0x20 changes instantly instead of fade + player_index %= SDL_arraysize(lights); + effects->ucPadLights = lights[player_index] | 0x20; + } else { + effects->ucPadLights = 0x00; + } +} + +static bool HIDAPI_DriverPS5_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS5_Context *ctx; + Uint8 data[USB_PACKET_LENGTH * 2]; + int size; + char serial[18]; + SDL_JoystickType joystick_type = SDL_JOYSTICK_TYPE_GAMEPAD; + + ctx = (SDL_DriverPS5_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + + device->context = ctx; + + if (device->serial && SDL_strlen(device->serial) == 12) { + int i, j; + + j = -1; + for (i = 0; i < 12; i += 2) { + j += 1; + SDL_memmove(&serial[j], &device->serial[i], 2); + j += 2; + serial[j] = '-'; + } + serial[j] = '\0'; + } else { + serial[0] = '\0'; + } + + // Read a report to see what mode we're in + size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 16); +#ifdef DEBUG_PS5_PROTOCOL + if (size > 0) { + HIDAPI_DumpPacket("PS5 first packet: size = %d", data, size); + } else { + SDL_Log("PS5 first packet: size = %d", size); + } +#endif + if (size == 64) { + // Connected over USB + ctx->enhanced_reports = true; + } else if (size > 0 && data[0] == k_EPS5ReportIdBluetoothEffects) { + // Connected over Bluetooth, using enhanced reports + ctx->enhanced_reports = true; + } else { + // Connected over Bluetooth, using simple reports (DirectInput enabled) + } + + if (device->vendor_id == USB_VENDOR_SONY && ctx->enhanced_reports) { + /* Read the serial number (Bluetooth address in reverse byte order) + This will also enable enhanced reports over Bluetooth + */ + if (ReadFeatureReport(device->dev, k_EPS5FeatureReportIdSerialNumber, data, sizeof(data)) >= 7) { + (void)SDL_snprintf(serial, sizeof(serial), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x", + data[6], data[5], data[4], data[3], data[2], data[1]); + } + + /* Read the firmware version + This will also enable enhanced reports over Bluetooth + */ + if (ReadFeatureReport(device->dev, k_EPS5FeatureReportIdFirmwareInfo, data, USB_PACKET_LENGTH) >= 46) { + ctx->firmware_version = (Uint16)data[44] | ((Uint16)data[45] << 8); + } + } + + // Get the device capabilities + if (device->vendor_id == USB_VENDOR_SONY) { + ctx->sensors_supported = true; + ctx->lightbar_supported = true; + ctx->vibration_supported = true; + ctx->playerled_supported = true; + ctx->touchpad_supported = true; + } else { + // Third party controller capability request + size = ReadFeatureReport(device->dev, k_EPS5FeatureReportIdCapabilities, data, sizeof(data)); + if (size == 48 && data[2] == 0x28) { + Uint8 capabilities = data[4]; + Uint8 capabilities2 = data[20]; + Uint8 device_type = data[5]; + +#ifdef DEBUG_PS5_PROTOCOL + HIDAPI_DumpPacket("PS5 capabilities: size = %d", data, size); +#endif + if (capabilities & 0x02) { + ctx->sensors_supported = true; + } + if (capabilities & 0x04) { + ctx->lightbar_supported = true; + } + if (capabilities & 0x08) { + ctx->vibration_supported = true; + } + if (capabilities & 0x40) { + ctx->touchpad_supported = true; + } + if (capabilities2 & 0x80) { + ctx->playerled_supported = true; + } + + switch (device_type) { + case 0x00: + joystick_type = SDL_JOYSTICK_TYPE_GAMEPAD; + break; + case 0x01: + joystick_type = SDL_JOYSTICK_TYPE_GUITAR; + break; + case 0x02: + joystick_type = SDL_JOYSTICK_TYPE_DRUM_KIT; + break; + case 0x06: + joystick_type = SDL_JOYSTICK_TYPE_WHEEL; + break; + case 0x07: + joystick_type = SDL_JOYSTICK_TYPE_ARCADE_STICK; + break; + case 0x08: + joystick_type = SDL_JOYSTICK_TYPE_FLIGHT_STICK; + break; + default: + joystick_type = SDL_JOYSTICK_TYPE_UNKNOWN; + break; + } + + ctx->use_alternate_report = true; + + if (device->vendor_id == USB_VENDOR_NACON_ALT && + (device->product_id == USB_PRODUCT_NACON_REVOLUTION_5_PRO_PS5_WIRED || + device->product_id == USB_PRODUCT_NACON_REVOLUTION_5_PRO_PS5_WIRELESS)) { + // This doesn't report vibration capability, but it can do rumble + ctx->vibration_supported = true; + } + } else if (device->vendor_id == USB_VENDOR_RAZER && + (device->product_id == USB_PRODUCT_RAZER_WOLVERINE_V2_PRO_PS5_WIRED || + device->product_id == USB_PRODUCT_RAZER_WOLVERINE_V2_PRO_PS5_WIRELESS)) { + // The Razer Wolverine V2 Pro doesn't respond to the detection protocol, but has a touchpad and sensors and no vibration + ctx->sensors_supported = true; + ctx->touchpad_supported = true; + ctx->use_alternate_report = true; + } else if (device->vendor_id == USB_VENDOR_RAZER && + device->product_id == USB_PRODUCT_RAZER_KITSUNE) { + // The Razer Kitsune doesn't respond to the detection protocol, but has a touchpad + joystick_type = SDL_JOYSTICK_TYPE_ARCADE_STICK; + ctx->touchpad_supported = true; + ctx->use_alternate_report = true; + } + } + ctx->effects_supported = (ctx->lightbar_supported || ctx->vibration_supported || ctx->playerled_supported); + + if (device->vendor_id == USB_VENDOR_NACON_ALT && + device->product_id == USB_PRODUCT_NACON_REVOLUTION_5_PRO_PS5_WIRELESS) { + ctx->is_nacon_dongle = true; + } + + device->joystick_type = joystick_type; + device->type = SDL_GAMEPAD_TYPE_PS5; + if (device->vendor_id == USB_VENDOR_SONY) { + if (SDL_IsJoystickDualSenseEdge(device->vendor_id, device->product_id)) { + HIDAPI_SetDeviceName(device, "DualSense Edge Wireless Controller"); + } else { + HIDAPI_SetDeviceName(device, "DualSense Wireless Controller"); + } + } + HIDAPI_SetDeviceSerial(device, serial); + + if (ctx->is_nacon_dongle) { + // We don't know if this is connected yet, wait for reports + return true; + } + + // Prefer the USB device over the Bluetooth device + if (device->is_bluetooth) { + if (HIDAPI_HasConnectedUSBDevice(device->serial)) { + return true; + } + } else { + HIDAPI_DisconnectBluetoothDevice(device->serial); + } + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverPS5_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverPS5_LoadCalibrationData(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + int i, size; + Uint8 data[USB_PACKET_LENGTH]; + + size = ReadFeatureReport(device->dev, k_EPS5FeatureReportIdCalibration, data, sizeof(data)); + if (size < 35) { +#ifdef DEBUG_PS5_CALIBRATION + SDL_Log("Short read of calibration data: %d, ignoring calibration", size); +#endif + return; + } + + { + Sint16 sGyroPitchBias, sGyroYawBias, sGyroRollBias; + Sint16 sGyroPitchPlus, sGyroPitchMinus; + Sint16 sGyroYawPlus, sGyroYawMinus; + Sint16 sGyroRollPlus, sGyroRollMinus; + Sint16 sGyroSpeedPlus, sGyroSpeedMinus; + + Sint16 sAccXPlus, sAccXMinus; + Sint16 sAccYPlus, sAccYMinus; + Sint16 sAccZPlus, sAccZMinus; + + float flNumerator; + Sint16 sRange2g; + +#ifdef DEBUG_PS5_CALIBRATION + HIDAPI_DumpPacket("PS5 calibration packet: size = %d", data, size); +#endif + + sGyroPitchBias = LOAD16(data[1], data[2]); + sGyroYawBias = LOAD16(data[3], data[4]); + sGyroRollBias = LOAD16(data[5], data[6]); + + sGyroPitchPlus = LOAD16(data[7], data[8]); + sGyroPitchMinus = LOAD16(data[9], data[10]); + sGyroYawPlus = LOAD16(data[11], data[12]); + sGyroYawMinus = LOAD16(data[13], data[14]); + sGyroRollPlus = LOAD16(data[15], data[16]); + sGyroRollMinus = LOAD16(data[17], data[18]); + + sGyroSpeedPlus = LOAD16(data[19], data[20]); + sGyroSpeedMinus = LOAD16(data[21], data[22]); + + sAccXPlus = LOAD16(data[23], data[24]); + sAccXMinus = LOAD16(data[25], data[26]); + sAccYPlus = LOAD16(data[27], data[28]); + sAccYMinus = LOAD16(data[29], data[30]); + sAccZPlus = LOAD16(data[31], data[32]); + sAccZMinus = LOAD16(data[33], data[34]); + + flNumerator = (sGyroSpeedPlus + sGyroSpeedMinus) * GYRO_RES_PER_DEGREE; + ctx->calibration[0].bias = sGyroPitchBias; + ctx->calibration[0].sensitivity = flNumerator / (sGyroPitchPlus - sGyroPitchMinus); + + ctx->calibration[1].bias = sGyroYawBias; + ctx->calibration[1].sensitivity = flNumerator / (sGyroYawPlus - sGyroYawMinus); + + ctx->calibration[2].bias = sGyroRollBias; + ctx->calibration[2].sensitivity = flNumerator / (sGyroRollPlus - sGyroRollMinus); + + sRange2g = sAccXPlus - sAccXMinus; + ctx->calibration[3].bias = sAccXPlus - sRange2g / 2; + ctx->calibration[3].sensitivity = 2.0f * ACCEL_RES_PER_G / (float)sRange2g; + + sRange2g = sAccYPlus - sAccYMinus; + ctx->calibration[4].bias = sAccYPlus - sRange2g / 2; + ctx->calibration[4].sensitivity = 2.0f * ACCEL_RES_PER_G / (float)sRange2g; + + sRange2g = sAccZPlus - sAccZMinus; + ctx->calibration[5].bias = sAccZPlus - sRange2g / 2; + ctx->calibration[5].sensitivity = 2.0f * ACCEL_RES_PER_G / (float)sRange2g; + + ctx->hardware_calibration = true; + for (i = 0; i < 6; ++i) { + float divisor = (i < 3 ? 64.0f : 1.0f); +#ifdef DEBUG_PS5_CALIBRATION + SDL_Log("calibration[%d] bias = %d, sensitivity = %f", i, ctx->calibration[i].bias, ctx->calibration[i].sensitivity); +#endif + // Some controllers have a bad calibration + if ((SDL_abs(ctx->calibration[i].bias) > 1024) || (SDL_fabsf(1.0f - ctx->calibration[i].sensitivity / divisor) > 0.5f)) { +#ifdef DEBUG_PS5_CALIBRATION + SDL_Log("invalid calibration, ignoring"); +#endif + ctx->hardware_calibration = false; + } + } + } +} + +static float HIDAPI_DriverPS5_ApplyCalibrationData(SDL_DriverPS5_Context *ctx, int index, Sint16 value) +{ + float result; + + if (ctx->hardware_calibration) { + IMUCalibrationData *calibration = &ctx->calibration[index]; + + result = (value - calibration->bias) * calibration->sensitivity; + } else if (index < 3) { + result = value * 64.f; + } else { + result = value; + } + + // Convert the raw data to the units expected by SDL + if (index < 3) { + result = (result / GYRO_RES_PER_DEGREE) * SDL_PI_F / 180.0f; + } else { + result = (result / ACCEL_RES_PER_G) * SDL_STANDARD_GRAVITY; + } + return result; +} + +static bool HIDAPI_DriverPS5_UpdateEffects(SDL_DriverPS5_Context *ctx, int effect_mask, bool application_usage) +{ + DS5EffectsState_t effects; + + // Make sure the Bluetooth connection sequence has completed before sending LED color change + if (ctx->device->is_bluetooth && ctx->enhanced_reports && + (effect_mask & (k_EDS5EffectLED | k_EDS5EffectPadLights)) != 0) { + if (ctx->led_reset_state != k_EDS5LEDResetStateComplete) { + ctx->led_reset_state = k_EDS5LEDResetStatePending; + return true; + } + } + + SDL_zero(effects); + + if (ctx->vibration_supported) { + if (ctx->rumble_left || ctx->rumble_right) { + if (ctx->firmware_version < 0x0224) { + effects.ucEnableBits1 |= 0x01; // Enable rumble emulation + + // Shift to reduce effective rumble strength to match Xbox controllers + effects.ucRumbleLeft = ctx->rumble_left >> 1; + effects.ucRumbleRight = ctx->rumble_right >> 1; + } else { + effects.ucEnableBits3 |= 0x04; // Enable improved rumble emulation on 2.24 firmware and newer + + effects.ucRumbleLeft = ctx->rumble_left; + effects.ucRumbleRight = ctx->rumble_right; + } + effects.ucEnableBits1 |= 0x02; // Disable audio haptics + } else { + // Leaving emulated rumble bits off will restore audio haptics + } + + if ((effect_mask & k_EDS5EffectRumbleStart) != 0) { + effects.ucEnableBits1 |= 0x02; // Disable audio haptics + } + if ((effect_mask & k_EDS5EffectRumble) != 0) { + // Already handled above + } + } + if (ctx->lightbar_supported) { + if ((effect_mask & k_EDS5EffectLEDReset) != 0) { + effects.ucEnableBits2 |= 0x08; // Reset LED state + } + if ((effect_mask & k_EDS5EffectLED) != 0) { + effects.ucEnableBits2 |= 0x04; // Enable LED color + + // Populate the LED state with the appropriate color from our lookup table + if (ctx->color_set) { + effects.ucLedRed = ctx->led_red; + effects.ucLedGreen = ctx->led_green; + effects.ucLedBlue = ctx->led_blue; + } else { + SetLedsForPlayerIndex(&effects, ctx->player_index); + } + } + } + if (ctx->playerled_supported) { + if ((effect_mask & k_EDS5EffectPadLights) != 0) { + effects.ucEnableBits2 |= 0x10; // Enable touchpad lights + + if (ctx->player_lights) { + SetLightsForPlayerIndex(&effects, ctx->player_index); + } else { + effects.ucPadLights = 0x00; + } + } + } + if ((effect_mask & k_EDS5EffectMicLight) != 0) { + effects.ucEnableBits2 |= 0x01; // Enable microphone light + + effects.ucMicLightMode = 0; // Bitmask, 0x00 = off, 0x01 = solid, 0x02 = pulse + } + + return HIDAPI_DriverPS5_InternalSendJoystickEffect(ctx, &effects, sizeof(effects), application_usage); +} + +static void HIDAPI_DriverPS5_CheckPendingLEDReset(SDL_DriverPS5_Context *ctx) +{ + bool led_reset_complete = false; + + if (ctx->enhanced_reports && ctx->sensors_supported && !ctx->use_alternate_report) { + const PS5StatePacketCommon_t *packet = &ctx->last_state.state; + + // Check the timer to make sure the Bluetooth connection LED animation is complete + const Uint32 connection_complete = 10200000; + Uint32 timestamp = LOAD32(packet->rgucSensorTimestamp[0], + packet->rgucSensorTimestamp[1], + packet->rgucSensorTimestamp[2], + packet->rgucSensorTimestamp[3]); + if (timestamp >= connection_complete) { + led_reset_complete = true; + } + } else { + // We don't know how to check the timer, just assume it's complete for now + led_reset_complete = true; + } + + if (led_reset_complete) { + HIDAPI_DriverPS5_UpdateEffects(ctx, k_EDS5EffectLEDReset, false); + + ctx->led_reset_state = k_EDS5LEDResetStateComplete; + + HIDAPI_DriverPS5_UpdateEffects(ctx, (k_EDS5EffectLED | k_EDS5EffectPadLights), false); + } +} + +static void HIDAPI_DriverPS5_TickleBluetooth(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + + if (ctx->enhanced_reports) { + // This is just a dummy packet that should have no effect, since we don't set the CRC + Uint8 data[78]; + + SDL_zeroa(data); + + data[0] = k_EPS5ReportIdBluetoothEffects; + data[1] = 0x02; // Magic value + + if (SDL_HIDAPI_LockRumble()) { + SDL_HIDAPI_SendRumbleAndUnlock(device, data, sizeof(data)); + } + } else { + // We can't even send an invalid effects packet, or it will put the controller in enhanced mode + if (device->num_joysticks > 0) { + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + } +} + +static void HIDAPI_DriverPS5_SetEnhancedModeAvailable(SDL_DriverPS5_Context *ctx) +{ + if (ctx->enhanced_mode_available) { + return; + } + ctx->enhanced_mode_available = true; + + if (ctx->touchpad_supported) { + SDL_PrivateJoystickAddTouchpad(ctx->joystick, 2); + ctx->report_touchpad = true; + } + + if (ctx->sensors_supported) { + if (ctx->device->is_bluetooth) { + // Bluetooth sensor update rate appears to be 1000 Hz + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_GYRO, 1000.0f); + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_ACCEL, 1000.0f); + } else { + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_GYRO, 250.0f); + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_ACCEL, 250.0f); + } + } + + ctx->report_battery = true; + + HIDAPI_UpdateDeviceProperties(ctx->device); +} + +static void HIDAPI_DriverPS5_SetEnhancedMode(SDL_DriverPS5_Context *ctx) +{ + HIDAPI_DriverPS5_SetEnhancedModeAvailable(ctx); + + if (!ctx->enhanced_mode) { + ctx->enhanced_mode = true; + + // Switch into enhanced report mode + HIDAPI_DriverPS5_UpdateEffects(ctx, 0, false); + + // Update the light effects + HIDAPI_DriverPS5_UpdateEffects(ctx, (k_EDS5EffectLED | k_EDS5EffectPadLights), false); + } +} + +static void HIDAPI_DriverPS5_SetEnhancedReportHint(SDL_DriverPS5_Context *ctx, HIDAPI_PS5_EnhancedReportHint enhanced_report_hint) +{ + switch (enhanced_report_hint) { + case PS5_ENHANCED_REPORT_HINT_OFF: + // Nothing to do, enhanced mode is a one-way ticket + break; + case PS5_ENHANCED_REPORT_HINT_ON: + HIDAPI_DriverPS5_SetEnhancedMode(ctx); + break; + case PS5_ENHANCED_REPORT_HINT_AUTO: + HIDAPI_DriverPS5_SetEnhancedModeAvailable(ctx); + break; + } + ctx->enhanced_report_hint = enhanced_report_hint; +} + +static void HIDAPI_DriverPS5_UpdateEnhancedModeOnEnhancedReport(SDL_DriverPS5_Context *ctx) +{ + ctx->enhanced_reports = true; + + if (ctx->enhanced_report_hint == PS5_ENHANCED_REPORT_HINT_AUTO) { + HIDAPI_DriverPS5_SetEnhancedReportHint(ctx, PS5_ENHANCED_REPORT_HINT_ON); + } +} + +static void HIDAPI_DriverPS5_UpdateEnhancedModeOnApplicationUsage(SDL_DriverPS5_Context *ctx) +{ + if (ctx->enhanced_report_hint == PS5_ENHANCED_REPORT_HINT_AUTO) { + HIDAPI_DriverPS5_SetEnhancedReportHint(ctx, PS5_ENHANCED_REPORT_HINT_ON); + } +} + +static void SDLCALL SDL_PS5EnhancedReportsChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)userdata; + + if (ctx->device->is_bluetooth) { + if (hint && SDL_strcasecmp(hint, "auto") == 0) { + HIDAPI_DriverPS5_SetEnhancedReportHint(ctx, PS5_ENHANCED_REPORT_HINT_AUTO); + } else if (SDL_GetStringBoolean(hint, true)) { + HIDAPI_DriverPS5_SetEnhancedReportHint(ctx, PS5_ENHANCED_REPORT_HINT_ON); + } else { + HIDAPI_DriverPS5_SetEnhancedReportHint(ctx, PS5_ENHANCED_REPORT_HINT_OFF); + } + } else { + HIDAPI_DriverPS5_SetEnhancedReportHint(ctx, PS5_ENHANCED_REPORT_HINT_ON); + } +} + +static void SDLCALL SDL_PS5PlayerLEDHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)userdata; + bool player_lights = SDL_GetStringBoolean(hint, true); + + if (player_lights != ctx->player_lights) { + ctx->player_lights = player_lights; + + HIDAPI_DriverPS5_UpdateEffects(ctx, k_EDS5EffectPadLights, false); + } +} + +static void HIDAPI_DriverPS5_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + + if (!ctx->joystick) { + return; + } + + ctx->player_index = player_index; + + // This will set the new LED state based on the new player index + // SDL automatically calls this, so it doesn't count as an application action to enable enhanced mode + HIDAPI_DriverPS5_UpdateEffects(ctx, (k_EDS5EffectLED | k_EDS5EffectPadLights), false); +} + +static bool HIDAPI_DriverPS5_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + ctx->joystick = joystick; + ctx->last_packet = SDL_GetTicks(); + ctx->report_sensors = false; + ctx->report_touchpad = false; + ctx->rumble_left = 0; + ctx->rumble_right = 0; + ctx->color_set = false; + ctx->led_reset_state = k_EDS5LEDResetStateNone; + SDL_zero(ctx->last_state); + + // Initialize player index (needed for setting LEDs) + ctx->player_index = SDL_GetJoystickPlayerIndex(joystick); + ctx->player_lights = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED, true); + + // Initialize the joystick capabilities + if (SDL_IsJoystickDualSenseEdge(device->vendor_id, device->product_id)) { + joystick->nbuttons = 17; // paddles and touchpad and microphone + } else if (ctx->touchpad_supported) { + joystick->nbuttons = 13; // touchpad and microphone + } else { + joystick->nbuttons = 11; + } + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + joystick->firmware_version = ctx->firmware_version; + + SDL_AddHintCallback(SDL_HINT_JOYSTICK_ENHANCED_REPORTS, + SDL_PS5EnhancedReportsChanged, ctx); + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED, + SDL_PS5PlayerLEDHintChanged, ctx); + + return true; +} + +static bool HIDAPI_DriverPS5_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + + if (!ctx->vibration_supported) { + return SDL_Unsupported(); + } + + if (!ctx->rumble_left && !ctx->rumble_right) { + HIDAPI_DriverPS5_UpdateEffects(ctx, k_EDS5EffectRumbleStart, true); + } + + ctx->rumble_left = (low_frequency_rumble >> 8); + ctx->rumble_right = (high_frequency_rumble >> 8); + + return HIDAPI_DriverPS5_UpdateEffects(ctx, k_EDS5EffectRumble, true); +} + +static bool HIDAPI_DriverPS5_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverPS5_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + Uint32 result = 0; + + if (ctx->enhanced_mode_available) { + if (ctx->lightbar_supported) { + result |= SDL_JOYSTICK_CAP_RGB_LED; + } + if (ctx->playerled_supported) { + result |= SDL_JOYSTICK_CAP_PLAYER_LED; + } + if (ctx->vibration_supported) { + result |= SDL_JOYSTICK_CAP_RUMBLE; + } + } + + return result; +} + +static bool HIDAPI_DriverPS5_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + + if (!ctx->lightbar_supported) { + return SDL_Unsupported(); + } + + ctx->color_set = true; + ctx->led_red = red; + ctx->led_green = green; + ctx->led_blue = blue; + + return HIDAPI_DriverPS5_UpdateEffects(ctx, k_EDS5EffectLED, true); +} + +static bool HIDAPI_DriverPS5_InternalSendJoystickEffect(SDL_DriverPS5_Context *ctx, const void *effect, int size, bool application_usage) +{ + Uint8 data[78]; + int report_size, offset; + Uint8 *pending_data; + int *pending_size; + int maximum_size; + + if (!ctx->effects_supported) { + // We shouldn't be sending packets to this controller + return SDL_Unsupported(); + } + + if (!ctx->enhanced_mode) { + if (application_usage) { + HIDAPI_DriverPS5_UpdateEnhancedModeOnApplicationUsage(ctx); + } + + if (!ctx->enhanced_mode) { + // We're not in enhanced mode, effects aren't allowed + return SDL_Unsupported(); + } + } + + SDL_zeroa(data); + + if (ctx->device->is_bluetooth) { + data[0] = k_EPS5ReportIdBluetoothEffects; + data[1] = 0x02; // Magic value + + report_size = 78; + offset = 2; + } else { + data[0] = k_EPS5ReportIdUsbEffects; + + report_size = 48; + offset = 1; + } + + SDL_memcpy(&data[offset], effect, SDL_min((sizeof(data) - offset), (size_t)size)); + + if (ctx->device->is_bluetooth) { + // Bluetooth reports need a CRC at the end of the packet (at least on Linux) + Uint8 ubHdr = 0xA2; // hidp header is part of the CRC calculation + Uint32 unCRC; + unCRC = SDL_crc32(0, &ubHdr, 1); + unCRC = SDL_crc32(unCRC, data, (size_t)(report_size - sizeof(unCRC))); + SDL_memcpy(&data[report_size - sizeof(unCRC)], &unCRC, sizeof(unCRC)); + } + + if (!SDL_HIDAPI_LockRumble()) { + return false; + } + + // See if we can update an existing pending request + if (SDL_HIDAPI_GetPendingRumbleLocked(ctx->device, &pending_data, &pending_size, &maximum_size)) { + DS5EffectsState_t *effects = (DS5EffectsState_t *)&data[offset]; + DS5EffectsState_t *pending_effects = (DS5EffectsState_t *)&pending_data[offset]; + if (report_size == *pending_size && + effects->ucEnableBits1 == pending_effects->ucEnableBits1 && + effects->ucEnableBits2 == pending_effects->ucEnableBits2) { + // We're simply updating the data for this request + SDL_memcpy(pending_data, data, report_size); + SDL_HIDAPI_UnlockRumble(); + return true; + } + } + + if (SDL_HIDAPI_SendRumbleAndUnlock(ctx->device, data, report_size) != report_size) { + return false; + } + + return true; +} + +static bool HIDAPI_DriverPS5_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *effect, int size) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + + return HIDAPI_DriverPS5_InternalSendJoystickEffect(ctx, effect, size, true); +} + +static bool HIDAPI_DriverPS5_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + + HIDAPI_DriverPS5_UpdateEnhancedModeOnApplicationUsage(ctx); + + if (!ctx->sensors_supported || (enabled && !ctx->enhanced_mode)) { + return SDL_Unsupported(); + } + + if (enabled) { + HIDAPI_DriverPS5_LoadCalibrationData(device); + } + ctx->report_sensors = enabled; + + return true; +} + +static void HIDAPI_DriverPS5_HandleSimpleStatePacket(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverPS5_Context *ctx, PS5SimpleStatePacket_t *packet, Uint64 timestamp) +{ + Sint16 axis; + + if (ctx->last_state.simple.rgucButtonsHatAndCounter[0] != packet->rgucButtonsHatAndCounter[0]) { + { + Uint8 data = (packet->rgucButtonsHatAndCounter[0] >> 4); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data & 0x08) != 0)); + } + { + Uint8 data = (packet->rgucButtonsHatAndCounter[0] & 0x0F); + Uint8 hat; + + switch (data) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + } + + if (ctx->last_state.simple.rgucButtonsHatAndCounter[1] != packet->rgucButtonsHatAndCounter[1]) { + Uint8 data = packet->rgucButtonsHatAndCounter[1]; + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x80) != 0)); + } + + if (ctx->last_state.simple.rgucButtonsHatAndCounter[2] != packet->rgucButtonsHatAndCounter[2]) { + Uint8 data = (packet->rgucButtonsHatAndCounter[2] & 0x03); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_PS5_TOUCHPAD, ((data & 0x02) != 0)); + } + + if (packet->ucTriggerLeft == 0 && (packet->rgucButtonsHatAndCounter[1] & 0x04)) { + axis = SDL_JOYSTICK_AXIS_MAX; + } else { + axis = ((int)packet->ucTriggerLeft * 257) - 32768; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + if (packet->ucTriggerRight == 0 && (packet->rgucButtonsHatAndCounter[1] & 0x08)) { + axis = SDL_JOYSTICK_AXIS_MAX; + } else { + axis = ((int)packet->ucTriggerRight * 257) - 32768; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + axis = ((int)packet->ucLeftJoystickX * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = ((int)packet->ucLeftJoystickY * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = ((int)packet->ucRightJoystickX * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = ((int)packet->ucRightJoystickY * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + SDL_memcpy(&ctx->last_state.simple, packet, sizeof(ctx->last_state.simple)); +} + +static void HIDAPI_DriverPS5_HandleStatePacketCommon(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverPS5_Context *ctx, PS5StatePacketCommon_t *packet, Uint64 timestamp) +{ + Sint16 axis; + + if (ctx->last_state.state.rgucButtonsAndHat[0] != packet->rgucButtonsAndHat[0]) { + { + Uint8 data = (packet->rgucButtonsAndHat[0] >> 4); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data & 0x08) != 0)); + } + { + Uint8 data = (packet->rgucButtonsAndHat[0] & 0x0F); + Uint8 hat; + + switch (data) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + } + + if (ctx->last_state.state.rgucButtonsAndHat[1] != packet->rgucButtonsAndHat[1]) { + Uint8 data = packet->rgucButtonsAndHat[1]; + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x80) != 0)); + } + + if (ctx->last_state.state.rgucButtonsAndHat[2] != packet->rgucButtonsAndHat[2]) { + Uint8 data = packet->rgucButtonsAndHat[2]; + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_PS5_TOUCHPAD, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_PS5_MICROPHONE, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_PS5_LEFT_FUNCTION, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_PS5_RIGHT_FUNCTION, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_PS5_LEFT_PADDLE, ((data & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_PS5_RIGHT_PADDLE, ((data & 0x80) != 0)); + } + + if (packet->ucTriggerLeft == 0 && (packet->rgucButtonsAndHat[1] & 0x04)) { + axis = SDL_JOYSTICK_AXIS_MAX; + } else { + axis = ((int)packet->ucTriggerLeft * 257) - 32768; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + if (packet->ucTriggerRight == 0 && (packet->rgucButtonsAndHat[1] & 0x08)) { + axis = SDL_JOYSTICK_AXIS_MAX; + } else { + axis = ((int)packet->ucTriggerRight * 257) - 32768; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + axis = ((int)packet->ucLeftJoystickX * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = ((int)packet->ucLeftJoystickY * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = ((int)packet->ucRightJoystickX * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = ((int)packet->ucRightJoystickY * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + if (ctx->report_sensors) { + Uint64 sensor_timestamp; + float data[3]; + + if (ctx->use_alternate_report) { + // 16-bit timestamp + Uint32 delta; + Uint16 tick = LOAD16(packet->rgucSensorTimestamp[0], + packet->rgucSensorTimestamp[1]); + if (ctx->last_tick < tick) { + delta = (tick - ctx->last_tick); + } else { + delta = (SDL_MAX_UINT16 - ctx->last_tick + tick + 1); + } + ctx->last_tick = tick; + ctx->sensor_ticks += delta; + + // Sensor timestamp is in 1us units + sensor_timestamp = SDL_US_TO_NS(ctx->sensor_ticks); + } else { + // 32-bit timestamp + Uint32 delta; + Uint32 tick = LOAD32(packet->rgucSensorTimestamp[0], + packet->rgucSensorTimestamp[1], + packet->rgucSensorTimestamp[2], + packet->rgucSensorTimestamp[3]); + if (ctx->last_tick < tick) { + delta = (tick - ctx->last_tick); + } else { + delta = (SDL_MAX_UINT32 - ctx->last_tick + tick + 1); + } + ctx->last_tick = tick; + ctx->sensor_ticks += delta; + + // Sensor timestamp is in 0.33us units + sensor_timestamp = (ctx->sensor_ticks * SDL_NS_PER_US) / 3; + } + + data[0] = HIDAPI_DriverPS5_ApplyCalibrationData(ctx, 0, LOAD16(packet->rgucGyroX[0], packet->rgucGyroX[1])); + data[1] = HIDAPI_DriverPS5_ApplyCalibrationData(ctx, 1, LOAD16(packet->rgucGyroY[0], packet->rgucGyroY[1])); + data[2] = HIDAPI_DriverPS5_ApplyCalibrationData(ctx, 2, LOAD16(packet->rgucGyroZ[0], packet->rgucGyroZ[1])); + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, sensor_timestamp, data, 3); + + data[0] = HIDAPI_DriverPS5_ApplyCalibrationData(ctx, 3, LOAD16(packet->rgucAccelX[0], packet->rgucAccelX[1])); + data[1] = HIDAPI_DriverPS5_ApplyCalibrationData(ctx, 4, LOAD16(packet->rgucAccelY[0], packet->rgucAccelY[1])); + data[2] = HIDAPI_DriverPS5_ApplyCalibrationData(ctx, 5, LOAD16(packet->rgucAccelZ[0], packet->rgucAccelZ[1])); + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, sensor_timestamp, data, 3); + } +} + +static void HIDAPI_DriverPS5_HandleStatePacket(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverPS5_Context *ctx, PS5StatePacket_t *packet, Uint64 timestamp) +{ + static const float TOUCHPAD_SCALEX = 5.20833333e-4f; // 1.0f / 1920 + static const float TOUCHPAD_SCALEY = 9.34579439e-4f; // 1.0f / 1070 + bool touchpad_down; + int touchpad_x, touchpad_y; + + if (ctx->report_touchpad) { + touchpad_down = ((packet->ucTouchpadCounter1 & 0x80) == 0); + touchpad_x = packet->rgucTouchpadData1[0] | (((int)packet->rgucTouchpadData1[1] & 0x0F) << 8); + touchpad_y = (packet->rgucTouchpadData1[1] >> 4) | ((int)packet->rgucTouchpadData1[2] << 4); + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, touchpad_down, touchpad_x * TOUCHPAD_SCALEX, touchpad_y * TOUCHPAD_SCALEY, touchpad_down ? 1.0f : 0.0f); + + touchpad_down = ((packet->ucTouchpadCounter2 & 0x80) == 0); + touchpad_x = packet->rgucTouchpadData2[0] | (((int)packet->rgucTouchpadData2[1] & 0x0F) << 8); + touchpad_y = (packet->rgucTouchpadData2[1] >> 4) | ((int)packet->rgucTouchpadData2[2] << 4); + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 1, touchpad_down, touchpad_x * TOUCHPAD_SCALEX, touchpad_y * TOUCHPAD_SCALEY, touchpad_down ? 1.0f : 0.0f); + } + + if (ctx->report_battery) { + SDL_PowerState state; + int percent; + Uint8 status = (packet->ucBatteryLevel >> 4) & 0x0F; + Uint8 level = (packet->ucBatteryLevel & 0x0F); + + switch (status) { + case 0: + state = SDL_POWERSTATE_ON_BATTERY; + percent = SDL_min(level * 10 + 5, 100); + break; + case 1: + state = SDL_POWERSTATE_CHARGING; + percent = SDL_min(level * 10 + 5, 100); + break; + case 2: + state = SDL_POWERSTATE_CHARGED; + percent = 100; + break; + default: + state = SDL_POWERSTATE_UNKNOWN; + percent = 0; + break; + } + SDL_SendJoystickPowerInfo(joystick, state, percent); + } + + HIDAPI_DriverPS5_HandleStatePacketCommon(joystick, dev, ctx, (PS5StatePacketCommon_t *)packet, timestamp); + + SDL_memcpy(&ctx->last_state, packet, sizeof(ctx->last_state)); +} + +static void HIDAPI_DriverPS5_HandleStatePacketAlt(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverPS5_Context *ctx, PS5StatePacketAlt_t *packet, Uint64 timestamp) +{ + static const float TOUCHPAD_SCALEX = 5.20833333e-4f; // 1.0f / 1920 + static const float TOUCHPAD_SCALEY = 9.34579439e-4f; // 1.0f / 1070 + bool touchpad_down; + int touchpad_x, touchpad_y; + + if (ctx->report_touchpad) { + touchpad_down = ((packet->ucTouchpadCounter1 & 0x80) == 0); + touchpad_x = packet->rgucTouchpadData1[0] | (((int)packet->rgucTouchpadData1[1] & 0x0F) << 8); + touchpad_y = (packet->rgucTouchpadData1[1] >> 4) | ((int)packet->rgucTouchpadData1[2] << 4); + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, touchpad_down, touchpad_x * TOUCHPAD_SCALEX, touchpad_y * TOUCHPAD_SCALEY, touchpad_down ? 1.0f : 0.0f); + + touchpad_down = ((packet->ucTouchpadCounter2 & 0x80) == 0); + touchpad_x = packet->rgucTouchpadData2[0] | (((int)packet->rgucTouchpadData2[1] & 0x0F) << 8); + touchpad_y = (packet->rgucTouchpadData2[1] >> 4) | ((int)packet->rgucTouchpadData2[2] << 4); + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 1, touchpad_down, touchpad_x * TOUCHPAD_SCALEX, touchpad_y * TOUCHPAD_SCALEY, touchpad_down ? 1.0f : 0.0f); + } + + HIDAPI_DriverPS5_HandleStatePacketCommon(joystick, dev, ctx, (PS5StatePacketCommon_t *)packet, timestamp); + + SDL_memcpy(&ctx->last_state, packet, sizeof(ctx->last_state)); +} + +static bool VerifyCRC(Uint8 *data, int size) +{ + Uint8 ubHdr = 0xA1; // hidp header is part of the CRC calculation + Uint32 unCRC, unPacketCRC; + Uint8 *packetCRC = data + size - sizeof(unPacketCRC); + unCRC = SDL_crc32(0, &ubHdr, 1); + unCRC = SDL_crc32(unCRC, data, (size_t)(size - sizeof(unCRC))); + + unPacketCRC = LOAD32(packetCRC[0], + packetCRC[1], + packetCRC[2], + packetCRC[3]); + return (unCRC == unPacketCRC); +} + +static bool HIDAPI_DriverPS5_IsPacketValid(SDL_DriverPS5_Context *ctx, Uint8 *data, int size) +{ + switch (data[0]) { + case k_EPS5ReportIdState: + if (ctx->is_nacon_dongle && size >= (1 + sizeof(PS5StatePacketAlt_t))) { + // The report timestamp doesn't change when the controller isn't connected + PS5StatePacketAlt_t *packet = (PS5StatePacketAlt_t *)&data[1]; + if (SDL_memcmp(packet->rgucPacketSequence, ctx->last_state.state.rgucPacketSequence, sizeof(packet->rgucPacketSequence)) == 0) { + return false; + } + if (ctx->last_state.alt_state.rgucAccelX[0] == 0 && ctx->last_state.alt_state.rgucAccelX[1] == 0 && + ctx->last_state.alt_state.rgucAccelY[0] == 0 && ctx->last_state.alt_state.rgucAccelY[1] == 0 && + ctx->last_state.alt_state.rgucAccelZ[0] == 0 && ctx->last_state.alt_state.rgucAccelZ[1] == 0) { + // We don't have any state to compare yet, go ahead and copy it + SDL_memcpy(&ctx->last_state, &data[1], sizeof(PS5StatePacketAlt_t)); + return false; + } + } + return true; + + case k_EPS5ReportIdBluetoothState: + if (VerifyCRC(data, size)) { + return true; + } + break; + default: + break; + } + return false; +} + +static bool HIDAPI_DriverPS5_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH * 2]; + int size; + int packet_count = 0; + Uint64 now = SDL_GetTicks(); + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { + Uint64 timestamp = SDL_GetTicksNS(); + +#ifdef DEBUG_PS5_PROTOCOL + HIDAPI_DumpPacket("PS5 packet: size = %d", data, size); +#endif + if (!HIDAPI_DriverPS5_IsPacketValid(ctx, data, size)) { + continue; + } + + ++packet_count; + ctx->last_packet = now; + + if (!joystick) { + continue; + } + + switch (data[0]) { + case k_EPS5ReportIdState: + if (size == 10 || size == 78) { + HIDAPI_DriverPS5_HandleSimpleStatePacket(joystick, device->dev, ctx, (PS5SimpleStatePacket_t *)&data[1], timestamp); + } else { + if (ctx->use_alternate_report) { + HIDAPI_DriverPS5_HandleStatePacketAlt(joystick, device->dev, ctx, (PS5StatePacketAlt_t *)&data[1], timestamp); + } else { + HIDAPI_DriverPS5_HandleStatePacket(joystick, device->dev, ctx, (PS5StatePacket_t *)&data[1], timestamp); + } + } + break; + case k_EPS5ReportIdBluetoothState: + // This is the extended report, we can enable effects now in auto mode + HIDAPI_DriverPS5_UpdateEnhancedModeOnEnhancedReport(ctx); + + if (ctx->use_alternate_report) { + HIDAPI_DriverPS5_HandleStatePacketAlt(joystick, device->dev, ctx, (PS5StatePacketAlt_t *)&data[2], timestamp); + } else { + HIDAPI_DriverPS5_HandleStatePacket(joystick, device->dev, ctx, (PS5StatePacket_t *)&data[2], timestamp); + } + if (ctx->led_reset_state == k_EDS5LEDResetStatePending) { + HIDAPI_DriverPS5_CheckPendingLEDReset(ctx); + } + break; + default: +#ifdef DEBUG_JOYSTICK + SDL_Log("Unknown PS5 packet: 0x%.2x", data[0]); +#endif + break; + } + } + + if (device->is_bluetooth) { + if (packet_count == 0) { + // Check to see if it looks like the device disconnected + if (now >= (ctx->last_packet + BLUETOOTH_DISCONNECT_TIMEOUT_MS)) { + // Send an empty output report to tickle the Bluetooth stack + HIDAPI_DriverPS5_TickleBluetooth(device); + ctx->last_packet = now; + } + } else { + // Reconnect the Bluetooth device once the USB device is gone + if (device->num_joysticks == 0 && + !HIDAPI_HasConnectedUSBDevice(device->serial)) { + HIDAPI_JoystickConnected(device, NULL); + } + } + } + + if (ctx->is_nacon_dongle) { + if (packet_count == 0) { + if (device->num_joysticks > 0) { + // Check to see if it looks like the device disconnected + if (now >= (ctx->last_packet + BLUETOOTH_DISCONNECT_TIMEOUT_MS)) { + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + } + } else { + if (device->num_joysticks == 0) { + HIDAPI_JoystickConnected(device, NULL); + } + } + } + + if (packet_count == 0 && size < 0 && device->num_joysticks > 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverPS5_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverPS5_Context *ctx = (SDL_DriverPS5_Context *)device->context; + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_ENHANCED_REPORTS, + SDL_PS5EnhancedReportsChanged, ctx); + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED, + SDL_PS5PlayerLEDHintChanged, ctx); + + ctx->joystick = NULL; + + ctx->report_sensors = false; + ctx->enhanced_mode = false; + ctx->enhanced_mode_available = false; +} + +static void HIDAPI_DriverPS5_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS5 = { + SDL_HINT_JOYSTICK_HIDAPI_PS5, + true, + HIDAPI_DriverPS5_RegisterHints, + HIDAPI_DriverPS5_UnregisterHints, + HIDAPI_DriverPS5_IsEnabled, + HIDAPI_DriverPS5_IsSupportedDevice, + HIDAPI_DriverPS5_InitDevice, + HIDAPI_DriverPS5_GetDevicePlayerIndex, + HIDAPI_DriverPS5_SetDevicePlayerIndex, + HIDAPI_DriverPS5_UpdateDevice, + HIDAPI_DriverPS5_OpenJoystick, + HIDAPI_DriverPS5_RumbleJoystick, + HIDAPI_DriverPS5_RumbleJoystickTriggers, + HIDAPI_DriverPS5_GetJoystickCapabilities, + HIDAPI_DriverPS5_SetJoystickLED, + HIDAPI_DriverPS5_SendJoystickEffect, + HIDAPI_DriverPS5_SetJoystickSensorsEnabled, + HIDAPI_DriverPS5_CloseJoystick, + HIDAPI_DriverPS5_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_PS5 + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_rumble.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_rumble.c new file mode 100644 index 00000000000..5fd93dc0b5a --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_rumble.c @@ -0,0 +1,285 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +// Handle rumble on a separate thread so it doesn't block the application + +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" +#include "../../thread/SDL_systhread.h" + +typedef struct SDL_HIDAPI_RumbleRequest +{ + SDL_HIDAPI_Device *device; + Uint8 data[2 * USB_PACKET_LENGTH]; // need enough space for the biggest report: dualshock4 is 78 bytes + int size; + SDL_HIDAPI_RumbleSentCallback callback; + void *userdata; + struct SDL_HIDAPI_RumbleRequest *prev; + +} SDL_HIDAPI_RumbleRequest; + +typedef struct SDL_HIDAPI_RumbleContext +{ + SDL_AtomicInt initialized; + SDL_AtomicInt running; + SDL_Thread *thread; + SDL_Semaphore *request_sem; + SDL_HIDAPI_RumbleRequest *requests_head; + SDL_HIDAPI_RumbleRequest *requests_tail; +} SDL_HIDAPI_RumbleContext; + +#ifndef SDL_THREAD_SAFETY_ANALYSIS +static +#endif +SDL_Mutex *SDL_HIDAPI_rumble_lock; +static SDL_HIDAPI_RumbleContext rumble_context SDL_GUARDED_BY(SDL_HIDAPI_rumble_lock); + +static int SDLCALL SDL_HIDAPI_RumbleThread(void *data) +{ + SDL_HIDAPI_RumbleContext *ctx = (SDL_HIDAPI_RumbleContext *)data; + + SDL_SetCurrentThreadPriority(SDL_THREAD_PRIORITY_HIGH); + + while (SDL_GetAtomicInt(&ctx->running)) { + SDL_HIDAPI_RumbleRequest *request = NULL; + + SDL_WaitSemaphore(ctx->request_sem); + + SDL_LockMutex(SDL_HIDAPI_rumble_lock); + request = ctx->requests_tail; + if (request) { + if (request == ctx->requests_head) { + ctx->requests_head = NULL; + } + ctx->requests_tail = request->prev; + } + SDL_UnlockMutex(SDL_HIDAPI_rumble_lock); + + if (request) { + SDL_LockMutex(request->device->dev_lock); + if (request->device->dev) { +#ifdef DEBUG_RUMBLE + HIDAPI_DumpPacket("Rumble packet: size = %d", request->data, request->size); +#endif + SDL_hid_write(request->device->dev, request->data, request->size); + } + SDL_UnlockMutex(request->device->dev_lock); + if (request->callback) { + request->callback(request->userdata); + } + (void)SDL_AtomicDecRef(&request->device->rumble_pending); + SDL_free(request); + + // Make sure we're not starving report reads when there's lots of rumble + SDL_Delay(10); + } + } + return 0; +} + +static void SDL_HIDAPI_StopRumbleThread(SDL_HIDAPI_RumbleContext *ctx) +{ + SDL_HIDAPI_RumbleRequest *request; + + SDL_SetAtomicInt(&ctx->running, false); + + if (ctx->thread) { + int result; + + SDL_SignalSemaphore(ctx->request_sem); + SDL_WaitThread(ctx->thread, &result); + ctx->thread = NULL; + } + + SDL_LockMutex(SDL_HIDAPI_rumble_lock); + while (ctx->requests_tail) { + request = ctx->requests_tail; + if (request == ctx->requests_head) { + ctx->requests_head = NULL; + } + ctx->requests_tail = request->prev; + + if (request->callback) { + request->callback(request->userdata); + } + (void)SDL_AtomicDecRef(&request->device->rumble_pending); + SDL_free(request); + } + SDL_UnlockMutex(SDL_HIDAPI_rumble_lock); + + if (ctx->request_sem) { + SDL_DestroySemaphore(ctx->request_sem); + ctx->request_sem = NULL; + } + + if (SDL_HIDAPI_rumble_lock) { + SDL_DestroyMutex(SDL_HIDAPI_rumble_lock); + SDL_HIDAPI_rumble_lock = NULL; + } + + SDL_SetAtomicInt(&ctx->initialized, false); +} + +static bool SDL_HIDAPI_StartRumbleThread(SDL_HIDAPI_RumbleContext *ctx) +{ + SDL_HIDAPI_rumble_lock = SDL_CreateMutex(); + if (!SDL_HIDAPI_rumble_lock) { + SDL_HIDAPI_StopRumbleThread(ctx); + return false; + } + + ctx->request_sem = SDL_CreateSemaphore(0); + if (!ctx->request_sem) { + SDL_HIDAPI_StopRumbleThread(ctx); + return false; + } + + SDL_SetAtomicInt(&ctx->running, true); + ctx->thread = SDL_CreateThread(SDL_HIDAPI_RumbleThread, "HIDAPI Rumble", ctx); + if (!ctx->thread) { + SDL_HIDAPI_StopRumbleThread(ctx); + return false; + } + return true; +} + +bool SDL_HIDAPI_LockRumble(void) +{ + SDL_HIDAPI_RumbleContext *ctx = &rumble_context; + + if (SDL_CompareAndSwapAtomicInt(&ctx->initialized, false, true)) { + if (!SDL_HIDAPI_StartRumbleThread(ctx)) { + return false; + } + } + + SDL_LockMutex(SDL_HIDAPI_rumble_lock); + return true; +} + +bool SDL_HIDAPI_GetPendingRumbleLocked(SDL_HIDAPI_Device *device, Uint8 **data, int **size, int *maximum_size) +{ + SDL_HIDAPI_RumbleContext *ctx = &rumble_context; + SDL_HIDAPI_RumbleRequest *request, *found; + + found = NULL; + for (request = ctx->requests_tail; request; request = request->prev) { + if (request->device == device) { + found = request; + } + } + if (found) { + *data = found->data; + *size = &found->size; + *maximum_size = sizeof(found->data); + return true; + } + return false; +} + +int SDL_HIDAPI_SendRumbleAndUnlock(SDL_HIDAPI_Device *device, const Uint8 *data, int size) +{ + return SDL_HIDAPI_SendRumbleWithCallbackAndUnlock(device, data, size, NULL, NULL); +} + +int SDL_HIDAPI_SendRumbleWithCallbackAndUnlock(SDL_HIDAPI_Device *device, const Uint8 *data, int size, SDL_HIDAPI_RumbleSentCallback callback, void *userdata) +{ + SDL_HIDAPI_RumbleContext *ctx = &rumble_context; + SDL_HIDAPI_RumbleRequest *request; + + if (size > sizeof(request->data)) { + SDL_HIDAPI_UnlockRumble(); + SDL_SetError("Couldn't send rumble, size %d is greater than %d", size, (int)sizeof(request->data)); + return -1; + } + + request = (SDL_HIDAPI_RumbleRequest *)SDL_calloc(1, sizeof(*request)); + if (!request) { + SDL_HIDAPI_UnlockRumble(); + return -1; + } + request->device = device; + SDL_memcpy(request->data, data, size); + request->size = size; + request->callback = callback; + request->userdata = userdata; + + SDL_AtomicIncRef(&device->rumble_pending); + + if (ctx->requests_head) { + ctx->requests_head->prev = request; + } else { + ctx->requests_tail = request; + } + ctx->requests_head = request; + + // Make sure we unlock before posting the semaphore so the rumble thread can run immediately + SDL_HIDAPI_UnlockRumble(); + + SDL_SignalSemaphore(ctx->request_sem); + + return size; +} + +void SDL_HIDAPI_UnlockRumble(void) +{ + SDL_UnlockMutex(SDL_HIDAPI_rumble_lock); +} + +int SDL_HIDAPI_SendRumble(SDL_HIDAPI_Device *device, const Uint8 *data, int size) +{ + Uint8 *pending_data; + int *pending_size; + int maximum_size; + + if (size <= 0) { + SDL_SetError("Tried to send rumble with invalid size"); + return -1; + } + + if (!SDL_HIDAPI_LockRumble()) { + return -1; + } + + // check if there is a pending request for the device and update it + if (SDL_HIDAPI_GetPendingRumbleLocked(device, &pending_data, &pending_size, &maximum_size) && + size == *pending_size && data[0] == pending_data[0]) { + SDL_memcpy(pending_data, data, size); + SDL_HIDAPI_UnlockRumble(); + return size; + } + + return SDL_HIDAPI_SendRumbleAndUnlock(device, data, size); +} + +void SDL_HIDAPI_QuitRumble(void) +{ + SDL_HIDAPI_RumbleContext *ctx = &rumble_context; + + if (SDL_GetAtomicInt(&ctx->running)) { + SDL_HIDAPI_StopRumbleThread(ctx); + } +} + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_rumble.h b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_rumble.h new file mode 100644 index 00000000000..ede061e0cf2 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_rumble.h @@ -0,0 +1,42 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +// Handle rumble on a separate thread so it doesn't block the application + +// Advanced API +#ifdef SDL_THREAD_SAFETY_ANALYSIS +extern SDL_Mutex *SDL_HIDAPI_rumble_lock; +#endif +bool SDL_HIDAPI_LockRumble(void) SDL_TRY_ACQUIRE(0, SDL_HIDAPI_rumble_lock); +bool SDL_HIDAPI_GetPendingRumbleLocked(SDL_HIDAPI_Device *device, Uint8 **data, int **size, int *maximum_size); +int SDL_HIDAPI_SendRumbleAndUnlock(SDL_HIDAPI_Device *device, const Uint8 *data, int size) SDL_RELEASE(SDL_HIDAPI_rumble_lock); +typedef void (*SDL_HIDAPI_RumbleSentCallback)(void *userdata); +int SDL_HIDAPI_SendRumbleWithCallbackAndUnlock(SDL_HIDAPI_Device *device, const Uint8 *data, int size, SDL_HIDAPI_RumbleSentCallback callback, void *userdata) SDL_RELEASE(SDL_HIDAPI_rumble_lock); +void SDL_HIDAPI_UnlockRumble(void) SDL_RELEASE(SDL_HIDAPI_rumble_lock); + +// Simple API, will replace any pending rumble with the new data +int SDL_HIDAPI_SendRumble(SDL_HIDAPI_Device *device, const Uint8 *data, int size); +void SDL_HIDAPI_QuitRumble(void); + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_shield.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_shield.c new file mode 100644 index 00000000000..10dcea36d93 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_shield.c @@ -0,0 +1,578 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" + +#ifdef SDL_JOYSTICK_HIDAPI_SHIELD + +// Define this if you want to log all packets from the controller +// #define DEBUG_SHIELD_PROTOCOL + +#define CMD_BATTERY_STATE 0x07 +#define CMD_RUMBLE 0x39 +#define CMD_CHARGE_STATE 0x3A + +// Milliseconds between polls of battery state +#define BATTERY_POLL_INTERVAL_MS 60000 + +// Milliseconds between retransmission of rumble to keep motors running +#define RUMBLE_REFRESH_INTERVAL_MS 500 + +// Reports that are too small are dropped over Bluetooth +#define HID_REPORT_SIZE 33 + +enum +{ + SDL_GAMEPAD_BUTTON_SHIELD_SHARE = 11, + SDL_GAMEPAD_BUTTON_SHIELD_V103_TOUCHPAD, + SDL_GAMEPAD_BUTTON_SHIELD_V103_MINUS, + SDL_GAMEPAD_BUTTON_SHIELD_V103_PLUS, + SDL_GAMEPAD_NUM_SHIELD_V103_BUTTONS, + + SDL_GAMEPAD_NUM_SHIELD_V104_BUTTONS = SDL_GAMEPAD_BUTTON_SHIELD_SHARE + 1, +}; + +typedef enum +{ + k_ShieldReportIdControllerState = 0x01, + k_ShieldReportIdControllerTouch = 0x02, + k_ShieldReportIdCommandResponse = 0x03, + k_ShieldReportIdCommandRequest = 0x04, +} EShieldReportId; + +// This same report structure is used for both requests and responses +typedef struct +{ + Uint8 report_id; + Uint8 cmd; + Uint8 seq_num; + Uint8 payload[HID_REPORT_SIZE - 3]; +} ShieldCommandReport_t; +SDL_COMPILE_TIME_ASSERT(ShieldCommandReport_t, sizeof(ShieldCommandReport_t) == HID_REPORT_SIZE); + +typedef struct +{ + Uint8 seq_num; + + bool has_charging; + Uint8 charging; + bool has_battery_level; + Uint8 battery_level; + Uint64 last_battery_query_time; + + bool rumble_report_pending; + bool rumble_update_pending; + Uint8 left_motor_amplitude; + Uint8 right_motor_amplitude; + Uint64 last_rumble_time; + + Uint8 last_state[USB_PACKET_LENGTH]; +} SDL_DriverShield_Context; + +static void HIDAPI_DriverShield_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SHIELD, callback, userdata); +} + +static void HIDAPI_DriverShield_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SHIELD, callback, userdata); +} + +static bool HIDAPI_DriverShield_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_SHIELD, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)); +} + +static bool HIDAPI_DriverShield_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + return SDL_IsJoystickNVIDIASHIELDController(vendor_id, product_id); +} + +static bool HIDAPI_DriverShield_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverShield_Context *ctx; + + ctx = (SDL_DriverShield_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + device->context = ctx; + + HIDAPI_SetDeviceName(device, "NVIDIA SHIELD Controller"); + + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverShield_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverShield_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ +} + +static bool HIDAPI_DriverShield_SendCommand(SDL_HIDAPI_Device *device, Uint8 cmd, const void *data, int size) +{ + SDL_DriverShield_Context *ctx = (SDL_DriverShield_Context *)device->context; + ShieldCommandReport_t cmd_pkt; + + if (size > sizeof(cmd_pkt.payload)) { + return SDL_SetError("Command data exceeds HID report size"); + } + + if (!SDL_HIDAPI_LockRumble()) { + return false; + } + + cmd_pkt.report_id = k_ShieldReportIdCommandRequest; + cmd_pkt.cmd = cmd; + cmd_pkt.seq_num = ctx->seq_num++; + if (data) { + SDL_memcpy(cmd_pkt.payload, data, size); + } + + // Zero unused data in the payload + if (size != sizeof(cmd_pkt.payload)) { + SDL_memset(&cmd_pkt.payload[size], 0, sizeof(cmd_pkt.payload) - size); + } + + if (SDL_HIDAPI_SendRumbleAndUnlock(device, (Uint8 *)&cmd_pkt, sizeof(cmd_pkt)) != sizeof(cmd_pkt)) { + return SDL_SetError("Couldn't send command packet"); + } + + return true; +} + +static bool HIDAPI_DriverShield_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverShield_Context *ctx = (SDL_DriverShield_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + ctx->rumble_report_pending = false; + ctx->rumble_update_pending = false; + ctx->left_motor_amplitude = 0; + ctx->right_motor_amplitude = 0; + ctx->last_rumble_time = 0; + SDL_zeroa(ctx->last_state); + + // Initialize the joystick capabilities + if (device->product_id == USB_PRODUCT_NVIDIA_SHIELD_CONTROLLER_V103) { + joystick->nbuttons = SDL_GAMEPAD_NUM_SHIELD_V103_BUTTONS; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + + SDL_PrivateJoystickAddTouchpad(joystick, 1); + } else { + joystick->nbuttons = SDL_GAMEPAD_NUM_SHIELD_V104_BUTTONS; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + } + + // Request battery and charging info + ctx->last_battery_query_time = SDL_GetTicks(); + HIDAPI_DriverShield_SendCommand(device, CMD_CHARGE_STATE, NULL, 0); + HIDAPI_DriverShield_SendCommand(device, CMD_BATTERY_STATE, NULL, 0); + + return true; +} + +static bool HIDAPI_DriverShield_SendNextRumble(SDL_HIDAPI_Device *device) +{ + SDL_DriverShield_Context *ctx = (SDL_DriverShield_Context *)device->context; + Uint8 rumble_data[3]; + + if (!ctx->rumble_update_pending) { + return true; + } + + rumble_data[0] = 0x01; // enable + rumble_data[1] = ctx->left_motor_amplitude; + rumble_data[2] = ctx->right_motor_amplitude; + + ctx->rumble_update_pending = false; + ctx->last_rumble_time = SDL_GetTicks(); + + return HIDAPI_DriverShield_SendCommand(device, CMD_RUMBLE, rumble_data, sizeof(rumble_data)); +} + +static bool HIDAPI_DriverShield_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + if (device->product_id == USB_PRODUCT_NVIDIA_SHIELD_CONTROLLER_V103) { + Uint8 rumble_packet[] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + rumble_packet[2] = (low_frequency_rumble >> 8); + rumble_packet[4] = (high_frequency_rumble >> 8); + + if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { + return SDL_SetError("Couldn't send rumble packet"); + } + return true; + + } else { + SDL_DriverShield_Context *ctx = (SDL_DriverShield_Context *)device->context; + + // The rumble motors are quite intense, so tone down the intensity like the official driver does + ctx->left_motor_amplitude = low_frequency_rumble >> 11; + ctx->right_motor_amplitude = high_frequency_rumble >> 11; + ctx->rumble_update_pending = true; + + if (ctx->rumble_report_pending) { + // We will service this after the hardware acknowledges the previous request + return true; + } + + return HIDAPI_DriverShield_SendNextRumble(device); + } +} + +static bool HIDAPI_DriverShield_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverShield_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + return SDL_JOYSTICK_CAP_RUMBLE; +} + +static bool HIDAPI_DriverShield_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverShield_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + const Uint8 *data_bytes = (const Uint8 *)data; + + if (size > 1) { + // Single command byte followed by a variable length payload + return HIDAPI_DriverShield_SendCommand(device, data_bytes[0], &data_bytes[1], size - 1); + } else if (size == 1) { + // Single command byte with no payload + return HIDAPI_DriverShield_SendCommand(device, data_bytes[0], NULL, 0); + } else { + return SDL_SetError("Effect data must at least contain a command byte"); + } +} + +static bool HIDAPI_DriverShield_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static void HIDAPI_DriverShield_HandleStatePacketV103(SDL_Joystick *joystick, SDL_DriverShield_Context *ctx, Uint8 *data, int size) +{ + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->last_state[3] != data[3]) { + Uint8 hat; + + switch (data[3]) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + if (ctx->last_state[1] != data[1]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[1] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[1] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[1] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[1] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[1] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[1] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[1] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[1] & 0x80) != 0)); + } + + if (ctx->last_state[2] != data[2]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[2] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SHIELD_V103_PLUS, ((data[2] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SHIELD_V103_MINUS, ((data[2] & 0x10) != 0)); + //SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[2] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[2] & 0x40) != 0)); + //SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SHIELD_SHARE, ((data[2] & 0x80) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[2] & 0x80) != 0)); + } + + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_Swap16LE(*(Sint16 *)&data[4]) - 0x8000); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_Swap16LE(*(Sint16 *)&data[6]) - 0x8000); + + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_Swap16LE(*(Sint16 *)&data[8]) - 0x8000); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_Swap16LE(*(Sint16 *)&data[10]) - 0x8000); + + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, SDL_Swap16LE(*(Sint16 *)&data[12]) - 0x8000); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, SDL_Swap16LE(*(Sint16 *)&data[14]) - 0x8000); + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +#undef clamp +#define clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val))) + +static void HIDAPI_DriverShield_HandleTouchPacketV103(SDL_Joystick *joystick, SDL_DriverShield_Context *ctx, const Uint8 *data, int size) +{ + bool touchpad_down; + float touchpad_x, touchpad_y; + Uint64 timestamp = SDL_GetTicksNS(); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SHIELD_V103_TOUCHPAD, ((data[1] & 0x01) != 0)); + + // It's a triangular pad, but just use the center as the usable touch area + touchpad_down = ((data[1] & 0x80) == 0); + touchpad_x = clamp((float)(data[2] - 0x70) / 0x50, 0.0f, 1.0f); + touchpad_y = clamp((float)(data[4] - 0x40) / 0x15, 0.0f, 1.0f); + SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, touchpad_down, touchpad_x, touchpad_y, touchpad_down ? 1.0f : 0.0f); +} + +static void HIDAPI_DriverShield_HandleStatePacketV104(SDL_Joystick *joystick, SDL_DriverShield_Context *ctx, Uint8 *data, int size) +{ + Uint64 timestamp = SDL_GetTicksNS(); + + if (size < 23) { + return; + } + + if (ctx->last_state[2] != data[2]) { + Uint8 hat; + + switch (data[2]) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + if (ctx->last_state[3] != data[3]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[3] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[3] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[3] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[3] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[3] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[3] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[3] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[3] & 0x80) != 0)); + } + + if (ctx->last_state[4] != data[4]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[4] & 0x01) != 0)); + } + + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_Swap16LE(*(Sint16 *)&data[9]) - 0x8000); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_Swap16LE(*(Sint16 *)&data[11]) - 0x8000); + + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_Swap16LE(*(Sint16 *)&data[13]) - 0x8000); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_Swap16LE(*(Sint16 *)&data[15]) - 0x8000); + + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, SDL_Swap16LE(*(Sint16 *)&data[19]) - 0x8000); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, SDL_Swap16LE(*(Sint16 *)&data[21]) - 0x8000); + + if (ctx->last_state[17] != data[17]) { + //SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SHIELD_SHARE, ((data[17] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[17] & 0x02) != 0)); + //SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[17] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[17] & 0x01) != 0)); + } + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static void HIDAPI_DriverShield_UpdatePowerInfo(SDL_Joystick *joystick, SDL_DriverShield_Context *ctx) +{ + if (!ctx->has_charging || !ctx->has_battery_level) { + return; + } + + SDL_PowerState state = ctx->charging ? SDL_POWERSTATE_CHARGING : SDL_POWERSTATE_ON_BATTERY; + int percent = ctx->battery_level * 20; + SDL_SendJoystickPowerInfo(joystick, state, percent); +} + +static bool HIDAPI_DriverShield_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverShield_Context *ctx = (SDL_DriverShield_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH]; + int size = 0; + ShieldCommandReport_t *cmd_resp_report; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } else { + return false; + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { +#ifdef DEBUG_SHIELD_PROTOCOL + HIDAPI_DumpPacket("NVIDIA SHIELD packet: size = %d", data, size); +#endif + + // Byte 0 is HID report ID + switch (data[0]) { + case k_ShieldReportIdControllerState: + if (!joystick) { + break; + } + if (size == 16) { + HIDAPI_DriverShield_HandleStatePacketV103(joystick, ctx, data, size); + } else { + HIDAPI_DriverShield_HandleStatePacketV104(joystick, ctx, data, size); + } + break; + case k_ShieldReportIdControllerTouch: + if (!joystick) { + break; + } + HIDAPI_DriverShield_HandleTouchPacketV103(joystick, ctx, data, size); + break; + case k_ShieldReportIdCommandResponse: + cmd_resp_report = (ShieldCommandReport_t *)data; + switch (cmd_resp_report->cmd) { + case CMD_RUMBLE: + ctx->rumble_report_pending = false; + HIDAPI_DriverShield_SendNextRumble(device); + break; + case CMD_CHARGE_STATE: + ctx->has_charging = true; + ctx->charging = cmd_resp_report->payload[0]; + HIDAPI_DriverShield_UpdatePowerInfo(joystick, ctx); + break; + case CMD_BATTERY_STATE: + ctx->has_battery_level = true; + ctx->battery_level = cmd_resp_report->payload[2]; + HIDAPI_DriverShield_UpdatePowerInfo(joystick, ctx); + break; + } + break; + } + } + + // Ask for battery state again if we're due for an update + if (joystick && SDL_GetTicks() >= (ctx->last_battery_query_time + BATTERY_POLL_INTERVAL_MS)) { + ctx->last_battery_query_time = SDL_GetTicks(); + HIDAPI_DriverShield_SendCommand(device, CMD_BATTERY_STATE, NULL, 0); + } + + // Retransmit rumble packets if they've lasted longer than the hardware supports + if ((ctx->left_motor_amplitude != 0 || ctx->right_motor_amplitude != 0) && + SDL_GetTicks() >= (ctx->last_rumble_time + RUMBLE_REFRESH_INTERVAL_MS)) { + ctx->rumble_update_pending = true; + HIDAPI_DriverShield_SendNextRumble(device); + } + + if (size < 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverShield_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ +} + +static void HIDAPI_DriverShield_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverShield = { + SDL_HINT_JOYSTICK_HIDAPI_SHIELD, + true, + HIDAPI_DriverShield_RegisterHints, + HIDAPI_DriverShield_UnregisterHints, + HIDAPI_DriverShield_IsEnabled, + HIDAPI_DriverShield_IsSupportedDevice, + HIDAPI_DriverShield_InitDevice, + HIDAPI_DriverShield_GetDevicePlayerIndex, + HIDAPI_DriverShield_SetDevicePlayerIndex, + HIDAPI_DriverShield_UpdateDevice, + HIDAPI_DriverShield_OpenJoystick, + HIDAPI_DriverShield_RumbleJoystick, + HIDAPI_DriverShield_RumbleJoystickTriggers, + HIDAPI_DriverShield_GetJoystickCapabilities, + HIDAPI_DriverShield_SetJoystickLED, + HIDAPI_DriverShield_SendJoystickEffect, + HIDAPI_DriverShield_SetJoystickSensorsEnabled, + HIDAPI_DriverShield_CloseJoystick, + HIDAPI_DriverShield_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_SHIELD + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_stadia.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_stadia.c new file mode 100644 index 00000000000..487bf41b2e8 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_stadia.c @@ -0,0 +1,324 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" + +#ifdef SDL_JOYSTICK_HIDAPI_STADIA + +// Define this if you want to log all packets from the controller +// #define DEBUG_STADIA_PROTOCOL + +enum +{ + SDL_GAMEPAD_BUTTON_STADIA_CAPTURE = 11, + SDL_GAMEPAD_BUTTON_STADIA_GOOGLE_ASSISTANT, + SDL_GAMEPAD_NUM_STADIA_BUTTONS, +}; + +typedef struct +{ + bool rumble_supported; + Uint8 last_state[USB_PACKET_LENGTH]; +} SDL_DriverStadia_Context; + +static void HIDAPI_DriverStadia_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STADIA, callback, userdata); +} + +static void HIDAPI_DriverStadia_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STADIA, callback, userdata); +} + +static bool HIDAPI_DriverStadia_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_STADIA, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)); +} + +static bool HIDAPI_DriverStadia_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + return SDL_IsJoystickGoogleStadiaController(vendor_id, product_id); +} + +static bool HIDAPI_DriverStadia_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverStadia_Context *ctx; + + ctx = (SDL_DriverStadia_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + device->context = ctx; + + // Check whether rumble is supported + { + Uint8 rumble_packet[] = { 0x05, 0x00, 0x00, 0x00, 0x00 }; + + if (SDL_hid_write(device->dev, rumble_packet, sizeof(rumble_packet)) >= 0) { + ctx->rumble_supported = true; + } + } + + HIDAPI_SetDeviceName(device, "Google Stadia Controller"); + + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverStadia_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverStadia_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ +} + +static bool HIDAPI_DriverStadia_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverStadia_Context *ctx = (SDL_DriverStadia_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + SDL_zeroa(ctx->last_state); + + // Initialize the joystick capabilities + joystick->nbuttons = SDL_GAMEPAD_NUM_STADIA_BUTTONS; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + + return true; +} + +static bool HIDAPI_DriverStadia_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + SDL_DriverStadia_Context *ctx = (SDL_DriverStadia_Context *)device->context; + + if (ctx->rumble_supported) { + Uint8 rumble_packet[] = { 0x05, 0x00, 0x00, 0x00, 0x00 }; + + + rumble_packet[1] = (low_frequency_rumble & 0xFF); + rumble_packet[2] = (low_frequency_rumble >> 8); + rumble_packet[3] = (high_frequency_rumble & 0xFF); + rumble_packet[4] = (high_frequency_rumble >> 8); + + if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { + return SDL_SetError("Couldn't send rumble packet"); + } + return true; + } else { + return SDL_Unsupported(); + } +} + +static bool HIDAPI_DriverStadia_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverStadia_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverStadia_Context *ctx = (SDL_DriverStadia_Context *)device->context; + Uint32 caps = 0; + + if (ctx->rumble_supported) { + caps |= SDL_JOYSTICK_CAP_RUMBLE; + } + return caps; +} + +static bool HIDAPI_DriverStadia_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverStadia_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverStadia_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static void HIDAPI_DriverStadia_HandleStatePacket(SDL_Joystick *joystick, SDL_DriverStadia_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; + Uint64 timestamp = SDL_GetTicksNS(); + + // The format is the same but the original FW will send 10 bytes and January '21 FW update will send 11 + if (size < 10 || data[0] != 0x03) { + // We don't know how to handle this report + return; + } + + if (ctx->last_state[1] != data[1]) { + Uint8 hat; + + switch (data[1]) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + if (ctx->last_state[2] != data[2]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[2] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[2] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[2] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[2] & 0x80) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_STADIA_CAPTURE, ((data[2] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_STADIA_GOOGLE_ASSISTANT, ((data[2] & 0x02) != 0)); + } + + if (ctx->last_state[3] != data[3]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[3] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[3] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[3] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[3] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[3] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[3] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[3] & 0x01) != 0)); + } + +#define READ_STICK_AXIS(offset) \ + (data[offset] == 0x80 ? 0 : (Sint16)HIDAPI_RemapVal((float)((int)data[offset] - 0x80), 0x01 - 0x80, 0xff - 0x80, SDL_MIN_SINT16, SDL_MAX_SINT16)) + { + axis = READ_STICK_AXIS(4); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = READ_STICK_AXIS(5); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = READ_STICK_AXIS(6); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = READ_STICK_AXIS(7); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + } +#undef READ_STICK_AXIS + +#define READ_TRIGGER_AXIS(offset) \ + (Sint16)(((int)data[offset] * 257) - 32768) + { + axis = READ_TRIGGER_AXIS(8); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + axis = READ_TRIGGER_AXIS(9); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + } +#undef READ_TRIGGER_AXIS + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static bool HIDAPI_DriverStadia_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverStadia_Context *ctx = (SDL_DriverStadia_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH]; + int size = 0; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } else { + return false; + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { +#ifdef DEBUG_STADIA_PROTOCOL + HIDAPI_DumpPacket("Google Stadia packet: size = %d", data, size); +#endif + if (!joystick) { + continue; + } + + HIDAPI_DriverStadia_HandleStatePacket(joystick, ctx, data, size); + } + + if (size < 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverStadia_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ +} + +static void HIDAPI_DriverStadia_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverStadia = { + SDL_HINT_JOYSTICK_HIDAPI_STADIA, + true, + HIDAPI_DriverStadia_RegisterHints, + HIDAPI_DriverStadia_UnregisterHints, + HIDAPI_DriverStadia_IsEnabled, + HIDAPI_DriverStadia_IsSupportedDevice, + HIDAPI_DriverStadia_InitDevice, + HIDAPI_DriverStadia_GetDevicePlayerIndex, + HIDAPI_DriverStadia_SetDevicePlayerIndex, + HIDAPI_DriverStadia_UpdateDevice, + HIDAPI_DriverStadia_OpenJoystick, + HIDAPI_DriverStadia_RumbleJoystick, + HIDAPI_DriverStadia_RumbleJoystickTriggers, + HIDAPI_DriverStadia_GetJoystickCapabilities, + HIDAPI_DriverStadia_SetJoystickLED, + HIDAPI_DriverStadia_SendJoystickEffect, + HIDAPI_DriverStadia_SetJoystickSensorsEnabled, + HIDAPI_DriverStadia_CloseJoystick, + HIDAPI_DriverStadia_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_STADIA + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_steam.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_steam.c new file mode 100644 index 00000000000..b48d35393b1 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_steam.c @@ -0,0 +1,1534 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../../SDL_hints_c.h" +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" + +#ifdef SDL_JOYSTICK_HIDAPI_STEAM + +// Define this if you want to log all packets from the controller +// #define DEBUG_STEAM_PROTOCOL + +#define SDL_HINT_JOYSTICK_HIDAPI_STEAM_PAIRING_ENABLED "SDL_JOYSTICK_HIDAPI_STEAM_PAIRING_ENABLED" + +#if defined(SDL_PLATFORM_ANDROID) || defined(SDL_PLATFORM_IOS) || defined(SDL_PLATFORM_TVOS) +// This requires prompting for Bluetooth permissions, so make sure the application really wants it +#define SDL_HINT_JOYSTICK_HIDAPI_STEAM_DEFAULT false +#else +#define SDL_HINT_JOYSTICK_HIDAPI_STEAM_DEFAULT SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT) +#endif + +#define PAIRING_STATE_DURATION_SECONDS 60 + + +/*****************************************************************************************************/ + +#include "steam/controller_constants.h" +#include "steam/controller_structs.h" + +enum +{ + SDL_GAMEPAD_BUTTON_STEAM_RIGHT_PADDLE = 11, + SDL_GAMEPAD_BUTTON_STEAM_LEFT_PADDLE, + SDL_GAMEPAD_NUM_STEAM_BUTTONS, +}; + +typedef struct SteamControllerStateInternal_t +{ + // Controller Type for this Controller State + Uint32 eControllerType; + + // If packet num matches that on your prior call, then the controller state hasn't been changed since + // your last call and there is no need to process it + Uint32 unPacketNum; + + // bit flags for each of the buttons + Uint64 ulButtons; + + // Left pad coordinates + short sLeftPadX; + short sLeftPadY; + + // Right pad coordinates + short sRightPadX; + short sRightPadY; + + // Center pad coordinates + short sCenterPadX; + short sCenterPadY; + + // Left analog stick coordinates + short sLeftStickX; + short sLeftStickY; + + // Right analog stick coordinates + short sRightStickX; + short sRightStickY; + + unsigned short sTriggerL; + unsigned short sTriggerR; + + short sAccelX; + short sAccelY; + short sAccelZ; + + short sGyroX; + short sGyroY; + short sGyroZ; + + float sGyroQuatW; + float sGyroQuatX; + float sGyroQuatY; + float sGyroQuatZ; + + short sGyroSteeringAngle; + + unsigned short sBatteryLevel; + + // Pressure sensor data. + unsigned short sPressurePadLeft; + unsigned short sPressurePadRight; + + unsigned short sPressureBumperLeft; + unsigned short sPressureBumperRight; + + // Internal state data + short sPrevLeftPad[2]; + short sPrevLeftStick[2]; +} SteamControllerStateInternal_t; + +// Defines for ulButtons in SteamControllerStateInternal_t +#define STEAM_RIGHT_TRIGGER_MASK 0x00000001 +#define STEAM_LEFT_TRIGGER_MASK 0x00000002 +#define STEAM_RIGHT_BUMPER_MASK 0x00000004 +#define STEAM_LEFT_BUMPER_MASK 0x00000008 +#define STEAM_BUTTON_NORTH_MASK 0x00000010 // Y +#define STEAM_BUTTON_EAST_MASK 0x00000020 // B +#define STEAM_BUTTON_WEST_MASK 0x00000040 // X +#define STEAM_BUTTON_SOUTH_MASK 0x00000080 // A +#define STEAM_DPAD_UP_MASK 0x00000100 // DPAD UP +#define STEAM_DPAD_RIGHT_MASK 0x00000200 // DPAD RIGHT +#define STEAM_DPAD_LEFT_MASK 0x00000400 // DPAD LEFT +#define STEAM_DPAD_DOWN_MASK 0x00000800 // DPAD DOWN +#define STEAM_BUTTON_MENU_MASK 0x00001000 // SELECT +#define STEAM_BUTTON_STEAM_MASK 0x00002000 // GUIDE +#define STEAM_BUTTON_ESCAPE_MASK 0x00004000 // START +#define STEAM_BUTTON_BACK_LEFT_MASK 0x00008000 +#define STEAM_BUTTON_BACK_RIGHT_MASK 0x00010000 +#define STEAM_BUTTON_LEFTPAD_CLICKED_MASK 0x00020000 +#define STEAM_BUTTON_RIGHTPAD_CLICKED_MASK 0x00040000 +#define STEAM_LEFTPAD_FINGERDOWN_MASK 0x00080000 +#define STEAM_RIGHTPAD_FINGERDOWN_MASK 0x00100000 +#define STEAM_JOYSTICK_BUTTON_MASK 0x00400000 +#define STEAM_LEFTPAD_AND_JOYSTICK_MASK 0x00800000 + +// Look for report version 0x0001, type WIRELESS (3), length >= 1 byte +#define D0G_IS_VALID_WIRELESS_EVENT(data, len) ((len) >= 5 && (data)[0] == 1 && (data)[1] == 0 && (data)[2] == 3 && (data)[3] >= 1) +#define D0G_GET_WIRELESS_EVENT_TYPE(data) ((data)[4]) +#define D0G_WIRELESS_DISCONNECTED 1 +#define D0G_WIRELESS_ESTABLISHED 2 +#define D0G_WIRELESS_NEWLYPAIRED 3 + +#define D0G_IS_WIRELESS_DISCONNECT(data, len) (D0G_IS_VALID_WIRELESS_EVENT(data, len) && D0G_GET_WIRELESS_EVENT_TYPE(data) == D0G_WIRELESS_DISCONNECTED) +#define D0G_IS_WIRELESS_CONNECT(data, len) (D0G_IS_VALID_WIRELESS_EVENT(data, len) && D0G_GET_WIRELESS_EVENT_TYPE(data) != D0G_WIRELESS_DISCONNECTED) + + +#define MAX_REPORT_SEGMENT_PAYLOAD_SIZE 18 +/* + * SteamControllerPacketAssembler has to be used when reading output repots from controllers. + */ +typedef struct +{ + uint8_t uBuffer[MAX_REPORT_SEGMENT_PAYLOAD_SIZE * 8 + 1]; + int nExpectedSegmentNumber; + bool bIsBle; +} SteamControllerPacketAssembler; + +#undef clamp +#define clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val))) + +#undef offsetof +#define offsetof(s, m) (size_t) & (((s *)0)->m) + +#ifdef DEBUG_STEAM_CONTROLLER +#define DPRINTF(format, ...) printf(format, ##__VA_ARGS__) +#define HEXDUMP(ptr, len) hexdump(ptr, len) +#else +#define DPRINTF(format, ...) +#define HEXDUMP(ptr, len) +#endif +#define printf SDL_Log + +#define MAX_REPORT_SEGMENT_SIZE (MAX_REPORT_SEGMENT_PAYLOAD_SIZE + 2) +#define CALC_REPORT_SEGMENT_NUM(index) ((index / MAX_REPORT_SEGMENT_PAYLOAD_SIZE) & 0x07) +#define REPORT_SEGMENT_DATA_FLAG 0x80 +#define REPORT_SEGMENT_LAST_FLAG 0x40 +#define BLE_REPORT_NUMBER 0x03 + +#define STEAMCONTROLLER_TRIGGER_MAX_ANALOG 26000 + +// Enable mouse mode when using the Steam Controller locally +#undef ENABLE_MOUSE_MODE + +// Wireless firmware quirk: the firmware intentionally signals "failure" when performing +// SET_FEATURE / GET_FEATURE when it actually means "pending radio roundtrip". The only +// way to make SET_FEATURE / GET_FEATURE work is to loop several times with a sleep. If +// it takes more than 50ms to get the response for SET_FEATURE / GET_FEATURE, we assume +// that the controller has failed. +#define RADIO_WORKAROUND_SLEEP_ATTEMPTS 50 +#define RADIO_WORKAROUND_SLEEP_DURATION_US 500 + +// This was defined by experimentation. 2000 seemed to work but to give that extra bit of margin, set to 3ms. +#define CONTROLLER_CONFIGURATION_DELAY_US 3000 + +static uint8_t GetSegmentHeader(int nSegmentNumber, bool bLastPacket) +{ + uint8_t header = REPORT_SEGMENT_DATA_FLAG; + header |= nSegmentNumber; + if (bLastPacket) { + header |= REPORT_SEGMENT_LAST_FLAG; + } + + return header; +} + +static void hexdump(const uint8_t *ptr, int len) +{ + HIDAPI_DumpPacket("Data", ptr, len); +} + +static void ResetSteamControllerPacketAssembler(SteamControllerPacketAssembler *pAssembler) +{ + SDL_memset(pAssembler->uBuffer, 0, sizeof(pAssembler->uBuffer)); + pAssembler->nExpectedSegmentNumber = 0; +} + +static void InitializeSteamControllerPacketAssembler(SteamControllerPacketAssembler *pAssembler, bool bIsBle) +{ + pAssembler->bIsBle = bIsBle; + ResetSteamControllerPacketAssembler(pAssembler); +} + +// Returns: +// <0 on error +// 0 on not ready +// Complete packet size on completion +static int WriteSegmentToSteamControllerPacketAssembler(SteamControllerPacketAssembler *pAssembler, const uint8_t *pSegment, int nSegmentLength) +{ + if (pAssembler->bIsBle) { + uint8_t uSegmentHeader = pSegment[1]; + int nSegmentNumber = uSegmentHeader & 0x07; + + HEXDUMP(pSegment, nSegmentLength); + + if (pSegment[0] != BLE_REPORT_NUMBER) { + // We may get keyboard/mouse input events until controller stops sending them + return 0; + } + + if (nSegmentLength != MAX_REPORT_SEGMENT_SIZE) { + printf("Bad segment size! %d\n", nSegmentLength); + hexdump(pSegment, nSegmentLength); + ResetSteamControllerPacketAssembler(pAssembler); + return -1; + } + + DPRINTF("GOT PACKET HEADER = 0x%x\n", uSegmentHeader); + + if (!(uSegmentHeader & REPORT_SEGMENT_DATA_FLAG)) { + // We get empty segments, just ignore them + return 0; + } + + if (nSegmentNumber != pAssembler->nExpectedSegmentNumber) { + ResetSteamControllerPacketAssembler(pAssembler); + + if (nSegmentNumber) { + // This happens occasionally + DPRINTF("Bad segment number, got %d, expected %d\n", + nSegmentNumber, pAssembler->nExpectedSegmentNumber); + return -1; + } + } + + SDL_memcpy(pAssembler->uBuffer + nSegmentNumber * MAX_REPORT_SEGMENT_PAYLOAD_SIZE, + pSegment + 2, // ignore header and report number + MAX_REPORT_SEGMENT_PAYLOAD_SIZE); + + if (uSegmentHeader & REPORT_SEGMENT_LAST_FLAG) { + pAssembler->nExpectedSegmentNumber = 0; + return (nSegmentNumber + 1) * MAX_REPORT_SEGMENT_PAYLOAD_SIZE; + } + + pAssembler->nExpectedSegmentNumber++; + } else { + // Just pass through + SDL_memcpy(pAssembler->uBuffer, + pSegment, + nSegmentLength); + return nSegmentLength; + } + + return 0; +} + +#define BLE_MAX_READ_RETRIES 8 + +static int SetFeatureReport(SDL_HIDAPI_Device *dev, const unsigned char uBuffer[65], int nActualDataLen) +{ + int nRet = -1; + + DPRINTF("SetFeatureReport %p %p %d\n", dev, uBuffer, nActualDataLen); + + if (dev->is_bluetooth) { + int nSegmentNumber = 0; + uint8_t uPacketBuffer[MAX_REPORT_SEGMENT_SIZE]; + const unsigned char *pBufferPtr = uBuffer + 1; + + if (nActualDataLen < 1) { + return -1; + } + + // Skip report number in data + nActualDataLen--; + + while (nActualDataLen > 0) { + int nBytesInPacket = nActualDataLen > MAX_REPORT_SEGMENT_PAYLOAD_SIZE ? MAX_REPORT_SEGMENT_PAYLOAD_SIZE : nActualDataLen; + + nActualDataLen -= nBytesInPacket; + + // Construct packet + SDL_memset(uPacketBuffer, 0, sizeof(uPacketBuffer)); + uPacketBuffer[0] = BLE_REPORT_NUMBER; + uPacketBuffer[1] = GetSegmentHeader(nSegmentNumber, nActualDataLen == 0); + SDL_memcpy(&uPacketBuffer[2], pBufferPtr, nBytesInPacket); + + pBufferPtr += nBytesInPacket; + nSegmentNumber++; + + nRet = SDL_hid_send_feature_report(dev->dev, uPacketBuffer, sizeof(uPacketBuffer)); + } + } else { + for (int nRetries = 0; nRetries < RADIO_WORKAROUND_SLEEP_ATTEMPTS; nRetries++) { + nRet = SDL_hid_send_feature_report(dev->dev, uBuffer, 65); + if (nRet >= 0) { + break; + } + + SDL_DelayNS(RADIO_WORKAROUND_SLEEP_DURATION_US * 1000); + } + } + + DPRINTF("SetFeatureReport() ret = %d\n", nRet); + + return nRet; +} + +static int GetFeatureReport(SDL_HIDAPI_Device *dev, unsigned char uBuffer[65]) +{ + int nRet = -1; + + DPRINTF("GetFeatureReport( %p %p )\n", dev, uBuffer); + + if (dev->is_bluetooth) { + int nRetries = 0; + uint8_t uSegmentBuffer[MAX_REPORT_SEGMENT_SIZE + 1]; + uint8_t ucBytesToRead = MAX_REPORT_SEGMENT_SIZE; + uint8_t ucDataStartOffset = 0; + + SteamControllerPacketAssembler assembler; + InitializeSteamControllerPacketAssembler(&assembler, dev->is_bluetooth); + + // On Windows and macOS, BLE devices get 2 copies of the feature report ID, one that is removed by ReadFeatureReport, + // and one that's included in the buffer we receive. We pad the bytes to read and skip over the report ID + // if necessary. +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_MACOS) + ++ucBytesToRead; + ++ucDataStartOffset; +#endif + + while (nRetries < BLE_MAX_READ_RETRIES) { + SDL_memset(uSegmentBuffer, 0, sizeof(uSegmentBuffer)); + uSegmentBuffer[0] = BLE_REPORT_NUMBER; + nRet = SDL_hid_get_feature_report(dev->dev, uSegmentBuffer, ucBytesToRead); + + DPRINTF("GetFeatureReport ble ret=%d\n", nRet); + HEXDUMP(uSegmentBuffer, nRet); + + // Zero retry counter if we got data + if (nRet > 2 && (uSegmentBuffer[ucDataStartOffset + 1] & REPORT_SEGMENT_DATA_FLAG)) { + nRetries = 0; + } else { + nRetries++; + } + + if (nRet > 0) { + int nPacketLength = WriteSegmentToSteamControllerPacketAssembler(&assembler, + uSegmentBuffer + ucDataStartOffset, + nRet - ucDataStartOffset); + + if (nPacketLength > 0 && nPacketLength < 65) { + // Leave space for "report number" + uBuffer[0] = 0; + SDL_memcpy(uBuffer + 1, assembler.uBuffer, nPacketLength); + return nPacketLength; + } + } + } + printf("Could not get a full ble packet after %d retries\n", nRetries); + return -1; + } else { + SDL_memset(uBuffer, 0, 65); + + for (int nRetries = 0; nRetries < RADIO_WORKAROUND_SLEEP_ATTEMPTS; nRetries++) { + nRet = SDL_hid_get_feature_report(dev->dev, uBuffer, 65); + if (nRet >= 0) { + break; + } + + SDL_DelayNS(RADIO_WORKAROUND_SLEEP_DURATION_US * 1000); + } + + DPRINTF("GetFeatureReport USB ret=%d\n", nRet); + HEXDUMP(uBuffer, nRet); + } + + return nRet; +} + +static int ReadResponse(SDL_HIDAPI_Device *dev, uint8_t uBuffer[65], int nExpectedResponse) +{ + for (int nRetries = 0; nRetries < 10; nRetries++) { + int nRet = GetFeatureReport(dev, uBuffer); + + DPRINTF("ReadResponse( %p %p 0x%x )\n", dev, uBuffer, nExpectedResponse); + + if (nRet < 0) { + continue; + } + + DPRINTF("ReadResponse got %d bytes of data: ", nRet); + HEXDUMP(uBuffer, nRet); + + if (uBuffer[1] != nExpectedResponse) { + continue; + } + + return nRet; + } + return -1; +} + +//--------------------------------------------------------------------------- +// Reset steam controller (unmap buttons and pads) and re-fetch capability bits +//--------------------------------------------------------------------------- +static bool ResetSteamController(SDL_HIDAPI_Device *dev, bool bSuppressErrorSpew, uint32_t *punUpdateRateUS) +{ + // Firmware quirk: Set Feature and Get Feature requests always require a 65-byte buffer. + unsigned char buf[65]; + unsigned int i; + int res = -1; + int nSettings = 0; + int nAttributesLength; + FeatureReportMsg *msg; + uint32_t unUpdateRateUS = 9000; // Good default rate + + DPRINTF("ResetSteamController hid=%p\n", dev); + + buf[0] = 0; + buf[1] = ID_GET_ATTRIBUTES_VALUES; + res = SetFeatureReport(dev, buf, 2); + if (res < 0) { + if (!bSuppressErrorSpew) { + printf("GET_ATTRIBUTES_VALUES failed for controller %p\n", dev); + } + return false; + } + + // Retrieve GET_ATTRIBUTES_VALUES result + // Wireless controller endpoints without a connected controller will return nAttrs == 0 + res = ReadResponse(dev, buf, ID_GET_ATTRIBUTES_VALUES); + if (res < 0 || buf[1] != ID_GET_ATTRIBUTES_VALUES) { + HEXDUMP(buf, res); + if (!bSuppressErrorSpew) { + printf("Bad GET_ATTRIBUTES_VALUES response for controller %p\n", dev); + } + return false; + } + + nAttributesLength = buf[2]; + if (nAttributesLength > res) { + if (!bSuppressErrorSpew) { + printf("Bad GET_ATTRIBUTES_VALUES response for controller %p\n", dev); + } + return false; + } + + msg = (FeatureReportMsg *)&buf[1]; + for (i = 0; i < (int)msg->header.length / sizeof(ControllerAttribute); ++i) { + uint8_t unAttribute = msg->payload.getAttributes.attributes[i].attributeTag; + uint32_t unValue = msg->payload.getAttributes.attributes[i].attributeValue; + + switch (unAttribute) { + case ATTRIB_UNIQUE_ID: + break; + case ATTRIB_PRODUCT_ID: + break; + case ATTRIB_CAPABILITIES: + break; + case ATTRIB_CONNECTION_INTERVAL_IN_US: + unUpdateRateUS = unValue; + break; + default: + break; + } + } + if (punUpdateRateUS) { + *punUpdateRateUS = unUpdateRateUS; + } + + // Clear digital button mappings + buf[0] = 0; + buf[1] = ID_CLEAR_DIGITAL_MAPPINGS; + res = SetFeatureReport(dev, buf, 2); + if (res < 0) { + if (!bSuppressErrorSpew) { + printf("CLEAR_DIGITAL_MAPPINGS failed for controller %p\n", dev); + } + return false; + } + + // Reset the default settings + SDL_memset(buf, 0, 65); + buf[1] = ID_LOAD_DEFAULT_SETTINGS; + buf[2] = 0; + res = SetFeatureReport(dev, buf, 3); + if (res < 0) { + if (!bSuppressErrorSpew) { + printf("LOAD_DEFAULT_SETTINGS failed for controller %p\n", dev); + } + return false; + } + + // Apply custom settings - clear trackpad modes (cancel mouse emulation), etc +#define ADD_SETTING(SETTING, VALUE) \ + buf[3 + nSettings * 3] = SETTING; \ + buf[3 + nSettings * 3 + 1] = ((uint16_t)VALUE) & 0xFF; \ + buf[3 + nSettings * 3 + 2] = ((uint16_t)VALUE) >> 8; \ + ++nSettings; + + SDL_memset(buf, 0, 65); + buf[1] = ID_SET_SETTINGS_VALUES; + ADD_SETTING(SETTING_WIRELESS_PACKET_VERSION, 2); + ADD_SETTING(SETTING_LEFT_TRACKPAD_MODE, TRACKPAD_NONE); +#ifdef ENABLE_MOUSE_MODE + ADD_SETTING(SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_ABSOLUTE_MOUSE); + ADD_SETTING(SETTING_SMOOTH_ABSOLUTE_MOUSE, 1); + ADD_SETTING(SETTING_MOMENTUM_MAXIMUM_VELOCITY, 20000); // [0-20000] default 8000 + ADD_SETTING(SETTING_MOMENTUM_DECAY_AMOUNT, 50); // [0-50] default 5 +#else + ADD_SETTING(SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_NONE); + ADD_SETTING(SETTING_SMOOTH_ABSOLUTE_MOUSE, 0); +#endif + buf[2] = (unsigned char)(nSettings * 3); + + res = SetFeatureReport(dev, buf, 3 + nSettings * 3); + if (res < 0) { + if (!bSuppressErrorSpew) { + printf("SET_SETTINGS failed for controller %p\n", dev); + } + return false; + } + +#ifdef ENABLE_MOUSE_MODE + // Wait for ID_CLEAR_DIGITAL_MAPPINGS to be processed on the controller + bool bMappingsCleared = false; + int iRetry; + for (iRetry = 0; iRetry < 2; ++iRetry) { + SDL_memset(buf, 0, 65); + buf[1] = ID_GET_DIGITAL_MAPPINGS; + buf[2] = 1; // one byte - requesting from index 0 + buf[3] = 0; + res = SetFeatureReport(dev, buf, 4); + if (res < 0) { + printf("GET_DIGITAL_MAPPINGS failed for controller %p\n", dev); + return false; + } + + res = ReadResponse(dev, buf, ID_GET_DIGITAL_MAPPINGS); + if (res < 0 || buf[1] != ID_GET_DIGITAL_MAPPINGS) { + printf("Bad GET_DIGITAL_MAPPINGS response for controller %p\n", dev); + return false; + } + + // If the length of the digital mappings result is not 1 (index byte, no mappings) then clearing hasn't executed + if (buf[2] == 1 && buf[3] == 0xFF) { + bMappingsCleared = true; + break; + } + usleep(CONTROLLER_CONFIGURATION_DELAY_US); + } + + if (!bMappingsCleared && !bSuppressErrorSpew) { + printf("Warning: CLEAR_DIGITAL_MAPPINGS never completed for controller %p\n", dev); + } + + // Set our new mappings + SDL_memset(buf, 0, 65); + buf[1] = ID_SET_DIGITAL_MAPPINGS; + buf[2] = 6; // 2 settings x 3 bytes + buf[3] = IO_DIGITAL_BUTTON_RIGHT_TRIGGER; + buf[4] = DEVICE_MOUSE; + buf[5] = MOUSE_BTN_LEFT; + buf[6] = IO_DIGITAL_BUTTON_LEFT_TRIGGER; + buf[7] = DEVICE_MOUSE; + buf[8] = MOUSE_BTN_RIGHT; + + res = SetFeatureReport(dev, buf, 9); + if (res < 0) { + if (!bSuppressErrorSpew) { + printf("SET_DIGITAL_MAPPINGS failed for controller %p\n", dev); + } + return false; + } +#endif // ENABLE_MOUSE_MODE + + return true; +} + +//--------------------------------------------------------------------------- +// Read from a Steam Controller +//--------------------------------------------------------------------------- +static int ReadSteamController(SDL_hid_device *dev, uint8_t *pData, int nDataSize) +{ + SDL_memset(pData, 0, nDataSize); + pData[0] = BLE_REPORT_NUMBER; // hid_read will also overwrite this with the same value, 0x03 + return SDL_hid_read(dev, pData, nDataSize); +} + +//--------------------------------------------------------------------------- +// Set Steam Controller pairing state +//--------------------------------------------------------------------------- +static void SetPairingState(SDL_HIDAPI_Device *dev, bool bEnablePairing) +{ + unsigned char buf[65]; + SDL_memset(buf, 0, 65); + buf[1] = ID_ENABLE_PAIRING; + buf[2] = 2; // 2 payload bytes: bool + timeout + buf[3] = bEnablePairing ? 1 : 0; + buf[4] = bEnablePairing ? PAIRING_STATE_DURATION_SECONDS : 0; + SetFeatureReport(dev, buf, 5); +} + +//--------------------------------------------------------------------------- +// Commit Steam Controller pairing +//--------------------------------------------------------------------------- +static void CommitPairing(SDL_HIDAPI_Device *dev) +{ + unsigned char buf[65]; + SDL_memset(buf, 0, 65); + buf[1] = ID_DONGLE_COMMIT_DEVICE; + SetFeatureReport(dev, buf, 2); +} + +//--------------------------------------------------------------------------- +// Close a Steam Controller +//--------------------------------------------------------------------------- +static void CloseSteamController(SDL_HIDAPI_Device *dev) +{ + // Switch the Steam Controller back to lizard mode so it works with the OS + unsigned char buf[65]; + int nSettings = 0; + + // Reset digital button mappings + SDL_memset(buf, 0, 65); + buf[1] = ID_SET_DEFAULT_DIGITAL_MAPPINGS; + SetFeatureReport(dev, buf, 2); + + // Reset the default settings + SDL_memset(buf, 0, 65); + buf[1] = ID_LOAD_DEFAULT_SETTINGS; + buf[2] = 0; + SetFeatureReport(dev, buf, 3); + + // Reset mouse mode for lizard mode + SDL_memset(buf, 0, 65); + buf[1] = ID_SET_SETTINGS_VALUES; + ADD_SETTING(SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_ABSOLUTE_MOUSE); + buf[2] = (unsigned char)(nSettings * 3); + SetFeatureReport(dev, buf, 3 + nSettings * 3); +} + +//--------------------------------------------------------------------------- +// Scale and clamp values to a range +//--------------------------------------------------------------------------- +static float RemapValClamped(float val, float A, float B, float C, float D) +{ + if (A == B) { + return (val - B) >= 0.0f ? D : C; + } else { + float cVal = (val - A) / (B - A); + cVal = clamp(cVal, 0.0f, 1.0f); + + return C + (D - C) * cVal; + } +} + +//--------------------------------------------------------------------------- +// Rotate the pad coordinates +//--------------------------------------------------------------------------- +static void RotatePad(int *pX, int *pY, float flAngleInRad) +{ + int origX = *pX, origY = *pY; + + *pX = (int)(SDL_cosf(flAngleInRad) * origX - SDL_sinf(flAngleInRad) * origY); + *pY = (int)(SDL_sinf(flAngleInRad) * origX + SDL_cosf(flAngleInRad) * origY); +} +static void RotatePadShort(short *pX, short *pY, float flAngleInRad) +{ + int origX = *pX, origY = *pY; + + *pX = (short)(SDL_cosf(flAngleInRad) * origX - SDL_sinf(flAngleInRad) * origY); + *pY = (short)(SDL_sinf(flAngleInRad) * origX + SDL_cosf(flAngleInRad) * origY); +} + +//--------------------------------------------------------------------------- +// Format the first part of the state packet +//--------------------------------------------------------------------------- +static void FormatStatePacketUntilGyro(SteamControllerStateInternal_t *pState, ValveControllerStatePacket_t *pStatePacket) +{ + int nLeftPadX; + int nLeftPadY; + int nRightPadX; + int nRightPadY; + int nPadOffset; + + // 15 degrees in rad + const float flRotationAngle = 0.261799f; + + SDL_memset(pState, 0, offsetof(SteamControllerStateInternal_t, sBatteryLevel)); + + // pState->eControllerType = m_eControllerType; + pState->eControllerType = 2; // k_eControllerType_SteamController; + pState->unPacketNum = pStatePacket->unPacketNum; + + // We have a chunk of trigger data in the packet format here, so zero it out afterwards + SDL_memcpy(&pState->ulButtons, &pStatePacket->ButtonTriggerData.ulButtons, 8); + pState->ulButtons &= ~0xFFFF000000LL; + + // The firmware uses this bit to tell us what kind of data is packed into the left two axes + if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK) { + // Finger-down bit not set; "left pad" is actually trackpad + pState->sLeftPadX = pState->sPrevLeftPad[0] = pStatePacket->sLeftPadX; + pState->sLeftPadY = pState->sPrevLeftPad[1] = pStatePacket->sLeftPadY; + + if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK) { + // The controller is interleaving both stick and pad data, both are active + pState->sLeftStickX = pState->sPrevLeftStick[0]; + pState->sLeftStickY = pState->sPrevLeftStick[1]; + } else { + // The stick is not active + pState->sPrevLeftStick[0] = 0; + pState->sPrevLeftStick[1] = 0; + } + } else { + // Finger-down bit not set; "left pad" is actually joystick + + // XXX there's a firmware bug where sometimes padX is 0 and padY is a large number (actually the battery voltage) + // If that happens skip this packet and report last frames stick + /* + if ( m_eControllerType == k_eControllerType_SteamControllerV2 && pStatePacket->sLeftPadY > 900 ) { + pState->sLeftStickX = pState->sPrevLeftStick[0]; + pState->sLeftStickY = pState->sPrevLeftStick[1]; + } else + */ + { + pState->sPrevLeftStick[0] = pState->sLeftStickX = pStatePacket->sLeftPadX; + pState->sPrevLeftStick[1] = pState->sLeftStickY = pStatePacket->sLeftPadY; + } + /* + if (m_eControllerType == k_eControllerType_SteamControllerV2) { + UpdateV2JoystickCap(&state); + } + */ + + if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK) { + // The controller is interleaving both stick and pad data, both are active + pState->sLeftPadX = pState->sPrevLeftPad[0]; + pState->sLeftPadY = pState->sPrevLeftPad[1]; + } else { + // The trackpad is not active + pState->sPrevLeftPad[0] = 0; + pState->sPrevLeftPad[1] = 0; + + // Old controllers send trackpad click for joystick button when trackpad is not active + if (pState->ulButtons & STEAM_BUTTON_LEFTPAD_CLICKED_MASK) { + pState->ulButtons &= ~STEAM_BUTTON_LEFTPAD_CLICKED_MASK; + pState->ulButtons |= STEAM_JOYSTICK_BUTTON_MASK; + } + } + } + + // Fingerdown bit indicates if the packed left axis data was joystick or pad, + // but if we are interleaving both, the left finger is definitely on the pad. + if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK) { + pState->ulButtons |= STEAM_LEFTPAD_FINGERDOWN_MASK; + } + + pState->sRightPadX = pStatePacket->sRightPadX; + pState->sRightPadY = pStatePacket->sRightPadY; + + nLeftPadX = pState->sLeftPadX; + nLeftPadY = pState->sLeftPadY; + nRightPadX = pState->sRightPadX; + nRightPadY = pState->sRightPadY; + + RotatePad(&nLeftPadX, &nLeftPadY, -flRotationAngle); + RotatePad(&nRightPadX, &nRightPadY, flRotationAngle); + + if (pState->ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK) { + nPadOffset = 1000; + } else { + nPadOffset = 0; + } + + pState->sLeftPadX = (short)clamp(nLeftPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); + pState->sLeftPadY = (short)clamp(nLeftPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); + + nPadOffset = 0; + if (pState->ulButtons & STEAM_RIGHTPAD_FINGERDOWN_MASK) { + nPadOffset = 1000; + } else { + nPadOffset = 0; + } + + pState->sRightPadX = (short)clamp(nRightPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); + pState->sRightPadY = (short)clamp(nRightPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); + + pState->sTriggerL = (unsigned short)RemapValClamped((float)((pStatePacket->ButtonTriggerData.Triggers.nLeft << 7) | pStatePacket->ButtonTriggerData.Triggers.nLeft), 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16); + pState->sTriggerR = (unsigned short)RemapValClamped((float)((pStatePacket->ButtonTriggerData.Triggers.nRight << 7) | pStatePacket->ButtonTriggerData.Triggers.nRight), 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16); +} + +//--------------------------------------------------------------------------- +// Update Steam Controller state from a BLE data packet, returns true if it parsed data +//--------------------------------------------------------------------------- +static bool UpdateBLESteamControllerState(const uint8_t *pData, int nDataSize, SteamControllerStateInternal_t *pState) +{ + const float flRotationAngle = 0.261799f; + uint32_t ucOptionDataMask; + + pState->unPacketNum++; + ucOptionDataMask = (*pData++ & 0xF0); + ucOptionDataMask |= (uint32_t)(*pData++) << 8; + if (ucOptionDataMask & k_EBLEButtonChunk1) { + SDL_memcpy(&pState->ulButtons, pData, 3); + pData += 3; + } + if (ucOptionDataMask & k_EBLEButtonChunk2) { + // The middle 2 bytes of the button bits over the wire are triggers when over the wire and non-SC buttons in the internal controller state packet + pState->sTriggerL = (unsigned short)RemapValClamped((float)((pData[0] << 7) | pData[0]), 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16); + pState->sTriggerR = (unsigned short)RemapValClamped((float)((pData[1] << 7) | pData[1]), 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16); + pData += 2; + } + if (ucOptionDataMask & k_EBLEButtonChunk3) { + uint8_t *pButtonByte = (uint8_t *)&pState->ulButtons; + pButtonByte[5] = *pData++; + pButtonByte[6] = *pData++; + pButtonByte[7] = *pData++; + } + if (ucOptionDataMask & k_EBLELeftJoystickChunk) { + // This doesn't handle any of the special headcrab stuff for raw joystick which is OK for now since that FW doesn't support + // this protocol yet either + int nLength = sizeof(pState->sLeftStickX) + sizeof(pState->sLeftStickY); + SDL_memcpy(&pState->sLeftStickX, pData, nLength); + pData += nLength; + } + if (ucOptionDataMask & k_EBLELeftTrackpadChunk) { + int nLength = sizeof(pState->sLeftPadX) + sizeof(pState->sLeftPadY); + int nPadOffset; + SDL_memcpy(&pState->sLeftPadX, pData, nLength); + if (pState->ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK) { + nPadOffset = 1000; + } else { + nPadOffset = 0; + } + + RotatePadShort(&pState->sLeftPadX, &pState->sLeftPadY, -flRotationAngle); + pState->sLeftPadX = (short)clamp(pState->sLeftPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); + pState->sLeftPadY = (short)clamp(pState->sLeftPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); + pData += nLength; + } + if (ucOptionDataMask & k_EBLERightTrackpadChunk) { + int nLength = sizeof(pState->sRightPadX) + sizeof(pState->sRightPadY); + int nPadOffset = 0; + + SDL_memcpy(&pState->sRightPadX, pData, nLength); + + if (pState->ulButtons & STEAM_RIGHTPAD_FINGERDOWN_MASK) { + nPadOffset = 1000; + } else { + nPadOffset = 0; + } + + RotatePadShort(&pState->sRightPadX, &pState->sRightPadY, flRotationAngle); + pState->sRightPadX = (short)clamp(pState->sRightPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); + pState->sRightPadY = (short)clamp(pState->sRightPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); + pData += nLength; + } + if (ucOptionDataMask & k_EBLEIMUAccelChunk) { + int nLength = sizeof(pState->sAccelX) + sizeof(pState->sAccelY) + sizeof(pState->sAccelZ); + SDL_memcpy(&pState->sAccelX, pData, nLength); + pData += nLength; + } + if (ucOptionDataMask & k_EBLEIMUGyroChunk) { + int nLength = sizeof(pState->sAccelX) + sizeof(pState->sAccelY) + sizeof(pState->sAccelZ); + SDL_memcpy(&pState->sGyroX, pData, nLength); + pData += nLength; + } + if (ucOptionDataMask & k_EBLEIMUQuatChunk) { + int nLength = sizeof(pState->sGyroQuatW) + sizeof(pState->sGyroQuatX) + sizeof(pState->sGyroQuatY) + sizeof(pState->sGyroQuatZ); + SDL_memcpy(&pState->sGyroQuatW, pData, nLength); + pData += nLength; + } + return true; +} + +//--------------------------------------------------------------------------- +// Update Steam Controller state from a data packet, returns true if it parsed data +//--------------------------------------------------------------------------- +static bool UpdateSteamControllerState(const uint8_t *pData, int nDataSize, SteamControllerStateInternal_t *pState) +{ + ValveInReport_t *pInReport = (ValveInReport_t *)pData; + + if (pInReport->header.unReportVersion != k_ValveInReportMsgVersion) { + if ((pData[0] & 0x0F) == k_EBLEReportState) { + return UpdateBLESteamControllerState(pData, nDataSize, pState); + } + return false; + } + + if ((pInReport->header.ucType != ID_CONTROLLER_STATE) && + (pInReport->header.ucType != ID_CONTROLLER_BLE_STATE)) { + return false; + } + + if (pInReport->header.ucType == ID_CONTROLLER_STATE) { + ValveControllerStatePacket_t *pStatePacket = &pInReport->payload.controllerState; + + // No new data to process; indicate that we received a state packet, but otherwise do nothing. + if (pState->unPacketNum == pStatePacket->unPacketNum) { + return true; + } + + FormatStatePacketUntilGyro(pState, pStatePacket); + + pState->sAccelX = pStatePacket->sAccelX; + pState->sAccelY = pStatePacket->sAccelY; + pState->sAccelZ = pStatePacket->sAccelZ; + + pState->sGyroQuatW = pStatePacket->sGyroQuatW; + pState->sGyroQuatX = pStatePacket->sGyroQuatX; + pState->sGyroQuatY = pStatePacket->sGyroQuatY; + pState->sGyroQuatZ = pStatePacket->sGyroQuatZ; + + pState->sGyroX = pStatePacket->sGyroX; + pState->sGyroY = pStatePacket->sGyroY; + pState->sGyroZ = pStatePacket->sGyroZ; + + } else if (pInReport->header.ucType == ID_CONTROLLER_BLE_STATE) { + ValveControllerBLEStatePacket_t *pBLEStatePacket = &pInReport->payload.controllerBLEState; + ValveControllerStatePacket_t *pStatePacket = &pInReport->payload.controllerState; + + // No new data to process; indicate that we received a state packet, but otherwise do nothing. + if (pState->unPacketNum == pStatePacket->unPacketNum) { + return true; + } + + FormatStatePacketUntilGyro(pState, pStatePacket); + + switch (pBLEStatePacket->ucGyroDataType) { + case 1: + pState->sGyroQuatW = ((float)pBLEStatePacket->sGyro[0]); + pState->sGyroQuatX = ((float)pBLEStatePacket->sGyro[1]); + pState->sGyroQuatY = ((float)pBLEStatePacket->sGyro[2]); + pState->sGyroQuatZ = ((float)pBLEStatePacket->sGyro[3]); + break; + + case 2: + pState->sAccelX = pBLEStatePacket->sGyro[0]; + pState->sAccelY = pBLEStatePacket->sGyro[1]; + pState->sAccelZ = pBLEStatePacket->sGyro[2]; + break; + + case 3: + pState->sGyroX = pBLEStatePacket->sGyro[0]; + pState->sGyroY = pBLEStatePacket->sGyro[1]; + pState->sGyroZ = pBLEStatePacket->sGyro[2]; + break; + + default: + break; + } + } + + return true; +} + +/*****************************************************************************************************/ + +typedef struct +{ + SDL_HIDAPI_Device *device; + bool connected; + bool report_sensors; + uint32_t update_rate_in_us; + Uint64 sensor_timestamp; + Uint64 pairing_time; + + SteamControllerPacketAssembler m_assembler; + SteamControllerStateInternal_t m_state; + SteamControllerStateInternal_t m_last_state; +} SDL_DriverSteam_Context; + +static bool IsDongle(Uint16 product_id) +{ + return (product_id == USB_PRODUCT_VALVE_STEAM_CONTROLLER_DONGLE); +} + +static void HIDAPI_DriverSteam_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAM, callback, userdata); +} + +static void HIDAPI_DriverSteam_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAM, callback, userdata); +} + +static bool HIDAPI_DriverSteam_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_STEAM, SDL_HINT_JOYSTICK_HIDAPI_STEAM_DEFAULT); +} + +static bool HIDAPI_DriverSteam_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + if (!SDL_IsJoystickSteamController(vendor_id, product_id)) { + return false; + } + + if (device->is_bluetooth) { + return true; + } + + if (IsDongle(product_id)) { + if (interface_number >= 1 && interface_number <= 4) { + // This is one of the wireless controller interfaces + return true; + } + } else { + if (interface_number == 2) { + // This is the controller interface (not mouse or keyboard) + return true; + } + } + return false; +} + +static void HIDAPI_DriverSteam_SetPairingState(SDL_DriverSteam_Context *ctx, bool enabled) +{ + // Only have one dongle in pairing mode at a time + static SDL_DriverSteam_Context *s_PairingContext = NULL; + + if (enabled && s_PairingContext != NULL) { + return; + } + + if (!enabled && s_PairingContext != ctx) { + return; + } + + if (ctx->connected) { + return; + } + + SetPairingState(ctx->device, enabled); + + if (enabled) { + ctx->pairing_time = SDL_GetTicks(); + s_PairingContext = ctx; + } else { + ctx->pairing_time = 0; + s_PairingContext = NULL; + } +} + +static void HIDAPI_DriverSteam_RenewPairingState(SDL_DriverSteam_Context *ctx) +{ + Uint64 now = SDL_GetTicks(); + + if (now >= ctx->pairing_time + PAIRING_STATE_DURATION_SECONDS * 1000) { + SetPairingState(ctx->device, true); + ctx->pairing_time = now; + } +} + +static void HIDAPI_DriverSteam_CommitPairing(SDL_DriverSteam_Context *ctx) +{ + CommitPairing(ctx->device); +} + +static void SDLCALL SDL_PairingEnabledHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)userdata; + bool enabled = SDL_GetStringBoolean(hint, false); + + HIDAPI_DriverSteam_SetPairingState(ctx, enabled); +} + +static bool HIDAPI_DriverSteam_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverSteam_Context *ctx; + + ctx = (SDL_DriverSteam_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + device->context = ctx; + +#ifdef SDL_PLATFORM_WIN32 + if (device->serial) { + // We get a garbage serial number on Windows + SDL_free(device->serial); + device->serial = NULL; + } +#endif // SDL_PLATFORM_WIN32 + + HIDAPI_SetDeviceName(device, "Steam Controller"); + + // If this is a wireless dongle, request a wireless state update + if (IsDongle(device->product_id)) { + unsigned char buf[65]; + int res; + + buf[0] = 0; + buf[1] = ID_DONGLE_GET_WIRELESS_STATE; + res = SetFeatureReport(device, buf, 2); + if (res < 0) { + return SDL_SetError("Failed to send ID_DONGLE_GET_WIRELESS_STATE request"); + } + + for (int attempt = 0; attempt < 5; ++attempt) { + uint8_t data[128]; + + res = ReadSteamController(device->dev, data, sizeof(data)); + if (res == 0) { + SDL_Delay(1); + continue; + } + if (res < 0) { + break; + } + +#ifdef DEBUG_STEAM_PROTOCOL + HIDAPI_DumpPacket("Initial dongle packet: size = %d", data, res); +#endif + + if (D0G_IS_WIRELESS_CONNECT(data, res)) { + ctx->connected = true; + break; + } else if (D0G_IS_WIRELESS_DISCONNECT(data, res)) { + ctx->connected = false; + break; + } + } + + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAM_PAIRING_ENABLED, + SDL_PairingEnabledHintChanged, ctx); + } else { + // Wired and BLE controllers are always connected if HIDAPI can see them + ctx->connected = true; + } + + if (ctx->connected) { + return HIDAPI_JoystickConnected(device, NULL); + } else { + // We will enumerate any attached controllers in UpdateDevice() + return true; + } +} + +static int HIDAPI_DriverSteam_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverSteam_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ +} + +static bool SetHomeLED(SDL_HIDAPI_Device *device, Uint8 value) +{ + unsigned char buf[65]; + int nSettings = 0; + + SDL_memset(buf, 0, 65); + buf[1] = ID_SET_SETTINGS_VALUES; + ADD_SETTING(SETTING_LED_USER_BRIGHTNESS, value); + buf[2] = (unsigned char)(nSettings * 3); + if (SetFeatureReport(device, buf, 3 + nSettings * 3) < 0) { + return SDL_SetError("Couldn't write feature report"); + } + return true; +} + +static void SDLCALL SDL_HomeLEDHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)userdata; + + if (hint && *hint) { + int value; + + if (SDL_strchr(hint, '.') != NULL) { + value = (int)(100.0f * SDL_atof(hint)); + if (value > 255) { + value = 255; + } + } else if (SDL_GetStringBoolean(hint, true)) { + value = 100; + } else { + value = 0; + } + SetHomeLED(ctx->device, (Uint8)value); + } +} + +static bool HIDAPI_DriverSteam_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context; + float update_rate_in_hz = 0.0f; + + SDL_AssertJoysticksLocked(); + + ctx->report_sensors = false; + SDL_zero(ctx->m_assembler); + SDL_zero(ctx->m_state); + SDL_zero(ctx->m_last_state); + + if (!ResetSteamController(device, false, &ctx->update_rate_in_us)) { + SDL_SetError("Couldn't reset controller"); + return false; + } + if (ctx->update_rate_in_us > 0) { + update_rate_in_hz = 1000000.0f / ctx->update_rate_in_us; + } + + InitializeSteamControllerPacketAssembler(&ctx->m_assembler, device->is_bluetooth); + + // Initialize the joystick capabilities + joystick->nbuttons = SDL_GAMEPAD_NUM_STEAM_BUTTONS; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + + if (IsDongle(device->product_id)) { + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRELESS; + } + + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, update_rate_in_hz); + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, update_rate_in_hz); + + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAM_HOME_LED, + SDL_HomeLEDHintChanged, ctx); + + return true; +} + +static bool HIDAPI_DriverSteam_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + // You should use the full Steam Input API for rumble support + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverSteam_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverSteam_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + // You should use the full Steam Input API for extended capabilities + return 0; +} + +static bool HIDAPI_DriverSteam_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + // You should use the full Steam Input API for LED support + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverSteam_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + if (size == 65) { + if (SetFeatureReport(device, data, size) < 0) { + return SDL_SetError("Couldn't write feature report"); + } + return true; + } + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverSteam_SetSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context; + unsigned char buf[65]; + int nSettings = 0; + + SDL_memset(buf, 0, 65); + buf[1] = ID_SET_SETTINGS_VALUES; + if (enabled) { + ADD_SETTING(SETTING_IMU_MODE, SETTING_GYRO_MODE_SEND_RAW_ACCEL | SETTING_GYRO_MODE_SEND_RAW_GYRO); + } else { + ADD_SETTING(SETTING_IMU_MODE, SETTING_GYRO_MODE_OFF); + } + buf[2] = (unsigned char)(nSettings * 3); + if (SetFeatureReport(device, buf, 3 + nSettings * 3) < 0) { + return SDL_SetError("Couldn't write feature report"); + } + + ctx->report_sensors = enabled; + + return true; +} + +static bool ControllerConnected(SDL_HIDAPI_Device *device, SDL_Joystick **joystick) +{ + SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context; + + if (!HIDAPI_JoystickConnected(device, NULL)) { + return false; + } + + // We'll automatically accept this controller if we're in pairing mode + HIDAPI_DriverSteam_CommitPairing(ctx); + + *joystick = SDL_GetJoystickFromID(device->joysticks[0]); + ctx->connected = true; + return true; +} + +static void ControllerDisconnected(SDL_HIDAPI_Device *device, SDL_Joystick **joystick) +{ + SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context; + + if (device->joysticks) { + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + ctx->connected = false; + *joystick = NULL; +} + +static bool HIDAPI_DriverSteam_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context; + SDL_Joystick *joystick = NULL; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } + + if (ctx->pairing_time) { + HIDAPI_DriverSteam_RenewPairingState(ctx); + } + + for (;;) { + uint8_t data[128]; + int r, nPacketLength; + const Uint8 *pPacket; + + r = ReadSteamController(device->dev, data, sizeof(data)); + if (r == 0) { + break; + } + if (r < 0) { + // Failed to read from controller + ControllerDisconnected(device, &joystick); + return false; + } + +#ifdef DEBUG_STEAM_PROTOCOL + HIDAPI_DumpPacket("Steam Controller packet: size = %d", data, r); +#endif + + nPacketLength = WriteSegmentToSteamControllerPacketAssembler(&ctx->m_assembler, data, r); + pPacket = ctx->m_assembler.uBuffer; + + if (nPacketLength > 0 && UpdateSteamControllerState(pPacket, nPacketLength, &ctx->m_state)) { + Uint64 timestamp = SDL_GetTicksNS(); + + if (!ctx->connected) { + // Maybe we missed a wireless status packet? + ControllerConnected(device, &joystick); + } + + if (!joystick) { + continue; + } + + if (ctx->m_state.ulButtons != ctx->m_last_state.ulButtons) { + Uint8 hat = 0; + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, + ((ctx->m_state.ulButtons & STEAM_BUTTON_SOUTH_MASK) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, + ((ctx->m_state.ulButtons & STEAM_BUTTON_EAST_MASK) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, + ((ctx->m_state.ulButtons & STEAM_BUTTON_WEST_MASK) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, + ((ctx->m_state.ulButtons & STEAM_BUTTON_NORTH_MASK) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, + ((ctx->m_state.ulButtons & STEAM_LEFT_BUMPER_MASK) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, + ((ctx->m_state.ulButtons & STEAM_RIGHT_BUMPER_MASK) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, + ((ctx->m_state.ulButtons & STEAM_BUTTON_MENU_MASK) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, + ((ctx->m_state.ulButtons & STEAM_BUTTON_ESCAPE_MASK) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, + ((ctx->m_state.ulButtons & STEAM_BUTTON_STEAM_MASK) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, + ((ctx->m_state.ulButtons & STEAM_JOYSTICK_BUTTON_MASK) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_STEAM_LEFT_PADDLE, + ((ctx->m_state.ulButtons & STEAM_BUTTON_BACK_LEFT_MASK) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_STEAM_RIGHT_PADDLE, + ((ctx->m_state.ulButtons & STEAM_BUTTON_BACK_RIGHT_MASK) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, + ((ctx->m_state.ulButtons & STEAM_BUTTON_RIGHTPAD_CLICKED_MASK) != 0)); + + if (ctx->m_state.ulButtons & STEAM_DPAD_UP_MASK) { + hat |= SDL_HAT_UP; + } + if (ctx->m_state.ulButtons & STEAM_DPAD_DOWN_MASK) { + hat |= SDL_HAT_DOWN; + } + if (ctx->m_state.ulButtons & STEAM_DPAD_LEFT_MASK) { + hat |= SDL_HAT_LEFT; + } + if (ctx->m_state.ulButtons & STEAM_DPAD_RIGHT_MASK) { + hat |= SDL_HAT_RIGHT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, (int)ctx->m_state.sTriggerL * 2 - 32768); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, (int)ctx->m_state.sTriggerR * 2 - 32768); + + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, ctx->m_state.sLeftStickX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, ~ctx->m_state.sLeftStickY); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, ctx->m_state.sRightPadX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, ~ctx->m_state.sRightPadY); + + if (ctx->report_sensors) { + float values[3]; + + ctx->sensor_timestamp += SDL_US_TO_NS(ctx->update_rate_in_us); + + values[0] = (ctx->m_state.sGyroX / 32768.0f) * (2000.0f * (SDL_PI_F / 180.0f)); + values[1] = (ctx->m_state.sGyroZ / 32768.0f) * (2000.0f * (SDL_PI_F / 180.0f)); + values[2] = (ctx->m_state.sGyroY / 32768.0f) * (2000.0f * (SDL_PI_F / 180.0f)); + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, ctx->sensor_timestamp, values, 3); + + values[0] = (ctx->m_state.sAccelX / 32768.0f) * 2.0f * SDL_STANDARD_GRAVITY; + values[1] = (ctx->m_state.sAccelZ / 32768.0f) * 2.0f * SDL_STANDARD_GRAVITY; + values[2] = (-ctx->m_state.sAccelY / 32768.0f) * 2.0f * SDL_STANDARD_GRAVITY; + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, ctx->sensor_timestamp, values, 3); + } + + ctx->m_last_state = ctx->m_state; + } else if (!ctx->connected && D0G_IS_WIRELESS_CONNECT(pPacket, nPacketLength)) { + ControllerConnected(device, &joystick); + } else if (ctx->connected && D0G_IS_WIRELESS_DISCONNECT(pPacket, nPacketLength)) { + ControllerDisconnected(device, &joystick); + } + } + return true; +} + +static void HIDAPI_DriverSteam_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context; + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAM_HOME_LED, + SDL_HomeLEDHintChanged, ctx); + + CloseSteamController(device); +} + +static void HIDAPI_DriverSteam_FreeDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context; + + if (IsDongle(device->product_id)) { + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAM_PAIRING_ENABLED, + SDL_PairingEnabledHintChanged, ctx); + + HIDAPI_DriverSteam_SetPairingState(ctx, false); + } +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSteam = { + SDL_HINT_JOYSTICK_HIDAPI_STEAM, + true, + HIDAPI_DriverSteam_RegisterHints, + HIDAPI_DriverSteam_UnregisterHints, + HIDAPI_DriverSteam_IsEnabled, + HIDAPI_DriverSteam_IsSupportedDevice, + HIDAPI_DriverSteam_InitDevice, + HIDAPI_DriverSteam_GetDevicePlayerIndex, + HIDAPI_DriverSteam_SetDevicePlayerIndex, + HIDAPI_DriverSteam_UpdateDevice, + HIDAPI_DriverSteam_OpenJoystick, + HIDAPI_DriverSteam_RumbleJoystick, + HIDAPI_DriverSteam_RumbleJoystickTriggers, + HIDAPI_DriverSteam_GetJoystickCapabilities, + HIDAPI_DriverSteam_SetJoystickLED, + HIDAPI_DriverSteam_SendJoystickEffect, + HIDAPI_DriverSteam_SetSensorsEnabled, + HIDAPI_DriverSteam_CloseJoystick, + HIDAPI_DriverSteam_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_STEAM + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_steam_hori.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_steam_hori.c new file mode 100644 index 00000000000..0cd192d018c --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_steam_hori.c @@ -0,0 +1,415 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" +#include "../SDL_joystick_c.h" + +#ifdef SDL_JOYSTICK_HIDAPI_STEAM_HORI + +/* Define this if you want to log all packets from the controller */ +/*#define DEBUG_HORI_PROTOCOL*/ + +#define LOAD16(A, B) (Sint16)((Uint16)(A) | (((Uint16)(B)) << 8)) + +enum +{ + SDL_GAMEPAD_BUTTON_HORI_QAM = 11, + SDL_GAMEPAD_BUTTON_HORI_FR, + SDL_GAMEPAD_BUTTON_HORI_FL, + SDL_GAMEPAD_BUTTON_HORI_M1, + SDL_GAMEPAD_BUTTON_HORI_M2, + SDL_GAMEPAD_BUTTON_HORI_JOYSTICK_TOUCH_L, + SDL_GAMEPAD_BUTTON_HORI_JOYSTICK_TOUCH_R, + SDL_GAMEPAD_NUM_HORI_BUTTONS +}; + +typedef struct +{ + Uint8 last_state[USB_PACKET_LENGTH]; + Uint64 sensor_ticks; + Uint32 last_tick; + bool wireless; + bool serial_needs_init; +} SDL_DriverSteamHori_Context; + +static bool HIDAPI_DriverSteamHori_UpdateDevice(SDL_HIDAPI_Device *device); + +static void HIDAPI_DriverSteamHori_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAM_HORI, callback, userdata); +} + +static void HIDAPI_DriverSteamHori_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAM_HORI, callback, userdata); +} + +static bool HIDAPI_DriverSteamHori_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_STEAM_HORI, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)); +} + +static bool HIDAPI_DriverSteamHori_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + return SDL_IsJoystickHoriSteamController(vendor_id, product_id); +} + +static bool HIDAPI_DriverSteamHori_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverSteamHori_Context *ctx; + + ctx = (SDL_DriverSteamHori_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + + device->context = ctx; + ctx->serial_needs_init = true; + + HIDAPI_SetDeviceName(device, "Wireless HORIPAD For Steam"); + + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverSteamHori_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverSteamHori_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ +} + +static bool HIDAPI_DriverSteamHori_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverSteamHori_Context *ctx = (SDL_DriverSteamHori_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + SDL_zeroa(ctx->last_state); + + /* Initialize the joystick capabilities */ + joystick->nbuttons = SDL_GAMEPAD_NUM_HORI_BUTTONS; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + + ctx->wireless = device->product_id == USB_PRODUCT_HORI_STEAM_CONTROLLER_BT; + + if (ctx->wireless && device->serial) { + joystick->serial = SDL_strdup(device->serial); + ctx->serial_needs_init = false; + } else if (!ctx->wireless) { + // Need to actual read from the device to init the serial + HIDAPI_DriverSteamHori_UpdateDevice(device); + } + + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, 250.0f); + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 250.0f); + + return true; +} + +static bool HIDAPI_DriverSteamHori_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + // Device doesn't support rumble + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverSteamHori_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverSteamHori_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + return 0; +} + +static bool HIDAPI_DriverSteamHori_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverSteamHori_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverSteamHori_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + return true; +} + +#undef clamp +#define clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val))) + +#ifndef DEG2RAD +#define DEG2RAD(x) ((float)(x) * (float)(SDL_PI_F / 180.f)) +#endif + +//--------------------------------------------------------------------------- +// Scale and clamp values to a range +//--------------------------------------------------------------------------- +static float RemapValClamped(float val, float A, float B, float C, float D) +{ + if (A == B) { + return (val - B) >= 0.0f ? D : C; + } else { + float cVal = (val - A) / (B - A); + cVal = clamp(cVal, 0.0f, 1.0f); + + return C + (D - C) * cVal; + } +} + +#define REPORT_HEADER_USB 0x07 +#define REPORT_HEADER_BT 0x00 + +static void HIDAPI_DriverSteamHori_HandleStatePacket(SDL_Joystick *joystick, SDL_DriverSteamHori_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; + Uint64 timestamp = SDL_GetTicksNS(); + + // Make sure it's gamepad state and not OTA FW update info + if (data[0] != REPORT_HEADER_USB && data[0] != REPORT_HEADER_BT) { + /* We don't know how to handle this report */ + return; + } + + #define READ_STICK_AXIS(offset) \ + (data[offset] == 0x80 ? 0 : (Sint16)HIDAPI_RemapVal((float)((int)data[offset] - 0x80), -0x80, 0xff - 0x80, SDL_MIN_SINT16, SDL_MAX_SINT16)) + { + axis = READ_STICK_AXIS(1); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = READ_STICK_AXIS(2); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = READ_STICK_AXIS(3); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = READ_STICK_AXIS(4); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + } +#undef READ_STICK_AXIS + + if (ctx->last_state[5] != data[5]) { + Uint8 hat; + + switch (data[5] & 0xF) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[5] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[5] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_HORI_QAM, ((data[5] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[5] & 0x80) != 0)); + + } + + if (ctx->last_state[6] != data[6]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[6] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_HORI_M1 /* M1 */, ((data[6] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[6] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[6] & 0x08) != 0)); + + // TODO: can we handle the digital trigger mode? The data seems to come through analog regardless of the trigger state + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[6] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[6] & 0x80) != 0)); + } + + if (ctx->last_state[7] != data[7]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[7] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[7] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[7] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_HORI_M2, ((data[7] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_HORI_JOYSTICK_TOUCH_L, ((data[7] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_HORI_JOYSTICK_TOUCH_R, ((data[7] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_HORI_FR, ((data[7] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_HORI_FL, ((data[7] & 0x80) != 0)); + } + + if (!ctx->wireless && ctx->serial_needs_init) { + char serial[18]; + (void)SDL_snprintf(serial, sizeof(serial), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x", + data[38], data[39], data[40], data[41], data[42], data[43]); + + joystick->serial = SDL_strdup(serial); + ctx->serial_needs_init = false; + } + +#define READ_TRIGGER_AXIS(offset) \ + (Sint16)(((int)data[offset] * 257) - 32768) + { + axis = READ_TRIGGER_AXIS(8); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + axis = READ_TRIGGER_AXIS(9); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + } +#undef READ_TRIGGER_AXIS + + if (1) { + Uint64 sensor_timestamp; + float imu_data[3]; + + /* 16-bit timestamp */ + Uint32 delta; + Uint16 tick = LOAD16(data[10], + data[11]); + if (ctx->last_tick < tick) { + delta = (tick - ctx->last_tick); + } else { + delta = (SDL_MAX_UINT16 - ctx->last_tick + tick + 1); + } + + ctx->last_tick = tick; + ctx->sensor_ticks += delta; + + /* Sensor timestamp is in 1us units, but there seems to be some issues with the values reported from the device */ + sensor_timestamp = timestamp; // if the values were good we woudl call SDL_US_TO_NS(ctx->sensor_ticks); + + const float accelScale = SDL_STANDARD_GRAVITY * 8 / 32768.0f; + const float gyroScale = DEG2RAD(2048); + + imu_data[1] = RemapValClamped(-1.0f * LOAD16(data[12], data[13]), INT16_MIN, INT16_MAX, -gyroScale, gyroScale); + imu_data[2] = RemapValClamped(-1.0f * LOAD16(data[14], data[15]), INT16_MIN, INT16_MAX, -gyroScale, gyroScale); + imu_data[0] = RemapValClamped(-1.0f * LOAD16(data[16], data[17]), INT16_MIN, INT16_MAX, -gyroScale, gyroScale); + + + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, sensor_timestamp, imu_data, 3); + + // SDL_Log("%u %f, %f, %f ", data[0], imu_data[0], imu_data[1], imu_data[2] ); + imu_data[2] = LOAD16(data[18], data[19]) * accelScale; + imu_data[1] = -1 * LOAD16(data[20], data[21]) * accelScale; + imu_data[0] = LOAD16(data[22], data[23]) * accelScale; + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, sensor_timestamp, imu_data, 3); + } + + if (ctx->last_state[24] != data[24]) { + bool bCharging = (data[24] & 0x10) != 0; + int percent = (data[24] & 0xF) * 10; + SDL_PowerState state; + if (bCharging) { + state = SDL_POWERSTATE_CHARGING; + } else if (ctx->wireless) { + state = SDL_POWERSTATE_ON_BATTERY; + } else { + state = SDL_POWERSTATE_CHARGED; + } + + SDL_SendJoystickPowerInfo(joystick, state, percent); + } + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static bool HIDAPI_DriverSteamHori_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverSteamHori_Context *ctx = (SDL_DriverSteamHori_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH]; + int size = 0; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } else { + return false; + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { +#ifdef DEBUG_HORI_PROTOCOL + HIDAPI_DumpPacket("Google Hori packet: size = %d", data, size); +#endif + if (!joystick) { + continue; + } + + HIDAPI_DriverSteamHori_HandleStatePacket(joystick, ctx, data, size); + } + + if (size < 0) { + /* Read error, device is disconnected */ + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverSteamHori_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ +} + +static void HIDAPI_DriverSteamHori_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSteamHori = { + SDL_HINT_JOYSTICK_HIDAPI_STEAM_HORI, + true, + HIDAPI_DriverSteamHori_RegisterHints, + HIDAPI_DriverSteamHori_UnregisterHints, + HIDAPI_DriverSteamHori_IsEnabled, + HIDAPI_DriverSteamHori_IsSupportedDevice, + HIDAPI_DriverSteamHori_InitDevice, + HIDAPI_DriverSteamHori_GetDevicePlayerIndex, + HIDAPI_DriverSteamHori_SetDevicePlayerIndex, + HIDAPI_DriverSteamHori_UpdateDevice, + HIDAPI_DriverSteamHori_OpenJoystick, + HIDAPI_DriverSteamHori_RumbleJoystick, + HIDAPI_DriverSteamHori_RumbleJoystickTriggers, + HIDAPI_DriverSteamHori_GetJoystickCapabilities, + HIDAPI_DriverSteamHori_SetJoystickLED, + HIDAPI_DriverSteamHori_SendJoystickEffect, + HIDAPI_DriverSteamHori_SetJoystickSensorsEnabled, + HIDAPI_DriverSteamHori_CloseJoystick, + HIDAPI_DriverSteamHori_FreeDevice, +}; + +#endif /* SDL_JOYSTICK_HIDAPI_STEAM_HORI */ + +#endif /* SDL_JOYSTICK_HIDAPI */ diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_steamdeck.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_steamdeck.c new file mode 100644 index 00000000000..75a13cc1b92 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_steamdeck.c @@ -0,0 +1,451 @@ +/* + Simple DirectMedia Layer + Copyright (C) 2023 Max Maisel + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" + +#ifdef SDL_JOYSTICK_HIDAPI_STEAMDECK + +/*****************************************************************************************************/ + +#include "steam/controller_constants.h" +#include "steam/controller_structs.h" + +enum +{ + SDL_GAMEPAD_BUTTON_STEAM_DECK_QAM = 11, + SDL_GAMEPAD_BUTTON_STEAM_DECK_RIGHT_PADDLE1, + SDL_GAMEPAD_BUTTON_STEAM_DECK_LEFT_PADDLE1, + SDL_GAMEPAD_BUTTON_STEAM_DECK_RIGHT_PADDLE2, + SDL_GAMEPAD_BUTTON_STEAM_DECK_LEFT_PADDLE2, + SDL_GAMEPAD_NUM_STEAM_DECK_BUTTONS, +}; + +typedef enum +{ + STEAMDECK_LBUTTON_R2 = 0x00000001, + STEAMDECK_LBUTTON_L2 = 0x00000002, + STEAMDECK_LBUTTON_R = 0x00000004, + STEAMDECK_LBUTTON_L = 0x00000008, + STEAMDECK_LBUTTON_Y = 0x00000010, + STEAMDECK_LBUTTON_B = 0x00000020, + STEAMDECK_LBUTTON_X = 0x00000040, + STEAMDECK_LBUTTON_A = 0x00000080, + STEAMDECK_LBUTTON_DPAD_UP = 0x00000100, + STEAMDECK_LBUTTON_DPAD_RIGHT = 0x00000200, + STEAMDECK_LBUTTON_DPAD_LEFT = 0x00000400, + STEAMDECK_LBUTTON_DPAD_DOWN = 0x00000800, + STEAMDECK_LBUTTON_VIEW = 0x00001000, + STEAMDECK_LBUTTON_STEAM = 0x00002000, + STEAMDECK_LBUTTON_MENU = 0x00004000, + STEAMDECK_LBUTTON_L5 = 0x00008000, + STEAMDECK_LBUTTON_R5 = 0x00010000, + STEAMDECK_LBUTTON_LEFT_PAD = 0x00020000, + STEAMDECK_LBUTTON_RIGHT_PAD = 0x00040000, + STEAMDECK_LBUTTON_L3 = 0x00400000, + STEAMDECK_LBUTTON_R3 = 0x04000000, + + STEAMDECK_HBUTTON_L4 = 0x00000200, + STEAMDECK_HBUTTON_R4 = 0x00000400, + STEAMDECK_HBUTTON_QAM = 0x00040000, +} SteamDeckButtons; + +typedef struct +{ + Uint32 update_rate_us; + Uint32 sensor_timestamp_us; + Uint64 last_button_state; + Uint8 watchdog_counter; +} SDL_DriverSteamDeck_Context; + +static bool DisableDeckLizardMode(SDL_hid_device *dev) +{ + int rc; + Uint8 buffer[HID_FEATURE_REPORT_BYTES + 1] = { 0 }; + FeatureReportMsg *msg = (FeatureReportMsg *)(buffer + 1); + + msg->header.type = ID_CLEAR_DIGITAL_MAPPINGS; + + rc = SDL_hid_send_feature_report(dev, buffer, sizeof(buffer)); + if (rc != sizeof(buffer)) + return false; + + msg->header.type = ID_SET_SETTINGS_VALUES; + msg->header.length = 5 * sizeof(ControllerSetting); + msg->payload.setSettingsValues.settings[0].settingNum = SETTING_SMOOTH_ABSOLUTE_MOUSE; + msg->payload.setSettingsValues.settings[0].settingValue = 0; + msg->payload.setSettingsValues.settings[1].settingNum = SETTING_LEFT_TRACKPAD_MODE; + msg->payload.setSettingsValues.settings[1].settingValue = TRACKPAD_NONE; + msg->payload.setSettingsValues.settings[2].settingNum = SETTING_RIGHT_TRACKPAD_MODE; // disable mouse + msg->payload.setSettingsValues.settings[2].settingValue = TRACKPAD_NONE; + msg->payload.setSettingsValues.settings[3].settingNum = SETTING_LEFT_TRACKPAD_CLICK_PRESSURE; // disable clicky pad + msg->payload.setSettingsValues.settings[3].settingValue = 0xFFFF; + msg->payload.setSettingsValues.settings[4].settingNum = SETTING_RIGHT_TRACKPAD_CLICK_PRESSURE; // disable clicky pad + msg->payload.setSettingsValues.settings[4].settingValue = 0xFFFF; + + rc = SDL_hid_send_feature_report(dev, buffer, sizeof(buffer)); + if (rc != sizeof(buffer)) + return false; + + // There may be a lingering report read back after changing settings. + // Discard it. + SDL_hid_get_feature_report(dev, buffer, sizeof(buffer)); + + return true; +} + +static bool FeedDeckLizardWatchdog(SDL_hid_device *dev) +{ + int rc; + Uint8 buffer[HID_FEATURE_REPORT_BYTES + 1] = { 0 }; + FeatureReportMsg *msg = (FeatureReportMsg *)(buffer + 1); + + msg->header.type = ID_CLEAR_DIGITAL_MAPPINGS; + + rc = SDL_hid_send_feature_report(dev, buffer, sizeof(buffer)); + if (rc != sizeof(buffer)) + return false; + + msg->header.type = ID_SET_SETTINGS_VALUES; + msg->header.length = 1 * sizeof(ControllerSetting); + msg->payload.setSettingsValues.settings[0].settingNum = SETTING_RIGHT_TRACKPAD_MODE; + msg->payload.setSettingsValues.settings[0].settingValue = TRACKPAD_NONE; + + rc = SDL_hid_send_feature_report(dev, buffer, sizeof(buffer)); + if (rc != sizeof(buffer)) + return false; + + // There may be a lingering report read back after changing settings. + // Discard it. + SDL_hid_get_feature_report(dev, buffer, sizeof(buffer)); + + return true; +} + +static void HIDAPI_DriverSteamDeck_HandleState(SDL_HIDAPI_Device *device, + SDL_Joystick *joystick, + ValveInReport_t *pInReport) +{ + float values[3]; + SDL_DriverSteamDeck_Context *ctx = (SDL_DriverSteamDeck_Context *)device->context; + Uint64 timestamp = SDL_GetTicksNS(); + + if (pInReport->payload.deckState.ulButtons != ctx->last_button_state) { + Uint8 hat = 0; + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_A) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_B) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_X) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_Y) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_L) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_R) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_VIEW) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_MENU) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_STEAM) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_STEAM_DECK_QAM, + ((pInReport->payload.deckState.ulButtonsH & STEAMDECK_HBUTTON_QAM) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_L3) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_R3) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_STEAM_DECK_RIGHT_PADDLE1, + ((pInReport->payload.deckState.ulButtonsH & STEAMDECK_HBUTTON_R4) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_STEAM_DECK_LEFT_PADDLE1, + ((pInReport->payload.deckState.ulButtonsH & STEAMDECK_HBUTTON_L4) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_STEAM_DECK_RIGHT_PADDLE2, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_R5) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_STEAM_DECK_LEFT_PADDLE2, + ((pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_L5) != 0)); + + if (pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_DPAD_UP) { + hat |= SDL_HAT_UP; + } + if (pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_DPAD_DOWN) { + hat |= SDL_HAT_DOWN; + } + if (pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_DPAD_LEFT) { + hat |= SDL_HAT_LEFT; + } + if (pInReport->payload.deckState.ulButtonsL & STEAMDECK_LBUTTON_DPAD_RIGHT) { + hat |= SDL_HAT_RIGHT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + + ctx->last_button_state = pInReport->payload.deckState.ulButtons; + } + + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, + (int)pInReport->payload.deckState.sTriggerRawL * 2 - 32768); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, + (int)pInReport->payload.deckState.sTriggerRawR * 2 - 32768); + + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, + pInReport->payload.deckState.sLeftStickX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, + -pInReport->payload.deckState.sLeftStickY); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, + pInReport->payload.deckState.sRightStickX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, + -pInReport->payload.deckState.sRightStickY); + + ctx->sensor_timestamp_us += ctx->update_rate_us; + + values[0] = (pInReport->payload.deckState.sGyroX / 32768.0f) * (2000.0f * (SDL_PI_F / 180.0f)); + values[1] = (pInReport->payload.deckState.sGyroZ / 32768.0f) * (2000.0f * (SDL_PI_F / 180.0f)); + values[2] = (-pInReport->payload.deckState.sGyroY / 32768.0f) * (2000.0f * (SDL_PI_F / 180.0f)); + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, ctx->sensor_timestamp_us, values, 3); + + values[0] = (pInReport->payload.deckState.sAccelX / 32768.0f) * 2.0f * SDL_STANDARD_GRAVITY; + values[1] = (pInReport->payload.deckState.sAccelZ / 32768.0f) * 2.0f * SDL_STANDARD_GRAVITY; + values[2] = (-pInReport->payload.deckState.sAccelY / 32768.0f) * 2.0f * SDL_STANDARD_GRAVITY; + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, ctx->sensor_timestamp_us, values, 3); +} + +/*****************************************************************************************************/ + +static void HIDAPI_DriverSteamDeck_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAMDECK, callback, userdata); +} + +static void HIDAPI_DriverSteamDeck_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAMDECK, callback, userdata); +} + +static bool HIDAPI_DriverSteamDeck_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_STEAMDECK, + SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)); +} + +static bool HIDAPI_DriverSteamDeck_IsSupportedDevice( + SDL_HIDAPI_Device *device, + const char *name, + SDL_GamepadType type, + Uint16 vendor_id, + Uint16 product_id, + Uint16 version, + int interface_number, + int interface_class, + int interface_subclass, + int interface_protocol) +{ + return SDL_IsJoystickSteamDeck(vendor_id, product_id); +} + +static bool HIDAPI_DriverSteamDeck_InitDevice(SDL_HIDAPI_Device *device) +{ + int size; + Uint8 data[64]; + SDL_DriverSteamDeck_Context *ctx; + + ctx = (SDL_DriverSteamDeck_Context *)SDL_calloc(1, sizeof(*ctx)); + if (ctx == NULL) { + return false; + } + + // Always 1kHz according to USB descriptor, but actually about 4 ms. + ctx->update_rate_us = 4000; + + device->context = ctx; + + // Read a report to see if this is the correct endpoint. + // Mouse, Keyboard and Controller have the same VID/PID but + // only the controller hidraw device receives hid reports. + size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 16); + if (size == 0) + return false; + + if (!DisableDeckLizardMode(device->dev)) + return false; + + HIDAPI_SetDeviceName(device, "Steam Deck"); + + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverSteamDeck_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverSteamDeck_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ +} + +static bool HIDAPI_DriverSteamDeck_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverSteamDeck_Context *ctx = (SDL_DriverSteamDeck_Context *)device->context; + SDL_Joystick *joystick = NULL; + int r; + uint8_t data[64]; + ValveInReport_t *pInReport = (ValveInReport_t *)data; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + if (joystick == NULL) { + return false; + } + } else { + return false; + } + + if (ctx->watchdog_counter++ > 200) { + ctx->watchdog_counter = 0; + if (!FeedDeckLizardWatchdog(device->dev)) + return false; + } + + SDL_memset(data, 0, sizeof(data)); + + do { + r = SDL_hid_read(device->dev, data, sizeof(data)); + + if (r < 0) { + // Failed to read from controller + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + return false; + } else if (r == 64 && + pInReport->header.unReportVersion == k_ValveInReportMsgVersion && + pInReport->header.ucType == ID_CONTROLLER_DECK_STATE && + pInReport->header.ucLength == 64) { + HIDAPI_DriverSteamDeck_HandleState(device, joystick, pInReport); + } + } while (r > 0); + + return true; +} + +static bool HIDAPI_DriverSteamDeck_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverSteamDeck_Context *ctx = (SDL_DriverSteamDeck_Context *)device->context; + float update_rate_in_hz = 1.0f / (float)(ctx->update_rate_us) * 1.0e6f; + + SDL_AssertJoysticksLocked(); + + // Initialize the joystick capabilities + joystick->nbuttons = SDL_GAMEPAD_NUM_STEAM_DECK_BUTTONS; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, update_rate_in_hz); + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, update_rate_in_hz); + + return true; +} + +static bool HIDAPI_DriverSteamDeck_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + int rc; + Uint8 buffer[HID_FEATURE_REPORT_BYTES + 1] = { 0 }; + FeatureReportMsg *msg = (FeatureReportMsg *)(buffer + 1); + + msg->header.type = ID_TRIGGER_RUMBLE_CMD; + msg->payload.simpleRumble.unRumbleType = 0; + msg->payload.simpleRumble.unIntensity = HAPTIC_INTENSITY_SYSTEM; + msg->payload.simpleRumble.unLeftMotorSpeed = low_frequency_rumble; + msg->payload.simpleRumble.unRightMotorSpeed = high_frequency_rumble; + msg->payload.simpleRumble.nLeftGain = 2; + msg->payload.simpleRumble.nRightGain = 0; + + rc = SDL_hid_send_feature_report(device->dev, buffer, sizeof(buffer)); + if (rc != sizeof(buffer)) + return false; + return true; +} + +static bool HIDAPI_DriverSteamDeck_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverSteamDeck_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + return SDL_JOYSTICK_CAP_RUMBLE; +} + +static bool HIDAPI_DriverSteamDeck_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverSteamDeck_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverSteamDeck_SetSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + // On steam deck, sensors are enabled by default. Nothing to do here. + return true; +} + +static void HIDAPI_DriverSteamDeck_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + // Lizard mode id automatically re-enabled by watchdog. Nothing to do here. +} + +static void HIDAPI_DriverSteamDeck_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSteamDeck = { + SDL_HINT_JOYSTICK_HIDAPI_STEAMDECK, + true, + HIDAPI_DriverSteamDeck_RegisterHints, + HIDAPI_DriverSteamDeck_UnregisterHints, + HIDAPI_DriverSteamDeck_IsEnabled, + HIDAPI_DriverSteamDeck_IsSupportedDevice, + HIDAPI_DriverSteamDeck_InitDevice, + HIDAPI_DriverSteamDeck_GetDevicePlayerIndex, + HIDAPI_DriverSteamDeck_SetDevicePlayerIndex, + HIDAPI_DriverSteamDeck_UpdateDevice, + HIDAPI_DriverSteamDeck_OpenJoystick, + HIDAPI_DriverSteamDeck_RumbleJoystick, + HIDAPI_DriverSteamDeck_RumbleJoystickTriggers, + HIDAPI_DriverSteamDeck_GetJoystickCapabilities, + HIDAPI_DriverSteamDeck_SetJoystickLED, + HIDAPI_DriverSteamDeck_SendJoystickEffect, + HIDAPI_DriverSteamDeck_SetSensorsEnabled, + HIDAPI_DriverSteamDeck_CloseJoystick, + HIDAPI_DriverSteamDeck_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_STEAMDECK + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_switch.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_switch.c new file mode 100644 index 00000000000..0e7b823c552 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_switch.c @@ -0,0 +1,2859 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +/* This driver supports the Nintendo Switch Pro controller. + Code and logic contributed by Valve Corporation under the SDL zlib license. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../../SDL_hints_c.h" +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" +#include "SDL_hidapi_nintendo.h" + +#ifdef SDL_JOYSTICK_HIDAPI_SWITCH + +// Define this if you want to log all packets from the controller +// #define DEBUG_SWITCH_PROTOCOL + +// Define this to get log output for rumble logic +// #define DEBUG_RUMBLE + +/* The initialization sequence doesn't appear to work correctly on Windows unless + the reads and writes are on the same thread. + + ... and now I can't reproduce this, so I'm leaving it in, but disabled for now. + */ +// #define SWITCH_SYNCHRONOUS_WRITES + +/* How often you can write rumble commands to the controller. + If you send commands more frequently than this, you can turn off the controller + in Bluetooth mode, or the motors can miss the command in USB mode. + */ +#define RUMBLE_WRITE_FREQUENCY_MS 30 + +// How often you have to refresh a long duration rumble to keep the motors running +#define RUMBLE_REFRESH_FREQUENCY_MS 50 + +#define SWITCH_GYRO_SCALE 14.2842f +#define SWITCH_ACCEL_SCALE 4096.f + +#define SWITCH_GYRO_SCALE_OFFSET 13371.0f +#define SWITCH_GYRO_SCALE_MULT 936.0f +#define SWITCH_ACCEL_SCALE_OFFSET 16384.0f +#define SWITCH_ACCEL_SCALE_MULT 4.0f + +enum +{ + SDL_GAMEPAD_BUTTON_SWITCH_SHARE = 11, + SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE1, + SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE1, + SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE2, + SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE2, + SDL_GAMEPAD_NUM_SWITCH_BUTTONS, +}; + +typedef enum +{ + k_eSwitchInputReportIDs_SubcommandReply = 0x21, + k_eSwitchInputReportIDs_FullControllerState = 0x30, + k_eSwitchInputReportIDs_FullControllerAndMcuState = 0x31, + k_eSwitchInputReportIDs_SimpleControllerState = 0x3F, + k_eSwitchInputReportIDs_CommandAck = 0x81, +} ESwitchInputReportIDs; + +typedef enum +{ + k_eSwitchOutputReportIDs_RumbleAndSubcommand = 0x01, + k_eSwitchOutputReportIDs_Rumble = 0x10, + k_eSwitchOutputReportIDs_Proprietary = 0x80, +} ESwitchOutputReportIDs; + +typedef enum +{ + k_eSwitchSubcommandIDs_BluetoothManualPair = 0x01, + k_eSwitchSubcommandIDs_RequestDeviceInfo = 0x02, + k_eSwitchSubcommandIDs_SetInputReportMode = 0x03, + k_eSwitchSubcommandIDs_SetHCIState = 0x06, + k_eSwitchSubcommandIDs_SPIFlashRead = 0x10, + k_eSwitchSubcommandIDs_SetPlayerLights = 0x30, + k_eSwitchSubcommandIDs_SetHomeLight = 0x38, + k_eSwitchSubcommandIDs_EnableIMU = 0x40, + k_eSwitchSubcommandIDs_SetIMUSensitivity = 0x41, + k_eSwitchSubcommandIDs_EnableVibration = 0x48, +} ESwitchSubcommandIDs; + +typedef enum +{ + k_eSwitchProprietaryCommandIDs_Status = 0x01, + k_eSwitchProprietaryCommandIDs_Handshake = 0x02, + k_eSwitchProprietaryCommandIDs_HighSpeed = 0x03, + k_eSwitchProprietaryCommandIDs_ForceUSB = 0x04, + k_eSwitchProprietaryCommandIDs_ClearUSB = 0x05, + k_eSwitchProprietaryCommandIDs_ResetMCU = 0x06, +} ESwitchProprietaryCommandIDs; + +#define k_unSwitchOutputPacketDataLength 49 +#define k_unSwitchMaxOutputPacketLength 64 +#define k_unSwitchBluetoothPacketLength k_unSwitchOutputPacketDataLength +#define k_unSwitchUSBPacketLength k_unSwitchMaxOutputPacketLength + +#define k_unSPIStickFactoryCalibrationStartOffset 0x603D +#define k_unSPIStickFactoryCalibrationEndOffset 0x604E +#define k_unSPIStickFactoryCalibrationLength (k_unSPIStickFactoryCalibrationEndOffset - k_unSPIStickFactoryCalibrationStartOffset + 1) + +#define k_unSPIStickUserCalibrationStartOffset 0x8010 +#define k_unSPIStickUserCalibrationEndOffset 0x8025 +#define k_unSPIStickUserCalibrationLength (k_unSPIStickUserCalibrationEndOffset - k_unSPIStickUserCalibrationStartOffset + 1) + +#define k_unSPIIMUScaleStartOffset 0x6020 +#define k_unSPIIMUScaleEndOffset 0x6037 +#define k_unSPIIMUScaleLength (k_unSPIIMUScaleEndOffset - k_unSPIIMUScaleStartOffset + 1) + +#define k_unSPIIMUUserScaleStartOffset 0x8026 +#define k_unSPIIMUUserScaleEndOffset 0x8039 +#define k_unSPIIMUUserScaleLength (k_unSPIIMUUserScaleEndOffset - k_unSPIIMUUserScaleStartOffset + 1) + +#pragma pack(1) +typedef struct +{ + Uint8 rgucButtons[2]; + Uint8 ucStickHat; + Uint8 rgucJoystickLeft[2]; + Uint8 rgucJoystickRight[2]; +} SwitchInputOnlyControllerStatePacket_t; + +typedef struct +{ + Uint8 rgucButtons[2]; + Uint8 ucStickHat; + Sint16 sJoystickLeft[2]; + Sint16 sJoystickRight[2]; +} SwitchSimpleStatePacket_t; + +typedef struct +{ + Uint8 ucCounter; + Uint8 ucBatteryAndConnection; + Uint8 rgucButtons[3]; + Uint8 rgucJoystickLeft[3]; + Uint8 rgucJoystickRight[3]; + Uint8 ucVibrationCode; +} SwitchControllerStatePacket_t; + +typedef struct +{ + SwitchControllerStatePacket_t controllerState; + + struct + { + Sint16 sAccelX; + Sint16 sAccelY; + Sint16 sAccelZ; + + Sint16 sGyroX; + Sint16 sGyroY; + Sint16 sGyroZ; + } imuState[3]; +} SwitchStatePacket_t; + +typedef struct +{ + Uint32 unAddress; + Uint8 ucLength; +} SwitchSPIOpData_t; + +typedef struct +{ + SwitchControllerStatePacket_t m_controllerState; + + Uint8 ucSubcommandAck; + Uint8 ucSubcommandID; + +#define k_unSubcommandDataBytes 35 + union + { + Uint8 rgucSubcommandData[k_unSubcommandDataBytes]; + + struct + { + SwitchSPIOpData_t opData; + Uint8 rgucReadData[k_unSubcommandDataBytes - sizeof(SwitchSPIOpData_t)]; + } spiReadData; + + struct + { + Uint8 rgucFirmwareVersion[2]; + Uint8 ucDeviceType; + Uint8 ucFiller1; + Uint8 rgucMACAddress[6]; + Uint8 ucFiller2; + Uint8 ucColorLocation; + } deviceInfo; + + struct + { + SwitchSPIOpData_t opData; + Uint8 rgucLeftCalibration[9]; + Uint8 rgucRightCalibration[9]; + } stickFactoryCalibration; + + struct + { + SwitchSPIOpData_t opData; + Uint8 rgucLeftMagic[2]; + Uint8 rgucLeftCalibration[9]; + Uint8 rgucRightMagic[2]; + Uint8 rgucRightCalibration[9]; + } stickUserCalibration; + }; +} SwitchSubcommandInputPacket_t; + +typedef struct +{ + Uint8 ucPacketType; + Uint8 ucCommandID; + Uint8 ucFiller; + + Uint8 ucDeviceType; + Uint8 rgucMACAddress[6]; +} SwitchProprietaryStatusPacket_t; + +typedef struct +{ + Uint8 rgucData[4]; +} SwitchRumbleData_t; + +typedef struct +{ + Uint8 ucPacketType; + Uint8 ucPacketNumber; + SwitchRumbleData_t rumbleData[2]; +} SwitchCommonOutputPacket_t; + +typedef struct +{ + SwitchCommonOutputPacket_t commonData; + + Uint8 ucSubcommandID; + Uint8 rgucSubcommandData[k_unSwitchOutputPacketDataLength - sizeof(SwitchCommonOutputPacket_t) - 1]; +} SwitchSubcommandOutputPacket_t; + +typedef struct +{ + Uint8 ucPacketType; + Uint8 ucProprietaryID; + + Uint8 rgucProprietaryData[k_unSwitchOutputPacketDataLength - 1 - 1]; +} SwitchProprietaryOutputPacket_t; +#pragma pack() + +/* Enhanced report hint mode: + * "0": enhanced features are never used + * "1": enhanced features are always used + * "auto": enhanced features are advertised to the application, but SDL doesn't touch the controller state unless the application explicitly requests it. + */ +typedef enum +{ + SWITCH_ENHANCED_REPORT_HINT_OFF, + SWITCH_ENHANCED_REPORT_HINT_ON, + SWITCH_ENHANCED_REPORT_HINT_AUTO +} HIDAPI_Switch_EnhancedReportHint; + +typedef struct +{ + SDL_HIDAPI_Device *device; + SDL_Joystick *joystick; + bool m_bInputOnly; + bool m_bUseButtonLabels; + bool m_bPlayerLights; + int m_nPlayerIndex; + bool m_bSyncWrite; + int m_nMaxWriteAttempts; + ESwitchDeviceInfoControllerType m_eControllerType; + Uint8 m_nInitialInputMode; + Uint8 m_nCurrentInputMode; + Uint8 m_rgucMACAddress[6]; + Uint8 m_nCommandNumber; + HIDAPI_Switch_EnhancedReportHint m_eEnhancedReportHint; + bool m_bEnhancedMode; + bool m_bEnhancedModeAvailable; + SwitchCommonOutputPacket_t m_RumblePacket; + Uint8 m_rgucReadBuffer[k_unSwitchMaxOutputPacketLength]; + bool m_bRumbleActive; + Uint64 m_ulRumbleSent; + bool m_bRumblePending; + bool m_bRumbleZeroPending; + Uint32 m_unRumblePending; + bool m_bSensorsSupported; + bool m_bReportSensors; + bool m_bHasSensorData; + Uint64 m_ulLastInput; + Uint64 m_ulLastIMUReset; + Uint64 m_ulIMUSampleTimestampNS; + Uint32 m_unIMUSamples; + Uint64 m_ulIMUUpdateIntervalNS; + Uint64 m_ulTimestampNS; + bool m_bVerticalMode; + + SwitchInputOnlyControllerStatePacket_t m_lastInputOnlyState; + SwitchSimpleStatePacket_t m_lastSimpleState; + SwitchStatePacket_t m_lastFullState; + + struct StickCalibrationData + { + struct + { + Sint16 sCenter; + Sint16 sMin; + Sint16 sMax; + } axis[2]; + } m_StickCalData[2]; + + struct StickExtents + { + struct + { + Sint16 sMin; + Sint16 sMax; + } axis[2]; + } m_StickExtents[2], m_SimpleStickExtents[2]; + + struct IMUScaleData + { + float fAccelScaleX; + float fAccelScaleY; + float fAccelScaleZ; + + float fGyroScaleX; + float fGyroScaleY; + float fGyroScaleZ; + } m_IMUScaleData; +} SDL_DriverSwitch_Context; + +static int ReadInput(SDL_DriverSwitch_Context *ctx) +{ + int result; + + // Make sure we don't try to read at the same time a write is happening + if (SDL_GetAtomicInt(&ctx->device->rumble_pending) > 0) { + return 0; + } + + result = SDL_hid_read_timeout(ctx->device->dev, ctx->m_rgucReadBuffer, sizeof(ctx->m_rgucReadBuffer), 0); + + // See if we can guess the initial input mode + if (result > 0 && !ctx->m_bInputOnly && !ctx->m_nInitialInputMode) { + switch (ctx->m_rgucReadBuffer[0]) { + case k_eSwitchInputReportIDs_FullControllerState: + case k_eSwitchInputReportIDs_FullControllerAndMcuState: + case k_eSwitchInputReportIDs_SimpleControllerState: + ctx->m_nInitialInputMode = ctx->m_rgucReadBuffer[0]; + break; + default: + break; + } + } + return result; +} + +static int WriteOutput(SDL_DriverSwitch_Context *ctx, const Uint8 *data, int size) +{ +#ifdef SWITCH_SYNCHRONOUS_WRITES + return SDL_hid_write(ctx->device->dev, data, size); +#else + // Use the rumble thread for general asynchronous writes + if (!SDL_HIDAPI_LockRumble()) { + return -1; + } + return SDL_HIDAPI_SendRumbleAndUnlock(ctx->device, data, size); +#endif // SWITCH_SYNCHRONOUS_WRITES +} + +static SwitchSubcommandInputPacket_t *ReadSubcommandReply(SDL_DriverSwitch_Context *ctx, ESwitchSubcommandIDs expectedID) +{ + // Average response time for messages is ~30ms + Uint64 endTicks = SDL_GetTicks() + 100; + + int nRead = 0; + while ((nRead = ReadInput(ctx)) != -1) { + if (nRead > 0) { + if (ctx->m_rgucReadBuffer[0] == k_eSwitchInputReportIDs_SubcommandReply) { + SwitchSubcommandInputPacket_t *reply = (SwitchSubcommandInputPacket_t *)&ctx->m_rgucReadBuffer[1]; + if (reply->ucSubcommandID == expectedID && (reply->ucSubcommandAck & 0x80)) { + return reply; + } + } + } else { + SDL_Delay(1); + } + + if (SDL_GetTicks() >= endTicks) { + break; + } + } + return NULL; +} + +static bool ReadProprietaryReply(SDL_DriverSwitch_Context *ctx, ESwitchProprietaryCommandIDs expectedID) +{ + // Average response time for messages is ~30ms + Uint64 endTicks = SDL_GetTicks() + 100; + + int nRead = 0; + while ((nRead = ReadInput(ctx)) != -1) { + if (nRead > 0) { + if (ctx->m_rgucReadBuffer[0] == k_eSwitchInputReportIDs_CommandAck && ctx->m_rgucReadBuffer[1] == expectedID) { + return true; + } + } else { + SDL_Delay(1); + } + + if (SDL_GetTicks() >= endTicks) { + break; + } + } + return false; +} + +static void ConstructSubcommand(SDL_DriverSwitch_Context *ctx, ESwitchSubcommandIDs ucCommandID, const Uint8 *pBuf, Uint8 ucLen, SwitchSubcommandOutputPacket_t *outPacket) +{ + SDL_memset(outPacket, 0, sizeof(*outPacket)); + + outPacket->commonData.ucPacketType = k_eSwitchOutputReportIDs_RumbleAndSubcommand; + outPacket->commonData.ucPacketNumber = ctx->m_nCommandNumber; + + SDL_memcpy(outPacket->commonData.rumbleData, ctx->m_RumblePacket.rumbleData, sizeof(ctx->m_RumblePacket.rumbleData)); + + outPacket->ucSubcommandID = ucCommandID; + if (pBuf) { + SDL_memcpy(outPacket->rgucSubcommandData, pBuf, ucLen); + } + + ctx->m_nCommandNumber = (ctx->m_nCommandNumber + 1) & 0xF; +} + +static bool WritePacket(SDL_DriverSwitch_Context *ctx, void *pBuf, Uint8 ucLen) +{ + Uint8 rgucBuf[k_unSwitchMaxOutputPacketLength]; + const size_t unWriteSize = ctx->device->is_bluetooth ? k_unSwitchBluetoothPacketLength : k_unSwitchUSBPacketLength; + + if (ucLen > k_unSwitchOutputPacketDataLength) { + return false; + } + + if (ucLen < unWriteSize) { + SDL_memcpy(rgucBuf, pBuf, ucLen); + SDL_memset(rgucBuf + ucLen, 0, unWriteSize - ucLen); + pBuf = rgucBuf; + ucLen = (Uint8)unWriteSize; + } + if (ctx->m_bSyncWrite) { + return SDL_hid_write(ctx->device->dev, (Uint8 *)pBuf, ucLen) >= 0; + } else { + return WriteOutput(ctx, (Uint8 *)pBuf, ucLen) >= 0; + } +} + +static bool WriteSubcommand(SDL_DriverSwitch_Context *ctx, ESwitchSubcommandIDs ucCommandID, const Uint8 *pBuf, Uint8 ucLen, SwitchSubcommandInputPacket_t **ppReply) +{ + SwitchSubcommandInputPacket_t *reply = NULL; + int nTries; + + for (nTries = 1; !reply && nTries <= ctx->m_nMaxWriteAttempts; ++nTries) { + SwitchSubcommandOutputPacket_t commandPacket; + ConstructSubcommand(ctx, ucCommandID, pBuf, ucLen, &commandPacket); + + if (!WritePacket(ctx, &commandPacket, sizeof(commandPacket))) { + continue; + } + + reply = ReadSubcommandReply(ctx, ucCommandID); + } + + if (ppReply) { + *ppReply = reply; + } + return reply != NULL; +} + +static bool WriteProprietary(SDL_DriverSwitch_Context *ctx, ESwitchProprietaryCommandIDs ucCommand, Uint8 *pBuf, Uint8 ucLen, bool waitForReply) +{ + int nTries; + + for (nTries = 1; nTries <= ctx->m_nMaxWriteAttempts; ++nTries) { + SwitchProprietaryOutputPacket_t packet; + + if ((!pBuf && ucLen > 0) || ucLen > sizeof(packet.rgucProprietaryData)) { + return false; + } + + SDL_zero(packet); + packet.ucPacketType = k_eSwitchOutputReportIDs_Proprietary; + packet.ucProprietaryID = ucCommand; + if (pBuf) { + SDL_memcpy(packet.rgucProprietaryData, pBuf, ucLen); + } + + if (!WritePacket(ctx, &packet, sizeof(packet))) { + continue; + } + + if (!waitForReply || ReadProprietaryReply(ctx, ucCommand)) { + // SDL_Log("Succeeded%s after %d tries", ctx->m_bSyncWrite ? " (sync)" : "", nTries); + return true; + } + } + // SDL_Log("Failed%s after %d tries", ctx->m_bSyncWrite ? " (sync)" : "", nTries); + return false; +} + +static Uint8 EncodeRumbleHighAmplitude(Uint16 amplitude) +{ + /* More information about these values can be found here: + * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md + */ + Uint16 hfa[101][2] = { { 0, 0x0 }, { 514, 0x2 }, { 775, 0x4 }, { 921, 0x6 }, { 1096, 0x8 }, { 1303, 0x0a }, { 1550, 0x0c }, { 1843, 0x0e }, { 2192, 0x10 }, { 2606, 0x12 }, { 3100, 0x14 }, { 3686, 0x16 }, { 4383, 0x18 }, { 5213, 0x1a }, { 6199, 0x1c }, { 7372, 0x1e }, { 7698, 0x20 }, { 8039, 0x22 }, { 8395, 0x24 }, { 8767, 0x26 }, { 9155, 0x28 }, { 9560, 0x2a }, { 9984, 0x2c }, { 10426, 0x2e }, { 10887, 0x30 }, { 11369, 0x32 }, { 11873, 0x34 }, { 12398, 0x36 }, { 12947, 0x38 }, { 13520, 0x3a }, { 14119, 0x3c }, { 14744, 0x3e }, { 15067, 0x40 }, { 15397, 0x42 }, { 15734, 0x44 }, { 16079, 0x46 }, { 16431, 0x48 }, { 16790, 0x4a }, { 17158, 0x4c }, { 17534, 0x4e }, { 17918, 0x50 }, { 18310, 0x52 }, { 18711, 0x54 }, { 19121, 0x56 }, { 19540, 0x58 }, { 19967, 0x5a }, { 20405, 0x5c }, { 20851, 0x5e }, { 21308, 0x60 }, { 21775, 0x62 }, { 22251, 0x64 }, { 22739, 0x66 }, { 23236, 0x68 }, { 23745, 0x6a }, { 24265, 0x6c }, { 24797, 0x6e }, { 25340, 0x70 }, { 25894, 0x72 }, { 26462, 0x74 }, { 27041, 0x76 }, { 27633, 0x78 }, { 28238, 0x7a }, { 28856, 0x7c }, { 29488, 0x7e }, { 30134, 0x80 }, { 30794, 0x82 }, { 31468, 0x84 }, { 32157, 0x86 }, { 32861, 0x88 }, { 33581, 0x8a }, { 34316, 0x8c }, { 35068, 0x8e }, { 35836, 0x90 }, { 36620, 0x92 }, { 37422, 0x94 }, { 38242, 0x96 }, { 39079, 0x98 }, { 39935, 0x9a }, { 40809, 0x9c }, { 41703, 0x9e }, { 42616, 0xa0 }, { 43549, 0xa2 }, { 44503, 0xa4 }, { 45477, 0xa6 }, { 46473, 0xa8 }, { 47491, 0xaa }, { 48531, 0xac }, { 49593, 0xae }, { 50679, 0xb0 }, { 51789, 0xb2 }, { 52923, 0xb4 }, { 54082, 0xb6 }, { 55266, 0xb8 }, { 56476, 0xba }, { 57713, 0xbc }, { 58977, 0xbe }, { 60268, 0xc0 }, { 61588, 0xc2 }, { 62936, 0xc4 }, { 64315, 0xc6 }, { 65535, 0xc8 } }; + int index = 0; + for (; index < 101; index++) { + if (amplitude <= hfa[index][0]) { + return (Uint8)hfa[index][1]; + } + } + return (Uint8)hfa[100][1]; +} + +static Uint16 EncodeRumbleLowAmplitude(Uint16 amplitude) +{ + /* More information about these values can be found here: + * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md + */ + Uint16 lfa[101][2] = { { 0, 0x0040 }, { 514, 0x8040 }, { 775, 0x0041 }, { 921, 0x8041 }, { 1096, 0x0042 }, { 1303, 0x8042 }, { 1550, 0x0043 }, { 1843, 0x8043 }, { 2192, 0x0044 }, { 2606, 0x8044 }, { 3100, 0x0045 }, { 3686, 0x8045 }, { 4383, 0x0046 }, { 5213, 0x8046 }, { 6199, 0x0047 }, { 7372, 0x8047 }, { 7698, 0x0048 }, { 8039, 0x8048 }, { 8395, 0x0049 }, { 8767, 0x8049 }, { 9155, 0x004a }, { 9560, 0x804a }, { 9984, 0x004b }, { 10426, 0x804b }, { 10887, 0x004c }, { 11369, 0x804c }, { 11873, 0x004d }, { 12398, 0x804d }, { 12947, 0x004e }, { 13520, 0x804e }, { 14119, 0x004f }, { 14744, 0x804f }, { 15067, 0x0050 }, { 15397, 0x8050 }, { 15734, 0x0051 }, { 16079, 0x8051 }, { 16431, 0x0052 }, { 16790, 0x8052 }, { 17158, 0x0053 }, { 17534, 0x8053 }, { 17918, 0x0054 }, { 18310, 0x8054 }, { 18711, 0x0055 }, { 19121, 0x8055 }, { 19540, 0x0056 }, { 19967, 0x8056 }, { 20405, 0x0057 }, { 20851, 0x8057 }, { 21308, 0x0058 }, { 21775, 0x8058 }, { 22251, 0x0059 }, { 22739, 0x8059 }, { 23236, 0x005a }, { 23745, 0x805a }, { 24265, 0x005b }, { 24797, 0x805b }, { 25340, 0x005c }, { 25894, 0x805c }, { 26462, 0x005d }, { 27041, 0x805d }, { 27633, 0x005e }, { 28238, 0x805e }, { 28856, 0x005f }, { 29488, 0x805f }, { 30134, 0x0060 }, { 30794, 0x8060 }, { 31468, 0x0061 }, { 32157, 0x8061 }, { 32861, 0x0062 }, { 33581, 0x8062 }, { 34316, 0x0063 }, { 35068, 0x8063 }, { 35836, 0x0064 }, { 36620, 0x8064 }, { 37422, 0x0065 }, { 38242, 0x8065 }, { 39079, 0x0066 }, { 39935, 0x8066 }, { 40809, 0x0067 }, { 41703, 0x8067 }, { 42616, 0x0068 }, { 43549, 0x8068 }, { 44503, 0x0069 }, { 45477, 0x8069 }, { 46473, 0x006a }, { 47491, 0x806a }, { 48531, 0x006b }, { 49593, 0x806b }, { 50679, 0x006c }, { 51789, 0x806c }, { 52923, 0x006d }, { 54082, 0x806d }, { 55266, 0x006e }, { 56476, 0x806e }, { 57713, 0x006f }, { 58977, 0x806f }, { 60268, 0x0070 }, { 61588, 0x8070 }, { 62936, 0x0071 }, { 64315, 0x8071 }, { 65535, 0x0072 } }; + int index = 0; + for (; index < 101; index++) { + if (amplitude <= lfa[index][0]) { + return lfa[index][1]; + } + } + return lfa[100][1]; +} + +static void SetNeutralRumble(SwitchRumbleData_t *pRumble) +{ + pRumble->rgucData[0] = 0x00; + pRumble->rgucData[1] = 0x01; + pRumble->rgucData[2] = 0x40; + pRumble->rgucData[3] = 0x40; +} + +static void EncodeRumble(SwitchRumbleData_t *pRumble, Uint16 usHighFreq, Uint8 ucHighFreqAmp, Uint8 ucLowFreq, Uint16 usLowFreqAmp) +{ + if (ucHighFreqAmp > 0 || usLowFreqAmp > 0) { + // High-band frequency and low-band amplitude are actually nine-bits each so they + // take a bit from the high-band amplitude and low-band frequency bytes respectively + pRumble->rgucData[0] = usHighFreq & 0xFF; + pRumble->rgucData[1] = ucHighFreqAmp | ((usHighFreq >> 8) & 0x01); + + pRumble->rgucData[2] = ucLowFreq | ((usLowFreqAmp >> 8) & 0x80); + pRumble->rgucData[3] = usLowFreqAmp & 0xFF; + +#ifdef DEBUG_RUMBLE + SDL_Log("Freq: %.2X %.2X %.2X, Amp: %.2X %.2X %.2X", + usHighFreq & 0xFF, ((usHighFreq >> 8) & 0x01), ucLowFreq, + ucHighFreqAmp, ((usLowFreqAmp >> 8) & 0x80), usLowFreqAmp & 0xFF); +#endif + } else { + SetNeutralRumble(pRumble); + } +} + +static bool WriteRumble(SDL_DriverSwitch_Context *ctx) +{ + /* Write into m_RumblePacket rather than a temporary buffer to allow the current rumble state + * to be retained for subsequent rumble or subcommand packets sent to the controller + */ + ctx->m_RumblePacket.ucPacketType = k_eSwitchOutputReportIDs_Rumble; + ctx->m_RumblePacket.ucPacketNumber = ctx->m_nCommandNumber; + ctx->m_nCommandNumber = (ctx->m_nCommandNumber + 1) & 0xF; + + // Refresh the rumble state periodically + ctx->m_ulRumbleSent = SDL_GetTicks(); + + return WritePacket(ctx, (Uint8 *)&ctx->m_RumblePacket, sizeof(ctx->m_RumblePacket)); +} + +static ESwitchDeviceInfoControllerType CalculateControllerType(SDL_DriverSwitch_Context *ctx, ESwitchDeviceInfoControllerType eControllerType) +{ + SDL_HIDAPI_Device *device = ctx->device; + + // The N64 controller reports as a Pro controller over USB + if (eControllerType == k_eSwitchDeviceInfoControllerType_ProController && + device->product_id == USB_PRODUCT_NINTENDO_N64_CONTROLLER) { + eControllerType = k_eSwitchDeviceInfoControllerType_N64; + } + + if (eControllerType == k_eSwitchDeviceInfoControllerType_Unknown) { + // This might be a Joy-Con that's missing from a charging grip slot + if (device->product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP) { + if (device->interface_number == 1) { + eControllerType = k_eSwitchDeviceInfoControllerType_JoyConLeft; + } else { + eControllerType = k_eSwitchDeviceInfoControllerType_JoyConRight; + } + } + } + return eControllerType; +} + +static bool BReadDeviceInfo(SDL_DriverSwitch_Context *ctx) +{ + SwitchSubcommandInputPacket_t *reply = NULL; + + if (ctx->device->is_bluetooth) { + if (WriteSubcommand(ctx, k_eSwitchSubcommandIDs_RequestDeviceInfo, NULL, 0, &reply)) { + // Byte 2: Controller ID (1=LJC, 2=RJC, 3=Pro) + ctx->m_eControllerType = CalculateControllerType(ctx, (ESwitchDeviceInfoControllerType)reply->deviceInfo.ucDeviceType); + + // Bytes 4-9: MAC address (big-endian) + SDL_memcpy(ctx->m_rgucMACAddress, reply->deviceInfo.rgucMACAddress, sizeof(ctx->m_rgucMACAddress)); + + return true; + } + } else { + if (WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_Status, NULL, 0, true)) { + SwitchProprietaryStatusPacket_t *status = (SwitchProprietaryStatusPacket_t *)&ctx->m_rgucReadBuffer[0]; + size_t i; + + ctx->m_eControllerType = CalculateControllerType(ctx, (ESwitchDeviceInfoControllerType)status->ucDeviceType); + + for (i = 0; i < sizeof(ctx->m_rgucMACAddress); ++i) { + ctx->m_rgucMACAddress[i] = status->rgucMACAddress[sizeof(ctx->m_rgucMACAddress) - i - 1]; + } + + return true; + } + } + return false; +} + +static bool BTrySetupUSB(SDL_DriverSwitch_Context *ctx) +{ + /* We have to send a connection handshake to the controller when communicating over USB + * before we're able to send it other commands. Luckily this command is not supported + * over Bluetooth, so we can use the controller's lack of response as a way to + * determine if the connection is over USB or Bluetooth + */ + if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_Handshake, NULL, 0, true)) { + return false; + } + if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_HighSpeed, NULL, 0, true)) { + // The 8BitDo M30 and SF30 Pro don't respond to this command, but otherwise work correctly + // return false; + } + if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_Handshake, NULL, 0, true)) { + // This fails on the right Joy-Con when plugged into the charging grip + // return false; + } + if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_ForceUSB, NULL, 0, false)) { + return false; + } + return true; +} + +static bool SetVibrationEnabled(SDL_DriverSwitch_Context *ctx, Uint8 enabled) +{ + return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_EnableVibration, &enabled, sizeof(enabled), NULL); +} +static bool SetInputMode(SDL_DriverSwitch_Context *ctx, Uint8 input_mode) +{ +#ifdef FORCE_SIMPLE_REPORTS + input_mode = k_eSwitchInputReportIDs_SimpleControllerState; +#endif +#ifdef FORCE_FULL_REPORTS + input_mode = k_eSwitchInputReportIDs_FullControllerState; +#endif + + if (input_mode == ctx->m_nCurrentInputMode) { + return true; + } else { + ctx->m_nCurrentInputMode = input_mode; + + return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SetInputReportMode, &input_mode, sizeof(input_mode), NULL); + } +} + +static bool SetHomeLED(SDL_DriverSwitch_Context *ctx, Uint8 brightness) +{ + Uint8 ucLedIntensity = 0; + Uint8 rgucBuffer[4]; + + if (brightness > 0) { + if (brightness < 65) { + ucLedIntensity = (brightness + 5) / 10; + } else { + ucLedIntensity = (Uint8)SDL_ceilf(0xF * SDL_powf((float)brightness / 100.f, 2.13f)); + } + } + + rgucBuffer[0] = (0x0 << 4) | 0x1; // 0 mini cycles (besides first), cycle duration 8ms + rgucBuffer[1] = ((ucLedIntensity & 0xF) << 4) | 0x0; // LED start intensity (0x0-0xF), 0 cycles (LED stays on at start intensity after first cycle) + rgucBuffer[2] = ((ucLedIntensity & 0xF) << 4) | 0x0; // First cycle LED intensity, 0x0 intensity for second cycle + rgucBuffer[3] = (0x0 << 4) | 0x0; // 8ms fade transition to first cycle, 8ms first cycle LED duration + + return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SetHomeLight, rgucBuffer, sizeof(rgucBuffer), NULL); +} + +static void SDLCALL SDL_HomeLEDHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)userdata; + + if (hint && *hint) { + int value; + + if (SDL_strchr(hint, '.') != NULL) { + value = (int)(100.0f * SDL_atof(hint)); + if (value > 255) { + value = 255; + } + } else if (SDL_GetStringBoolean(hint, true)) { + value = 100; + } else { + value = 0; + } + SetHomeLED(ctx, (Uint8)value); + } +} + +static void UpdateSlotLED(SDL_DriverSwitch_Context *ctx) +{ + if (!ctx->m_bInputOnly) { + Uint8 led_data = 0; + + if (ctx->m_bPlayerLights && ctx->m_nPlayerIndex >= 0) { + led_data = (1 << (ctx->m_nPlayerIndex % 4)); + } + WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SetPlayerLights, &led_data, sizeof(led_data), NULL); + } +} + +static void SDLCALL SDL_PlayerLEDHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)userdata; + bool bPlayerLights = SDL_GetStringBoolean(hint, true); + + if (bPlayerLights != ctx->m_bPlayerLights) { + ctx->m_bPlayerLights = bPlayerLights; + + UpdateSlotLED(ctx); + HIDAPI_UpdateDeviceProperties(ctx->device); + } +} + +static void GetInitialInputMode(SDL_DriverSwitch_Context *ctx) +{ + if (!ctx->m_nInitialInputMode) { + // This will set the initial input mode if it can + ReadInput(ctx); + } +} + +static Uint8 GetDefaultInputMode(SDL_DriverSwitch_Context *ctx) +{ + Uint8 input_mode; + + // Determine the desired input mode + if (ctx->m_nInitialInputMode) { + input_mode = ctx->m_nInitialInputMode; + } else { + if (ctx->device->is_bluetooth) { + input_mode = k_eSwitchInputReportIDs_SimpleControllerState; + } else { + input_mode = k_eSwitchInputReportIDs_FullControllerState; + } + } + + switch (ctx->m_eEnhancedReportHint) { + case SWITCH_ENHANCED_REPORT_HINT_OFF: + input_mode = k_eSwitchInputReportIDs_SimpleControllerState; + break; + case SWITCH_ENHANCED_REPORT_HINT_ON: + if (input_mode == k_eSwitchInputReportIDs_SimpleControllerState) { + input_mode = k_eSwitchInputReportIDs_FullControllerState; + } + break; + case SWITCH_ENHANCED_REPORT_HINT_AUTO: + /* Joy-Con controllers switch their thumbsticks into D-pad mode in simple mode, + * so let's enable full controller state for them. + */ + if (ctx->device->vendor_id == USB_VENDOR_NINTENDO && + (ctx->device->product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT || + ctx->device->product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT)) { + input_mode = k_eSwitchInputReportIDs_FullControllerState; + } + break; + } + + // Wired controllers break if they are put into simple controller state + if (input_mode == k_eSwitchInputReportIDs_SimpleControllerState && + !ctx->device->is_bluetooth) { + input_mode = k_eSwitchInputReportIDs_FullControllerState; + } + return input_mode; +} + +static Uint8 GetSensorInputMode(SDL_DriverSwitch_Context *ctx) +{ + Uint8 input_mode; + + // Determine the desired input mode + if (!ctx->m_nInitialInputMode || + ctx->m_nInitialInputMode == k_eSwitchInputReportIDs_SimpleControllerState) { + input_mode = k_eSwitchInputReportIDs_FullControllerState; + } else { + input_mode = ctx->m_nInitialInputMode; + } + return input_mode; +} + +static void UpdateInputMode(SDL_DriverSwitch_Context *ctx) +{ + Uint8 input_mode; + + if (ctx->m_bReportSensors) { + input_mode = GetSensorInputMode(ctx); + } else { + input_mode = GetDefaultInputMode(ctx); + } + SetInputMode(ctx, input_mode); +} + +static void SetEnhancedModeAvailable(SDL_DriverSwitch_Context *ctx) +{ + if (ctx->m_bEnhancedModeAvailable) { + return; + } + ctx->m_bEnhancedModeAvailable = true; + + if (ctx->m_bSensorsSupported) { + // Use the right sensor in the combined Joy-Con pair + if (!ctx->device->parent || + ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_GYRO, 200.0f); + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_ACCEL, 200.0f); + } + if (ctx->device->parent && + ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft) { + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_GYRO_L, 200.0f); + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_ACCEL_L, 200.0f); + } + if (ctx->device->parent && + ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_GYRO_R, 200.0f); + SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_ACCEL_R, 200.0f); + } + } +} + +static void SetEnhancedReportHint(SDL_DriverSwitch_Context *ctx, HIDAPI_Switch_EnhancedReportHint eEnhancedReportHint) +{ + ctx->m_eEnhancedReportHint = eEnhancedReportHint; + + switch (eEnhancedReportHint) { + case SWITCH_ENHANCED_REPORT_HINT_OFF: + ctx->m_bEnhancedMode = false; + break; + case SWITCH_ENHANCED_REPORT_HINT_ON: + SetEnhancedModeAvailable(ctx); + ctx->m_bEnhancedMode = true; + break; + case SWITCH_ENHANCED_REPORT_HINT_AUTO: + SetEnhancedModeAvailable(ctx); + break; + } + + UpdateInputMode(ctx); +} + +static void UpdateEnhancedModeOnEnhancedReport(SDL_DriverSwitch_Context *ctx) +{ + if (ctx->m_eEnhancedReportHint == SWITCH_ENHANCED_REPORT_HINT_AUTO) { + SetEnhancedReportHint(ctx, SWITCH_ENHANCED_REPORT_HINT_ON); + } +} + +static void UpdateEnhancedModeOnApplicationUsage(SDL_DriverSwitch_Context *ctx) +{ + if (ctx->m_eEnhancedReportHint == SWITCH_ENHANCED_REPORT_HINT_AUTO) { + SetEnhancedReportHint(ctx, SWITCH_ENHANCED_REPORT_HINT_ON); + } +} + +static void SDLCALL SDL_EnhancedReportsChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)userdata; + + if (hint && SDL_strcasecmp(hint, "auto") == 0) { + SetEnhancedReportHint(ctx, SWITCH_ENHANCED_REPORT_HINT_AUTO); + } else if (SDL_GetStringBoolean(hint, true)) { + SetEnhancedReportHint(ctx, SWITCH_ENHANCED_REPORT_HINT_ON); + } else { + SetEnhancedReportHint(ctx, SWITCH_ENHANCED_REPORT_HINT_OFF); + } +} + +static bool SetIMUEnabled(SDL_DriverSwitch_Context *ctx, bool enabled) +{ + Uint8 imu_data = enabled ? 1 : 0; + return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_EnableIMU, &imu_data, sizeof(imu_data), NULL); +} + +static bool LoadStickCalibration(SDL_DriverSwitch_Context *ctx) +{ + Uint8 *pLeftStickCal; + Uint8 *pRightStickCal; + size_t stick, axis; + SwitchSubcommandInputPacket_t *user_reply = NULL; + SwitchSubcommandInputPacket_t *factory_reply = NULL; + SwitchSPIOpData_t readUserParams; + SwitchSPIOpData_t readFactoryParams; + + // Read User Calibration Info + readUserParams.unAddress = k_unSPIStickUserCalibrationStartOffset; + readUserParams.ucLength = k_unSPIStickUserCalibrationLength; + + // This isn't readable on all controllers, so ignore failure + WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SPIFlashRead, (uint8_t *)&readUserParams, sizeof(readUserParams), &user_reply); + + // Read Factory Calibration Info + readFactoryParams.unAddress = k_unSPIStickFactoryCalibrationStartOffset; + readFactoryParams.ucLength = k_unSPIStickFactoryCalibrationLength; + + const int MAX_ATTEMPTS = 3; + for (int attempt = 0; ; ++attempt) { + if (!WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SPIFlashRead, (uint8_t *)&readFactoryParams, sizeof(readFactoryParams), &factory_reply)) { + return false; + } + + if (factory_reply->stickFactoryCalibration.opData.unAddress == k_unSPIStickFactoryCalibrationStartOffset) { + // We successfully read the calibration data + break; + } + + if (attempt == MAX_ATTEMPTS) { + return false; + } + } + + // Automatically select the user calibration if magic bytes are set + if (user_reply && user_reply->stickUserCalibration.rgucLeftMagic[0] == 0xB2 && user_reply->stickUserCalibration.rgucLeftMagic[1] == 0xA1) { + pLeftStickCal = user_reply->stickUserCalibration.rgucLeftCalibration; + } else { + pLeftStickCal = factory_reply->stickFactoryCalibration.rgucLeftCalibration; + } + + if (user_reply && user_reply->stickUserCalibration.rgucRightMagic[0] == 0xB2 && user_reply->stickUserCalibration.rgucRightMagic[1] == 0xA1) { + pRightStickCal = user_reply->stickUserCalibration.rgucRightCalibration; + } else { + pRightStickCal = factory_reply->stickFactoryCalibration.rgucRightCalibration; + } + + /* Stick calibration values are 12-bits each and are packed by bit + * For whatever reason the fields are in a different order for each stick + * Left: X-Max, Y-Max, X-Center, Y-Center, X-Min, Y-Min + * Right: X-Center, Y-Center, X-Min, Y-Min, X-Max, Y-Max + */ + + // Left stick + ctx->m_StickCalData[0].axis[0].sMax = ((pLeftStickCal[1] << 8) & 0xF00) | pLeftStickCal[0]; // X Axis max above center + ctx->m_StickCalData[0].axis[1].sMax = (pLeftStickCal[2] << 4) | (pLeftStickCal[1] >> 4); // Y Axis max above center + ctx->m_StickCalData[0].axis[0].sCenter = ((pLeftStickCal[4] << 8) & 0xF00) | pLeftStickCal[3]; // X Axis center + ctx->m_StickCalData[0].axis[1].sCenter = (pLeftStickCal[5] << 4) | (pLeftStickCal[4] >> 4); // Y Axis center + ctx->m_StickCalData[0].axis[0].sMin = ((pLeftStickCal[7] << 8) & 0xF00) | pLeftStickCal[6]; // X Axis min below center + ctx->m_StickCalData[0].axis[1].sMin = (pLeftStickCal[8] << 4) | (pLeftStickCal[7] >> 4); // Y Axis min below center + + // Right stick + ctx->m_StickCalData[1].axis[0].sCenter = ((pRightStickCal[1] << 8) & 0xF00) | pRightStickCal[0]; // X Axis center + ctx->m_StickCalData[1].axis[1].sCenter = (pRightStickCal[2] << 4) | (pRightStickCal[1] >> 4); // Y Axis center + ctx->m_StickCalData[1].axis[0].sMin = ((pRightStickCal[4] << 8) & 0xF00) | pRightStickCal[3]; // X Axis min below center + ctx->m_StickCalData[1].axis[1].sMin = (pRightStickCal[5] << 4) | (pRightStickCal[4] >> 4); // Y Axis min below center + ctx->m_StickCalData[1].axis[0].sMax = ((pRightStickCal[7] << 8) & 0xF00) | pRightStickCal[6]; // X Axis max above center + ctx->m_StickCalData[1].axis[1].sMax = (pRightStickCal[8] << 4) | (pRightStickCal[7] >> 4); // Y Axis max above center + + // Filter out any values that were uninitialized (0xFFF) in the SPI read + for (stick = 0; stick < 2; ++stick) { + for (axis = 0; axis < 2; ++axis) { + if (ctx->m_StickCalData[stick].axis[axis].sCenter == 0xFFF) { + ctx->m_StickCalData[stick].axis[axis].sCenter = 2048; + } + if (ctx->m_StickCalData[stick].axis[axis].sMax == 0xFFF) { + ctx->m_StickCalData[stick].axis[axis].sMax = (Sint16)(ctx->m_StickCalData[stick].axis[axis].sCenter * 0.7f); + } + if (ctx->m_StickCalData[stick].axis[axis].sMin == 0xFFF) { + ctx->m_StickCalData[stick].axis[axis].sMin = (Sint16)(ctx->m_StickCalData[stick].axis[axis].sCenter * 0.7f); + } + } + } + + for (stick = 0; stick < 2; ++stick) { + for (axis = 0; axis < 2; ++axis) { + ctx->m_StickExtents[stick].axis[axis].sMin = -(Sint16)(ctx->m_StickCalData[stick].axis[axis].sMin * 0.7f); + ctx->m_StickExtents[stick].axis[axis].sMax = (Sint16)(ctx->m_StickCalData[stick].axis[axis].sMax * 0.7f); + } + } + + for (stick = 0; stick < 2; ++stick) { + for (axis = 0; axis < 2; ++axis) { + ctx->m_SimpleStickExtents[stick].axis[axis].sMin = (Sint16)(SDL_MIN_SINT16 * 0.5f); + ctx->m_SimpleStickExtents[stick].axis[axis].sMax = (Sint16)(SDL_MAX_SINT16 * 0.5f); + } + } + + return true; +} + +static bool LoadIMUCalibration(SDL_DriverSwitch_Context *ctx) +{ + SwitchSubcommandInputPacket_t *reply = NULL; + + // Read Calibration Info + SwitchSPIOpData_t readParams; + readParams.unAddress = k_unSPIIMUScaleStartOffset; + readParams.ucLength = k_unSPIIMUScaleLength; + + if (WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SPIFlashRead, (uint8_t *)&readParams, sizeof(readParams), &reply)) { + Uint8 *pIMUScale; + Sint16 sAccelRawX, sAccelRawY, sAccelRawZ, sGyroRawX, sGyroRawY, sGyroRawZ; + + // IMU scale gives us multipliers for converting raw values to real world values + pIMUScale = reply->spiReadData.rgucReadData; + + sAccelRawX = (pIMUScale[1] << 8) | pIMUScale[0]; + sAccelRawY = (pIMUScale[3] << 8) | pIMUScale[2]; + sAccelRawZ = (pIMUScale[5] << 8) | pIMUScale[4]; + + sGyroRawX = (pIMUScale[13] << 8) | pIMUScale[12]; + sGyroRawY = (pIMUScale[15] << 8) | pIMUScale[14]; + sGyroRawZ = (pIMUScale[17] << 8) | pIMUScale[16]; + + // Check for user calibration data. If it's present and set, it'll override the factory settings + readParams.unAddress = k_unSPIIMUUserScaleStartOffset; + readParams.ucLength = k_unSPIIMUUserScaleLength; + if (WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SPIFlashRead, (uint8_t *)&readParams, sizeof(readParams), &reply) && (pIMUScale[0] | pIMUScale[1] << 8) == 0xA1B2) { + pIMUScale = reply->spiReadData.rgucReadData; + + sAccelRawX = (pIMUScale[3] << 8) | pIMUScale[2]; + sAccelRawY = (pIMUScale[5] << 8) | pIMUScale[4]; + sAccelRawZ = (pIMUScale[7] << 8) | pIMUScale[6]; + + sGyroRawX = (pIMUScale[15] << 8) | pIMUScale[14]; + sGyroRawY = (pIMUScale[17] << 8) | pIMUScale[16]; + sGyroRawZ = (pIMUScale[19] << 8) | pIMUScale[18]; + } + + // Accelerometer scale + ctx->m_IMUScaleData.fAccelScaleX = SWITCH_ACCEL_SCALE_MULT / (SWITCH_ACCEL_SCALE_OFFSET - (float)sAccelRawX) * SDL_STANDARD_GRAVITY; + ctx->m_IMUScaleData.fAccelScaleY = SWITCH_ACCEL_SCALE_MULT / (SWITCH_ACCEL_SCALE_OFFSET - (float)sAccelRawY) * SDL_STANDARD_GRAVITY; + ctx->m_IMUScaleData.fAccelScaleZ = SWITCH_ACCEL_SCALE_MULT / (SWITCH_ACCEL_SCALE_OFFSET - (float)sAccelRawZ) * SDL_STANDARD_GRAVITY; + + // Gyro scale + ctx->m_IMUScaleData.fGyroScaleX = SWITCH_GYRO_SCALE_MULT / (SWITCH_GYRO_SCALE_OFFSET - (float)sGyroRawX) * SDL_PI_F / 180.0f; + ctx->m_IMUScaleData.fGyroScaleY = SWITCH_GYRO_SCALE_MULT / (SWITCH_GYRO_SCALE_OFFSET - (float)sGyroRawY) * SDL_PI_F / 180.0f; + ctx->m_IMUScaleData.fGyroScaleZ = SWITCH_GYRO_SCALE_MULT / (SWITCH_GYRO_SCALE_OFFSET - (float)sGyroRawZ) * SDL_PI_F / 180.0f; + + } else { + // Use default values + const float accelScale = SDL_STANDARD_GRAVITY / SWITCH_ACCEL_SCALE; + const float gyroScale = SDL_PI_F / 180.0f / SWITCH_GYRO_SCALE; + + ctx->m_IMUScaleData.fAccelScaleX = accelScale; + ctx->m_IMUScaleData.fAccelScaleY = accelScale; + ctx->m_IMUScaleData.fAccelScaleZ = accelScale; + + ctx->m_IMUScaleData.fGyroScaleX = gyroScale; + ctx->m_IMUScaleData.fGyroScaleY = gyroScale; + ctx->m_IMUScaleData.fGyroScaleZ = gyroScale; + } + return true; +} + +static Sint16 ApplyStickCalibration(SDL_DriverSwitch_Context *ctx, int nStick, int nAxis, Sint16 sRawValue) +{ + sRawValue -= ctx->m_StickCalData[nStick].axis[nAxis].sCenter; + + if (sRawValue > ctx->m_StickExtents[nStick].axis[nAxis].sMax) { + ctx->m_StickExtents[nStick].axis[nAxis].sMax = sRawValue; + } + if (sRawValue < ctx->m_StickExtents[nStick].axis[nAxis].sMin) { + ctx->m_StickExtents[nStick].axis[nAxis].sMin = sRawValue; + } + + return (Sint16)HIDAPI_RemapVal(sRawValue, ctx->m_StickExtents[nStick].axis[nAxis].sMin, ctx->m_StickExtents[nStick].axis[nAxis].sMax, SDL_MIN_SINT16, SDL_MAX_SINT16); +} + +static Sint16 ApplySimpleStickCalibration(SDL_DriverSwitch_Context *ctx, int nStick, int nAxis, Sint16 sRawValue) +{ + // 0x8000 is the neutral value for all joystick axes + const Uint16 usJoystickCenter = 0x8000; + + sRawValue -= usJoystickCenter; + + if (sRawValue > ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMax) { + ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMax = sRawValue; + } + if (sRawValue < ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMin) { + ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMin = sRawValue; + } + + return (Sint16)HIDAPI_RemapVal(sRawValue, ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMin, ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMax, SDL_MIN_SINT16, SDL_MAX_SINT16); +} + +static Uint8 RemapButton(SDL_DriverSwitch_Context *ctx, Uint8 button) +{ + if (ctx->m_bUseButtonLabels) { + // Use button labels instead of positions, e.g. Nintendo Online Classic controllers + switch (button) { + case SDL_GAMEPAD_BUTTON_SOUTH: + return SDL_GAMEPAD_BUTTON_EAST; + case SDL_GAMEPAD_BUTTON_EAST: + return SDL_GAMEPAD_BUTTON_SOUTH; + case SDL_GAMEPAD_BUTTON_WEST: + return SDL_GAMEPAD_BUTTON_NORTH; + case SDL_GAMEPAD_BUTTON_NORTH: + return SDL_GAMEPAD_BUTTON_WEST; + default: + break; + } + } + return button; +} + +static int GetMaxWriteAttempts(SDL_HIDAPI_Device *device) +{ + if (device->vendor_id == USB_VENDOR_NINTENDO && + device->product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP) { + // This device is a little slow and we know we're always on USB + return 20; + } else { + return 5; + } +} + +static ESwitchDeviceInfoControllerType ReadJoyConControllerType(SDL_HIDAPI_Device *device) +{ + ESwitchDeviceInfoControllerType eControllerType = k_eSwitchDeviceInfoControllerType_Unknown; + const int MAX_ATTEMPTS = 1; // Don't try too long, in case this is a zombie Bluetooth controller + int attempts = 0; + + // Create enough of a context to read the controller type from the device + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)SDL_calloc(1, sizeof(*ctx)); + if (ctx) { + ctx->device = device; + ctx->m_bSyncWrite = true; + ctx->m_nMaxWriteAttempts = GetMaxWriteAttempts(device); + + for ( ; ; ) { + ++attempts; + if (device->is_bluetooth) { + SwitchSubcommandInputPacket_t *reply = NULL; + + if (WriteSubcommand(ctx, k_eSwitchSubcommandIDs_RequestDeviceInfo, NULL, 0, &reply)) { + eControllerType = CalculateControllerType(ctx, (ESwitchDeviceInfoControllerType)reply->deviceInfo.ucDeviceType); + } + } else { + if (WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_Status, NULL, 0, true)) { + SwitchProprietaryStatusPacket_t *status = (SwitchProprietaryStatusPacket_t *)&ctx->m_rgucReadBuffer[0]; + + eControllerType = CalculateControllerType(ctx, (ESwitchDeviceInfoControllerType)status->ucDeviceType); + } + } + if (eControllerType == k_eSwitchDeviceInfoControllerType_Unknown && attempts < MAX_ATTEMPTS) { + // Wait a bit and try again + SDL_Delay(100); + continue; + } + break; + } + SDL_free(ctx); + } + return eControllerType; +} + +static bool HasHomeLED(SDL_DriverSwitch_Context *ctx) +{ + Uint16 vendor_id = ctx->device->vendor_id; + Uint16 product_id = ctx->device->product_id; + + // The Power A Nintendo Switch Pro controllers don't have a Home LED + if (vendor_id == 0 && product_id == 0) { + return false; + } + + // HORI Wireless Switch Pad + if (vendor_id == 0x0f0d && product_id == 0x00f6) { + return false; + } + + // Third party controllers don't have a home LED and will shut off if we try to set it + if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_Unknown || + ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_LicProController) { + return false; + } + + // The Nintendo Online classic controllers don't have a Home LED + if (vendor_id == USB_VENDOR_NINTENDO && + ctx->m_eControllerType > k_eSwitchDeviceInfoControllerType_ProController) { + return false; + } + + return true; +} + +static bool AlwaysUsesLabels(Uint16 vendor_id, Uint16 product_id, ESwitchDeviceInfoControllerType eControllerType) +{ + // Some controllers don't have a diamond button configuration, so should always use labels + if (SDL_IsJoystickGameCube(vendor_id, product_id)) { + return true; + } + switch (eControllerType) { + case k_eSwitchDeviceInfoControllerType_HVCLeft: + case k_eSwitchDeviceInfoControllerType_HVCRight: + case k_eSwitchDeviceInfoControllerType_NESLeft: + case k_eSwitchDeviceInfoControllerType_NESRight: + case k_eSwitchDeviceInfoControllerType_N64: + case k_eSwitchDeviceInfoControllerType_SEGA_Genesis: + return true; + default: + return false; + } +} + +static void HIDAPI_DriverNintendoClassic_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC, callback, userdata); +} + +static void HIDAPI_DriverNintendoClassic_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC, callback, userdata); +} + +static bool HIDAPI_DriverNintendoClassic_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)); +} + +static bool HIDAPI_DriverNintendoClassic_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + if (vendor_id == USB_VENDOR_NINTENDO) { + if (product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT) { + if (SDL_strncmp(name, "NES Controller", 14) == 0 || + SDL_strncmp(name, "HVC Controller", 14) == 0) { + return true; + } + } + + if (product_id == USB_PRODUCT_NINTENDO_N64_CONTROLLER) { + return true; + } + + if (product_id == USB_PRODUCT_NINTENDO_SEGA_GENESIS_CONTROLLER) { + return true; + } + + if (product_id == USB_PRODUCT_NINTENDO_SNES_CONTROLLER) { + return true; + } + } + + return false; +} + +static void HIDAPI_DriverJoyCons_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, callback, userdata); +} + +static void HIDAPI_DriverJoyCons_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, callback, userdata); +} + +static bool HIDAPI_DriverJoyCons_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)); +} + +static bool HIDAPI_DriverJoyCons_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + if (vendor_id == USB_VENDOR_NINTENDO) { + if (product_id == USB_PRODUCT_NINTENDO_SWITCH_PRO && device && device->dev) { + // This might be a Kinvoca Joy-Con that reports VID/PID as a Switch Pro controller + ESwitchDeviceInfoControllerType eControllerType = ReadJoyConControllerType(device); + if (eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft || + eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + return true; + } + } + + if (product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT || + product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT || + product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP) { + return true; + } + } + return false; +} + +static void HIDAPI_DriverSwitch_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, callback, userdata); +} + +static void HIDAPI_DriverSwitch_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, callback, userdata); +} + +static bool HIDAPI_DriverSwitch_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)); +} + +static bool HIDAPI_DriverSwitch_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + /* The HORI Wireless Switch Pad enumerates as a HID device when connected via USB + with the same VID/PID as when connected over Bluetooth but doesn't actually + support communication over USB. The most reliable way to block this without allowing the + controller to continually attempt to reconnect is to filter it out by manufacturer/product string. + Note that the controller does have a different product string when connected over Bluetooth. + */ + if (SDL_strcmp(name, "HORI Wireless Switch Pad") == 0) { + return false; + } + + // If it's handled by another driver, it's not handled here + if (HIDAPI_DriverNintendoClassic_IsSupportedDevice(device, name, type, vendor_id, product_id, version, interface_number, interface_class, interface_subclass, interface_protocol) || + HIDAPI_DriverJoyCons_IsSupportedDevice(device, name, type, vendor_id, product_id, version, interface_number, interface_class, interface_subclass, interface_protocol)) { + return false; + } + + return (type == SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO); +} + +static void UpdateDeviceIdentity(SDL_HIDAPI_Device *device) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; + + if (ctx->m_bInputOnly) { + if (SDL_IsJoystickGameCube(device->vendor_id, device->product_id)) { + device->type = SDL_GAMEPAD_TYPE_STANDARD; + } + } else { + char serial[18]; + + switch (ctx->m_eControllerType) { + case k_eSwitchDeviceInfoControllerType_JoyConLeft: + HIDAPI_SetDeviceName(device, "Nintendo Switch Joy-Con (L)"); + HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT); + device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT; + break; + case k_eSwitchDeviceInfoControllerType_JoyConRight: + HIDAPI_SetDeviceName(device, "Nintendo Switch Joy-Con (R)"); + HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT); + device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT; + break; + case k_eSwitchDeviceInfoControllerType_ProController: + case k_eSwitchDeviceInfoControllerType_LicProController: + HIDAPI_SetDeviceName(device, "Nintendo Switch Pro Controller"); + HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_PRO); + device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO; + break; + case k_eSwitchDeviceInfoControllerType_HVCLeft: + HIDAPI_SetDeviceName(device, "Nintendo HVC Controller (1)"); + device->type = SDL_GAMEPAD_TYPE_STANDARD; + break; + case k_eSwitchDeviceInfoControllerType_HVCRight: + HIDAPI_SetDeviceName(device, "Nintendo HVC Controller (2)"); + device->type = SDL_GAMEPAD_TYPE_STANDARD; + break; + case k_eSwitchDeviceInfoControllerType_NESLeft: + HIDAPI_SetDeviceName(device, "Nintendo NES Controller (L)"); + device->type = SDL_GAMEPAD_TYPE_STANDARD; + break; + case k_eSwitchDeviceInfoControllerType_NESRight: + HIDAPI_SetDeviceName(device, "Nintendo NES Controller (R)"); + device->type = SDL_GAMEPAD_TYPE_STANDARD; + break; + case k_eSwitchDeviceInfoControllerType_SNES: + HIDAPI_SetDeviceName(device, "Nintendo SNES Controller"); + HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SNES_CONTROLLER); + device->type = SDL_GAMEPAD_TYPE_STANDARD; + break; + case k_eSwitchDeviceInfoControllerType_N64: + HIDAPI_SetDeviceName(device, "Nintendo N64 Controller"); + HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_N64_CONTROLLER); + device->type = SDL_GAMEPAD_TYPE_STANDARD; + break; + case k_eSwitchDeviceInfoControllerType_SEGA_Genesis: + HIDAPI_SetDeviceName(device, "Nintendo SEGA Genesis Controller"); + HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SEGA_GENESIS_CONTROLLER); + device->type = SDL_GAMEPAD_TYPE_STANDARD; + break; + case k_eSwitchDeviceInfoControllerType_Unknown: + // We couldn't read the device info for this controller, might not be fully compliant + if (device->vendor_id == USB_VENDOR_NINTENDO) { + switch (device->product_id) { + case USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT: + ctx->m_eControllerType = k_eSwitchDeviceInfoControllerType_JoyConLeft; + HIDAPI_SetDeviceName(device, "Nintendo Switch Joy-Con (L)"); + device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT; + break; + case USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT: + ctx->m_eControllerType = k_eSwitchDeviceInfoControllerType_JoyConRight; + HIDAPI_SetDeviceName(device, "Nintendo Switch Joy-Con (R)"); + device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT; + break; + case USB_PRODUCT_NINTENDO_SWITCH_PRO: + ctx->m_eControllerType = k_eSwitchDeviceInfoControllerType_ProController; + HIDAPI_SetDeviceName(device, "Nintendo Switch Pro Controller"); + device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO; + break; + default: + break; + } + } + return; + default: + device->type = SDL_GAMEPAD_TYPE_STANDARD; + break; + } + device->guid.data[15] = ctx->m_eControllerType; + + (void)SDL_snprintf(serial, sizeof(serial), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x", + ctx->m_rgucMACAddress[0], + ctx->m_rgucMACAddress[1], + ctx->m_rgucMACAddress[2], + ctx->m_rgucMACAddress[3], + ctx->m_rgucMACAddress[4], + ctx->m_rgucMACAddress[5]); + HIDAPI_SetDeviceSerial(device, serial); + } +} + +static bool HIDAPI_DriverSwitch_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverSwitch_Context *ctx; + + ctx = (SDL_DriverSwitch_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + device->context = ctx; + + ctx->m_nMaxWriteAttempts = GetMaxWriteAttempts(device); + ctx->m_bSyncWrite = true; + + // Find out whether or not we can send output reports + ctx->m_bInputOnly = SDL_IsJoystickNintendoSwitchProInputOnly(device->vendor_id, device->product_id); + if (!ctx->m_bInputOnly) { + // Initialize rumble data, important for reading device info on the MOBAPAD M073 + SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[0]); + SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[1]); + + BReadDeviceInfo(ctx); + } + UpdateDeviceIdentity(device); + + // Prefer the USB device over the Bluetooth device + if (device->is_bluetooth) { + if (HIDAPI_HasConnectedUSBDevice(device->serial)) { + return true; + } + } else { + HIDAPI_DisconnectBluetoothDevice(device->serial); + } + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverSwitch_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverSwitch_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; + + if (!ctx->joystick) { + return; + } + + ctx->m_nPlayerIndex = player_index; + + UpdateSlotLED(ctx); +} + +static bool HIDAPI_DriverSwitch_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + ctx->joystick = joystick; + + ctx->m_bSyncWrite = true; + + if (!ctx->m_bInputOnly) { +#ifdef SDL_PLATFORM_MACOS + // Wait for the OS to finish its handshake with the controller + SDL_Delay(250); +#endif + GetInitialInputMode(ctx); + ctx->m_nCurrentInputMode = ctx->m_nInitialInputMode; + + // Initialize rumble data + SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[0]); + SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[1]); + + if (!device->is_bluetooth) { + if (!BTrySetupUSB(ctx)) { + SDL_SetError("Couldn't setup USB mode"); + return false; + } + } + + if (!LoadStickCalibration(ctx)) { + SDL_SetError("Couldn't load stick calibration"); + return false; + } + + if (ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_HVCLeft && + ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_HVCRight && + ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_NESLeft && + ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_NESRight && + ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_SNES && + ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_N64 && + ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_SEGA_Genesis) { + if (LoadIMUCalibration(ctx)) { + ctx->m_bSensorsSupported = true; + } + } + + // Enable vibration + SetVibrationEnabled(ctx, 1); + + // Set desired input mode + SDL_AddHintCallback(SDL_HINT_JOYSTICK_ENHANCED_REPORTS, + SDL_EnhancedReportsChanged, ctx); + + // Start sending USB reports + if (!device->is_bluetooth) { + // ForceUSB doesn't generate an ACK, so don't wait for a reply + if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_ForceUSB, NULL, 0, false)) { + SDL_SetError("Couldn't start USB reports"); + return false; + } + } + + // Set the LED state + if (HasHomeLED(ctx)) { + if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft || + ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_JOYCON_HOME_LED, + SDL_HomeLEDHintChanged, ctx); + } else { + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_HOME_LED, + SDL_HomeLEDHintChanged, ctx); + } + } + } + + if (AlwaysUsesLabels(device->vendor_id, device->product_id, ctx->m_eControllerType)) { + ctx->m_bUseButtonLabels = true; + } + + // Initialize player index (needed for setting LEDs) + ctx->m_nPlayerIndex = SDL_GetJoystickPlayerIndex(joystick); + ctx->m_bPlayerLights = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED, true); + UpdateSlotLED(ctx); + + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED, + SDL_PlayerLEDHintChanged, ctx); + + // Initialize the joystick capabilities + joystick->nbuttons = SDL_GAMEPAD_NUM_SWITCH_BUTTONS; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + + // Set up for input + ctx->m_bSyncWrite = false; + ctx->m_ulLastIMUReset = ctx->m_ulLastInput = SDL_GetTicks(); + ctx->m_ulIMUUpdateIntervalNS = SDL_MS_TO_NS(5); // Start off at 5 ms update rate + + // Set up for vertical mode + ctx->m_bVerticalMode = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_VERTICAL_JOY_CONS, false); + + return true; +} + +static bool HIDAPI_DriverSwitch_ActuallyRumbleJoystick(SDL_DriverSwitch_Context *ctx, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + /* Experimentally determined rumble values. These will only matter on some controllers as tested ones + * seem to disregard these and just use any non-zero rumble values as a binary flag for constant rumble + * + * More information about these values can be found here: + * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md + */ + const Uint16 k_usHighFreq = 0x0074; + const Uint8 k_ucHighFreqAmp = EncodeRumbleHighAmplitude(high_frequency_rumble); + const Uint8 k_ucLowFreq = 0x3D; + const Uint16 k_usLowFreqAmp = EncodeRumbleLowAmplitude(low_frequency_rumble); + + if (low_frequency_rumble || high_frequency_rumble) { + EncodeRumble(&ctx->m_RumblePacket.rumbleData[0], k_usHighFreq, k_ucHighFreqAmp, k_ucLowFreq, k_usLowFreqAmp); + EncodeRumble(&ctx->m_RumblePacket.rumbleData[1], k_usHighFreq, k_ucHighFreqAmp, k_ucLowFreq, k_usLowFreqAmp); + } else { + SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[0]); + SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[1]); + } + + ctx->m_bRumbleActive = (low_frequency_rumble || high_frequency_rumble); + + if (!WriteRumble(ctx)) { + return SDL_SetError("Couldn't send rumble packet"); + } + return true; +} + +static bool HIDAPI_DriverSwitch_SendPendingRumble(SDL_DriverSwitch_Context *ctx) +{ + if (SDL_GetTicks() < (ctx->m_ulRumbleSent + RUMBLE_WRITE_FREQUENCY_MS)) { + return true; + } + + if (ctx->m_bRumblePending) { + Uint16 low_frequency_rumble = (Uint16)(ctx->m_unRumblePending >> 16); + Uint16 high_frequency_rumble = (Uint16)ctx->m_unRumblePending; + +#ifdef DEBUG_RUMBLE + SDL_Log("Sent pending rumble %d/%d, %d ms after previous rumble", low_frequency_rumble, high_frequency_rumble, SDL_GetTicks() - ctx->m_ulRumbleSent); +#endif + ctx->m_bRumblePending = false; + ctx->m_unRumblePending = 0; + + return HIDAPI_DriverSwitch_ActuallyRumbleJoystick(ctx, low_frequency_rumble, high_frequency_rumble); + } + + if (ctx->m_bRumbleZeroPending) { + ctx->m_bRumbleZeroPending = false; + +#ifdef DEBUG_RUMBLE + SDL_Log("Sent pending zero rumble, %d ms after previous rumble", SDL_GetTicks() - ctx->m_ulRumbleSent); +#endif + return HIDAPI_DriverSwitch_ActuallyRumbleJoystick(ctx, 0, 0); + } + + return true; +} + +static bool HIDAPI_DriverSwitch_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; + + if (ctx->m_bInputOnly) { + return SDL_Unsupported(); + } + + if (device->parent) { + if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft) { + // Just handle low frequency rumble + high_frequency_rumble = 0; + } else if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + // Just handle high frequency rumble + low_frequency_rumble = 0; + } + } + + if (ctx->m_bRumblePending) { + if (!HIDAPI_DriverSwitch_SendPendingRumble(ctx)) { + return false; + } + } + + if (SDL_GetTicks() < (ctx->m_ulRumbleSent + RUMBLE_WRITE_FREQUENCY_MS)) { + if (low_frequency_rumble || high_frequency_rumble) { + Uint32 unRumblePending = ((Uint32)low_frequency_rumble << 16) | high_frequency_rumble; + + // Keep the highest rumble intensity in the given interval + if (unRumblePending > ctx->m_unRumblePending) { + ctx->m_unRumblePending = unRumblePending; + } + ctx->m_bRumblePending = true; + ctx->m_bRumbleZeroPending = false; + } else { + // When rumble is complete, turn it off + ctx->m_bRumbleZeroPending = true; + } + return true; + } + +#ifdef DEBUG_RUMBLE + SDL_Log("Sent rumble %d/%d", low_frequency_rumble, high_frequency_rumble); +#endif + + return HIDAPI_DriverSwitch_ActuallyRumbleJoystick(ctx, low_frequency_rumble, high_frequency_rumble); +} + +static bool HIDAPI_DriverSwitch_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverSwitch_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; + Uint32 result = 0; + + if (ctx->m_bPlayerLights && !ctx->m_bInputOnly) { + result |= SDL_JOYSTICK_CAP_PLAYER_LED; + } + + if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_ProController && !ctx->m_bInputOnly) { + // Doesn't have an RGB LED, so don't return SDL_JOYSTICK_CAP_RGB_LED here + result |= SDL_JOYSTICK_CAP_RUMBLE; + } else if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft || + ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + result |= SDL_JOYSTICK_CAP_RUMBLE; + } + return result; +} + +static bool HIDAPI_DriverSwitch_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverSwitch_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; + + if (size == sizeof(SwitchCommonOutputPacket_t)) { + const SwitchCommonOutputPacket_t *packet = (SwitchCommonOutputPacket_t *)data; + + if (packet->ucPacketType != k_eSwitchOutputReportIDs_Rumble) { + return SDL_SetError("Unknown Nintendo Switch Pro effect type"); + } + + SDL_copyp(&ctx->m_RumblePacket.rumbleData[0], &packet->rumbleData[0]); + SDL_copyp(&ctx->m_RumblePacket.rumbleData[1], &packet->rumbleData[1]); + if (!WriteRumble(ctx)) { + return false; + } + + // This overwrites any internal rumble + ctx->m_bRumblePending = false; + ctx->m_bRumbleZeroPending = false; + return true; + } else if (size >= 2 && size <= 256) { + const Uint8 *payload = (const Uint8 *)data; + ESwitchSubcommandIDs cmd = (ESwitchSubcommandIDs)payload[0]; + + if (cmd == k_eSwitchSubcommandIDs_SetInputReportMode && !device->is_bluetooth) { + // Going into simple mode over USB disables input reports, so don't do that + return true; + } + if (cmd == k_eSwitchSubcommandIDs_SetHomeLight && !HasHomeLED(ctx)) { + // Setting the home LED when it's not supported can cause the controller to reset + return true; + } + + if (!WriteSubcommand(ctx, cmd, &payload[1], (Uint8)(size - 1), NULL)) { + return false; + } + return true; + } + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverSwitch_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; + + UpdateEnhancedModeOnApplicationUsage(ctx); + + if (!ctx->m_bSensorsSupported || (enabled && !ctx->m_bEnhancedMode)) { + return SDL_Unsupported(); + } + + ctx->m_bReportSensors = enabled; + ctx->m_unIMUSamples = 0; + ctx->m_ulIMUSampleTimestampNS = SDL_GetTicksNS(); + + UpdateInputMode(ctx); + SetIMUEnabled(ctx, enabled); + + return true; +} + +static void HandleInputOnlyControllerState(SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchInputOnlyControllerStatePacket_t *packet) +{ + Sint16 axis; + Uint64 timestamp = SDL_GetTicksNS(); + + if (packet->rgucButtons[0] != ctx->m_lastInputOnlyState.rgucButtons[0]) { + Uint8 data = packet->rgucButtons[0]; + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x20) != 0)); + } + + if (packet->rgucButtons[1] != ctx->m_lastInputOnlyState.rgucButtons[1]) { + Uint8 data = packet->rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0)); + } + + if (packet->ucStickHat != ctx->m_lastInputOnlyState.ucStickHat) { + Uint8 hat; + + switch (packet->ucStickHat) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + axis = (packet->rgucButtons[0] & 0x40) ? 32767 : -32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + + axis = (packet->rgucButtons[0] & 0x80) ? 32767 : -32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + + if (packet->rgucJoystickLeft[0] != ctx->m_lastInputOnlyState.rgucJoystickLeft[0]) { + axis = (Sint16)HIDAPI_RemapVal(packet->rgucJoystickLeft[0], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + } + + if (packet->rgucJoystickLeft[1] != ctx->m_lastInputOnlyState.rgucJoystickLeft[1]) { + axis = (Sint16)HIDAPI_RemapVal(packet->rgucJoystickLeft[1], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + } + + if (packet->rgucJoystickRight[0] != ctx->m_lastInputOnlyState.rgucJoystickRight[0]) { + axis = (Sint16)HIDAPI_RemapVal(packet->rgucJoystickRight[0], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + } + + if (packet->rgucJoystickRight[1] != ctx->m_lastInputOnlyState.rgucJoystickRight[1]) { + axis = (Sint16)HIDAPI_RemapVal(packet->rgucJoystickRight[1], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + } + + ctx->m_lastInputOnlyState = *packet; +} + +static void HandleCombinedSimpleControllerStateL(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet) +{ + if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) { + Uint8 data = packet->rgucButtons[0]; + Uint8 hat = 0; + + if (data & 0x01) { + hat |= SDL_HAT_LEFT; + } + if (data & 0x02) { + hat |= SDL_HAT_DOWN; + } + if (data & 0x04) { + hat |= SDL_HAT_UP; + } + if (data & 0x08) { + hat |= SDL_HAT_RIGHT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE1, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE2, ((data & 0x20) != 0)); + } + + if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) { + Uint8 data = packet->rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x40) != 0)); + } + + Sint16 axis = (packet->rgucButtons[1] & 0x80) ? 32767 : -32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + + if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) { + switch (packet->ucStickHat) { + case 0: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0); + break; + case 1: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 2: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 3: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 4: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0); + break; + case 5: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN); + break; + case 6: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN); + break; + case 7: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN); + break; + default: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0); + break; + } + } +} + +static void HandleCombinedSimpleControllerStateR(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet) +{ + if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) { + Uint8 data = packet->rgucButtons[0]; + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE2, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE1, ((data & 0x20) != 0)); + } + + if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) { + Uint8 data = packet->rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x40) != 0)); + } + + Sint16 axis = (packet->rgucButtons[1] & 0x80) ? 32767 : -32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + + if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) { + switch (packet->ucStickHat) { + case 0: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, 0); + break; + case 1: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MIN); + break; + case 2: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MIN); + break; + case 3: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MIN); + break; + case 4: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, 0); + break; + case 5: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 6: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 7: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MAX); + break; + default: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, 0); + break; + } + } +} + +static void HandleMiniSimpleControllerStateL(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet) +{ + if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) { + Uint8 data = packet->rgucButtons[0]; + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x20) != 0)); + } + + if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) { + Uint8 data = packet->rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE1, ((data & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE2, ((data & 0x80) != 0)); + } + + if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) { + switch (packet->ucStickHat) { + case 0: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN); + break; + case 1: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN); + break; + case 2: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0); + break; + case 3: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 4: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 5: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 6: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0); + break; + case 7: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN); + break; + default: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0); + break; + } + } +} + +static void HandleMiniSimpleControllerStateR(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet) +{ + if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) { + Uint8 data = packet->rgucButtons[0]; + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x20) != 0)); + } + + if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) { + Uint8 data = packet->rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE1, ((data & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE2, ((data & 0x80) != 0)); + } + + if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) { + switch (packet->ucStickHat) { + case 0: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN); + break; + case 1: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN); + break; + case 2: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0); + break; + case 3: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 4: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 5: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX); + break; + case 6: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0); + break; + case 7: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN); + break; + default: + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0); + break; + } + } +} + +static void HandleSimpleControllerState(SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet) +{ + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft) { + if (ctx->device->parent || ctx->m_bVerticalMode) { + HandleCombinedSimpleControllerStateL(timestamp, joystick, ctx, packet); + } else { + HandleMiniSimpleControllerStateL(timestamp, joystick, ctx, packet); + } + } else if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + if (ctx->device->parent || ctx->m_bVerticalMode) { + HandleCombinedSimpleControllerStateR(timestamp, joystick, ctx, packet); + } else { + HandleMiniSimpleControllerStateR(timestamp, joystick, ctx, packet); + } + } else { + Sint16 axis; + + if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) { + Uint8 data = packet->rgucButtons[0]; + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x20) != 0)); + } + + if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) { + Uint8 data = packet->rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0)); + } + + if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) { + Uint8 hat; + + switch (packet->ucStickHat) { + case 0: + hat = SDL_HAT_UP; + break; + case 1: + hat = SDL_HAT_RIGHTUP; + break; + case 2: + hat = SDL_HAT_RIGHT; + break; + case 3: + hat = SDL_HAT_RIGHTDOWN; + break; + case 4: + hat = SDL_HAT_DOWN; + break; + case 5: + hat = SDL_HAT_LEFTDOWN; + break; + case 6: + hat = SDL_HAT_LEFT; + break; + case 7: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + axis = (packet->rgucButtons[0] & 0x40) ? 32767 : -32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + + axis = ((packet->rgucButtons[0] & 0x80) || (packet->rgucButtons[1] & 0x80)) ? 32767 : -32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + + axis = ApplySimpleStickCalibration(ctx, 0, 0, packet->sJoystickLeft[0]); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + + axis = ApplySimpleStickCalibration(ctx, 0, 1, packet->sJoystickLeft[1]); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + + axis = ApplySimpleStickCalibration(ctx, 1, 0, packet->sJoystickRight[0]); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + + axis = ApplySimpleStickCalibration(ctx, 1, 1, packet->sJoystickRight[1]); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + } + + ctx->m_lastSimpleState = *packet; +} + +static void SendSensorUpdate(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SDL_SensorType type, Uint64 sensor_timestamp, const Sint16 *values) +{ + float data[3]; + + /* Note the order of components has been shuffled to match PlayStation controllers, + * since that's our de facto standard from already supporting those controllers, and + * users will want consistent axis mappings across devices. + */ + if (type == SDL_SENSOR_GYRO || type == SDL_SENSOR_GYRO_L || type == SDL_SENSOR_GYRO_R) { + data[0] = -(ctx->m_IMUScaleData.fGyroScaleY * (float)values[1]); + data[1] = ctx->m_IMUScaleData.fGyroScaleZ * (float)values[2]; + data[2] = -(ctx->m_IMUScaleData.fGyroScaleX * (float)values[0]); + } else { + data[0] = -(ctx->m_IMUScaleData.fAccelScaleY * (float)values[1]); + data[1] = ctx->m_IMUScaleData.fAccelScaleZ * (float)values[2]; + data[2] = -(ctx->m_IMUScaleData.fAccelScaleX * (float)values[0]); + } + + // Right Joy-Con flips some axes, so let's flip them back for consistency + if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + data[0] = -data[0]; + data[1] = -data[1]; + } + + if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft && + !ctx->device->parent && !ctx->m_bVerticalMode) { + // Mini-gamepad mode, swap some axes around + float tmp = data[2]; + data[2] = -data[0]; + data[0] = tmp; + } + + if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight && + !ctx->device->parent && !ctx->m_bVerticalMode) { + // Mini-gamepad mode, swap some axes around + float tmp = data[2]; + data[2] = data[0]; + data[0] = -tmp; + } + + SDL_SendJoystickSensor(timestamp, joystick, type, sensor_timestamp, data, 3); +} + +static void HandleCombinedControllerStateL(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet) +{ + Sint16 axis; + + if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) { + Uint8 data = packet->controllerState.rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0)); + } + + if (packet->controllerState.rgucButtons[2] != ctx->m_lastFullState.controllerState.rgucButtons[2]) { + Uint8 data = packet->controllerState.rgucButtons[2]; + Uint8 hat = 0; + + if (data & 0x01) { + hat |= SDL_HAT_DOWN; + } + if (data & 0x02) { + hat |= SDL_HAT_UP; + } + if (data & 0x04) { + hat |= SDL_HAT_RIGHT; + } + if (data & 0x08) { + hat |= SDL_HAT_LEFT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE2, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE1, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x40) != 0)); + axis = (data & 0x80) ? 32767 : -32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + } + + axis = packet->controllerState.rgucJoystickLeft[0] | ((packet->controllerState.rgucJoystickLeft[1] & 0xF) << 8); + axis = ApplyStickCalibration(ctx, 0, 0, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + + axis = ((packet->controllerState.rgucJoystickLeft[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickLeft[2] << 4); + axis = ApplyStickCalibration(ctx, 0, 1, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, ~axis); +} + +static void HandleCombinedControllerStateR(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet) +{ + Sint16 axis; + + if (packet->controllerState.rgucButtons[0] != ctx->m_lastFullState.controllerState.rgucButtons[0]) { + Uint8 data = packet->controllerState.rgucButtons[0]; + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE1, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE2, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x40) != 0)); + axis = (data & 0x80) ? 32767 : -32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + } + + if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) { + Uint8 data = packet->controllerState.rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0)); + } + + axis = packet->controllerState.rgucJoystickRight[0] | ((packet->controllerState.rgucJoystickRight[1] & 0xF) << 8); + axis = ApplyStickCalibration(ctx, 1, 0, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + + axis = ((packet->controllerState.rgucJoystickRight[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickRight[2] << 4); + axis = ApplyStickCalibration(ctx, 1, 1, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, ~axis); +} + +static void HandleMiniControllerStateL(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet) +{ + Sint16 axis; + + if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) { + Uint8 data = packet->controllerState.rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x20) != 0)); + } + + if (packet->controllerState.rgucButtons[2] != ctx->m_lastFullState.controllerState.rgucButtons[2]) { + Uint8 data = packet->controllerState.rgucButtons[2]; + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE1, ((data & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE2, ((data & 0x80) != 0)); + } + + axis = packet->controllerState.rgucJoystickLeft[0] | ((packet->controllerState.rgucJoystickLeft[1] & 0xF) << 8); + axis = ApplyStickCalibration(ctx, 0, 0, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, ~axis); + + axis = ((packet->controllerState.rgucJoystickLeft[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickLeft[2] << 4); + axis = ApplyStickCalibration(ctx, 0, 1, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, ~axis); +} + +static void HandleMiniControllerStateR(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet) +{ + Sint16 axis; + + if (packet->controllerState.rgucButtons[0] != ctx->m_lastFullState.controllerState.rgucButtons[0]) { + Uint8 data = packet->controllerState.rgucButtons[0]; + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE1, ((data & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE2, ((data & 0x80) != 0)); + } + + if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) { + Uint8 data = packet->controllerState.rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0)); + } + + axis = packet->controllerState.rgucJoystickRight[0] | ((packet->controllerState.rgucJoystickRight[1] & 0xF) << 8); + axis = ApplyStickCalibration(ctx, 1, 0, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + + axis = ((packet->controllerState.rgucJoystickRight[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickRight[2] << 4); + axis = ApplyStickCalibration(ctx, 1, 1, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); +} + +static void HandleFullControllerState(SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet) SDL_NO_THREAD_SAFETY_ANALYSIS // We unlock and lock the device lock to be able to change IMU state +{ + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft) { + if (ctx->device->parent || ctx->m_bVerticalMode) { + HandleCombinedControllerStateL(timestamp, joystick, ctx, packet); + } else { + HandleMiniControllerStateL(timestamp, joystick, ctx, packet); + } + } else if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + if (ctx->device->parent || ctx->m_bVerticalMode) { + HandleCombinedControllerStateR(timestamp, joystick, ctx, packet); + } else { + HandleMiniControllerStateR(timestamp, joystick, ctx, packet); + } + } else { + Sint16 axis; + + if (packet->controllerState.rgucButtons[0] != ctx->m_lastFullState.controllerState.rgucButtons[0]) { + Uint8 data = packet->controllerState.rgucButtons[0]; + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x40) != 0)); + } + + if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) { + Uint8 data = packet->controllerState.rgucButtons[1]; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x08) != 0)); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0)); + } + + if (packet->controllerState.rgucButtons[2] != ctx->m_lastFullState.controllerState.rgucButtons[2]) { + Uint8 data = packet->controllerState.rgucButtons[2]; + Uint8 hat = 0; + + if (data & 0x01) { + hat |= SDL_HAT_DOWN; + } + if (data & 0x02) { + hat |= SDL_HAT_UP; + } + if (data & 0x04) { + hat |= SDL_HAT_RIGHT; + } + if (data & 0x08) { + hat |= SDL_HAT_LEFT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x40) != 0)); + } + + axis = (packet->controllerState.rgucButtons[0] & 0x80) ? 32767 : -32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + + axis = (packet->controllerState.rgucButtons[2] & 0x80) ? 32767 : -32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + + axis = packet->controllerState.rgucJoystickLeft[0] | ((packet->controllerState.rgucJoystickLeft[1] & 0xF) << 8); + axis = ApplyStickCalibration(ctx, 0, 0, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + + axis = ((packet->controllerState.rgucJoystickLeft[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickLeft[2] << 4); + axis = ApplyStickCalibration(ctx, 0, 1, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, ~axis); + + axis = packet->controllerState.rgucJoystickRight[0] | ((packet->controllerState.rgucJoystickRight[1] & 0xF) << 8); + axis = ApplyStickCalibration(ctx, 1, 0, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + + axis = ((packet->controllerState.rgucJoystickRight[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickRight[2] << 4); + axis = ApplyStickCalibration(ctx, 1, 1, axis); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, ~axis); + } + + /* High nibble of battery/connection byte is battery level, low nibble is connection status (always 0 on 8BitDo Pro 2) + * LSB of connection nibble is USB/Switch connection status + * LSB of the battery nibble is used to report charging. + * The battery level is reported from 0(empty)-8(full) + */ + SDL_PowerState state; + int charging = (packet->controllerState.ucBatteryAndConnection & 0x10); + int level = (packet->controllerState.ucBatteryAndConnection & 0xE0) >> 4; + int percent = (int)SDL_roundf((level / 8.0f) * 100.0f); + + if (charging) { + if (level == 8) { + state = SDL_POWERSTATE_CHARGED; + } else { + state = SDL_POWERSTATE_CHARGING; + } + } else { + state = SDL_POWERSTATE_ON_BATTERY; + } + SDL_SendJoystickPowerInfo(joystick, state, percent); + + if (ctx->m_bReportSensors) { + bool bHasSensorData = (packet->imuState[0].sAccelZ != 0 || + packet->imuState[0].sAccelY != 0 || + packet->imuState[0].sAccelX != 0); + if (bHasSensorData) { + const Uint32 IMU_UPDATE_RATE_SAMPLE_FREQUENCY = 1000; + Uint64 sensor_timestamp[3]; + + ctx->m_bHasSensorData = true; + + // We got three IMU samples, calculate the IMU update rate and timestamps + ctx->m_unIMUSamples += 3; + if (ctx->m_unIMUSamples >= IMU_UPDATE_RATE_SAMPLE_FREQUENCY) { + Uint64 now = SDL_GetTicksNS(); + Uint64 elapsed = (now - ctx->m_ulIMUSampleTimestampNS); + + if (elapsed > 0) { + ctx->m_ulIMUUpdateIntervalNS = elapsed / ctx->m_unIMUSamples; + } + ctx->m_unIMUSamples = 0; + ctx->m_ulIMUSampleTimestampNS = now; + } + + ctx->m_ulTimestampNS += ctx->m_ulIMUUpdateIntervalNS; + sensor_timestamp[0] = ctx->m_ulTimestampNS; + ctx->m_ulTimestampNS += ctx->m_ulIMUUpdateIntervalNS; + sensor_timestamp[1] = ctx->m_ulTimestampNS; + ctx->m_ulTimestampNS += ctx->m_ulIMUUpdateIntervalNS; + sensor_timestamp[2] = ctx->m_ulTimestampNS; + + if (!ctx->device->parent || + ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO, sensor_timestamp[0], &packet->imuState[2].sGyroX); + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL, sensor_timestamp[0], &packet->imuState[2].sAccelX); + + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO, sensor_timestamp[1], &packet->imuState[1].sGyroX); + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL, sensor_timestamp[1], &packet->imuState[1].sAccelX); + + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO, sensor_timestamp[2], &packet->imuState[0].sGyroX); + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL, sensor_timestamp[2], &packet->imuState[0].sAccelX); + } + + if (ctx->device->parent && + ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft) { + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_L, sensor_timestamp[0], &packet->imuState[2].sGyroX); + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_L, sensor_timestamp[0], &packet->imuState[2].sAccelX); + + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_L, sensor_timestamp[1], &packet->imuState[1].sGyroX); + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_L, sensor_timestamp[1], &packet->imuState[1].sAccelX); + + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_L, sensor_timestamp[2], &packet->imuState[0].sGyroX); + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_L, sensor_timestamp[2], &packet->imuState[0].sAccelX); + } + if (ctx->device->parent && + ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_R, sensor_timestamp[0], &packet->imuState[2].sGyroX); + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_R, sensor_timestamp[0], &packet->imuState[2].sAccelX); + + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_R, sensor_timestamp[1], &packet->imuState[1].sGyroX); + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_R, sensor_timestamp[1], &packet->imuState[1].sAccelX); + + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_R, sensor_timestamp[2], &packet->imuState[0].sGyroX); + SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_R, sensor_timestamp[2], &packet->imuState[0].sAccelX); + } + + } else if (ctx->m_bHasSensorData) { + // Uh oh, someone turned off the IMU? + const int IMU_RESET_DELAY_MS = 3000; + Uint64 now = SDL_GetTicks(); + + if (now >= (ctx->m_ulLastIMUReset + IMU_RESET_DELAY_MS)) { + SDL_HIDAPI_Device *device = ctx->device; + + if (device->updating) { + SDL_UnlockMutex(device->dev_lock); + } + + SetIMUEnabled(ctx, true); + + if (device->updating) { + SDL_LockMutex(device->dev_lock); + } + ctx->m_ulLastIMUReset = now; + } + + } else { + // We have never gotten IMU data, probably not supported on this device + } + } + + ctx->m_lastFullState = *packet; +} + +static bool HIDAPI_DriverSwitch_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; + SDL_Joystick *joystick = NULL; + int size; + int packet_count = 0; + Uint64 now = SDL_GetTicks(); + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } + + while ((size = ReadInput(ctx)) > 0) { +#ifdef DEBUG_SWITCH_PROTOCOL + HIDAPI_DumpPacket("Nintendo Switch packet: size = %d", ctx->m_rgucReadBuffer, size); +#endif + ++packet_count; + ctx->m_ulLastInput = now; + + if (!joystick) { + continue; + } + + if (ctx->m_bInputOnly) { + HandleInputOnlyControllerState(joystick, ctx, (SwitchInputOnlyControllerStatePacket_t *)&ctx->m_rgucReadBuffer[0]); + } else { + if (ctx->m_rgucReadBuffer[0] == k_eSwitchInputReportIDs_SubcommandReply) { + continue; + } + + ctx->m_nCurrentInputMode = ctx->m_rgucReadBuffer[0]; + + switch (ctx->m_rgucReadBuffer[0]) { + case k_eSwitchInputReportIDs_SimpleControllerState: + HandleSimpleControllerState(joystick, ctx, (SwitchSimpleStatePacket_t *)&ctx->m_rgucReadBuffer[1]); + break; + case k_eSwitchInputReportIDs_FullControllerState: + case k_eSwitchInputReportIDs_FullControllerAndMcuState: + // This is the extended report, we can enable sensors now in auto mode + UpdateEnhancedModeOnEnhancedReport(ctx); + + HandleFullControllerState(joystick, ctx, (SwitchStatePacket_t *)&ctx->m_rgucReadBuffer[1]); + break; + default: + break; + } + } + } + + if (joystick) { + if (packet_count == 0) { + if (!ctx->m_bInputOnly && !device->is_bluetooth && + ctx->device->product_id != USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP) { + const int INPUT_WAIT_TIMEOUT_MS = 100; + if (now >= (ctx->m_ulLastInput + INPUT_WAIT_TIMEOUT_MS)) { + // Steam may have put the controller back into non-reporting mode + bool wasSyncWrite = ctx->m_bSyncWrite; + + ctx->m_bSyncWrite = true; + WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_ForceUSB, NULL, 0, false); + ctx->m_bSyncWrite = wasSyncWrite; + } + } else if (device->is_bluetooth && + ctx->m_nCurrentInputMode != k_eSwitchInputReportIDs_SimpleControllerState) { + const int INPUT_WAIT_TIMEOUT_MS = 3000; + if (now >= (ctx->m_ulLastInput + INPUT_WAIT_TIMEOUT_MS)) { + // Bluetooth may have disconnected, try reopening the controller + size = -1; + } + } + } + + if (ctx->m_bRumblePending || ctx->m_bRumbleZeroPending) { + HIDAPI_DriverSwitch_SendPendingRumble(ctx); + } else if (ctx->m_bRumbleActive && + now >= (ctx->m_ulRumbleSent + RUMBLE_REFRESH_FREQUENCY_MS)) { +#ifdef DEBUG_RUMBLE + SDL_Log("Sent continuing rumble, %d ms after previous rumble", now - ctx->m_ulRumbleSent); +#endif + WriteRumble(ctx); + } + } + + // Reconnect the Bluetooth device once the USB device is gone + if (device->num_joysticks == 0 && device->is_bluetooth && packet_count > 0 && + !device->parent && + !HIDAPI_HasConnectedUSBDevice(device->serial)) { + HIDAPI_JoystickConnected(device, NULL); + } + + if (size < 0 && device->num_joysticks > 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverSwitch_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; + + if (!ctx->m_bInputOnly) { + // Restore simple input mode for other applications + if (!ctx->m_nInitialInputMode || + ctx->m_nInitialInputMode == k_eSwitchInputReportIDs_SimpleControllerState) { + SetInputMode(ctx, k_eSwitchInputReportIDs_SimpleControllerState); + } + } + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_ENHANCED_REPORTS, + SDL_EnhancedReportsChanged, ctx); + + if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft || + ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) { + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_JOYCON_HOME_LED, + SDL_HomeLEDHintChanged, ctx); + } else { + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_HOME_LED, + SDL_HomeLEDHintChanged, ctx); + } + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED, + SDL_PlayerLEDHintChanged, ctx); + + ctx->joystick = NULL; + + ctx->m_bReportSensors = false; + ctx->m_bEnhancedMode = false; + ctx->m_bEnhancedModeAvailable = false; +} + +static void HIDAPI_DriverSwitch_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverNintendoClassic = { + SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC, + true, + HIDAPI_DriverNintendoClassic_RegisterHints, + HIDAPI_DriverNintendoClassic_UnregisterHints, + HIDAPI_DriverNintendoClassic_IsEnabled, + HIDAPI_DriverNintendoClassic_IsSupportedDevice, + HIDAPI_DriverSwitch_InitDevice, + HIDAPI_DriverSwitch_GetDevicePlayerIndex, + HIDAPI_DriverSwitch_SetDevicePlayerIndex, + HIDAPI_DriverSwitch_UpdateDevice, + HIDAPI_DriverSwitch_OpenJoystick, + HIDAPI_DriverSwitch_RumbleJoystick, + HIDAPI_DriverSwitch_RumbleJoystickTriggers, + HIDAPI_DriverSwitch_GetJoystickCapabilities, + HIDAPI_DriverSwitch_SetJoystickLED, + HIDAPI_DriverSwitch_SendJoystickEffect, + HIDAPI_DriverSwitch_SetJoystickSensorsEnabled, + HIDAPI_DriverSwitch_CloseJoystick, + HIDAPI_DriverSwitch_FreeDevice, +}; + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverJoyCons = { + SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, + true, + HIDAPI_DriverJoyCons_RegisterHints, + HIDAPI_DriverJoyCons_UnregisterHints, + HIDAPI_DriverJoyCons_IsEnabled, + HIDAPI_DriverJoyCons_IsSupportedDevice, + HIDAPI_DriverSwitch_InitDevice, + HIDAPI_DriverSwitch_GetDevicePlayerIndex, + HIDAPI_DriverSwitch_SetDevicePlayerIndex, + HIDAPI_DriverSwitch_UpdateDevice, + HIDAPI_DriverSwitch_OpenJoystick, + HIDAPI_DriverSwitch_RumbleJoystick, + HIDAPI_DriverSwitch_RumbleJoystickTriggers, + HIDAPI_DriverSwitch_GetJoystickCapabilities, + HIDAPI_DriverSwitch_SetJoystickLED, + HIDAPI_DriverSwitch_SendJoystickEffect, + HIDAPI_DriverSwitch_SetJoystickSensorsEnabled, + HIDAPI_DriverSwitch_CloseJoystick, + HIDAPI_DriverSwitch_FreeDevice, +}; + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSwitch = { + SDL_HINT_JOYSTICK_HIDAPI_SWITCH, + true, + HIDAPI_DriverSwitch_RegisterHints, + HIDAPI_DriverSwitch_UnregisterHints, + HIDAPI_DriverSwitch_IsEnabled, + HIDAPI_DriverSwitch_IsSupportedDevice, + HIDAPI_DriverSwitch_InitDevice, + HIDAPI_DriverSwitch_GetDevicePlayerIndex, + HIDAPI_DriverSwitch_SetDevicePlayerIndex, + HIDAPI_DriverSwitch_UpdateDevice, + HIDAPI_DriverSwitch_OpenJoystick, + HIDAPI_DriverSwitch_RumbleJoystick, + HIDAPI_DriverSwitch_RumbleJoystickTriggers, + HIDAPI_DriverSwitch_GetJoystickCapabilities, + HIDAPI_DriverSwitch_SetJoystickLED, + HIDAPI_DriverSwitch_SendJoystickEffect, + HIDAPI_DriverSwitch_SetJoystickSensorsEnabled, + HIDAPI_DriverSwitch_CloseJoystick, + HIDAPI_DriverSwitch_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_SWITCH + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_wii.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_wii.c new file mode 100644 index 00000000000..fb3e164a8d0 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_wii.c @@ -0,0 +1,1617 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../../SDL_hints_c.h" +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" +#include "SDL_hidapi_nintendo.h" + +#ifdef SDL_JOYSTICK_HIDAPI_WII + +// Define this if you want to log all packets from the controller +// #define DEBUG_WII_PROTOCOL + +#define ENABLE_CONTINUOUS_REPORTING true + +#define INPUT_WAIT_TIMEOUT_MS (3 * 1000) +#define MOTION_PLUS_UPDATE_TIME_MS (8 * 1000) +#define STATUS_UPDATE_TIME_MS (15 * 60 * 1000) + +#define WII_EXTENSION_NONE 0x2E2E +#define WII_EXTENSION_UNINITIALIZED 0xFFFF +#define WII_EXTENSION_NUNCHUK 0x0000 +#define WII_EXTENSION_GAMEPAD 0x0101 +#define WII_EXTENSION_WIIUPRO 0x0120 +#define WII_EXTENSION_MOTIONPLUS_MASK 0xF0FF +#define WII_EXTENSION_MOTIONPLUS_ID 0x0005 + +#define WII_MOTIONPLUS_MODE_NONE 0x00 +#define WII_MOTIONPLUS_MODE_STANDARD 0x04 +#define WII_MOTIONPLUS_MODE_NUNCHUK 0x05 +#define WII_MOTIONPLUS_MODE_GAMEPAD 0x07 + +typedef enum +{ + k_eWiiInputReportIDs_Status = 0x20, + k_eWiiInputReportIDs_ReadMemory = 0x21, + k_eWiiInputReportIDs_Acknowledge = 0x22, + k_eWiiInputReportIDs_ButtonData0 = 0x30, + k_eWiiInputReportIDs_ButtonData1 = 0x31, + k_eWiiInputReportIDs_ButtonData2 = 0x32, + k_eWiiInputReportIDs_ButtonData3 = 0x33, + k_eWiiInputReportIDs_ButtonData4 = 0x34, + k_eWiiInputReportIDs_ButtonData5 = 0x35, + k_eWiiInputReportIDs_ButtonData6 = 0x36, + k_eWiiInputReportIDs_ButtonData7 = 0x37, + k_eWiiInputReportIDs_ButtonDataD = 0x3D, + k_eWiiInputReportIDs_ButtonDataE = 0x3E, + k_eWiiInputReportIDs_ButtonDataF = 0x3F, +} EWiiInputReportIDs; + +typedef enum +{ + k_eWiiOutputReportIDs_Rumble = 0x10, + k_eWiiOutputReportIDs_LEDs = 0x11, + k_eWiiOutputReportIDs_DataReportingMode = 0x12, + k_eWiiOutputReportIDs_IRCameraEnable = 0x13, + k_eWiiOutputReportIDs_SpeakerEnable = 0x14, + k_eWiiOutputReportIDs_StatusRequest = 0x15, + k_eWiiOutputReportIDs_WriteMemory = 0x16, + k_eWiiOutputReportIDs_ReadMemory = 0x17, + k_eWiiOutputReportIDs_SpeakerData = 0x18, + k_eWiiOutputReportIDs_SpeakerMute = 0x19, + k_eWiiOutputReportIDs_IRCameraEnable2 = 0x1a, +} EWiiOutputReportIDs; + +typedef enum +{ + k_eWiiPlayerLEDs_P1 = 0x10, + k_eWiiPlayerLEDs_P2 = 0x20, + k_eWiiPlayerLEDs_P3 = 0x40, + k_eWiiPlayerLEDs_P4 = 0x80, +} EWiiPlayerLEDs; + +typedef enum +{ + k_eWiiCommunicationState_None, // No special communications happening + k_eWiiCommunicationState_CheckMotionPlusStage1, // Sent standard extension identify request + k_eWiiCommunicationState_CheckMotionPlusStage2, // Sent Motion Plus extension identify request +} EWiiCommunicationState; + +typedef enum +{ + k_eWiiButtons_A = SDL_GAMEPAD_BUTTON_MISC1, + k_eWiiButtons_B, + k_eWiiButtons_One, + k_eWiiButtons_Two, + k_eWiiButtons_Plus, + k_eWiiButtons_Minus, + k_eWiiButtons_Home, + k_eWiiButtons_DPad_Up, + k_eWiiButtons_DPad_Down, + k_eWiiButtons_DPad_Left, + k_eWiiButtons_DPad_Right, + k_eWiiButtons_Max +} EWiiButtons; + +#define k_unWiiPacketDataLength 22 + +typedef struct +{ + Uint8 rgucBaseButtons[2]; + Uint8 rgucAccelerometer[3]; + Uint8 rgucExtension[21]; + bool hasBaseButtons; + bool hasAccelerometer; + Uint8 ucNExtensionBytes; +} WiiButtonData; + +typedef struct +{ + Uint16 min; + Uint16 max; + Uint16 center; + Uint16 deadzone; +} StickCalibrationData; + +typedef struct +{ + SDL_HIDAPI_Device *device; + SDL_Joystick *joystick; + Uint64 timestamp; + EWiiCommunicationState m_eCommState; + EWiiExtensionControllerType m_eExtensionControllerType; + bool m_bPlayerLights; + int m_nPlayerIndex; + bool m_bRumbleActive; + bool m_bMotionPlusPresent; + Uint8 m_ucMotionPlusMode; + bool m_bReportSensors; + Uint8 m_rgucReadBuffer[k_unWiiPacketDataLength]; + Uint64 m_ulLastInput; + Uint64 m_ulLastStatus; + Uint64 m_ulNextMotionPlusCheck; + bool m_bDisconnected; + + StickCalibrationData m_StickCalibrationData[6]; +} SDL_DriverWii_Context; + +static void HIDAPI_DriverWii_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_WII, callback, userdata); +} + +static void HIDAPI_DriverWii_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_WII, callback, userdata); +} + +static bool HIDAPI_DriverWii_IsEnabled(void) +{ +#if 1 // This doesn't work with the dolphinbar, so don't enable by default right now + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_WII, false); +#else + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_WII, + SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, + SDL_HIDAPI_DEFAULT)); +#endif +} + +static bool HIDAPI_DriverWii_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + if (vendor_id == USB_VENDOR_NINTENDO && + (product_id == USB_PRODUCT_NINTENDO_WII_REMOTE || + product_id == USB_PRODUCT_NINTENDO_WII_REMOTE2)) { + return true; + } + return false; +} + +static int ReadInput(SDL_DriverWii_Context *ctx) +{ + int size; + + // Make sure we don't try to read at the same time a write is happening + if (SDL_GetAtomicInt(&ctx->device->rumble_pending) > 0) { + return 0; + } + + size = SDL_hid_read_timeout(ctx->device->dev, ctx->m_rgucReadBuffer, sizeof(ctx->m_rgucReadBuffer), 0); +#ifdef DEBUG_WII_PROTOCOL + if (size > 0) { + HIDAPI_DumpPacket("Wii packet: size = %d", ctx->m_rgucReadBuffer, size); + } +#endif + return size; +} + +static bool WriteOutput(SDL_DriverWii_Context *ctx, const Uint8 *data, int size, bool sync) +{ +#ifdef DEBUG_WII_PROTOCOL + if (size > 0) { + HIDAPI_DumpPacket("Wii write packet: size = %d", data, size); + } +#endif + if (sync) { + return SDL_hid_write(ctx->device->dev, data, size) >= 0; + } else { + // Use the rumble thread for general asynchronous writes + if (!SDL_HIDAPI_LockRumble()) { + return false; + } + return SDL_HIDAPI_SendRumbleAndUnlock(ctx->device, data, size) >= 0; + } +} + +static bool ReadInputSync(SDL_DriverWii_Context *ctx, EWiiInputReportIDs expectedID, bool (*isMine)(const Uint8 *)) +{ + Uint64 endTicks = SDL_GetTicks() + 250; // Seeing successful reads after about 200 ms + + int nRead = 0; + while ((nRead = ReadInput(ctx)) != -1) { + if (nRead > 0) { + if (ctx->m_rgucReadBuffer[0] == expectedID && (!isMine || isMine(ctx->m_rgucReadBuffer))) { + return true; + } + } else { + if (SDL_GetTicks() >= endTicks) { + break; + } + SDL_Delay(1); + } + } + SDL_SetError("Read timed out"); + return false; +} + +static bool IsWriteMemoryResponse(const Uint8 *data) +{ + return data[3] == k_eWiiOutputReportIDs_WriteMemory; +} + +static bool WriteRegister(SDL_DriverWii_Context *ctx, Uint32 address, const Uint8 *data, int size, bool sync) +{ + Uint8 writeRequest[k_unWiiPacketDataLength]; + + SDL_zeroa(writeRequest); + writeRequest[0] = k_eWiiOutputReportIDs_WriteMemory; + writeRequest[1] = (Uint8)(0x04 | (Uint8)ctx->m_bRumbleActive); + writeRequest[2] = (address >> 16) & 0xff; + writeRequest[3] = (address >> 8) & 0xff; + writeRequest[4] = address & 0xff; + writeRequest[5] = (Uint8)size; + SDL_assert(size > 0 && size <= 16); + SDL_memcpy(writeRequest + 6, data, size); + + if (!WriteOutput(ctx, writeRequest, sizeof(writeRequest), sync)) { + return false; + } + if (sync) { + // Wait for response + if (!ReadInputSync(ctx, k_eWiiInputReportIDs_Acknowledge, IsWriteMemoryResponse)) { + return false; + } + if (ctx->m_rgucReadBuffer[4]) { + SDL_SetError("Write memory failed: %u", ctx->m_rgucReadBuffer[4]); + return false; + } + } + return true; +} + +static bool ReadRegister(SDL_DriverWii_Context *ctx, Uint32 address, int size, bool sync) +{ + Uint8 readRequest[7]; + + readRequest[0] = k_eWiiOutputReportIDs_ReadMemory; + readRequest[1] = (Uint8)(0x04 | (Uint8)ctx->m_bRumbleActive); + readRequest[2] = (address >> 16) & 0xff; + readRequest[3] = (address >> 8) & 0xff; + readRequest[4] = address & 0xff; + readRequest[5] = (size >> 8) & 0xff; + readRequest[6] = size & 0xff; + + SDL_assert(size > 0 && size <= 0xffff); + + if (!WriteOutput(ctx, readRequest, sizeof(readRequest), sync)) { + return false; + } + if (sync) { + SDL_assert(size <= 16); // Only waiting for one packet is supported right now + // Wait for response + if (!ReadInputSync(ctx, k_eWiiInputReportIDs_ReadMemory, NULL)) { + return false; + } + } + return true; +} + +static bool SendExtensionIdentify(SDL_DriverWii_Context *ctx, bool sync) +{ + return ReadRegister(ctx, 0xA400FE, 2, sync); +} + +static bool ParseExtensionIdentifyResponse(SDL_DriverWii_Context *ctx, Uint16 *extension) +{ + int i; + + if (ctx->m_rgucReadBuffer[0] != k_eWiiInputReportIDs_ReadMemory) { + SDL_SetError("Unexpected extension response type"); + return false; + } + + if (ctx->m_rgucReadBuffer[4] != 0x00 || ctx->m_rgucReadBuffer[5] != 0xFE) { + SDL_SetError("Unexpected extension response address"); + return false; + } + + if (ctx->m_rgucReadBuffer[3] != 0x10) { + Uint8 error = (ctx->m_rgucReadBuffer[3] & 0xF); + + if (error == 7) { + // The extension memory isn't mapped + *extension = WII_EXTENSION_NONE; + return true; + } + + if (error) { + SDL_SetError("Failed to read extension type: %u", error); + } else { + SDL_SetError("Unexpected read length when reading extension type: %d", (ctx->m_rgucReadBuffer[3] >> 4) + 1); + } + return false; + } + + *extension = 0; + for (i = 6; i < 8; i++) { + *extension = *extension << 8 | ctx->m_rgucReadBuffer[i]; + } + return true; +} + +static EWiiExtensionControllerType GetExtensionType(Uint16 extension_id) +{ + switch (extension_id) { + case WII_EXTENSION_NONE: + return k_eWiiExtensionControllerType_None; + case WII_EXTENSION_NUNCHUK: + return k_eWiiExtensionControllerType_Nunchuk; + case WII_EXTENSION_GAMEPAD: + return k_eWiiExtensionControllerType_Gamepad; + case WII_EXTENSION_WIIUPRO: + return k_eWiiExtensionControllerType_WiiUPro; + default: + return k_eWiiExtensionControllerType_Unknown; + } +} + +static bool SendExtensionReset(SDL_DriverWii_Context *ctx, bool sync) +{ + bool result = true; + { + Uint8 data = 0x55; + result = result && WriteRegister(ctx, 0xA400F0, &data, sizeof(data), sync); + } + // This write will fail if there is no extension connected, that's fine + { + Uint8 data = 0x00; + (void)WriteRegister(ctx, 0xA400FB, &data, sizeof(data), sync); + } + return result; +} + +static bool GetMotionPlusState(SDL_DriverWii_Context *ctx, bool *connected, Uint8 *mode) +{ + Uint16 extension; + + if (connected) { + *connected = false; + } + if (mode) { + *mode = 0; + } + + if (ctx->m_eExtensionControllerType == k_eWiiExtensionControllerType_WiiUPro) { + // The Wii U Pro controller never has the Motion Plus extension + return true; + } + + if (SendExtensionIdentify(ctx, true) && + ParseExtensionIdentifyResponse(ctx, &extension)) { + if ((extension & WII_EXTENSION_MOTIONPLUS_MASK) == WII_EXTENSION_MOTIONPLUS_ID) { + // Motion Plus is currently active + if (connected) { + *connected = true; + } + if (mode) { + *mode = (extension >> 8); + } + return true; + } + } + + if (ReadRegister(ctx, 0xA600FE, 2, true) && + ParseExtensionIdentifyResponse(ctx, &extension)) { + if ((extension & WII_EXTENSION_MOTIONPLUS_MASK) == WII_EXTENSION_MOTIONPLUS_ID) { + // Motion Plus is currently connected + if (connected) { + *connected = true; + } + } + return true; + } + + // Failed to read the register or parse the response + return false; +} + +static bool NeedsPeriodicMotionPlusCheck(SDL_DriverWii_Context *ctx, bool status_update) +{ + if (ctx->m_eExtensionControllerType == k_eWiiExtensionControllerType_WiiUPro) { + // The Wii U Pro controller never has the Motion Plus extension + return false; + } + + if (ctx->m_ucMotionPlusMode != WII_MOTIONPLUS_MODE_NONE && !status_update) { + // We'll get a status update when Motion Plus is disconnected + return false; + } + + return true; +} + +static void SchedulePeriodicMotionPlusCheck(SDL_DriverWii_Context *ctx) +{ + ctx->m_ulNextMotionPlusCheck = SDL_GetTicks() + MOTION_PLUS_UPDATE_TIME_MS; +} + +static void CheckMotionPlusConnection(SDL_DriverWii_Context *ctx) +{ + SendExtensionIdentify(ctx, false); + + ctx->m_eCommState = k_eWiiCommunicationState_CheckMotionPlusStage1; +} + +static void ActivateMotionPlusWithMode(SDL_DriverWii_Context *ctx, Uint8 mode) +{ +#ifdef SDL_PLATFORM_LINUX + /* Linux drivers maintain a lot of state around the Motion Plus + * extension, so don't mess with it here. + */ +#else + WriteRegister(ctx, 0xA600FE, &mode, sizeof(mode), true); + + ctx->m_ucMotionPlusMode = mode; +#endif // LINUX +} + +static void ActivateMotionPlus(SDL_DriverWii_Context *ctx) +{ + Uint8 mode = WII_MOTIONPLUS_MODE_STANDARD; + + // Pick the pass-through mode based on the connected controller + if (ctx->m_eExtensionControllerType == k_eWiiExtensionControllerType_Nunchuk) { + mode = WII_MOTIONPLUS_MODE_NUNCHUK; + } else if (ctx->m_eExtensionControllerType == k_eWiiExtensionControllerType_Gamepad) { + mode = WII_MOTIONPLUS_MODE_GAMEPAD; + } + ActivateMotionPlusWithMode(ctx, mode); +} + +static void DeactivateMotionPlus(SDL_DriverWii_Context *ctx) +{ + Uint8 data = 0x55; + WriteRegister(ctx, 0xA400F0, &data, sizeof(data), true); + + // Wait for the deactivation status message + ReadInputSync(ctx, k_eWiiInputReportIDs_Status, NULL); + + ctx->m_ucMotionPlusMode = WII_MOTIONPLUS_MODE_NONE; +} + +static void UpdatePowerLevelWii(SDL_Joystick *joystick, Uint8 batteryLevelByte) +{ + int percent; + if (batteryLevelByte > 178) { + percent = 100; + } else if (batteryLevelByte > 51) { + percent = 70; + } else if (batteryLevelByte > 13) { + percent = 20; + } else { + percent = 5; + } + SDL_SendJoystickPowerInfo(joystick, SDL_POWERSTATE_ON_BATTERY, percent); +} + +static void UpdatePowerLevelWiiU(SDL_Joystick *joystick, Uint8 extensionBatteryByte) +{ + bool charging = !(extensionBatteryByte & 0x08); + bool pluggedIn = !(extensionBatteryByte & 0x04); + Uint8 batteryLevel = extensionBatteryByte >> 4; + + if (pluggedIn) { + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRED; + } else { + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRELESS; + } + + /* Not sure if all Wii U Pro controllers act like this, but on mine + * 4, 3, and 2 are held for about 20 hours each + * 1 is held for about 6 hours + * 0 is held for about 2 hours + * No value above 4 has been observed. + */ + SDL_PowerState state; + int percent; + if (charging) { + state = SDL_POWERSTATE_CHARGING; + } else if (pluggedIn) { + state = SDL_POWERSTATE_CHARGED; + } else { + state = SDL_POWERSTATE_ON_BATTERY; + } + if (batteryLevel >= 4) { + percent = 100; + } else if (batteryLevel == 3) { + percent = 70; + } else if (batteryLevel == 2) { + percent = 40; + } else if (batteryLevel == 1) { + percent = 10; + } else { + percent = 3; + } + SDL_SendJoystickPowerInfo(joystick, state, percent); +} + +static EWiiInputReportIDs GetButtonPacketType(SDL_DriverWii_Context *ctx) +{ + switch (ctx->m_eExtensionControllerType) { + case k_eWiiExtensionControllerType_WiiUPro: + return k_eWiiInputReportIDs_ButtonDataD; + case k_eWiiExtensionControllerType_Nunchuk: + case k_eWiiExtensionControllerType_Gamepad: + if (ctx->m_bReportSensors) { + return k_eWiiInputReportIDs_ButtonData5; + } else { + return k_eWiiInputReportIDs_ButtonData2; + } + default: + if (ctx->m_bReportSensors) { + return k_eWiiInputReportIDs_ButtonData5; + } else { + return k_eWiiInputReportIDs_ButtonData0; + } + } +} + +static bool RequestButtonPacketType(SDL_DriverWii_Context *ctx, EWiiInputReportIDs type) +{ + Uint8 data[3]; + Uint8 tt = (Uint8)ctx->m_bRumbleActive; + + // Continuous reporting off, tt & 4 == 0 + if (ENABLE_CONTINUOUS_REPORTING) { + tt |= 4; + } + + data[0] = k_eWiiOutputReportIDs_DataReportingMode; + data[1] = tt; + data[2] = type; + return WriteOutput(ctx, data, sizeof(data), false); +} + +static void ResetButtonPacketType(SDL_DriverWii_Context *ctx) +{ + RequestButtonPacketType(ctx, GetButtonPacketType(ctx)); +} + +static void InitStickCalibrationData(SDL_DriverWii_Context *ctx) +{ + int i; + switch (ctx->m_eExtensionControllerType) { + case k_eWiiExtensionControllerType_WiiUPro: + for (i = 0; i < 4; i++) { + ctx->m_StickCalibrationData[i].min = 1000; + ctx->m_StickCalibrationData[i].max = 3000; + ctx->m_StickCalibrationData[i].center = 0; + ctx->m_StickCalibrationData[i].deadzone = 100; + } + break; + case k_eWiiExtensionControllerType_Gamepad: + for (i = 0; i < 4; i++) { + ctx->m_StickCalibrationData[i].min = i < 2 ? 9 : 5; + ctx->m_StickCalibrationData[i].max = i < 2 ? 54 : 26; + ctx->m_StickCalibrationData[i].center = 0; + ctx->m_StickCalibrationData[i].deadzone = i < 2 ? 4 : 2; + } + break; + case k_eWiiExtensionControllerType_Nunchuk: + for (i = 0; i < 2; i++) { + ctx->m_StickCalibrationData[i].min = 40; + ctx->m_StickCalibrationData[i].max = 215; + ctx->m_StickCalibrationData[i].center = 0; + ctx->m_StickCalibrationData[i].deadzone = 10; + } + break; + default: + break; + } +} + +static void InitializeExtension(SDL_DriverWii_Context *ctx) +{ + SendExtensionReset(ctx, true); + InitStickCalibrationData(ctx); + ResetButtonPacketType(ctx); +} + +static void UpdateSlotLED(SDL_DriverWii_Context *ctx) +{ + Uint8 leds; + Uint8 data[2]; + + // The lowest bit needs to have the rumble status + leds = (Uint8)ctx->m_bRumbleActive; + + if (ctx->m_bPlayerLights) { + // Use the same LED codes as Smash 8-player for 5-7 + if (ctx->m_nPlayerIndex == 0 || ctx->m_nPlayerIndex > 3) { + leds |= k_eWiiPlayerLEDs_P1; + } + if (ctx->m_nPlayerIndex == 1 || ctx->m_nPlayerIndex == 4) { + leds |= k_eWiiPlayerLEDs_P2; + } + if (ctx->m_nPlayerIndex == 2 || ctx->m_nPlayerIndex == 5) { + leds |= k_eWiiPlayerLEDs_P3; + } + if (ctx->m_nPlayerIndex == 3 || ctx->m_nPlayerIndex == 6) { + leds |= k_eWiiPlayerLEDs_P4; + } + // Turn on all lights for other player indexes + if (ctx->m_nPlayerIndex < 0 || ctx->m_nPlayerIndex > 6) { + leds |= k_eWiiPlayerLEDs_P1 | k_eWiiPlayerLEDs_P2 | k_eWiiPlayerLEDs_P3 | k_eWiiPlayerLEDs_P4; + } + } + + data[0] = k_eWiiOutputReportIDs_LEDs; + data[1] = leds; + WriteOutput(ctx, data, sizeof(data), false); +} + +static void SDLCALL SDL_PlayerLEDHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverWii_Context *ctx = (SDL_DriverWii_Context *)userdata; + bool bPlayerLights = SDL_GetStringBoolean(hint, true); + + if (bPlayerLights != ctx->m_bPlayerLights) { + ctx->m_bPlayerLights = bPlayerLights; + + UpdateSlotLED(ctx); + } +} + +static EWiiExtensionControllerType ReadExtensionControllerType(SDL_HIDAPI_Device *device) +{ + SDL_DriverWii_Context *ctx = (SDL_DriverWii_Context *)device->context; + EWiiExtensionControllerType eExtensionControllerType = k_eWiiExtensionControllerType_Unknown; + const int MAX_ATTEMPTS = 20; + int attempts = 0; + + // Create enough of a context to read the controller type from the device + for (attempts = 0; attempts < MAX_ATTEMPTS; ++attempts) { + Uint16 extension; + if (SendExtensionIdentify(ctx, true) && + ParseExtensionIdentifyResponse(ctx, &extension)) { + Uint8 motion_plus_mode = 0; + if ((extension & WII_EXTENSION_MOTIONPLUS_MASK) == WII_EXTENSION_MOTIONPLUS_ID) { + motion_plus_mode = (Uint8)(extension >> 8); + } + if (motion_plus_mode || extension == WII_EXTENSION_UNINITIALIZED) { + SendExtensionReset(ctx, true); + if (SendExtensionIdentify(ctx, true)) { + ParseExtensionIdentifyResponse(ctx, &extension); + } + } + + eExtensionControllerType = GetExtensionType(extension); + + // Reset the Motion Plus controller if needed + if (motion_plus_mode) { + ActivateMotionPlusWithMode(ctx, motion_plus_mode); + } + break; + } + } + return eExtensionControllerType; +} + +static void UpdateDeviceIdentity(SDL_HIDAPI_Device *device) +{ + SDL_DriverWii_Context *ctx = (SDL_DriverWii_Context *)device->context; + + switch (ctx->m_eExtensionControllerType) { + case k_eWiiExtensionControllerType_None: + HIDAPI_SetDeviceName(device, "Nintendo Wii Remote"); + break; + case k_eWiiExtensionControllerType_Nunchuk: + HIDAPI_SetDeviceName(device, "Nintendo Wii Remote with Nunchuk"); + break; + case k_eWiiExtensionControllerType_Gamepad: + HIDAPI_SetDeviceName(device, "Nintendo Wii Remote with Classic Controller"); + break; + case k_eWiiExtensionControllerType_WiiUPro: + HIDAPI_SetDeviceName(device, "Nintendo Wii U Pro Controller"); + break; + default: + HIDAPI_SetDeviceName(device, "Nintendo Wii Remote with Unknown Extension"); + break; + } + device->guid.data[15] = ctx->m_eExtensionControllerType; +} + +static bool HIDAPI_DriverWii_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverWii_Context *ctx; + + ctx = (SDL_DriverWii_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + device->context = ctx; + + if (device->vendor_id == USB_VENDOR_NINTENDO) { + ctx->m_eExtensionControllerType = ReadExtensionControllerType(device); + + UpdateDeviceIdentity(device); + } + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverWii_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverWii_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ + SDL_DriverWii_Context *ctx = (SDL_DriverWii_Context *)device->context; + + if (!ctx->joystick) { + return; + } + + ctx->m_nPlayerIndex = player_index; + + UpdateSlotLED(ctx); +} + +static bool HIDAPI_DriverWii_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverWii_Context *ctx = (SDL_DriverWii_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + ctx->joystick = joystick; + + InitializeExtension(ctx); + + GetMotionPlusState(ctx, &ctx->m_bMotionPlusPresent, &ctx->m_ucMotionPlusMode); + + if (NeedsPeriodicMotionPlusCheck(ctx, false)) { + SchedulePeriodicMotionPlusCheck(ctx); + } + + if (ctx->m_eExtensionControllerType == k_eWiiExtensionControllerType_None || + ctx->m_eExtensionControllerType == k_eWiiExtensionControllerType_Nunchuk) { + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 100.0f); + if (ctx->m_eExtensionControllerType == k_eWiiExtensionControllerType_Nunchuk) { + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL_L, 100.0f); + } + + if (ctx->m_bMotionPlusPresent) { + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, 100.0f); + } + } + + // Initialize player index (needed for setting LEDs) + ctx->m_nPlayerIndex = SDL_GetJoystickPlayerIndex(joystick); + ctx->m_bPlayerLights = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_WII_PLAYER_LED, true); + UpdateSlotLED(ctx); + + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_WII_PLAYER_LED, + SDL_PlayerLEDHintChanged, ctx); + + // Initialize the joystick capabilities + if (ctx->m_eExtensionControllerType == k_eWiiExtensionControllerType_WiiUPro) { + joystick->nbuttons = 15; + } else { + // Maximum is Classic Controller + Wiimote + joystick->nbuttons = k_eWiiButtons_Max; + } + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + + ctx->m_ulLastInput = SDL_GetTicks(); + + return true; +} + +static bool HIDAPI_DriverWii_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + SDL_DriverWii_Context *ctx = (SDL_DriverWii_Context *)device->context; + bool active = (low_frequency_rumble || high_frequency_rumble); + + if (active != ctx->m_bRumbleActive) { + Uint8 data[2]; + + data[0] = k_eWiiOutputReportIDs_Rumble; + data[1] = (Uint8)active; + WriteOutput(ctx, data, sizeof(data), false); + + ctx->m_bRumbleActive = active; + } + return true; +} + +static bool HIDAPI_DriverWii_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverWii_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + return SDL_JOYSTICK_CAP_RUMBLE; +} + +static bool HIDAPI_DriverWii_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverWii_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverWii_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + SDL_DriverWii_Context *ctx = (SDL_DriverWii_Context *)device->context; + + if (enabled != ctx->m_bReportSensors) { + ctx->m_bReportSensors = enabled; + + if (ctx->m_bMotionPlusPresent) { + if (enabled) { + ActivateMotionPlus(ctx); + } else { + DeactivateMotionPlus(ctx); + } + } + + ResetButtonPacketType(ctx); + } + return true; +} + +static void PostStickCalibrated(Uint64 timestamp, SDL_Joystick *joystick, StickCalibrationData *calibration, Uint8 axis, Uint16 data) +{ + Sint16 value = 0; + if (!calibration->center) { + // Center on first read + calibration->center = data; + return; + } + if (data < calibration->min) { + calibration->min = data; + } + if (data > calibration->max) { + calibration->max = data; + } + if (data < calibration->center - calibration->deadzone) { + Uint16 zero = calibration->center - calibration->deadzone; + Uint16 range = zero - calibration->min; + Uint16 distance = zero - data; + float fvalue = (float)distance / (float)range; + value = (Sint16)(fvalue * SDL_JOYSTICK_AXIS_MIN); + } else if (data > calibration->center + calibration->deadzone) { + Uint16 zero = calibration->center + calibration->deadzone; + Uint16 range = calibration->max - zero; + Uint16 distance = data - zero; + float fvalue = (float)distance / (float)range; + value = (Sint16)(fvalue * SDL_JOYSTICK_AXIS_MAX); + } + if (axis == SDL_GAMEPAD_AXIS_LEFTY || axis == SDL_GAMEPAD_AXIS_RIGHTY) { + if (value) { + value = ~value; + } + } + SDL_SendJoystickAxis(timestamp, joystick, axis, value); +} + +/* Send button data to SDL + *`defs` is a mapping for each bit to which button it represents. 0xFF indicates an unused bit + *`data` is the button data from the controller + *`size` is the number of bytes in `data` and the number of arrays of 8 mappings in `defs` + *`on` is the joystick value to be sent if a bit is on + *`off` is the joystick value to be sent if a bit is off + */ +static void PostPackedButtonData(Uint64 timestamp, SDL_Joystick *joystick, const Uint8 defs[][8], const Uint8 *data, int size, bool on, bool off) +{ + int i, j; + + for (i = 0; i < size; i++) { + for (j = 0; j < 8; j++) { + Uint8 button = defs[i][j]; + if (button != 0xFF) { + bool down = (data[i] >> j) & 1 ? on : off; + SDL_SendJoystickButton(timestamp, joystick, button, down); + } + } + } +} + +static const Uint8 GAMEPAD_BUTTON_DEFS[3][8] = { + { + 0xFF /* Unused */, + SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, + SDL_GAMEPAD_BUTTON_START, + SDL_GAMEPAD_BUTTON_GUIDE, + SDL_GAMEPAD_BUTTON_BACK, + SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, + SDL_GAMEPAD_BUTTON_DPAD_DOWN, + SDL_GAMEPAD_BUTTON_DPAD_RIGHT, + }, + { + SDL_GAMEPAD_BUTTON_DPAD_UP, + SDL_GAMEPAD_BUTTON_DPAD_LEFT, + 0xFF /* ZR */, + SDL_GAMEPAD_BUTTON_NORTH, + SDL_GAMEPAD_BUTTON_EAST, + SDL_GAMEPAD_BUTTON_WEST, + SDL_GAMEPAD_BUTTON_SOUTH, + 0xFF /*ZL*/, + }, + { + SDL_GAMEPAD_BUTTON_RIGHT_STICK, + SDL_GAMEPAD_BUTTON_LEFT_STICK, + 0xFF /* Charging */, + 0xFF /* Plugged In */, + 0xFF /* Unused */, + 0xFF /* Unused */, + 0xFF /* Unused */, + 0xFF /* Unused */, + } +}; + +static const Uint8 MP_GAMEPAD_BUTTON_DEFS[3][8] = { + { + 0xFF /* Unused */, + SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, + SDL_GAMEPAD_BUTTON_START, + SDL_GAMEPAD_BUTTON_GUIDE, + SDL_GAMEPAD_BUTTON_BACK, + SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, + SDL_GAMEPAD_BUTTON_DPAD_DOWN, + SDL_GAMEPAD_BUTTON_DPAD_RIGHT, + }, + { + 0xFF /* Motion Plus data */, + 0xFF /* Motion Plus data */, + 0xFF /* ZR */, + SDL_GAMEPAD_BUTTON_NORTH, + SDL_GAMEPAD_BUTTON_EAST, + SDL_GAMEPAD_BUTTON_WEST, + SDL_GAMEPAD_BUTTON_SOUTH, + 0xFF /*ZL*/, + }, + { + SDL_GAMEPAD_BUTTON_RIGHT_STICK, + SDL_GAMEPAD_BUTTON_LEFT_STICK, + 0xFF /* Charging */, + 0xFF /* Plugged In */, + 0xFF /* Unused */, + 0xFF /* Unused */, + 0xFF /* Unused */, + 0xFF /* Unused */, + } +}; + +static const Uint8 MP_FIXUP_DPAD_BUTTON_DEFS[2][8] = { + { + SDL_GAMEPAD_BUTTON_DPAD_UP, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + }, + { + SDL_GAMEPAD_BUTTON_DPAD_LEFT, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + } +}; + +static void HandleWiiUProButtonData(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick, const WiiButtonData *data) +{ + static const Uint8 axes[] = { SDL_GAMEPAD_AXIS_LEFTX, SDL_GAMEPAD_AXIS_RIGHTX, SDL_GAMEPAD_AXIS_LEFTY, SDL_GAMEPAD_AXIS_RIGHTY }; + const Uint8(*buttons)[8] = GAMEPAD_BUTTON_DEFS; + Uint8 zl, zr; + int i; + + if (data->ucNExtensionBytes < 11) { + return; + } + + // Buttons + PostPackedButtonData(ctx->timestamp, joystick, buttons, data->rgucExtension + 8, 3, false, true); + + // Triggers + zl = data->rgucExtension[9] & 0x80; + zr = data->rgucExtension[9] & 0x04; + SDL_SendJoystickAxis(ctx->timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, zl ? SDL_JOYSTICK_AXIS_MIN : SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(ctx->timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, zr ? SDL_JOYSTICK_AXIS_MIN : SDL_JOYSTICK_AXIS_MAX); + + // Sticks + for (i = 0; i < 4; i++) { + Uint16 value = data->rgucExtension[i * 2] | (data->rgucExtension[i * 2 + 1] << 8); + PostStickCalibrated(ctx->timestamp, joystick, &ctx->m_StickCalibrationData[i], axes[i], value); + } + + // Power + UpdatePowerLevelWiiU(joystick, data->rgucExtension[10]); +} + +static void HandleGamepadControllerButtonData(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick, const WiiButtonData *data) +{ + const Uint8(*buttons)[8] = (ctx->m_ucMotionPlusMode == WII_MOTIONPLUS_MODE_GAMEPAD) ? MP_GAMEPAD_BUTTON_DEFS : GAMEPAD_BUTTON_DEFS; + Uint8 lx, ly, rx, ry, zl, zr; + + if (data->ucNExtensionBytes < 6) { + return; + } + + // Buttons + PostPackedButtonData(ctx->timestamp, joystick, buttons, data->rgucExtension + 4, 2, false, true); + if (ctx->m_ucMotionPlusMode == WII_MOTIONPLUS_MODE_GAMEPAD) { + PostPackedButtonData(ctx->timestamp, joystick, MP_FIXUP_DPAD_BUTTON_DEFS, data->rgucExtension, 2, false, true); + } + + // Triggers + zl = data->rgucExtension[5] & 0x80; + zr = data->rgucExtension[5] & 0x04; + SDL_SendJoystickAxis(ctx->timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, zl ? SDL_JOYSTICK_AXIS_MIN : SDL_JOYSTICK_AXIS_MAX); + SDL_SendJoystickAxis(ctx->timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, zr ? SDL_JOYSTICK_AXIS_MIN : SDL_JOYSTICK_AXIS_MAX); + + // Sticks + if (ctx->m_ucMotionPlusMode == WII_MOTIONPLUS_MODE_GAMEPAD) { + lx = data->rgucExtension[0] & 0x3E; + ly = data->rgucExtension[1] & 0x3E; + } else { + lx = data->rgucExtension[0] & 0x3F; + ly = data->rgucExtension[1] & 0x3F; + } + rx = (data->rgucExtension[2] >> 7) | ((data->rgucExtension[1] >> 5) & 0x06) | ((data->rgucExtension[0] >> 3) & 0x18); + ry = data->rgucExtension[2] & 0x1F; + PostStickCalibrated(ctx->timestamp, joystick, &ctx->m_StickCalibrationData[0], SDL_GAMEPAD_AXIS_LEFTX, lx); + PostStickCalibrated(ctx->timestamp, joystick, &ctx->m_StickCalibrationData[1], SDL_GAMEPAD_AXIS_LEFTY, ly); + PostStickCalibrated(ctx->timestamp, joystick, &ctx->m_StickCalibrationData[2], SDL_GAMEPAD_AXIS_RIGHTX, rx); + PostStickCalibrated(ctx->timestamp, joystick, &ctx->m_StickCalibrationData[3], SDL_GAMEPAD_AXIS_RIGHTY, ry); +} + +static void HandleWiiRemoteButtonData(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick, const WiiButtonData *data) +{ + static const Uint8 buttons[2][8] = { + { + k_eWiiButtons_DPad_Left, + k_eWiiButtons_DPad_Right, + k_eWiiButtons_DPad_Down, + k_eWiiButtons_DPad_Up, + k_eWiiButtons_Plus, + 0xFF /* Unused */, + 0xFF /* Unused */, + 0xFF /* Unused */, + }, + { + k_eWiiButtons_Two, + k_eWiiButtons_One, + k_eWiiButtons_B, + k_eWiiButtons_A, + k_eWiiButtons_Minus, + 0xFF /* Unused */, + 0xFF /* Unused */, + k_eWiiButtons_Home, + } + }; + if (data->hasBaseButtons) { + PostPackedButtonData(ctx->timestamp, joystick, buttons, data->rgucBaseButtons, 2, true, false); + } +} + +static void HandleWiiRemoteButtonDataAsMainController(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick, const WiiButtonData *data) +{ + /* Wii remote maps really badly to a normal controller + * Mapped 1 and 2 as X and Y + * Not going to attempt positional mapping + */ + static const Uint8 buttons[2][8] = { + { + SDL_GAMEPAD_BUTTON_DPAD_LEFT, + SDL_GAMEPAD_BUTTON_DPAD_RIGHT, + SDL_GAMEPAD_BUTTON_DPAD_DOWN, + SDL_GAMEPAD_BUTTON_DPAD_UP, + SDL_GAMEPAD_BUTTON_START, + 0xFF /* Unused */, + 0xFF /* Unused */, + 0xFF /* Unused */, + }, + { + SDL_GAMEPAD_BUTTON_NORTH, + SDL_GAMEPAD_BUTTON_WEST, + SDL_GAMEPAD_BUTTON_SOUTH, + SDL_GAMEPAD_BUTTON_EAST, + SDL_GAMEPAD_BUTTON_BACK, + 0xFF /* Unused */, + 0xFF /* Unused */, + SDL_GAMEPAD_BUTTON_GUIDE, + } + }; + if (data->hasBaseButtons) { + PostPackedButtonData(ctx->timestamp, joystick, buttons, data->rgucBaseButtons, 2, true, false); + } +} + +static void HandleNunchuckButtonData(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick, const WiiButtonData *data) +{ + bool c_button, z_button; + + if (data->ucNExtensionBytes < 6) { + return; + } + + if (ctx->m_ucMotionPlusMode == WII_MOTIONPLUS_MODE_NUNCHUK) { + c_button = (data->rgucExtension[5] & 0x08) ? false : true; + z_button = (data->rgucExtension[5] & 0x04) ? false : true; + } else { + c_button = (data->rgucExtension[5] & 0x02) ? false : true; + z_button = (data->rgucExtension[5] & 0x01) ? false : true; + } + SDL_SendJoystickButton(ctx->timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, c_button); + SDL_SendJoystickAxis(ctx->timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, z_button ? SDL_JOYSTICK_AXIS_MAX : SDL_JOYSTICK_AXIS_MIN); + PostStickCalibrated(ctx->timestamp, joystick, &ctx->m_StickCalibrationData[0], SDL_GAMEPAD_AXIS_LEFTX, data->rgucExtension[0]); + PostStickCalibrated(ctx->timestamp, joystick, &ctx->m_StickCalibrationData[1], SDL_GAMEPAD_AXIS_LEFTY, data->rgucExtension[1]); + + if (ctx->m_bReportSensors) { + const float ACCEL_RES_PER_G = 200.0f; + Sint16 x, y, z; + float values[3]; + + x = (data->rgucExtension[2] << 2); + y = (data->rgucExtension[3] << 2); + z = (data->rgucExtension[4] << 2); + + if (ctx->m_ucMotionPlusMode == WII_MOTIONPLUS_MODE_NUNCHUK) { + x |= ((data->rgucExtension[5] >> 3) & 0x02); + y |= ((data->rgucExtension[5] >> 4) & 0x02); + z &= ~0x04; + z |= ((data->rgucExtension[5] >> 5) & 0x06); + } else { + x |= ((data->rgucExtension[5] >> 2) & 0x03); + y |= ((data->rgucExtension[5] >> 4) & 0x03); + z |= ((data->rgucExtension[5] >> 6) & 0x03); + } + + x -= 0x200; + y -= 0x200; + z -= 0x200; + + values[0] = -((float)x / ACCEL_RES_PER_G) * SDL_STANDARD_GRAVITY; + values[1] = ((float)z / ACCEL_RES_PER_G) * SDL_STANDARD_GRAVITY; + values[2] = ((float)y / ACCEL_RES_PER_G) * SDL_STANDARD_GRAVITY; + SDL_SendJoystickSensor(ctx->timestamp, joystick, SDL_SENSOR_ACCEL_L, ctx->timestamp, values, 3); + } +} + +static void HandleMotionPlusData(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick, const WiiButtonData *data) +{ + if (ctx->m_bReportSensors) { + const float GYRO_RES_PER_DEGREE = 8192.0f; + int x, y, z; + float values[3]; + + x = (data->rgucExtension[0] | ((data->rgucExtension[3] << 6) & 0xFF00)) - 8192; + y = (data->rgucExtension[1] | ((data->rgucExtension[4] << 6) & 0xFF00)) - 8192; + z = (data->rgucExtension[2] | ((data->rgucExtension[5] << 6) & 0xFF00)) - 8192; + + if (data->rgucExtension[3] & 0x02) { + // Slow rotation rate: 8192/440 units per deg/s + x *= 440; + } else { + // Fast rotation rate: 8192/2000 units per deg/s + x *= 2000; + } + if (data->rgucExtension[4] & 0x02) { + // Slow rotation rate: 8192/440 units per deg/s + y *= 440; + } else { + // Fast rotation rate: 8192/2000 units per deg/s + y *= 2000; + } + if (data->rgucExtension[3] & 0x01) { + // Slow rotation rate: 8192/440 units per deg/s + z *= 440; + } else { + // Fast rotation rate: 8192/2000 units per deg/s + z *= 2000; + } + + values[0] = -((float)z / GYRO_RES_PER_DEGREE) * SDL_PI_F / 180.0f; + values[1] = ((float)x / GYRO_RES_PER_DEGREE) * SDL_PI_F / 180.0f; + values[2] = ((float)y / GYRO_RES_PER_DEGREE) * SDL_PI_F / 180.0f; + SDL_SendJoystickSensor(ctx->timestamp, joystick, SDL_SENSOR_GYRO, ctx->timestamp, values, 3); + } +} + +static void HandleWiiRemoteAccelData(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick, const WiiButtonData *data) +{ + const float ACCEL_RES_PER_G = 100.0f; + Sint16 x, y, z; + float values[3]; + + if (!ctx->m_bReportSensors) { + return; + } + + x = ((data->rgucAccelerometer[0] << 2) | ((data->rgucBaseButtons[0] >> 5) & 0x03)) - 0x200; + y = ((data->rgucAccelerometer[1] << 2) | ((data->rgucBaseButtons[1] >> 4) & 0x02)) - 0x200; + z = ((data->rgucAccelerometer[2] << 2) | ((data->rgucBaseButtons[1] >> 5) & 0x02)) - 0x200; + + values[0] = -((float)x / ACCEL_RES_PER_G) * SDL_STANDARD_GRAVITY; + values[1] = ((float)z / ACCEL_RES_PER_G) * SDL_STANDARD_GRAVITY; + values[2] = ((float)y / ACCEL_RES_PER_G) * SDL_STANDARD_GRAVITY; + SDL_SendJoystickSensor(ctx->timestamp, joystick, SDL_SENSOR_ACCEL, ctx->timestamp, values, 3); +} + +static void HandleButtonData(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick, WiiButtonData *data) +{ + if (ctx->m_eExtensionControllerType == k_eWiiExtensionControllerType_WiiUPro) { + HandleWiiUProButtonData(ctx, joystick, data); + return; + } + + if (ctx->m_ucMotionPlusMode != WII_MOTIONPLUS_MODE_NONE && + data->ucNExtensionBytes > 5) { + if (data->rgucExtension[5] & 0x01) { + // The data is invalid, possibly during a hotplug + return; + } + + if (data->rgucExtension[4] & 0x01) { + if (ctx->m_eExtensionControllerType == k_eWiiExtensionControllerType_None) { + // Something was plugged into the extension port, reinitialize to get new state + ctx->m_bDisconnected = true; + } + } else { + if (ctx->m_eExtensionControllerType != k_eWiiExtensionControllerType_None) { + // Something was removed from the extension port, reinitialize to get new state + ctx->m_bDisconnected = true; + } + } + + if (data->rgucExtension[5] & 0x02) { + HandleMotionPlusData(ctx, joystick, data); + + // The extension data is consumed + data->ucNExtensionBytes = 0; + } + } + + HandleWiiRemoteButtonData(ctx, joystick, data); + switch (ctx->m_eExtensionControllerType) { + case k_eWiiExtensionControllerType_Nunchuk: + HandleNunchuckButtonData(ctx, joystick, data); + SDL_FALLTHROUGH; + case k_eWiiExtensionControllerType_None: + HandleWiiRemoteButtonDataAsMainController(ctx, joystick, data); + break; + case k_eWiiExtensionControllerType_Gamepad: + HandleGamepadControllerButtonData(ctx, joystick, data); + break; + default: + break; + } + HandleWiiRemoteAccelData(ctx, joystick, data); +} + +static void GetBaseButtons(WiiButtonData *dst, const Uint8 *src) +{ + SDL_memcpy(dst->rgucBaseButtons, src, 2); + dst->hasBaseButtons = true; +} + +static void GetAccelerometer(WiiButtonData *dst, const Uint8 *src) +{ + SDL_memcpy(dst->rgucAccelerometer, src, 3); + dst->hasAccelerometer = true; +} + +static void GetExtensionData(WiiButtonData *dst, const Uint8 *src, int size) +{ + bool valid_data = false; + int i; + + if (size > sizeof(dst->rgucExtension)) { + size = sizeof(dst->rgucExtension); + } + + for (i = 0; i < size; ++i) { + if (src[i] != 0xFF) { + valid_data = true; + break; + } + } + if (valid_data) { + SDL_memcpy(dst->rgucExtension, src, size); + dst->ucNExtensionBytes = (Uint8)size; + } +} + +static void HandleStatus(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick) +{ + bool hadExtension = ctx->m_eExtensionControllerType != k_eWiiExtensionControllerType_None; + bool hasExtension = (ctx->m_rgucReadBuffer[3] & 2) ? true : false; + WiiButtonData data; + SDL_zero(data); + GetBaseButtons(&data, ctx->m_rgucReadBuffer + 1); + HandleButtonData(ctx, joystick, &data); + + if (ctx->m_eExtensionControllerType != k_eWiiExtensionControllerType_WiiUPro) { + // Wii U has separate battery level tracking + UpdatePowerLevelWii(joystick, ctx->m_rgucReadBuffer[6]); + } + + // The report data format has been reset, need to update it + ResetButtonPacketType(ctx); + + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, "HIDAPI Wii: Status update, extension %s", hasExtension ? "CONNECTED" : "DISCONNECTED"); + + /* When Motion Plus is active, we get extension connect/disconnect status + * through the Motion Plus packets. Otherwise we can use the status here. + */ + if (ctx->m_ucMotionPlusMode != WII_MOTIONPLUS_MODE_NONE) { + /* Check to make sure the Motion Plus extension state hasn't changed, + * otherwise we'll get extension connect/disconnect status through + * Motion Plus packets. + */ + if (NeedsPeriodicMotionPlusCheck(ctx, true)) { + ctx->m_ulNextMotionPlusCheck = SDL_GetTicks(); + } + + } else if (hadExtension != hasExtension) { + // Reinitialize to get new state + ctx->m_bDisconnected = true; + } +} + +static void HandleResponse(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick) +{ + EWiiInputReportIDs type = (EWiiInputReportIDs)ctx->m_rgucReadBuffer[0]; + WiiButtonData data; + SDL_assert(type == k_eWiiInputReportIDs_Acknowledge || type == k_eWiiInputReportIDs_ReadMemory); + SDL_zero(data); + GetBaseButtons(&data, ctx->m_rgucReadBuffer + 1); + HandleButtonData(ctx, joystick, &data); + + switch (ctx->m_eCommState) { + case k_eWiiCommunicationState_None: + break; + + case k_eWiiCommunicationState_CheckMotionPlusStage1: + case k_eWiiCommunicationState_CheckMotionPlusStage2: + { + Uint16 extension = 0; + if (ParseExtensionIdentifyResponse(ctx, &extension)) { + if ((extension & WII_EXTENSION_MOTIONPLUS_MASK) == WII_EXTENSION_MOTIONPLUS_ID) { + // Motion Plus is currently active + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, "HIDAPI Wii: Motion Plus CONNECTED (stage %d)", ctx->m_eCommState == k_eWiiCommunicationState_CheckMotionPlusStage1 ? 1 : 2); + + if (!ctx->m_bMotionPlusPresent) { + // Reinitialize to get new sensor availability + ctx->m_bDisconnected = true; + } + ctx->m_eCommState = k_eWiiCommunicationState_None; + + } else if (ctx->m_eCommState == k_eWiiCommunicationState_CheckMotionPlusStage1) { + // Check to see if Motion Plus is present + ReadRegister(ctx, 0xA600FE, 2, false); + + ctx->m_eCommState = k_eWiiCommunicationState_CheckMotionPlusStage2; + + } else { + // Motion Plus is not present + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, "HIDAPI Wii: Motion Plus DISCONNECTED (stage %d)", ctx->m_eCommState == k_eWiiCommunicationState_CheckMotionPlusStage1 ? 1 : 2); + + if (ctx->m_bMotionPlusPresent) { + // Reinitialize to get new sensor availability + ctx->m_bDisconnected = true; + } + ctx->m_eCommState = k_eWiiCommunicationState_None; + } + } + } break; + default: + // Should never happen + break; + } +} + +static void HandleButtonPacket(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick) +{ + EWiiInputReportIDs eExpectedReport = GetButtonPacketType(ctx); + WiiButtonData data; + + // FIXME: This should see if the data format is compatible rather than equal + if (eExpectedReport != ctx->m_rgucReadBuffer[0]) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, "HIDAPI Wii: Resetting report mode to %d", eExpectedReport); + RequestButtonPacketType(ctx, eExpectedReport); + } + + // IR camera data is not supported + SDL_zero(data); + switch (ctx->m_rgucReadBuffer[0]) { + case k_eWiiInputReportIDs_ButtonData0: // 30 BB BB + GetBaseButtons(&data, ctx->m_rgucReadBuffer + 1); + break; + case k_eWiiInputReportIDs_ButtonData1: // 31 BB BB AA AA AA + case k_eWiiInputReportIDs_ButtonData3: // 33 BB BB AA AA AA II II II II II II II II II II II II + GetBaseButtons(&data, ctx->m_rgucReadBuffer + 1); + GetAccelerometer(&data, ctx->m_rgucReadBuffer + 3); + break; + case k_eWiiInputReportIDs_ButtonData2: // 32 BB BB EE EE EE EE EE EE EE EE + GetBaseButtons(&data, ctx->m_rgucReadBuffer + 1); + GetExtensionData(&data, ctx->m_rgucReadBuffer + 3, 8); + break; + case k_eWiiInputReportIDs_ButtonData4: // 34 BB BB EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE + GetBaseButtons(&data, ctx->m_rgucReadBuffer + 1); + GetExtensionData(&data, ctx->m_rgucReadBuffer + 3, 19); + break; + case k_eWiiInputReportIDs_ButtonData5: // 35 BB BB AA AA AA EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE + GetBaseButtons(&data, ctx->m_rgucReadBuffer + 1); + GetAccelerometer(&data, ctx->m_rgucReadBuffer + 3); + GetExtensionData(&data, ctx->m_rgucReadBuffer + 6, 16); + break; + case k_eWiiInputReportIDs_ButtonData6: // 36 BB BB II II II II II II II II II II EE EE EE EE EE EE EE EE EE + GetBaseButtons(&data, ctx->m_rgucReadBuffer + 1); + GetExtensionData(&data, ctx->m_rgucReadBuffer + 13, 9); + break; + case k_eWiiInputReportIDs_ButtonData7: // 37 BB BB AA AA AA II II II II II II II II II II EE EE EE EE EE EE + GetBaseButtons(&data, ctx->m_rgucReadBuffer + 1); + GetExtensionData(&data, ctx->m_rgucReadBuffer + 16, 6); + break; + case k_eWiiInputReportIDs_ButtonDataD: // 3d EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE + GetExtensionData(&data, ctx->m_rgucReadBuffer + 1, 21); + break; + case k_eWiiInputReportIDs_ButtonDataE: + case k_eWiiInputReportIDs_ButtonDataF: + default: + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, "HIDAPI Wii: Unsupported button data type %02x", ctx->m_rgucReadBuffer[0]); + return; + } + HandleButtonData(ctx, joystick, &data); +} + +static void HandleInput(SDL_DriverWii_Context *ctx, SDL_Joystick *joystick) +{ + EWiiInputReportIDs type = (EWiiInputReportIDs)ctx->m_rgucReadBuffer[0]; + + // Set up for handling input + ctx->timestamp = SDL_GetTicksNS(); + + if (type == k_eWiiInputReportIDs_Status) { + HandleStatus(ctx, joystick); + } else if (type == k_eWiiInputReportIDs_Acknowledge || type == k_eWiiInputReportIDs_ReadMemory) { + HandleResponse(ctx, joystick); + } else if (type >= k_eWiiInputReportIDs_ButtonData0 && type <= k_eWiiInputReportIDs_ButtonDataF) { + HandleButtonPacket(ctx, joystick); + } else { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, "HIDAPI Wii: Unexpected input packet of type %x", type); + } +} + +static bool HIDAPI_DriverWii_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverWii_Context *ctx = (SDL_DriverWii_Context *)device->context; + SDL_Joystick *joystick = NULL; + int size; + Uint64 now; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } else { + return false; + } + + now = SDL_GetTicks(); + + while ((size = ReadInput(ctx)) > 0) { + if (joystick) { + HandleInput(ctx, joystick); + } + ctx->m_ulLastInput = now; + } + + /* Check to see if we've lost connection to the controller. + * We have continuous reporting enabled, so this should be reliable now. + */ + { + SDL_COMPILE_TIME_ASSERT(ENABLE_CONTINUOUS_REPORTING, ENABLE_CONTINUOUS_REPORTING); + } + if (now >= (ctx->m_ulLastInput + INPUT_WAIT_TIMEOUT_MS)) { + // Bluetooth may have disconnected, try reopening the controller + size = -1; + } + + if (joystick) { + // These checks aren't needed on the Wii U Pro Controller + if (ctx->m_eExtensionControllerType != k_eWiiExtensionControllerType_WiiUPro) { + + // Check to see if the Motion Plus extension status has changed + if (ctx->m_ulNextMotionPlusCheck && now >= ctx->m_ulNextMotionPlusCheck) { + CheckMotionPlusConnection(ctx); + if (NeedsPeriodicMotionPlusCheck(ctx, false)) { + SchedulePeriodicMotionPlusCheck(ctx); + } else { + ctx->m_ulNextMotionPlusCheck = 0; + } + } + + // Request a status update periodically to make sure our battery value is up to date + if (!ctx->m_ulLastStatus || now >= (ctx->m_ulLastStatus + STATUS_UPDATE_TIME_MS)) { + Uint8 data[2]; + + data[0] = k_eWiiOutputReportIDs_StatusRequest; + data[1] = (Uint8)ctx->m_bRumbleActive; + WriteOutput(ctx, data, sizeof(data), false); + + ctx->m_ulLastStatus = now; + } + } + } + + if (size < 0 || ctx->m_bDisconnected) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverWii_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverWii_Context *ctx = (SDL_DriverWii_Context *)device->context; + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_WII_PLAYER_LED, + SDL_PlayerLEDHintChanged, ctx); + + ctx->joystick = NULL; +} + +static void HIDAPI_DriverWii_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverWii = { + SDL_HINT_JOYSTICK_HIDAPI_WII, + true, + HIDAPI_DriverWii_RegisterHints, + HIDAPI_DriverWii_UnregisterHints, + HIDAPI_DriverWii_IsEnabled, + HIDAPI_DriverWii_IsSupportedDevice, + HIDAPI_DriverWii_InitDevice, + HIDAPI_DriverWii_GetDevicePlayerIndex, + HIDAPI_DriverWii_SetDevicePlayerIndex, + HIDAPI_DriverWii_UpdateDevice, + HIDAPI_DriverWii_OpenJoystick, + HIDAPI_DriverWii_RumbleJoystick, + HIDAPI_DriverWii_RumbleJoystickTriggers, + HIDAPI_DriverWii_GetJoystickCapabilities, + HIDAPI_DriverWii_SetJoystickLED, + HIDAPI_DriverWii_SendJoystickEffect, + HIDAPI_DriverWii_SetJoystickSensorsEnabled, + HIDAPI_DriverWii_CloseJoystick, + HIDAPI_DriverWii_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_WII + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_xbox360.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_xbox360.c new file mode 100644 index 00000000000..49be08ab52b --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_xbox360.c @@ -0,0 +1,379 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../../SDL_hints_c.h" +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" + +#ifdef SDL_JOYSTICK_HIDAPI_XBOX360 + +// Define this if you want to log all packets from the controller +// #define DEBUG_XBOX_PROTOCOL + +typedef struct +{ + SDL_HIDAPI_Device *device; + SDL_Joystick *joystick; + int player_index; + bool player_lights; + Uint8 last_state[USB_PACKET_LENGTH]; +} SDL_DriverXbox360_Context; + +static void HIDAPI_DriverXbox360_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX, callback, userdata); + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360, callback, userdata); +} + +static void HIDAPI_DriverXbox360_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX, callback, userdata); + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360, callback, userdata); +} + +static bool HIDAPI_DriverXbox360_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360, + SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_XBOX, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT))); +} + +static bool HIDAPI_DriverXbox360_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + const int XB360W_IFACE_PROTOCOL = 129; // Wireless + + if (vendor_id == USB_VENDOR_ASTRO && product_id == USB_PRODUCT_ASTRO_C40_XBOX360) { + // This is the ASTRO C40 in Xbox 360 mode + return true; + } + if (vendor_id == USB_VENDOR_NVIDIA) { + // This is the NVIDIA Shield controller which doesn't talk Xbox controller protocol + return false; + } + if ((vendor_id == USB_VENDOR_MICROSOFT && (product_id == USB_PRODUCT_XBOX360_WIRELESS_RECEIVER_THIRDPARTY2 || product_id == USB_PRODUCT_XBOX360_WIRELESS_RECEIVER)) || + (type == SDL_GAMEPAD_TYPE_XBOX360 && interface_protocol == XB360W_IFACE_PROTOCOL)) { + // This is the wireless dongle, which talks a different protocol + return false; + } + if (interface_number > 0) { + // This is the chatpad or other input interface, not the Xbox 360 interface + return false; + } +#if defined(SDL_PLATFORM_MACOS) && defined(SDL_JOYSTICK_MFI) + if (SDL_IsJoystickSteamVirtualGamepad(vendor_id, product_id, version)) { + // GCController support doesn't work with the Steam Virtual Gamepad + return true; + } else { + // On macOS you can't write output reports to wired XBox controllers, + // so we'll just use the GCController support instead. + return false; + } +#else + return (type == SDL_GAMEPAD_TYPE_XBOX360); +#endif +} + +static bool SetSlotLED(SDL_hid_device *dev, Uint8 slot, bool on) +{ + const bool blink = false; + Uint8 mode = on ? ((blink ? 0x02 : 0x06) + slot) : 0; + Uint8 led_packet[] = { 0x01, 0x03, 0x00 }; + + led_packet[2] = mode; + if (SDL_hid_write(dev, led_packet, sizeof(led_packet)) != sizeof(led_packet)) { + return false; + } + return true; +} + +static void UpdateSlotLED(SDL_DriverXbox360_Context *ctx) +{ + if (ctx->player_lights && ctx->player_index >= 0) { + SetSlotLED(ctx->device->dev, (ctx->player_index % 4), true); + } else { + SetSlotLED(ctx->device->dev, 0, false); + } +} + +static void SDLCALL SDL_PlayerLEDHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)userdata; + bool player_lights = SDL_GetStringBoolean(hint, true); + + if (player_lights != ctx->player_lights) { + ctx->player_lights = player_lights; + + UpdateSlotLED(ctx); + HIDAPI_UpdateDeviceProperties(ctx->device); + } +} + +static bool HIDAPI_DriverXbox360_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverXbox360_Context *ctx; + + ctx = (SDL_DriverXbox360_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + + device->context = ctx; + + device->type = SDL_GAMEPAD_TYPE_XBOX360; + + if (SDL_IsJoystickSteamVirtualGamepad(device->vendor_id, device->product_id, device->version) && + device->product_string && SDL_strncmp(device->product_string, "GamePad-", 8) == 0) { + int slot = 0; + SDL_sscanf(device->product_string, "GamePad-%d", &slot); + device->steam_virtual_gamepad_slot = (slot - 1); + } + + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverXbox360_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverXbox360_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ + SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context; + + if (!ctx->joystick) { + return; + } + + ctx->player_index = player_index; + + UpdateSlotLED(ctx); +} + +static bool HIDAPI_DriverXbox360_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + ctx->joystick = joystick; + SDL_zeroa(ctx->last_state); + + // Initialize player index (needed for setting LEDs) + ctx->player_index = SDL_GetJoystickPlayerIndex(joystick); + ctx->player_lights = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_PLAYER_LED, true); + UpdateSlotLED(ctx); + + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_PLAYER_LED, + SDL_PlayerLEDHintChanged, ctx); + + // Initialize the joystick capabilities + joystick->nbuttons = 11; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + + return true; +} + +static bool HIDAPI_DriverXbox360_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + Uint8 rumble_packet[] = { 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + rumble_packet[3] = (low_frequency_rumble >> 8); + rumble_packet[4] = (high_frequency_rumble >> 8); + + if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { + return SDL_SetError("Couldn't send rumble packet"); + } + return true; +} + +static bool HIDAPI_DriverXbox360_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverXbox360_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context; + Uint32 result = SDL_JOYSTICK_CAP_RUMBLE; + + if (ctx->player_lights) { + result |= SDL_JOYSTICK_CAP_PLAYER_LED; + } + return result; +} + +static bool HIDAPI_DriverXbox360_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverXbox360_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverXbox360_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static void HIDAPI_DriverXbox360_HandleStatePacket(SDL_Joystick *joystick, SDL_DriverXbox360_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; +#ifdef SDL_PLATFORM_MACOS + const bool invert_y_axes = false; +#else + const bool invert_y_axes = true; +#endif + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->last_state[2] != data[2]) { + Uint8 hat = 0; + + if (data[2] & 0x01) { + hat |= SDL_HAT_UP; + } + if (data[2] & 0x02) { + hat |= SDL_HAT_DOWN; + } + if (data[2] & 0x04) { + hat |= SDL_HAT_LEFT; + } + if (data[2] & 0x08) { + hat |= SDL_HAT_RIGHT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[2] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[2] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[2] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[2] & 0x80) != 0)); + } + + if (ctx->last_state[3] != data[3]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[3] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[3] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[3] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[3] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[3] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[3] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[3] & 0x80) != 0)); + } + + axis = ((int)data[4] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + axis = ((int)data[5] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[6])); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[8])); + if (invert_y_axes) { + axis = ~axis; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[10])); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[12])); + if (invert_y_axes) { + axis = ~axis; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + SDL_memcpy(ctx->last_state, data, SDL_min((size_t)size, sizeof(ctx->last_state))); +} + +static bool HIDAPI_DriverXbox360_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH]; + int size = 0; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } else { + return false; + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { +#ifdef DEBUG_XBOX_PROTOCOL + HIDAPI_DumpPacket("Xbox 360 packet: size = %d", data, size); +#endif + if (!joystick) { + continue; + } + + if (data[0] == 0x00) { + HIDAPI_DriverXbox360_HandleStatePacket(joystick, ctx, data, size); + } + } + + if (size < 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverXbox360_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context; + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_PLAYER_LED, + SDL_PlayerLEDHintChanged, ctx); + + ctx->joystick = NULL; +} + +static void HIDAPI_DriverXbox360_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXbox360 = { + SDL_HINT_JOYSTICK_HIDAPI_XBOX_360, + true, + HIDAPI_DriverXbox360_RegisterHints, + HIDAPI_DriverXbox360_UnregisterHints, + HIDAPI_DriverXbox360_IsEnabled, + HIDAPI_DriverXbox360_IsSupportedDevice, + HIDAPI_DriverXbox360_InitDevice, + HIDAPI_DriverXbox360_GetDevicePlayerIndex, + HIDAPI_DriverXbox360_SetDevicePlayerIndex, + HIDAPI_DriverXbox360_UpdateDevice, + HIDAPI_DriverXbox360_OpenJoystick, + HIDAPI_DriverXbox360_RumbleJoystick, + HIDAPI_DriverXbox360_RumbleJoystickTriggers, + HIDAPI_DriverXbox360_GetJoystickCapabilities, + HIDAPI_DriverXbox360_SetJoystickLED, + HIDAPI_DriverXbox360_SendJoystickEffect, + HIDAPI_DriverXbox360_SetJoystickSensorsEnabled, + HIDAPI_DriverXbox360_CloseJoystick, + HIDAPI_DriverXbox360_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_XBOX360 + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_xbox360w.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_xbox360w.c new file mode 100644 index 00000000000..bf63707a0ac --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_xbox360w.c @@ -0,0 +1,388 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../../SDL_hints_c.h" +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" + +#ifdef SDL_JOYSTICK_HIDAPI_XBOX360 + +// Define this if you want to log all packets from the controller +// #define DEBUG_XBOX_PROTOCOL + +typedef struct +{ + SDL_HIDAPI_Device *device; + bool connected; + int player_index; + bool player_lights; + Uint8 last_state[USB_PACKET_LENGTH]; +} SDL_DriverXbox360W_Context; + +static void HIDAPI_DriverXbox360W_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX, callback, userdata); + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360, callback, userdata); + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_WIRELESS, callback, userdata); +} + +static void HIDAPI_DriverXbox360W_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX, callback, userdata); + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360, callback, userdata); + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_WIRELESS, callback, userdata); +} + +static bool HIDAPI_DriverXbox360W_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_WIRELESS, + SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_XBOX, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT)))); +} + +static bool HIDAPI_DriverXbox360W_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + const int XB360W_IFACE_PROTOCOL = 129; // Wireless + + if ((vendor_id == USB_VENDOR_MICROSOFT && (product_id == USB_PRODUCT_XBOX360_WIRELESS_RECEIVER_THIRDPARTY2 || product_id == USB_PRODUCT_XBOX360_WIRELESS_RECEIVER_THIRDPARTY1 || product_id == USB_PRODUCT_XBOX360_WIRELESS_RECEIVER) && interface_protocol == 0) || + (type == SDL_GAMEPAD_TYPE_XBOX360 && interface_protocol == XB360W_IFACE_PROTOCOL)) { + return true; + } + return false; +} + +static bool SetSlotLED(SDL_hid_device *dev, Uint8 slot, bool on) +{ + const bool blink = false; + Uint8 mode = on ? ((blink ? 0x02 : 0x06) + slot) : 0; + Uint8 led_packet[] = { 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + led_packet[3] = 0x40 + (mode % 0x0e); + if (SDL_hid_write(dev, led_packet, sizeof(led_packet)) != sizeof(led_packet)) { + return false; + } + return true; +} + +static void UpdateSlotLED(SDL_DriverXbox360W_Context *ctx) +{ + if (ctx->player_lights && ctx->player_index >= 0) { + SetSlotLED(ctx->device->dev, (ctx->player_index % 4), true); + } else { + SetSlotLED(ctx->device->dev, 0, false); + } +} + +static void SDLCALL SDL_PlayerLEDHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverXbox360W_Context *ctx = (SDL_DriverXbox360W_Context *)userdata; + bool player_lights = SDL_GetStringBoolean(hint, true); + + if (player_lights != ctx->player_lights) { + ctx->player_lights = player_lights; + + UpdateSlotLED(ctx); + HIDAPI_UpdateDeviceProperties(ctx->device); + } +} + +static void UpdatePowerLevel(SDL_Joystick *joystick, Uint8 level) +{ + int percent = (int)SDL_roundf((level / 255.0f) * 100.0f); + SDL_SendJoystickPowerInfo(joystick, SDL_POWERSTATE_ON_BATTERY, percent); +} + +static bool HIDAPI_DriverXbox360W_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverXbox360W_Context *ctx; + + // Requests controller presence information from the wireless dongle + const Uint8 init_packet[] = { 0x08, 0x00, 0x0F, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + HIDAPI_SetDeviceName(device, "Xbox 360 Wireless Controller"); + + ctx = (SDL_DriverXbox360W_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + + device->context = ctx; + + if (SDL_hid_write(device->dev, init_packet, sizeof(init_packet)) != sizeof(init_packet)) { + SDL_SetError("Couldn't write init packet"); + return false; + } + + device->type = SDL_GAMEPAD_TYPE_XBOX360; + + return true; +} + +static int HIDAPI_DriverXbox360W_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverXbox360W_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ + SDL_DriverXbox360W_Context *ctx = (SDL_DriverXbox360W_Context *)device->context; + + if (!ctx) { + return; + } + + ctx->player_index = player_index; + + UpdateSlotLED(ctx); +} + +static bool HIDAPI_DriverXbox360W_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverXbox360W_Context *ctx = (SDL_DriverXbox360W_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + SDL_zeroa(ctx->last_state); + + // Initialize player index (needed for setting LEDs) + ctx->player_index = SDL_GetJoystickPlayerIndex(joystick); + ctx->player_lights = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_PLAYER_LED, true); + UpdateSlotLED(ctx); + + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_PLAYER_LED, + SDL_PlayerLEDHintChanged, ctx); + + // Initialize the joystick capabilities + joystick->nbuttons = 11; + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRELESS; + + return true; +} + +static bool HIDAPI_DriverXbox360W_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + Uint8 rumble_packet[] = { 0x00, 0x01, 0x0f, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + rumble_packet[5] = (low_frequency_rumble >> 8); + rumble_packet[6] = (high_frequency_rumble >> 8); + + if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { + return SDL_SetError("Couldn't send rumble packet"); + } + return true; +} + +static bool HIDAPI_DriverXbox360W_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static Uint32 HIDAPI_DriverXbox360W_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverXbox360W_Context *ctx = (SDL_DriverXbox360W_Context *)device->context; + Uint32 result = SDL_JOYSTICK_CAP_RUMBLE; + + if (ctx->player_lights) { + result |= SDL_JOYSTICK_CAP_PLAYER_LED; + } + return result; +} + +static bool HIDAPI_DriverXbox360W_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverXbox360W_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverXbox360W_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static void HIDAPI_DriverXbox360W_HandleStatePacket(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverXbox360W_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; + const bool invert_y_axes = true; + Uint64 timestamp = SDL_GetTicksNS(); + + if (ctx->last_state[2] != data[2]) { + Uint8 hat = 0; + + if (data[2] & 0x01) { + hat |= SDL_HAT_UP; + } + if (data[2] & 0x02) { + hat |= SDL_HAT_DOWN; + } + if (data[2] & 0x04) { + hat |= SDL_HAT_LEFT; + } + if (data[2] & 0x08) { + hat |= SDL_HAT_RIGHT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[2] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[2] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[2] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[2] & 0x80) != 0)); + } + + if (ctx->last_state[3] != data[3]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[3] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[3] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[3] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[3] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[3] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[3] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[3] & 0x80) != 0)); + } + + axis = ((int)data[4] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + axis = ((int)data[5] * 257) - 32768; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[6])); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[8])); + if (invert_y_axes) { + axis = ~axis; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[10])); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[12])); + if (invert_y_axes) { + axis = ~axis; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static bool HIDAPI_DriverXbox360W_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverXbox360W_Context *ctx = (SDL_DriverXbox360W_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH]; + int size; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { +#ifdef DEBUG_XBOX_PROTOCOL + HIDAPI_DumpPacket("Xbox 360 wireless packet: size = %d", data, size); +#endif + if (size == 2 && data[0] == 0x08) { + bool connected = (data[1] & 0x80) ? true : false; +#ifdef DEBUG_JOYSTICK + SDL_Log("Connected = %s", connected ? "TRUE" : "FALSE"); +#endif + if (connected != ctx->connected) { + ctx->connected = connected; + + if (connected) { + SDL_JoystickID joystickID; + + HIDAPI_JoystickConnected(device, &joystickID); + + } else if (device->num_joysticks > 0) { + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + } + } else if (size == 29 && data[0] == 0x00 && data[1] == 0x0f && data[2] == 0x00 && data[3] == 0xf0) { + // Serial number is data[7-13] +#ifdef DEBUG_JOYSTICK + SDL_Log("Battery status (initial): %d", data[17]); +#endif + if (joystick) { + UpdatePowerLevel(joystick, data[17]); + } + } else if (size == 29 && data[0] == 0x00 && data[1] == 0x00 && data[2] == 0x00 && data[3] == 0x13) { +#ifdef DEBUG_JOYSTICK + SDL_Log("Battery status: %d", data[4]); +#endif + if (joystick) { + UpdatePowerLevel(joystick, data[4]); + } + } else if (size == 29 && data[0] == 0x00 && (data[1] & 0x01) == 0x01) { + if (joystick) { + HIDAPI_DriverXbox360W_HandleStatePacket(joystick, device->dev, ctx, data + 4, size - 4); + } + } + } + + if (size < 0 && device->num_joysticks > 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverXbox360W_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverXbox360W_Context *ctx = (SDL_DriverXbox360W_Context *)device->context; + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_PLAYER_LED, + SDL_PlayerLEDHintChanged, ctx); +} + +static void HIDAPI_DriverXbox360W_FreeDevice(SDL_HIDAPI_Device *device) +{ +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXbox360W = { + SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_WIRELESS, + true, + HIDAPI_DriverXbox360W_RegisterHints, + HIDAPI_DriverXbox360W_UnregisterHints, + HIDAPI_DriverXbox360W_IsEnabled, + HIDAPI_DriverXbox360W_IsSupportedDevice, + HIDAPI_DriverXbox360W_InitDevice, + HIDAPI_DriverXbox360W_GetDevicePlayerIndex, + HIDAPI_DriverXbox360W_SetDevicePlayerIndex, + HIDAPI_DriverXbox360W_UpdateDevice, + HIDAPI_DriverXbox360W_OpenJoystick, + HIDAPI_DriverXbox360W_RumbleJoystick, + HIDAPI_DriverXbox360W_RumbleJoystickTriggers, + HIDAPI_DriverXbox360W_GetJoystickCapabilities, + HIDAPI_DriverXbox360W_SetJoystickLED, + HIDAPI_DriverXbox360W_SendJoystickEffect, + HIDAPI_DriverXbox360W_SetJoystickSensorsEnabled, + HIDAPI_DriverXbox360W_CloseJoystick, + HIDAPI_DriverXbox360W_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_XBOX360 + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_xboxone.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_xboxone.c new file mode 100644 index 00000000000..342eabdf75c --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_xboxone.c @@ -0,0 +1,1675 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../../SDL_hints_c.h" +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" + +#ifdef SDL_JOYSTICK_HIDAPI_XBOXONE + +// Define this if you want verbose logging of the init sequence +// #define DEBUG_JOYSTICK + +// Define this if you want to log all packets from the controller +// #define DEBUG_XBOX_PROTOCOL + +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) +#define XBOX_ONE_DRIVER_ACTIVE 1 +#else +#define XBOX_ONE_DRIVER_ACTIVE 0 +#endif + +#define CONTROLLER_IDENTIFY_TIMEOUT_MS 100 +#define CONTROLLER_PREPARE_INPUT_TIMEOUT_MS 50 + +// Deadzone thresholds +#define XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE 7849 +#define XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE 8689 +#define XINPUT_GAMEPAD_TRIGGER_THRESHOLD -25058 // Uint8 30 scaled to Sint16 full range + +enum +{ + SDL_GAMEPAD_BUTTON_XBOX_SHARE_BUTTON = 11 +}; + +// Power on +static const Uint8 xbox_init_power_on[] = { + 0x05, 0x20, 0x00, 0x01, 0x00 +}; +// Enable LED +static const Uint8 xbox_init_enable_led[] = { + 0x0A, 0x20, 0x00, 0x03, 0x00, 0x01, 0x14 +}; +// This controller passed security check +static const Uint8 xbox_init_security_passed[] = { + 0x06, 0x20, 0x00, 0x02, 0x01, 0x00 +}; +// Some PowerA controllers need to actually start the rumble motors +static const Uint8 xbox_init_powera_rumble[] = { + 0x09, 0x00, 0x00, 0x09, 0x00, 0x0F, 0x00, 0x00, + 0x1D, 0x1D, 0xFF, 0x00, 0x00 +}; +// Setup rumble (not needed for Microsoft controllers, but it doesn't hurt) +static const Uint8 xbox_init_rumble[] = { + 0x09, 0x00, 0x00, 0x09, 0x00, 0x0F, 0x00, 0x00, + 0x00, 0x00, 0xFF, 0x00, 0xEB +}; + +/* + * This specifies the selection of init packets that a gamepad + * will be sent on init *and* the order in which they will be + * sent. The correct sequence number will be added when the + * packet is going to be sent. + */ +typedef struct +{ + Uint16 vendor_id; + Uint16 product_id; + const Uint8 *data; + int size; +} SDL_DriverXboxOne_InitPacket; + +static const SDL_DriverXboxOne_InitPacket xboxone_init_packets[] = { + { 0x0000, 0x0000, xbox_init_power_on, sizeof(xbox_init_power_on) }, + { 0x0000, 0x0000, xbox_init_enable_led, sizeof(xbox_init_enable_led) }, + { 0x0000, 0x0000, xbox_init_security_passed, sizeof(xbox_init_security_passed) }, + { 0x24c6, 0x541a, xbox_init_powera_rumble, sizeof(xbox_init_powera_rumble) }, + { 0x24c6, 0x542a, xbox_init_powera_rumble, sizeof(xbox_init_powera_rumble) }, + { 0x24c6, 0x543a, xbox_init_powera_rumble, sizeof(xbox_init_powera_rumble) }, + { 0x0000, 0x0000, xbox_init_rumble, sizeof(xbox_init_rumble) }, +}; + +typedef enum +{ + XBOX_ONE_INIT_STATE_ANNOUNCED, + XBOX_ONE_INIT_STATE_IDENTIFYING, + XBOX_ONE_INIT_STATE_STARTUP, + XBOX_ONE_INIT_STATE_PREPARE_INPUT, + XBOX_ONE_INIT_STATE_COMPLETE, +} SDL_XboxOneInitState; + +typedef enum +{ + XBOX_ONE_RUMBLE_STATE_IDLE, + XBOX_ONE_RUMBLE_STATE_QUEUED, + XBOX_ONE_RUMBLE_STATE_BUSY +} SDL_XboxOneRumbleState; + +typedef struct +{ + SDL_HIDAPI_Device *device; + Uint16 vendor_id; + Uint16 product_id; + SDL_XboxOneInitState init_state; + Uint64 start_time; + Uint8 sequence; + Uint64 send_time; + bool has_guide_packet; + bool has_color_led; + bool has_paddles; + bool has_unmapped_state; + bool has_trigger_rumble; + bool has_share_button; + Uint8 last_paddle_state; + Uint8 low_frequency_rumble; + Uint8 high_frequency_rumble; + Uint8 left_trigger_rumble; + Uint8 right_trigger_rumble; + SDL_XboxOneRumbleState rumble_state; + Uint64 rumble_time; + bool rumble_pending; + Uint8 last_state[USB_PACKET_LENGTH]; + Uint8 *chunk_buffer; + Uint32 chunk_length; +} SDL_DriverXboxOne_Context; + +static bool ControllerHasColorLED(Uint16 vendor_id, Uint16 product_id) +{ + return vendor_id == USB_VENDOR_MICROSOFT && product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2; +} + +static bool ControllerHasPaddles(Uint16 vendor_id, Uint16 product_id) +{ + return SDL_IsJoystickXboxOneElite(vendor_id, product_id); +} + +static bool ControllerHasTriggerRumble(Uint16 vendor_id, Uint16 product_id) +{ + // All the Microsoft Xbox One controllers have trigger rumble + if (vendor_id == USB_VENDOR_MICROSOFT) { + return true; + } + + /* It turns out other controllers a mixed bag as to whether they support + trigger rumble or not, and when they do it's often a buzz rather than + the vibration of the Microsoft trigger rumble, so for now just pretend + that it is not available. + */ + return false; +} + +static bool ControllerHasShareButton(Uint16 vendor_id, Uint16 product_id) +{ + return SDL_IsJoystickXboxSeriesX(vendor_id, product_id); +} + +static int GetHomeLEDBrightness(const char *hint) +{ + const int MAX_VALUE = 50; + int value = 20; + + if (hint && *hint) { + if (SDL_strchr(hint, '.') != NULL) { + value = (int)(MAX_VALUE * SDL_atof(hint)); + } else if (!SDL_GetStringBoolean(hint, true)) { + value = 0; + } + } + return value; +} + +static void SetHomeLED(SDL_DriverXboxOne_Context *ctx, int value) +{ + Uint8 led_packet[] = { 0x0A, 0x20, 0x00, 0x03, 0x00, 0x00, 0x00 }; + + if (value > 0) { + led_packet[5] = 0x01; + led_packet[6] = (Uint8)value; + } + SDL_HIDAPI_SendRumble(ctx->device, led_packet, sizeof(led_packet)); +} + +static void SDLCALL SDL_HomeLEDHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)userdata; + + if (hint && *hint) { + SetHomeLED(ctx, GetHomeLEDBrightness(hint)); + } +} + +static void SetInitState(SDL_DriverXboxOne_Context *ctx, SDL_XboxOneInitState state) +{ +#ifdef DEBUG_JOYSTICK + SDL_Log("Setting init state %d", state); +#endif + ctx->init_state = state; +} + +static Uint8 GetNextPacketSequence(SDL_DriverXboxOne_Context *ctx) +{ + ++ctx->sequence; + if (!ctx->sequence) { + ctx->sequence = 1; + } + return ctx->sequence; +} + +static bool SendProtocolPacket(SDL_DriverXboxOne_Context *ctx, const Uint8 *data, int size) +{ +#ifdef DEBUG_XBOX_PROTOCOL + HIDAPI_DumpPacket("Xbox One sending packet: size = %d", data, size); +#endif + + ctx->send_time = SDL_GetTicks(); + + if (!SDL_HIDAPI_LockRumble()) { + return false; + } + if (SDL_HIDAPI_SendRumbleAndUnlock(ctx->device, data, size) != size) { + return false; + } + return true; +} + +#if 0 +static bool SendSerialRequest(SDL_DriverXboxOne_Context *ctx) +{ + Uint8 packet[] = { 0x1E, 0x20, 0x00, 0x01, 0x04 }; + + packet[2] = GetNextPacketSequence(ctx); + + /* Request the serial number + * Sending this should be done only after startup is complete. + * It will cancel the announce packet if sent before that, and will be + * ignored if sent during the startup sequence. + */ + if (!SendProtocolPacket(ctx, packet, sizeof(packet))) { + SDL_SetError("Couldn't send serial request packet"); + return false; + } + return true; +} +#endif + +static bool ControllerSendsAnnouncement(Uint16 vendor_id, Uint16 product_id) +{ + if (vendor_id == USB_VENDOR_PDP && product_id == 0x0246) { + // The PDP Rock Candy (PID 0x0246) doesn't send the announce packet on Linux for some reason + return false; + } + return true; +} + +static bool SendIdentificationRequest(SDL_DriverXboxOne_Context *ctx) +{ + // Request identification, sent in response to announce packet + Uint8 packet[] = { + 0x04, 0x20, 0x00, 0x00 + }; + + packet[2] = GetNextPacketSequence(ctx); + + if (!SendProtocolPacket(ctx, packet, sizeof(packet))) { + SDL_SetError("Couldn't send identification request packet"); + return false; + } + return true; +} + +static bool SendControllerStartup(SDL_DriverXboxOne_Context *ctx) +{ + Uint16 vendor_id = ctx->vendor_id; + Uint16 product_id = ctx->product_id; + Uint8 init_packet[USB_PACKET_LENGTH]; + size_t i; + + for (i = 0; i < SDL_arraysize(xboxone_init_packets); ++i) { + const SDL_DriverXboxOne_InitPacket *packet = &xboxone_init_packets[i]; + + if (packet->vendor_id && (vendor_id != packet->vendor_id)) { + continue; + } + + if (packet->product_id && (product_id != packet->product_id)) { + continue; + } + + SDL_memcpy(init_packet, packet->data, packet->size); + init_packet[2] = GetNextPacketSequence(ctx); + + if (init_packet[0] == 0x0A) { + // Get the initial brightness value + int brightness = GetHomeLEDBrightness(SDL_GetHint(SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE_HOME_LED)); + init_packet[5] = (brightness > 0) ? 0x01 : 0x00; + init_packet[6] = (Uint8)brightness; + } + + if (!SendProtocolPacket(ctx, init_packet, packet->size)) { + SDL_SetError("Couldn't send initialization packet"); + return false; + } + + // Wait to process the rumble packet + if (packet->data == xbox_init_powera_rumble) { + SDL_Delay(10); + } + } + return true; +} + +static void HIDAPI_DriverXboxOne_RegisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX, callback, userdata); + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE, callback, userdata); +} + +static void HIDAPI_DriverXboxOne_UnregisterHints(SDL_HintCallback callback, void *userdata) +{ + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX, callback, userdata); + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE, callback, userdata); +} + +static bool HIDAPI_DriverXboxOne_IsEnabled(void) +{ + return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE, + SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_XBOX, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT))); +} + +static bool HIDAPI_DriverXboxOne_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ +#if defined(SDL_PLATFORM_MACOS) && defined(SDL_JOYSTICK_MFI) + if (!SDL_IsJoystickBluetoothXboxOne(vendor_id, product_id)) { + // On macOS we get a shortened version of the real report and + // you can't write output reports for wired controllers, so + // we'll just use the GCController support instead. + return false; + } +#endif + return (type == SDL_GAMEPAD_TYPE_XBOXONE); +} + +static bool HIDAPI_DriverXboxOne_InitDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverXboxOne_Context *ctx; + + ctx = (SDL_DriverXboxOne_Context *)SDL_calloc(1, sizeof(*ctx)); + if (!ctx) { + return false; + } + ctx->device = device; + + device->context = ctx; + + ctx->vendor_id = device->vendor_id; + ctx->product_id = device->product_id; + ctx->start_time = SDL_GetTicks(); + ctx->sequence = 0; + ctx->has_color_led = ControllerHasColorLED(ctx->vendor_id, ctx->product_id); + ctx->has_paddles = ControllerHasPaddles(ctx->vendor_id, ctx->product_id); + ctx->has_trigger_rumble = ControllerHasTriggerRumble(ctx->vendor_id, ctx->product_id); + ctx->has_share_button = ControllerHasShareButton(ctx->vendor_id, ctx->product_id); + + // Assume that the controller is correctly initialized when we start + if (!ControllerSendsAnnouncement(device->vendor_id, device->product_id)) { + // Jump into the startup sequence for this controller + ctx->init_state = XBOX_ONE_INIT_STATE_STARTUP; + } else { + ctx->init_state = XBOX_ONE_INIT_STATE_COMPLETE; + } + +#ifdef DEBUG_JOYSTICK + SDL_Log("Controller version: %d (0x%.4x)", device->version, device->version); +#endif + + device->type = SDL_GAMEPAD_TYPE_XBOXONE; + + return HIDAPI_JoystickConnected(device, NULL); +} + +static int HIDAPI_DriverXboxOne_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) +{ + return -1; +} + +static void HIDAPI_DriverXboxOne_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) +{ +} + +static bool HIDAPI_DriverXboxOne_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)device->context; + + SDL_AssertJoysticksLocked(); + + ctx->low_frequency_rumble = 0; + ctx->high_frequency_rumble = 0; + ctx->left_trigger_rumble = 0; + ctx->right_trigger_rumble = 0; + ctx->rumble_state = XBOX_ONE_RUMBLE_STATE_IDLE; + ctx->rumble_time = 0; + ctx->rumble_pending = false; + SDL_zeroa(ctx->last_state); + + // Initialize the joystick capabilities + joystick->nbuttons = 11; + if (ctx->has_share_button) { + joystick->nbuttons += 1; + } + if (ctx->has_paddles) { + joystick->nbuttons += 4; + } + joystick->naxes = SDL_GAMEPAD_AXIS_COUNT; + joystick->nhats = 1; + + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE_HOME_LED, + SDL_HomeLEDHintChanged, ctx); + return true; +} + +static void HIDAPI_DriverXboxOne_RumbleSent(void *userdata) +{ + SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)userdata; + ctx->rumble_time = SDL_GetTicks(); +} + +static bool HIDAPI_DriverXboxOne_UpdateRumble(SDL_DriverXboxOne_Context *ctx) +{ + if (ctx->rumble_state == XBOX_ONE_RUMBLE_STATE_QUEUED) { + if (ctx->rumble_time) { + ctx->rumble_state = XBOX_ONE_RUMBLE_STATE_BUSY; + } + } + + if (ctx->rumble_state == XBOX_ONE_RUMBLE_STATE_BUSY) { + const int RUMBLE_BUSY_TIME_MS = ctx->device->is_bluetooth ? 50 : 10; + if (SDL_GetTicks() >= (ctx->rumble_time + RUMBLE_BUSY_TIME_MS)) { + ctx->rumble_time = 0; + ctx->rumble_state = XBOX_ONE_RUMBLE_STATE_IDLE; + } + } + + if (!ctx->rumble_pending) { + return true; + } + + if (ctx->rumble_state != XBOX_ONE_RUMBLE_STATE_IDLE) { + return true; + } + + // We're no longer pending, even if we fail to send the rumble below + ctx->rumble_pending = false; + + if (!SDL_HIDAPI_LockRumble()) { + return false; + } + + if (ctx->device->is_bluetooth) { + Uint8 rumble_packet[] = { 0x03, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xEB }; + + rumble_packet[2] = ctx->left_trigger_rumble; + rumble_packet[3] = ctx->right_trigger_rumble; + rumble_packet[4] = ctx->low_frequency_rumble; + rumble_packet[5] = ctx->high_frequency_rumble; + + if (SDL_HIDAPI_SendRumbleWithCallbackAndUnlock(ctx->device, rumble_packet, sizeof(rumble_packet), HIDAPI_DriverXboxOne_RumbleSent, ctx) != sizeof(rumble_packet)) { + return SDL_SetError("Couldn't send rumble packet"); + } + } else { + Uint8 rumble_packet[] = { 0x09, 0x00, 0x00, 0x09, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xEB }; + + rumble_packet[6] = ctx->left_trigger_rumble; + rumble_packet[7] = ctx->right_trigger_rumble; + rumble_packet[8] = ctx->low_frequency_rumble; + rumble_packet[9] = ctx->high_frequency_rumble; + + if (SDL_HIDAPI_SendRumbleWithCallbackAndUnlock(ctx->device, rumble_packet, sizeof(rumble_packet), HIDAPI_DriverXboxOne_RumbleSent, ctx) != sizeof(rumble_packet)) { + return SDL_SetError("Couldn't send rumble packet"); + } + } + + ctx->rumble_state = XBOX_ONE_RUMBLE_STATE_QUEUED; + + return true; +} + +static bool HIDAPI_DriverXboxOne_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)device->context; + + // Magnitude is 1..100 so scale the 16-bit input here + ctx->low_frequency_rumble = (Uint8)(low_frequency_rumble / 655); + ctx->high_frequency_rumble = (Uint8)(high_frequency_rumble / 655); + ctx->rumble_pending = true; + + return HIDAPI_DriverXboxOne_UpdateRumble(ctx); +} + +static bool HIDAPI_DriverXboxOne_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)device->context; + + if (!ctx->has_trigger_rumble) { + return SDL_Unsupported(); + } + + // Magnitude is 1..100 so scale the 16-bit input here + ctx->left_trigger_rumble = (Uint8)(left_rumble / 655); + ctx->right_trigger_rumble = (Uint8)(right_rumble / 655); + ctx->rumble_pending = true; + + return HIDAPI_DriverXboxOne_UpdateRumble(ctx); +} + +static Uint32 HIDAPI_DriverXboxOne_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)device->context; + Uint32 result = 0; + + result |= SDL_JOYSTICK_CAP_RUMBLE; + if (ctx->has_trigger_rumble) { + result |= SDL_JOYSTICK_CAP_TRIGGER_RUMBLE; + } + + if (ctx->has_color_led) { + result |= SDL_JOYSTICK_CAP_RGB_LED; + } + + return result; +} + +static bool HIDAPI_DriverXboxOne_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)device->context; + + if (ctx->has_color_led) { + Uint8 led_packet[] = { 0x0E, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + led_packet[5] = 0x00; // Whiteness? Sets white intensity when RGB is 0, seems additive + led_packet[6] = red; + led_packet[7] = green; + led_packet[8] = blue; + + if (SDL_HIDAPI_SendRumble(device, led_packet, sizeof(led_packet)) != sizeof(led_packet)) { + return SDL_SetError("Couldn't send LED packet"); + } + return true; + } else { + return SDL_Unsupported(); + } +} + +static bool HIDAPI_DriverXboxOne_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool HIDAPI_DriverXboxOne_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +/* + * The Xbox One Elite controller with 5.13+ firmware sends the unmapped state in a separate packet. + * We can use this to send the paddle state when they aren't mapped + */ +static void HIDAPI_DriverXboxOne_HandleUnmappedStatePacket(SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, Uint8 *data, int size) +{ + Uint8 profile; + int paddle_index; + int button1_bit; + int button2_bit; + int button3_bit; + int button4_bit; + bool paddles_mapped; + Uint64 timestamp = SDL_GetTicksNS(); + + if (size == 17) { + // XBox One Elite Series 2 + paddle_index = 14; + button1_bit = 0x01; + button2_bit = 0x02; + button3_bit = 0x04; + button4_bit = 0x08; + profile = data[15]; + + if (profile == 0) { + paddles_mapped = false; + } else if (SDL_memcmp(&data[0], &ctx->last_state[0], 14) == 0) { + // We're using a profile, but paddles aren't mapped + paddles_mapped = false; + } else { + // Something is mapped, we can't use the paddles + paddles_mapped = true; + } + + } else { + // Unknown format + return; + } +#ifdef DEBUG_XBOX_PROTOCOL + SDL_Log(">>> Paddles: %d,%d,%d,%d mapped = %s", + (data[paddle_index] & button1_bit) ? 1 : 0, + (data[paddle_index] & button2_bit) ? 1 : 0, + (data[paddle_index] & button3_bit) ? 1 : 0, + (data[paddle_index] & button4_bit) ? 1 : 0, + paddles_mapped ? "TRUE" : "FALSE"); +#endif + + if (paddles_mapped) { + // Respect that the paddles are being used for other controls and don't pass them on to the app + data[paddle_index] = 0; + } + + if (ctx->last_paddle_state != data[paddle_index]) { + Uint8 nButton = (Uint8)(SDL_GAMEPAD_BUTTON_XBOX_SHARE_BUTTON + ctx->has_share_button); // Next available button + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button1_bit) != 0)); + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button2_bit) != 0)); + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button3_bit) != 0)); + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button4_bit) != 0)); + ctx->last_paddle_state = data[paddle_index]; + } + ctx->has_unmapped_state = true; +} + +static void HIDAPI_DriverXboxOne_HandleStatePacket(SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; + Uint64 timestamp = SDL_GetTicksNS(); + + // Enable paddles on the Xbox Elite controller when connected over USB + if (ctx->has_paddles && !ctx->has_unmapped_state && size == 46) { + Uint8 packet[] = { 0x4d, 0x00, 0x00, 0x02, 0x07, 0x00 }; + +#ifdef DEBUG_JOYSTICK + SDL_Log("Enabling paddles on XBox Elite 2"); +#endif + SDL_HIDAPI_SendRumble(ctx->device, packet, sizeof(packet)); + } + + if (ctx->last_state[0] != data[0]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[0] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[0] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[0] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[0] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[0] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[0] & 0x80) != 0)); + } + + if (ctx->last_state[1] != data[1]) { + Uint8 hat = 0; + + if (data[1] & 0x01) { + hat |= SDL_HAT_UP; + } + if (data[1] & 0x02) { + hat |= SDL_HAT_DOWN; + } + if (data[1] & 0x04) { + hat |= SDL_HAT_LEFT; + } + if (data[1] & 0x08) { + hat |= SDL_HAT_RIGHT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + + if (ctx->vendor_id == USB_VENDOR_RAZER && ctx->product_id == USB_PRODUCT_RAZER_ATROX) { + // The Razer Atrox has the right and left shoulder bits reversed + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[1] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[1] & 0x10) != 0)); + } else { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[1] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[1] & 0x20) != 0)); + } + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[1] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[1] & 0x80) != 0)); + } + + if (ctx->has_share_button) { + /* Xbox Series X firmware version 5.0, report is 32 bytes, share button is in byte 14 + * Xbox Series X firmware version 5.1, report is 40 bytes, share button is in byte 14 + * Xbox Series X firmware version 5.5, report is 44 bytes, share button is in byte 18 + * Victrix Gambit Tournament Controller, report is 46 bytes, share button is in byte 28 + * ThrustMaster eSwap PRO Controller Xbox, report is 60 bytes, share button is in byte 42 + */ + if (size < 44) { + if (ctx->last_state[14] != data[14]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_XBOX_SHARE_BUTTON, ((data[14] & 0x01) != 0)); + } + } else if (size == 44) { + if (ctx->last_state[18] != data[18]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_XBOX_SHARE_BUTTON, ((data[18] & 0x01) != 0)); + } + } else if (size == 46) { + if (ctx->last_state[28] != data[28]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_XBOX_SHARE_BUTTON, ((data[28] & 0x01) != 0)); + } + } else if (size == 60) { + if (ctx->last_state[42] != data[42]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_XBOX_SHARE_BUTTON, ((data[42] & 0x01) != 0)); + } + } + } + + /* Xbox One S report is 14 bytes + Xbox One Elite Series 1 report is 29 bytes, paddles in data[28], mode in data[28] & 0x10, both modes have mapped paddles by default + Paddle bits: + P3: 0x01 (A) P1: 0x02 (B) + P4: 0x04 (X) P2: 0x08 (Y) + Xbox One Elite Series 2 4.x firmware report is 34 bytes, paddles in data[14], mode in data[15], mode 0 has no mapped paddles by default + Paddle bits: + P3: 0x04 (A) P1: 0x01 (B) + P4: 0x08 (X) P2: 0x02 (Y) + Xbox One Elite Series 2 5.x firmware report is 46 bytes, paddles in data[18], mode in data[19], mode 0 has no mapped paddles by default + Paddle bits: + P3: 0x04 (A) P1: 0x01 (B) + P4: 0x08 (X) P2: 0x02 (Y) + Xbox One Elite Series 2 5.17+ firmware report is 47 bytes, paddles in data[14], mode in data[20], mode 0 has no mapped paddles by default + Paddle bits: + P3: 0x04 (A) P1: 0x01 (B) + P4: 0x08 (X) P2: 0x02 (Y) + */ + if (ctx->has_paddles && !ctx->has_unmapped_state && (size == 29 || size == 34 || size == 46 || size == 47)) { + int paddle_index; + int button1_bit; + int button2_bit; + int button3_bit; + int button4_bit; + bool paddles_mapped; + + if (size == 29) { + // XBox One Elite Series 1 + paddle_index = 28; + button1_bit = 0x02; + button2_bit = 0x08; + button3_bit = 0x01; + button4_bit = 0x04; + + // The mapped controller state is at offset 0, the raw state is at offset 14, compare them to see if the paddles are mapped + paddles_mapped = (SDL_memcmp(&data[0], &data[14], 2) != 0); + + } else if (size == 34) { + // XBox One Elite Series 2 + paddle_index = 14; + button1_bit = 0x01; + button2_bit = 0x02; + button3_bit = 0x04; + button4_bit = 0x08; + paddles_mapped = (data[15] != 0); + + } else if (size == 46) { + // XBox One Elite Series 2 + paddle_index = 18; + button1_bit = 0x01; + button2_bit = 0x02; + button3_bit = 0x04; + button4_bit = 0x08; + paddles_mapped = (data[19] != 0); + } else /* if (size == 47) */ { + // XBox One Elite Series 2 + paddle_index = 14; + button1_bit = 0x01; + button2_bit = 0x02; + button3_bit = 0x04; + button4_bit = 0x08; + paddles_mapped = (data[20] != 0); + } +#ifdef DEBUG_XBOX_PROTOCOL + SDL_Log(">>> Paddles: %d,%d,%d,%d mapped = %s", + (data[paddle_index] & button1_bit) ? 1 : 0, + (data[paddle_index] & button2_bit) ? 1 : 0, + (data[paddle_index] & button3_bit) ? 1 : 0, + (data[paddle_index] & button4_bit) ? 1 : 0, + paddles_mapped ? "TRUE" : "FALSE"); +#endif + + if (paddles_mapped) { + // Respect that the paddles are being used for other controls and don't pass them on to the app + data[paddle_index] = 0; + } + + if (ctx->last_paddle_state != data[paddle_index]) { + Uint8 nButton = (Uint8)(SDL_GAMEPAD_BUTTON_XBOX_SHARE_BUTTON + ctx->has_share_button); // Next available button + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button1_bit) != 0)); + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button2_bit) != 0)); + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button3_bit) != 0)); + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button4_bit) != 0)); + ctx->last_paddle_state = data[paddle_index]; + } + } + + axis = ((int)SDL_Swap16LE(*(Sint16 *)(&data[2])) * 64) - 32768; + if (axis == 32704) { + axis = 32767; + } + if (axis == -32768 && size == 26 && (data[18] & 0x80)) { + axis = 32767; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + + axis = ((int)SDL_Swap16LE(*(Sint16 *)(&data[4])) * 64) - 32768; + if (axis == -32768 && size == 26 && (data[18] & 0x40)) { + axis = 32767; + } + if (axis == 32704) { + axis = 32767; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + + axis = SDL_Swap16LE(*(Sint16 *)(&data[6])); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[8])); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, ~axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[10])); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = SDL_Swap16LE(*(Sint16 *)(&data[12])); + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, ~axis); + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); + + // We don't have the unmapped state for this packet + ctx->has_unmapped_state = false; +} + +static void HIDAPI_DriverXboxOne_HandleStatusPacket(SDL_DriverXboxOne_Context *ctx, const Uint8 *data, int size) +{ + if (ctx->init_state < XBOX_ONE_INIT_STATE_COMPLETE) { + SetInitState(ctx, XBOX_ONE_INIT_STATE_COMPLETE); + } +} + +static void HIDAPI_DriverXboxOne_HandleModePacket(SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, const Uint8 *data, int size) +{ + Uint64 timestamp = SDL_GetTicksNS(); + + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[0] & 0x01) != 0)); +} + +/* + * Xbox One S with firmware 3.1.1221 uses a 16 byte packet and the GUIDE button in a separate packet + */ +static void HIDAPI_DriverXboxOneBluetooth_HandleButtons16(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, const Uint8 *data, int size) +{ + if (ctx->last_state[14] != data[14]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[14] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[14] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[14] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[14] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[14] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[14] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[14] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[14] & 0x80) != 0)); + } + + if (ctx->last_state[15] != data[15]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[15] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[15] & 0x02) != 0)); + } +} + +/* + * Xbox One S with firmware 4.8.1923 uses a 17 byte packet with BACK button in byte 16 and the GUIDE button in a separate packet (on Windows), or in byte 15 (on Linux) + * Xbox One S with firmware 5.x uses a 17 byte packet with BACK and GUIDE buttons in byte 15 + * Xbox One Elite Series 2 with firmware 4.7.1872 uses a 55 byte packet with BACK button in byte 16, paddles starting at byte 33, and the GUIDE button in a separate packet + * Xbox One Elite Series 2 with firmware 4.8.1908 uses a 33 byte packet with BACK button in byte 16, paddles starting at byte 17, and the GUIDE button in a separate packet + * Xbox One Elite Series 2 with firmware 5.11.3112 uses a 19 byte packet with BACK and GUIDE buttons in byte 15 + * Xbox Series X with firmware 5.5.2641 uses a 17 byte packet with BACK and GUIDE buttons in byte 15, and SHARE button in byte 17 + */ +static void HIDAPI_DriverXboxOneBluetooth_HandleButtons(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, Uint8 *data, int size) +{ + if (ctx->last_state[14] != data[14]) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data[14] & 0x01) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data[14] & 0x02) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data[14] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data[14] & 0x10) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data[14] & 0x40) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data[14] & 0x80) != 0)); + } + + if (ctx->last_state[15] != data[15]) { + if (!ctx->has_guide_packet) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[15] & 0x10) != 0)); + } + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data[15] & 0x08) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data[15] & 0x20) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data[15] & 0x40) != 0)); + } + + if (ctx->has_share_button) { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[15] & 0x04) != 0)); + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_XBOX_SHARE_BUTTON, ((data[16] & 0x01) != 0)); + } else { + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data[15] & 0x04) || ((data[16] & 0x01)) != 0)); + } + + /* + Paddle bits: + P3: 0x04 (A) P1: 0x01 (B) + P4: 0x08 (X) P2: 0x02 (Y) + */ + if (ctx->has_paddles && (size == 20 || size == 39 || size == 55)) { + int paddle_index; + int button1_bit; + int button2_bit; + int button3_bit; + int button4_bit; + bool paddles_mapped; + + if (size == 55) { + // Initial firmware for the Xbox Elite Series 2 controller + paddle_index = 33; + button1_bit = 0x01; + button2_bit = 0x02; + button3_bit = 0x04; + button4_bit = 0x08; + paddles_mapped = (data[35] != 0); + } else if (size == 39) { + // Updated firmware for the Xbox Elite Series 2 controller + paddle_index = 17; + button1_bit = 0x01; + button2_bit = 0x02; + button3_bit = 0x04; + button4_bit = 0x08; + paddles_mapped = (data[19] != 0); + } else /* if (size == 20) */ { + // Updated firmware for the Xbox Elite Series 2 controller (5.13+) + paddle_index = 19; + button1_bit = 0x01; + button2_bit = 0x02; + button3_bit = 0x04; + button4_bit = 0x08; + paddles_mapped = (data[17] != 0); + } + +#ifdef DEBUG_XBOX_PROTOCOL + SDL_Log(">>> Paddles: %d,%d,%d,%d mapped = %s", + (data[paddle_index] & button1_bit) ? 1 : 0, + (data[paddle_index] & button2_bit) ? 1 : 0, + (data[paddle_index] & button3_bit) ? 1 : 0, + (data[paddle_index] & button4_bit) ? 1 : 0, + paddles_mapped ? "TRUE" : "FALSE"); +#endif + + if (paddles_mapped) { + // Respect that the paddles are being used for other controls and don't pass them on to the app + data[paddle_index] = 0; + } + + if (ctx->last_paddle_state != data[paddle_index]) { + Uint8 nButton = SDL_GAMEPAD_BUTTON_XBOX_SHARE_BUTTON; // Next available button + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button1_bit) != 0)); + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button2_bit) != 0)); + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button3_bit) != 0)); + SDL_SendJoystickButton(timestamp, joystick, nButton++, ((data[paddle_index] & button4_bit) != 0)); + ctx->last_paddle_state = data[paddle_index]; + } + } +} + +static void HIDAPI_DriverXboxOneBluetooth_HandleStatePacket(SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, Uint8 *data, int size) +{ + Sint16 axis; + Uint64 timestamp = SDL_GetTicksNS(); + + if (size == 16) { + // Original Xbox One S, with separate report for guide button + HIDAPI_DriverXboxOneBluetooth_HandleButtons16(timestamp, joystick, ctx, data, size); + } else if (size > 16) { + HIDAPI_DriverXboxOneBluetooth_HandleButtons(timestamp, joystick, ctx, data, size); + } else { +#ifdef DEBUG_XBOX_PROTOCOL + SDL_Log("Unknown Bluetooth state packet format"); +#endif + return; + } + + if (ctx->last_state[13] != data[13]) { + Uint8 hat; + + switch (data[13]) { + case 1: + hat = SDL_HAT_UP; + break; + case 2: + hat = SDL_HAT_RIGHTUP; + break; + case 3: + hat = SDL_HAT_RIGHT; + break; + case 4: + hat = SDL_HAT_RIGHTDOWN; + break; + case 5: + hat = SDL_HAT_DOWN; + break; + case 6: + hat = SDL_HAT_LEFTDOWN; + break; + case 7: + hat = SDL_HAT_LEFT; + break; + case 8: + hat = SDL_HAT_LEFTUP; + break; + default: + hat = SDL_HAT_CENTERED; + break; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + } + + axis = ((int)SDL_Swap16LE(*(Sint16 *)(&data[9])) * 64) - 32768; + if (axis == 32704) { + axis = 32767; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis); + + axis = ((int)SDL_Swap16LE(*(Sint16 *)(&data[11])) * 64) - 32768; + if (axis == 32704) { + axis = 32767; + } + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis); + + axis = (int)SDL_Swap16LE(*(Uint16 *)(&data[1])) - 0x8000; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis); + axis = (int)SDL_Swap16LE(*(Uint16 *)(&data[3])) - 0x8000; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis); + axis = (int)SDL_Swap16LE(*(Uint16 *)(&data[5])) - 0x8000; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis); + axis = (int)SDL_Swap16LE(*(Uint16 *)(&data[7])) - 0x8000; + SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis); + + SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); +} + +static void HIDAPI_DriverXboxOneBluetooth_HandleGuidePacket(SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, const Uint8 *data, int size) +{ + Uint64 timestamp = SDL_GetTicksNS(); + + ctx->has_guide_packet = true; + SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data[1] & 0x01) != 0)); +} + +static void HIDAPI_DriverXboxOneBluetooth_HandleBatteryPacket(SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, const Uint8 *data, int size) +{ + Uint8 flags = data[1]; + bool on_usb = (((flags & 0x0C) >> 2) == 0); + SDL_PowerState state; + int percent = 0; + + // Mapped percentage value from: + // https://learn.microsoft.com/en-us/gaming/gdk/_content/gc/reference/input/gameinput/interfaces/igameinputdevice/methods/igameinputdevice_getbatterystate + switch (flags & 0x03) { + case 0: + percent = 10; + break; + case 1: + percent = 40; + break; + case 2: + percent = 70; + break; + case 3: + percent = 100; + break; + } + if (on_usb) { + state = SDL_POWERSTATE_CHARGING; + } else { + state = SDL_POWERSTATE_ON_BATTERY; + } + SDL_SendJoystickPowerInfo(joystick, state, percent); +} + +static void HIDAPI_DriverXboxOne_HandleSerialIDPacket(SDL_DriverXboxOne_Context *ctx, const Uint8 *data, int size) +{ + char serial[29]; + int i; + + for (i = 0; i < 14; ++i) { + SDL_uitoa(data[2 + i], &serial[i * 2], 16); + } + serial[i * 2] = '\0'; + +#ifdef DEBUG_JOYSTICK + SDL_Log("Setting serial number to %s", serial); +#endif + HIDAPI_SetDeviceSerial(ctx->device, serial); +} + +static bool HIDAPI_DriverXboxOne_UpdateInitState(SDL_DriverXboxOne_Context *ctx) +{ + SDL_XboxOneInitState prev_state; + do { + prev_state = ctx->init_state; + + switch (ctx->init_state) { + case XBOX_ONE_INIT_STATE_ANNOUNCED: + if (XBOX_ONE_DRIVER_ACTIVE) { + // The driver is taking care of identification + SetInitState(ctx, XBOX_ONE_INIT_STATE_COMPLETE); + } else { + SendIdentificationRequest(ctx); + SetInitState(ctx, XBOX_ONE_INIT_STATE_IDENTIFYING); + } + break; + case XBOX_ONE_INIT_STATE_IDENTIFYING: + if (SDL_GetTicks() >= (ctx->send_time + CONTROLLER_IDENTIFY_TIMEOUT_MS)) { + // We haven't heard anything, let's move on +#ifdef DEBUG_JOYSTICK + SDL_Log("Identification request timed out after %llu ms", (SDL_GetTicks() - ctx->send_time)); +#endif + SetInitState(ctx, XBOX_ONE_INIT_STATE_STARTUP); + } + break; + case XBOX_ONE_INIT_STATE_STARTUP: + if (XBOX_ONE_DRIVER_ACTIVE) { + // The driver is taking care of startup + SetInitState(ctx, XBOX_ONE_INIT_STATE_COMPLETE); + } else { + SendControllerStartup(ctx); + SetInitState(ctx, XBOX_ONE_INIT_STATE_PREPARE_INPUT); + } + break; + case XBOX_ONE_INIT_STATE_PREPARE_INPUT: + if (SDL_GetTicks() >= (ctx->send_time + CONTROLLER_PREPARE_INPUT_TIMEOUT_MS)) { +#ifdef DEBUG_JOYSTICK + SDL_Log("Prepare input complete after %llu ms", (SDL_GetTicks() - ctx->send_time)); +#endif + SetInitState(ctx, XBOX_ONE_INIT_STATE_COMPLETE); + } + break; + case XBOX_ONE_INIT_STATE_COMPLETE: + break; + } + + } while (ctx->init_state != prev_state); + + return true; +} + +/* GIP protocol handling adapted under the Zlib license with permission from @medusalix: + * https://github.com/medusalix/xone/blob/master/bus/protocol.h + * https://github.com/medusalix/xone/blob/master/bus/protocol.c + */ +#define GIP_HEADER_MIN_LENGTH 3 + +// Internal commands +#define GIP_CMD_ACKNOWLEDGE 0x01 +#define GIP_CMD_ANNOUNCE 0x02 +#define GIP_CMD_STATUS 0x03 +#define GIP_CMD_IDENTIFY 0x04 +#define GIP_CMD_POWER 0x05 +#define GIP_CMD_AUTHENTICATE 0x06 +#define GIP_CMD_VIRTUAL_KEY 0x07 +#define GIP_CMD_AUDIO_CONTROL 0x08 +#define GIP_CMD_LED 0x0A +#define GIP_CMD_HID_REPORT 0x0B +#define GIP_CMD_FIRMWARE 0x0C +#define GIP_CMD_SERIAL_NUMBER 0x1E +#define GIP_CMD_AUDIO_SAMPLES 0x60 + +// External commands +#define GIP_CMD_RUMBLE 0x09 +#define GIP_CMD_UNMAPPED_STATE 0x0C +#define GIP_CMD_INPUT 0x20 + +// Header option flags +#define GIP_OPT_ACKNOWLEDGE 0x10 +#define GIP_OPT_INTERNAL 0x20 +#define GIP_OPT_CHUNK_START 0x40 +#define GIP_OPT_CHUNK 0x80 + +#pragma pack(push, 1) + +struct gip_header { + Uint8 command; + Uint8 options; + Uint8 sequence; + Uint32 packet_length; + Uint32 chunk_offset; +}; + +struct gip_pkt_acknowledge { + Uint8 unknown; + Uint8 command; + Uint8 options; + Uint16 length; + Uint8 padding[2]; + Uint16 remaining; +}; + +#pragma pack(pop) + +static int EncodeVariableInt(Uint8 *buf, Uint32 val) +{ + int i; + + for (i = 0; i < sizeof(val); i++) { + buf[i] = (Uint8)val; + if (val > 0x7F) { + buf[i] |= 0x80; + } + + val >>= 7; + if (!val) { + break; + } + } + return i + 1; +} + +static int DecodeVariableInt(const Uint8 *data, int len, void *out) +{ + int i; + Uint32 val = 0; + + for (i = 0; i < sizeof(val) && i < len; i++) { + val |= (data[i] & 0x7F) << (i * 7); + + if (!(data[i] & 0x80)) { + break; + } + } + SDL_memcpy(out, &val, sizeof(val)); + return i + 1; +} + +static int HIDAPI_GIP_GetActualHeaderLength(struct gip_header *hdr) +{ + Uint32 pkt_len = hdr->packet_length; + Uint32 chunk_offset = hdr->chunk_offset; + int len = GIP_HEADER_MIN_LENGTH; + + do { + len++; + pkt_len >>= 7; + } while (pkt_len); + + if (hdr->options & GIP_OPT_CHUNK) { + while (chunk_offset) { + len++; + chunk_offset >>= 7; + } + } + + return len; +} + +static int HIDAPI_GIP_GetHeaderLength(struct gip_header *hdr) +{ + int len = HIDAPI_GIP_GetActualHeaderLength(hdr); + + // Header length must be even + return len + (len % 2); +} + +static void HIDAPI_GIP_EncodeHeader(struct gip_header *hdr, Uint8 *buf) +{ + int hdr_len = 0; + + buf[hdr_len++] = hdr->command; + buf[hdr_len++] = hdr->options; + buf[hdr_len++] = hdr->sequence; + + hdr_len += EncodeVariableInt(buf + hdr_len, hdr->packet_length); + + // Header length must be even + if (HIDAPI_GIP_GetActualHeaderLength(hdr) % 2) { + buf[hdr_len - 1] |= 0x80; + buf[hdr_len++] = 0; + } + + if (hdr->options & GIP_OPT_CHUNK) { + EncodeVariableInt(buf + hdr_len, hdr->chunk_offset); + } +} + +static int HIDAPI_GIP_DecodeHeader(struct gip_header *hdr, const Uint8 *data, int len) +{ + int hdr_len = 0; + + hdr->command = data[hdr_len++]; + hdr->options = data[hdr_len++]; + hdr->sequence = data[hdr_len++]; + hdr->packet_length = 0; + hdr->chunk_offset = 0; + + hdr_len += DecodeVariableInt(data + hdr_len, len - hdr_len, &hdr->packet_length); + + if (hdr->options & GIP_OPT_CHUNK) { + hdr_len += DecodeVariableInt(data + hdr_len, len - hdr_len, &hdr->chunk_offset); + } + return hdr_len; +} + +static bool HIDAPI_GIP_SendPacket(SDL_DriverXboxOne_Context *ctx, struct gip_header *hdr, const void *data) +{ + Uint8 packet[USB_PACKET_LENGTH]; + int hdr_len, size; + + hdr_len = HIDAPI_GIP_GetHeaderLength(hdr); + size = (hdr_len + hdr->packet_length); + if (size > sizeof(packet)) { + SDL_SetError("Couldn't send GIP packet, size (%d) too large", size); + return false; + } + + if (!hdr->sequence) { + hdr->sequence = GetNextPacketSequence(ctx); + } + + HIDAPI_GIP_EncodeHeader(hdr, packet); + if (data) { + SDL_memcpy(&packet[hdr_len], data, hdr->packet_length); + } + + if (!SendProtocolPacket(ctx, packet, size)) { + SDL_SetError("Couldn't send protocol packet"); + return false; + } + return true; +} + +static bool HIDAPI_GIP_AcknowledgePacket(SDL_DriverXboxOne_Context *ctx, struct gip_header *ack) +{ + if (XBOX_ONE_DRIVER_ACTIVE) { + // The driver is taking care of acks + return true; + } else { + struct gip_header hdr; + struct gip_pkt_acknowledge pkt; + + SDL_zero(hdr); + hdr.command = GIP_CMD_ACKNOWLEDGE; + hdr.options = GIP_OPT_INTERNAL; + hdr.sequence = ack->sequence; + hdr.packet_length = sizeof(pkt); + + SDL_zero(pkt); + pkt.command = ack->command; + pkt.options = GIP_OPT_INTERNAL; + pkt.length = SDL_Swap16LE((Uint16)(ack->chunk_offset + ack->packet_length)); + + if ((ack->options & GIP_OPT_CHUNK) && ctx->chunk_buffer) { + pkt.remaining = SDL_Swap16LE((Uint16)(ctx->chunk_length - pkt.length)); + } + + return HIDAPI_GIP_SendPacket(ctx, &hdr, &pkt); + } +} + +static bool HIDAPI_GIP_DispatchPacket(SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, struct gip_header *hdr, Uint8 *data, Uint32 size) +{ + if ((hdr->options & 0x0F) != 0) { + // This is a packet for a device plugged into the controller, skip it + return true; + } + + if (hdr->options & GIP_OPT_INTERNAL) { + switch (hdr->command) { + case GIP_CMD_ACKNOWLEDGE: + // Ignore this packet + break; + case GIP_CMD_ANNOUNCE: + // Controller is connected and waiting for initialization + /* The data bytes are: + 0x02 0x20 NN 0x1c, where NN is the packet sequence + then 6 bytes of wireless MAC address + then 2 bytes padding + then 16-bit VID + then 16-bit PID + then 16-bit firmware version quartet AA.BB.CC.DD + e.g. 0x05 0x00 0x05 0x00 0x51 0x0a 0x00 0x00 + is firmware version 5.5.2641.0, and product version 0x0505 = 1285 + then 8 bytes of unknown data + */ +#ifdef DEBUG_JOYSTICK + SDL_Log("Controller announce after %llu ms", (SDL_GetTicks() - ctx->start_time)); +#endif + SetInitState(ctx, XBOX_ONE_INIT_STATE_ANNOUNCED); + break; + case GIP_CMD_STATUS: + // Controller status update + HIDAPI_DriverXboxOne_HandleStatusPacket(ctx, data, size); + break; + case GIP_CMD_IDENTIFY: +#ifdef DEBUG_JOYSTICK + SDL_Log("Identification request completed after %llu ms", (SDL_GetTicks() - ctx->send_time)); +#endif +#ifdef DEBUG_XBOX_PROTOCOL + HIDAPI_DumpPacket("Xbox One identification data: size = %d", data, size); +#endif + SetInitState(ctx, XBOX_ONE_INIT_STATE_STARTUP); + break; + case GIP_CMD_POWER: + // Ignore this packet + break; + case GIP_CMD_AUTHENTICATE: + // Ignore this packet + break; + case GIP_CMD_VIRTUAL_KEY: + if (!joystick) { + break; + } + HIDAPI_DriverXboxOne_HandleModePacket(joystick, ctx, data, size); + break; + case GIP_CMD_SERIAL_NUMBER: + /* If the packet starts with this: + 0x1E 0x30 0x00 0x10 0x04 0x00 + then the next 14 bytes are the controller serial number + e.g. 0x30 0x39 0x37 0x31 0x32 0x33 0x33 0x32 0x33 0x35 0x34 0x30 0x33 0x36 + is serial number "3039373132333332333534303336" + + The controller sends that in response to this request: + 0x1E 0x20 0x00 0x01 0x04 + */ + HIDAPI_DriverXboxOne_HandleSerialIDPacket(ctx, data, size); + break; + default: +#ifdef DEBUG_JOYSTICK + SDL_Log("Unknown Xbox One packet: 0x%.2x", hdr->command); +#endif + break; + } + } else { + switch (hdr->command) { + case GIP_CMD_INPUT: + if (ctx->init_state < XBOX_ONE_INIT_STATE_COMPLETE) { + SetInitState(ctx, XBOX_ONE_INIT_STATE_COMPLETE); + + // Ignore the first input, it may be spurious +#ifdef DEBUG_JOYSTICK + SDL_Log("Controller ignoring spurious input"); +#endif + break; + } + if (!joystick) { + break; + } + HIDAPI_DriverXboxOne_HandleStatePacket(joystick, ctx, data, size); + break; + case GIP_CMD_UNMAPPED_STATE: + if (!joystick) { + break; + } + HIDAPI_DriverXboxOne_HandleUnmappedStatePacket(joystick, ctx, data, size); + break; + default: +#ifdef DEBUG_JOYSTICK + SDL_Log("Unknown Xbox One packet: 0x%.2x", hdr->command); +#endif + break; + } + } + return true; +} + +static void HIDAPI_GIP_DestroyChunkBuffer(SDL_DriverXboxOne_Context *ctx) +{ + if (ctx->chunk_buffer) { + SDL_free(ctx->chunk_buffer); + ctx->chunk_buffer = NULL; + ctx->chunk_length = 0; + } +} + +static bool HIDAPI_GIP_CreateChunkBuffer(SDL_DriverXboxOne_Context *ctx, Uint32 size) +{ + HIDAPI_GIP_DestroyChunkBuffer(ctx); + + ctx->chunk_buffer = (Uint8 *)SDL_malloc(size); + if (ctx->chunk_buffer) { + ctx->chunk_length = size; + return true; + } else { + return false; + } +} + +static bool HIDAPI_GIP_ProcessPacketChunked(SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, struct gip_header *hdr, Uint8 *data) +{ + bool result; + + if (!ctx->chunk_buffer) { + return false; + } + + if ((hdr->chunk_offset + hdr->packet_length) > ctx->chunk_length) { + return false; + } + + if (hdr->packet_length) { + SDL_memcpy(ctx->chunk_buffer + hdr->chunk_offset, data, hdr->packet_length); + return true; + } + + result = HIDAPI_GIP_DispatchPacket(joystick, ctx, hdr, ctx->chunk_buffer, ctx->chunk_length); + + HIDAPI_GIP_DestroyChunkBuffer(ctx); + + return result; +} + +static bool HIDAPI_GIP_ProcessPacket(SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, struct gip_header *hdr, Uint8 *data) +{ + if (hdr->options & GIP_OPT_CHUNK_START) { + if (!HIDAPI_GIP_CreateChunkBuffer(ctx, hdr->chunk_offset)) { + return false; + } + ctx->chunk_length = hdr->chunk_offset; + + hdr->chunk_offset = 0; + } + + if (hdr->options & GIP_OPT_ACKNOWLEDGE) { + if (!HIDAPI_GIP_AcknowledgePacket(ctx, hdr)) { + return false; + } + } + + if (hdr->options & GIP_OPT_CHUNK) { + return HIDAPI_GIP_ProcessPacketChunked(joystick, ctx, hdr, data); + } else { + return HIDAPI_GIP_DispatchPacket(joystick, ctx, hdr, data, hdr->packet_length); + } +} + +static bool HIDAPI_GIP_ProcessData(SDL_Joystick *joystick, SDL_DriverXboxOne_Context *ctx, Uint8 *data, int size) +{ + struct gip_header hdr; + int hdr_len; + + while (size > GIP_HEADER_MIN_LENGTH) { + hdr_len = HIDAPI_GIP_DecodeHeader(&hdr, data, size); + if ((hdr_len + hdr.packet_length) > (Uint32)size) { + // On macOS we get a shortened version of the real report + hdr.packet_length = (Uint32)(size - hdr_len); + } + + if (!HIDAPI_GIP_ProcessPacket(joystick, ctx, &hdr, data + hdr_len)) { + return false; + } + + data += hdr_len + hdr.packet_length; + size -= hdr_len + hdr.packet_length; + } + return true; +} + +static bool HIDAPI_DriverXboxOne_UpdateDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)device->context; + SDL_Joystick *joystick = NULL; + Uint8 data[USB_PACKET_LENGTH]; + int size; + + if (device->num_joysticks > 0) { + joystick = SDL_GetJoystickFromID(device->joysticks[0]); + } else { + return false; + } + + while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { +#ifdef DEBUG_XBOX_PROTOCOL + HIDAPI_DumpPacket("Xbox One packet: size = %d", data, size); +#endif + if (device->is_bluetooth) { + switch (data[0]) { + case 0x01: + if (!joystick) { + break; + } + if (size >= 16) { + HIDAPI_DriverXboxOneBluetooth_HandleStatePacket(joystick, ctx, data, size); + } else { +#ifdef DEBUG_JOYSTICK + SDL_Log("Unknown Xbox One Bluetooth packet size: %d", size); +#endif + } + break; + case 0x02: + if (!joystick) { + break; + } + HIDAPI_DriverXboxOneBluetooth_HandleGuidePacket(joystick, ctx, data, size); + break; + case 0x04: + if (!joystick) { + break; + } + HIDAPI_DriverXboxOneBluetooth_HandleBatteryPacket(joystick, ctx, data, size); + break; + default: +#ifdef DEBUG_JOYSTICK + SDL_Log("Unknown Xbox One packet: 0x%.2x", data[0]); +#endif + break; + } + } else { + HIDAPI_GIP_ProcessData(joystick, ctx, data, size); + } + } + + HIDAPI_DriverXboxOne_UpdateInitState(ctx); + HIDAPI_DriverXboxOne_UpdateRumble(ctx); + + if (size < 0) { + // Read error, device is disconnected + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + return (size >= 0); +} + +static void HIDAPI_DriverXboxOne_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)device->context; + + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE_HOME_LED, + SDL_HomeLEDHintChanged, ctx); +} + +static void HIDAPI_DriverXboxOne_FreeDevice(SDL_HIDAPI_Device *device) +{ + SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)device->context; + + HIDAPI_GIP_DestroyChunkBuffer(ctx); +} + +SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXboxOne = { + SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE, + true, + HIDAPI_DriverXboxOne_RegisterHints, + HIDAPI_DriverXboxOne_UnregisterHints, + HIDAPI_DriverXboxOne_IsEnabled, + HIDAPI_DriverXboxOne_IsSupportedDevice, + HIDAPI_DriverXboxOne_InitDevice, + HIDAPI_DriverXboxOne_GetDevicePlayerIndex, + HIDAPI_DriverXboxOne_SetDevicePlayerIndex, + HIDAPI_DriverXboxOne_UpdateDevice, + HIDAPI_DriverXboxOne_OpenJoystick, + HIDAPI_DriverXboxOne_RumbleJoystick, + HIDAPI_DriverXboxOne_RumbleJoystickTriggers, + HIDAPI_DriverXboxOne_GetJoystickCapabilities, + HIDAPI_DriverXboxOne_SetJoystickLED, + HIDAPI_DriverXboxOne_SendJoystickEffect, + HIDAPI_DriverXboxOne_SetJoystickSensorsEnabled, + HIDAPI_DriverXboxOne_CloseJoystick, + HIDAPI_DriverXboxOne_FreeDevice, +}; + +#endif // SDL_JOYSTICK_HIDAPI_XBOXONE + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapijoystick.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapijoystick.c new file mode 100644 index 00000000000..c7607aeadfa --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapijoystick.c @@ -0,0 +1,1734 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_HIDAPI + +#include "../SDL_sysjoystick.h" +#include "SDL_hidapijoystick_c.h" +#include "SDL_hidapi_rumble.h" +#include "../../SDL_hints_c.h" + +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) +#include "../windows/SDL_rawinputjoystick_c.h" +#endif + + +struct joystick_hwdata +{ + SDL_HIDAPI_Device *device; +}; + +static SDL_HIDAPI_DeviceDriver *SDL_HIDAPI_drivers[] = { +#ifdef SDL_JOYSTICK_HIDAPI_GAMECUBE + &SDL_HIDAPI_DriverGameCube, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_LUNA + &SDL_HIDAPI_DriverLuna, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_SHIELD + &SDL_HIDAPI_DriverShield, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_PS3 + &SDL_HIDAPI_DriverPS3, + &SDL_HIDAPI_DriverPS3ThirdParty, + &SDL_HIDAPI_DriverPS3SonySixaxis, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_PS4 + &SDL_HIDAPI_DriverPS4, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_PS5 + &SDL_HIDAPI_DriverPS5, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_STADIA + &SDL_HIDAPI_DriverStadia, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_STEAM + &SDL_HIDAPI_DriverSteam, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_STEAM_HORI + &SDL_HIDAPI_DriverSteamHori, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_STEAMDECK + &SDL_HIDAPI_DriverSteamDeck, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_SWITCH + &SDL_HIDAPI_DriverNintendoClassic, + &SDL_HIDAPI_DriverJoyCons, + &SDL_HIDAPI_DriverSwitch, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_WII + &SDL_HIDAPI_DriverWii, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_XBOX360 + &SDL_HIDAPI_DriverXbox360, + &SDL_HIDAPI_DriverXbox360W, +#endif +#ifdef SDL_JOYSTICK_HIDAPI_XBOXONE + &SDL_HIDAPI_DriverXboxOne, +#endif +}; +static int SDL_HIDAPI_numdrivers = 0; +static SDL_AtomicInt SDL_HIDAPI_updating_devices; +static bool SDL_HIDAPI_hints_changed = false; +static Uint32 SDL_HIDAPI_change_count = 0; +static SDL_HIDAPI_Device *SDL_HIDAPI_devices SDL_GUARDED_BY(SDL_joystick_lock); +static int SDL_HIDAPI_numjoysticks = 0; +static bool SDL_HIDAPI_combine_joycons = true; +static bool initialized = false; +static bool shutting_down = false; + +static char *HIDAPI_ConvertString(const wchar_t *wide_string) +{ + char *string = NULL; + + if (wide_string) { + string = SDL_iconv_string("UTF-8", "WCHAR_T", (char *)wide_string, (SDL_wcslen(wide_string) + 1) * sizeof(wchar_t)); + if (!string) { + switch (sizeof(wchar_t)) { + case 2: + string = SDL_iconv_string("UTF-8", "UCS-2-INTERNAL", (char *)wide_string, (SDL_wcslen(wide_string) + 1) * sizeof(wchar_t)); + break; + case 4: + string = SDL_iconv_string("UTF-8", "UCS-4-INTERNAL", (char *)wide_string, (SDL_wcslen(wide_string) + 1) * sizeof(wchar_t)); + break; + } + } + } + return string; +} + +void HIDAPI_DumpPacket(const char *prefix, const Uint8 *data, int size) +{ + int i; + char *buffer; + size_t length = SDL_strlen(prefix) + 11 * (size / 8) + (5 * size * 2) + 1 + 1; + int start = 0, amount = size; + size_t current_len; + + buffer = (char *)SDL_malloc(length); + current_len = SDL_snprintf(buffer, length, prefix, size); + for (i = start; i < start + amount; ++i) { + if ((i % 8) == 0) { + current_len += SDL_snprintf(&buffer[current_len], length - current_len, "\n%.2d: ", i); + } + current_len += SDL_snprintf(&buffer[current_len], length - current_len, " 0x%.2x", data[i]); + } + SDL_strlcat(buffer, "\n", length); + SDL_Log("%s", buffer); + SDL_free(buffer); +} + +bool HIDAPI_SupportsPlaystationDetection(Uint16 vendor, Uint16 product) +{ + /* If we already know the controller is a different type, don't try to detect it. + * This fixes a hang with the HORIPAD for Nintendo Switch (0x0f0d/0x00c1) + */ + if (SDL_GetGamepadTypeFromVIDPID(vendor, product, NULL, false) != SDL_GAMEPAD_TYPE_STANDARD) { + return false; + } + + switch (vendor) { + case USB_VENDOR_DRAGONRISE: + return true; + case USB_VENDOR_HORI: + return true; + case USB_VENDOR_LOGITECH: + /* Most Logitech devices are not PlayStation controllers, and some of them + * lock up or reset when we send them the Sony third-party query feature + * report, so don't include that vendor here. Instead add devices as + * appropriate to controller_list.h + */ + return false; + case USB_VENDOR_MADCATZ: + if (product == USB_PRODUCT_MADCATZ_SAITEK_SIDE_PANEL_CONTROL_DECK) { + // This is not a Playstation compatible device + return false; + } + return true; + case USB_VENDOR_MAYFLASH: + return true; + case USB_VENDOR_NACON: + case USB_VENDOR_NACON_ALT: + return true; + case USB_VENDOR_PDP: + return true; + case USB_VENDOR_POWERA: + return true; + case USB_VENDOR_POWERA_ALT: + return true; + case USB_VENDOR_QANBA: + return true; + case USB_VENDOR_RAZER: + /* Most Razer devices are not PlayStation controllers, and some of them + * lock up or reset when we send them the Sony third-party query feature + * report, so don't include that vendor here. Instead add devices as + * appropriate to controller_list.h + * + * Reference: https://github.com/libsdl-org/SDL/issues/6733 + * https://github.com/libsdl-org/SDL/issues/6799 + */ + return false; + case USB_VENDOR_SHANWAN: + return true; + case USB_VENDOR_SHANWAN_ALT: + return true; + case USB_VENDOR_THRUSTMASTER: + /* Most of these are wheels, don't have the full set of effects, and + * at least in the case of the T248 and T300 RS, the hid-tmff2 driver + * puts them in a non-standard report mode and they can't be read. + * + * If these should use the HIDAPI driver, add them to controller_list.h + */ + return false; + case USB_VENDOR_ZEROPLUS: + return true; + case 0x7545 /* SZ-MYPOWER */: + return true; + default: + return false; + } +} + +float HIDAPI_RemapVal(float val, float val_min, float val_max, float output_min, float output_max) +{ + return output_min + (output_max - output_min) * (val - val_min) / (val_max - val_min); +} + +static void HIDAPI_UpdateDeviceList(void); +static void HIDAPI_JoystickClose(SDL_Joystick *joystick); + +static SDL_GamepadType SDL_GetJoystickGameControllerProtocol(const char *name, Uint16 vendor, Uint16 product, int interface_number, int interface_class, int interface_subclass, int interface_protocol) +{ + static const int LIBUSB_CLASS_VENDOR_SPEC = 0xFF; + static const int XB360_IFACE_SUBCLASS = 93; + static const int XB360_IFACE_PROTOCOL = 1; // Wired + static const int XB360W_IFACE_PROTOCOL = 129; // Wireless + static const int XBONE_IFACE_SUBCLASS = 71; + static const int XBONE_IFACE_PROTOCOL = 208; + + SDL_GamepadType type = SDL_GAMEPAD_TYPE_STANDARD; + + // This code should match the checks in libusb/hid.c and HIDDeviceManager.java + if (interface_class == LIBUSB_CLASS_VENDOR_SPEC && + interface_subclass == XB360_IFACE_SUBCLASS && + (interface_protocol == XB360_IFACE_PROTOCOL || + interface_protocol == XB360W_IFACE_PROTOCOL)) { + + static const int SUPPORTED_VENDORS[] = { + 0x0079, // GPD Win 2 + 0x044f, // Thrustmaster + 0x045e, // Microsoft + 0x046d, // Logitech + 0x056e, // Elecom + 0x06a3, // Saitek + 0x0738, // Mad Catz + 0x07ff, // Mad Catz + 0x0e6f, // PDP + 0x0f0d, // Hori + 0x1038, // SteelSeries + 0x11c9, // Nacon + 0x12ab, // Unknown + 0x1430, // RedOctane + 0x146b, // BigBen + 0x1532, // Razer + 0x15e4, // Numark + 0x162e, // Joytech + 0x1689, // Razer Onza + 0x1949, // Lab126, Inc. + 0x1bad, // Harmonix + 0x20d6, // PowerA + 0x24c6, // PowerA + 0x2c22, // Qanba + 0x2dc8, // 8BitDo + 0x9886, // ASTRO Gaming + }; + + int i; + for (i = 0; i < SDL_arraysize(SUPPORTED_VENDORS); ++i) { + if (vendor == SUPPORTED_VENDORS[i]) { + type = SDL_GAMEPAD_TYPE_XBOX360; + break; + } + } + } + + if (interface_number == 0 && + interface_class == LIBUSB_CLASS_VENDOR_SPEC && + interface_subclass == XBONE_IFACE_SUBCLASS && + interface_protocol == XBONE_IFACE_PROTOCOL) { + + static const int SUPPORTED_VENDORS[] = { + 0x03f0, // HP + 0x044f, // Thrustmaster + 0x045e, // Microsoft + 0x0738, // Mad Catz + 0x0b05, // ASUS + 0x0e6f, // PDP + 0x0f0d, // Hori + 0x10f5, // Turtle Beach + 0x1532, // Razer + 0x20d6, // PowerA + 0x24c6, // PowerA + 0x2dc8, // 8BitDo + 0x2e24, // Hyperkin + 0x3537, // GameSir + }; + + int i; + for (i = 0; i < SDL_arraysize(SUPPORTED_VENDORS); ++i) { + if (vendor == SUPPORTED_VENDORS[i]) { + type = SDL_GAMEPAD_TYPE_XBOXONE; + break; + } + } + } + + if (type == SDL_GAMEPAD_TYPE_STANDARD) { + type = SDL_GetGamepadTypeFromVIDPID(vendor, product, name, false); + } + return type; +} + +static bool HIDAPI_IsDeviceSupported(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ + int i; + SDL_GamepadType type = SDL_GetJoystickGameControllerProtocol(name, vendor_id, product_id, -1, 0, 0, 0); + + for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { + SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; + if (driver->enabled && driver->IsSupportedDevice(NULL, name, type, vendor_id, product_id, version, -1, 0, 0, 0)) { + return true; + } + } + return false; +} + +static SDL_HIDAPI_DeviceDriver *HIDAPI_GetDeviceDriver(SDL_HIDAPI_Device *device) +{ + const Uint16 USAGE_PAGE_GENERIC_DESKTOP = 0x0001; + const Uint16 USAGE_JOYSTICK = 0x0004; + const Uint16 USAGE_GAMEPAD = 0x0005; + const Uint16 USAGE_MULTIAXISCONTROLLER = 0x0008; + int i; + + if (device->num_children > 0) { + return &SDL_HIDAPI_DriverCombined; + } + + if (SDL_ShouldIgnoreJoystick(device->vendor_id, device->product_id, device->version, device->name)) { + return NULL; + } + + if (device->vendor_id != USB_VENDOR_VALVE) { + if (device->usage_page && device->usage_page != USAGE_PAGE_GENERIC_DESKTOP) { + return NULL; + } + if (device->usage && device->usage != USAGE_JOYSTICK && device->usage != USAGE_GAMEPAD && device->usage != USAGE_MULTIAXISCONTROLLER) { + return NULL; + } + } + + for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { + SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; + if (driver->enabled && driver->IsSupportedDevice(device, device->name, device->type, device->vendor_id, device->product_id, device->version, device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol)) { + return driver; + } + } + return NULL; +} + +static SDL_HIDAPI_Device *HIDAPI_GetDeviceByIndex(int device_index, SDL_JoystickID *pJoystickID) +{ + SDL_HIDAPI_Device *device; + + SDL_AssertJoysticksLocked(); + + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (device->parent || device->broken) { + continue; + } + if (device->driver) { + if (device_index < device->num_joysticks) { + if (pJoystickID) { + *pJoystickID = device->joysticks[device_index]; + } + return device; + } + device_index -= device->num_joysticks; + } + } + return NULL; +} + +static SDL_HIDAPI_Device *HIDAPI_GetJoystickByInfo(const char *path, Uint16 vendor_id, Uint16 product_id) +{ + SDL_HIDAPI_Device *device; + + SDL_AssertJoysticksLocked(); + + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (device->vendor_id == vendor_id && device->product_id == product_id && + SDL_strcmp(device->path, path) == 0) { + break; + } + } + return device; +} + +static void HIDAPI_CleanupDeviceDriver(SDL_HIDAPI_Device *device) +{ + if (!device->driver) { + return; // Already cleaned up + } + + // Disconnect any joysticks + while (device->num_joysticks && device->joysticks) { + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + + device->driver->FreeDevice(device); + device->driver = NULL; + + SDL_LockMutex(device->dev_lock); + { + if (device->dev) { + SDL_hid_close(device->dev); + device->dev = NULL; + } + + if (device->context) { + SDL_free(device->context); + device->context = NULL; + } + } + SDL_UnlockMutex(device->dev_lock); +} + +static void HIDAPI_SetupDeviceDriver(SDL_HIDAPI_Device *device, bool *removed) SDL_NO_THREAD_SAFETY_ANALYSIS // We unlock the joystick lock to be able to open the HID device on Android +{ + *removed = false; + + if (device->driver) { + bool enabled; + + if (device->vendor_id == USB_VENDOR_NINTENDO && device->product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR) { + enabled = SDL_HIDAPI_combine_joycons; + } else { + enabled = device->driver->enabled; + } + if (device->children) { + int i; + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + if (!child->driver || !child->driver->enabled) { + enabled = false; + break; + } + } + } + if (!enabled) { + HIDAPI_CleanupDeviceDriver(device); + } + return; // Already setup + } + + if (HIDAPI_GetDeviceDriver(device)) { + // We might have a device driver for this device, try opening it and see + if (device->num_children == 0) { + SDL_hid_device *dev; + + // Wait a little bit for the device to initialize + SDL_Delay(10); + + dev = SDL_hid_open_path(device->path); + + if (dev == NULL) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "HIDAPI_SetupDeviceDriver() couldn't open %s: %s", + device->path, SDL_GetError()); + return; + } + SDL_hid_set_nonblocking(dev, 1); + + device->dev = dev; + } + + device->driver = HIDAPI_GetDeviceDriver(device); + + // Initialize the device, which may cause a connected event + if (device->driver && !device->driver->InitDevice(device)) { + HIDAPI_CleanupDeviceDriver(device); + } + + if (!device->driver && device->dev) { + // No driver claimed this device, go ahead and close it + SDL_hid_close(device->dev); + device->dev = NULL; + } + } +} + +static void SDL_HIDAPI_UpdateDrivers(void) +{ + int i; + SDL_HIDAPI_Device *device; + bool removed; + + SDL_AssertJoysticksLocked(); + + SDL_HIDAPI_numdrivers = 0; + for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { + SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; + driver->enabled = driver->IsEnabled(); + if (driver->enabled && driver != &SDL_HIDAPI_DriverCombined) { + ++SDL_HIDAPI_numdrivers; + } + } + + removed = false; + do { + for (device = SDL_HIDAPI_devices; device; device = device->next) { + HIDAPI_SetupDeviceDriver(device, &removed); + if (removed) { + break; + } + } + } while (removed); +} + +static void SDLCALL SDL_HIDAPIDriverHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + if (SDL_strcmp(name, SDL_HINT_JOYSTICK_HIDAPI_COMBINE_JOY_CONS) == 0) { + SDL_HIDAPI_combine_joycons = SDL_GetStringBoolean(hint, true); + } + SDL_HIDAPI_hints_changed = true; + SDL_HIDAPI_change_count = 0; +} + +static bool HIDAPI_JoystickInit(void) +{ + int i; + + if (initialized) { + return true; + } + + if (SDL_hid_init() < 0) { + return SDL_SetError("Couldn't initialize hidapi"); + } + + for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { + SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; + driver->RegisterHints(SDL_HIDAPIDriverHintChanged, driver); + } + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_COMBINE_JOY_CONS, + SDL_HIDAPIDriverHintChanged, NULL); + SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI, + SDL_HIDAPIDriverHintChanged, NULL); + + SDL_HIDAPI_change_count = SDL_hid_device_change_count(); + HIDAPI_UpdateDeviceList(); + HIDAPI_UpdateDevices(); + + initialized = true; + + return true; +} + +static bool HIDAPI_AddJoystickInstanceToDevice(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID) +{ + SDL_JoystickID *joysticks = (SDL_JoystickID *)SDL_realloc(device->joysticks, (device->num_joysticks + 1) * sizeof(*device->joysticks)); + if (!joysticks) { + return false; + } + + device->joysticks = joysticks; + device->joysticks[device->num_joysticks++] = joystickID; + return true; +} + +static bool HIDAPI_DelJoystickInstanceFromDevice(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID) +{ + int i, size; + + for (i = 0; i < device->num_joysticks; ++i) { + if (device->joysticks[i] == joystickID) { + size = (device->num_joysticks - i - 1) * sizeof(SDL_JoystickID); + SDL_memmove(&device->joysticks[i], &device->joysticks[i + 1], size); + --device->num_joysticks; + if (device->num_joysticks == 0) { + SDL_free(device->joysticks); + device->joysticks = NULL; + } + return true; + } + } + return false; +} + +static bool HIDAPI_JoystickInstanceIsUnique(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID) +{ + if (device->parent && device->num_joysticks == 1 && device->parent->num_joysticks == 1 && + device->joysticks[0] == device->parent->joysticks[0]) { + return false; + } + return true; +} + +void HIDAPI_SetDeviceName(SDL_HIDAPI_Device *device, const char *name) +{ + if (name && *name && SDL_strcmp(name, device->name) != 0) { + SDL_free(device->name); + device->name = SDL_strdup(name); + SDL_SetJoystickGUIDCRC(&device->guid, SDL_crc16(0, name, SDL_strlen(name))); + } +} + +void HIDAPI_SetDeviceProduct(SDL_HIDAPI_Device *device, Uint16 vendor_id, Uint16 product_id) +{ + // Don't set the device product ID directly, or we'll constantly re-enumerate this device + device->guid = SDL_CreateJoystickGUID(device->guid.data[0], vendor_id, product_id, device->version, device->manufacturer_string, device->product_string, 'h', 0); +} + +static void HIDAPI_UpdateJoystickSerial(SDL_HIDAPI_Device *device) +{ + int i; + + SDL_AssertJoysticksLocked(); + + for (i = 0; i < device->num_joysticks; ++i) { + SDL_Joystick *joystick = SDL_GetJoystickFromID(device->joysticks[i]); + if (joystick && device->serial) { + SDL_free(joystick->serial); + joystick->serial = SDL_strdup(device->serial); + } + } +} + +static bool HIDAPI_SerialIsEmpty(SDL_HIDAPI_Device *device) +{ + bool all_zeroes = true; + + if (device->serial) { + const char *serial = device->serial; + for (serial = device->serial; *serial; ++serial) { + if (*serial != '0') { + all_zeroes = false; + break; + } + } + } + return all_zeroes; +} + +void HIDAPI_SetDeviceSerial(SDL_HIDAPI_Device *device, const char *serial) +{ + if (serial && *serial && (!device->serial || SDL_strcmp(serial, device->serial) != 0)) { + SDL_free(device->serial); + device->serial = SDL_strdup(serial); + HIDAPI_UpdateJoystickSerial(device); + } +} + +static int wcstrcmp(const wchar_t *str1, const char *str2) +{ + int result; + + while (1) { + result = (*str1 - *str2); + if (result != 0 || *str1 == 0) { + break; + } + ++str1; + ++str2; + } + return result; +} + +static void HIDAPI_SetDeviceSerialW(SDL_HIDAPI_Device *device, const wchar_t *serial) +{ + if (serial && *serial && (!device->serial || wcstrcmp(serial, device->serial) != 0)) { + SDL_free(device->serial); + device->serial = HIDAPI_ConvertString(serial); + HIDAPI_UpdateJoystickSerial(device); + } +} + +bool HIDAPI_HasConnectedUSBDevice(const char *serial) +{ + SDL_HIDAPI_Device *device; + + SDL_AssertJoysticksLocked(); + + if (!serial) { + return false; + } + + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (!device->driver || device->broken) { + continue; + } + + if (device->is_bluetooth) { + continue; + } + + if (device->serial && SDL_strcmp(serial, device->serial) == 0) { + return true; + } + } + return false; +} + +void HIDAPI_DisconnectBluetoothDevice(const char *serial) +{ + SDL_HIDAPI_Device *device; + + SDL_AssertJoysticksLocked(); + + if (!serial) { + return; + } + + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (!device->driver || device->broken) { + continue; + } + + if (!device->is_bluetooth) { + continue; + } + + if (device->serial && SDL_strcmp(serial, device->serial) == 0) { + while (device->num_joysticks && device->joysticks) { + HIDAPI_JoystickDisconnected(device, device->joysticks[0]); + } + } + } +} + +bool HIDAPI_JoystickConnected(SDL_HIDAPI_Device *device, SDL_JoystickID *pJoystickID) +{ + int i, j; + SDL_JoystickID joystickID; + + SDL_AssertJoysticksLocked(); + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + for (j = child->num_joysticks; j--;) { + HIDAPI_JoystickDisconnected(child, child->joysticks[j]); + } + } + + joystickID = SDL_GetNextObjectID(); + HIDAPI_AddJoystickInstanceToDevice(device, joystickID); + + for (i = 0; i < device->num_children; ++i) { + SDL_HIDAPI_Device *child = device->children[i]; + HIDAPI_AddJoystickInstanceToDevice(child, joystickID); + } + + ++SDL_HIDAPI_numjoysticks; + + if (pJoystickID) { + *pJoystickID = joystickID; + } + + SDL_PrivateJoystickAdded(joystickID); + + return true; +} + +void HIDAPI_JoystickDisconnected(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID) +{ + int i, j; + + SDL_LockJoysticks(); + + if (!HIDAPI_JoystickInstanceIsUnique(device, joystickID)) { + // Disconnecting a child always disconnects the parent + device = device->parent; + } + + for (i = 0; i < device->num_joysticks; ++i) { + if (device->joysticks[i] == joystickID) { + SDL_Joystick *joystick = SDL_GetJoystickFromID(joystickID); + if (joystick) { + HIDAPI_JoystickClose(joystick); + } + + HIDAPI_DelJoystickInstanceFromDevice(device, joystickID); + + for (j = 0; j < device->num_children; ++j) { + SDL_HIDAPI_Device *child = device->children[j]; + HIDAPI_DelJoystickInstanceFromDevice(child, joystickID); + } + + --SDL_HIDAPI_numjoysticks; + + if (!shutting_down) { + SDL_PrivateJoystickRemoved(joystickID); + } + } + } + + // Rescan the device list in case device state has changed + SDL_HIDAPI_change_count = 0; + + SDL_UnlockJoysticks(); +} + +static void HIDAPI_UpdateJoystickProperties(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) +{ + SDL_PropertiesID props = SDL_GetJoystickProperties(joystick); + Uint32 caps = device->driver->GetJoystickCapabilities(device, joystick); + + if (caps & SDL_JOYSTICK_CAP_MONO_LED) { + SDL_SetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_MONO_LED_BOOLEAN, true); + } else { + SDL_SetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_MONO_LED_BOOLEAN, false); + } + if (caps & SDL_JOYSTICK_CAP_RGB_LED) { + SDL_SetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN, true); + } else { + SDL_SetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN, false); + } + if (caps & SDL_JOYSTICK_CAP_PLAYER_LED) { + SDL_SetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_PLAYER_LED_BOOLEAN, true); + } else { + SDL_SetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_PLAYER_LED_BOOLEAN, false); + } + if (caps & SDL_JOYSTICK_CAP_RUMBLE) { + SDL_SetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true); + } else { + SDL_SetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, false); + } + if (caps & SDL_JOYSTICK_CAP_TRIGGER_RUMBLE) { + SDL_SetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN, true); + } else { + SDL_SetBooleanProperty(props, SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN, false); + } +} + +void HIDAPI_UpdateDeviceProperties(SDL_HIDAPI_Device *device) +{ + int i; + + SDL_LockJoysticks(); + + for (i = 0; i < device->num_joysticks; ++i) { + SDL_Joystick *joystick = SDL_GetJoystickFromID(device->joysticks[i]); + if (joystick) { + HIDAPI_UpdateJoystickProperties(device, joystick); + } + } + + SDL_UnlockJoysticks(); +} + +static int HIDAPI_JoystickGetCount(void) +{ + return SDL_HIDAPI_numjoysticks; +} + +static SDL_HIDAPI_Device *HIDAPI_AddDevice(const struct SDL_hid_device_info *info, int num_children, SDL_HIDAPI_Device **children) +{ + SDL_HIDAPI_Device *device; + SDL_HIDAPI_Device *curr, *last = NULL; + bool removed; + Uint16 bus; + + SDL_AssertJoysticksLocked(); + + for (curr = SDL_HIDAPI_devices, last = NULL; curr; last = curr, curr = curr->next) { + } + + device = (SDL_HIDAPI_Device *)SDL_calloc(1, sizeof(*device)); + if (!device) { + return NULL; + } + SDL_SetObjectValid(device, SDL_OBJECT_TYPE_HIDAPI_JOYSTICK, true); + if (info->path) { + device->path = SDL_strdup(info->path); + } + device->seen = true; + device->vendor_id = info->vendor_id; + device->product_id = info->product_id; + device->version = info->release_number; + device->interface_number = info->interface_number; + device->interface_class = info->interface_class; + device->interface_subclass = info->interface_subclass; + device->interface_protocol = info->interface_protocol; + device->usage_page = info->usage_page; + device->usage = info->usage; + device->is_bluetooth = (info->bus_type == SDL_HID_API_BUS_BLUETOOTH); + device->dev_lock = SDL_CreateMutex(); + + // Need the device name before getting the driver to know whether to ignore this device + { + char *serial_number = HIDAPI_ConvertString(info->serial_number); + + device->manufacturer_string = HIDAPI_ConvertString(info->manufacturer_string); + device->product_string = HIDAPI_ConvertString(info->product_string); + device->name = SDL_CreateJoystickName(device->vendor_id, device->product_id, device->manufacturer_string, device->product_string); + + if (serial_number && *serial_number) { + device->serial = serial_number; + } else { + SDL_free(serial_number); + } + + if (!device->name) { + SDL_free(device->manufacturer_string); + SDL_free(device->product_string); + SDL_free(device->serial); + SDL_free(device->path); + SDL_free(device); + return NULL; + } + } + + if (info->bus_type == SDL_HID_API_BUS_BLUETOOTH) { + bus = SDL_HARDWARE_BUS_BLUETOOTH; + } else { + bus = SDL_HARDWARE_BUS_USB; + } + device->guid = SDL_CreateJoystickGUID(bus, device->vendor_id, device->product_id, device->version, device->manufacturer_string, device->product_string, 'h', 0); + device->joystick_type = SDL_JOYSTICK_TYPE_GAMEPAD; + device->type = SDL_GetJoystickGameControllerProtocol(device->name, device->vendor_id, device->product_id, device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol); + device->steam_virtual_gamepad_slot = -1; + + if (num_children > 0) { + int i; + + device->num_children = num_children; + device->children = children; + for (i = 0; i < num_children; ++i) { + children[i]->parent = device; + } + } + + // Add it to the list + if (last) { + last->next = device; + } else { + SDL_HIDAPI_devices = device; + } + + removed = false; + HIDAPI_SetupDeviceDriver(device, &removed); + if (removed) { + return NULL; + } + + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, "Added HIDAPI device '%s' VID 0x%.4x, PID 0x%.4x, bluetooth %d, version %d, serial %s, interface %d, interface_class %d, interface_subclass %d, interface_protocol %d, usage page 0x%.4x, usage 0x%.4x, path = %s, driver = %s (%s)", device->name, device->vendor_id, device->product_id, device->is_bluetooth, device->version, + device->serial ? device->serial : "NONE", device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol, device->usage_page, device->usage, + device->path, device->driver ? device->driver->name : "NONE", device->driver && device->driver->enabled ? "ENABLED" : "DISABLED"); + + return device; +} + +static void HIDAPI_DelDevice(SDL_HIDAPI_Device *device) +{ + SDL_HIDAPI_Device *curr, *last; + int i; + + SDL_AssertJoysticksLocked(); + + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, "Removing HIDAPI device '%s' VID 0x%.4x, PID 0x%.4x, bluetooth %d, version %d, serial %s, interface %d, interface_class %d, interface_subclass %d, interface_protocol %d, usage page 0x%.4x, usage 0x%.4x, path = %s, driver = %s (%s)", device->name, device->vendor_id, device->product_id, device->is_bluetooth, device->version, + device->serial ? device->serial : "NONE", device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol, device->usage_page, device->usage, + device->path, device->driver ? device->driver->name : "NONE", device->driver && device->driver->enabled ? "ENABLED" : "DISABLED"); + + for (curr = SDL_HIDAPI_devices, last = NULL; curr; last = curr, curr = curr->next) { + if (curr == device) { + if (last) { + last->next = curr->next; + } else { + SDL_HIDAPI_devices = curr->next; + } + + HIDAPI_CleanupDeviceDriver(device); + + // Make sure the rumble thread is done with this device + while (SDL_GetAtomicInt(&device->rumble_pending) > 0) { + SDL_Delay(10); + } + + for (i = 0; i < device->num_children; ++i) { + device->children[i]->parent = NULL; + } + + SDL_SetObjectValid(device, SDL_OBJECT_TYPE_HIDAPI_JOYSTICK, false); + SDL_DestroyMutex(device->dev_lock); + SDL_free(device->manufacturer_string); + SDL_free(device->product_string); + SDL_free(device->serial); + SDL_free(device->name); + SDL_free(device->path); + SDL_free(device->children); + SDL_free(device); + return; + } + } +} + +static bool HIDAPI_CreateCombinedJoyCons(void) +{ + SDL_HIDAPI_Device *device, *combined; + SDL_HIDAPI_Device *joycons[2] = { NULL, NULL }; + + SDL_AssertJoysticksLocked(); + + if (!SDL_HIDAPI_combine_joycons) { + return false; + } + + for (device = SDL_HIDAPI_devices; device; device = device->next) { + Uint16 vendor, product; + + if (!device->driver) { + // Unsupported device + continue; + } + if (device->parent) { + // This device is already part of a combined device + continue; + } + if (device->broken) { + // This device can't be used + continue; + } + + SDL_GetJoystickGUIDInfo(device->guid, &vendor, &product, NULL, NULL); + + if (!joycons[0] && + (SDL_IsJoystickNintendoSwitchJoyConLeft(vendor, product) || + (SDL_IsJoystickNintendoSwitchJoyConGrip(vendor, product) && + SDL_strstr(device->name, "(L)") != NULL))) { + joycons[0] = device; + } + if (!joycons[1] && + (SDL_IsJoystickNintendoSwitchJoyConRight(vendor, product) || + (SDL_IsJoystickNintendoSwitchJoyConGrip(vendor, product) && + SDL_strstr(device->name, "(R)") != NULL))) { + joycons[1] = device; + } + if (joycons[0] && joycons[1]) { + SDL_hid_device_info info; + SDL_HIDAPI_Device **children = (SDL_HIDAPI_Device **)SDL_malloc(2 * sizeof(SDL_HIDAPI_Device *)); + if (!children) { + return false; + } + children[0] = joycons[0]; + children[1] = joycons[1]; + + SDL_zero(info); + info.path = "nintendo_joycons_combined"; + info.vendor_id = USB_VENDOR_NINTENDO; + info.product_id = USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR; + info.interface_number = -1; + info.usage_page = USB_USAGEPAGE_GENERIC_DESKTOP; + info.usage = USB_USAGE_GENERIC_GAMEPAD; + info.manufacturer_string = L"Nintendo"; + info.product_string = L"Switch Joy-Con (L/R)"; + if (children[0]->is_bluetooth || children[1]->is_bluetooth) { + info.bus_type = SDL_HID_API_BUS_BLUETOOTH; + } else { + info.bus_type = SDL_HID_API_BUS_USB; + } + + combined = HIDAPI_AddDevice(&info, 2, children); + if (combined && combined->driver) { + return true; + } else { + if (combined) { + HIDAPI_DelDevice(combined); + } else { + SDL_free(children); + } + return false; + } + } + } + return false; +} + +static void HIDAPI_UpdateDeviceList(void) +{ + SDL_HIDAPI_Device *device; + struct SDL_hid_device_info *devs, *info; + + SDL_LockJoysticks(); + + if (SDL_HIDAPI_hints_changed) { + SDL_HIDAPI_UpdateDrivers(); + SDL_HIDAPI_hints_changed = false; + } + + // Prepare the existing device list + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (device->children) { + continue; + } + device->seen = false; + } + + // Enumerate the devices + if (SDL_HIDAPI_numdrivers > 0) { + devs = SDL_hid_enumerate(0, 0); + if (devs) { + for (info = devs; info; info = info->next) { + device = HIDAPI_GetJoystickByInfo(info->path, info->vendor_id, info->product_id); + if (device) { + device->seen = true; + + // Check to see if the serial number is available now + if(HIDAPI_SerialIsEmpty(device)) { + HIDAPI_SetDeviceSerialW(device, info->serial_number); + } + } else { + HIDAPI_AddDevice(info, 0, NULL); + } + } + SDL_hid_free_enumeration(devs); + } + } + + // Remove any devices that weren't seen or have been disconnected due to read errors +check_removed: + device = SDL_HIDAPI_devices; + while (device) { + SDL_HIDAPI_Device *next = device->next; + + if (!device->seen || + ((device->driver || device->children) && device->num_joysticks == 0 && !device->dev)) { + if (device->parent) { + // When a child device goes away, so does the parent + int i; + device = device->parent; + for (i = 0; i < device->num_children; ++i) { + HIDAPI_DelDevice(device->children[i]); + } + HIDAPI_DelDevice(device); + + // Update the device list again to pick up any children left + SDL_HIDAPI_change_count = 0; + + // We deleted more than one device here, restart the loop + goto check_removed; + } else { + HIDAPI_DelDevice(device); + device = NULL; + + // Update the device list again in case this device comes back + SDL_HIDAPI_change_count = 0; + } + } + if (device && device->broken && device->parent) { + HIDAPI_DelDevice(device->parent); + + // We deleted a different device here, restart the loop + goto check_removed; + } + device = next; + } + + // See if we can create any combined Joy-Con controllers + while (HIDAPI_CreateCombinedJoyCons()) { + } + + SDL_UnlockJoysticks(); +} + +static bool HIDAPI_IsEquivalentToDevice(Uint16 vendor_id, Uint16 product_id, SDL_HIDAPI_Device *device) +{ + if (vendor_id == device->vendor_id && product_id == device->product_id) { + return true; + } + + if (vendor_id == USB_VENDOR_MICROSOFT) { + // If we're looking for the wireless XBox 360 controller, also look for the dongle + if (product_id == USB_PRODUCT_XBOX360_XUSB_CONTROLLER && device->product_id == USB_PRODUCT_XBOX360_WIRELESS_RECEIVER) { + return true; + } + + // If we're looking for the raw input Xbox One controller, match it against any other Xbox One controller + if (product_id == USB_PRODUCT_XBOX_ONE_XBOXGIP_CONTROLLER && + device->type == SDL_GAMEPAD_TYPE_XBOXONE) { + return true; + } + + // If we're looking for an XInput controller, match it against any other Xbox controller + if (product_id == USB_PRODUCT_XBOX360_XUSB_CONTROLLER) { + if (device->type == SDL_GAMEPAD_TYPE_XBOX360 || device->type == SDL_GAMEPAD_TYPE_XBOXONE) { + return true; + } + } + } + + if (vendor_id == USB_VENDOR_NVIDIA) { + // If we're looking for the NVIDIA SHIELD controller Xbox interface, match it against any NVIDIA SHIELD controller + if (product_id == 0xb400 && + SDL_IsJoystickNVIDIASHIELDController(vendor_id, product_id)) { + return true; + } + } + return false; +} + +static bool HIDAPI_StartUpdatingDevices(void) +{ + return SDL_CompareAndSwapAtomicInt(&SDL_HIDAPI_updating_devices, false, true); +} + +static void HIDAPI_FinishUpdatingDevices(void) +{ + SDL_SetAtomicInt(&SDL_HIDAPI_updating_devices, false); +} + +bool HIDAPI_IsDeviceTypePresent(SDL_GamepadType type) +{ + SDL_HIDAPI_Device *device; + bool result = false; + + // Make sure we're initialized, as this could be called from other drivers during startup + if (!HIDAPI_JoystickInit()) { + return false; + } + + if (HIDAPI_StartUpdatingDevices()) { + HIDAPI_UpdateDeviceList(); + HIDAPI_FinishUpdatingDevices(); + } + + SDL_LockJoysticks(); + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (device->driver && device->type == type) { + result = true; + break; + } + } + SDL_UnlockJoysticks(); + +#ifdef DEBUG_HIDAPI + SDL_Log("HIDAPI_IsDeviceTypePresent() returning %s for %d", result ? "true" : "false", type); +#endif + return result; +} + +bool HIDAPI_IsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ + SDL_HIDAPI_Device *device; + bool supported = false; + bool result = false; + + // Make sure we're initialized, as this could be called from other drivers during startup + if (!HIDAPI_JoystickInit()) { + return false; + } + + /* Only update the device list for devices we know might be supported. + If we did this for every device, it would hit the USB driver too hard and potentially + lock up the system. This won't catch devices that we support but can only detect using + USB interface details, like Xbox controllers, but hopefully the device list update is + responsive enough to catch those. + */ + supported = HIDAPI_IsDeviceSupported(vendor_id, product_id, version, name); +#if defined(SDL_JOYSTICK_HIDAPI_XBOX360) || defined(SDL_JOYSTICK_HIDAPI_XBOXONE) + if (!supported && + (SDL_strstr(name, "Xbox") || SDL_strstr(name, "X-Box") || SDL_strstr(name, "XBOX"))) { + supported = true; + } +#endif // SDL_JOYSTICK_HIDAPI_XBOX360 || SDL_JOYSTICK_HIDAPI_XBOXONE + if (supported) { + if (HIDAPI_StartUpdatingDevices()) { + HIDAPI_UpdateDeviceList(); + HIDAPI_FinishUpdatingDevices(); + } + } + + /* Note that this isn't a perfect check - there may be multiple devices with 0 VID/PID, + or a different name than we have it listed here, etc, but if we support the device + and we have something similar in our device list, mark it as present. + */ + SDL_LockJoysticks(); + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (device->driver && + HIDAPI_IsEquivalentToDevice(vendor_id, product_id, device)) { + result = true; + break; + } + } + SDL_UnlockJoysticks(); + +#ifdef DEBUG_HIDAPI + SDL_Log("HIDAPI_IsDevicePresent() returning %s for 0x%.4x / 0x%.4x", result ? "true" : "false", vendor_id, product_id); +#endif + return result; +} + +char *HIDAPI_GetDeviceProductName(Uint16 vendor_id, Uint16 product_id) +{ + SDL_HIDAPI_Device *device; + char *name = NULL; + + SDL_LockJoysticks(); + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (vendor_id == device->vendor_id && product_id == device->product_id) { + if (device->product_string) { + name = SDL_strdup(device->product_string); + } + break; + } + } + SDL_UnlockJoysticks(); + + return name; +} + +char *HIDAPI_GetDeviceManufacturerName(Uint16 vendor_id, Uint16 product_id) +{ + SDL_HIDAPI_Device *device; + char *name = NULL; + + SDL_LockJoysticks(); + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (vendor_id == device->vendor_id && product_id == device->product_id) { + if (device->manufacturer_string) { + name = SDL_strdup(device->manufacturer_string); + } + break; + } + } + SDL_UnlockJoysticks(); + + return name; +} + +SDL_JoystickType HIDAPI_GetJoystickTypeFromGUID(SDL_GUID guid) +{ + SDL_HIDAPI_Device *device; + SDL_JoystickType type = SDL_JOYSTICK_TYPE_UNKNOWN; + + SDL_LockJoysticks(); + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (SDL_memcmp(&guid, &device->guid, sizeof(guid)) == 0) { + type = device->joystick_type; + break; + } + } + SDL_UnlockJoysticks(); + + return type; +} + +SDL_GamepadType HIDAPI_GetGamepadTypeFromGUID(SDL_GUID guid) +{ + SDL_HIDAPI_Device *device; + SDL_GamepadType type = SDL_GAMEPAD_TYPE_STANDARD; + + SDL_LockJoysticks(); + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (SDL_memcmp(&guid, &device->guid, sizeof(guid)) == 0) { + type = device->type; + break; + } + } + SDL_UnlockJoysticks(); + + return type; +} + +static void HIDAPI_JoystickDetect(void) +{ + if (HIDAPI_StartUpdatingDevices()) { + Uint32 count = SDL_hid_device_change_count(); + if (SDL_HIDAPI_change_count != count) { + SDL_HIDAPI_change_count = count; + HIDAPI_UpdateDeviceList(); + } + HIDAPI_FinishUpdatingDevices(); + } +} + +void HIDAPI_UpdateDevices(void) +{ + SDL_HIDAPI_Device *device; + + SDL_AssertJoysticksLocked(); + + // Update the devices, which may change connected joysticks and send events + + // Prepare the existing device list + if (HIDAPI_StartUpdatingDevices()) { + for (device = SDL_HIDAPI_devices; device; device = device->next) { + if (device->parent) { + continue; + } + if (device->driver) { + if (SDL_TryLockMutex(device->dev_lock)) { + device->updating = true; + device->driver->UpdateDevice(device); + device->updating = false; + SDL_UnlockMutex(device->dev_lock); + } + } + } + HIDAPI_FinishUpdatingDevices(); + } +} + +static const char *HIDAPI_JoystickGetDeviceName(int device_index) +{ + SDL_HIDAPI_Device *device; + const char *name = NULL; + + device = HIDAPI_GetDeviceByIndex(device_index, NULL); + if (device) { + // FIXME: The device could be freed after this name is returned... + name = device->name; + } + + return name; +} + +static const char *HIDAPI_JoystickGetDevicePath(int device_index) +{ + SDL_HIDAPI_Device *device; + const char *path = NULL; + + device = HIDAPI_GetDeviceByIndex(device_index, NULL); + if (device) { + // FIXME: The device could be freed after this path is returned... + path = device->path; + } + + return path; +} + +static int HIDAPI_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index) +{ + SDL_HIDAPI_Device *device; + + device = HIDAPI_GetDeviceByIndex(device_index, NULL); + if (device) { + return device->steam_virtual_gamepad_slot; + } + return -1; +} + +static int HIDAPI_JoystickGetDevicePlayerIndex(int device_index) +{ + SDL_HIDAPI_Device *device; + SDL_JoystickID instance_id; + int player_index = -1; + + device = HIDAPI_GetDeviceByIndex(device_index, &instance_id); + if (device) { + player_index = device->driver->GetDevicePlayerIndex(device, instance_id); + } + + return player_index; +} + +static void HIDAPI_JoystickSetDevicePlayerIndex(int device_index, int player_index) +{ + SDL_HIDAPI_Device *device; + SDL_JoystickID instance_id; + + device = HIDAPI_GetDeviceByIndex(device_index, &instance_id); + if (device) { + device->driver->SetDevicePlayerIndex(device, instance_id, player_index); + } +} + +static SDL_GUID HIDAPI_JoystickGetDeviceGUID(int device_index) +{ + SDL_HIDAPI_Device *device; + SDL_GUID guid; + + device = HIDAPI_GetDeviceByIndex(device_index, NULL); + if (device) { + SDL_memcpy(&guid, &device->guid, sizeof(guid)); + } else { + SDL_zero(guid); + } + + return guid; +} + +static SDL_JoystickID HIDAPI_JoystickGetDeviceInstanceID(int device_index) +{ + SDL_JoystickID joystickID = 0; + HIDAPI_GetDeviceByIndex(device_index, &joystickID); + return joystickID; +} + +static bool HIDAPI_JoystickOpen(SDL_Joystick *joystick, int device_index) +{ + SDL_JoystickID joystickID = 0; + SDL_HIDAPI_Device *device = HIDAPI_GetDeviceByIndex(device_index, &joystickID); + struct joystick_hwdata *hwdata; + + SDL_AssertJoysticksLocked(); + + if (!device || !device->driver || device->broken) { + // This should never happen - validated before being called + return SDL_SetError("Couldn't find HIDAPI device at index %d", device_index); + } + + hwdata = (struct joystick_hwdata *)SDL_calloc(1, sizeof(*hwdata)); + if (!hwdata) { + return false; + } + hwdata->device = device; + + // Process any pending reports before opening the device + SDL_LockMutex(device->dev_lock); + device->updating = true; + device->driver->UpdateDevice(device); + device->updating = false; + SDL_UnlockMutex(device->dev_lock); + + // UpdateDevice() may have called HIDAPI_JoystickDisconnected() if the device went away + if (device->num_joysticks == 0) { + SDL_free(hwdata); + return SDL_SetError("HIDAPI device disconnected while opening"); + } + + // Set the default connection state, can be overridden below + if (device->is_bluetooth) { + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRELESS; + } else { + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRED; + } + + if (!device->driver->OpenJoystick(device, joystick)) { + // The open failed, mark this device as disconnected and update devices + HIDAPI_JoystickDisconnected(device, joystickID); + SDL_free(hwdata); + return false; + } + + HIDAPI_UpdateJoystickProperties(device, joystick); + + if (device->serial) { + joystick->serial = SDL_strdup(device->serial); + } + + joystick->hwdata = hwdata; + return true; +} + +static bool HIDAPI_GetJoystickDevice(SDL_Joystick *joystick, SDL_HIDAPI_Device **device) +{ + SDL_AssertJoysticksLocked(); + + if (joystick && joystick->hwdata) { + *device = joystick->hwdata->device; + if (SDL_ObjectValid(*device, SDL_OBJECT_TYPE_HIDAPI_JOYSTICK) && (*device)->driver != NULL) { + return true; + } + } + return false; +} + +static bool HIDAPI_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + bool result; + SDL_HIDAPI_Device *device = NULL; + + if (HIDAPI_GetJoystickDevice(joystick, &device)) { + result = device->driver->RumbleJoystick(device, joystick, low_frequency_rumble, high_frequency_rumble); + } else { + result = SDL_SetError("Rumble failed, device disconnected"); + } + + return result; +} + +static bool HIDAPI_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + bool result; + SDL_HIDAPI_Device *device = NULL; + + if (HIDAPI_GetJoystickDevice(joystick, &device)) { + result = device->driver->RumbleJoystickTriggers(device, joystick, left_rumble, right_rumble); + } else { + result = SDL_SetError("Rumble failed, device disconnected"); + } + + return result; +} + +static bool HIDAPI_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + bool result; + SDL_HIDAPI_Device *device = NULL; + + if (HIDAPI_GetJoystickDevice(joystick, &device)) { + result = device->driver->SetJoystickLED(device, joystick, red, green, blue); + } else { + result = SDL_SetError("SetLED failed, device disconnected"); + } + + return result; +} + +static bool HIDAPI_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size) +{ + bool result; + SDL_HIDAPI_Device *device = NULL; + + if (HIDAPI_GetJoystickDevice(joystick, &device)) { + result = device->driver->SendJoystickEffect(device, joystick, data, size); + } else { + result = SDL_SetError("SendEffect failed, device disconnected"); + } + + return result; +} + +static bool HIDAPI_JoystickSetSensorsEnabled(SDL_Joystick *joystick, bool enabled) +{ + bool result; + SDL_HIDAPI_Device *device = NULL; + + if (HIDAPI_GetJoystickDevice(joystick, &device)) { + result = device->driver->SetJoystickSensorsEnabled(device, joystick, enabled); + } else { + result = SDL_SetError("SetSensorsEnabled failed, device disconnected"); + } + + return result; +} + +static void HIDAPI_JoystickUpdate(SDL_Joystick *joystick) +{ + // This is handled in SDL_HIDAPI_UpdateDevices() +} + +static void HIDAPI_JoystickClose(SDL_Joystick *joystick) SDL_NO_THREAD_SAFETY_ANALYSIS // We unlock the device lock so rumble can complete +{ + SDL_AssertJoysticksLocked(); + + if (joystick->hwdata) { + SDL_HIDAPI_Device *device = joystick->hwdata->device; + int i; + + // Wait up to 30 ms for pending rumble to complete + if (device->updating) { + // Unlock the device so rumble can complete + SDL_UnlockMutex(device->dev_lock); + } + for (i = 0; i < 3; ++i) { + if (SDL_GetAtomicInt(&device->rumble_pending) > 0) { + SDL_Delay(10); + } + } + if (device->updating) { + // Relock the device + SDL_LockMutex(device->dev_lock); + } + + device->driver->CloseJoystick(device, joystick); + + SDL_free(joystick->hwdata); + joystick->hwdata = NULL; + } +} + +static void HIDAPI_JoystickQuit(void) +{ + int i; + + SDL_AssertJoysticksLocked(); + + shutting_down = true; + + SDL_HIDAPI_QuitRumble(); + + while (SDL_HIDAPI_devices) { + SDL_HIDAPI_Device *device = SDL_HIDAPI_devices; + if (device->parent) { + // When a child device goes away, so does the parent + device = device->parent; + for (i = 0; i < device->num_children; ++i) { + HIDAPI_DelDevice(device->children[i]); + } + HIDAPI_DelDevice(device); + } else { + HIDAPI_DelDevice(device); + } + } + + // Make sure the drivers cleaned up properly + SDL_assert(SDL_HIDAPI_numjoysticks == 0); + + for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { + SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; + driver->UnregisterHints(SDL_HIDAPIDriverHintChanged, driver); + } + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_COMBINE_JOY_CONS, + SDL_HIDAPIDriverHintChanged, NULL); + SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI, + SDL_HIDAPIDriverHintChanged, NULL); + + SDL_hid_exit(); + + SDL_HIDAPI_change_count = 0; + shutting_down = false; + initialized = false; +} + +static bool HIDAPI_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) +{ + return false; +} + +SDL_JoystickDriver SDL_HIDAPI_JoystickDriver = { + HIDAPI_JoystickInit, + HIDAPI_JoystickGetCount, + HIDAPI_JoystickDetect, + HIDAPI_IsDevicePresent, + HIDAPI_JoystickGetDeviceName, + HIDAPI_JoystickGetDevicePath, + HIDAPI_JoystickGetDeviceSteamVirtualGamepadSlot, + HIDAPI_JoystickGetDevicePlayerIndex, + HIDAPI_JoystickSetDevicePlayerIndex, + HIDAPI_JoystickGetDeviceGUID, + HIDAPI_JoystickGetDeviceInstanceID, + HIDAPI_JoystickOpen, + HIDAPI_JoystickRumble, + HIDAPI_JoystickRumbleTriggers, + HIDAPI_JoystickSetLED, + HIDAPI_JoystickSendEffect, + HIDAPI_JoystickSetSensorsEnabled, + HIDAPI_JoystickUpdate, + HIDAPI_JoystickClose, + HIDAPI_JoystickQuit, + HIDAPI_JoystickGetGamepadMapping +}; + +#endif // SDL_JOYSTICK_HIDAPI diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapijoystick_c.h b/thirdparty/sdl/joystick/hidapi/SDL_hidapijoystick_c.h new file mode 100644 index 00000000000..9cd9f400651 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapijoystick_c.h @@ -0,0 +1,195 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_JOYSTICK_HIDAPI_H +#define SDL_JOYSTICK_HIDAPI_H + +#include "../usb_ids.h" + +// This is the full set of HIDAPI drivers available +#define SDL_JOYSTICK_HIDAPI_GAMECUBE +#define SDL_JOYSTICK_HIDAPI_LUNA +#define SDL_JOYSTICK_HIDAPI_PS3 +#define SDL_JOYSTICK_HIDAPI_PS4 +#define SDL_JOYSTICK_HIDAPI_PS5 +#define SDL_JOYSTICK_HIDAPI_STADIA +#define SDL_JOYSTICK_HIDAPI_STEAM +#define SDL_JOYSTICK_HIDAPI_STEAMDECK +#define SDL_JOYSTICK_HIDAPI_SWITCH +#define SDL_JOYSTICK_HIDAPI_WII +#define SDL_JOYSTICK_HIDAPI_XBOX360 +#define SDL_JOYSTICK_HIDAPI_XBOXONE +#define SDL_JOYSTICK_HIDAPI_SHIELD +#define SDL_JOYSTICK_HIDAPI_STEAM_HORI + +// Joystick capability definitions +#define SDL_JOYSTICK_CAP_MONO_LED 0x00000001 +#define SDL_JOYSTICK_CAP_RGB_LED 0x00000002 +#define SDL_JOYSTICK_CAP_PLAYER_LED 0x00000004 +#define SDL_JOYSTICK_CAP_RUMBLE 0x00000010 +#define SDL_JOYSTICK_CAP_TRIGGER_RUMBLE 0x00000020 + +// Whether HIDAPI is enabled by default +#if defined(SDL_PLATFORM_ANDROID) || \ + defined(SDL_PLATFORM_IOS) || \ + defined(SDL_PLATFORM_TVOS) || \ + defined(SDL_PLATFORM_VISIONOS) +// On Android, HIDAPI prompts for permissions and acquires exclusive access to the device, and on Apple mobile platforms it doesn't do anything except for handling Bluetooth Steam Controllers, so we'll leave it off by default. +#define SDL_HIDAPI_DEFAULT false +#else +#define SDL_HIDAPI_DEFAULT true +#endif + +// The maximum size of a USB packet for HID devices +#define USB_PACKET_LENGTH 64 + +// Forward declaration +struct SDL_HIDAPI_DeviceDriver; + +typedef struct SDL_HIDAPI_Device +{ + char *name; + char *manufacturer_string; + char *product_string; + char *path; + Uint16 vendor_id; + Uint16 product_id; + Uint16 version; + char *serial; + SDL_GUID guid; + int interface_number; // Available on Windows and Linux + int interface_class; + int interface_subclass; + int interface_protocol; + Uint16 usage_page; // Available on Windows and macOS + Uint16 usage; // Available on Windows and macOS + bool is_bluetooth; + SDL_JoystickType joystick_type; + SDL_GamepadType type; + int steam_virtual_gamepad_slot; + + struct SDL_HIDAPI_DeviceDriver *driver; + void *context; + SDL_Mutex *dev_lock; + SDL_hid_device *dev; + SDL_AtomicInt rumble_pending; + int num_joysticks; + SDL_JoystickID *joysticks; + + // Used during scanning for device changes + bool seen; + + // Used to flag that the device is being updated + bool updating; + + // Used to flag devices that failed open + // This can happen on Windows with Bluetooth devices that have turned off + bool broken; + + struct SDL_HIDAPI_Device *parent; + int num_children; + struct SDL_HIDAPI_Device **children; + + struct SDL_HIDAPI_Device *next; +} SDL_HIDAPI_Device; + +typedef struct SDL_HIDAPI_DeviceDriver +{ + const char *name; + bool enabled; + void (*RegisterHints)(SDL_HintCallback callback, void *userdata); + void (*UnregisterHints)(SDL_HintCallback callback, void *userdata); + bool (*IsEnabled)(void); + bool (*IsSupportedDevice)(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol); + bool (*InitDevice)(SDL_HIDAPI_Device *device); + int (*GetDevicePlayerIndex)(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id); + void (*SetDevicePlayerIndex)(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index); + bool (*UpdateDevice)(SDL_HIDAPI_Device *device); + bool (*OpenJoystick)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick); + bool (*RumbleJoystick)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble); + bool (*RumbleJoystickTriggers)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble); + Uint32 (*GetJoystickCapabilities)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick); + bool (*SetJoystickLED)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue); + bool (*SendJoystickEffect)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size); + bool (*SetJoystickSensorsEnabled)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled); + void (*CloseJoystick)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick); + void (*FreeDevice)(SDL_HIDAPI_Device *device); + +} SDL_HIDAPI_DeviceDriver; + +// HIDAPI device support +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverCombined; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverGameCube; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverJoyCons; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverLuna; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverNintendoClassic; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS3; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS3ThirdParty; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS3SonySixaxis; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS4; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS5; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverShield; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverStadia; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSteam; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSteamDeck; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSwitch; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverWii; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXbox360; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXbox360W; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXboxOne; +extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSteamHori; + +// Return true if a HID device is present and supported as a joystick of the given type +extern bool HIDAPI_IsDeviceTypePresent(SDL_GamepadType type); + +// Return true if a HID device is present and supported as a joystick +extern bool HIDAPI_IsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name); + +// Return the name of a connected device, which should be freed with SDL_free(), or NULL if it's not available +extern char *HIDAPI_GetDeviceProductName(Uint16 vendor_id, Uint16 product_id); + +// Return the manufacturer of a connected device, which should be freed with SDL_free(), or NULL if it's not available +extern char *HIDAPI_GetDeviceManufacturerName(Uint16 vendor_id, Uint16 product_id); + +// Return the type of a joystick if it's present and supported +extern SDL_JoystickType HIDAPI_GetJoystickTypeFromGUID(SDL_GUID guid); + +// Return the type of a game controller if it's present and supported +extern SDL_GamepadType HIDAPI_GetGamepadTypeFromGUID(SDL_GUID guid); + +extern void HIDAPI_UpdateDevices(void); +extern void HIDAPI_SetDeviceName(SDL_HIDAPI_Device *device, const char *name); +extern void HIDAPI_SetDeviceProduct(SDL_HIDAPI_Device *device, Uint16 vendor_id, Uint16 product_id); +extern void HIDAPI_SetDeviceSerial(SDL_HIDAPI_Device *device, const char *serial); +extern bool HIDAPI_HasConnectedUSBDevice(const char *serial); +extern void HIDAPI_DisconnectBluetoothDevice(const char *serial); +extern bool HIDAPI_JoystickConnected(SDL_HIDAPI_Device *device, SDL_JoystickID *pJoystickID); +extern void HIDAPI_JoystickDisconnected(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID); +extern void HIDAPI_UpdateDeviceProperties(SDL_HIDAPI_Device *device); + +extern void HIDAPI_DumpPacket(const char *prefix, const Uint8 *data, int size); + +extern bool HIDAPI_SupportsPlaystationDetection(Uint16 vendor, Uint16 product); + +extern float HIDAPI_RemapVal(float val, float val_min, float val_max, float output_min, float output_max); + +#endif // SDL_JOYSTICK_HIDAPI_H diff --git a/thirdparty/sdl/joystick/hidapi/steam/controller_constants.h b/thirdparty/sdl/joystick/hidapi/steam/controller_constants.h new file mode 100644 index 00000000000..78af0164b8d --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/steam/controller_constants.h @@ -0,0 +1,582 @@ +/* + Simple DirectMedia Layer + Copyright (C) 2021 Valve Corporation + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef _CONTROLLER_CONSTANTS_ +#define _CONTROLLER_CONSTANTS_ + +#include "controller_structs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define FEATURE_REPORT_SIZE 64 + +#define VALVE_USB_VID 0x28DE + +// Frame update rate (in ms). +#define FAST_SCAN_INTERVAL 6 +#define SLOW_SCAN_INTERVAL 9 + +// Contains each of the USB PIDs for Valve controllers (only add to this enum and never change the order) +enum ValveControllerPID +{ + BASTILLE_PID = 0x2202, + CHELL_PID = 0x1101, + D0G_PID = 0x1102, + ELI_PID = 0x1103, + FREEMAN_PID = 0x1104, + D0G_BLE_PID = 0x1105, + D0G_BLE2_PID = 0x1106, + D0GGLE_PID = 0x1142, + + JUPITER_PID = 0x1205, +}; + +// This enum contains all of the messages exchanged between the host and the target (only add to this enum and never change the order) +enum FeatureReportMessageIDs +{ + ID_SET_DIGITAL_MAPPINGS = 0x80, + ID_CLEAR_DIGITAL_MAPPINGS = 0x81, + ID_GET_DIGITAL_MAPPINGS = 0x82, + ID_GET_ATTRIBUTES_VALUES = 0x83, + ID_GET_ATTRIBUTE_LABEL = 0x84, + ID_SET_DEFAULT_DIGITAL_MAPPINGS = 0x85, + ID_FACTORY_RESET = 0x86, + ID_SET_SETTINGS_VALUES = 0x87, + ID_CLEAR_SETTINGS_VALUES = 0x88, + ID_GET_SETTINGS_VALUES = 0x89, + ID_GET_SETTING_LABEL = 0x8A, + ID_GET_SETTINGS_MAXS = 0x8B, + ID_GET_SETTINGS_DEFAULTS = 0x8C, + ID_SET_CONTROLLER_MODE = 0x8D, + ID_LOAD_DEFAULT_SETTINGS = 0x8E, + ID_TRIGGER_HAPTIC_PULSE = 0x8F, + + ID_TURN_OFF_CONTROLLER = 0x9F, + + ID_GET_DEVICE_INFO = 0xA1, + + ID_CALIBRATE_TRACKPADS = 0xA7, + ID_RESERVED_0 = 0xA8, + ID_SET_SERIAL_NUMBER = 0xA9, + ID_GET_TRACKPAD_CALIBRATION = 0xAA, + ID_GET_TRACKPAD_FACTORY_CALIBRATION = 0xAB, + ID_GET_TRACKPAD_RAW_DATA = 0xAC, + ID_ENABLE_PAIRING = 0xAD, + ID_GET_STRING_ATTRIBUTE = 0xAE, + ID_RADIO_ERASE_RECORDS = 0xAF, + ID_RADIO_WRITE_RECORD = 0xB0, + ID_SET_DONGLE_SETTING = 0xB1, + ID_DONGLE_DISCONNECT_DEVICE = 0xB2, + ID_DONGLE_COMMIT_DEVICE = 0xB3, + ID_DONGLE_GET_WIRELESS_STATE = 0xB4, + ID_CALIBRATE_GYRO = 0xB5, + ID_PLAY_AUDIO = 0xB6, + ID_AUDIO_UPDATE_START = 0xB7, + ID_AUDIO_UPDATE_DATA = 0xB8, + ID_AUDIO_UPDATE_COMPLETE = 0xB9, + ID_GET_CHIPID = 0xBA, + + ID_CALIBRATE_JOYSTICK = 0xBF, + ID_CALIBRATE_ANALOG_TRIGGERS = 0xC0, + ID_SET_AUDIO_MAPPING = 0xC1, + ID_CHECK_GYRO_FW_LOAD = 0xC2, + ID_CALIBRATE_ANALOG = 0xC3, + ID_DONGLE_GET_CONNECTED_SLOTS = 0xC4, + + ID_RESET_IMU = 0xCE, + + // Deck only + ID_TRIGGER_HAPTIC_CMD = 0xEA, + ID_TRIGGER_RUMBLE_CMD = 0xEB, +}; + + +// Enumeration of all wireless dongle events +typedef enum WirelessEventTypes +{ + WIRELESS_EVENT_DISCONNECT = 1, + WIRELESS_EVENT_CONNECT = 2, + WIRELESS_EVENT_PAIR = 3, +} EWirelessEventType; + + +// Enumeration of generic digital inputs - not all of these will be supported on all controllers (only add to this enum and never change the order) +typedef enum +{ + IO_DIGITAL_BUTTON_NONE = -1, + IO_DIGITAL_BUTTON_RIGHT_TRIGGER, + IO_DIGITAL_BUTTON_LEFT_TRIGGER, + IO_DIGITAL_BUTTON_1, + IO_DIGITAL_BUTTON_Y=IO_DIGITAL_BUTTON_1, + IO_DIGITAL_BUTTON_2, + IO_DIGITAL_BUTTON_B=IO_DIGITAL_BUTTON_2, + IO_DIGITAL_BUTTON_3, + IO_DIGITAL_BUTTON_X=IO_DIGITAL_BUTTON_3, + IO_DIGITAL_BUTTON_4, + IO_DIGITAL_BUTTON_A=IO_DIGITAL_BUTTON_4, + IO_DIGITAL_BUTTON_RIGHT_BUMPER, + IO_DIGITAL_BUTTON_LEFT_BUMPER, + IO_DIGITAL_BUTTON_LEFT_JOYSTICK_CLICK, + IO_DIGITAL_BUTTON_ESCAPE, + IO_DIGITAL_BUTTON_STEAM, + IO_DIGITAL_BUTTON_MENU, + IO_DIGITAL_STICK_UP, + IO_DIGITAL_STICK_DOWN, + IO_DIGITAL_STICK_LEFT, + IO_DIGITAL_STICK_RIGHT, + IO_DIGITAL_TOUCH_1, + IO_DIGITAL_BUTTON_UP=IO_DIGITAL_TOUCH_1, + IO_DIGITAL_TOUCH_2, + IO_DIGITAL_BUTTON_RIGHT=IO_DIGITAL_TOUCH_2, + IO_DIGITAL_TOUCH_3, + IO_DIGITAL_BUTTON_LEFT=IO_DIGITAL_TOUCH_3, + IO_DIGITAL_TOUCH_4, + IO_DIGITAL_BUTTON_DOWN=IO_DIGITAL_TOUCH_4, + IO_DIGITAL_BUTTON_BACK_LEFT, + IO_DIGITAL_BUTTON_BACK_RIGHT, + IO_DIGITAL_LEFT_TRACKPAD_N, + IO_DIGITAL_LEFT_TRACKPAD_NE, + IO_DIGITAL_LEFT_TRACKPAD_E, + IO_DIGITAL_LEFT_TRACKPAD_SE, + IO_DIGITAL_LEFT_TRACKPAD_S, + IO_DIGITAL_LEFT_TRACKPAD_SW, + IO_DIGITAL_LEFT_TRACKPAD_W, + IO_DIGITAL_LEFT_TRACKPAD_NW, + IO_DIGITAL_RIGHT_TRACKPAD_N, + IO_DIGITAL_RIGHT_TRACKPAD_NE, + IO_DIGITAL_RIGHT_TRACKPAD_E, + IO_DIGITAL_RIGHT_TRACKPAD_SE, + IO_DIGITAL_RIGHT_TRACKPAD_S, + IO_DIGITAL_RIGHT_TRACKPAD_SW, + IO_DIGITAL_RIGHT_TRACKPAD_W, + IO_DIGITAL_RIGHT_TRACKPAD_NW, + IO_DIGITAL_LEFT_TRACKPAD_DOUBLE_TAP, + IO_DIGITAL_RIGHT_TRACKPAD_DOUBLE_TAP, + IO_DIGITAL_LEFT_TRACKPAD_OUTER_RADIUS, + IO_DIGITAL_RIGHT_TRACKPAD_OUTER_RADIUS, + IO_DIGITAL_LEFT_TRACKPAD_CLICK, + IO_DIGITAL_RIGHT_TRACKPAD_CLICK, + IO_DIGITAL_BATTERY_LOW, + IO_DIGITAL_LEFT_TRIGGER_THRESHOLD, + IO_DIGITAL_RIGHT_TRIGGER_THRESHOLD, + IO_DIGITAL_BUTTON_BACK_LEFT2, + IO_DIGITAL_BUTTON_BACK_RIGHT2, + IO_DIGITAL_BUTTON_ALWAYS_ON, + IO_DIGITAL_BUTTON_ANCILLARY_1, + IO_DIGITAL_BUTTON_MACRO_0, + IO_DIGITAL_BUTTON_MACRO_1, + IO_DIGITAL_BUTTON_MACRO_2, + IO_DIGITAL_BUTTON_MACRO_3, + IO_DIGITAL_BUTTON_MACRO_4, + IO_DIGITAL_BUTTON_MACRO_5, + IO_DIGITAL_BUTTON_MACRO_6, + IO_DIGITAL_BUTTON_MACRO_7, + IO_DIGITAL_BUTTON_MACRO_1FINGER, + IO_DIGITAL_BUTTON_MACRO_2FINGER, + IO_DIGITAL_COUNT +} DigitalIO ; + +// Enumeration of generic analog inputs - not all of these will be supported on all controllers (only add to this enum and never change the order) +typedef enum +{ + IO_ANALOG_LEFT_STICK_X, + IO_ANALOG_LEFT_STICK_Y, + IO_ANALOG_RIGHT_STICK_X, + IO_ANALOG_RIGHT_STICK_Y, + IO_ANALOG_LEFT_TRIGGER, + IO_ANALOG_RIGHT_TRIGGER, + IO_MOUSE1_X, + IO_MOUSE1_Y, + IO_MOUSE1_Z, + IO_ACCEL_X, + IO_ACCEL_Y, + IO_ACCEL_Z, + IO_GYRO_X, + IO_GYRO_Y, + IO_GYRO_Z, + IO_GYRO_QUAT_W, + IO_GYRO_QUAT_X, + IO_GYRO_QUAT_Y, + IO_GYRO_QUAT_Z, + IO_GYRO_STEERING_VEC, + IO_RAW_TRIGGER_LEFT, + IO_RAW_TRIGGER_RIGHT, + IO_RAW_JOYSTICK_X, + IO_RAW_JOYSTICK_Y, + IO_GYRO_TILT_VEC, + IO_PRESSURE_LEFT_PAD, + IO_PRESSURE_RIGHT_PAD, + IO_PRESSURE_LEFT_BUMPER, + IO_PRESSURE_RIGHT_BUMPER, + IO_PRESSURE_LEFT_GRIP, + IO_PRESSURE_RIGHT_GRIP, + IO_ANALOG_LEFT_TRIGGER_THRESHOLD, + IO_ANALOG_RIGHT_TRIGGER_THRESHOLD, + IO_PRESSURE_RIGHT_PAD_THRESHOLD, + IO_PRESSURE_LEFT_PAD_THRESHOLD, + IO_PRESSURE_RIGHT_BUMPER_THRESHOLD, + IO_PRESSURE_LEFT_BUMPER_THRESHOLD, + IO_PRESSURE_RIGHT_GRIP_THRESHOLD, + IO_PRESSURE_LEFT_GRIP_THRESHOLD, + IO_PRESSURE_RIGHT_PAD_RAW, + IO_PRESSURE_LEFT_PAD_RAW, + IO_PRESSURE_RIGHT_BUMPER_RAW, + IO_PRESSURE_LEFT_BUMPER_RAW, + IO_PRESSURE_RIGHT_GRIP_RAW, + IO_PRESSURE_LEFT_GRIP_RAW, + IO_PRESSURE_RIGHT_GRIP2_THRESHOLD, + IO_PRESSURE_LEFT_GRIP2_THRESHOLD, + IO_PRESSURE_LEFT_GRIP2, + IO_PRESSURE_RIGHT_GRIP2, + IO_PRESSURE_RIGHT_GRIP2_RAW, + IO_PRESSURE_LEFT_GRIP2_RAW, + IO_ANALOG_COUNT +} AnalogIO; + + +// Contains list of all types of devices that the controller emulates (only add to this enum and never change the order) +enum DeviceTypes +{ + DEVICE_KEYBOARD, + DEVICE_MOUSE, + DEVICE_GAMEPAD, + DEVICE_MODE_ADJUST, + DEVICE_COUNT +}; + +// Scan codes for HID keyboards +enum HIDKeyboardKeys +{ + KEY_INVALID, + KEY_FIRST = 0x04, + KEY_A = KEY_FIRST, KEY_B, KEY_C, KEY_D, KEY_E, KEY_F, KEY_G, KEY_H, KEY_I, KEY_J, KEY_K, KEY_L, + KEY_M, KEY_N, KEY_O, KEY_P, KEY_Q, KEY_R, KEY_S, KEY_T, KEY_U, KEY_V, KEY_W, KEY_X, KEY_Y, KEY_Z, KEY_1, KEY_2, + KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9, KEY_0, KEY_RETURN, KEY_ESCAPE, KEY_BACKSPACE, KEY_TAB, KEY_SPACE, KEY_DASH, KEY_EQUALS, KEY_LEFT_BRACKET, + KEY_RIGHT_BRACKET, KEY_BACKSLASH, KEY_UNUSED1, KEY_SEMICOLON, KEY_SINGLE_QUOTE, KEY_BACK_TICK, KEY_COMMA, KEY_PERIOD, KEY_FORWARD_SLASH, KEY_CAPSLOCK, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, + KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_PRINT_SCREEN, KEY_SCROLL_LOCK, KEY_BREAK, KEY_INSERT, KEY_HOME, KEY_PAGE_UP, KEY_DELETE, KEY_END, KEY_PAGE_DOWN, KEY_RIGHT_ARROW, + KEY_LEFT_ARROW, KEY_DOWN_ARROW, KEY_UP_ARROW, KEY_NUM_LOCK, KEY_KEYPAD_FORWARD_SLASH, KEY_KEYPAD_ASTERISK, KEY_KEYPAD_DASH, KEY_KEYPAD_PLUS, KEY_KEYPAD_ENTER, KEY_KEYPAD_1, KEY_KEYPAD_2, KEY_KEYPAD_3, KEY_KEYPAD_4, KEY_KEYPAD_5, KEY_KEYPAD_6, KEY_KEYPAD_7, + KEY_KEYPAD_8, KEY_KEYPAD_9, KEY_KEYPAD_0, KEY_KEYPAD_PERIOD, + KEY_LALT, + KEY_LSHIFT, + KEY_LWIN, + KEY_LCONTROL, + KEY_RALT, + KEY_RSHIFT, + KEY_RWIN, + KEY_RCONTROL, + KEY_VOLUP, + KEY_VOLDOWN, + KEY_MUTE, + KEY_PLAY, + KEY_STOP, + KEY_NEXT, + KEY_PREV, + KEY_LAST = KEY_PREV +}; + +enum ModifierMasks +{ + KEY_LCONTROL_MASK = (1<<0), + KEY_LSHIFT_MASK = (1<<1), + KEY_LALT_MASK = (1<<2), + KEY_LWIN_MASK = (1<<3), + KEY_RCONTROL_MASK = (1<<4), + KEY_RSHIFT_MASK = (1<<5), + KEY_RALT_MASK = (1<<6), + KEY_RWIN_MASK = (1<<7) +}; + +// Standard mouse buttons as specified in the HID mouse spec +enum MouseButtons +{ + MOUSE_BTN_LEFT, + MOUSE_BTN_RIGHT, + MOUSE_BTN_MIDDLE, + MOUSE_BTN_BACK, + MOUSE_BTN_FORWARD, + MOUSE_SCROLL_UP, + MOUSE_SCROLL_DOWN, + MOUSE_BTN_COUNT +}; + +// Gamepad buttons +enum GamepadButtons +{ + GAMEPAD_BTN_TRIGGER_LEFT=1, + GAMEPAD_BTN_TRIGGER_RIGHT, + GAMEPAD_BTN_A, + GAMEPAD_BTN_B, + GAMEPAD_BTN_Y, + GAMEPAD_BTN_X, + GAMEPAD_BTN_SHOULDER_LEFT, + GAMEPAD_BTN_SHOULDER_RIGHT, + GAMEPAD_BTN_LEFT_JOYSTICK, + GAMEPAD_BTN_RIGHT_JOYSTICK, + GAMEPAD_BTN_START, + GAMEPAD_BTN_SELECT, + GAMEPAD_BTN_STEAM, + GAMEPAD_BTN_DPAD_UP, + GAMEPAD_BTN_DPAD_DOWN, + GAMEPAD_BTN_DPAD_LEFT, + GAMEPAD_BTN_DPAD_RIGHT, + GAMEPAD_BTN_LSTICK_UP, + GAMEPAD_BTN_LSTICK_DOWN, + GAMEPAD_BTN_LSTICK_LEFT, + GAMEPAD_BTN_LSTICK_RIGHT, + GAMEPAD_BTN_RSTICK_UP, + GAMEPAD_BTN_RSTICK_DOWN, + GAMEPAD_BTN_RSTICK_LEFT, + GAMEPAD_BTN_RSTICK_RIGHT, + GAMEPAD_BTN_COUNT +}; + +// Mode adjust +enum ModeAdjustModes +{ + MODE_ADJUST_SENSITITY=1, + MODE_ADJUST_LEFT_PAD_SECONDARY_MODE, + MODE_ADJUST_RIGHT_PAD_SECONDARY_MODE, + MODE_ADJUST_COUNT +}; + +// Read-only attributes of controllers (only add to this enum and never change the order) +typedef enum +{ + ATTRIB_UNIQUE_ID, + ATTRIB_PRODUCT_ID, + ATTRIB_PRODUCT_REVISON, // deprecated + ATTRIB_CAPABILITIES = ATTRIB_PRODUCT_REVISON, // intentional aliasing + ATTRIB_FIRMWARE_VERSION, // deprecated + ATTRIB_FIRMWARE_BUILD_TIME, + ATTRIB_RADIO_FIRMWARE_BUILD_TIME, + ATTRIB_RADIO_DEVICE_ID0, + ATTRIB_RADIO_DEVICE_ID1, + ATTRIB_DONGLE_FIRMWARE_BUILD_TIME, + ATTRIB_BOARD_REVISION, + ATTRIB_BOOTLOADER_BUILD_TIME, + ATTRIB_CONNECTION_INTERVAL_IN_US, + ATTRIB_COUNT +} ControllerAttributes; + +// Read-only string attributes of controllers (only add to this enum and never change the order) +typedef enum +{ + ATTRIB_STR_BOARD_SERIAL, + ATTRIB_STR_UNIT_SERIAL, + ATTRIB_STR_COUNT +} ControllerStringAttributes; + +typedef enum +{ + STATUS_CODE_NORMAL, + STATUS_CODE_CRITICAL_BATTERY, + STATUS_CODE_GYRO_INIT_ERROR, +} ControllerStatusEventCodes; + +typedef enum +{ + STATUS_STATE_LOW_BATTERY=0, +} ControllerStatusStateFlags; + +typedef enum { + TRACKPAD_ABSOLUTE_MOUSE, + TRACKPAD_RELATIVE_MOUSE, + TRACKPAD_DPAD_FOUR_WAY_DISCRETE, + TRACKPAD_DPAD_FOUR_WAY_OVERLAP, + TRACKPAD_DPAD_EIGHT_WAY, + TRACKPAD_RADIAL_MODE, + TRACKPAD_ABSOLUTE_DPAD, + TRACKPAD_NONE, + TRACKPAD_GESTURE_KEYBOARD, + TRACKPAD_NUM_MODES +} TrackpadDPadMode; + +// Read-write controller settings (only add to this enum and never change the order) +typedef enum +{ + SETTING_MOUSE_SENSITIVITY, + SETTING_MOUSE_ACCELERATION, + SETTING_TRACKBALL_ROTATION_ANGLE, + SETTING_HAPTIC_INTENSITY_UNUSED, + SETTING_LEFT_GAMEPAD_STICK_ENABLED, + SETTING_RIGHT_GAMEPAD_STICK_ENABLED, + SETTING_USB_DEBUG_MODE, + SETTING_LEFT_TRACKPAD_MODE, + SETTING_RIGHT_TRACKPAD_MODE, + SETTING_MOUSE_POINTER_ENABLED, + + // 10 + SETTING_DPAD_DEADZONE, + SETTING_MINIMUM_MOMENTUM_VEL, + SETTING_MOMENTUM_DECAY_AMOUNT, + SETTING_TRACKPAD_RELATIVE_MODE_TICKS_PER_PIXEL, + SETTING_HAPTIC_INCREMENT, + SETTING_DPAD_ANGLE_SIN, + SETTING_DPAD_ANGLE_COS, + SETTING_MOMENTUM_VERTICAL_DIVISOR, + SETTING_MOMENTUM_MAXIMUM_VELOCITY, + SETTING_TRACKPAD_Z_ON, + + // 20 + SETTING_TRACKPAD_Z_OFF, + SETTING_SENSITIVITY_SCALE_AMOUNT, + SETTING_LEFT_TRACKPAD_SECONDARY_MODE, + SETTING_RIGHT_TRACKPAD_SECONDARY_MODE, + SETTING_SMOOTH_ABSOLUTE_MOUSE, + SETTING_STEAMBUTTON_POWEROFF_TIME, + SETTING_UNUSED_1, + SETTING_TRACKPAD_OUTER_RADIUS, + SETTING_TRACKPAD_Z_ON_LEFT, + SETTING_TRACKPAD_Z_OFF_LEFT, + + // 30 + SETTING_TRACKPAD_OUTER_SPIN_VEL, + SETTING_TRACKPAD_OUTER_SPIN_RADIUS, + SETTING_TRACKPAD_OUTER_SPIN_HORIZONTAL_ONLY, + SETTING_TRACKPAD_RELATIVE_MODE_DEADZONE, + SETTING_TRACKPAD_RELATIVE_MODE_MAX_VEL, + SETTING_TRACKPAD_RELATIVE_MODE_INVERT_Y, + SETTING_TRACKPAD_DOUBLE_TAP_BEEP_ENABLED, + SETTING_TRACKPAD_DOUBLE_TAP_BEEP_PERIOD, + SETTING_TRACKPAD_DOUBLE_TAP_BEEP_COUNT, + SETTING_TRACKPAD_OUTER_RADIUS_RELEASE_ON_TRANSITION, + + // 40 + SETTING_RADIAL_MODE_ANGLE, + SETTING_HAPTIC_INTENSITY_MOUSE_MODE, + SETTING_LEFT_DPAD_REQUIRES_CLICK, + SETTING_RIGHT_DPAD_REQUIRES_CLICK, + SETTING_LED_BASELINE_BRIGHTNESS, + SETTING_LED_USER_BRIGHTNESS, + SETTING_ENABLE_RAW_JOYSTICK, + SETTING_ENABLE_FAST_SCAN, + SETTING_IMU_MODE, + SETTING_WIRELESS_PACKET_VERSION, + + // 50 + SETTING_SLEEP_INACTIVITY_TIMEOUT, + SETTING_TRACKPAD_NOISE_THRESHOLD, + SETTING_LEFT_TRACKPAD_CLICK_PRESSURE, + SETTING_RIGHT_TRACKPAD_CLICK_PRESSURE, + SETTING_LEFT_BUMPER_CLICK_PRESSURE, + SETTING_RIGHT_BUMPER_CLICK_PRESSURE, + SETTING_LEFT_GRIP_CLICK_PRESSURE, + SETTING_RIGHT_GRIP_CLICK_PRESSURE, + SETTING_LEFT_GRIP2_CLICK_PRESSURE, + SETTING_RIGHT_GRIP2_CLICK_PRESSURE, + + // 60 + SETTING_PRESSURE_MODE, + SETTING_CONTROLLER_TEST_MODE, + SETTING_TRIGGER_MODE, + SETTING_TRACKPAD_Z_THRESHOLD, + SETTING_FRAME_RATE, + SETTING_TRACKPAD_FILT_CTRL, + SETTING_TRACKPAD_CLIP, + SETTING_DEBUG_OUTPUT_SELECT, + SETTING_TRIGGER_THRESHOLD_PERCENT, + SETTING_TRACKPAD_FREQUENCY_HOPPING, + + // 70 + SETTING_HAPTICS_ENABLED, + SETTING_STEAM_WATCHDOG_ENABLE, + SETTING_TIMP_TOUCH_THRESHOLD_ON, + SETTING_TIMP_TOUCH_THRESHOLD_OFF, + SETTING_FREQ_HOPPING, + SETTING_TEST_CONTROL, + SETTING_HAPTIC_MASTER_GAIN_DB, + SETTING_THUMB_TOUCH_THRESH, + SETTING_DEVICE_POWER_STATUS, + SETTING_HAPTIC_INTENSITY, + + // 80 + SETTING_STABILIZER_ENABLED, + SETTING_TIMP_MODE_MTE, + SETTING_COUNT, + + // This is a special setting value use for callbacks and should not be set/get explicitly. + SETTING_ALL=0xFF +} ControllerSettings; + +typedef enum +{ + SETTING_DEFAULT, + SETTING_MIN, + SETTING_MAX, + SETTING_DEFAULTMINMAXCOUNT +} SettingDefaultMinMax; + +// Bitmask that define which IMU features to enable. +typedef enum +{ + SETTING_GYRO_MODE_OFF = 0x0000, + SETTING_GYRO_MODE_STEERING = 0x0001, + SETTING_GYRO_MODE_TILT = 0x0002, + SETTING_GYRO_MODE_SEND_ORIENTATION = 0x0004, + SETTING_GYRO_MODE_SEND_RAW_ACCEL = 0x0008, + SETTING_GYRO_MODE_SEND_RAW_GYRO = 0x0010, +} SettingGyroMode; + +// Bitmask for haptic pulse flags +typedef enum +{ + HAPTIC_PULSE_NORMAL = 0x0000, + HAPTIC_PULSE_HIGH_PRIORITY = 0x0001, + HAPTIC_PULSE_VERY_HIGH_PRIORITY = 0x0002, + HAPTIC_PULSE_IGNORE_USER_PREFS = 0x0003, +} SettingHapticPulseFlags; + +typedef struct +{ + // default,min,max in this array in that order + short defaultminmax[SETTING_DEFAULTMINMAXCOUNT]; +} SettingValueRange_t; + +// below is from controller_constants.c which should be compiled into any code that uses this +extern const SettingValueRange_t g_DefaultSettingValues[SETTING_COUNT]; + +// Read-write settings for dongle (only add to this enum and never change the order) +typedef enum +{ + DONGLE_SETTING_MOUSE_KEYBOARD_ENABLED, + DONGLE_SETTING_COUNT, +} DongleSettings; + +typedef enum +{ + AUDIO_STARTUP = 0, + AUDIO_SHUTDOWN = 1, + AUDIO_PAIR = 2, + AUDIO_PAIR_SUCCESS = 3, + AUDIO_IDENTIFY = 4, + AUDIO_LIZARDMODE = 5, + AUDIO_NORMALMODE = 6, + + AUDIO_MAX_SLOT = 15 +} ControllerAudio; + +#ifdef __cplusplus +} +#endif + +#endif // _CONTROLLER_CONSTANTS_H diff --git a/thirdparty/sdl/joystick/hidapi/steam/controller_structs.h b/thirdparty/sdl/joystick/hidapi/steam/controller_structs.h new file mode 100644 index 00000000000..ea2a3522509 --- /dev/null +++ b/thirdparty/sdl/joystick/hidapi/steam/controller_structs.h @@ -0,0 +1,463 @@ +/* + Simple DirectMedia Layer + Copyright (C) 2020 Valve Corporation + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#ifndef _CONTROLLER_STRUCTS_ +#define _CONTROLLER_STRUCTS_ + +#pragma pack(1) + +#define HID_FEATURE_REPORT_BYTES 64 + +// Header for all host <==> target messages +typedef struct +{ + unsigned char type; + unsigned char length; +} FeatureReportHeader; + +// Generic controller settings structure +typedef struct +{ + unsigned char settingNum; + unsigned short settingValue; +} ControllerSetting; + +// Generic controller attribute structure +typedef struct +{ + unsigned char attributeTag; + uint32_t attributeValue; +} ControllerAttribute; + +// Generic controller settings structure +typedef struct +{ + ControllerSetting settings[ ( HID_FEATURE_REPORT_BYTES - sizeof( FeatureReportHeader ) ) / sizeof( ControllerSetting ) ]; +} MsgSetSettingsValues, MsgGetSettingsValues, MsgGetSettingsDefaults, MsgGetSettingsMaxs; + +// Generic controller settings structure +typedef struct +{ + ControllerAttribute attributes[ ( HID_FEATURE_REPORT_BYTES - sizeof( FeatureReportHeader ) ) / sizeof( ControllerAttribute ) ]; +} MsgGetAttributes; + +typedef struct +{ + unsigned char attributeTag; + char attributeValue[20]; +} MsgGetStringAttribute; + +typedef struct +{ + unsigned char mode; +} MsgSetControllerMode; + +// Trigger a haptic pulse +typedef struct { + unsigned char which_pad; + unsigned short pulse_duration; + unsigned short pulse_interval; + unsigned short pulse_count; + short dBgain; + unsigned char priority; +} MsgFireHapticPulse; + +typedef struct { + uint8_t mode; +} MsgHapticSetMode; + +typedef enum { + HAPTIC_TYPE_OFF, + HAPTIC_TYPE_TICK, + HAPTIC_TYPE_CLICK, + HAPTIC_TYPE_TONE, + HAPTIC_TYPE_RUMBLE, + HAPTIC_TYPE_NOISE, + HAPTIC_TYPE_SCRIPT, + HAPTIC_TYPE_LOG_SWEEP, +} haptic_type_t; + +typedef enum { + HAPTIC_INTENSITY_SYSTEM, + HAPTIC_INTENSITY_SHORT, + HAPTIC_INTENSITY_MEDIUM, + HAPTIC_INTENSITY_LONG, + HAPTIC_INTENSITY_INSANE, +} haptic_intensity_t; + +typedef struct { + uint8_t side; // 0x01 = L, 0x02 = R, 0x03 = Both + uint8_t cmd; // 0 = Off, 1 = tick, 2 = click, 3 = tone, 4 = rumble, 5 = + // rumble_noise, 6 = script, 7 = sweep, + uint8_t ui_intensity; // 0-4 (0 = default) + int8_t dBgain; // dB Can be positive (reasonable clipping / limiting will apply) + uint16_t freq; // Frequency of tone (if applicable) + int16_t dur_ms; // Duration of tone / rumble (if applicable) (neg = infinite) + + uint16_t noise_intensity; + uint16_t lfo_freq; // Drives both tone and rumble geneators + uint8_t lfo_depth; // percentage, typically 100 + uint8_t rand_tone_gain; // Randomize each LFO cycle's gain + uint8_t script_id; // Used w/ dBgain for scripted haptics + + uint16_t lss_start_freq; // Used w/ Log Sine Sweep + uint16_t lss_end_freq; // Ditto +} MsgTriggerHaptic; + +typedef struct { + uint8_t unRumbleType; + uint16_t unIntensity; + uint16_t unLeftMotorSpeed; + uint16_t unRightMotorSpeed; + int8_t nLeftGain; + int8_t nRightGain; +} MsgSimpleRumbleCmd; + +// This is the only message struct that application code should use to interact with feature request messages. Any new +// messages should be added to the union. The structures defined here should correspond to the ones defined in +// ValveDeviceCore.cpp. +// +typedef struct +{ + FeatureReportHeader header; + union + { + MsgSetSettingsValues setSettingsValues; + MsgGetSettingsValues getSettingsValues; + MsgGetSettingsMaxs getSettingsMaxs; + MsgGetSettingsDefaults getSettingsDefaults; + MsgGetAttributes getAttributes; + MsgSetControllerMode controllerMode; + MsgFireHapticPulse fireHapticPulse; + MsgGetStringAttribute getStringAttribute; + MsgHapticSetMode hapticMode; + MsgTriggerHaptic triggerHaptic; + MsgSimpleRumbleCmd simpleRumble; + } payload; + +} FeatureReportMsg; + +// Roll this version forward anytime that you are breaking compatibility of existing +// message types within ValveInReport_t or the header itself. Hopefully this should +// be super rare and instead you should just add new message payloads to the union, +// or just add fields to the end of existing payload structs which is expected to be +// safe in all code consuming these as they should just consume/copy up to the prior size +// they were aware of when processing. +#define k_ValveInReportMsgVersion 0x01 + +typedef enum +{ + ID_CONTROLLER_STATE = 1, + ID_CONTROLLER_DEBUG = 2, + ID_CONTROLLER_WIRELESS = 3, + ID_CONTROLLER_STATUS = 4, + ID_CONTROLLER_DEBUG2 = 5, + ID_CONTROLLER_SECONDARY_STATE = 6, + ID_CONTROLLER_BLE_STATE = 7, + ID_CONTROLLER_DECK_STATE = 9, + ID_CONTROLLER_MSG_COUNT +} ValveInReportMessageIDs; + +typedef struct +{ + unsigned short unReportVersion; + + unsigned char ucType; + unsigned char ucLength; + +} ValveInReportHeader_t; + +// State payload +typedef struct +{ + // If packet num matches that on your prior call, then the controller state hasn't been changed since + // your last call and there is no need to process it + Uint32 unPacketNum; + + // Button bitmask and trigger data. + union + { + Uint64 ulButtons; + struct + { + unsigned char _pad0[3]; + unsigned char nLeft; + unsigned char nRight; + unsigned char _pad1[3]; + } Triggers; + } ButtonTriggerData; + + // Left pad coordinates + short sLeftPadX; + short sLeftPadY; + + // Right pad coordinates + short sRightPadX; + short sRightPadY; + + // This is redundant, packed above, but still sent over wired + unsigned short sTriggerL; + unsigned short sTriggerR; + + // FIXME figure out a way to grab this stuff over wireless + short sAccelX; + short sAccelY; + short sAccelZ; + + short sGyroX; + short sGyroY; + short sGyroZ; + + short sGyroQuatW; + short sGyroQuatX; + short sGyroQuatY; + short sGyroQuatZ; + +} ValveControllerStatePacket_t; + +// BLE State payload this has to be re-formatted from the normal state because BLE controller shows up as +//a HID device and we don't want to send all the optional parts of the message. Keep in sync with struct above. +typedef struct +{ + // If packet num matches that on your prior call, then the controller state hasn't been changed since + // your last call and there is no need to process it + Uint32 unPacketNum; + + // Button bitmask and trigger data. + union + { + Uint64 ulButtons; + struct + { + unsigned char _pad0[3]; + unsigned char nLeft; + unsigned char nRight; + unsigned char _pad1[3]; + } Triggers; + } ButtonTriggerData; + + // Left pad coordinates + short sLeftPadX; + short sLeftPadY; + + // Right pad coordinates + short sRightPadX; + short sRightPadY; + + //This mimcs how the dongle reconstitutes HID packets, there will be 0-4 shorts depending on gyro mode + unsigned char ucGyroDataType; //TODO could maybe find some unused bits in the button field for this info (is only 2bits) + short sGyro[4]; + +} ValveControllerBLEStatePacket_t; + +// Define a payload for reporting debug information +typedef struct +{ + // Left pad coordinates + short sLeftPadX; + short sLeftPadY; + + // Right pad coordinates + short sRightPadX; + short sRightPadY; + + // Left mouse deltas + short sLeftPadMouseDX; + short sLeftPadMouseDY; + + // Right mouse deltas + short sRightPadMouseDX; + short sRightPadMouseDY; + + // Left mouse filtered deltas + short sLeftPadMouseFilteredDX; + short sLeftPadMouseFilteredDY; + + // Right mouse filtered deltas + short sRightPadMouseFilteredDX; + short sRightPadMouseFilteredDY; + + // Pad Z values + unsigned char ucLeftZ; + unsigned char ucRightZ; + + // FingerPresent + unsigned char ucLeftFingerPresent; + unsigned char ucRightFingerPresent; + + // Timestamps + unsigned char ucLeftTimestamp; + unsigned char ucRightTimestamp; + + // Double tap state + unsigned char ucLeftTapState; + unsigned char ucRightTapState; + + unsigned int unDigitalIOStates0; + unsigned int unDigitalIOStates1; + +} ValveControllerDebugPacket_t; + +typedef struct +{ + unsigned char ucPadNum; + unsigned char ucPad[3]; // need Data to be word aligned + short Data[20]; + unsigned short unNoise; +} ValveControllerTrackpadImage_t; + +typedef struct +{ + unsigned char ucPadNum; + unsigned char ucOffset; + unsigned char ucPad[2]; // need Data to be word aligned + short rgData[28]; +} ValveControllerRawTrackpadImage_t; + +// Payload for wireless metadata +typedef struct +{ + unsigned char ucEventType; +} SteamControllerWirelessEvent_t; + +typedef struct +{ + // Current packet number. + unsigned int unPacketNum; + + // Event codes and state information. + unsigned short sEventCode; + unsigned short unStateFlags; + + // Current battery voltage (mV). + unsigned short sBatteryVoltage; + + // Current battery level (0-100). + unsigned char ucBatteryLevel; +} SteamControllerStatusEvent_t; + +// Deck State payload +typedef struct +{ + // If packet num matches that on your prior call, then the controller + // state hasn't been changed since your last call and there is no need to + // process it + Uint32 unPacketNum; + + // Button bitmask and trigger data. + union + { + Uint64 ulButtons; + struct + { + Uint32 ulButtonsL; + Uint32 ulButtonsH; + }; + }; + + // Left pad coordinates + short sLeftPadX; + short sLeftPadY; + + // Right pad coordinates + short sRightPadX; + short sRightPadY; + + // Accelerometer values + short sAccelX; + short sAccelY; + short sAccelZ; + + // Gyroscope values + short sGyroX; + short sGyroY; + short sGyroZ; + + // Gyro quaternions + short sGyroQuatW; + short sGyroQuatX; + short sGyroQuatY; + short sGyroQuatZ; + + // Uncalibrated trigger values + unsigned short sTriggerRawL; + unsigned short sTriggerRawR; + + // Left stick values + short sLeftStickX; + short sLeftStickY; + + // Right stick values + short sRightStickX; + short sRightStickY; + + // Touchpad pressures + unsigned short sPressurePadLeft; + unsigned short sPressurePadRight; +} SteamDeckStatePacket_t; + +typedef struct +{ + ValveInReportHeader_t header; + + union + { + ValveControllerStatePacket_t controllerState; + ValveControllerBLEStatePacket_t controllerBLEState; + ValveControllerDebugPacket_t debugState; + ValveControllerTrackpadImage_t padImage; + ValveControllerRawTrackpadImage_t rawPadImage; + SteamControllerWirelessEvent_t wirelessEvent; + SteamControllerStatusEvent_t statusEvent; + SteamDeckStatePacket_t deckState; + } payload; + +} ValveInReport_t; + + +// Enumeration for BLE packet protocol +enum EBLEPacketReportNums +{ + // Skipping past 2-3 because they are escape characters in Uart protocol + k_EBLEReportState = 4, + k_EBLEReportStatus = 5, +}; + + +// Enumeration of data chunks in BLE state packets +enum EBLEOptionDataChunksBitmask +{ + // First byte upper nibble + k_EBLEButtonChunk1 = 0x10, + k_EBLEButtonChunk2 = 0x20, + k_EBLEButtonChunk3 = 0x40, + k_EBLELeftJoystickChunk = 0x80, + + // Second full byte + k_EBLELeftTrackpadChunk = 0x100, + k_EBLERightTrackpadChunk = 0x200, + k_EBLEIMUAccelChunk = 0x400, + k_EBLEIMUGyroChunk = 0x800, + k_EBLEIMUQuatChunk = 0x1000, +}; + +#pragma pack() + +#endif // _CONTROLLER_STRUCTS diff --git a/thirdparty/sdl/joystick/linux/SDL_sysjoystick.c b/thirdparty/sdl/joystick/linux/SDL_sysjoystick.c new file mode 100644 index 00000000000..ea73821c064 --- /dev/null +++ b/thirdparty/sdl/joystick/linux/SDL_sysjoystick.c @@ -0,0 +1,2730 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_LINUX + +#ifndef SDL_INPUT_LINUXEV +#error SDL now requires a Linux 2.4+ kernel with /dev/input/event support. +#endif + +// This is the Linux implementation of the SDL joystick API + +#include +#include // errno, strerror +#include +#include // For the definition of PATH_MAX +#ifdef HAVE_INOTIFY +#include +#include // strerror +#endif +#include +#include +#include +#include + +#include "../../events/SDL_events_c.h" +#include "../../core/linux/SDL_evdev.h" +#include "../SDL_sysjoystick.h" +#include "../SDL_joystick_c.h" +#include "../usb_ids.h" +#include "SDL_sysjoystick_c.h" +#include "../hidapi/SDL_hidapijoystick_c.h" + +// This isn't defined in older Linux kernel headers +#ifndef MSC_TIMESTAMP +#define MSC_TIMESTAMP 0x05 +#endif + +#ifndef SYN_DROPPED +#define SYN_DROPPED 3 +#endif +#ifndef BTN_NORTH +#define BTN_NORTH 0x133 +#endif +#ifndef BTN_WEST +#define BTN_WEST 0x134 +#endif +#ifndef BTN_DPAD_UP +#define BTN_DPAD_UP 0x220 +#endif +#ifndef BTN_DPAD_DOWN +#define BTN_DPAD_DOWN 0x221 +#endif +#ifndef BTN_DPAD_LEFT +#define BTN_DPAD_LEFT 0x222 +#endif +#ifndef BTN_DPAD_RIGHT +#define BTN_DPAD_RIGHT 0x223 +#endif + +#ifndef BTN_TRIGGER_HAPPY +#define BTN_TRIGGER_HAPPY 0x2c0 +#define BTN_TRIGGER_HAPPY1 0x2c0 +#define BTN_TRIGGER_HAPPY2 0x2c1 +#define BTN_TRIGGER_HAPPY3 0x2c2 +#define BTN_TRIGGER_HAPPY4 0x2c3 +#define BTN_TRIGGER_HAPPY5 0x2c4 +#define BTN_TRIGGER_HAPPY6 0x2c5 +#define BTN_TRIGGER_HAPPY7 0x2c6 +#define BTN_TRIGGER_HAPPY8 0x2c7 +#define BTN_TRIGGER_HAPPY9 0x2c8 +#define BTN_TRIGGER_HAPPY10 0x2c9 +#define BTN_TRIGGER_HAPPY11 0x2ca +#define BTN_TRIGGER_HAPPY12 0x2cb +#define BTN_TRIGGER_HAPPY13 0x2cc +#define BTN_TRIGGER_HAPPY14 0x2cd +#define BTN_TRIGGER_HAPPY15 0x2ce +#define BTN_TRIGGER_HAPPY16 0x2cf +#define BTN_TRIGGER_HAPPY17 0x2d0 +#define BTN_TRIGGER_HAPPY18 0x2d1 +#define BTN_TRIGGER_HAPPY19 0x2d2 +#define BTN_TRIGGER_HAPPY20 0x2d3 +#define BTN_TRIGGER_HAPPY21 0x2d4 +#define BTN_TRIGGER_HAPPY22 0x2d5 +#define BTN_TRIGGER_HAPPY23 0x2d6 +#define BTN_TRIGGER_HAPPY24 0x2d7 +#define BTN_TRIGGER_HAPPY25 0x2d8 +#define BTN_TRIGGER_HAPPY26 0x2d9 +#define BTN_TRIGGER_HAPPY27 0x2da +#define BTN_TRIGGER_HAPPY28 0x2db +#define BTN_TRIGGER_HAPPY29 0x2dc +#define BTN_TRIGGER_HAPPY30 0x2dd +#define BTN_TRIGGER_HAPPY31 0x2de +#define BTN_TRIGGER_HAPPY32 0x2df +#define BTN_TRIGGER_HAPPY33 0x2e0 +#define BTN_TRIGGER_HAPPY34 0x2e1 +#define BTN_TRIGGER_HAPPY35 0x2e2 +#define BTN_TRIGGER_HAPPY36 0x2e3 +#define BTN_TRIGGER_HAPPY37 0x2e4 +#define BTN_TRIGGER_HAPPY38 0x2e5 +#define BTN_TRIGGER_HAPPY39 0x2e6 +#define BTN_TRIGGER_HAPPY40 0x2e7 +#endif + + +#include "../../core/linux/SDL_evdev_capabilities.h" +#include "../../core/linux/SDL_udev.h" + +#if 0 +#define DEBUG_INPUT_EVENTS 1 +#endif + +#if 0 +#define DEBUG_GAMEPAD_MAPPING 1 +#endif + +typedef enum +{ + ENUMERATION_UNSET, + ENUMERATION_LIBUDEV, + ENUMERATION_FALLBACK +} EnumerationMethod; + +static EnumerationMethod enumeration_method = ENUMERATION_UNSET; + +static bool IsJoystickJSNode(const char *node); +static void MaybeAddDevice(const char *path); +static void MaybeRemoveDevice(const char *path); + +// A linked list of available joysticks +typedef struct SDL_joylist_item +{ + SDL_JoystickID device_instance; + char *path; // "/dev/input/event2" or whatever + char *name; // "SideWinder 3D Pro" or whatever + SDL_GUID guid; + dev_t devnum; + int steam_virtual_gamepad_slot; + struct joystick_hwdata *hwdata; + struct SDL_joylist_item *next; + + bool checked_mapping; + SDL_GamepadMapping *mapping; +} SDL_joylist_item; + +// A linked list of available gamepad sensors +typedef struct SDL_sensorlist_item +{ + char *path; // "/dev/input/event2" or whatever + dev_t devnum; + struct joystick_hwdata *hwdata; + struct SDL_sensorlist_item *next; +} SDL_sensorlist_item; + +static bool SDL_classic_joysticks = false; +static SDL_joylist_item *SDL_joylist SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static SDL_joylist_item *SDL_joylist_tail SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static int numjoysticks SDL_GUARDED_BY(SDL_joystick_lock) = 0; +static SDL_sensorlist_item *SDL_sensorlist SDL_GUARDED_BY(SDL_joystick_lock) = NULL; +static int inotify_fd = -1; + +static Uint64 last_joy_detect_time; +static time_t last_input_dir_mtime; + +static void FixupDeviceInfoForMapping(int fd, struct input_id *inpid) +{ + if (inpid->vendor == 0x045e && inpid->product == 0x0b05 && inpid->version == 0x0903) { + // This is a Microsoft Xbox One Elite Series 2 controller + unsigned long keybit[NBITS(KEY_MAX)] = { 0 }; + + // The first version of the firmware duplicated all the inputs + if ((ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) >= 0) && + test_bit(0x2c0, keybit)) { + // Change the version to 0x0902, so we can map it differently + inpid->version = 0x0902; + } + } + + /* For Atari vcs modern and classic controllers have the version reflecting + * firmware version, but the mapping stays stable so ignore + * version information */ + if (inpid->vendor == 0x3250 && (inpid->product == 0x1001 || inpid->product == 0x1002)) { + inpid->version = 0; + } +} + +#ifdef SDL_JOYSTICK_HIDAPI +static bool IsVirtualJoystick(Uint16 vendor, Uint16 product, Uint16 version, const char *name) +{ + if (vendor == USB_VENDOR_MICROSOFT && product == USB_PRODUCT_XBOX_ONE_S && version == 0 && + SDL_strcmp(name, "Xbox One S Controller") == 0) { + // This is the virtual device created by the xow driver + return true; + } + return false; +} +#else +static bool IsVirtualJoystick(Uint16 vendor, Uint16 product, Uint16 version, const char *name) +{ + return false; +} +#endif // SDL_JOYSTICK_HIDAPI + +static bool GetSteamVirtualGamepadSlot(int fd, int *slot) +{ + char name[128]; + + if (ioctl(fd, EVIOCGNAME(sizeof(name)), name) > 0) { + const char *digits = SDL_strstr(name, "pad "); + if (digits) { + digits += 4; + if (SDL_isdigit(*digits)) { + *slot = SDL_atoi(digits); + return true; + } + } + } + return false; +} + +static int GuessDeviceClass(int fd) +{ + unsigned long propbit[NBITS(INPUT_PROP_MAX)] = { 0 }; + unsigned long evbit[NBITS(EV_MAX)] = { 0 }; + unsigned long keybit[NBITS(KEY_MAX)] = { 0 }; + unsigned long absbit[NBITS(ABS_MAX)] = { 0 }; + unsigned long relbit[NBITS(REL_MAX)] = { 0 }; + + if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) || + (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) || + (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relbit)), relbit) < 0) || + (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) { + return 0; + } + + /* This is a newer feature, so it's allowed to fail - if so, then the + * device just doesn't have any properties. */ + (void) ioctl(fd, EVIOCGPROP(sizeof(propbit)), propbit); + + return SDL_EVDEV_GuessDeviceClass(propbit, evbit, absbit, keybit, relbit); +} + +static bool GuessIsJoystick(int fd) +{ + if (GuessDeviceClass(fd) & SDL_UDEV_DEVICE_JOYSTICK) { + return true; + } + return false; +} + +static bool GuessIsSensor(int fd) +{ + if (GuessDeviceClass(fd) & SDL_UDEV_DEVICE_ACCELEROMETER) { + return true; + } + return false; +} + +static bool IsJoystick(const char *path, int *fd, char **name_return, Uint16 *vendor_return, Uint16 *product_return, SDL_GUID *guid) +{ + struct input_id inpid; + char *name; + char product_string[128]; + int class = 0; + + SDL_zero(inpid); +#ifdef SDL_USE_LIBUDEV + // Opening input devices can generate synchronous device I/O, so avoid it if we can + if (SDL_UDEV_GetProductInfo(path, &inpid.vendor, &inpid.product, &inpid.version, &class) && + !(class & SDL_UDEV_DEVICE_JOYSTICK)) { + return false; + } +#endif + + if (fd && *fd < 0) { + *fd = open(path, O_RDONLY | O_CLOEXEC, 0); + } + if (!fd || *fd < 0) { + return false; + } + + if (ioctl(*fd, JSIOCGNAME(sizeof(product_string)), product_string) <= 0) { + // When udev enumeration or classification, we only got joysticks here, so no need to test + if (enumeration_method != ENUMERATION_LIBUDEV && !class && !GuessIsJoystick(*fd)) { + return false; + } + + // Could have vendor and product already from udev, but should agree with evdev + if (ioctl(*fd, EVIOCGID, &inpid) < 0) { + return false; + } + + if (ioctl(*fd, EVIOCGNAME(sizeof(product_string)), product_string) < 0) { + return false; + } + } + + name = SDL_CreateJoystickName(inpid.vendor, inpid.product, NULL, product_string); + if (!name) { + return false; + } + + if (!IsVirtualJoystick(inpid.vendor, inpid.product, inpid.version, name) && + SDL_JoystickHandledByAnotherDriver(&SDL_LINUX_JoystickDriver, inpid.vendor, inpid.product, inpid.version, name)) { + SDL_free(name); + return false; + } + + FixupDeviceInfoForMapping(*fd, &inpid); + +#ifdef DEBUG_JOYSTICK + SDL_Log("Joystick: %s, bustype = %d, vendor = 0x%.4x, product = 0x%.4x, version = %d", name, inpid.bustype, inpid.vendor, inpid.product, inpid.version); +#endif + + if (SDL_ShouldIgnoreJoystick(inpid.vendor, inpid.product, inpid.version, name)) { + SDL_free(name); + return false; + } + *name_return = name; + *vendor_return = inpid.vendor; + *product_return = inpid.product; + *guid = SDL_CreateJoystickGUID(inpid.bustype, inpid.vendor, inpid.product, inpid.version, NULL, product_string, 0, 0); + return true; +} + +static bool IsSensor(const char *path, int *fd) +{ + struct input_id inpid; + int class = 0; + + SDL_zero(inpid); +#ifdef SDL_USE_LIBUDEV + // Opening input devices can generate synchronous device I/O, so avoid it if we can + if (SDL_UDEV_GetProductInfo(path, &inpid.vendor, &inpid.product, &inpid.version, &class) && + !(class & SDL_UDEV_DEVICE_ACCELEROMETER)) { + return false; + } +#endif + + if (fd && *fd < 0) { + *fd = open(path, O_RDONLY | O_CLOEXEC, 0); + } + if (!fd || *fd < 0) { + return false; + } + + if (!class && !GuessIsSensor(*fd)) { + return false; + } + + if (ioctl(*fd, EVIOCGID, &inpid) < 0) { + return false; + } + + if (inpid.vendor == USB_VENDOR_NINTENDO && inpid.product == USB_PRODUCT_NINTENDO_WII_REMOTE) { + // Wii extension controls + // These may create 3 sensor devices but we only support reading from 1: ignore them + return false; + } + + return true; +} + +#ifdef SDL_USE_LIBUDEV +static void joystick_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath) +{ + if (!devpath) { + return; + } + + switch (udev_type) { + case SDL_UDEV_DEVICEADDED: + if (!(udev_class & (SDL_UDEV_DEVICE_JOYSTICK | SDL_UDEV_DEVICE_ACCELEROMETER))) { + return; + } + if (SDL_classic_joysticks) { + if (!IsJoystickJSNode(devpath)) { + return; + } + } else { + if (IsJoystickJSNode(devpath)) { + return; + } + } + + // Wait a bit for the hidraw udev node to initialize + SDL_Delay(10); + + MaybeAddDevice(devpath); + break; + + case SDL_UDEV_DEVICEREMOVED: + MaybeRemoveDevice(devpath); + break; + + default: + break; + } +} +#endif // SDL_USE_LIBUDEV + +static void FreeJoylistItem(SDL_joylist_item *item) +{ + SDL_free(item->mapping); + SDL_free(item->path); + SDL_free(item->name); + SDL_free(item); +} + +static void FreeSensorlistItem(SDL_sensorlist_item *item) +{ + SDL_free(item->path); + SDL_free(item); +} + +static void MaybeAddDevice(const char *path) +{ + struct stat sb; + int fd = -1; + char *name = NULL; + Uint16 vendor, product; + SDL_GUID guid; + SDL_joylist_item *item; + SDL_sensorlist_item *item_sensor; + + if (!path) { + return; + } + + fd = open(path, O_RDONLY | O_CLOEXEC, 0); + if (fd < 0) { + return; + } + + if (fstat(fd, &sb) == -1) { + close(fd); + return; + } + + SDL_LockJoysticks(); + + // Check to make sure it's not already in list. + for (item = SDL_joylist; item; item = item->next) { + if (sb.st_rdev == item->devnum) { + goto done; // already have this one + } + } + for (item_sensor = SDL_sensorlist; item_sensor; item_sensor = item_sensor->next) { + if (sb.st_rdev == item_sensor->devnum) { + goto done; // already have this one + } + } + +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Checking %s", path); +#endif + + if (IsJoystick(path, &fd, &name, &vendor, &product, &guid)) { +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("found joystick: %s", path); +#endif + item = (SDL_joylist_item *)SDL_calloc(1, sizeof(SDL_joylist_item)); + if (!item) { + SDL_free(name); + goto done; + } + + item->devnum = sb.st_rdev; + item->steam_virtual_gamepad_slot = -1; + item->path = SDL_strdup(path); + item->name = name; + item->guid = guid; + + if (vendor == USB_VENDOR_VALVE && + product == USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD) { + GetSteamVirtualGamepadSlot(fd, &item->steam_virtual_gamepad_slot); + } + + if ((!item->path) || (!item->name)) { + FreeJoylistItem(item); + goto done; + } + + item->device_instance = SDL_GetNextObjectID(); + if (!SDL_joylist_tail) { + SDL_joylist = SDL_joylist_tail = item; + } else { + SDL_joylist_tail->next = item; + SDL_joylist_tail = item; + } + + // Need to increment the joystick count before we post the event + ++numjoysticks; + + SDL_PrivateJoystickAdded(item->device_instance); + goto done; + } + + if (IsSensor(path, &fd)) { +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("found sensor: %s", path); +#endif + item_sensor = (SDL_sensorlist_item *)SDL_calloc(1, sizeof(SDL_sensorlist_item)); + if (!item_sensor) { + goto done; + } + item_sensor->devnum = sb.st_rdev; + item_sensor->path = SDL_strdup(path); + + if (!item_sensor->path) { + FreeSensorlistItem(item_sensor); + goto done; + } + + item_sensor->next = SDL_sensorlist; + SDL_sensorlist = item_sensor; + goto done; + } + +done: + close(fd); + SDL_UnlockJoysticks(); +} + +static void RemoveJoylistItem(SDL_joylist_item *item, SDL_joylist_item *prev) +{ + SDL_AssertJoysticksLocked(); + + if (item->hwdata) { + item->hwdata->item = NULL; + } + + if (prev) { + prev->next = item->next; + } else { + SDL_assert(SDL_joylist == item); + SDL_joylist = item->next; + } + + if (item == SDL_joylist_tail) { + SDL_joylist_tail = prev; + } + + // Need to decrement the joystick count before we post the event + --numjoysticks; + + SDL_PrivateJoystickRemoved(item->device_instance); + FreeJoylistItem(item); +} + +static void RemoveSensorlistItem(SDL_sensorlist_item *item, SDL_sensorlist_item *prev) +{ + SDL_AssertJoysticksLocked(); + + if (item->hwdata) { + item->hwdata->item_sensor = NULL; + } + + if (prev) { + prev->next = item->next; + } else { + SDL_assert(SDL_sensorlist == item); + SDL_sensorlist = item->next; + } + + /* Do not call SDL_PrivateJoystickRemoved here as RemoveJoylistItem will do it, + * assuming both sensor and joy item are removed at the same time */ + FreeSensorlistItem(item); +} + +static void MaybeRemoveDevice(const char *path) +{ + SDL_joylist_item *item; + SDL_joylist_item *prev = NULL; + SDL_sensorlist_item *item_sensor; + SDL_sensorlist_item *prev_sensor = NULL; + + if (!path) { + return; + } + + SDL_LockJoysticks(); + for (item = SDL_joylist; item; item = item->next) { + // found it, remove it. + if (SDL_strcmp(path, item->path) == 0) { + RemoveJoylistItem(item, prev); + goto done; + } + prev = item; + } + for (item_sensor = SDL_sensorlist; item_sensor; item_sensor = item_sensor->next) { + // found it, remove it. + if (SDL_strcmp(path, item_sensor->path) == 0) { + RemoveSensorlistItem(item_sensor, prev_sensor); + goto done; + } + prev_sensor = item_sensor; + } +done: + SDL_UnlockJoysticks(); +} + +static void HandlePendingRemovals(void) +{ + SDL_joylist_item *prev = NULL; + SDL_joylist_item *item = NULL; + SDL_sensorlist_item *prev_sensor = NULL; + SDL_sensorlist_item *item_sensor = NULL; + + SDL_AssertJoysticksLocked(); + + item = SDL_joylist; + while (item) { + if (item->hwdata && item->hwdata->gone) { + RemoveJoylistItem(item, prev); + + if (prev) { + item = prev->next; + } else { + item = SDL_joylist; + } + } else { + prev = item; + item = item->next; + } + } + + item_sensor = SDL_sensorlist; + while (item_sensor) { + if (item_sensor->hwdata && item_sensor->hwdata->sensor_gone) { + RemoveSensorlistItem(item_sensor, prev_sensor); + + if (prev_sensor) { + item_sensor = prev_sensor->next; + } else { + item_sensor = SDL_sensorlist; + } + } else { + prev_sensor = item_sensor; + item_sensor = item_sensor->next; + } + } +} + +static bool StrIsInteger(const char *string) +{ + const char *p; + + if (*string == '\0') { + return false; + } + + for (p = string; *p != '\0'; p++) { + if (*p < '0' || *p > '9') { + return false; + } + } + + return true; +} + +static bool IsJoystickJSNode(const char *node) +{ + const char *last_slash = SDL_strrchr(node, '/'); + if (last_slash) { + node = last_slash + 1; + } + return SDL_startswith(node, "js") && StrIsInteger(node + 2); +} + +static bool IsJoystickEventNode(const char *node) +{ + const char *last_slash = SDL_strrchr(node, '/'); + if (last_slash) { + node = last_slash + 1; + } + return SDL_startswith(node, "event") && StrIsInteger(node + 5); +} + +static bool IsJoystickDeviceNode(const char *node) +{ + if (SDL_classic_joysticks) { + return IsJoystickJSNode(node); + } else { + return IsJoystickEventNode(node); + } +} + +#ifdef HAVE_INOTIFY +#ifdef HAVE_INOTIFY_INIT1 +static int SDL_inotify_init1(void) +{ + return inotify_init1(IN_NONBLOCK | IN_CLOEXEC); +} +#else +static int SDL_inotify_init1(void) +{ + int fd = inotify_init(); + if (fd < 0) { + return -1; + } + fcntl(fd, F_SETFL, O_NONBLOCK); + fcntl(fd, F_SETFD, FD_CLOEXEC); + return fd; +} +#endif + +static void LINUX_InotifyJoystickDetect(void) +{ + union + { + struct inotify_event event; + char storage[4096]; + char enough_for_inotify[sizeof(struct inotify_event) + NAME_MAX + 1]; + } buf; + ssize_t bytes; + size_t remain = 0; + size_t len; + char path[PATH_MAX]; + + bytes = read(inotify_fd, &buf, sizeof(buf)); + + if (bytes > 0) { + remain = (size_t)bytes; + } + + while (remain > 0) { + if (buf.event.len > 0) { + if (IsJoystickDeviceNode(buf.event.name)) { + (void)SDL_snprintf(path, SDL_arraysize(path), "/dev/input/%s", buf.event.name); + + if (buf.event.mask & (IN_CREATE | IN_MOVED_TO | IN_ATTRIB)) { + MaybeAddDevice(path); + } else if (buf.event.mask & (IN_DELETE | IN_MOVED_FROM)) { + MaybeRemoveDevice(path); + } + } + } + + len = sizeof(struct inotify_event) + buf.event.len; + remain -= len; + + if (remain != 0) { + SDL_memmove(&buf.storage[0], &buf.storage[len], remain); + } + } +} +#endif // HAVE_INOTIFY + +static int get_event_joystick_index(int event) +{ + int joystick_index = -1; + int i, count; + struct dirent **entries = NULL; + char path[PATH_MAX]; + + (void)SDL_snprintf(path, SDL_arraysize(path), "/sys/class/input/event%d/device", event); + count = scandir(path, &entries, NULL, alphasort); + for (i = 0; i < count; ++i) { + if (SDL_strncmp(entries[i]->d_name, "js", 2) == 0) { + joystick_index = SDL_atoi(entries[i]->d_name + 2); + } + free(entries[i]); // This should NOT be SDL_free() + } + free(entries); // This should NOT be SDL_free() + + return joystick_index; +} + +/* Detect devices by reading /dev/input. In the inotify code path we + * have to do this the first time, to detect devices that already existed + * before we started; in the non-inotify code path we do this repeatedly + * (polling). */ +static int filter_entries(const struct dirent *entry) +{ + return IsJoystickDeviceNode(entry->d_name); +} +static int SDLCALL sort_entries(const void *_a, const void *_b) +{ + const struct dirent **a = (const struct dirent **)_a; + const struct dirent **b = (const struct dirent **)_b; + int numA, numB; + int offset; + + if (SDL_classic_joysticks) { + offset = 2; // strlen("js") + numA = SDL_atoi((*a)->d_name + offset); + numB = SDL_atoi((*b)->d_name + offset); + } else { + offset = 5; // strlen("event") + numA = SDL_atoi((*a)->d_name + offset); + numB = SDL_atoi((*b)->d_name + offset); + + // See if we can get the joystick ordering + { + int jsA = get_event_joystick_index(numA); + int jsB = get_event_joystick_index(numB); + if (jsA >= 0 && jsB >= 0) { + numA = jsA; + numB = jsB; + } else if (jsA >= 0) { + return -1; + } else if (jsB >= 0) { + return 1; + } + } + } + return numA - numB; +} + +typedef struct +{ + char *path; + int slot; +} VirtualGamepadEntry; + +static int SDLCALL sort_virtual_gamepads(const void *_a, const void *_b) +{ + const VirtualGamepadEntry *a = (const VirtualGamepadEntry *)_a; + const VirtualGamepadEntry *b = (const VirtualGamepadEntry *)_b; + return a->slot - b->slot; +} + +static void LINUX_ScanSteamVirtualGamepads(void) +{ + int i, count; + int fd; + struct dirent **entries = NULL; + char path[PATH_MAX]; + struct input_id inpid; + int num_virtual_gamepads = 0; + int virtual_gamepad_slot; + VirtualGamepadEntry *virtual_gamepads = NULL; +#ifdef SDL_USE_LIBUDEV + int class; +#endif + + count = scandir("/dev/input", &entries, filter_entries, NULL); + for (i = 0; i < count; ++i) { + (void)SDL_snprintf(path, SDL_arraysize(path), "/dev/input/%s", entries[i]->d_name); + +#ifdef SDL_USE_LIBUDEV + // Opening input devices can generate synchronous device I/O, so avoid it if we can + class = 0; + SDL_zero(inpid); + if (SDL_UDEV_GetProductInfo(path, &inpid.vendor, &inpid.product, &inpid.version, &class) && + (inpid.vendor != USB_VENDOR_VALVE || inpid.product != USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD)) { + free(entries[i]); // This should NOT be SDL_free() + continue; + } +#endif + fd = open(path, O_RDONLY | O_CLOEXEC, 0); + if (fd >= 0) { + if (ioctl(fd, EVIOCGID, &inpid) == 0 && + inpid.vendor == USB_VENDOR_VALVE && + inpid.product == USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD && + GetSteamVirtualGamepadSlot(fd, &virtual_gamepad_slot)) { + VirtualGamepadEntry *new_virtual_gamepads = (VirtualGamepadEntry *)SDL_realloc(virtual_gamepads, (num_virtual_gamepads + 1) * sizeof(*virtual_gamepads)); + if (new_virtual_gamepads) { + VirtualGamepadEntry *entry = &new_virtual_gamepads[num_virtual_gamepads]; + entry->path = SDL_strdup(path); + entry->slot = virtual_gamepad_slot; + if (entry->path) { + virtual_gamepads = new_virtual_gamepads; + ++num_virtual_gamepads; + } else { + SDL_free(entry->path); + SDL_free(new_virtual_gamepads); + } + } + } + close(fd); + } + free(entries[i]); // This should NOT be SDL_free() + } + free(entries); // This should NOT be SDL_free() + + if (num_virtual_gamepads > 1) { + SDL_qsort(virtual_gamepads, num_virtual_gamepads, sizeof(*virtual_gamepads), sort_virtual_gamepads); + } + for (i = 0; i < num_virtual_gamepads; ++i) { + MaybeAddDevice(virtual_gamepads[i].path); + SDL_free(virtual_gamepads[i].path); + } + SDL_free(virtual_gamepads); +} + +static void LINUX_ScanInputDevices(void) +{ + int i, count; + struct dirent **entries = NULL; + char path[PATH_MAX]; + + count = scandir("/dev/input", &entries, filter_entries, NULL); + if (count > 1) { + SDL_qsort(entries, count, sizeof(*entries), sort_entries); + } + for (i = 0; i < count; ++i) { + (void)SDL_snprintf(path, SDL_arraysize(path), "/dev/input/%s", entries[i]->d_name); + MaybeAddDevice(path); + + free(entries[i]); // This should NOT be SDL_free() + } + free(entries); // This should NOT be SDL_free() +} + +static void LINUX_FallbackJoystickDetect(void) +{ + const Uint32 SDL_JOY_DETECT_INTERVAL_MS = 3000; // Update every 3 seconds + Uint64 now = SDL_GetTicks(); + + if (!last_joy_detect_time || now >= (last_joy_detect_time + SDL_JOY_DETECT_INTERVAL_MS)) { + struct stat sb; + + // Opening input devices can generate synchronous device I/O, so avoid it if we can + if (stat("/dev/input", &sb) == 0 && sb.st_mtime != last_input_dir_mtime) { + // Look for Steam virtual gamepads first, and sort by Steam controller slot + LINUX_ScanSteamVirtualGamepads(); + + LINUX_ScanInputDevices(); + + last_input_dir_mtime = sb.st_mtime; + } + + last_joy_detect_time = now; + } +} + +static void LINUX_JoystickDetect(void) +{ +#ifdef SDL_USE_LIBUDEV + if (enumeration_method == ENUMERATION_LIBUDEV) { + SDL_UDEV_Poll(); + } else +#endif +#ifdef HAVE_INOTIFY + if (inotify_fd >= 0 && last_joy_detect_time != 0) { + LINUX_InotifyJoystickDetect(); + } else +#endif + { + LINUX_FallbackJoystickDetect(); + } + + HandlePendingRemovals(); +} + +static bool LINUX_JoystickIsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ + // We don't override any other drivers + return false; +} + +static bool LINUX_JoystickInit(void) +{ + const char *devices = SDL_GetHint(SDL_HINT_JOYSTICK_DEVICE); +#ifdef SDL_USE_LIBUDEV + bool udev_initialized = SDL_UDEV_Init(); +#endif + + SDL_classic_joysticks = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_LINUX_CLASSIC, false); + + enumeration_method = ENUMERATION_UNSET; + + // First see if the user specified one or more joysticks to use + if (devices) { + char *envcopy, *envpath, *delim; + envcopy = SDL_strdup(devices); + envpath = envcopy; + while (envpath) { + delim = SDL_strchr(envpath, ':'); + if (delim) { + *delim++ = '\0'; + } + MaybeAddDevice(envpath); + envpath = delim; + } + SDL_free(envcopy); + } + + // Force immediate joystick detection if using fallback + last_joy_detect_time = 0; + last_input_dir_mtime = 0; + + // Manually scan first, since we sort by device number and udev doesn't + LINUX_JoystickDetect(); + +#ifdef SDL_USE_LIBUDEV + if (enumeration_method == ENUMERATION_UNSET) { + if (SDL_GetHintBoolean("SDL_JOYSTICK_DISABLE_UDEV", false)) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "udev disabled by SDL_JOYSTICK_DISABLE_UDEV"); + enumeration_method = ENUMERATION_FALLBACK; + } else if (SDL_GetSandbox() != SDL_SANDBOX_NONE) { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "Container detected, disabling udev integration"); + enumeration_method = ENUMERATION_FALLBACK; + + } else { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "Using udev for joystick device discovery"); + enumeration_method = ENUMERATION_LIBUDEV; + } + } + + if (enumeration_method == ENUMERATION_LIBUDEV) { + if (udev_initialized) { + // Set up the udev callback + if (!SDL_UDEV_AddCallback(joystick_udev_callback)) { + SDL_UDEV_Quit(); + return SDL_SetError("Could not set up joystick <-> udev callback"); + } + + // Force a scan to build the initial device list + SDL_UDEV_Scan(); + } else { + SDL_LogDebug(SDL_LOG_CATEGORY_INPUT, + "udev init failed, disabling udev integration"); + enumeration_method = ENUMERATION_FALLBACK; + } + } else { + if (udev_initialized) { + SDL_UDEV_Quit(); + } + } +#endif + + if (enumeration_method != ENUMERATION_LIBUDEV) { +#ifdef HAVE_INOTIFY + inotify_fd = SDL_inotify_init1(); + + if (inotify_fd < 0) { + SDL_LogWarn(SDL_LOG_CATEGORY_INPUT, + "Unable to initialize inotify, falling back to polling: %s", + strerror(errno)); + } else { + /* We need to watch for attribute changes in addition to + * creation, because when a device is first created, it has + * permissions that we can't read. When udev chmods it to + * something that we maybe *can* read, we'll get an + * IN_ATTRIB event to tell us. */ + if (inotify_add_watch(inotify_fd, "/dev/input", + IN_CREATE | IN_DELETE | IN_MOVE | IN_ATTRIB) < 0) { + close(inotify_fd); + inotify_fd = -1; + SDL_LogWarn(SDL_LOG_CATEGORY_INPUT, + "Unable to add inotify watch, falling back to polling: %s", + strerror(errno)); + } + } +#endif // HAVE_INOTIFY + } + + return true; +} + +static int LINUX_JoystickGetCount(void) +{ + SDL_AssertJoysticksLocked(); + + return numjoysticks; +} + +static SDL_joylist_item *GetJoystickByDevIndex(int device_index) +{ + SDL_joylist_item *item; + + SDL_AssertJoysticksLocked(); + + if ((device_index < 0) || (device_index >= numjoysticks)) { + return NULL; + } + + item = SDL_joylist; + while (device_index > 0) { + SDL_assert(item != NULL); + device_index--; + item = item->next; + } + + return item; +} + +static const char *LINUX_JoystickGetDeviceName(int device_index) +{ + return GetJoystickByDevIndex(device_index)->name; +} + +static const char *LINUX_JoystickGetDevicePath(int device_index) +{ + return GetJoystickByDevIndex(device_index)->path; +} + +static int LINUX_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index) +{ + return GetJoystickByDevIndex(device_index)->steam_virtual_gamepad_slot; +} + +static int LINUX_JoystickGetDevicePlayerIndex(int device_index) +{ + return -1; +} + +static void LINUX_JoystickSetDevicePlayerIndex(int device_index, int player_index) +{ +} + +static SDL_GUID LINUX_JoystickGetDeviceGUID(int device_index) +{ + return GetJoystickByDevIndex(device_index)->guid; +} + +// Function to perform the mapping from device index to the instance id for this index +static SDL_JoystickID LINUX_JoystickGetDeviceInstanceID(int device_index) +{ + return GetJoystickByDevIndex(device_index)->device_instance; +} + +static bool allocate_balldata(SDL_Joystick *joystick) +{ + joystick->hwdata->balls = + (struct hwdata_ball *)SDL_calloc(joystick->nballs, sizeof(struct hwdata_ball)); + if (joystick->hwdata->balls == NULL) { + return false; + } + return true; +} + +static bool allocate_hatdata(SDL_Joystick *joystick) +{ + int i; + + SDL_AssertJoysticksLocked(); + + joystick->hwdata->hats = + (struct hwdata_hat *)SDL_malloc(joystick->nhats * + sizeof(struct hwdata_hat)); + if (!joystick->hwdata->hats) { + return false; + } + for (i = 0; i < joystick->nhats; ++i) { + joystick->hwdata->hats[i].axis[0] = 1; + joystick->hwdata->hats[i].axis[1] = 1; + } + return true; +} + +static bool GuessIfAxesAreDigitalHat(struct input_absinfo *absinfo_x, struct input_absinfo *absinfo_y) +{ + /* A "hat" is assumed to be a digital input with at most 9 possible states + * (3 per axis: negative/zero/positive), as opposed to a true "axis" which + * can report a continuous range of possible values. Unfortunately the Linux + * joystick interface makes no distinction between digital hat axes and any + * other continuous analog axis, so we have to guess. */ + + // If both axes are missing, they're not anything. + if (!absinfo_x && !absinfo_y) { + return false; + } + + // If the hint says so, treat all hats as digital. + if (SDL_GetHintBoolean(SDL_HINT_JOYSTICK_LINUX_DIGITAL_HATS, false)) { + return true; + } + + // If both axes have ranges constrained between -1 and 1, they're definitely digital. + if ((!absinfo_x || (absinfo_x->minimum == -1 && absinfo_x->maximum == 1)) && (!absinfo_y || (absinfo_y->minimum == -1 && absinfo_y->maximum == 1))) { + return true; + } + + // If both axes lack fuzz, flat, and resolution values, they're probably digital. + if ((!absinfo_x || (!absinfo_x->fuzz && !absinfo_x->flat && !absinfo_x->resolution)) && (!absinfo_y || (!absinfo_y->fuzz && !absinfo_y->flat && !absinfo_y->resolution))) { + return true; + } + + // Otherwise, treat them as analog. + return false; +} + +static void ConfigJoystick(SDL_Joystick *joystick, int fd, int fd_sensor) +{ + int i, t; + unsigned long keybit[NBITS(KEY_MAX)] = { 0 }; + unsigned long absbit[NBITS(ABS_MAX)] = { 0 }; + unsigned long relbit[NBITS(REL_MAX)] = { 0 }; + unsigned long ffbit[NBITS(FF_MAX)] = { 0 }; + Uint8 key_pam_size, abs_pam_size; + bool use_deadzones = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_LINUX_DEADZONES, false); + bool use_hat_deadzones = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_LINUX_HAT_DEADZONES, true); + + SDL_AssertJoysticksLocked(); + + // See if this device uses the new unified event API + if ((ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) >= 0) && + (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) >= 0) && + (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relbit)), relbit) >= 0)) { + + // Get the number of buttons, axes, and other thingamajigs + for (i = BTN_JOYSTICK; i < KEY_MAX; ++i) { + if (test_bit(i, keybit)) { +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick has button: 0x%x", i); +#endif + joystick->hwdata->key_map[i] = joystick->nbuttons; + joystick->hwdata->has_key[i] = true; + ++joystick->nbuttons; + } + } + for (i = 0; i < BTN_JOYSTICK; ++i) { + if (test_bit(i, keybit)) { +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick has button: 0x%x", i); +#endif + joystick->hwdata->key_map[i] = joystick->nbuttons; + joystick->hwdata->has_key[i] = true; + ++joystick->nbuttons; + } + } + for (i = ABS_HAT0X; i <= ABS_HAT3Y; i += 2) { + int hat_x = -1; + int hat_y = -1; + struct input_absinfo absinfo_x; + struct input_absinfo absinfo_y; + if (test_bit(i, absbit)) { + hat_x = ioctl(fd, EVIOCGABS(i), &absinfo_x); + } + if (test_bit(i + 1, absbit)) { + hat_y = ioctl(fd, EVIOCGABS(i + 1), &absinfo_y); + } + if (GuessIfAxesAreDigitalHat((hat_x < 0 ? (void *)0 : &absinfo_x), + (hat_y < 0 ? (void *)0 : &absinfo_y))) { + const int hat_index = (i - ABS_HAT0X) / 2; + struct hat_axis_correct *correct = &joystick->hwdata->hat_correct[hat_index]; +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick has digital hat: #%d", hat_index); + if (hat_x >= 0) { + SDL_Log("X Values = { val:%d, min:%d, max:%d, fuzz:%d, flat:%d, res:%d }", + absinfo_x.value, absinfo_x.minimum, absinfo_x.maximum, + absinfo_x.fuzz, absinfo_x.flat, absinfo_x.resolution); + } + if (hat_y >= 0) { + SDL_Log("Y Values = { val:%d, min:%d, max:%d, fuzz:%d, flat:%d, res:%d }", + absinfo_y.value, absinfo_y.minimum, absinfo_y.maximum, + absinfo_y.fuzz, absinfo_y.flat, absinfo_y.resolution); + } +#endif // DEBUG_INPUT_EVENTS + joystick->hwdata->hats_indices[hat_index] = joystick->nhats; + joystick->hwdata->has_hat[hat_index] = true; + correct->use_deadzones = use_hat_deadzones; + correct->minimum[0] = (hat_x < 0) ? -1 : absinfo_x.minimum; + correct->maximum[0] = (hat_x < 0) ? 1 : absinfo_x.maximum; + correct->minimum[1] = (hat_y < 0) ? -1 : absinfo_y.minimum; + correct->maximum[1] = (hat_y < 0) ? 1 : absinfo_y.maximum; + ++joystick->nhats; + } + } + for (i = 0; i < ABS_MAX; ++i) { + // Skip digital hats + if (i >= ABS_HAT0X && i <= ABS_HAT3Y && joystick->hwdata->has_hat[(i - ABS_HAT0X) / 2]) { + continue; + } + if (test_bit(i, absbit)) { + struct input_absinfo absinfo; + struct axis_correct *correct = &joystick->hwdata->abs_correct[i]; + + if (ioctl(fd, EVIOCGABS(i), &absinfo) < 0) { + continue; + } +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick has absolute axis: 0x%.2x", i); + SDL_Log("Values = { val:%d, min:%d, max:%d, fuzz:%d, flat:%d, res:%d }", + absinfo.value, absinfo.minimum, absinfo.maximum, + absinfo.fuzz, absinfo.flat, absinfo.resolution); +#endif // DEBUG_INPUT_EVENTS + joystick->hwdata->abs_map[i] = joystick->naxes; + joystick->hwdata->has_abs[i] = true; + + correct->minimum = absinfo.minimum; + correct->maximum = absinfo.maximum; + if (correct->minimum != correct->maximum) { + if (use_deadzones) { + correct->use_deadzones = true; + correct->coef[0] = (absinfo.maximum + absinfo.minimum) - 2 * absinfo.flat; + correct->coef[1] = (absinfo.maximum + absinfo.minimum) + 2 * absinfo.flat; + t = ((absinfo.maximum - absinfo.minimum) - 4 * absinfo.flat); + if (t != 0) { + correct->coef[2] = (1 << 28) / t; + } else { + correct->coef[2] = 0; + } + } else { + float value_range = (correct->maximum - correct->minimum); + float output_range = (SDL_JOYSTICK_AXIS_MAX - SDL_JOYSTICK_AXIS_MIN); + + correct->scale = (output_range / value_range); + } + } + ++joystick->naxes; + } + } + if (test_bit(REL_X, relbit) || test_bit(REL_Y, relbit)) { + ++joystick->nballs; + } + + } else if ((ioctl(fd, JSIOCGBUTTONS, &key_pam_size, sizeof(key_pam_size)) >= 0) && + (ioctl(fd, JSIOCGAXES, &abs_pam_size, sizeof(abs_pam_size)) >= 0)) { + size_t len; + + joystick->hwdata->classic = true; + + len = (KEY_MAX - BTN_MISC + 1) * sizeof(*joystick->hwdata->key_pam); + joystick->hwdata->key_pam = (Uint16 *)SDL_calloc(1, len); + if (joystick->hwdata->key_pam) { + if (ioctl(fd, JSIOCGBTNMAP, joystick->hwdata->key_pam, len) < 0) { + SDL_free(joystick->hwdata->key_pam); + joystick->hwdata->key_pam = NULL; + key_pam_size = 0; + } + } else { + key_pam_size = 0; + } + for (i = 0; i < key_pam_size; ++i) { + Uint16 code = joystick->hwdata->key_pam[i]; +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick has button: 0x%x", code); +#endif + joystick->hwdata->key_map[code] = joystick->nbuttons; + joystick->hwdata->has_key[code] = true; + ++joystick->nbuttons; + } + + len = ABS_CNT * sizeof(*joystick->hwdata->abs_pam); + joystick->hwdata->abs_pam = (Uint8 *)SDL_calloc(1, len); + if (joystick->hwdata->abs_pam) { + if (ioctl(fd, JSIOCGAXMAP, joystick->hwdata->abs_pam, len) < 0) { + SDL_free(joystick->hwdata->abs_pam); + joystick->hwdata->abs_pam = NULL; + abs_pam_size = 0; + } + } else { + abs_pam_size = 0; + } + for (i = 0; i < abs_pam_size; ++i) { + Uint8 code = joystick->hwdata->abs_pam[i]; + + // TODO: is there any way to detect analog hats in advance via this API? + if (code >= ABS_HAT0X && code <= ABS_HAT3Y) { + int hat_index = (code - ABS_HAT0X) / 2; + if (!joystick->hwdata->has_hat[hat_index]) { +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick has digital hat: #%d", hat_index); +#endif + joystick->hwdata->hats_indices[hat_index] = joystick->nhats++; + joystick->hwdata->has_hat[hat_index] = true; + joystick->hwdata->hat_correct[hat_index].minimum[0] = -1; + joystick->hwdata->hat_correct[hat_index].maximum[0] = 1; + joystick->hwdata->hat_correct[hat_index].minimum[1] = -1; + joystick->hwdata->hat_correct[hat_index].maximum[1] = 1; + } + } else { +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick has absolute axis: 0x%.2x", code); +#endif + joystick->hwdata->abs_map[code] = joystick->naxes; + joystick->hwdata->has_abs[code] = true; + ++joystick->naxes; + } + } + } + + // Sensors are only available through the new unified event API + if (fd_sensor >= 0 && (ioctl(fd_sensor, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) >= 0)) { + if (test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit) && test_bit(ABS_Z, absbit)) { + joystick->hwdata->has_accelerometer = true; + for (i = 0; i < 3; ++i) { + struct input_absinfo absinfo; + if (ioctl(fd_sensor, EVIOCGABS(ABS_X + i), &absinfo) < 0) { + joystick->hwdata->has_accelerometer = false; + break; // do not report an accelerometer if we can't read all axes + } + joystick->hwdata->accelerometer_scale[i] = absinfo.resolution; +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick has accelerometer axis: 0x%.2x", ABS_X + i); + SDL_Log("Values = { val:%d, min:%d, max:%d, fuzz:%d, flat:%d, res:%d }", + absinfo.value, absinfo.minimum, absinfo.maximum, + absinfo.fuzz, absinfo.flat, absinfo.resolution); +#endif // DEBUG_INPUT_EVENTS + } + } + + if (test_bit(ABS_RX, absbit) && test_bit(ABS_RY, absbit) && test_bit(ABS_RZ, absbit)) { + joystick->hwdata->has_gyro = true; + for (i = 0; i < 3; ++i) { + struct input_absinfo absinfo; + if (ioctl(fd_sensor, EVIOCGABS(ABS_RX + i), &absinfo) < 0) { + joystick->hwdata->has_gyro = false; + break; // do not report a gyro if we can't read all axes + } + joystick->hwdata->gyro_scale[i] = absinfo.resolution; +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick has gyro axis: 0x%.2x", ABS_RX + i); + SDL_Log("Values = { val:%d, min:%d, max:%d, fuzz:%d, flat:%d, res:%d }", + absinfo.value, absinfo.minimum, absinfo.maximum, + absinfo.fuzz, absinfo.flat, absinfo.resolution); +#endif // DEBUG_INPUT_EVENTS + } + } + } + + // Allocate data to keep track of these thingamajigs + if (joystick->nballs > 0) { + if (!allocate_balldata(joystick)) { + joystick->nballs = 0; + } + } + if (joystick->nhats > 0) { + if (!allocate_hatdata(joystick)) { + joystick->nhats = 0; + } + } + + if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) >= 0) { + if (test_bit(FF_RUMBLE, ffbit)) { + joystick->hwdata->ff_rumble = true; + } + if (test_bit(FF_SINE, ffbit)) { + joystick->hwdata->ff_sine = true; + } + } +} + +/* This is used to do the heavy lifting for LINUX_JoystickOpen and + also LINUX_JoystickGetGamepadMapping, so we can query the hardware + without adding an opened SDL_Joystick object to the system. + This expects `joystick->hwdata` to be allocated and will not free it + on error. Returns -1 on error, 0 on success. */ +static bool PrepareJoystickHwdata(SDL_Joystick *joystick, SDL_joylist_item *item, SDL_sensorlist_item *item_sensor) +{ + SDL_AssertJoysticksLocked(); + + joystick->hwdata->item = item; + joystick->hwdata->item_sensor = item_sensor; + joystick->hwdata->guid = item->guid; + joystick->hwdata->effect.id = -1; + SDL_memset(joystick->hwdata->key_map, 0xFF, sizeof(joystick->hwdata->key_map)); + SDL_memset(joystick->hwdata->abs_map, 0xFF, sizeof(joystick->hwdata->abs_map)); + + int fd = -1, fd_sensor = -1; + // Try read-write first, so we can do rumble + fd = open(item->path, O_RDWR | O_CLOEXEC, 0); + if (fd < 0) { + // Try read-only again, at least we'll get events in this case + fd = open(item->path, O_RDONLY | O_CLOEXEC, 0); + } + if (fd < 0) { + return SDL_SetError("Unable to open %s", item->path); + } + // If opening sensor fail, continue with buttons and axes only + if (item_sensor) { + fd_sensor = open(item_sensor->path, O_RDONLY | O_CLOEXEC, 0); + } + + joystick->hwdata->fd = fd; + joystick->hwdata->fd_sensor = fd_sensor; + joystick->hwdata->fname = SDL_strdup(item->path); + if (!joystick->hwdata->fname) { + close(fd); + if (fd_sensor >= 0) { + close(fd_sensor); + } + return false; + } + + // Set the joystick to non-blocking read mode + fcntl(fd, F_SETFL, O_NONBLOCK); + if (fd_sensor >= 0) { + fcntl(fd_sensor, F_SETFL, O_NONBLOCK); + } + + // Get the number of buttons and axes on the joystick + ConfigJoystick(joystick, fd, fd_sensor); + return true; +} + +static SDL_sensorlist_item *GetSensor(SDL_joylist_item *item) +{ + SDL_sensorlist_item *item_sensor; + char uniq_item[128]; + int fd_item = -1; + + SDL_AssertJoysticksLocked(); + + if (!item || !SDL_sensorlist) { + return NULL; + } + + SDL_memset(uniq_item, 0, sizeof(uniq_item)); + fd_item = open(item->path, O_RDONLY | O_CLOEXEC, 0); + if (fd_item < 0) { + return NULL; + } + if (ioctl(fd_item, EVIOCGUNIQ(sizeof(uniq_item) - 1), &uniq_item) < 0) { + close(fd_item); + return NULL; + } + close(fd_item); +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick UNIQ: %s", uniq_item); +#endif // DEBUG_INPUT_EVENTS + + for (item_sensor = SDL_sensorlist; item_sensor; item_sensor = item_sensor->next) { + char uniq_sensor[128]; + int fd_sensor = -1; + if (item_sensor->hwdata) { + // already associated with another joystick + continue; + } + + SDL_memset(uniq_sensor, 0, sizeof(uniq_sensor)); + fd_sensor = open(item_sensor->path, O_RDONLY | O_CLOEXEC, 0); + if (fd_sensor < 0) { + continue; + } + if (ioctl(fd_sensor, EVIOCGUNIQ(sizeof(uniq_sensor) - 1), &uniq_sensor) < 0) { + close(fd_sensor); + continue; + } + close(fd_sensor); +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Sensor UNIQ: %s", uniq_sensor); +#endif // DEBUG_INPUT_EVENTS + + if (SDL_strcmp(uniq_item, uniq_sensor) == 0) { + return item_sensor; + } + } + return NULL; +} + +static bool LINUX_JoystickOpen(SDL_Joystick *joystick, int device_index) +{ + SDL_joylist_item *item; + SDL_sensorlist_item *item_sensor; + + SDL_AssertJoysticksLocked(); + + item = GetJoystickByDevIndex(device_index); + if (!item) { + return SDL_SetError("No such device"); + } + + joystick->hwdata = (struct joystick_hwdata *) + SDL_calloc(1, sizeof(*joystick->hwdata)); + if (!joystick->hwdata) { + return false; + } + + item_sensor = GetSensor(item); + if (!PrepareJoystickHwdata(joystick, item, item_sensor)) { + SDL_free(joystick->hwdata); + joystick->hwdata = NULL; + return false; // SDL_SetError will already have been called + } + + SDL_assert(item->hwdata == NULL); + SDL_assert(!item_sensor || item_sensor->hwdata == NULL); + item->hwdata = joystick->hwdata; + if (item_sensor) { + item_sensor->hwdata = joystick->hwdata; + } + + // mark joystick as fresh and ready + joystick->hwdata->fresh = true; + + if (joystick->hwdata->has_gyro) { + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, 0.0f); + } + if (joystick->hwdata->has_accelerometer) { + SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 0.0f); + } + if (joystick->hwdata->fd_sensor >= 0) { + // Don't keep fd_sensor opened while sensor is disabled + close(joystick->hwdata->fd_sensor); + joystick->hwdata->fd_sensor = -1; + } + + if (joystick->hwdata->ff_rumble || joystick->hwdata->ff_sine) { + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true); + } + return true; +} + +static bool LINUX_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + struct input_event event; + + SDL_AssertJoysticksLocked(); + + if (joystick->hwdata->ff_rumble) { + struct ff_effect *effect = &joystick->hwdata->effect; + + effect->type = FF_RUMBLE; + effect->replay.length = SDL_MAX_RUMBLE_DURATION_MS; + effect->u.rumble.strong_magnitude = low_frequency_rumble; + effect->u.rumble.weak_magnitude = high_frequency_rumble; + } else if (joystick->hwdata->ff_sine) { + // Scale and average the two rumble strengths + Sint16 magnitude = (Sint16)(((low_frequency_rumble / 2) + (high_frequency_rumble / 2)) / 2); + struct ff_effect *effect = &joystick->hwdata->effect; + + effect->type = FF_PERIODIC; + effect->replay.length = SDL_MAX_RUMBLE_DURATION_MS; + effect->u.periodic.waveform = FF_SINE; + effect->u.periodic.magnitude = magnitude; + } else { + return SDL_Unsupported(); + } + + if (ioctl(joystick->hwdata->fd, EVIOCSFF, &joystick->hwdata->effect) < 0) { + // The kernel may have lost this effect, try to allocate a new one + joystick->hwdata->effect.id = -1; + if (ioctl(joystick->hwdata->fd, EVIOCSFF, &joystick->hwdata->effect) < 0) { + return SDL_SetError("Couldn't update rumble effect: %s", strerror(errno)); + } + } + + event.type = EV_FF; + event.code = joystick->hwdata->effect.id; + event.value = 1; + if (write(joystick->hwdata->fd, &event, sizeof(event)) < 0) { + return SDL_SetError("Couldn't start rumble effect: %s", strerror(errno)); + } + return true; +} + +static bool LINUX_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static bool LINUX_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool LINUX_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool LINUX_JoystickSetSensorsEnabled(SDL_Joystick *joystick, bool enabled) +{ + SDL_AssertJoysticksLocked(); + + if (!joystick->hwdata->has_accelerometer && !joystick->hwdata->has_gyro) { + return SDL_Unsupported(); + } + if (enabled == joystick->hwdata->report_sensor) { + return true; + } + + if (enabled) { + if (!joystick->hwdata->item_sensor) { + return SDL_SetError("Sensors unplugged."); + } + joystick->hwdata->fd_sensor = open(joystick->hwdata->item_sensor->path, O_RDONLY | O_CLOEXEC, 0); + if (joystick->hwdata->fd_sensor < 0) { + return SDL_SetError("Couldn't open sensor file %s.", joystick->hwdata->item_sensor->path); + } + fcntl(joystick->hwdata->fd_sensor, F_SETFL, O_NONBLOCK); + } else { + SDL_assert(joystick->hwdata->fd_sensor >= 0); + close(joystick->hwdata->fd_sensor); + joystick->hwdata->fd_sensor = -1; + } + + joystick->hwdata->report_sensor = enabled; + return true; +} + +static void HandleHat(Uint64 timestamp, SDL_Joystick *stick, int hatidx, int axis, int value) +{ + int hatnum; + struct hwdata_hat *the_hat; + struct hat_axis_correct *correct; + const Uint8 position_map[3][3] = { + { SDL_HAT_LEFTUP, SDL_HAT_UP, SDL_HAT_RIGHTUP }, + { SDL_HAT_LEFT, SDL_HAT_CENTERED, SDL_HAT_RIGHT }, + { SDL_HAT_LEFTDOWN, SDL_HAT_DOWN, SDL_HAT_RIGHTDOWN } + }; + + SDL_AssertJoysticksLocked(); + + hatnum = stick->hwdata->hats_indices[hatidx]; + the_hat = &stick->hwdata->hats[hatnum]; + correct = &stick->hwdata->hat_correct[hatidx]; + /* Hopefully we detected any analog axes and left them as is rather than trying + * to use them as digital hats, but just in case, the deadzones here will + * prevent the slightest of twitches on an analog axis from registering as a hat + * movement. If the axes really are digital, this won't hurt since they should + * only ever be sending min, 0, or max anyway. */ + if (value < 0) { + if (value <= correct->minimum[axis]) { + correct->minimum[axis] = value; + value = 0; + } else if (!correct->use_deadzones || value < correct->minimum[axis] / 3) { + value = 0; + } else { + value = 1; + } + } else if (value > 0) { + if (value >= correct->maximum[axis]) { + correct->maximum[axis] = value; + value = 2; + } else if (!correct->use_deadzones || value > correct->maximum[axis] / 3) { + value = 2; + } else { + value = 1; + } + } else { // value == 0 + value = 1; + } + if (value != the_hat->axis[axis]) { + the_hat->axis[axis] = value; + SDL_SendJoystickHat(timestamp, stick, hatnum, + position_map[the_hat->axis[1]][the_hat->axis[0]]); + } +} + +static void HandleBall(SDL_Joystick *stick, Uint8 ball, int axis, int value) +{ + stick->hwdata->balls[ball].axis[axis] += value; +} + +static int AxisCorrect(SDL_Joystick *joystick, int which, int value) +{ + struct axis_correct *correct; + + SDL_AssertJoysticksLocked(); + + correct = &joystick->hwdata->abs_correct[which]; + if (correct->minimum != correct->maximum) { + if (correct->use_deadzones) { + value *= 2; + if (value > correct->coef[0]) { + if (value < correct->coef[1]) { + return 0; + } + value -= correct->coef[1]; + } else { + value -= correct->coef[0]; + } + value *= correct->coef[2]; + value >>= 13; + } else { + value = (int)SDL_floorf((value - correct->minimum) * correct->scale + SDL_JOYSTICK_AXIS_MIN + 0.5f); + } + } + + // Clamp and return + if (value < SDL_JOYSTICK_AXIS_MIN) { + return SDL_JOYSTICK_AXIS_MIN; + } + if (value > SDL_JOYSTICK_AXIS_MAX) { + return SDL_JOYSTICK_AXIS_MAX; + } + return value; +} + +static void PollAllValues(Uint64 timestamp, SDL_Joystick *joystick) +{ + struct input_absinfo absinfo; + unsigned long keyinfo[NBITS(KEY_MAX)]; + int i; + + SDL_AssertJoysticksLocked(); + + // Poll all axis + for (i = ABS_X; i < ABS_MAX; i++) { + // We don't need to test for digital hats here, they won't have has_abs[] set + if (joystick->hwdata->has_abs[i]) { + if (ioctl(joystick->hwdata->fd, EVIOCGABS(i), &absinfo) >= 0) { + absinfo.value = AxisCorrect(joystick, i, absinfo.value); + +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick : Re-read Axis %d (%d) val= %d", + joystick->hwdata->abs_map[i], i, absinfo.value); +#endif + SDL_SendJoystickAxis(timestamp, joystick, + joystick->hwdata->abs_map[i], + absinfo.value); + } + } + } + + // Poll all digital hats + for (i = ABS_HAT0X; i <= ABS_HAT3Y; i++) { + const int baseaxis = i - ABS_HAT0X; + const int hatidx = baseaxis / 2; + SDL_assert(hatidx < SDL_arraysize(joystick->hwdata->has_hat)); + // We don't need to test for analog axes here, they won't have has_hat[] set + if (joystick->hwdata->has_hat[hatidx]) { + if (ioctl(joystick->hwdata->fd, EVIOCGABS(i), &absinfo) >= 0) { + const int hataxis = baseaxis % 2; + HandleHat(timestamp, joystick, hatidx, hataxis, absinfo.value); + } + } + } + + // Poll all buttons + SDL_zeroa(keyinfo); + if (ioctl(joystick->hwdata->fd, EVIOCGKEY(sizeof(keyinfo)), keyinfo) >= 0) { + for (i = 0; i < KEY_MAX; i++) { + if (joystick->hwdata->has_key[i]) { + bool down = test_bit(i, keyinfo); +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick : Re-read Button %d (%d) val= %d", + joystick->hwdata->key_map[i], i, down); +#endif + SDL_SendJoystickButton(timestamp, joystick, + joystick->hwdata->key_map[i], down); + } + } + } + + // Joyballs are relative input, so there's no poll state. Events only! +} + +static void PollAllSensors(Uint64 timestamp, SDL_Joystick *joystick) +{ + struct input_absinfo absinfo; + int i; + + SDL_AssertJoysticksLocked(); + + SDL_assert(joystick->hwdata->fd_sensor >= 0); + + if (joystick->hwdata->has_gyro) { + float data[3] = {0.0f, 0.0f, 0.0f}; + for (i = 0; i < 3; i++) { + if (ioctl(joystick->hwdata->fd_sensor, EVIOCGABS(ABS_RX + i), &absinfo) >= 0) { + data[i] = absinfo.value * (SDL_PI_F / 180.f) / joystick->hwdata->gyro_scale[i]; +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick : Re-read Gyro (axis %d) val= %f", i, data[i]); +#endif + } + } + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, SDL_US_TO_NS(joystick->hwdata->sensor_tick), data, 3); + } + if (joystick->hwdata->has_accelerometer) { + float data[3] = {0.0f, 0.0f, 0.0f}; + for (i = 0; i < 3; i++) { + if (ioctl(joystick->hwdata->fd_sensor, EVIOCGABS(ABS_X + i), &absinfo) >= 0) { + data[i] = absinfo.value * SDL_STANDARD_GRAVITY / joystick->hwdata->accelerometer_scale[i]; +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Joystick : Re-read Accelerometer (axis %d) val= %f", i, data[i]); +#endif + } + } + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, SDL_US_TO_NS(joystick->hwdata->sensor_tick), data, 3); + } +} + +static void HandleInputEvents(SDL_Joystick *joystick) +{ + struct input_event events[32]; + int i, len, code, hat_index; + + SDL_AssertJoysticksLocked(); + + if (joystick->hwdata->fresh) { + Uint64 ticks = SDL_GetTicksNS(); + PollAllValues(ticks, joystick); + if (joystick->hwdata->report_sensor) { + PollAllSensors(ticks, joystick); + } + joystick->hwdata->fresh = false; + } + + errno = 0; + + while ((len = read(joystick->hwdata->fd, events, sizeof(events))) > 0) { + len /= sizeof(events[0]); + for (i = 0; i < len; ++i) { + struct input_event *event = &events[i]; + + code = event->code; + + /* If the kernel sent a SYN_DROPPED, we are supposed to ignore the + rest of the packet (the end of it signified by a SYN_REPORT) */ + if (joystick->hwdata->recovering_from_dropped && + ((event->type != EV_SYN) || (code != SYN_REPORT))) { + continue; + } + + switch (event->type) { + case EV_KEY: +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Key 0x%.2x %s", code, event->value ? "PRESSED" : "RELEASED"); +#endif + SDL_SendJoystickButton(SDL_EVDEV_GetEventTimestamp(event), joystick, + joystick->hwdata->key_map[code], + (event->value != 0)); + break; + case EV_ABS: + switch (code) { + case ABS_HAT0X: + case ABS_HAT0Y: + case ABS_HAT1X: + case ABS_HAT1Y: + case ABS_HAT2X: + case ABS_HAT2Y: + case ABS_HAT3X: + case ABS_HAT3Y: + hat_index = (code - ABS_HAT0X) / 2; + if (joystick->hwdata->has_hat[hat_index]) { +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Axis 0x%.2x = %d", code, event->value); +#endif + HandleHat(SDL_EVDEV_GetEventTimestamp(event), joystick, hat_index, code % 2, event->value); + break; + } + SDL_FALLTHROUGH; + default: +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Axis 0x%.2x = %d", code, event->value); +#endif + event->value = AxisCorrect(joystick, code, event->value); + SDL_SendJoystickAxis(SDL_EVDEV_GetEventTimestamp(event), joystick, + joystick->hwdata->abs_map[code], + event->value); + break; + } + break; + case EV_REL: + switch (code) { + case REL_X: + case REL_Y: + code -= REL_X; + HandleBall(joystick, code / 2, code % 2, event->value); + break; + default: + break; + } + break; + case EV_SYN: + switch (code) { + case SYN_DROPPED: +#ifdef DEBUG_INPUT_EVENTS + SDL_Log("Event SYN_DROPPED detected"); +#endif + joystick->hwdata->recovering_from_dropped = true; + break; + case SYN_REPORT: + if (joystick->hwdata->recovering_from_dropped) { + joystick->hwdata->recovering_from_dropped = false; + PollAllValues(SDL_GetTicksNS(), joystick); // try to sync up to current state now + } + break; + default: + break; + } + break; + default: + break; + } + } + } + + if (errno == ENODEV) { + // We have to wait until the JoystickDetect callback to remove this + joystick->hwdata->gone = true; + errno = 0; + } + + if (joystick->hwdata->report_sensor) { + SDL_assert(joystick->hwdata->fd_sensor >= 0); + + while ((len = read(joystick->hwdata->fd_sensor, events, sizeof(events))) > 0) { + len /= sizeof(events[0]); + for (i = 0; i < len; ++i) { + unsigned int j; + struct input_event *event = &events[i]; + + code = event->code; + + /* If the kernel sent a SYN_DROPPED, we are supposed to ignore the + rest of the packet (the end of it signified by a SYN_REPORT) */ + if (joystick->hwdata->recovering_from_dropped_sensor && + ((event->type != EV_SYN) || (code != SYN_REPORT))) { + continue; + } + + switch (event->type) { + case EV_KEY: + SDL_assert(0); + break; + case EV_ABS: + switch (code) { + case ABS_X: + case ABS_Y: + case ABS_Z: + j = code - ABS_X; + joystick->hwdata->accel_data[j] = event->value * SDL_STANDARD_GRAVITY + / joystick->hwdata->accelerometer_scale[j]; + break; + case ABS_RX: + case ABS_RY: + case ABS_RZ: + j = code - ABS_RX; + joystick->hwdata->gyro_data[j] = event->value * (SDL_PI_F / 180.f) + / joystick->hwdata->gyro_scale[j]; + break; + } + break; + case EV_MSC: + if (code == MSC_TIMESTAMP) { + Sint32 tick = event->value; + Sint32 delta; + if (joystick->hwdata->last_tick < tick) { + delta = (tick - joystick->hwdata->last_tick); + } else { + delta = (SDL_MAX_SINT32 - joystick->hwdata->last_tick + tick + 1); + } + joystick->hwdata->sensor_tick += delta; + joystick->hwdata->last_tick = tick; + } + break; + case EV_SYN: + switch (code) { + case SYN_DROPPED: + #ifdef DEBUG_INPUT_EVENTS + SDL_Log("Event SYN_DROPPED detected"); + #endif + joystick->hwdata->recovering_from_dropped_sensor = true; + break; + case SYN_REPORT: + if (joystick->hwdata->recovering_from_dropped_sensor) { + joystick->hwdata->recovering_from_dropped_sensor = false; + PollAllSensors(SDL_GetTicksNS(), joystick); // try to sync up to current state now + } else { + Uint64 timestamp = SDL_EVDEV_GetEventTimestamp(event); + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, + SDL_US_TO_NS(joystick->hwdata->sensor_tick), + joystick->hwdata->gyro_data, 3); + SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, + SDL_US_TO_NS(joystick->hwdata->sensor_tick), + joystick->hwdata->accel_data, 3); + } + break; + default: + break; + } + break; + default: + break; + } + } + } + } + + if (errno == ENODEV) { + // We have to wait until the JoystickDetect callback to remove this + joystick->hwdata->sensor_gone = true; + } +} + +static void HandleClassicEvents(SDL_Joystick *joystick) +{ + struct js_event events[32]; + int i, len, code, hat_index; + Uint64 timestamp = SDL_GetTicksNS(); + + SDL_AssertJoysticksLocked(); + + joystick->hwdata->fresh = false; + while ((len = read(joystick->hwdata->fd, events, sizeof(events))) > 0) { + len /= sizeof(events[0]); + for (i = 0; i < len; ++i) { + switch (events[i].type) { + case JS_EVENT_BUTTON: + code = joystick->hwdata->key_pam[events[i].number]; + SDL_SendJoystickButton(timestamp, joystick, + joystick->hwdata->key_map[code], + (events[i].value != 0)); + break; + case JS_EVENT_AXIS: + code = joystick->hwdata->abs_pam[events[i].number]; + switch (code) { + case ABS_HAT0X: + case ABS_HAT0Y: + case ABS_HAT1X: + case ABS_HAT1Y: + case ABS_HAT2X: + case ABS_HAT2Y: + case ABS_HAT3X: + case ABS_HAT3Y: + hat_index = (code - ABS_HAT0X) / 2; + if (joystick->hwdata->has_hat[hat_index]) { + HandleHat(timestamp, joystick, hat_index, code % 2, events[i].value); + break; + } + SDL_FALLTHROUGH; + default: + SDL_SendJoystickAxis(timestamp, joystick, + joystick->hwdata->abs_map[code], + events[i].value); + break; + } + } + } + } +} + +static void LINUX_JoystickUpdate(SDL_Joystick *joystick) +{ + int i; + + SDL_AssertJoysticksLocked(); + + if (joystick->hwdata->classic) { + HandleClassicEvents(joystick); + } else { + HandleInputEvents(joystick); + } + + // Deliver ball motion updates + for (i = 0; i < joystick->nballs; ++i) { + int xrel, yrel; + + xrel = joystick->hwdata->balls[i].axis[0]; + yrel = joystick->hwdata->balls[i].axis[1]; + if (xrel || yrel) { + joystick->hwdata->balls[i].axis[0] = 0; + joystick->hwdata->balls[i].axis[1] = 0; + SDL_SendJoystickBall(0, joystick, (Uint8)i, xrel, yrel); + } + } +} + +// Function to close a joystick after use +static void LINUX_JoystickClose(SDL_Joystick *joystick) +{ + SDL_AssertJoysticksLocked(); + + if (joystick->hwdata) { + if (joystick->hwdata->effect.id >= 0) { + ioctl(joystick->hwdata->fd, EVIOCRMFF, joystick->hwdata->effect.id); + joystick->hwdata->effect.id = -1; + } + if (joystick->hwdata->fd >= 0) { + close(joystick->hwdata->fd); + } + if (joystick->hwdata->fd_sensor >= 0) { + close(joystick->hwdata->fd_sensor); + } + if (joystick->hwdata->item) { + joystick->hwdata->item->hwdata = NULL; + } + if (joystick->hwdata->item_sensor) { + joystick->hwdata->item_sensor->hwdata = NULL; + } + SDL_free(joystick->hwdata->key_pam); + SDL_free(joystick->hwdata->abs_pam); + SDL_free(joystick->hwdata->hats); + SDL_free(joystick->hwdata->balls); + SDL_free(joystick->hwdata->fname); + SDL_free(joystick->hwdata); + } +} + +// Function to perform any system-specific joystick related cleanup +static void LINUX_JoystickQuit(void) +{ + SDL_joylist_item *item = NULL; + SDL_joylist_item *next = NULL; + SDL_sensorlist_item *item_sensor = NULL; + SDL_sensorlist_item *next_sensor = NULL; + + SDL_AssertJoysticksLocked(); + + if (inotify_fd >= 0) { + close(inotify_fd); + inotify_fd = -1; + } + + for (item = SDL_joylist; item; item = next) { + next = item->next; + FreeJoylistItem(item); + } + for (item_sensor = SDL_sensorlist; item_sensor; item_sensor = next_sensor) { + next_sensor = item_sensor->next; + FreeSensorlistItem(item_sensor); + } + + SDL_joylist = SDL_joylist_tail = NULL; + SDL_sensorlist = NULL; + + numjoysticks = 0; + +#ifdef SDL_USE_LIBUDEV + if (enumeration_method == ENUMERATION_LIBUDEV) { + SDL_UDEV_DelCallback(joystick_udev_callback); + SDL_UDEV_Quit(); + } +#endif +} + +/* + This is based on the Linux Gamepad Specification + available at: https://www.kernel.org/doc/html/v4.15/input/gamepad.html + and the Android gamepad documentation, + https://developer.android.com/develop/ui/views/touch-and-input/game-controllers/controller-input + */ +static bool LINUX_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) +{ + SDL_Joystick *joystick; + SDL_joylist_item *item = GetJoystickByDevIndex(device_index); + enum { + MAPPED_TRIGGER_LEFT = 0x1, + MAPPED_TRIGGER_RIGHT = 0x2, + MAPPED_TRIGGER_BOTH = 0x3, + + MAPPED_DPAD_UP = 0x1, + MAPPED_DPAD_DOWN = 0x2, + MAPPED_DPAD_LEFT = 0x4, + MAPPED_DPAD_RIGHT = 0x8, + MAPPED_DPAD_ALL = 0xF, + }; + unsigned int mapped; + bool result = false; + + SDL_AssertJoysticksLocked(); + + if (item->checked_mapping) { + if (item->mapping) { + SDL_memcpy(out, item->mapping, sizeof(*out)); +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Prior mapping for device %d", device_index); +#endif + return true; + } else { + return false; + } + } + + /* We temporarily open the device to check how it's configured. Make + a fake SDL_Joystick object to do so. */ + joystick = (SDL_Joystick *)SDL_calloc(1, sizeof(*joystick)); + if (!joystick) { + return false; + } + SDL_memcpy(&joystick->guid, &item->guid, sizeof(item->guid)); + + joystick->hwdata = (struct joystick_hwdata *)SDL_calloc(1, sizeof(*joystick->hwdata)); + if (!joystick->hwdata) { + SDL_free(joystick); + return false; + } + SDL_SetObjectValid(joystick, SDL_OBJECT_TYPE_JOYSTICK, true); + + item->checked_mapping = true; + + if (!PrepareJoystickHwdata(joystick, item, NULL)) { + goto done; // SDL_SetError will already have been called + } + + // don't assign `item->hwdata` so it's not in any global state. + + // it is now safe to call LINUX_JoystickClose on this fake joystick. + + if (!joystick->hwdata->has_key[BTN_GAMEPAD]) { + // Not a gamepad according to the specs. + goto done; + } + + // We have a gamepad, start filling out the mappings + +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapping %s (VID/PID 0x%.4x/0x%.4x)", item->name, SDL_GetJoystickVendor(joystick), SDL_GetJoystickProduct(joystick)); +#endif + + if (joystick->hwdata->has_key[BTN_A]) { + out->a.kind = EMappingKind_Button; + out->a.target = joystick->hwdata->key_map[BTN_A]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped A to button %d (BTN_A)", out->a.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_B]) { + out->b.kind = EMappingKind_Button; + out->b.target = joystick->hwdata->key_map[BTN_B]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped B to button %d (BTN_B)", out->b.target); +#endif + } + + // Xbox controllers use BTN_X and BTN_Y, and PS4 controllers use BTN_WEST and BTN_NORTH + if (SDL_GetJoystickVendor(joystick) == USB_VENDOR_SONY) { + if (joystick->hwdata->has_key[BTN_WEST]) { + out->x.kind = EMappingKind_Button; + out->x.target = joystick->hwdata->key_map[BTN_WEST]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped X to button %d (BTN_WEST)", out->x.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_NORTH]) { + out->y.kind = EMappingKind_Button; + out->y.target = joystick->hwdata->key_map[BTN_NORTH]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped Y to button %d (BTN_NORTH)", out->y.target); +#endif + } + } else { + if (joystick->hwdata->has_key[BTN_X]) { + out->x.kind = EMappingKind_Button; + out->x.target = joystick->hwdata->key_map[BTN_X]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped X to button %d (BTN_X)", out->x.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_Y]) { + out->y.kind = EMappingKind_Button; + out->y.target = joystick->hwdata->key_map[BTN_Y]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped Y to button %d (BTN_Y)", out->y.target); +#endif + } + } + + if (joystick->hwdata->has_key[BTN_SELECT]) { + out->back.kind = EMappingKind_Button; + out->back.target = joystick->hwdata->key_map[BTN_SELECT]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped BACK to button %d (BTN_SELECT)", out->back.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_START]) { + out->start.kind = EMappingKind_Button; + out->start.target = joystick->hwdata->key_map[BTN_START]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped START to button %d (BTN_START)", out->start.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_THUMBL]) { + out->leftstick.kind = EMappingKind_Button; + out->leftstick.target = joystick->hwdata->key_map[BTN_THUMBL]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped LEFTSTICK to button %d (BTN_THUMBL)", out->leftstick.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_THUMBR]) { + out->rightstick.kind = EMappingKind_Button; + out->rightstick.target = joystick->hwdata->key_map[BTN_THUMBR]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped RIGHTSTICK to button %d (BTN_THUMBR)", out->rightstick.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_MODE]) { + out->guide.kind = EMappingKind_Button; + out->guide.target = joystick->hwdata->key_map[BTN_MODE]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped GUIDE to button %d (BTN_MODE)", out->guide.target); +#endif + } + + /* + According to the specs the D-Pad, the shoulder buttons and the triggers + can be digital, or analog, or both at the same time. + */ + + // Prefer digital shoulder buttons, but settle for digital or analog hat. + mapped = 0; + + if (joystick->hwdata->has_key[BTN_TL]) { + out->leftshoulder.kind = EMappingKind_Button; + out->leftshoulder.target = joystick->hwdata->key_map[BTN_TL]; + mapped |= 0x1; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped LEFTSHOULDER to button %d (BTN_TL)", out->leftshoulder.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_TR]) { + out->rightshoulder.kind = EMappingKind_Button; + out->rightshoulder.target = joystick->hwdata->key_map[BTN_TR]; + mapped |= 0x2; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped RIGHTSHOULDER to button %d (BTN_TR)", out->rightshoulder.target); +#endif + } + + if (mapped != 0x3 && joystick->hwdata->has_hat[1]) { + int hat = joystick->hwdata->hats_indices[1] << 4; + out->leftshoulder.kind = EMappingKind_Hat; + out->rightshoulder.kind = EMappingKind_Hat; + out->leftshoulder.target = hat | 0x4; + out->rightshoulder.target = hat | 0x2; + mapped |= 0x3; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped LEFT+RIGHTSHOULDER to hat 1 (ABS_HAT1X, ABS_HAT1Y)"); +#endif + } + + if (!(mapped & 0x1) && joystick->hwdata->has_abs[ABS_HAT1Y]) { + out->leftshoulder.kind = EMappingKind_Axis; + out->leftshoulder.target = joystick->hwdata->abs_map[ABS_HAT1Y]; + mapped |= 0x1; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped LEFTSHOULDER to axis %d (ABS_HAT1Y)", out->leftshoulder.target); +#endif + } + + if (!(mapped & 0x2) && joystick->hwdata->has_abs[ABS_HAT1X]) { + out->rightshoulder.kind = EMappingKind_Axis; + out->rightshoulder.target = joystick->hwdata->abs_map[ABS_HAT1X]; + mapped |= 0x2; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped RIGHTSHOULDER to axis %d (ABS_HAT1X)", out->rightshoulder.target); +#endif + } + + // Prefer analog triggers, but settle for digital hat or buttons. + mapped = 0; + + /* Unfortunately there are several conventions for how analog triggers + * are represented as absolute axes: + * + * - Linux Gamepad Specification: + * LT = ABS_HAT2Y, RT = ABS_HAT2X + * - Android (and therefore many Bluetooth controllers): + * LT = ABS_BRAKE, RT = ABS_GAS + * - De facto standard for older Xbox and Playstation controllers: + * LT = ABS_Z, RT = ABS_RZ + * + * We try each one in turn. */ + if (joystick->hwdata->has_abs[ABS_HAT2Y]) { + // Linux Gamepad Specification + out->lefttrigger.kind = EMappingKind_Axis; + out->lefttrigger.target = joystick->hwdata->abs_map[ABS_HAT2Y]; + mapped |= MAPPED_TRIGGER_LEFT; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped LEFTTRIGGER to axis %d (ABS_HAT2Y)", out->lefttrigger.target); +#endif + } else if (joystick->hwdata->has_abs[ABS_BRAKE]) { + // Android convention + out->lefttrigger.kind = EMappingKind_Axis; + out->lefttrigger.target = joystick->hwdata->abs_map[ABS_BRAKE]; + mapped |= MAPPED_TRIGGER_LEFT; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped LEFTTRIGGER to axis %d (ABS_BRAKE)", out->lefttrigger.target); +#endif + } else if (joystick->hwdata->has_abs[ABS_Z]) { + // De facto standard for Xbox 360 and Playstation gamepads + out->lefttrigger.kind = EMappingKind_Axis; + out->lefttrigger.target = joystick->hwdata->abs_map[ABS_Z]; + mapped |= MAPPED_TRIGGER_LEFT; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped LEFTTRIGGER to axis %d (ABS_Z)", out->lefttrigger.target); +#endif + } + + if (joystick->hwdata->has_abs[ABS_HAT2X]) { + // Linux Gamepad Specification + out->righttrigger.kind = EMappingKind_Axis; + out->righttrigger.target = joystick->hwdata->abs_map[ABS_HAT2X]; + mapped |= MAPPED_TRIGGER_RIGHT; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped RIGHTTRIGGER to axis %d (ABS_HAT2X)", out->righttrigger.target); +#endif + } else if (joystick->hwdata->has_abs[ABS_GAS]) { + // Android convention + out->righttrigger.kind = EMappingKind_Axis; + out->righttrigger.target = joystick->hwdata->abs_map[ABS_GAS]; + mapped |= MAPPED_TRIGGER_RIGHT; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped RIGHTTRIGGER to axis %d (ABS_GAS)", out->righttrigger.target); +#endif + } else if (joystick->hwdata->has_abs[ABS_RZ]) { + // De facto standard for Xbox 360 and Playstation gamepads + out->righttrigger.kind = EMappingKind_Axis; + out->righttrigger.target = joystick->hwdata->abs_map[ABS_RZ]; + mapped |= MAPPED_TRIGGER_RIGHT; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped RIGHTTRIGGER to axis %d (ABS_RZ)", out->righttrigger.target); +#endif + } + + if (mapped != MAPPED_TRIGGER_BOTH && joystick->hwdata->has_hat[2]) { + int hat = joystick->hwdata->hats_indices[2] << 4; + out->lefttrigger.kind = EMappingKind_Hat; + out->righttrigger.kind = EMappingKind_Hat; + out->lefttrigger.target = hat | 0x4; + out->righttrigger.target = hat | 0x2; + mapped |= MAPPED_TRIGGER_BOTH; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped LEFT+RIGHTTRIGGER to hat 2 (ABS_HAT2X, ABS_HAT2Y)"); +#endif + } + + if (!(mapped & MAPPED_TRIGGER_LEFT) && joystick->hwdata->has_key[BTN_TL2]) { + out->lefttrigger.kind = EMappingKind_Button; + out->lefttrigger.target = joystick->hwdata->key_map[BTN_TL2]; + mapped |= MAPPED_TRIGGER_LEFT; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped LEFTTRIGGER to button %d (BTN_TL2)", out->lefttrigger.target); +#endif + } + + if (!(mapped & MAPPED_TRIGGER_RIGHT) && joystick->hwdata->has_key[BTN_TR2]) { + out->righttrigger.kind = EMappingKind_Button; + out->righttrigger.target = joystick->hwdata->key_map[BTN_TR2]; + mapped |= MAPPED_TRIGGER_RIGHT; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped RIGHTTRIGGER to button %d (BTN_TR2)", out->righttrigger.target); +#endif + } + + // Prefer digital D-Pad buttons, but settle for digital or analog hat. + mapped = 0; + + if (joystick->hwdata->has_key[BTN_DPAD_UP]) { + out->dpup.kind = EMappingKind_Button; + out->dpup.target = joystick->hwdata->key_map[BTN_DPAD_UP]; + mapped |= MAPPED_DPAD_UP; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped DPUP to button %d (BTN_DPAD_UP)", out->dpup.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_DPAD_DOWN]) { + out->dpdown.kind = EMappingKind_Button; + out->dpdown.target = joystick->hwdata->key_map[BTN_DPAD_DOWN]; + mapped |= MAPPED_DPAD_DOWN; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped DPDOWN to button %d (BTN_DPAD_DOWN)", out->dpdown.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_DPAD_LEFT]) { + out->dpleft.kind = EMappingKind_Button; + out->dpleft.target = joystick->hwdata->key_map[BTN_DPAD_LEFT]; + mapped |= MAPPED_DPAD_LEFT; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped DPLEFT to button %d (BTN_DPAD_LEFT)", out->dpleft.target); +#endif + } + + if (joystick->hwdata->has_key[BTN_DPAD_RIGHT]) { + out->dpright.kind = EMappingKind_Button; + out->dpright.target = joystick->hwdata->key_map[BTN_DPAD_RIGHT]; + mapped |= MAPPED_DPAD_RIGHT; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped DPRIGHT to button %d (BTN_DPAD_RIGHT)", out->dpright.target); +#endif + } + + if (mapped != MAPPED_DPAD_ALL) { + if (joystick->hwdata->has_hat[0]) { + int hat = joystick->hwdata->hats_indices[0] << 4; + out->dpleft.kind = EMappingKind_Hat; + out->dpright.kind = EMappingKind_Hat; + out->dpup.kind = EMappingKind_Hat; + out->dpdown.kind = EMappingKind_Hat; + out->dpleft.target = hat | 0x8; + out->dpright.target = hat | 0x2; + out->dpup.target = hat | 0x1; + out->dpdown.target = hat | 0x4; + mapped |= MAPPED_DPAD_ALL; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped DPUP+DOWN+LEFT+RIGHT to hat 0 (ABS_HAT0X, ABS_HAT0Y)"); +#endif + } else if (joystick->hwdata->has_abs[ABS_HAT0X] && joystick->hwdata->has_abs[ABS_HAT0Y]) { + out->dpleft.kind = EMappingKind_Axis; + out->dpright.kind = EMappingKind_Axis; + out->dpup.kind = EMappingKind_Axis; + out->dpdown.kind = EMappingKind_Axis; + out->dpleft.target = joystick->hwdata->abs_map[ABS_HAT0X]; + out->dpright.target = joystick->hwdata->abs_map[ABS_HAT0X]; + out->dpup.target = joystick->hwdata->abs_map[ABS_HAT0Y]; + out->dpdown.target = joystick->hwdata->abs_map[ABS_HAT0Y]; + mapped |= MAPPED_DPAD_ALL; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped DPUP+DOWN to axis %d (ABS_HAT0Y)", out->dpup.target); + SDL_Log("Mapped DPLEFT+RIGHT to axis %d (ABS_HAT0X)", out->dpleft.target); +#endif + } + } + + if (joystick->hwdata->has_abs[ABS_X] && joystick->hwdata->has_abs[ABS_Y]) { + out->leftx.kind = EMappingKind_Axis; + out->lefty.kind = EMappingKind_Axis; + out->leftx.target = joystick->hwdata->abs_map[ABS_X]; + out->lefty.target = joystick->hwdata->abs_map[ABS_Y]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped LEFTX to axis %d (ABS_X)", out->leftx.target); + SDL_Log("Mapped LEFTY to axis %d (ABS_Y)", out->lefty.target); +#endif + } + + /* The Linux Gamepad Specification uses the RX and RY axes, + * originally intended to represent X and Y rotation, as a second + * joystick. This is common for USB gamepads, and also many Bluetooth + * gamepads, particularly older ones. + * + * The Android mapping convention used by many Bluetooth controllers + * instead uses the Z axis as a secondary X axis, and the RZ axis as + * a secondary Y axis. */ + if (joystick->hwdata->has_abs[ABS_RX] && joystick->hwdata->has_abs[ABS_RY]) { + // Linux Gamepad Specification, Xbox 360, Playstation etc. + out->rightx.kind = EMappingKind_Axis; + out->righty.kind = EMappingKind_Axis; + out->rightx.target = joystick->hwdata->abs_map[ABS_RX]; + out->righty.target = joystick->hwdata->abs_map[ABS_RY]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped RIGHTX to axis %d (ABS_RX)", out->rightx.target); + SDL_Log("Mapped RIGHTY to axis %d (ABS_RY)", out->righty.target); +#endif + } else if (joystick->hwdata->has_abs[ABS_Z] && joystick->hwdata->has_abs[ABS_RZ]) { + // Android convention + out->rightx.kind = EMappingKind_Axis; + out->righty.kind = EMappingKind_Axis; + out->rightx.target = joystick->hwdata->abs_map[ABS_Z]; + out->righty.target = joystick->hwdata->abs_map[ABS_RZ]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped RIGHTX to axis %d (ABS_Z)", out->rightx.target); + SDL_Log("Mapped RIGHTY to axis %d (ABS_RZ)", out->righty.target); +#endif + } + + if (SDL_GetJoystickVendor(joystick) == USB_VENDOR_MICROSOFT) { + // The Xbox Elite controllers have the paddles as BTN_TRIGGER_HAPPY5 - BTN_TRIGGER_HAPPY8 + if (joystick->hwdata->has_key[BTN_TRIGGER_HAPPY5] && + joystick->hwdata->has_key[BTN_TRIGGER_HAPPY6] && + joystick->hwdata->has_key[BTN_TRIGGER_HAPPY7] && + joystick->hwdata->has_key[BTN_TRIGGER_HAPPY8]) { + out->right_paddle1.kind = EMappingKind_Button; + out->right_paddle1.target = joystick->hwdata->key_map[BTN_TRIGGER_HAPPY5]; + out->left_paddle1.kind = EMappingKind_Button; + out->left_paddle1.target = joystick->hwdata->key_map[BTN_TRIGGER_HAPPY7]; + out->right_paddle2.kind = EMappingKind_Button; + out->right_paddle2.target = joystick->hwdata->key_map[BTN_TRIGGER_HAPPY6]; + out->left_paddle2.kind = EMappingKind_Button; + out->left_paddle2.target = joystick->hwdata->key_map[BTN_TRIGGER_HAPPY8]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped RIGHT_PADDLE1 to button %d (BTN_TRIGGER_HAPPY5)", out->right_paddle1.target); + SDL_Log("Mapped LEFT_PADDLE1 to button %d (BTN_TRIGGER_HAPPY7)", out->left_paddle1.target); + SDL_Log("Mapped RIGHT_PADDLE2 to button %d (BTN_TRIGGER_HAPPY6)", out->right_paddle2.target); + SDL_Log("Mapped LEFT_PADDLE2 to button %d (BTN_TRIGGER_HAPPY8)", out->left_paddle2.target); +#endif + } + + // The Xbox Series X controllers have the Share button as KEY_RECORD + if (joystick->hwdata->has_key[KEY_RECORD]) { + out->misc1.kind = EMappingKind_Button; + out->misc1.target = joystick->hwdata->key_map[KEY_RECORD]; +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Mapped MISC1 to button %d (KEY_RECORD)", out->misc1.target); +#endif + } + } + + // Cache the mapping for later + item->mapping = (SDL_GamepadMapping *)SDL_malloc(sizeof(*item->mapping)); + if (item->mapping) { + SDL_memcpy(item->mapping, out, sizeof(*out)); + } +#ifdef DEBUG_GAMEPAD_MAPPING + SDL_Log("Generated mapping for device %d", device_index); +#endif + result = true; + +done: + LINUX_JoystickClose(joystick); + SDL_SetObjectValid(joystick, SDL_OBJECT_TYPE_JOYSTICK, false); + SDL_free(joystick); + + return result; +} + +SDL_JoystickDriver SDL_LINUX_JoystickDriver = { + LINUX_JoystickInit, + LINUX_JoystickGetCount, + LINUX_JoystickDetect, + LINUX_JoystickIsDevicePresent, + LINUX_JoystickGetDeviceName, + LINUX_JoystickGetDevicePath, + LINUX_JoystickGetDeviceSteamVirtualGamepadSlot, + LINUX_JoystickGetDevicePlayerIndex, + LINUX_JoystickSetDevicePlayerIndex, + LINUX_JoystickGetDeviceGUID, + LINUX_JoystickGetDeviceInstanceID, + LINUX_JoystickOpen, + LINUX_JoystickRumble, + LINUX_JoystickRumbleTriggers, + LINUX_JoystickSetLED, + LINUX_JoystickSendEffect, + LINUX_JoystickSetSensorsEnabled, + LINUX_JoystickUpdate, + LINUX_JoystickClose, + LINUX_JoystickQuit, + LINUX_JoystickGetGamepadMapping +}; + +#endif // SDL_JOYSTICK_LINUX diff --git a/thirdparty/sdl/joystick/linux/SDL_sysjoystick_c.h b/thirdparty/sdl/joystick/linux/SDL_sysjoystick_c.h new file mode 100644 index 00000000000..ae5384f1d41 --- /dev/null +++ b/thirdparty/sdl/joystick/linux/SDL_sysjoystick_c.h @@ -0,0 +1,117 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_sysjoystick_c_h_ +#define SDL_sysjoystick_c_h_ + +#include + +struct SDL_joylist_item; +struct SDL_sensorlist_item; + +// The private structure used to keep track of a joystick +struct joystick_hwdata +{ + int fd; + // linux driver creates a separate device for gyro/accelerometer + int fd_sensor; + struct SDL_joylist_item *item; + struct SDL_sensorlist_item *item_sensor; + SDL_GUID guid; + char *fname; // Used in haptic subsystem + + bool ff_rumble; + bool ff_sine; + struct ff_effect effect; + Uint32 effect_expiration; + + // The current Linux joystick driver maps balls to two axes + struct hwdata_ball + { + int axis[2]; + } *balls; + + // The current Linux joystick driver maps hats to two axes + struct hwdata_hat + { + int axis[2]; + } *hats; + + // Support for the Linux 2.4 unified input interface + Uint8 key_map[KEY_MAX]; + Uint8 abs_map[ABS_MAX]; + bool has_key[KEY_MAX]; + bool has_abs[ABS_MAX]; + bool has_accelerometer; + bool has_gyro; + + // Support for the classic joystick interface + bool classic; + Uint16 *key_pam; + Uint8 *abs_pam; + + struct axis_correct + { + bool use_deadzones; + + // Deadzone coefficients + int coef[3]; + + // Raw coordinate scale + int minimum; + int maximum; + float scale; + } abs_correct[ABS_MAX]; + + float accelerometer_scale[3]; + float gyro_scale[3]; + + /* Each axis is read independently, if we don't get all axis this call to + * LINUX_JoystickUpdateupdate(), store them for the next one */ + float gyro_data[3]; + float accel_data[3]; + Uint64 sensor_tick; + Sint32 last_tick; + + bool report_sensor; + bool fresh; + bool recovering_from_dropped; + bool recovering_from_dropped_sensor; + + // Steam Controller support + bool m_bSteamController; + + // 4 = (ABS_HAT3X-ABS_HAT0X)/2 (see input-event-codes.h in kernel) + int hats_indices[4]; + bool has_hat[4]; + struct hat_axis_correct + { + bool use_deadzones; + int minimum[2]; + int maximum[2]; + } hat_correct[4]; + + // Set when gamepad is pending removal due to ENODEV read error + bool gone; + bool sensor_gone; +}; + +#endif // SDL_sysjoystick_c_h_ diff --git a/thirdparty/sdl/joystick/usb_ids.h b/thirdparty/sdl/joystick/usb_ids.h new file mode 100644 index 00000000000..15c1bb74542 --- /dev/null +++ b/thirdparty/sdl/joystick/usb_ids.h @@ -0,0 +1,195 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef usb_ids_h_ +#define usb_ids_h_ + +// Definitions of useful USB VID/PID values + +#define USB_VENDOR_8BITDO 0x2dc8 +#define USB_VENDOR_AMAZON 0x1949 +#define USB_VENDOR_APPLE 0x05ac +#define USB_VENDOR_ASTRO 0x9886 +#define USB_VENDOR_ASUS 0x0b05 +#define USB_VENDOR_BACKBONE 0x358a +#define USB_VENDOR_GAMESIR 0x3537 +#define USB_VENDOR_DRAGONRISE 0x0079 +#define USB_VENDOR_GOOGLE 0x18d1 +#define USB_VENDOR_HORI 0x0f0d +#define USB_VENDOR_HP 0x03f0 +#define USB_VENDOR_HYPERKIN 0x2e24 +#define USB_VENDOR_LOGITECH 0x046d +#define USB_VENDOR_MADCATZ 0x0738 +#define USB_VENDOR_MAYFLASH 0x33df +#define USB_VENDOR_MICROSOFT 0x045e +#define USB_VENDOR_NACON 0x146b +#define USB_VENDOR_NACON_ALT 0x3285 +#define USB_VENDOR_NINTENDO 0x057e +#define USB_VENDOR_NVIDIA 0x0955 +#define USB_VENDOR_PDP 0x0e6f +#define USB_VENDOR_POWERA 0x24c6 +#define USB_VENDOR_POWERA_ALT 0x20d6 +#define USB_VENDOR_QANBA 0x2c22 +#define USB_VENDOR_RAZER 0x1532 +#define USB_VENDOR_SAITEK 0x06a3 +#define USB_VENDOR_SHANWAN 0x2563 +#define USB_VENDOR_SHANWAN_ALT 0x20bc +#define USB_VENDOR_SONY 0x054c +#define USB_VENDOR_THRUSTMASTER 0x044f +#define USB_VENDOR_TURTLE_BEACH 0x10f5 +#define USB_VENDOR_SWITCH 0x2563 +#define USB_VENDOR_VALVE 0x28de +#define USB_VENDOR_ZEROPLUS 0x0c12 + +#define USB_PRODUCT_8BITDO_XBOX_CONTROLLER1 0x2002 // Ultimate Wired Controller for Xbox +#define USB_PRODUCT_8BITDO_XBOX_CONTROLLER2 0x3106 // Ultimate Wireless / Pro 2 Wired Controller +#define USB_PRODUCT_AMAZON_LUNA_CONTROLLER 0x0419 +#define USB_PRODUCT_ASTRO_C40_XBOX360 0x0024 +#define USB_PRODUCT_BACKBONE_ONE_IOS 0x0103 +#define USB_PRODUCT_BACKBONE_ONE_IOS_PS5 0x0104 +#define USB_PRODUCT_GAMESIR_G7 0x1001 +#define USB_PRODUCT_GOOGLE_STADIA_CONTROLLER 0x9400 +#define USB_PRODUCT_EVORETRO_GAMECUBE_ADAPTER1 0x1843 +#define USB_PRODUCT_EVORETRO_GAMECUBE_ADAPTER2 0x1846 +#define USB_PRODUCT_HORI_FIGHTING_COMMANDER_OCTA_SERIES_X 0x0150 +#define USB_PRODUCT_HORI_HORIPAD_PRO_SERIES_X 0x014f +#define USB_PRODUCT_HORI_FIGHTING_STICK_ALPHA_PS4 0x011c +#define USB_PRODUCT_HORI_FIGHTING_STICK_ALPHA_PS5 0x0184 +#define USB_PRODUCT_HORI_FIGHTING_STICK_ALPHA_PS5 0x0184 +#define USB_PRODUCT_HORI_STEAM_CONTROLLER 0x01AB +#define USB_PRODUCT_HORI_STEAM_CONTROLLER_BT 0x0196 +#define USB_PRODUCT_HORI_TAIKO_DRUM_CONTROLLER 0x01b2 +#define USB_PRODUCT_LOGITECH_F310 0xc216 +#define USB_PRODUCT_LOGITECH_CHILLSTREAM 0xcad1 +#define USB_PRODUCT_MADCATZ_SAITEK_SIDE_PANEL_CONTROL_DECK 0x2218 +#define USB_PRODUCT_NACON_REVOLUTION_5_PRO_PS4_WIRELESS 0x0d16 +#define USB_PRODUCT_NACON_REVOLUTION_5_PRO_PS4_WIRED 0x0d17 +#define USB_PRODUCT_NACON_REVOLUTION_5_PRO_PS5_WIRELESS 0x0d18 +#define USB_PRODUCT_NACON_REVOLUTION_5_PRO_PS5_WIRED 0x0d19 +#define USB_PRODUCT_NINTENDO_GAMECUBE_ADAPTER 0x0337 +#define USB_PRODUCT_NINTENDO_N64_CONTROLLER 0x2019 +#define USB_PRODUCT_NINTENDO_SEGA_GENESIS_CONTROLLER 0x201e +#define USB_PRODUCT_NINTENDO_SNES_CONTROLLER 0x2017 +#define USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP 0x200e +#define USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT 0x2006 +#define USB_PRODUCT_NINTENDO_SWITCH_JOYCON_PAIR 0x2008 // Used by joycond +#define USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT 0x2007 +#define USB_PRODUCT_NINTENDO_SWITCH_PRO 0x2009 +#define USB_PRODUCT_NINTENDO_WII_REMOTE 0x0306 +#define USB_PRODUCT_NINTENDO_WII_REMOTE2 0x0330 +#define USB_PRODUCT_NVIDIA_SHIELD_CONTROLLER_V103 0x7210 +#define USB_PRODUCT_NVIDIA_SHIELD_CONTROLLER_V104 0x7214 +#define USB_PRODUCT_RAZER_ATROX 0x0a00 +#define USB_PRODUCT_RAZER_KITSUNE 0x1012 +#define USB_PRODUCT_RAZER_PANTHERA 0x0401 +#define USB_PRODUCT_RAZER_PANTHERA_EVO 0x1008 +#define USB_PRODUCT_RAZER_RAIJU 0x1000 +#define USB_PRODUCT_RAZER_TOURNAMENT_EDITION_USB 0x1007 +#define USB_PRODUCT_RAZER_TOURNAMENT_EDITION_BLUETOOTH 0x100a +#define USB_PRODUCT_RAZER_ULTIMATE_EDITION_USB 0x1004 +#define USB_PRODUCT_RAZER_ULTIMATE_EDITION_BLUETOOTH 0x1009 +#define USB_PRODUCT_RAZER_WOLVERINE_V2 0x0a29 +#define USB_PRODUCT_RAZER_WOLVERINE_V2_CHROMA 0x0a2e +#define USB_PRODUCT_RAZER_WOLVERINE_V2_PRO_PS5_WIRED 0x100b +#define USB_PRODUCT_RAZER_WOLVERINE_V2_PRO_PS5_WIRELESS 0x100c +#define USB_PRODUCT_RAZER_WOLVERINE_V2_PRO_XBOX_WIRED 0x1010 +#define USB_PRODUCT_RAZER_WOLVERINE_V2_PRO_XBOX_WIRELESS 0x1011 +#define USB_PRODUCT_RAZER_WOLVERINE_V3_PRO 0x0a3f +#define USB_PRODUCT_ROG_RAIKIRI 0x1a38 +#define USB_PRODUCT_SAITEK_CYBORG_V3 0xf622 +#define USB_PRODUCT_SHANWAN_DS3 0x0523 +#define USB_PRODUCT_SONY_DS3 0x0268 +#define USB_PRODUCT_SONY_DS4 0x05c4 +#define USB_PRODUCT_SONY_DS4_DONGLE 0x0ba0 +#define USB_PRODUCT_SONY_DS4_SLIM 0x09cc +#define USB_PRODUCT_SONY_DS4_STRIKEPAD 0x05c5 +#define USB_PRODUCT_SONY_DS5 0x0ce6 +#define USB_PRODUCT_SONY_DS5_EDGE 0x0df2 +#define USB_PRODUCT_SWITCH_RETROBIT_CONTROLLER 0x0575 +#define USB_PRODUCT_THRUSTMASTER_ESWAPX_PRO_PS4 0xd00e +#define USB_PRODUCT_THRUSTMASTER_ESWAPX_PRO_SERIES_X 0xd012 +#define USB_PRODUCT_TURTLE_BEACH_SERIES_X_REACT_R 0x7013 +#define USB_PRODUCT_TURTLE_BEACH_SERIES_X_RECON 0x7009 +#define USB_PRODUCT_VALVE_STEAM_CONTROLLER_DONGLE 0x1142 +#define USB_PRODUCT_VICTRIX_FS_PRO 0x0203 +#define USB_PRODUCT_VICTRIX_FS_PRO_V2 0x0207 +#define USB_PRODUCT_XBOX360_XUSB_CONTROLLER 0x02a1 // XUSB driver software PID +#define USB_PRODUCT_XBOX360_WIRED_CONTROLLER 0x028e +#define USB_PRODUCT_XBOX360_WIRELESS_RECEIVER 0x0719 +#define USB_PRODUCT_XBOX360_WIRELESS_RECEIVER_THIRDPARTY1 0x02a9 +#define USB_PRODUCT_XBOX360_WIRELESS_RECEIVER_THIRDPARTY2 0x0291 +#define USB_PRODUCT_XBOX_ONE_ADAPTIVE 0x0b0a +#define USB_PRODUCT_XBOX_ONE_ADAPTIVE_BLUETOOTH 0x0b0c +#define USB_PRODUCT_XBOX_ONE_ADAPTIVE_BLE 0x0b21 +#define USB_PRODUCT_XBOX_ONE_ELITE_SERIES_1 0x02e3 +#define USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2 0x0b00 +#define USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLUETOOTH 0x0b05 +#define USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLE 0x0b22 +#define USB_PRODUCT_XBOX_ONE_S 0x02ea +#define USB_PRODUCT_XBOX_ONE_S_REV1_BLUETOOTH 0x02e0 +#define USB_PRODUCT_XBOX_ONE_S_REV2_BLUETOOTH 0x02fd +#define USB_PRODUCT_XBOX_ONE_S_REV2_BLE 0x0b20 +#define USB_PRODUCT_XBOX_SERIES_X 0x0b12 +#define USB_PRODUCT_XBOX_SERIES_X_BLE 0x0b13 +#define USB_PRODUCT_XBOX_SERIES_X_HP_HYPERX 0x08b6 +#define USB_PRODUCT_XBOX_SERIES_X_HP_HYPERX_RGB 0x07a0 +#define USB_PRODUCT_XBOX_SERIES_X_PDP_AFTERGLOW 0x02da +#define USB_PRODUCT_XBOX_SERIES_X_PDP_BLUE 0x02d9 +#define USB_PRODUCT_XBOX_SERIES_X_POWERA_FUSION_PRO2 0x4001 +#define USB_PRODUCT_XBOX_SERIES_X_POWERA_FUSION_PRO4 0x400b +#define USB_PRODUCT_XBOX_SERIES_X_POWERA_FUSION_PRO_WIRELESS_USB 0x4014 +#define USB_PRODUCT_XBOX_SERIES_X_POWERA_FUSION_PRO_WIRELESS_DONGLE 0x4016 +#define USB_PRODUCT_XBOX_SERIES_X_POWERA_MOGA_XP_ULTRA 0x890b +#define USB_PRODUCT_XBOX_SERIES_X_POWERA_SPECTRA 0x4002 +#define USB_PRODUCT_XBOX_SERIES_X_VICTRIX_GAMBIT 0x02d6 +#define USB_PRODUCT_XBOX_ONE_XBOXGIP_CONTROLLER 0x02ff // XBOXGIP driver software PID +#define USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD 0x11ff + +// USB usage pages +#define USB_USAGEPAGE_GENERIC_DESKTOP 0x0001 +#define USB_USAGEPAGE_BUTTON 0x0009 + +// USB usages for USAGE_PAGE_GENERIC_DESKTOP +#define USB_USAGE_GENERIC_POINTER 0x0001 +#define USB_USAGE_GENERIC_MOUSE 0x0002 +#define USB_USAGE_GENERIC_JOYSTICK 0x0004 +#define USB_USAGE_GENERIC_GAMEPAD 0x0005 +#define USB_USAGE_GENERIC_KEYBOARD 0x0006 +#define USB_USAGE_GENERIC_KEYPAD 0x0007 +#define USB_USAGE_GENERIC_MULTIAXISCONTROLLER 0x0008 +#define USB_USAGE_GENERIC_X 0x0030 +#define USB_USAGE_GENERIC_Y 0x0031 +#define USB_USAGE_GENERIC_Z 0x0032 +#define USB_USAGE_GENERIC_RX 0x0033 +#define USB_USAGE_GENERIC_RY 0x0034 +#define USB_USAGE_GENERIC_RZ 0x0035 +#define USB_USAGE_GENERIC_SLIDER 0x0036 +#define USB_USAGE_GENERIC_DIAL 0x0037 +#define USB_USAGE_GENERIC_WHEEL 0x0038 +#define USB_USAGE_GENERIC_HAT 0x0039 + +/* Bluetooth SIG assigned Company Identifiers + https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers/ */ +#define BLUETOOTH_VENDOR_AMAZON 0x0171 + +#define BLUETOOTH_PRODUCT_LUNA_CONTROLLER 0x0419 + +#endif // usb_ids_h_ diff --git a/thirdparty/sdl/joystick/windows/SDL_dinputjoystick.c b/thirdparty/sdl/joystick/windows/SDL_dinputjoystick.c new file mode 100644 index 00000000000..377992ed9ee --- /dev/null +++ b/thirdparty/sdl/joystick/windows/SDL_dinputjoystick.c @@ -0,0 +1,1207 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "../SDL_sysjoystick.h" + +#ifdef SDL_JOYSTICK_DINPUT + +#include "SDL_windowsjoystick_c.h" +#include "SDL_dinputjoystick_c.h" +#include "SDL_rawinputjoystick_c.h" +#include "SDL_xinputjoystick_c.h" +#include "../hidapi/SDL_hidapijoystick_c.h" + +#ifndef DIDFT_OPTIONAL +#define DIDFT_OPTIONAL 0x80000000 +#endif + +#define INPUT_QSIZE 128 // Buffer up to 128 input messages +#define JOY_AXIS_THRESHOLD (((SDL_JOYSTICK_AXIS_MAX) - (SDL_JOYSTICK_AXIS_MIN)) / 100) // 1% motion + +#define CONVERT_MAGNITUDE(x) (((x)*10000) / 0x7FFF) + +// external variables referenced. +extern HWND SDL_HelperWindow; + + +// local variables +static bool coinitialized = false; +static LPDIRECTINPUT8 dinput = NULL; + +// Taken from Wine - Thanks! +static DIOBJECTDATAFORMAT dfDIJoystick2[] = { + { &GUID_XAxis, DIJOFS_X, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTPOSITION }, + { &GUID_YAxis, DIJOFS_Y, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTPOSITION }, + { &GUID_ZAxis, DIJOFS_Z, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTPOSITION }, + { &GUID_RxAxis, DIJOFS_RX, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTPOSITION }, + { &GUID_RyAxis, DIJOFS_RY, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTPOSITION }, + { &GUID_RzAxis, DIJOFS_RZ, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTPOSITION }, + { &GUID_Slider, DIJOFS_SLIDER(0), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTPOSITION }, + { &GUID_Slider, DIJOFS_SLIDER(1), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTPOSITION }, + { &GUID_POV, DIJOFS_POV(0), DIDFT_OPTIONAL | DIDFT_POV | DIDFT_ANYINSTANCE, 0 }, + { &GUID_POV, DIJOFS_POV(1), DIDFT_OPTIONAL | DIDFT_POV | DIDFT_ANYINSTANCE, 0 }, + { &GUID_POV, DIJOFS_POV(2), DIDFT_OPTIONAL | DIDFT_POV | DIDFT_ANYINSTANCE, 0 }, + { &GUID_POV, DIJOFS_POV(3), DIDFT_OPTIONAL | DIDFT_POV | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(0), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(1), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(2), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(3), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(4), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(5), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(6), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(7), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(8), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(9), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(10), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(11), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(12), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(13), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(14), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(15), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(16), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(17), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(18), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(19), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(20), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(21), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(22), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(23), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(24), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(25), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(26), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(27), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(28), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(29), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(30), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(31), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(32), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(33), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(34), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(35), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(36), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(37), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(38), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(39), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(40), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(41), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(42), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(43), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(44), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(45), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(46), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(47), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(48), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(49), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(50), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(51), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(52), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(53), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(54), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(55), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(56), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(57), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(58), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(59), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(60), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(61), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(62), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(63), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(64), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(65), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(66), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(67), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(68), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(69), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(70), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(71), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(72), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(73), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(74), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(75), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(76), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(77), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(78), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(79), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(80), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(81), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(82), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(83), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(84), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(85), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(86), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(87), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(88), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(89), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(90), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(91), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(92), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(93), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(94), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(95), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(96), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(97), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(98), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(99), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(100), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(101), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(102), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(103), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(104), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(105), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(106), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(107), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(108), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(109), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(110), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(111), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(112), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(113), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(114), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(115), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(116), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(117), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(118), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(119), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(120), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(121), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(122), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(123), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(124), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(125), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(126), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { NULL, DIJOFS_BUTTON(127), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 }, + { &GUID_XAxis, FIELD_OFFSET(DIJOYSTATE2, lVX), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTVELOCITY }, + { &GUID_YAxis, FIELD_OFFSET(DIJOYSTATE2, lVY), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTVELOCITY }, + { &GUID_ZAxis, FIELD_OFFSET(DIJOYSTATE2, lVZ), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTVELOCITY }, + { &GUID_RxAxis, FIELD_OFFSET(DIJOYSTATE2, lVRx), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTVELOCITY }, + { &GUID_RyAxis, FIELD_OFFSET(DIJOYSTATE2, lVRy), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTVELOCITY }, + { &GUID_RzAxis, FIELD_OFFSET(DIJOYSTATE2, lVRz), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTVELOCITY }, + // note: dwOfs value matches Windows + { &GUID_Slider, DIJOFS_SLIDER(0), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTVELOCITY }, + { &GUID_Slider, DIJOFS_SLIDER(1), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTVELOCITY }, + { &GUID_XAxis, FIELD_OFFSET(DIJOYSTATE2, lAX), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTACCEL }, + { &GUID_YAxis, FIELD_OFFSET(DIJOYSTATE2, lAY), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTACCEL }, + { &GUID_ZAxis, FIELD_OFFSET(DIJOYSTATE2, lAZ), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTACCEL }, + { &GUID_RxAxis, FIELD_OFFSET(DIJOYSTATE2, lARx), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTACCEL }, + { &GUID_RyAxis, FIELD_OFFSET(DIJOYSTATE2, lARy), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTACCEL }, + { &GUID_RzAxis, FIELD_OFFSET(DIJOYSTATE2, lARz), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTACCEL }, + // note: dwOfs value matches Windows + { &GUID_Slider, DIJOFS_SLIDER(0), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTACCEL }, + { &GUID_Slider, DIJOFS_SLIDER(1), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTACCEL }, + { &GUID_XAxis, FIELD_OFFSET(DIJOYSTATE2, lFX), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTFORCE }, + { &GUID_YAxis, FIELD_OFFSET(DIJOYSTATE2, lFY), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTFORCE }, + { &GUID_ZAxis, FIELD_OFFSET(DIJOYSTATE2, lFZ), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTFORCE }, + { &GUID_RxAxis, FIELD_OFFSET(DIJOYSTATE2, lFRx), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTFORCE }, + { &GUID_RyAxis, FIELD_OFFSET(DIJOYSTATE2, lFRy), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTFORCE }, + { &GUID_RzAxis, FIELD_OFFSET(DIJOYSTATE2, lFRz), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTFORCE }, + // note: dwOfs value matches Windows + { &GUID_Slider, DIJOFS_SLIDER(0), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTFORCE }, + { &GUID_Slider, DIJOFS_SLIDER(1), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTFORCE }, +}; + +const DIDATAFORMAT SDL_c_dfDIJoystick2 = { + sizeof(DIDATAFORMAT), + sizeof(DIOBJECTDATAFORMAT), + DIDF_ABSAXIS, + sizeof(DIJOYSTATE2), + SDL_arraysize(dfDIJoystick2), + dfDIJoystick2 +}; + +// Convert a DirectInput return code to a text message +static bool SetDIerror(const char *function, HRESULT code) +{ + return SDL_SetError("%s() DirectX error 0x%8.8lx", function, code); +} + +static bool SDL_IsXInputDevice(Uint16 vendor_id, Uint16 product_id, const char *hidPath) +{ +#if defined(SDL_JOYSTICK_XINPUT) || defined(SDL_JOYSTICK_RAWINPUT) + SDL_GamepadType type; + + // XInput and RawInput backends will pick up XInput-compatible devices + if (!SDL_XINPUT_Enabled() +#ifdef SDL_JOYSTICK_RAWINPUT + && !RAWINPUT_IsEnabled() +#endif + ) { + return false; + } + + // If device path contains "IG_" then its an XInput device + // See: https://docs.microsoft.com/windows/win32/xinput/xinput-and-directinput + if (SDL_strstr(hidPath, "IG_") != NULL) { + return true; + } + + type = SDL_GetGamepadTypeFromVIDPID(vendor_id, product_id, NULL, false); + if (type == SDL_GAMEPAD_TYPE_XBOX360 || + type == SDL_GAMEPAD_TYPE_XBOXONE || + (vendor_id == USB_VENDOR_VALVE && product_id == USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD)) { + return true; + } +#endif // SDL_JOYSTICK_XINPUT || SDL_JOYSTICK_RAWINPUT + + return false; +} + +static bool QueryDeviceName(LPDIRECTINPUTDEVICE8 device, Uint16 vendor_id, Uint16 product_id, char **manufacturer_string, char **product_string) +{ + DIPROPSTRING dipstr; + + if (!device || !manufacturer_string || !product_string) { + return false; + } + +#ifdef SDL_JOYSTICK_HIDAPI + *manufacturer_string = HIDAPI_GetDeviceManufacturerName(vendor_id, product_id); + *product_string = HIDAPI_GetDeviceProductName(vendor_id, product_id); + if (*product_string) { + return true; + } +#endif + + dipstr.diph.dwSize = sizeof(dipstr); + dipstr.diph.dwHeaderSize = sizeof(dipstr.diph); + dipstr.diph.dwObj = 0; + dipstr.diph.dwHow = DIPH_DEVICE; + + if (FAILED(IDirectInputDevice8_GetProperty(device, DIPROP_PRODUCTNAME, &dipstr.diph))) { + return false; + } + + *manufacturer_string = NULL; + *product_string = WIN_StringToUTF8(dipstr.wsz); + + return true; +} + +static bool QueryDevicePath(LPDIRECTINPUTDEVICE8 device, char **device_path) +{ + DIPROPGUIDANDPATH dippath; + + if (!device || !device_path) { + return false; + } + + dippath.diph.dwSize = sizeof(dippath); + dippath.diph.dwHeaderSize = sizeof(dippath.diph); + dippath.diph.dwObj = 0; + dippath.diph.dwHow = DIPH_DEVICE; + + if (FAILED(IDirectInputDevice8_GetProperty(device, DIPROP_GUIDANDPATH, &dippath.diph))) { + return false; + } + + *device_path = WIN_StringToUTF8W(dippath.wszPath); + + // Normalize path to upper case. + SDL_strupr(*device_path); + + return true; +} + +static bool QueryDeviceInfo(LPDIRECTINPUTDEVICE8 device, Uint16 *vendor_id, Uint16 *product_id) +{ + DIPROPDWORD dipdw; + + if (!device || !vendor_id || !product_id) { + return false; + } + + dipdw.diph.dwSize = sizeof(dipdw); + dipdw.diph.dwHeaderSize = sizeof(dipdw.diph); + dipdw.diph.dwObj = 0; + dipdw.diph.dwHow = DIPH_DEVICE; + dipdw.dwData = 0; + + if (FAILED(IDirectInputDevice8_GetProperty(device, DIPROP_VIDPID, &dipdw.diph))) { + return false; + } + + *vendor_id = LOWORD(dipdw.dwData); + *product_id = HIWORD(dipdw.dwData); + + return true; +} + +void FreeRumbleEffectData(DIEFFECT *effect) +{ + if (!effect) { + return; + } + SDL_free(effect->rgdwAxes); + SDL_free(effect->rglDirection); + SDL_free(effect->lpvTypeSpecificParams); + SDL_free(effect); +} + +DIEFFECT *CreateRumbleEffectData(Sint16 magnitude) +{ + DIEFFECT *effect; + DIPERIODIC *periodic; + + // Create the effect + effect = (DIEFFECT *)SDL_calloc(1, sizeof(*effect)); + if (!effect) { + return NULL; + } + effect->dwSize = sizeof(*effect); + effect->dwGain = 10000; + effect->dwFlags = DIEFF_OBJECTOFFSETS; + effect->dwDuration = SDL_MAX_RUMBLE_DURATION_MS * 1000; // In microseconds. + effect->dwTriggerButton = DIEB_NOTRIGGER; + + effect->cAxes = 2; + effect->rgdwAxes = (DWORD *)SDL_calloc(effect->cAxes, sizeof(DWORD)); + if (!effect->rgdwAxes) { + FreeRumbleEffectData(effect); + return NULL; + } + + effect->rglDirection = (LONG *)SDL_calloc(effect->cAxes, sizeof(LONG)); + if (!effect->rglDirection) { + FreeRumbleEffectData(effect); + return NULL; + } + effect->dwFlags |= DIEFF_CARTESIAN; + + periodic = (DIPERIODIC *)SDL_calloc(1, sizeof(*periodic)); + if (!periodic) { + FreeRumbleEffectData(effect); + return NULL; + } + periodic->dwMagnitude = CONVERT_MAGNITUDE(magnitude); + periodic->dwPeriod = 1000000; + + effect->cbTypeSpecificParams = sizeof(*periodic); + effect->lpvTypeSpecificParams = periodic; + + return effect; +} + +bool SDL_DINPUT_JoystickInit(void) +{ + HRESULT result; + HINSTANCE instance; + + if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_DIRECTINPUT, true)) { + // In some environments, IDirectInput8_Initialize / _EnumDevices can take a minute even with no controllers. + dinput = NULL; + return true; + } + + result = WIN_CoInitialize(); + if (FAILED(result)) { + return SetDIerror("CoInitialize", result); + } + + coinitialized = true; + + result = CoCreateInstance(&CLSID_DirectInput8, NULL, CLSCTX_INPROC_SERVER, + &IID_IDirectInput8, (LPVOID *)&dinput); + + if (FAILED(result)) { + return SetDIerror("CoCreateInstance", result); + } + + // Because we used CoCreateInstance, we need to Initialize it, first. + instance = GetModuleHandle(NULL); + if (!instance) { + IDirectInput8_Release(dinput); + dinput = NULL; + return SDL_SetError("GetModuleHandle() failed with error code %lu.", GetLastError()); + } + result = IDirectInput8_Initialize(dinput, instance, DIRECTINPUT_VERSION); + + if (FAILED(result)) { + IDirectInput8_Release(dinput); + dinput = NULL; + return SetDIerror("IDirectInput::Initialize", result); + } + return true; +} + +static int GetSteamVirtualGamepadSlot(Uint16 vendor_id, Uint16 product_id, const char *device_path) +{ + int slot = -1; + + if (vendor_id == USB_VENDOR_VALVE && + product_id == USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD) { + (void)SDL_sscanf(device_path, "\\\\?\\HID#VID_28DE&PID_11FF&IG_0%d", &slot); + } + return slot; +} + +// helper function for direct input, gets called for each connected joystick +static BOOL CALLBACK EnumJoystickDetectCallback(LPCDIDEVICEINSTANCE pDeviceInstance, LPVOID pContext) +{ +#define CHECK(expression) \ + { \ + if (!(expression)) \ + goto err; \ + } + JoyStick_DeviceData *pNewJoystick = NULL; + JoyStick_DeviceData *pPrevJoystick = NULL; + Uint16 vendor = 0; + Uint16 product = 0; + Uint16 version = 0; + char *hidPath = NULL; + char *manufacturer_string = NULL; + char *product_string = NULL; + LPDIRECTINPUTDEVICE8 device = NULL; + + // We are only supporting HID devices. + CHECK(pDeviceInstance->dwDevType & DIDEVTYPE_HID); + + CHECK(SUCCEEDED(IDirectInput8_CreateDevice(dinput, &pDeviceInstance->guidInstance, &device, NULL))); + CHECK(QueryDevicePath(device, &hidPath)); + CHECK(QueryDeviceInfo(device, &vendor, &product)); + CHECK(QueryDeviceName(device, vendor, product, &manufacturer_string, &product_string)); + + CHECK(!SDL_IsXInputDevice(vendor, product, hidPath)); + CHECK(!SDL_ShouldIgnoreJoystick(vendor, product, version, product_string)); + CHECK(!SDL_JoystickHandledByAnotherDriver(&SDL_WINDOWS_JoystickDriver, vendor, product, version, product_string)); + + pNewJoystick = *(JoyStick_DeviceData **)pContext; + while (pNewJoystick) { + // update GUIDs of joysticks with matching paths, in case they're not open yet + if (SDL_strcmp(pNewJoystick->path, hidPath) == 0) { + // if we are replacing the front of the list then update it + if (pNewJoystick == *(JoyStick_DeviceData **)pContext) { + *(JoyStick_DeviceData **)pContext = pNewJoystick->pNext; + } else if (pPrevJoystick) { + pPrevJoystick->pNext = pNewJoystick->pNext; + } + + // Update with new guid/etc, if it has changed + SDL_memcpy(&pNewJoystick->dxdevice, pDeviceInstance, sizeof(DIDEVICEINSTANCE)); + + pNewJoystick->pNext = SYS_Joystick; + SYS_Joystick = pNewJoystick; + + pNewJoystick = NULL; + CHECK(FALSE); + } + + pPrevJoystick = pNewJoystick; + pNewJoystick = pNewJoystick->pNext; + } + + pNewJoystick = (JoyStick_DeviceData *)SDL_calloc(1, sizeof(JoyStick_DeviceData)); + CHECK(pNewJoystick); + + pNewJoystick->steam_virtual_gamepad_slot = GetSteamVirtualGamepadSlot(vendor, product, hidPath); + SDL_strlcpy(pNewJoystick->path, hidPath, SDL_arraysize(pNewJoystick->path)); + SDL_memcpy(&pNewJoystick->dxdevice, pDeviceInstance, sizeof(DIDEVICEINSTANCE)); + + pNewJoystick->joystickname = SDL_CreateJoystickName(vendor, product, manufacturer_string, product_string); + CHECK(pNewJoystick->joystickname); + + if (vendor && product) { + pNewJoystick->guid = SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_USB, vendor, product, version, manufacturer_string, product_string, 0, 0); + } else { + pNewJoystick->guid = SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_BLUETOOTH, vendor, product, version, manufacturer_string, product_string, 0, 0); + } + + WINDOWS_AddJoystickDevice(pNewJoystick); + pNewJoystick = NULL; + +err: + if (pNewJoystick) { + SDL_free(pNewJoystick->joystickname); + SDL_free(pNewJoystick); + } + + SDL_free(hidPath); + SDL_free(manufacturer_string); + SDL_free(product_string); + + if (device) { + IDirectInputDevice8_Release(device); + } + + return DIENUM_CONTINUE; // get next device, please +#undef CHECK +} + +void SDL_DINPUT_JoystickDetect(JoyStick_DeviceData **pContext) +{ + if (!dinput) { + return; + } + + IDirectInput8_EnumDevices(dinput, DI8DEVCLASS_GAMECTRL, EnumJoystickDetectCallback, pContext, DIEDFL_ATTACHEDONLY); +} + +// helper function for direct input, gets called for each connected joystick +typedef struct +{ + Uint16 vendor; + Uint16 product; + bool present; +} Joystick_PresentData; + +static BOOL CALLBACK EnumJoystickPresentCallback(LPCDIDEVICEINSTANCE pDeviceInstance, LPVOID pContext) +{ +#define CHECK(expression) \ + { \ + if (!(expression)) \ + goto err; \ + } + Joystick_PresentData *pData = (Joystick_PresentData *)pContext; + Uint16 vendor = 0; + Uint16 product = 0; + LPDIRECTINPUTDEVICE8 device = NULL; + BOOL result = DIENUM_CONTINUE; + + // We are only supporting HID devices. + CHECK(pDeviceInstance->dwDevType & DIDEVTYPE_HID); + + CHECK(SUCCEEDED(IDirectInput8_CreateDevice(dinput, &pDeviceInstance->guidInstance, &device, NULL))); + CHECK(QueryDeviceInfo(device, &vendor, &product)); + + if (vendor == pData->vendor && product == pData->product) { + pData->present = true; + result = DIENUM_STOP; // found it + } + +err: + if (device) { + IDirectInputDevice8_Release(device); + } + + return result; +#undef CHECK +} + +bool SDL_DINPUT_JoystickPresent(Uint16 vendor_id, Uint16 product_id, Uint16 version_number) +{ + Joystick_PresentData data; + + if (!dinput) { + return false; + } + + data.vendor = vendor_id; + data.product = product_id; + data.present = false; + IDirectInput8_EnumDevices(dinput, DI8DEVCLASS_GAMECTRL, EnumJoystickPresentCallback, &data, DIEDFL_ATTACHEDONLY); + return data.present; +} + +static BOOL CALLBACK EnumDevObjectsCallback(LPCDIDEVICEOBJECTINSTANCE pDeviceObject, LPVOID pContext) +{ + SDL_Joystick *joystick = (SDL_Joystick *)pContext; + HRESULT result; + input_t *in = &joystick->hwdata->Inputs[joystick->hwdata->NumInputs]; + + if (pDeviceObject->dwType & DIDFT_BUTTON) { + in->type = BUTTON; + in->num = (Uint8)joystick->nbuttons; + in->ofs = DIJOFS_BUTTON(in->num); + joystick->nbuttons++; + } else if (pDeviceObject->dwType & DIDFT_POV) { + in->type = HAT; + in->num = (Uint8)joystick->nhats; + in->ofs = DIJOFS_POV(in->num); + joystick->nhats++; + } else if (pDeviceObject->dwType & DIDFT_AXIS) { + DIPROPRANGE diprg; + DIPROPDWORD dilong; + + in->type = AXIS; + in->num = (Uint8)joystick->naxes; + if (SDL_memcmp(&pDeviceObject->guidType, &GUID_XAxis, sizeof(pDeviceObject->guidType)) == 0) { + in->ofs = DIJOFS_X; + } else if (SDL_memcmp(&pDeviceObject->guidType, &GUID_YAxis, sizeof(pDeviceObject->guidType)) == 0) { + in->ofs = DIJOFS_Y; + } else if (SDL_memcmp(&pDeviceObject->guidType, &GUID_ZAxis, sizeof(pDeviceObject->guidType)) == 0) { + in->ofs = DIJOFS_Z; + } else if (SDL_memcmp(&pDeviceObject->guidType, &GUID_RxAxis, sizeof(pDeviceObject->guidType)) == 0) { + in->ofs = DIJOFS_RX; + } else if (SDL_memcmp(&pDeviceObject->guidType, &GUID_RyAxis, sizeof(pDeviceObject->guidType)) == 0) { + in->ofs = DIJOFS_RY; + } else if (SDL_memcmp(&pDeviceObject->guidType, &GUID_RzAxis, sizeof(pDeviceObject->guidType)) == 0) { + in->ofs = DIJOFS_RZ; + } else if (SDL_memcmp(&pDeviceObject->guidType, &GUID_Slider, sizeof(pDeviceObject->guidType)) == 0) { + in->ofs = DIJOFS_SLIDER(joystick->hwdata->NumSliders); + ++joystick->hwdata->NumSliders; + } else { + return DIENUM_CONTINUE; // not an axis we can grok + } + + diprg.diph.dwSize = sizeof(diprg); + diprg.diph.dwHeaderSize = sizeof(diprg.diph); + diprg.diph.dwObj = pDeviceObject->dwType; + diprg.diph.dwHow = DIPH_BYID; + diprg.lMin = SDL_JOYSTICK_AXIS_MIN; + diprg.lMax = SDL_JOYSTICK_AXIS_MAX; + + result = + IDirectInputDevice8_SetProperty(joystick->hwdata->InputDevice, + DIPROP_RANGE, &diprg.diph); + if (FAILED(result)) { + return DIENUM_CONTINUE; // don't use this axis + } + + // Set dead zone to 0. + dilong.diph.dwSize = sizeof(dilong); + dilong.diph.dwHeaderSize = sizeof(dilong.diph); + dilong.diph.dwObj = pDeviceObject->dwType; + dilong.diph.dwHow = DIPH_BYID; + dilong.dwData = 0; + result = + IDirectInputDevice8_SetProperty(joystick->hwdata->InputDevice, + DIPROP_DEADZONE, &dilong.diph); + if (FAILED(result)) { + return DIENUM_CONTINUE; // don't use this axis + } + + joystick->naxes++; + } else { + // not supported at this time + return DIENUM_CONTINUE; + } + + joystick->hwdata->NumInputs++; + + if (joystick->hwdata->NumInputs == MAX_INPUTS) { + return DIENUM_STOP; // too many + } + + return DIENUM_CONTINUE; +} + +/* Sort using the data offset into the DInput struct. + * This gives a reasonable ordering for the inputs. + */ +static int SDLCALL SortDevFunc(const void *a, const void *b) +{ + const input_t *inputA = (const input_t *)a; + const input_t *inputB = (const input_t *)b; + + if (inputA->ofs < inputB->ofs) { + return -1; + } + if (inputA->ofs > inputB->ofs) { + return 1; + } + return 0; +} + +// Sort the input objects and recalculate the indices for each input. +static void SortDevObjects(SDL_Joystick *joystick) +{ + input_t *inputs = joystick->hwdata->Inputs; + Uint8 nButtons = 0; + Uint8 nHats = 0; + Uint8 nAxis = 0; + int n; + + SDL_qsort(inputs, joystick->hwdata->NumInputs, sizeof(input_t), SortDevFunc); + + for (n = 0; n < joystick->hwdata->NumInputs; n++) { + switch (inputs[n].type) { + case BUTTON: + inputs[n].num = nButtons; + nButtons++; + break; + + case HAT: + inputs[n].num = nHats; + nHats++; + break; + + case AXIS: + inputs[n].num = nAxis; + nAxis++; + break; + } + } +} + +bool SDL_DINPUT_JoystickOpen(SDL_Joystick *joystick, JoyStick_DeviceData *joystickdevice) +{ + HRESULT result; + DIPROPDWORD dipdw; + + joystick->hwdata->buffered = true; + joystick->hwdata->Capabilities.dwSize = sizeof(DIDEVCAPS); + + SDL_zero(dipdw); + dipdw.diph.dwSize = sizeof(DIPROPDWORD); + dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); + + result = + IDirectInput8_CreateDevice(dinput, + &joystickdevice->dxdevice.guidInstance, + &joystick->hwdata->InputDevice, + NULL); + if (FAILED(result)) { + return SetDIerror("IDirectInput::CreateDevice", result); + } + + /* Acquire shared access. Exclusive access is required for forces, + * though. */ + result = + IDirectInputDevice8_SetCooperativeLevel(joystick->hwdata->InputDevice, SDL_HelperWindow, + DISCL_EXCLUSIVE | + DISCL_BACKGROUND); + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::SetCooperativeLevel", result); + } + + // Use the extended data structure: DIJOYSTATE2. + result = + IDirectInputDevice8_SetDataFormat(joystick->hwdata->InputDevice, + &SDL_c_dfDIJoystick2); + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::SetDataFormat", result); + } + + // Get device capabilities + result = + IDirectInputDevice8_GetCapabilities(joystick->hwdata->InputDevice, + &joystick->hwdata->Capabilities); + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::GetCapabilities", result); + } + + // Force capable? + if (joystick->hwdata->Capabilities.dwFlags & DIDC_FORCEFEEDBACK) { + result = IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice); + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::Acquire", result); + } + + // reset all actuators. + result = + IDirectInputDevice8_SendForceFeedbackCommand(joystick->hwdata->InputDevice, + DISFFC_RESET); + + /* Not necessarily supported, ignore if not supported. + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::SendForceFeedbackCommand", result); + } + */ + + result = IDirectInputDevice8_Unacquire(joystick->hwdata->InputDevice); + + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::Unacquire", result); + } + + /* Turn on auto-centering for a ForceFeedback device (until told + * otherwise). */ + dipdw.diph.dwObj = 0; + dipdw.diph.dwHow = DIPH_DEVICE; + dipdw.dwData = DIPROPAUTOCENTER_ON; + + result = + IDirectInputDevice8_SetProperty(joystick->hwdata->InputDevice, + DIPROP_AUTOCENTER, &dipdw.diph); + + /* Not necessarily supported, ignore if not supported. + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::SetProperty", result); + } + */ + + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true); + } + + // What buttons and axes does it have? + IDirectInputDevice8_EnumObjects(joystick->hwdata->InputDevice, + EnumDevObjectsCallback, joystick, + DIDFT_BUTTON | DIDFT_AXIS | DIDFT_POV); + + /* Reorder the input objects. Some devices do not report the X axis as + * the first axis, for example. */ + SortDevObjects(joystick); + + dipdw.diph.dwObj = 0; + dipdw.diph.dwHow = DIPH_DEVICE; + dipdw.dwData = INPUT_QSIZE; + + // Set the buffer size + result = + IDirectInputDevice8_SetProperty(joystick->hwdata->InputDevice, + DIPROP_BUFFERSIZE, &dipdw.diph); + + if (result == DI_POLLEDDEVICE) { + /* This device doesn't support buffering, so we're forced + * to use less reliable polling. */ + joystick->hwdata->buffered = false; + } else if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::SetProperty", result); + } + joystick->hwdata->first_update = true; + + // Poll and wait for initial device state to be populated + result = IDirectInputDevice8_Poll(joystick->hwdata->InputDevice); + if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { + IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice); + IDirectInputDevice8_Poll(joystick->hwdata->InputDevice); + } + SDL_Delay(50); + + return true; +} + +static bool SDL_DINPUT_JoystickInitRumble(SDL_Joystick *joystick, Sint16 magnitude) +{ + HRESULT result; + + // Reset and then enable actuators + result = IDirectInputDevice8_SendForceFeedbackCommand(joystick->hwdata->InputDevice, DISFFC_RESET); + if (result == DIERR_INPUTLOST || result == DIERR_NOTEXCLUSIVEACQUIRED) { + result = IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice); + if (SUCCEEDED(result)) { + result = IDirectInputDevice8_SendForceFeedbackCommand(joystick->hwdata->InputDevice, DISFFC_RESET); + } + } + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::SendForceFeedbackCommand(DISFFC_RESET)", result); + } + + result = IDirectInputDevice8_SendForceFeedbackCommand(joystick->hwdata->InputDevice, DISFFC_SETACTUATORSON); + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::SendForceFeedbackCommand(DISFFC_SETACTUATORSON)", result); + } + + // Create the effect + joystick->hwdata->ffeffect = CreateRumbleEffectData(magnitude); + if (!joystick->hwdata->ffeffect) { + return false; + } + + result = IDirectInputDevice8_CreateEffect(joystick->hwdata->InputDevice, &GUID_Sine, + joystick->hwdata->ffeffect, &joystick->hwdata->ffeffect_ref, NULL); + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::CreateEffect", result); + } + return true; +} + +bool SDL_DINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + HRESULT result; + + // Scale and average the two rumble strengths + Sint16 magnitude = (Sint16)(((low_frequency_rumble / 2) + (high_frequency_rumble / 2)) / 2); + + if (!(joystick->hwdata->Capabilities.dwFlags & DIDC_FORCEFEEDBACK)) { + return SDL_Unsupported(); + } + + if (joystick->hwdata->ff_initialized) { + DIPERIODIC *periodic = ((DIPERIODIC *)joystick->hwdata->ffeffect->lpvTypeSpecificParams); + periodic->dwMagnitude = CONVERT_MAGNITUDE(magnitude); + + result = IDirectInputEffect_SetParameters(joystick->hwdata->ffeffect_ref, joystick->hwdata->ffeffect, (DIEP_DURATION | DIEP_TYPESPECIFICPARAMS)); + if (result == DIERR_INPUTLOST) { + result = IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice); + if (SUCCEEDED(result)) { + result = IDirectInputEffect_SetParameters(joystick->hwdata->ffeffect_ref, joystick->hwdata->ffeffect, (DIEP_DURATION | DIEP_TYPESPECIFICPARAMS)); + } + } + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::SetParameters", result); + } + } else { + if (!SDL_DINPUT_JoystickInitRumble(joystick, magnitude)) { + return false; + } + joystick->hwdata->ff_initialized = true; + } + + result = IDirectInputEffect_Start(joystick->hwdata->ffeffect_ref, 1, 0); + if (result == DIERR_INPUTLOST || result == DIERR_NOTEXCLUSIVEACQUIRED) { + result = IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice); + if (SUCCEEDED(result)) { + result = IDirectInputEffect_Start(joystick->hwdata->ffeffect_ref, 1, 0); + } + } + if (FAILED(result)) { + return SetDIerror("IDirectInputDevice8::Start", result); + } + return true; +} + +static Uint8 TranslatePOV(DWORD value) +{ + const Uint8 HAT_VALS[] = { + SDL_HAT_UP, + SDL_HAT_UP | SDL_HAT_RIGHT, + SDL_HAT_RIGHT, + SDL_HAT_DOWN | SDL_HAT_RIGHT, + SDL_HAT_DOWN, + SDL_HAT_DOWN | SDL_HAT_LEFT, + SDL_HAT_LEFT, + SDL_HAT_UP | SDL_HAT_LEFT + }; + + if (LOWORD(value) == 0xFFFF) { + return SDL_HAT_CENTERED; + } + + // Round the value up: + value += 4500 / 2; + value %= 36000; + value /= 4500; + + if (value >= 8) { + return SDL_HAT_CENTERED; // shouldn't happen + } + + return HAT_VALS[value]; +} + +/* Function to update the state of a joystick - called as a device poll. + * This function shouldn't update the joystick structure directly, + * but instead should call SDL_PrivateJoystick*() to deliver events + * and update joystick device state. + */ +static void UpdateDINPUTJoystickState_Polled(SDL_Joystick *joystick) +{ + DIJOYSTATE2 state; + HRESULT result; + int i; + Uint64 timestamp = SDL_GetTicksNS(); + + result = + IDirectInputDevice8_GetDeviceState(joystick->hwdata->InputDevice, + sizeof(DIJOYSTATE2), &state); + if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { + IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice); + result = + IDirectInputDevice8_GetDeviceState(joystick->hwdata->InputDevice, + sizeof(DIJOYSTATE2), &state); + } + + if (result != DI_OK) { + return; + } + + // Set each known axis, button and POV. + for (i = 0; i < joystick->hwdata->NumInputs; ++i) { + const input_t *in = &joystick->hwdata->Inputs[i]; + + switch (in->type) { + case AXIS: + switch (in->ofs) { + case DIJOFS_X: + SDL_SendJoystickAxis(timestamp, joystick, in->num, (Sint16)state.lX); + break; + case DIJOFS_Y: + SDL_SendJoystickAxis(timestamp, joystick, in->num, (Sint16)state.lY); + break; + case DIJOFS_Z: + SDL_SendJoystickAxis(timestamp, joystick, in->num, (Sint16)state.lZ); + break; + case DIJOFS_RX: + SDL_SendJoystickAxis(timestamp, joystick, in->num, (Sint16)state.lRx); + break; + case DIJOFS_RY: + SDL_SendJoystickAxis(timestamp, joystick, in->num, (Sint16)state.lRy); + break; + case DIJOFS_RZ: + SDL_SendJoystickAxis(timestamp, joystick, in->num, (Sint16)state.lRz); + break; + case DIJOFS_SLIDER(0): + SDL_SendJoystickAxis(timestamp, joystick, in->num, (Sint16)state.rglSlider[0]); + break; + case DIJOFS_SLIDER(1): + SDL_SendJoystickAxis(timestamp, joystick, in->num, (Sint16)state.rglSlider[1]); + break; + } + break; + + case BUTTON: + SDL_SendJoystickButton(timestamp, joystick, in->num, + (state.rgbButtons[in->ofs - DIJOFS_BUTTON0] != 0)); + break; + case HAT: + { + Uint8 pos = TranslatePOV(state.rgdwPOV[in->ofs - DIJOFS_POV(0)]); + SDL_SendJoystickHat(timestamp, joystick, in->num, pos); + break; + } + } + } +} + +static void UpdateDINPUTJoystickState_Buffered(SDL_Joystick *joystick) +{ + int i; + HRESULT result; + DWORD numevents; + DIDEVICEOBJECTDATA evtbuf[INPUT_QSIZE]; + Uint64 timestamp = SDL_GetTicksNS(); + + numevents = INPUT_QSIZE; + result = + IDirectInputDevice8_GetDeviceData(joystick->hwdata->InputDevice, + sizeof(DIDEVICEOBJECTDATA), evtbuf, + &numevents, 0); + if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { + IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice); + result = + IDirectInputDevice8_GetDeviceData(joystick->hwdata->InputDevice, + sizeof(DIDEVICEOBJECTDATA), + evtbuf, &numevents, 0); + } + + // Handle the events or punt + if (FAILED(result)) { + return; + } + + for (i = 0; i < (int)numevents; ++i) { + int j; + + for (j = 0; j < joystick->hwdata->NumInputs; ++j) { + const input_t *in = &joystick->hwdata->Inputs[j]; + + if (evtbuf[i].dwOfs != in->ofs) { + continue; + } + + switch (in->type) { + case AXIS: + SDL_SendJoystickAxis(timestamp, joystick, in->num, (Sint16)evtbuf[i].dwData); + break; + case BUTTON: + SDL_SendJoystickButton(timestamp, joystick, in->num, + (evtbuf[i].dwData != 0)); + break; + case HAT: + { + Uint8 pos = TranslatePOV(evtbuf[i].dwData); + SDL_SendJoystickHat(timestamp, joystick, in->num, pos); + } break; + } + } + } + + if (result == DI_BUFFEROVERFLOW) { + /* Our buffer wasn't big enough to hold all the queued events, + * so poll the device to make sure we have the complete state. + */ + UpdateDINPUTJoystickState_Polled(joystick); + } +} + +void SDL_DINPUT_JoystickUpdate(SDL_Joystick *joystick) +{ + HRESULT result; + + result = IDirectInputDevice8_Poll(joystick->hwdata->InputDevice); + if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { + IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice); + IDirectInputDevice8_Poll(joystick->hwdata->InputDevice); + } + + if (joystick->hwdata->first_update) { + // Poll to get the initial state of the joystick + UpdateDINPUTJoystickState_Polled(joystick); + joystick->hwdata->first_update = false; + return; + } + + if (joystick->hwdata->buffered ) { + UpdateDINPUTJoystickState_Buffered(joystick); + } else { + UpdateDINPUTJoystickState_Polled(joystick); + } +} + +void SDL_DINPUT_JoystickClose(SDL_Joystick *joystick) +{ + if (joystick->hwdata->ffeffect_ref) { + IDirectInputEffect_Unload(joystick->hwdata->ffeffect_ref); + joystick->hwdata->ffeffect_ref = NULL; + } + if (joystick->hwdata->ffeffect) { + FreeRumbleEffectData(joystick->hwdata->ffeffect); + joystick->hwdata->ffeffect = NULL; + } + IDirectInputDevice8_Unacquire(joystick->hwdata->InputDevice); + IDirectInputDevice8_Release(joystick->hwdata->InputDevice); + joystick->hwdata->ff_initialized = false; +} + +void SDL_DINPUT_JoystickQuit(void) +{ + if (dinput != NULL) { + IDirectInput8_Release(dinput); + dinput = NULL; + } + + if (coinitialized) { + WIN_CoUninitialize(); + coinitialized = false; + } +} + +#else // !SDL_JOYSTICK_DINPUT + +typedef struct JoyStick_DeviceData JoyStick_DeviceData; + +bool SDL_DINPUT_JoystickInit(void) +{ + return true; +} + +void SDL_DINPUT_JoystickDetect(JoyStick_DeviceData **pContext) +{ +} + +bool SDL_DINPUT_JoystickPresent(Uint16 vendor, Uint16 product, Uint16 version) +{ + return false; +} + +bool SDL_DINPUT_JoystickOpen(SDL_Joystick *joystick, JoyStick_DeviceData *joystickdevice) +{ + return SDL_Unsupported(); +} + +bool SDL_DINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + return SDL_Unsupported(); +} + +void SDL_DINPUT_JoystickUpdate(SDL_Joystick *joystick) +{ +} + +void SDL_DINPUT_JoystickClose(SDL_Joystick *joystick) +{ +} + +void SDL_DINPUT_JoystickQuit(void) +{ +} + +#endif // SDL_JOYSTICK_DINPUT diff --git a/thirdparty/sdl/joystick/windows/SDL_dinputjoystick_c.h b/thirdparty/sdl/joystick/windows/SDL_dinputjoystick_c.h new file mode 100644 index 00000000000..0643ce10244 --- /dev/null +++ b/thirdparty/sdl/joystick/windows/SDL_dinputjoystick_c.h @@ -0,0 +1,40 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +extern bool SDL_DINPUT_JoystickInit(void); +extern void SDL_DINPUT_JoystickDetect(JoyStick_DeviceData **pContext); +extern bool SDL_DINPUT_JoystickPresent(Uint16 vendor, Uint16 product, Uint16 version); +extern bool SDL_DINPUT_JoystickOpen(SDL_Joystick *joystick, JoyStick_DeviceData *joystickdevice); +extern bool SDL_DINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble); +extern void SDL_DINPUT_JoystickUpdate(SDL_Joystick *joystick); +extern void SDL_DINPUT_JoystickClose(SDL_Joystick *joystick); +extern void SDL_DINPUT_JoystickQuit(void); + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif diff --git a/thirdparty/sdl/joystick/windows/SDL_rawinputjoystick.c b/thirdparty/sdl/joystick/windows/SDL_rawinputjoystick.c new file mode 100644 index 00000000000..8590d9a8361 --- /dev/null +++ b/thirdparty/sdl/joystick/windows/SDL_rawinputjoystick.c @@ -0,0 +1,2242 @@ +/* + Simple DirectMedia Layer + Copyright (C) 2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + +*/ +/* + RAWINPUT Joystick API for better handling XInput-capable devices on Windows. + + XInput is limited to 4 devices. + Windows.Gaming.Input does not get inputs from XBox One controllers when not in the foreground. + DirectInput does not get inputs from XBox One controllers when not in the foreground, nor rumble or accurate triggers. + RawInput does not get rumble or accurate triggers. + + So, combine them as best we can! +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_RAWINPUT + +#include "../usb_ids.h" +#include "../SDL_sysjoystick.h" +#include "../../core/windows/SDL_windows.h" +#include "../../core/windows/SDL_hid.h" +#include "../hidapi/SDL_hidapijoystick_c.h" + +/* SDL_JOYSTICK_RAWINPUT_XINPUT is disabled because using XInput at the same time as + raw input will turn off the Xbox Series X controller when it is connected via the + Xbox One Wireless Adapter. + */ +#ifdef HAVE_XINPUT_H +#define SDL_JOYSTICK_RAWINPUT_XINPUT +#endif +#ifdef HAVE_WINDOWS_GAMING_INPUT_H +#define SDL_JOYSTICK_RAWINPUT_WGI +#endif + +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT +#include "../../core/windows/SDL_xinput.h" +#endif + +#ifdef SDL_JOYSTICK_RAWINPUT_WGI +#include "../../core/windows/SDL_windows.h" +typedef struct WindowsGamingInputGamepadState WindowsGamingInputGamepadState; +#define GamepadButtons_GUIDE 0x40000000 +#define COBJMACROS +#include "windows.gaming.input.h" +#include +#endif + +#if defined(SDL_JOYSTICK_RAWINPUT_XINPUT) || defined(SDL_JOYSTICK_RAWINPUT_WGI) +#define SDL_JOYSTICK_RAWINPUT_MATCHING +#define SDL_JOYSTICK_RAWINPUT_MATCH_AXES +#define SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS +#define SDL_JOYSTICK_RAWINPUT_MATCH_COUNT 6 // stick + trigger axes +#else +#define SDL_JOYSTICK_RAWINPUT_MATCH_COUNT 4 // stick axes +#endif +#endif + +#if 0 +#define DEBUG_RAWINPUT +#endif + +#ifndef RIDEV_EXINPUTSINK +#define RIDEV_EXINPUTSINK 0x00001000 +#define RIDEV_DEVNOTIFY 0x00002000 +#endif + +#ifndef WM_INPUT_DEVICE_CHANGE +#define WM_INPUT_DEVICE_CHANGE 0x00FE +#endif +#ifndef WM_INPUT +#define WM_INPUT 0x00FF +#endif +#ifndef GIDC_ARRIVAL +#define GIDC_ARRIVAL 1 +#define GIDC_REMOVAL 2 +#endif + +extern void WINDOWS_RAWINPUTEnabledChanged(void); +extern void WINDOWS_JoystickDetect(void); + +static bool SDL_RAWINPUT_inited = false; +static bool SDL_RAWINPUT_remote_desktop = false; +static int SDL_RAWINPUT_numjoysticks = 0; + +static void RAWINPUT_JoystickClose(SDL_Joystick *joystick); + +typedef struct SDL_RAWINPUT_Device +{ + SDL_AtomicInt refcount; + char *name; + char *path; + Uint16 vendor_id; + Uint16 product_id; + Uint16 version; + SDL_GUID guid; + bool is_xinput; + bool is_xboxone; + int steam_virtual_gamepad_slot; + PHIDP_PREPARSED_DATA preparsed_data; + + HANDLE hDevice; + SDL_Joystick *joystick; + SDL_JoystickID joystick_id; + + struct SDL_RAWINPUT_Device *next; +} SDL_RAWINPUT_Device; + +struct joystick_hwdata +{ + bool is_xinput; + bool is_xboxone; + PHIDP_PREPARSED_DATA preparsed_data; + ULONG max_data_length; + HIDP_DATA *data; + USHORT *button_indices; + USHORT *axis_indices; + USHORT *hat_indices; + bool guide_hack; + bool trigger_hack; + USHORT trigger_hack_index; + +#ifdef SDL_JOYSTICK_RAWINPUT_MATCHING + Uint64 match_state; // Lowest 16 bits for button states, higher 24 for 6 4bit axes + Uint64 last_state_packet; +#endif + +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + bool xinput_enabled; + bool xinput_correlated; + Uint8 xinput_correlation_id; + Uint8 xinput_correlation_count; + Uint8 xinput_uncorrelate_count; + Uint8 xinput_slot; +#endif + +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + bool wgi_correlated; + Uint8 wgi_correlation_id; + Uint8 wgi_correlation_count; + Uint8 wgi_uncorrelate_count; + WindowsGamingInputGamepadState *wgi_slot; + struct __x_ABI_CWindows_CGaming_CInput_CGamepadVibration vibration; +#endif + + bool triggers_rumbling; + + SDL_RAWINPUT_Device *device; +}; +typedef struct joystick_hwdata RAWINPUT_DeviceContext; + +SDL_RAWINPUT_Device *SDL_RAWINPUT_devices; + +static const Uint16 subscribed_devices[] = { + USB_USAGE_GENERIC_GAMEPAD, + /* Don't need Joystick for any devices we're handling here (XInput-capable) + USB_USAGE_GENERIC_JOYSTICK, + USB_USAGE_GENERIC_MULTIAXISCONTROLLER, + */ +}; + +#ifdef SDL_JOYSTICK_RAWINPUT_MATCHING + +static struct +{ + Uint64 last_state_packet; + SDL_Joystick *joystick; + SDL_Joystick *last_joystick; +} guide_button_candidate; + +typedef struct WindowsMatchState +{ +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES + SHORT match_axes[SDL_JOYSTICK_RAWINPUT_MATCH_COUNT]; +#endif +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + WORD xinput_buttons; +#endif +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + Uint32 wgi_buttons; +#endif + bool any_data; +} WindowsMatchState; + +static void RAWINPUT_FillMatchState(WindowsMatchState *state, Uint64 match_state) +{ +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES + int ii; +#endif + + bool any_axes_data = false; +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES + /* SHORT state->match_axes[4] = { + (match_state & 0x000F0000) >> 4, + (match_state & 0x00F00000) >> 8, + (match_state & 0x0F000000) >> 12, + (match_state & 0xF0000000) >> 16, + }; */ + for (ii = 0; ii < 4; ii++) { + state->match_axes[ii] = (SHORT)((match_state & (0x000F0000ull << (ii * 4))) >> (4 + ii * 4)); + any_axes_data |= ((Uint32)(state->match_axes[ii] + 0x1000) > 0x2000); // match_state bit is not 0xF, 0x1, or 0x2 + } +#endif // SDL_JOYSTICK_RAWINPUT_MATCH_AXES +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS + for (; ii < SDL_JOYSTICK_RAWINPUT_MATCH_COUNT; ii++) { + state->match_axes[ii] = (SHORT)((match_state & (0x000F0000ull << (ii * 4))) >> (4 + ii * 4)); + any_axes_data |= (state->match_axes[ii] != SDL_MIN_SINT16); + } +#endif // SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS + + state->any_data = any_axes_data; + +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + // Match axes by checking if the distance between the high 4 bits of axis and the 4 bits from match_state is 1 or less +#define XInputAxesMatch(gamepad) ( \ + (Uint32)(gamepad.sThumbLX - state->match_axes[0] + 0x1000) <= 0x2fff && \ + (Uint32)(~gamepad.sThumbLY - state->match_axes[1] + 0x1000) <= 0x2fff && \ + (Uint32)(gamepad.sThumbRX - state->match_axes[2] + 0x1000) <= 0x2fff && \ + (Uint32)(~gamepad.sThumbRY - state->match_axes[3] + 0x1000) <= 0x2fff) + /* Explicit +#define XInputAxesMatch(gamepad) (\ + SDL_abs((Sint8)((gamepad.sThumbLX & 0xF000) >> 8) - ((match_state & 0x000F0000) >> 12)) <= 0x10 && \ + SDL_abs((Sint8)((~gamepad.sThumbLY & 0xF000) >> 8) - ((match_state & 0x00F00000) >> 16)) <= 0x10 && \ + SDL_abs((Sint8)((gamepad.sThumbRX & 0xF000) >> 8) - ((match_state & 0x0F000000) >> 20)) <= 0x10 && \ + SDL_abs((Sint8)((~gamepad.sThumbRY & 0xF000) >> 8) - ((match_state & 0xF0000000) >> 24)) <= 0x10) */ + + // Can only match trigger values if a single trigger has a value. +#define XInputTriggersMatch(gamepad) ( \ + ((state->match_axes[4] == SDL_MIN_SINT16) && (state->match_axes[5] == SDL_MIN_SINT16)) || \ + ((gamepad.bLeftTrigger != 0) && (gamepad.bRightTrigger != 0)) || \ + ((Uint32)((((int)gamepad.bLeftTrigger * 257) - 32768) - state->match_axes[4]) <= 0x2fff) || \ + ((Uint32)((((int)gamepad.bRightTrigger * 257) - 32768) - state->match_axes[5]) <= 0x2fff)) + + state->xinput_buttons = + // Bitwise map .RLDUWVQTS.KYXBA -> YXBA..WVQTKSRLDU + (WORD)(match_state << 12 | (match_state & 0x0780) >> 1 | (match_state & 0x0010) << 1 | (match_state & 0x0040) >> 2 | (match_state & 0x7800) >> 11); + /* Explicit + ((match_state & (1<xinput_buttons) { + state->any_data = true; + } +#endif + +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + // Match axes by checking if the distance between the high 4 bits of axis and the 4 bits from match_state is 1 or less +#define WindowsGamingInputAxesMatch(gamepad) ( \ + (Uint16)(((Sint16)(gamepad.LeftThumbstickX * SDL_MAX_SINT16) & 0xF000) - state->match_axes[0] + 0x1000) <= 0x2fff && \ + (Uint16)((~(Sint16)(gamepad.LeftThumbstickY * SDL_MAX_SINT16) & 0xF000) - state->match_axes[1] + 0x1000) <= 0x2fff && \ + (Uint16)(((Sint16)(gamepad.RightThumbstickX * SDL_MAX_SINT16) & 0xF000) - state->match_axes[2] + 0x1000) <= 0x2fff && \ + (Uint16)((~(Sint16)(gamepad.RightThumbstickY * SDL_MAX_SINT16) & 0xF000) - state->match_axes[3] + 0x1000) <= 0x2fff) + +#define WindowsGamingInputTriggersMatch(gamepad) ( \ + ((state->match_axes[4] == SDL_MIN_SINT16) && (state->match_axes[5] == SDL_MIN_SINT16)) || \ + ((gamepad.LeftTrigger == 0.0f) && (gamepad.RightTrigger == 0.0f)) || \ + ((Uint16)((((int)(gamepad.LeftTrigger * SDL_MAX_UINT16)) - 32768) - state->match_axes[4]) <= 0x2fff) || \ + ((Uint16)((((int)(gamepad.RightTrigger * SDL_MAX_UINT16)) - 32768) - state->match_axes[5]) <= 0x2fff)) + + state->wgi_buttons = + // Bitwise map .RLD UWVQ TS.K YXBA -> ..QT WVRL DUYX BAKS + // RStick/LStick (QT) RShould/LShould (WV) DPad R/L/D/U YXBA bac(K) (S)tart + (match_state & 0x0180) << 5 | (match_state & 0x0600) << 1 | (match_state & 0x7800) >> 5 | (match_state & 0x000F) << 2 | (match_state & 0x0010) >> 3 | (match_state & 0x0040) >> 6; + /* Explicit + ((match_state & (1<wgi_buttons) { + state->any_data = true; + } +#endif +} + +#endif // SDL_JOYSTICK_RAWINPUT_MATCHING + +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + +static struct +{ + XINPUT_STATE state; + XINPUT_BATTERY_INFORMATION_EX battery; + bool connected; // Currently has an active XInput device + bool used; // Is currently mapped to an SDL device + Uint8 correlation_id; +} xinput_state[XUSER_MAX_COUNT]; +static bool xinput_device_change = true; +static bool xinput_state_dirty = true; + +static void RAWINPUT_UpdateXInput(void) +{ + DWORD user_index; + if (xinput_device_change) { + for (user_index = 0; user_index < XUSER_MAX_COUNT; user_index++) { + XINPUT_CAPABILITIES capabilities; + xinput_state[user_index].connected = (XINPUTGETCAPABILITIES(user_index, XINPUT_FLAG_GAMEPAD, &capabilities) == ERROR_SUCCESS); + } + xinput_device_change = false; + xinput_state_dirty = true; + } + if (xinput_state_dirty) { + xinput_state_dirty = false; + for (user_index = 0; user_index < SDL_arraysize(xinput_state); ++user_index) { + if (xinput_state[user_index].connected) { + if (XINPUTGETSTATE(user_index, &xinput_state[user_index].state) != ERROR_SUCCESS) { + xinput_state[user_index].connected = false; + } + xinput_state[user_index].battery.BatteryType = BATTERY_TYPE_UNKNOWN; + if (XINPUTGETBATTERYINFORMATION) { + XINPUTGETBATTERYINFORMATION(user_index, BATTERY_DEVTYPE_GAMEPAD, &xinput_state[user_index].battery); + } + } + } + } +} + +static void RAWINPUT_MarkXInputSlotUsed(Uint8 xinput_slot) +{ + if (xinput_slot != XUSER_INDEX_ANY) { + xinput_state[xinput_slot].used = true; + } +} + +static void RAWINPUT_MarkXInputSlotFree(Uint8 xinput_slot) +{ + if (xinput_slot != XUSER_INDEX_ANY) { + xinput_state[xinput_slot].used = false; + } +} +static bool RAWINPUT_MissingXInputSlot(void) +{ + int ii; + for (ii = 0; ii < SDL_arraysize(xinput_state); ii++) { + if (xinput_state[ii].connected && !xinput_state[ii].used) { + return true; + } + } + return false; +} + +static bool RAWINPUT_XInputSlotMatches(const WindowsMatchState *state, Uint8 slot_idx) +{ + if (xinput_state[slot_idx].connected) { + WORD xinput_buttons = xinput_state[slot_idx].state.Gamepad.wButtons; + if ((xinput_buttons & ~XINPUT_GAMEPAD_GUIDE) == state->xinput_buttons +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES + && XInputAxesMatch(xinput_state[slot_idx].state.Gamepad) +#endif +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS + && XInputTriggersMatch(xinput_state[slot_idx].state.Gamepad) +#endif + ) { + return true; + } + } + return false; +} + +static bool RAWINPUT_GuessXInputSlot(const WindowsMatchState *state, Uint8 *correlation_id, Uint8 *slot_idx) +{ + Uint8 user_index; + int match_count; + + /* If there is only one available slot, let's use that + * That will be right most of the time, and uncorrelation will fix any bad guesses + */ + match_count = 0; + for (user_index = 0; user_index < XUSER_MAX_COUNT; ++user_index) { + if (xinput_state[user_index].connected && !xinput_state[user_index].used) { + *slot_idx = user_index; + ++match_count; + } + } + if (match_count == 1) { + *correlation_id = ++xinput_state[*slot_idx].correlation_id; + return true; + } + + *slot_idx = 0; + + match_count = 0; + for (user_index = 0; user_index < XUSER_MAX_COUNT; ++user_index) { + if (!xinput_state[user_index].used && RAWINPUT_XInputSlotMatches(state, user_index)) { + ++match_count; + *slot_idx = user_index; + // Incrementing correlation_id for any match, as negative evidence for others being correlated + *correlation_id = ++xinput_state[user_index].correlation_id; + } + } + /* Only return a match if we match exactly one, and we have some non-zero data (buttons or axes) that matched. + Note that we're still invalidating *other* potential correlations if we have more than one match or we have no + data. */ + if (match_count == 1 && state->any_data) { + return true; + } + return false; +} + +#endif // SDL_JOYSTICK_RAWINPUT_XINPUT + +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + +typedef struct WindowsGamingInputGamepadState +{ + __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad; + struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading state; + RAWINPUT_DeviceContext *correlated_context; + bool used; // Is currently mapped to an SDL device + bool connected; // Just used during update to track disconnected + Uint8 correlation_id; +} WindowsGamingInputGamepadState; + +static struct +{ + WindowsGamingInputGamepadState **per_gamepad; + int per_gamepad_count; + bool initialized; + bool dirty; + bool need_device_list_update; + int ref_count; + __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics *gamepad_statics; + EventRegistrationToken gamepad_added_token; + EventRegistrationToken gamepad_removed_token; +} wgi_state; + +typedef struct GamepadDelegate +{ + __FIEventHandler_1_Windows__CGaming__CInput__CGamepad iface; + SDL_AtomicInt refcount; +} GamepadDelegate; + +static const IID IID_IEventHandler_Gamepad = { 0x8a7639ee, 0x624a, 0x501a, { 0xbb, 0x53, 0x56, 0x2d, 0x1e, 0xc1, 0x1b, 0x52 } }; + +static HRESULT STDMETHODCALLTYPE IEventHandler_CGamepadVtbl_QueryInterface(__FIEventHandler_1_Windows__CGaming__CInput__CGamepad *This, REFIID riid, void **ppvObject) +{ + if (!ppvObject) { + return E_INVALIDARG; + } + + *ppvObject = NULL; + if (WIN_IsEqualIID(riid, &IID_IUnknown) || WIN_IsEqualIID(riid, &IID_IAgileObject) || WIN_IsEqualIID(riid, &IID_IEventHandler_Gamepad)) { + *ppvObject = This; + __FIEventHandler_1_Windows__CGaming__CInput__CGamepad_AddRef(This); + return S_OK; + } else if (WIN_IsEqualIID(riid, &IID_IMarshal)) { + // This seems complicated. Let's hope it doesn't happen. + return E_OUTOFMEMORY; + } else { + return E_NOINTERFACE; + } +} + +static ULONG STDMETHODCALLTYPE IEventHandler_CGamepadVtbl_AddRef(__FIEventHandler_1_Windows__CGaming__CInput__CGamepad *This) +{ + GamepadDelegate *self = (GamepadDelegate *)This; + return SDL_AddAtomicInt(&self->refcount, 1) + 1UL; +} + +static ULONG STDMETHODCALLTYPE IEventHandler_CGamepadVtbl_Release(__FIEventHandler_1_Windows__CGaming__CInput__CGamepad *This) +{ + GamepadDelegate *self = (GamepadDelegate *)This; + int rc = SDL_AddAtomicInt(&self->refcount, -1) - 1; + // Should never free the static delegate objects + SDL_assert(rc > 0); + return rc; +} + +static HRESULT STDMETHODCALLTYPE IEventHandler_CGamepadVtbl_InvokeAdded(__FIEventHandler_1_Windows__CGaming__CInput__CGamepad *This, IInspectable *sender, __x_ABI_CWindows_CGaming_CInput_CIGamepad *e) +{ + wgi_state.need_device_list_update = true; + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE IEventHandler_CGamepadVtbl_InvokeRemoved(__FIEventHandler_1_Windows__CGaming__CInput__CGamepad *This, IInspectable *sender, __x_ABI_CWindows_CGaming_CInput_CIGamepad *e) +{ + wgi_state.need_device_list_update = true; + return S_OK; +} + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4028) // formal parameter 3 different from declaration, when using older buggy WGI headers +#pragma warning(disable : 4113) // X differs in parameter lists from Y, when using older buggy WGI headers +#endif + +static __FIEventHandler_1_Windows__CGaming__CInput__CGamepadVtbl gamepad_added_vtbl = { + IEventHandler_CGamepadVtbl_QueryInterface, + IEventHandler_CGamepadVtbl_AddRef, + IEventHandler_CGamepadVtbl_Release, + IEventHandler_CGamepadVtbl_InvokeAdded +}; +static GamepadDelegate gamepad_added = { + { &gamepad_added_vtbl }, + { 1 } +}; + +static __FIEventHandler_1_Windows__CGaming__CInput__CGamepadVtbl gamepad_removed_vtbl = { + IEventHandler_CGamepadVtbl_QueryInterface, + IEventHandler_CGamepadVtbl_AddRef, + IEventHandler_CGamepadVtbl_Release, + IEventHandler_CGamepadVtbl_InvokeRemoved +}; +static GamepadDelegate gamepad_removed = { + { &gamepad_removed_vtbl }, + { 1 } +}; + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +static void RAWINPUT_MarkWindowsGamingInputSlotUsed(WindowsGamingInputGamepadState *wgi_slot, RAWINPUT_DeviceContext *ctx) +{ + wgi_slot->used = true; + wgi_slot->correlated_context = ctx; +} + +static void RAWINPUT_MarkWindowsGamingInputSlotFree(WindowsGamingInputGamepadState *wgi_slot) +{ + wgi_slot->used = false; + wgi_slot->correlated_context = NULL; +} + +static bool RAWINPUT_MissingWindowsGamingInputSlot(void) +{ + int ii; + for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) { + if (!wgi_state.per_gamepad[ii]->used) { + return true; + } + } + return false; +} + +static bool RAWINPUT_UpdateWindowsGamingInput(void) +{ + int ii; + if (!wgi_state.gamepad_statics) { + return true; + } + + if (!wgi_state.dirty) { + return true; + } + + wgi_state.dirty = false; + + if (wgi_state.need_device_list_update) { + HRESULT hr; + __FIVectorView_1_Windows__CGaming__CInput__CGamepad *gamepads; + wgi_state.need_device_list_update = false; + for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) { + wgi_state.per_gamepad[ii]->connected = false; + } + + hr = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_get_Gamepads(wgi_state.gamepad_statics, &gamepads); + if (SUCCEEDED(hr)) { + unsigned int num_gamepads; + + hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_get_Size(gamepads, &num_gamepads); + if (SUCCEEDED(hr)) { + unsigned int i; + for (i = 0; i < num_gamepads; ++i) { + __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad; + + hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_GetAt(gamepads, i, &gamepad); + if (SUCCEEDED(hr)) { + bool found = false; + int jj; + for (jj = 0; jj < wgi_state.per_gamepad_count; jj++) { + if (wgi_state.per_gamepad[jj]->gamepad == gamepad) { + found = true; + wgi_state.per_gamepad[jj]->connected = true; + break; + } + } + if (!found) { + // New device, add it + WindowsGamingInputGamepadState *gamepad_state; + WindowsGamingInputGamepadState **new_per_gamepad; + gamepad_state = SDL_calloc(1, sizeof(*gamepad_state)); + if (!gamepad_state) { + return false; + } + new_per_gamepad = SDL_realloc(wgi_state.per_gamepad, sizeof(wgi_state.per_gamepad[0]) * (wgi_state.per_gamepad_count + 1)); + if (!new_per_gamepad) { + SDL_free(gamepad_state); + return false; + } + wgi_state.per_gamepad = new_per_gamepad; + wgi_state.per_gamepad_count++; + wgi_state.per_gamepad[wgi_state.per_gamepad_count - 1] = gamepad_state; + gamepad_state->gamepad = gamepad; + gamepad_state->connected = true; + } else { + // Already tracked + __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad); + } + } + } + for (ii = wgi_state.per_gamepad_count - 1; ii >= 0; ii--) { + WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[ii]; + if (!gamepad_state->connected) { + // Device missing, must be disconnected + if (gamepad_state->correlated_context) { + gamepad_state->correlated_context->wgi_correlated = false; + gamepad_state->correlated_context->wgi_slot = NULL; + } + __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad_state->gamepad); + SDL_free(gamepad_state); + wgi_state.per_gamepad[ii] = wgi_state.per_gamepad[wgi_state.per_gamepad_count - 1]; + --wgi_state.per_gamepad_count; + } + } + } + __FIVectorView_1_Windows__CGaming__CInput__CGamepad_Release(gamepads); + } + } // need_device_list_update + + for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) { + HRESULT hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_GetCurrentReading(wgi_state.per_gamepad[ii]->gamepad, &wgi_state.per_gamepad[ii]->state); + if (!SUCCEEDED(hr)) { + wgi_state.per_gamepad[ii]->connected = false; // Not used by anything, currently + } + } + return true; +} +static void RAWINPUT_InitWindowsGamingInput(RAWINPUT_DeviceContext *ctx) +{ + if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_WGI, true)) { + return; + } + + wgi_state.ref_count++; + if (!wgi_state.initialized) { + static const IID SDL_IID_IGamepadStatics = { 0x8BBCE529, 0xD49C, 0x39E9, { 0x95, 0x60, 0xE4, 0x7D, 0xDE, 0x96, 0xB7, 0xC8 } }; + HRESULT hr; + + if (FAILED(WIN_RoInitialize())) { + return; + } + wgi_state.initialized = true; + wgi_state.dirty = true; + + { + typedef HRESULT(WINAPI * WindowsCreateStringReference_t)(PCWSTR sourceString, UINT32 length, HSTRING_HEADER * hstringHeader, HSTRING * string); + typedef HRESULT(WINAPI * RoGetActivationFactory_t)(HSTRING activatableClassId, REFIID iid, void **factory); + + WindowsCreateStringReference_t WindowsCreateStringReferenceFunc = (WindowsCreateStringReference_t)WIN_LoadComBaseFunction("WindowsCreateStringReference"); + RoGetActivationFactory_t RoGetActivationFactoryFunc = (RoGetActivationFactory_t)WIN_LoadComBaseFunction("RoGetActivationFactory"); + if (WindowsCreateStringReferenceFunc && RoGetActivationFactoryFunc) { + PCWSTR pNamespace = L"Windows.Gaming.Input.Gamepad"; + HSTRING_HEADER hNamespaceStringHeader; + HSTRING hNamespaceString; + + hr = WindowsCreateStringReferenceFunc(pNamespace, (UINT32)SDL_wcslen(pNamespace), &hNamespaceStringHeader, &hNamespaceString); + if (SUCCEEDED(hr)) { + RoGetActivationFactoryFunc(hNamespaceString, &SDL_IID_IGamepadStatics, (void **)&wgi_state.gamepad_statics); + } + + if (wgi_state.gamepad_statics) { + wgi_state.need_device_list_update = true; + + hr = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_add_GamepadAdded(wgi_state.gamepad_statics, &gamepad_added.iface, &wgi_state.gamepad_added_token); + if (!SUCCEEDED(hr)) { + SDL_SetError("add_GamepadAdded() failed: 0x%lx", hr); + } + + hr = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_add_GamepadRemoved(wgi_state.gamepad_statics, &gamepad_removed.iface, &wgi_state.gamepad_removed_token); + if (!SUCCEEDED(hr)) { + SDL_SetError("add_GamepadRemoved() failed: 0x%lx", hr); + } + } + } + } + } +} + +static bool RAWINPUT_WindowsGamingInputSlotMatches(const WindowsMatchState *state, WindowsGamingInputGamepadState *slot, bool xinput_correlated) +{ + Uint32 wgi_buttons = slot->state.Buttons; + if ((wgi_buttons & 0x3FFF) == state->wgi_buttons +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES + && WindowsGamingInputAxesMatch(slot->state) +#endif +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS + // Don't try to match WGI triggers if getting values from XInput + && (xinput_correlated || WindowsGamingInputTriggersMatch(slot->state)) +#endif + ) { + return true; + } + return false; +} + +static bool RAWINPUT_GuessWindowsGamingInputSlot(const WindowsMatchState *state, Uint8 *correlation_id, WindowsGamingInputGamepadState **slot, bool xinput_correlated) +{ + int match_count, user_index; + WindowsGamingInputGamepadState *gamepad_state = NULL; + + /* If there is only one available slot, let's use that + * That will be right most of the time, and uncorrelation will fix any bad guesses + */ + match_count = 0; + for (user_index = 0; user_index < wgi_state.per_gamepad_count; ++user_index) { + gamepad_state = wgi_state.per_gamepad[user_index]; + if (gamepad_state->connected && !gamepad_state->used) { + *slot = gamepad_state; + ++match_count; + } + } + if (match_count == 1) { + *correlation_id = ++gamepad_state->correlation_id; + return true; + } + + match_count = 0; + for (user_index = 0; user_index < wgi_state.per_gamepad_count; ++user_index) { + gamepad_state = wgi_state.per_gamepad[user_index]; + if (RAWINPUT_WindowsGamingInputSlotMatches(state, gamepad_state, xinput_correlated)) { + ++match_count; + *slot = gamepad_state; + // Incrementing correlation_id for any match, as negative evidence for others being correlated + *correlation_id = ++gamepad_state->correlation_id; + } + } + /* Only return a match if we match exactly one, and we have some non-zero data (buttons or axes) that matched. + Note that we're still invalidating *other* potential correlations if we have more than one match or we have no + data. */ + if (match_count == 1 && state->any_data) { + return true; + } + return false; +} + +static void RAWINPUT_QuitWindowsGamingInput(RAWINPUT_DeviceContext *ctx) +{ + --wgi_state.ref_count; + if (!wgi_state.ref_count && wgi_state.initialized) { + int ii; + for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) { + __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(wgi_state.per_gamepad[ii]->gamepad); + } + if (wgi_state.per_gamepad) { + SDL_free(wgi_state.per_gamepad); + wgi_state.per_gamepad = NULL; + } + wgi_state.per_gamepad_count = 0; + if (wgi_state.gamepad_statics) { + __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_remove_GamepadAdded(wgi_state.gamepad_statics, wgi_state.gamepad_added_token); + __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_remove_GamepadRemoved(wgi_state.gamepad_statics, wgi_state.gamepad_removed_token); + __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_Release(wgi_state.gamepad_statics); + wgi_state.gamepad_statics = NULL; + } + WIN_RoUninitialize(); + wgi_state.initialized = false; + } +} + +#endif // SDL_JOYSTICK_RAWINPUT_WGI + +static SDL_RAWINPUT_Device *RAWINPUT_AcquireDevice(SDL_RAWINPUT_Device *device) +{ + SDL_AtomicIncRef(&device->refcount); + return device; +} + +static void RAWINPUT_ReleaseDevice(SDL_RAWINPUT_Device *device) +{ +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + if (device->joystick) { + RAWINPUT_DeviceContext *ctx = device->joystick->hwdata; + + if (ctx->xinput_enabled && ctx->xinput_correlated) { + RAWINPUT_MarkXInputSlotFree(ctx->xinput_slot); + ctx->xinput_correlated = false; + } + } +#endif // SDL_JOYSTICK_RAWINPUT_XINPUT + + if (SDL_AtomicDecRef(&device->refcount)) { + SDL_free(device->preparsed_data); + SDL_free(device->name); + SDL_free(device->path); + SDL_free(device); + } +} + +static SDL_RAWINPUT_Device *RAWINPUT_DeviceFromHandle(HANDLE hDevice) +{ + SDL_RAWINPUT_Device *curr; + + for (curr = SDL_RAWINPUT_devices; curr; curr = curr->next) { + if (curr->hDevice == hDevice) { + return curr; + } + } + return NULL; +} + +static int GetSteamVirtualGamepadSlot(Uint16 vendor_id, Uint16 product_id, const char *device_path) +{ + int slot = -1; + + // The format for the raw input device path is documented here: + // https://partner.steamgames.com/doc/features/steam_controller/steam_input_gamepad_emulation_bestpractices + if (vendor_id == USB_VENDOR_VALVE && + product_id == USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD) { + (void)SDL_sscanf(device_path, "\\\\.\\pipe\\HID#VID_045E&PID_028E&IG_00#%*X&%*X&%*X#%d#%*u", &slot); + } + return slot; +} + +static void RAWINPUT_AddDevice(HANDLE hDevice) +{ +#define CHECK(expression) \ + { \ + if (!(expression)) \ + goto err; \ + } + SDL_RAWINPUT_Device *device = NULL; + SDL_RAWINPUT_Device *curr, *last; + RID_DEVICE_INFO rdi; + UINT size; + char dev_name[MAX_PATH] = { 0 }; + HANDLE hFile = INVALID_HANDLE_VALUE; + + // Make sure we're not trying to add the same device twice + if (RAWINPUT_DeviceFromHandle(hDevice)) { + return; + } + + // Figure out what kind of device it is + size = sizeof(rdi); + SDL_zero(rdi); + CHECK(GetRawInputDeviceInfoA(hDevice, RIDI_DEVICEINFO, &rdi, &size) != (UINT)-1); + CHECK(rdi.dwType == RIM_TYPEHID); + + // Get the device "name" (HID Path) + size = SDL_arraysize(dev_name); + CHECK(GetRawInputDeviceInfoA(hDevice, RIDI_DEVICENAME, dev_name, &size) != (UINT)-1); + // Only take XInput-capable devices + CHECK(SDL_strstr(dev_name, "IG_") != NULL); + CHECK(!SDL_ShouldIgnoreJoystick((Uint16)rdi.hid.dwVendorId, (Uint16)rdi.hid.dwProductId, (Uint16)rdi.hid.dwVersionNumber, "")); + CHECK(!SDL_JoystickHandledByAnotherDriver(&SDL_RAWINPUT_JoystickDriver, (Uint16)rdi.hid.dwVendorId, (Uint16)rdi.hid.dwProductId, (Uint16)rdi.hid.dwVersionNumber, "")); + + device = (SDL_RAWINPUT_Device *)SDL_calloc(1, sizeof(SDL_RAWINPUT_Device)); + CHECK(device); + device->hDevice = hDevice; + device->vendor_id = (Uint16)rdi.hid.dwVendorId; + device->product_id = (Uint16)rdi.hid.dwProductId; + device->version = (Uint16)rdi.hid.dwVersionNumber; + device->is_xinput = true; + device->is_xboxone = SDL_IsJoystickXboxOne(device->vendor_id, device->product_id); + device->steam_virtual_gamepad_slot = GetSteamVirtualGamepadSlot(device->vendor_id, device->product_id, dev_name); + + // Get HID Top-Level Collection Preparsed Data + size = 0; + CHECK(GetRawInputDeviceInfoA(hDevice, RIDI_PREPARSEDDATA, NULL, &size) != (UINT)-1); + device->preparsed_data = (PHIDP_PREPARSED_DATA)SDL_calloc(size, sizeof(BYTE)); + CHECK(device->preparsed_data); + CHECK(GetRawInputDeviceInfoA(hDevice, RIDI_PREPARSEDDATA, device->preparsed_data, &size) != (UINT)-1); + + hFile = CreateFileA(dev_name, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + CHECK(hFile != INVALID_HANDLE_VALUE); + + { + char *manufacturer_string = NULL; + char *product_string = NULL; + WCHAR string[128]; + + string[0] = 0; + if (SDL_HidD_GetManufacturerString(hFile, string, sizeof(string))) { + manufacturer_string = WIN_StringToUTF8W(string); + } + string[0] = 0; + if (SDL_HidD_GetProductString(hFile, string, sizeof(string))) { + product_string = WIN_StringToUTF8W(string); + } + + device->name = SDL_CreateJoystickName(device->vendor_id, device->product_id, manufacturer_string, product_string); + device->guid = SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_USB, device->vendor_id, device->product_id, device->version, manufacturer_string, product_string, 'r', 0); + + if (manufacturer_string) { + SDL_free(manufacturer_string); + } + if (product_string) { + SDL_free(product_string); + } + } + + device->path = SDL_strdup(dev_name); + + CloseHandle(hFile); + hFile = INVALID_HANDLE_VALUE; + + device->joystick_id = SDL_GetNextObjectID(); + +#ifdef DEBUG_RAWINPUT + SDL_Log("Adding RAWINPUT device '%s' VID 0x%.4x, PID 0x%.4x, version %d, handle 0x%.8x", device->name, device->vendor_id, device->product_id, device->version, device->hDevice); +#endif + + // Add it to the list + RAWINPUT_AcquireDevice(device); + for (curr = SDL_RAWINPUT_devices, last = NULL; curr; last = curr, curr = curr->next) { + } + if (last) { + last->next = device; + } else { + SDL_RAWINPUT_devices = device; + } + + ++SDL_RAWINPUT_numjoysticks; + + SDL_PrivateJoystickAdded(device->joystick_id); + + return; + +err: + if (hFile != INVALID_HANDLE_VALUE) { + CloseHandle(hFile); + } + if (device) { + if (device->name) { + SDL_free(device->name); + } + if (device->path) { + SDL_free(device->path); + } + SDL_free(device); + } +#undef CHECK +} + +static void RAWINPUT_DelDevice(SDL_RAWINPUT_Device *device, bool send_event) +{ + SDL_RAWINPUT_Device *curr, *last; + for (curr = SDL_RAWINPUT_devices, last = NULL; curr; last = curr, curr = curr->next) { + if (curr == device) { + if (last) { + last->next = curr->next; + } else { + SDL_RAWINPUT_devices = curr->next; + } + --SDL_RAWINPUT_numjoysticks; + + SDL_PrivateJoystickRemoved(device->joystick_id); + +#ifdef DEBUG_RAWINPUT + SDL_Log("Removing RAWINPUT device '%s' VID 0x%.4x, PID 0x%.4x, version %d, handle %p", device->name, device->vendor_id, device->product_id, device->version, device->hDevice); +#endif + RAWINPUT_ReleaseDevice(device); + return; + } + } +} + +static void RAWINPUT_DetectDevices(void) +{ + UINT device_count = 0; + + if ((GetRawInputDeviceList(NULL, &device_count, sizeof(RAWINPUTDEVICELIST)) != -1) && device_count > 0) { + PRAWINPUTDEVICELIST devices = NULL; + UINT i; + + devices = (PRAWINPUTDEVICELIST)SDL_malloc(sizeof(RAWINPUTDEVICELIST) * device_count); + if (devices) { + device_count = GetRawInputDeviceList(devices, &device_count, sizeof(RAWINPUTDEVICELIST)); + if (device_count != (UINT)-1) { + for (i = 0; i < device_count; ++i) { + RAWINPUT_AddDevice(devices[i].hDevice); + } + } + SDL_free(devices); + } + } +} + +static void RAWINPUT_RemoveDevices(void) +{ + while (SDL_RAWINPUT_devices) { + RAWINPUT_DelDevice(SDL_RAWINPUT_devices, false); + } + SDL_assert(SDL_RAWINPUT_numjoysticks == 0); +} + +static bool RAWINPUT_JoystickInit(void) +{ + SDL_assert(!SDL_RAWINPUT_inited); + + if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_RAWINPUT, false)) { + return true; + } + + if (!WIN_IsWindowsVistaOrGreater()) { + // According to bug 6400, this doesn't work on Windows XP + return false; + } + + if (!WIN_LoadHIDDLL()) { + return false; + } + + SDL_RAWINPUT_inited = true; + + RAWINPUT_DetectDevices(); + + return true; +} + +static int RAWINPUT_JoystickGetCount(void) +{ + return SDL_RAWINPUT_numjoysticks; +} + +bool RAWINPUT_IsEnabled(void) +{ + return SDL_RAWINPUT_inited && !SDL_RAWINPUT_remote_desktop; +} + +static void RAWINPUT_PostUpdate(void) +{ +#ifdef SDL_JOYSTICK_RAWINPUT_MATCHING + bool unmapped_guide_pressed = false; + +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + if (!wgi_state.dirty) { + int ii; + for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) { + WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[ii]; + if (!gamepad_state->used && (gamepad_state->state.Buttons & GamepadButtons_GUIDE)) { + unmapped_guide_pressed = true; + break; + } + } + } + wgi_state.dirty = true; +#endif + +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + if (!xinput_state_dirty) { + int ii; + for (ii = 0; ii < SDL_arraysize(xinput_state); ii++) { + if (xinput_state[ii].connected && !xinput_state[ii].used && (xinput_state[ii].state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE)) { + unmapped_guide_pressed = true; + break; + } + } + } + xinput_state_dirty = true; +#endif + + if (unmapped_guide_pressed) { + if (guide_button_candidate.joystick && !guide_button_candidate.last_joystick) { + SDL_Joystick *joystick = guide_button_candidate.joystick; + RAWINPUT_DeviceContext *ctx = joystick->hwdata; + if (ctx->guide_hack) { + int guide_button = joystick->nbuttons - 1; + + SDL_SendJoystickButton(SDL_GetTicksNS(), guide_button_candidate.joystick, (Uint8)guide_button, true); + } + guide_button_candidate.last_joystick = guide_button_candidate.joystick; + } + } else if (guide_button_candidate.last_joystick) { + SDL_Joystick *joystick = guide_button_candidate.last_joystick; + RAWINPUT_DeviceContext *ctx = joystick->hwdata; + if (ctx->guide_hack) { + int guide_button = joystick->nbuttons - 1; + + SDL_SendJoystickButton(SDL_GetTicksNS(), joystick, (Uint8)guide_button, false); + } + guide_button_candidate.last_joystick = NULL; + } + guide_button_candidate.joystick = NULL; + +#endif // SDL_JOYSTICK_RAWINPUT_MATCHING +} + +static void RAWINPUT_JoystickDetect(void) +{ + bool remote_desktop; + + if (!SDL_RAWINPUT_inited) { + return; + } + + remote_desktop = GetSystemMetrics(SM_REMOTESESSION) ? true : false; + if (remote_desktop != SDL_RAWINPUT_remote_desktop) { + SDL_RAWINPUT_remote_desktop = remote_desktop; + + WINDOWS_RAWINPUTEnabledChanged(); + + if (remote_desktop) { + RAWINPUT_RemoveDevices(); + WINDOWS_JoystickDetect(); + } else { + WINDOWS_JoystickDetect(); + RAWINPUT_DetectDevices(); + } + } + RAWINPUT_PostUpdate(); +} + +static bool RAWINPUT_JoystickIsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ + SDL_RAWINPUT_Device *device; + + // If we're being asked about a device, that means another API just detected one, so rescan +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + xinput_device_change = true; +#endif + + device = SDL_RAWINPUT_devices; + while (device) { + if (vendor_id == device->vendor_id && product_id == device->product_id) { + return true; + } + + /* The Xbox 360 wireless controller shows up as product 0 in WGI. + Try to match it to a Raw Input device via name or known product ID. */ + if (vendor_id == device->vendor_id && product_id == 0 && + ((name && SDL_strstr(device->name, name) != NULL) || + (device->vendor_id == USB_VENDOR_MICROSOFT && + device->product_id == USB_PRODUCT_XBOX360_XUSB_CONTROLLER))) { + return true; + } + + // The Xbox One controller shows up as a hardcoded raw input VID/PID + if (name && SDL_strcmp(name, "Xbox One Game Controller") == 0 && + device->vendor_id == USB_VENDOR_MICROSOFT && + device->product_id == USB_PRODUCT_XBOX_ONE_XBOXGIP_CONTROLLER) { + return true; + } + + device = device->next; + } + return false; +} + +static SDL_RAWINPUT_Device *RAWINPUT_GetDeviceByIndex(int device_index) +{ + SDL_RAWINPUT_Device *device = SDL_RAWINPUT_devices; + while (device) { + if (device_index == 0) { + break; + } + --device_index; + device = device->next; + } + return device; +} + +static const char *RAWINPUT_JoystickGetDeviceName(int device_index) +{ + return RAWINPUT_GetDeviceByIndex(device_index)->name; +} + +static const char *RAWINPUT_JoystickGetDevicePath(int device_index) +{ + return RAWINPUT_GetDeviceByIndex(device_index)->path; +} + +static int RAWINPUT_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index) +{ + return RAWINPUT_GetDeviceByIndex(device_index)->steam_virtual_gamepad_slot; +} + +static int RAWINPUT_JoystickGetDevicePlayerIndex(int device_index) +{ + return false; +} + +static void RAWINPUT_JoystickSetDevicePlayerIndex(int device_index, int player_index) +{ +} + +static SDL_GUID RAWINPUT_JoystickGetDeviceGUID(int device_index) +{ + return RAWINPUT_GetDeviceByIndex(device_index)->guid; +} + +static SDL_JoystickID RAWINPUT_JoystickGetDeviceInstanceID(int device_index) +{ + return RAWINPUT_GetDeviceByIndex(device_index)->joystick_id; +} + +static int SDLCALL RAWINPUT_SortValueCaps(const void *A, const void *B) +{ + HIDP_VALUE_CAPS *capsA = (HIDP_VALUE_CAPS *)A; + HIDP_VALUE_CAPS *capsB = (HIDP_VALUE_CAPS *)B; + + // Sort by Usage for single values, or UsageMax for range of values + return (int)capsA->NotRange.Usage - capsB->NotRange.Usage; +} + +static bool RAWINPUT_JoystickOpen(SDL_Joystick *joystick, int device_index) +{ + SDL_RAWINPUT_Device *device = RAWINPUT_GetDeviceByIndex(device_index); + RAWINPUT_DeviceContext *ctx; + HIDP_CAPS caps; + HIDP_BUTTON_CAPS *button_caps; + HIDP_VALUE_CAPS *value_caps; + ULONG i; + + ctx = (RAWINPUT_DeviceContext *)SDL_calloc(1, sizeof(RAWINPUT_DeviceContext)); + if (!ctx) { + return false; + } + joystick->hwdata = ctx; + + ctx->device = RAWINPUT_AcquireDevice(device); + device->joystick = joystick; + + if (device->is_xinput) { + // We'll try to get guide button and trigger axes from XInput +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + xinput_device_change = true; + ctx->xinput_enabled = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT, true); + if (ctx->xinput_enabled && (!WIN_LoadXInputDLL() || !XINPUTGETSTATE)) { + ctx->xinput_enabled = false; + } + ctx->xinput_slot = XUSER_INDEX_ANY; +#endif +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + RAWINPUT_InitWindowsGamingInput(ctx); +#endif + } + + ctx->is_xinput = device->is_xinput; + ctx->is_xboxone = device->is_xboxone; +#ifdef SDL_JOYSTICK_RAWINPUT_MATCHING + ctx->match_state = 0x0000008800000000ULL; // Trigger axes at rest +#endif + ctx->preparsed_data = device->preparsed_data; + ctx->max_data_length = SDL_HidP_MaxDataListLength(HidP_Input, ctx->preparsed_data); + ctx->data = (HIDP_DATA *)SDL_malloc(ctx->max_data_length * sizeof(*ctx->data)); + if (!ctx->data) { + RAWINPUT_JoystickClose(joystick); + return false; + } + + if (SDL_HidP_GetCaps(ctx->preparsed_data, &caps) != HIDP_STATUS_SUCCESS) { + RAWINPUT_JoystickClose(joystick); + return SDL_SetError("Couldn't get device capabilities"); + } + + button_caps = SDL_stack_alloc(HIDP_BUTTON_CAPS, caps.NumberInputButtonCaps); + if (SDL_HidP_GetButtonCaps(HidP_Input, button_caps, &caps.NumberInputButtonCaps, ctx->preparsed_data) != HIDP_STATUS_SUCCESS) { + RAWINPUT_JoystickClose(joystick); + return SDL_SetError("Couldn't get device button capabilities"); + } + + value_caps = SDL_stack_alloc(HIDP_VALUE_CAPS, caps.NumberInputValueCaps); + if (SDL_HidP_GetValueCaps(HidP_Input, value_caps, &caps.NumberInputValueCaps, ctx->preparsed_data) != HIDP_STATUS_SUCCESS) { + RAWINPUT_JoystickClose(joystick); + SDL_stack_free(button_caps); + return SDL_SetError("Couldn't get device value capabilities"); + } + + // Sort the axes by usage, so X comes before Y, etc. + SDL_qsort(value_caps, caps.NumberInputValueCaps, sizeof(*value_caps), RAWINPUT_SortValueCaps); + + for (i = 0; i < caps.NumberInputButtonCaps; ++i) { + HIDP_BUTTON_CAPS *cap = &button_caps[i]; + + if (cap->UsagePage == USB_USAGEPAGE_BUTTON) { + int count; + + if (cap->IsRange) { + count = 1 + (cap->Range.DataIndexMax - cap->Range.DataIndexMin); + } else { + count = 1; + } + + joystick->nbuttons += count; + } + } + + if (joystick->nbuttons > 0) { + int button_index = 0; + + ctx->button_indices = (USHORT *)SDL_malloc(joystick->nbuttons * sizeof(*ctx->button_indices)); + if (!ctx->button_indices) { + RAWINPUT_JoystickClose(joystick); + SDL_stack_free(value_caps); + SDL_stack_free(button_caps); + return false; + } + + for (i = 0; i < caps.NumberInputButtonCaps; ++i) { + HIDP_BUTTON_CAPS *cap = &button_caps[i]; + + if (cap->UsagePage == USB_USAGEPAGE_BUTTON) { + if (cap->IsRange) { + int j, count = 1 + (cap->Range.DataIndexMax - cap->Range.DataIndexMin); + + for (j = 0; j < count; ++j) { + ctx->button_indices[button_index++] = (USHORT)(cap->Range.DataIndexMin + j); + } + } else { + ctx->button_indices[button_index++] = cap->NotRange.DataIndex; + } + } + } + } + if (ctx->is_xinput && joystick->nbuttons == 10) { + ctx->guide_hack = true; + joystick->nbuttons += 1; + } + + SDL_stack_free(button_caps); + + for (i = 0; i < caps.NumberInputValueCaps; ++i) { + HIDP_VALUE_CAPS *cap = &value_caps[i]; + + if (cap->IsRange) { + continue; + } + + if (ctx->trigger_hack && cap->NotRange.Usage == USB_USAGE_GENERIC_Z) { + continue; + } + + if (cap->NotRange.Usage == USB_USAGE_GENERIC_HAT) { + joystick->nhats += 1; + continue; + } + + if (ctx->is_xinput && cap->NotRange.Usage == USB_USAGE_GENERIC_Z) { + continue; + } + + joystick->naxes += 1; + } + + if (joystick->naxes > 0) { + int axis_index = 0; + + ctx->axis_indices = (USHORT *)SDL_malloc(joystick->naxes * sizeof(*ctx->axis_indices)); + if (!ctx->axis_indices) { + RAWINPUT_JoystickClose(joystick); + SDL_stack_free(value_caps); + return false; + } + + for (i = 0; i < caps.NumberInputValueCaps; ++i) { + HIDP_VALUE_CAPS *cap = &value_caps[i]; + + if (cap->IsRange) { + continue; + } + + if (cap->NotRange.Usage == USB_USAGE_GENERIC_HAT) { + continue; + } + + if (ctx->is_xinput && cap->NotRange.Usage == USB_USAGE_GENERIC_Z) { + ctx->trigger_hack = true; + ctx->trigger_hack_index = cap->NotRange.DataIndex; + continue; + } + + ctx->axis_indices[axis_index++] = cap->NotRange.DataIndex; + } + } + if (ctx->trigger_hack) { + joystick->naxes += 2; + } + + if (joystick->nhats > 0) { + int hat_index = 0; + + ctx->hat_indices = (USHORT *)SDL_malloc(joystick->nhats * sizeof(*ctx->hat_indices)); + if (!ctx->hat_indices) { + RAWINPUT_JoystickClose(joystick); + SDL_stack_free(value_caps); + return false; + } + + for (i = 0; i < caps.NumberInputValueCaps; ++i) { + HIDP_VALUE_CAPS *cap = &value_caps[i]; + + if (cap->IsRange) { + continue; + } + + if (cap->NotRange.Usage != USB_USAGE_GENERIC_HAT) { + continue; + } + + ctx->hat_indices[hat_index++] = cap->NotRange.DataIndex; + } + } + + SDL_stack_free(value_caps); + +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + if (ctx->is_xinput) { + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true); + } +#endif +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + if (ctx->is_xinput) { + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true); + + if (ctx->is_xboxone) { + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN, true); + } + } +#endif + + return true; +} + +static bool RAWINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ +#if defined(SDL_JOYSTICK_RAWINPUT_WGI) || defined(SDL_JOYSTICK_RAWINPUT_XINPUT) + RAWINPUT_DeviceContext *ctx = joystick->hwdata; +#endif + bool rumbled = false; + +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + // Prefer XInput over WGI because it allows rumble in the background + if (!rumbled && ctx->xinput_correlated && !ctx->triggers_rumbling) { + XINPUT_VIBRATION XVibration; + + if (!XINPUTSETSTATE) { + return SDL_Unsupported(); + } + + XVibration.wLeftMotorSpeed = low_frequency_rumble; + XVibration.wRightMotorSpeed = high_frequency_rumble; + if (XINPUTSETSTATE(ctx->xinput_slot, &XVibration) == ERROR_SUCCESS) { + rumbled = true; + } else { + return SDL_SetError("XInputSetState() failed"); + } + } +#endif // SDL_JOYSTICK_RAWINPUT_XINPUT + +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + // Save off the motor state in case trigger rumble is started + ctx->vibration.LeftMotor = (DOUBLE)low_frequency_rumble / SDL_MAX_UINT16; + ctx->vibration.RightMotor = (DOUBLE)high_frequency_rumble / SDL_MAX_UINT16; + if (!rumbled && ctx->wgi_correlated) { + WindowsGamingInputGamepadState *gamepad_state = ctx->wgi_slot; + HRESULT hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(gamepad_state->gamepad, ctx->vibration); + if (SUCCEEDED(hr)) { + rumbled = true; + } + } +#endif + + if (!rumbled) { +#if defined(SDL_JOYSTICK_RAWINPUT_WGI) || defined(SDL_JOYSTICK_RAWINPUT_XINPUT) + return SDL_SetError("Controller isn't correlated yet, try hitting a button first"); +#else + return SDL_Unsupported(); +#endif + } + return true; +} + +static bool RAWINPUT_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + RAWINPUT_DeviceContext *ctx = joystick->hwdata; + + ctx->vibration.LeftTrigger = (DOUBLE)left_rumble / SDL_MAX_UINT16; + ctx->vibration.RightTrigger = (DOUBLE)right_rumble / SDL_MAX_UINT16; + if (ctx->wgi_correlated) { + WindowsGamingInputGamepadState *gamepad_state = ctx->wgi_slot; + HRESULT hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(gamepad_state->gamepad, ctx->vibration); + if (!SUCCEEDED(hr)) { + return SDL_SetError("Setting vibration failed: 0x%lx", hr); + } + ctx->triggers_rumbling = (left_rumble > 0 || right_rumble > 0); + return true; + } else { + return SDL_SetError("Controller isn't correlated yet, try hitting a button first"); + } +#else + return SDL_Unsupported(); +#endif +} + +static bool RAWINPUT_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool RAWINPUT_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool RAWINPUT_JoystickSetSensorsEnabled(SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static HIDP_DATA *GetData(USHORT index, HIDP_DATA *data, ULONG length) +{ + ULONG i; + + // Check to see if the data is at the expected offset + if (index < length && data[index].DataIndex == index) { + return &data[index]; + } + + // Loop through the data to find it + for (i = 0; i < length; ++i) { + if (data[i].DataIndex == index) { + return &data[i]; + } + } + return NULL; +} + +/* This is the packet format for Xbox 360 and Xbox One controllers on Windows, + however with this interface there is no rumble support, no guide button, + and the left and right triggers are tied together as a single axis. + + We use XInput and Windows.Gaming.Input to make up for these shortcomings. + */ +static void RAWINPUT_HandleStatePacket(SDL_Joystick *joystick, Uint8 *data, int size) +{ + RAWINPUT_DeviceContext *ctx = joystick->hwdata; +#ifdef SDL_JOYSTICK_RAWINPUT_MATCHING + // Map new buttons and axes into game controller controls + static const int button_map[] = { + SDL_GAMEPAD_BUTTON_SOUTH, + SDL_GAMEPAD_BUTTON_EAST, + SDL_GAMEPAD_BUTTON_WEST, + SDL_GAMEPAD_BUTTON_NORTH, + SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, + SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, + SDL_GAMEPAD_BUTTON_BACK, + SDL_GAMEPAD_BUTTON_START, + SDL_GAMEPAD_BUTTON_LEFT_STICK, + SDL_GAMEPAD_BUTTON_RIGHT_STICK + }; +#define HAT_MASK ((1 << SDL_GAMEPAD_BUTTON_DPAD_UP) | (1 << SDL_GAMEPAD_BUTTON_DPAD_DOWN) | (1 << SDL_GAMEPAD_BUTTON_DPAD_LEFT) | (1 << SDL_GAMEPAD_BUTTON_DPAD_RIGHT)) + static const int hat_map[] = { + 0, + (1 << SDL_GAMEPAD_BUTTON_DPAD_UP), + (1 << SDL_GAMEPAD_BUTTON_DPAD_UP) | (1 << SDL_GAMEPAD_BUTTON_DPAD_RIGHT), + (1 << SDL_GAMEPAD_BUTTON_DPAD_RIGHT), + (1 << SDL_GAMEPAD_BUTTON_DPAD_DOWN) | (1 << SDL_GAMEPAD_BUTTON_DPAD_RIGHT), + (1 << SDL_GAMEPAD_BUTTON_DPAD_DOWN), + (1 << SDL_GAMEPAD_BUTTON_DPAD_DOWN) | (1 << SDL_GAMEPAD_BUTTON_DPAD_LEFT), + (1 << SDL_GAMEPAD_BUTTON_DPAD_LEFT), + (1 << SDL_GAMEPAD_BUTTON_DPAD_UP) | (1 << SDL_GAMEPAD_BUTTON_DPAD_LEFT), + 0, + }; + Uint64 match_state = ctx->match_state; + // Update match_state with button bit, then fall through +#define SDL_SendJoystickButton(timestamp, joystick, button, down) \ + if (button < SDL_arraysize(button_map)) { \ + Uint64 button_bit = 1ull << button_map[button]; \ + match_state = (match_state & ~button_bit) | (button_bit * (down)); \ + } \ + SDL_SendJoystickButton(timestamp, joystick, button, down) +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES + // Grab high 4 bits of value, then fall through +#define AddAxisToMatchState(axis, value) \ + { \ + match_state = (match_state & ~(0xFull << (4 * axis + 16))) | ((value)&0xF000ull) << (4 * axis + 4); \ + } +#define SDL_SendJoystickAxis(timestamp, joystick, axis, value) \ + if (axis < 4) \ + AddAxisToMatchState(axis, value); \ + SDL_SendJoystickAxis(timestamp, joystick, axis, value) +#endif +#endif // SDL_JOYSTICK_RAWINPUT_MATCHING + + ULONG data_length = ctx->max_data_length; + int i; + int nbuttons = joystick->nbuttons - (ctx->guide_hack * 1); + int naxes = joystick->naxes - (ctx->trigger_hack * 2); + int nhats = joystick->nhats; + Uint32 button_mask = 0; + Uint64 timestamp = SDL_GetTicksNS(); + + if (SDL_HidP_GetData(HidP_Input, ctx->data, &data_length, ctx->preparsed_data, (PCHAR)data, size) != HIDP_STATUS_SUCCESS) { + return; + } + + for (i = 0; i < nbuttons; ++i) { + HIDP_DATA *item = GetData(ctx->button_indices[i], ctx->data, data_length); + if (item && item->On) { + button_mask |= (1 << i); + } + } + for (i = 0; i < nbuttons; ++i) { + SDL_SendJoystickButton(timestamp, joystick, (Uint8)i, ((button_mask & (1 << i)) != 0)); + } + + for (i = 0; i < naxes; ++i) { + HIDP_DATA *item = GetData(ctx->axis_indices[i], ctx->data, data_length); + if (item) { + Sint16 axis = (int)(Uint16)item->RawValue - 0x8000; + SDL_SendJoystickAxis(timestamp, joystick, (Uint8)i, axis); + } + } + + for (i = 0; i < nhats; ++i) { + HIDP_DATA *item = GetData(ctx->hat_indices[i], ctx->data, data_length); + if (item) { + Uint8 hat = SDL_HAT_CENTERED; + const Uint8 hat_states[] = { + SDL_HAT_CENTERED, + SDL_HAT_UP, + SDL_HAT_UP | SDL_HAT_RIGHT, + SDL_HAT_RIGHT, + SDL_HAT_DOWN | SDL_HAT_RIGHT, + SDL_HAT_DOWN, + SDL_HAT_DOWN | SDL_HAT_LEFT, + SDL_HAT_LEFT, + SDL_HAT_UP | SDL_HAT_LEFT, + SDL_HAT_CENTERED, + }; + ULONG state = item->RawValue; + + if (state < SDL_arraysize(hat_states)) { +#ifdef SDL_JOYSTICK_RAWINPUT_MATCHING + match_state = (match_state & ~HAT_MASK) | hat_map[state]; +#endif + hat = hat_states[state]; + } + SDL_SendJoystickHat(timestamp, joystick, (Uint8)i, hat); + } + } + +#ifdef SDL_SendJoystickButton +#undef SDL_SendJoystickButton +#endif +#ifdef SDL_SendJoystickAxis +#undef SDL_SendJoystickAxis +#endif + +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS +#define AddTriggerToMatchState(axis, value) \ + { \ + int match_axis = axis + SDL_JOYSTICK_RAWINPUT_MATCH_COUNT - joystick->naxes; \ + AddAxisToMatchState(match_axis, value); \ + } +#endif // SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS + + if (ctx->trigger_hack) { + bool has_trigger_data = false; + int left_trigger = joystick->naxes - 2; + int right_trigger = joystick->naxes - 1; + +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + // Prefer XInput over WindowsGamingInput, it continues to provide data in the background + if (!has_trigger_data && ctx->xinput_enabled && ctx->xinput_correlated) { + has_trigger_data = true; + } +#endif // SDL_JOYSTICK_RAWINPUT_XINPUT + +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + if (!has_trigger_data && ctx->wgi_correlated) { + has_trigger_data = true; + } +#endif // SDL_JOYSTICK_RAWINPUT_WGI + +#ifndef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS + if (!has_trigger_data) +#endif + { + HIDP_DATA *item = GetData(ctx->trigger_hack_index, ctx->data, data_length); + if (item) { + Sint16 value = (int)(Uint16)item->RawValue - 0x8000; + Sint16 left_value = (value > 0) ? (value * 2 - 32767) : SDL_MIN_SINT16; + Sint16 right_value = (value < 0) ? (-value * 2 - 32769) : SDL_MIN_SINT16; + +#ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS + AddTriggerToMatchState(left_trigger, left_value); + AddTriggerToMatchState(right_trigger, right_value); + if (!has_trigger_data) +#endif // SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS + { + SDL_SendJoystickAxis(timestamp, joystick, (Uint8)left_trigger, left_value); + SDL_SendJoystickAxis(timestamp, joystick, (Uint8)right_trigger, right_value); + } + } + } + } + +#ifdef AddAxisToMatchState +#undef AddAxisToMatchState +#endif +#ifdef AddTriggerToMatchState +#undef AddTriggerToMatchState +#endif + +#ifdef SDL_JOYSTICK_RAWINPUT_MATCHING + if (ctx->is_xinput) { + ctx->match_state = match_state; + ctx->last_state_packet = SDL_GetTicks(); + } +#endif +} + +static void RAWINPUT_UpdateOtherAPIs(SDL_Joystick *joystick) +{ +#ifdef SDL_JOYSTICK_RAWINPUT_MATCHING + RAWINPUT_DeviceContext *ctx = joystick->hwdata; + bool has_trigger_data = false; + bool correlated = false; + WindowsMatchState match_state_xinput; + int guide_button = joystick->nbuttons - 1; + int left_trigger = joystick->naxes - 2; + int right_trigger = joystick->naxes - 1; +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + bool xinput_correlated; +#endif + + RAWINPUT_FillMatchState(&match_state_xinput, ctx->match_state); + +#ifdef SDL_JOYSTICK_RAWINPUT_WGI +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + xinput_correlated = ctx->xinput_correlated; +#else + xinput_correlated = false; +#endif + // Parallel logic to WINDOWS_XINPUT below + RAWINPUT_UpdateWindowsGamingInput(); + if (ctx->wgi_correlated && + !joystick->low_frequency_rumble && !joystick->high_frequency_rumble && + !joystick->left_trigger_rumble && !joystick->right_trigger_rumble) { + // We have been previously correlated, ensure we are still matching, see comments in XINPUT section + if (RAWINPUT_WindowsGamingInputSlotMatches(&match_state_xinput, ctx->wgi_slot, xinput_correlated)) { + ctx->wgi_uncorrelate_count = 0; + } else { + ++ctx->wgi_uncorrelate_count; + /* Only un-correlate if this is consistent over multiple Update() calls - the timing of polling/event + pumping can easily cause this to uncorrelate for a frame. 2 seemed reliable in my testing, but + let's set it to 5 to be safe. An incorrect un-correlation will simply result in lower precision + triggers for a frame. */ + if (ctx->wgi_uncorrelate_count >= 5) { +#ifdef DEBUG_RAWINPUT + SDL_Log("UN-Correlated joystick %d to WindowsGamingInput device #%d", joystick->instance_id, ctx->wgi_slot); +#endif + RAWINPUT_MarkWindowsGamingInputSlotFree(ctx->wgi_slot); + ctx->wgi_correlated = false; + ctx->wgi_correlation_count = 0; + // Force release of Guide button, it can't possibly be down on this device now. + /* It gets left down if we were actually correlated incorrectly and it was released on the WindowsGamingInput + device but we didn't get a state packet. */ + if (ctx->guide_hack) { + SDL_SendJoystickButton(0, joystick, (Uint8)guide_button, false); + } + } + } + } + if (!ctx->wgi_correlated) { + Uint8 new_correlation_count = 0; + if (RAWINPUT_MissingWindowsGamingInputSlot()) { + Uint8 correlation_id = 0; + WindowsGamingInputGamepadState *slot_idx = NULL; + if (RAWINPUT_GuessWindowsGamingInputSlot(&match_state_xinput, &correlation_id, &slot_idx, xinput_correlated)) { + // we match exactly one WindowsGamingInput device + /* Probably can do without wgi_correlation_count, just check and clear wgi_slot to NULL, unless we need + even more frames to be sure. */ + if (ctx->wgi_correlation_count && ctx->wgi_slot == slot_idx) { + // was correlated previously, and still the same device + if (ctx->wgi_correlation_id + 1 == correlation_id) { + // no one else was correlated in the meantime + new_correlation_count = ctx->wgi_correlation_count + 1; + if (new_correlation_count == 2) { + // correlation stayed steady and uncontested across multiple frames, guaranteed match + ctx->wgi_correlated = true; +#ifdef DEBUG_RAWINPUT + SDL_Log("Correlated joystick %d to WindowsGamingInput device #%d", joystick->instance_id, slot_idx); +#endif + correlated = true; + RAWINPUT_MarkWindowsGamingInputSlotUsed(ctx->wgi_slot, ctx); + // If the generalized Guide button was using us, it doesn't need to anymore + if (guide_button_candidate.joystick == joystick) { + guide_button_candidate.joystick = NULL; + } + if (guide_button_candidate.last_joystick == joystick) { + guide_button_candidate.last_joystick = NULL; + } + } + } else { + // someone else also possibly correlated to this device, start over + new_correlation_count = 1; + } + } else { + // new possible correlation + new_correlation_count = 1; + ctx->wgi_slot = slot_idx; + } + ctx->wgi_correlation_id = correlation_id; + } else { + // Match multiple WindowsGamingInput devices, or none (possibly due to no buttons pressed) + } + } + ctx->wgi_correlation_count = new_correlation_count; + } else { + correlated = true; + } +#endif // SDL_JOYSTICK_RAWINPUT_WGI + +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + // Parallel logic to WINDOWS_GAMING_INPUT above + if (ctx->xinput_enabled) { + RAWINPUT_UpdateXInput(); + if (ctx->xinput_correlated && + !joystick->low_frequency_rumble && !joystick->high_frequency_rumble) { + // We have been previously correlated, ensure we are still matching + /* This is required to deal with two (mostly) un-preventable mis-correlation situations: + A) Since the HID data stream does not provide an initial state (but polling XInput does), if we open + 5 controllers (#1-4 XInput mapped, #5 is not), and controller 1 had the A button down (and we don't + know), and the user presses A on controller #5, we'll see exactly 1 controller with A down (#5) and + exactly 1 XInput device with A down (#1), and incorrectly correlate. This code will then un-correlate + when A is released from either controller #1 or #5. + B) Since the app may not open all controllers, we could have a similar situation where only controller #5 + is opened, and the user holds A on controllers #1 and #5 simultaneously - again we see only 1 controller + with A down and 1 XInput device with A down, and incorrectly correlate. This should be very unusual + (only when apps do not open all controllers, yet are listening to Guide button presses, yet + for some reason want to ignore guide button presses on the un-opened controllers, yet users are + pressing buttons on the unopened controllers), and will resolve itself when either button is released + and we un-correlate. We could prevent this by processing the state packets for *all* controllers, + even un-opened ones, as that would allow more precise correlation. + */ + if (RAWINPUT_XInputSlotMatches(&match_state_xinput, ctx->xinput_slot)) { + ctx->xinput_uncorrelate_count = 0; + } else { + ++ctx->xinput_uncorrelate_count; + /* Only un-correlate if this is consistent over multiple Update() calls - the timing of polling/event + pumping can easily cause this to uncorrelate for a frame. 2 seemed reliable in my testing, but + let's set it to 5 to be safe. An incorrect un-correlation will simply result in lower precision + triggers for a frame. */ + if (ctx->xinput_uncorrelate_count >= 5) { +#ifdef DEBUG_RAWINPUT + SDL_Log("UN-Correlated joystick %d to XInput device #%d", joystick->instance_id, ctx->xinput_slot); +#endif + RAWINPUT_MarkXInputSlotFree(ctx->xinput_slot); + ctx->xinput_correlated = false; + ctx->xinput_correlation_count = 0; + // Force release of Guide button, it can't possibly be down on this device now. + /* It gets left down if we were actually correlated incorrectly and it was released on the XInput + device but we didn't get a state packet. */ + if (ctx->guide_hack) { + SDL_SendJoystickButton(0, joystick, (Uint8)guide_button, false); + } + } + } + } + if (!ctx->xinput_correlated) { + Uint8 new_correlation_count = 0; + if (RAWINPUT_MissingXInputSlot()) { + Uint8 correlation_id = 0; + Uint8 slot_idx = 0; + if (RAWINPUT_GuessXInputSlot(&match_state_xinput, &correlation_id, &slot_idx)) { + // we match exactly one XInput device + /* Probably can do without xinput_correlation_count, just check and clear xinput_slot to ANY, unless + we need even more frames to be sure */ + if (ctx->xinput_correlation_count && ctx->xinput_slot == slot_idx) { + // was correlated previously, and still the same device + if (ctx->xinput_correlation_id + 1 == correlation_id) { + // no one else was correlated in the meantime + new_correlation_count = ctx->xinput_correlation_count + 1; + if (new_correlation_count == 2) { + // correlation stayed steady and uncontested across multiple frames, guaranteed match + ctx->xinput_correlated = true; +#ifdef DEBUG_RAWINPUT + SDL_Log("Correlated joystick %d to XInput device #%d", joystick->instance_id, slot_idx); +#endif + correlated = true; + RAWINPUT_MarkXInputSlotUsed(ctx->xinput_slot); + // If the generalized Guide button was using us, it doesn't need to anymore + if (guide_button_candidate.joystick == joystick) { + guide_button_candidate.joystick = NULL; + } + if (guide_button_candidate.last_joystick == joystick) { + guide_button_candidate.last_joystick = NULL; + } + } + } else { + // someone else also possibly correlated to this device, start over + new_correlation_count = 1; + } + } else { + // new possible correlation + new_correlation_count = 1; + ctx->xinput_slot = slot_idx; + } + ctx->xinput_correlation_id = correlation_id; + } else { + // Match multiple XInput devices, or none (possibly due to no buttons pressed) + } + } + ctx->xinput_correlation_count = new_correlation_count; + } else { + correlated = true; + } + } +#endif // SDL_JOYSTICK_RAWINPUT_XINPUT + + // Poll for trigger data once (not per-state-packet) +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + // Prefer XInput over WindowsGamingInput, it continues to provide data in the background + if (!has_trigger_data && ctx->xinput_enabled && ctx->xinput_correlated) { + RAWINPUT_UpdateXInput(); + if (xinput_state[ctx->xinput_slot].connected) { + XINPUT_BATTERY_INFORMATION_EX *battery_info = &xinput_state[ctx->xinput_slot].battery; + Uint64 timestamp; + + if (ctx->guide_hack || ctx->trigger_hack) { + timestamp = SDL_GetTicksNS(); + } else { + // timestamp won't be used + timestamp = 0; + } + + if (ctx->guide_hack) { + bool down = ((xinput_state[ctx->xinput_slot].state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE) != 0); + SDL_SendJoystickButton(timestamp, joystick, (Uint8)guide_button, down); + } + if (ctx->trigger_hack) { + SDL_SendJoystickAxis(timestamp, joystick, (Uint8)left_trigger, ((int)xinput_state[ctx->xinput_slot].state.Gamepad.bLeftTrigger * 257) - 32768); + SDL_SendJoystickAxis(timestamp, joystick, (Uint8)right_trigger, ((int)xinput_state[ctx->xinput_slot].state.Gamepad.bRightTrigger * 257) - 32768); + } + has_trigger_data = true; + + SDL_PowerState state; + int percent; + switch (battery_info->BatteryType) { + case BATTERY_TYPE_WIRED: + state = SDL_POWERSTATE_CHARGING; + break; + case BATTERY_TYPE_UNKNOWN: + case BATTERY_TYPE_DISCONNECTED: + state = SDL_POWERSTATE_UNKNOWN; + break; + default: + state = SDL_POWERSTATE_ON_BATTERY; + break; + } + switch (battery_info->BatteryLevel) { + case BATTERY_LEVEL_EMPTY: + percent = 10; + break; + case BATTERY_LEVEL_LOW: + percent = 40; + break; + case BATTERY_LEVEL_MEDIUM: + percent = 70; + break; + default: + case BATTERY_LEVEL_FULL: + percent = 100; + break; + } + SDL_SendJoystickPowerInfo(joystick, state, percent); + } + } +#endif // SDL_JOYSTICK_RAWINPUT_XINPUT + +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + if (!has_trigger_data && ctx->wgi_correlated) { + RAWINPUT_UpdateWindowsGamingInput(); // May detect disconnect / cause uncorrelation + if (ctx->wgi_correlated) { // Still connected + struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading *state = &ctx->wgi_slot->state; + Uint64 timestamp; + + if (ctx->guide_hack || ctx->trigger_hack) { + timestamp = SDL_GetTicksNS(); + } else { + // timestamp won't be used + timestamp = 0; + } + + if (ctx->guide_hack) { + bool down = ((state->Buttons & GamepadButtons_GUIDE) != 0); + SDL_SendJoystickButton(timestamp, joystick, (Uint8)guide_button, down); + } + if (ctx->trigger_hack) { + SDL_SendJoystickAxis(timestamp, joystick, (Uint8)left_trigger, (Sint16)(((int)(state->LeftTrigger * SDL_MAX_UINT16)) - 32768)); + SDL_SendJoystickAxis(timestamp, joystick, (Uint8)right_trigger, (Sint16)(((int)(state->RightTrigger * SDL_MAX_UINT16)) - 32768)); + } + has_trigger_data = true; + } + } +#endif // SDL_JOYSTICK_RAWINPUT_WGI + + if (!correlated) { + if (!guide_button_candidate.joystick || + (ctx->last_state_packet && (!guide_button_candidate.last_state_packet || + ctx->last_state_packet >= guide_button_candidate.last_state_packet))) { + guide_button_candidate.joystick = joystick; + guide_button_candidate.last_state_packet = ctx->last_state_packet; + } + } +#endif // SDL_JOYSTICK_RAWINPUT_MATCHING +} + +static void RAWINPUT_JoystickUpdate(SDL_Joystick *joystick) +{ + RAWINPUT_UpdateOtherAPIs(joystick); +} + +static void RAWINPUT_JoystickClose(SDL_Joystick *joystick) +{ + RAWINPUT_DeviceContext *ctx = joystick->hwdata; + +#ifdef SDL_JOYSTICK_RAWINPUT_MATCHING + if (guide_button_candidate.joystick == joystick) { + guide_button_candidate.joystick = NULL; + } + if (guide_button_candidate.last_joystick == joystick) { + guide_button_candidate.last_joystick = NULL; + } +#endif + + if (ctx) { + SDL_RAWINPUT_Device *device; + +#ifdef SDL_JOYSTICK_RAWINPUT_XINPUT + xinput_device_change = true; + if (ctx->xinput_enabled) { + if (ctx->xinput_correlated) { + RAWINPUT_MarkXInputSlotFree(ctx->xinput_slot); + } + WIN_UnloadXInputDLL(); + } +#endif +#ifdef SDL_JOYSTICK_RAWINPUT_WGI + RAWINPUT_QuitWindowsGamingInput(ctx); +#endif + + device = ctx->device; + if (device) { + SDL_assert(device->joystick == joystick); + device->joystick = NULL; + RAWINPUT_ReleaseDevice(device); + } + + SDL_free(ctx->data); + SDL_free(ctx->button_indices); + SDL_free(ctx->axis_indices); + SDL_free(ctx->hat_indices); + SDL_free(ctx); + joystick->hwdata = NULL; + } +} + +bool RAWINPUT_RegisterNotifications(HWND hWnd) +{ + int i; + RAWINPUTDEVICE rid[SDL_arraysize(subscribed_devices)]; + + if (!SDL_RAWINPUT_inited) { + return true; + } + + for (i = 0; i < SDL_arraysize(subscribed_devices); i++) { + rid[i].usUsagePage = USB_USAGEPAGE_GENERIC_DESKTOP; + rid[i].usUsage = subscribed_devices[i]; + rid[i].dwFlags = RIDEV_DEVNOTIFY | RIDEV_INPUTSINK; // Receive messages when in background, including device add/remove + rid[i].hwndTarget = hWnd; + } + + if (!RegisterRawInputDevices(rid, SDL_arraysize(rid), sizeof(RAWINPUTDEVICE))) { + return SDL_SetError("Couldn't register for raw input events"); + } + return true; +} + +bool RAWINPUT_UnregisterNotifications(void) +{ + int i; + RAWINPUTDEVICE rid[SDL_arraysize(subscribed_devices)]; + + if (!SDL_RAWINPUT_inited) { + return true; + } + + for (i = 0; i < SDL_arraysize(subscribed_devices); i++) { + rid[i].usUsagePage = USB_USAGEPAGE_GENERIC_DESKTOP; + rid[i].usUsage = subscribed_devices[i]; + rid[i].dwFlags = RIDEV_REMOVE; + rid[i].hwndTarget = NULL; + } + + if (!RegisterRawInputDevices(rid, SDL_arraysize(rid), sizeof(RAWINPUTDEVICE))) { + return SDL_SetError("Couldn't unregister for raw input events"); + } + return true; +} + +LRESULT CALLBACK +RAWINPUT_WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + LRESULT result = -1; + + if (SDL_RAWINPUT_inited) { + SDL_LockJoysticks(); + + switch (msg) { + case WM_INPUT_DEVICE_CHANGE: + { + HANDLE hDevice = (HANDLE)lParam; + switch (wParam) { + case GIDC_ARRIVAL: + RAWINPUT_AddDevice(hDevice); + break; + case GIDC_REMOVAL: + { + SDL_RAWINPUT_Device *device; + device = RAWINPUT_DeviceFromHandle(hDevice); + if (device) { + RAWINPUT_DelDevice(device, true); + } + break; + } + default: + break; + } + } + result = 0; + break; + + case WM_INPUT: + { + Uint8 data[sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + USB_PACKET_LENGTH]; + UINT buffer_size = SDL_arraysize(data); + + if ((int)GetRawInputData((HRAWINPUT)lParam, RID_INPUT, data, &buffer_size, sizeof(RAWINPUTHEADER)) > 0) { + PRAWINPUT raw_input = (PRAWINPUT)data; + SDL_RAWINPUT_Device *device = RAWINPUT_DeviceFromHandle(raw_input->header.hDevice); + if (device) { + SDL_Joystick *joystick = device->joystick; + if (joystick) { + RAWINPUT_HandleStatePacket(joystick, raw_input->data.hid.bRawData, raw_input->data.hid.dwSizeHid); + } + } + } + } + result = 0; + break; + } + + SDL_UnlockJoysticks(); + } + + if (result >= 0) { + return result; + } + return CallWindowProc(DefWindowProc, hWnd, msg, wParam, lParam); +} + +static void RAWINPUT_JoystickQuit(void) +{ + if (!SDL_RAWINPUT_inited) { + return; + } + + RAWINPUT_RemoveDevices(); + + WIN_UnloadHIDDLL(); + + SDL_RAWINPUT_inited = false; +} + +static bool RAWINPUT_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) +{ + return false; +} + +SDL_JoystickDriver SDL_RAWINPUT_JoystickDriver = { + RAWINPUT_JoystickInit, + RAWINPUT_JoystickGetCount, + RAWINPUT_JoystickDetect, + RAWINPUT_JoystickIsDevicePresent, + RAWINPUT_JoystickGetDeviceName, + RAWINPUT_JoystickGetDevicePath, + RAWINPUT_JoystickGetDeviceSteamVirtualGamepadSlot, + RAWINPUT_JoystickGetDevicePlayerIndex, + RAWINPUT_JoystickSetDevicePlayerIndex, + RAWINPUT_JoystickGetDeviceGUID, + RAWINPUT_JoystickGetDeviceInstanceID, + RAWINPUT_JoystickOpen, + RAWINPUT_JoystickRumble, + RAWINPUT_JoystickRumbleTriggers, + RAWINPUT_JoystickSetLED, + RAWINPUT_JoystickSendEffect, + RAWINPUT_JoystickSetSensorsEnabled, + RAWINPUT_JoystickUpdate, + RAWINPUT_JoystickClose, + RAWINPUT_JoystickQuit, + RAWINPUT_JoystickGetGamepadMapping +}; + +#endif // SDL_JOYSTICK_RAWINPUT diff --git a/thirdparty/sdl/joystick/windows/SDL_rawinputjoystick_c.h b/thirdparty/sdl/joystick/windows/SDL_rawinputjoystick_c.h new file mode 100644 index 00000000000..b67544bd717 --- /dev/null +++ b/thirdparty/sdl/joystick/windows/SDL_rawinputjoystick_c.h @@ -0,0 +1,32 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" +#include "../../core/windows/SDL_windows.h" + +// Return true if the RawInput driver is enabled +extern bool RAWINPUT_IsEnabled(void); + +// Registers for input events +extern int RAWINPUT_RegisterNotifications(HWND hWnd); +extern int RAWINPUT_UnregisterNotifications(void); + +// Returns 0 if message was handled +extern LRESULT CALLBACK RAWINPUT_WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); diff --git a/thirdparty/sdl/joystick/windows/SDL_windows_gaming_input.c b/thirdparty/sdl/joystick/windows/SDL_windows_gaming_input.c new file mode 100644 index 00000000000..dbc5658ef54 --- /dev/null +++ b/thirdparty/sdl/joystick/windows/SDL_windows_gaming_input.c @@ -0,0 +1,1039 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_JOYSTICK_WGI + +#include "../SDL_sysjoystick.h" +#include "../hidapi/SDL_hidapijoystick_c.h" +#include "SDL_rawinputjoystick_c.h" + +#include "../../core/windows/SDL_windows.h" +#define COBJMACROS +#include "windows.gaming.input.h" +#include +#include +#include +#include + +#ifdef ____FIReference_1_INT32_INTERFACE_DEFINED__ +// MinGW-64 uses __FIReference_1_INT32 instead of Microsoft's __FIReference_1_int +#define __FIReference_1_int __FIReference_1_INT32 +#define __FIReference_1_int_get_Value __FIReference_1_INT32_get_Value +#define __FIReference_1_int_Release __FIReference_1_INT32_Release +#endif + +struct joystick_hwdata +{ + __x_ABI_CWindows_CGaming_CInput_CIRawGameController *controller; + __x_ABI_CWindows_CGaming_CInput_CIGameController *game_controller; + __x_ABI_CWindows_CGaming_CInput_CIGameControllerBatteryInfo *battery; + __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad; + __x_ABI_CWindows_CGaming_CInput_CGamepadVibration vibration; + UINT64 timestamp; +}; + +typedef struct WindowsGamingInputControllerState +{ + SDL_JoystickID instance_id; + __x_ABI_CWindows_CGaming_CInput_CIRawGameController *controller; + char *name; + SDL_GUID guid; + SDL_JoystickType type; + int steam_virtual_gamepad_slot; +} WindowsGamingInputControllerState; + +typedef HRESULT(WINAPI *CoIncrementMTAUsage_t)(CO_MTA_USAGE_COOKIE *pCookie); +typedef HRESULT(WINAPI *RoGetActivationFactory_t)(HSTRING activatableClassId, REFIID iid, void **factory); +typedef HRESULT(WINAPI *WindowsCreateStringReference_t)(PCWSTR sourceString, UINT32 length, HSTRING_HEADER *hstringHeader, HSTRING *string); +typedef HRESULT(WINAPI *WindowsDeleteString_t)(HSTRING string); +typedef PCWSTR(WINAPI *WindowsGetStringRawBuffer_t)(HSTRING string, UINT32 *length); + +static struct +{ + CoIncrementMTAUsage_t CoIncrementMTAUsage; + RoGetActivationFactory_t RoGetActivationFactory; + WindowsCreateStringReference_t WindowsCreateStringReference; + WindowsDeleteString_t WindowsDeleteString; + WindowsGetStringRawBuffer_t WindowsGetStringRawBuffer; + __x_ABI_CWindows_CGaming_CInput_CIRawGameControllerStatics *controller_statics; + __x_ABI_CWindows_CGaming_CInput_CIArcadeStickStatics *arcade_stick_statics; + __x_ABI_CWindows_CGaming_CInput_CIArcadeStickStatics2 *arcade_stick_statics2; + __x_ABI_CWindows_CGaming_CInput_CIFlightStickStatics *flight_stick_statics; + __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics *gamepad_statics; + __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics2 *gamepad_statics2; + __x_ABI_CWindows_CGaming_CInput_CIRacingWheelStatics *racing_wheel_statics; + __x_ABI_CWindows_CGaming_CInput_CIRacingWheelStatics2 *racing_wheel_statics2; + EventRegistrationToken controller_added_token; + EventRegistrationToken controller_removed_token; + int controller_count; + WindowsGamingInputControllerState *controllers; +} wgi; + +// WinRT headers in official Windows SDK contain only declarations, and we have to define these GUIDs ourselves. +// https://stackoverflow.com/a/55605485/1795050 +DEFINE_GUID(IID___FIEventHandler_1_Windows__CGaming__CInput__CRawGameController, 0x00621c22, 0x42e8, 0x529f, 0x92, 0x70, 0x83, 0x6b, 0x32, 0x93, 0x1d, 0x72); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIArcadeStickStatics, 0x5c37b8c8, 0x37b1, 0x4ad8, 0x94, 0x58, 0x20, 0x0f, 0x1a, 0x30, 0x01, 0x8e); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIArcadeStickStatics2, 0x52b5d744, 0xbb86, 0x445a, 0xb5, 0x9c, 0x59, 0x6f, 0x0e, 0x2a, 0x49, 0xdf); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIFlightStickStatics, 0x5514924a, 0xfecc, 0x435e, 0x83, 0xdc, 0x5c, 0xec, 0x8a, 0x18, 0xa5, 0x20); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIGameController, 0x1baf6522, 0x5f64, 0x42c5, 0x82, 0x67, 0xb9, 0xfe, 0x22, 0x15, 0xbf, 0xbd); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIGameControllerBatteryInfo, 0xdcecc681, 0x3963, 0x4da6, 0x95, 0x5d, 0x55, 0x3f, 0x3b, 0x6f, 0x61, 0x61); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIGamepadStatics, 0x8bbce529, 0xd49c, 0x39e9, 0x95, 0x60, 0xe4, 0x7d, 0xde, 0x96, 0xb7, 0xc8); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIGamepadStatics2, 0x42676dc5, 0x0856, 0x47c4, 0x92, 0x13, 0xb3, 0x95, 0x50, 0x4c, 0x3a, 0x3c); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIRacingWheelStatics, 0x3ac12cd5, 0x581b, 0x4936, 0x9f, 0x94, 0x69, 0xf1, 0xe6, 0x51, 0x4c, 0x7d); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIRacingWheelStatics2, 0xe666bcaa, 0xedfd, 0x4323, 0xa9, 0xf6, 0x3c, 0x38, 0x40, 0x48, 0xd1, 0xed); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIRawGameController, 0x7cad6d91, 0xa7e1, 0x4f71, 0x9a, 0x78, 0x33, 0xe9, 0xc5, 0xdf, 0xea, 0x62); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIRawGameController2, 0x43c0c035, 0xbb73, 0x4756, 0xa7, 0x87, 0x3e, 0xd6, 0xbe, 0xa6, 0x17, 0xbd); +DEFINE_GUID(IID___x_ABI_CWindows_CGaming_CInput_CIRawGameControllerStatics, 0xeb8d0792, 0xe95a, 0x4b19, 0xaf, 0xc7, 0x0a, 0x59, 0xf8, 0xbf, 0x75, 0x9e); + +extern bool SDL_XINPUT_Enabled(void); + + +static bool SDL_IsXInputDevice(Uint16 vendor, Uint16 product, const char *name) +{ +#if defined(SDL_JOYSTICK_XINPUT) || defined(SDL_JOYSTICK_RAWINPUT) + PRAWINPUTDEVICELIST raw_devices = NULL; + UINT i, raw_device_count = 0; + LONG vidpid = MAKELONG(vendor, product); + + // XInput and RawInput backends will pick up XInput-compatible devices + if (!SDL_XINPUT_Enabled() +#ifdef SDL_JOYSTICK_RAWINPUT + && !RAWINPUT_IsEnabled() +#endif + ) { + return false; + } + + // Sometimes we'll get a Windows.Gaming.Input callback before the raw input device is even in the list, + // so try to do some checks up front to catch these cases. + if (SDL_IsJoystickXboxOne(vendor, product) || + (name && SDL_strncmp(name, "Xbox ", 5) == 0)) { + return true; + } + + // Go through RAWINPUT (WinXP and later) to find HID devices. + if ((GetRawInputDeviceList(NULL, &raw_device_count, sizeof(RAWINPUTDEVICELIST)) == -1) || (!raw_device_count)) { + return false; // oh well. + } + + raw_devices = (PRAWINPUTDEVICELIST)SDL_malloc(sizeof(RAWINPUTDEVICELIST) * raw_device_count); + if (!raw_devices) { + return false; + } + + raw_device_count = GetRawInputDeviceList(raw_devices, &raw_device_count, sizeof(RAWINPUTDEVICELIST)); + if (raw_device_count == (UINT)-1) { + SDL_free(raw_devices); + raw_devices = NULL; + return false; // oh well. + } + + for (i = 0; i < raw_device_count; i++) { + RID_DEVICE_INFO rdi; + char devName[MAX_PATH] = { 0 }; + UINT rdiSize = sizeof(rdi); + UINT nameSize = SDL_arraysize(devName); + DEVINST devNode; + char devVidPidString[32]; + int j; + + rdi.cbSize = sizeof(rdi); + + if ((raw_devices[i].dwType != RIM_TYPEHID) || + (GetRawInputDeviceInfoA(raw_devices[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) == ((UINT)-1)) || + (GetRawInputDeviceInfoA(raw_devices[i].hDevice, RIDI_DEVICENAME, devName, &nameSize) == ((UINT)-1)) || + (SDL_strstr(devName, "IG_") == NULL)) { + // Skip non-XInput devices + continue; + } + + // First check for a simple VID/PID match. This will work for Xbox 360 controllers. + if (MAKELONG(rdi.hid.dwVendorId, rdi.hid.dwProductId) == vidpid) { + SDL_free(raw_devices); + return true; + } + + /* For Xbox One controllers, Microsoft doesn't propagate the VID/PID down to the HID stack. + * We'll have to walk the device tree upwards searching for a match for our VID/PID. */ + + // Make sure the device interface string is something we know how to parse + // Example: \\?\HID#VID_045E&PID_02FF&IG_00#9&2c203035&2&0000#{4d1e55b2-f16f-11cf-88cb-001111000030} + if ((SDL_strstr(devName, "\\\\?\\") != devName) || (SDL_strstr(devName, "#{") == NULL)) { + continue; + } + + // Unescape the backslashes in the string and terminate before the GUID portion + for (j = 0; devName[j] != '\0'; j++) { + if (devName[j] == '#') { + if (devName[j + 1] == '{') { + devName[j] = '\0'; + break; + } else { + devName[j] = '\\'; + } + } + } + + /* We'll be left with a string like this: \\?\HID\VID_045E&PID_02FF&IG_00\9&2c203035&2&0000 + * Simply skip the \\?\ prefix and we'll have a properly formed device instance ID */ + if (CM_Locate_DevNodeA(&devNode, &devName[4], CM_LOCATE_DEVNODE_NORMAL) != CR_SUCCESS) { + continue; + } + + (void)SDL_snprintf(devVidPidString, sizeof(devVidPidString), "VID_%04X&PID_%04X", vendor, product); + + while (CM_Get_Parent(&devNode, devNode, 0) == CR_SUCCESS) { + char deviceId[MAX_DEVICE_ID_LEN]; + + if ((CM_Get_Device_IDA(devNode, deviceId, SDL_arraysize(deviceId), 0) == CR_SUCCESS) && + (SDL_strstr(deviceId, devVidPidString) != NULL)) { + // The VID/PID matched a parent device + SDL_free(raw_devices); + return true; + } + } + } + + SDL_free(raw_devices); +#endif // SDL_JOYSTICK_XINPUT || SDL_JOYSTICK_RAWINPUT + + return false; +} + +static void WGI_LoadRawGameControllerStatics(void) +{ + HRESULT hr; + HSTRING_HEADER class_name_header; + HSTRING class_name; + + hr = wgi.WindowsCreateStringReference(RuntimeClass_Windows_Gaming_Input_RawGameController, (UINT32)SDL_wcslen(RuntimeClass_Windows_Gaming_Input_RawGameController), &class_name_header, &class_name); + if (SUCCEEDED(hr)) { + hr = wgi.RoGetActivationFactory(class_name, &IID___x_ABI_CWindows_CGaming_CInput_CIRawGameControllerStatics, (void **)&wgi.controller_statics); + if (!SUCCEEDED(hr)) { + WIN_SetErrorFromHRESULT("Couldn't find Windows.Gaming.Input.IRawGameControllerStatics", hr); + } + } +} + +static void WGI_LoadOtherControllerStatics(void) +{ + HRESULT hr; + HSTRING_HEADER class_name_header; + HSTRING class_name; + + if (!wgi.arcade_stick_statics) { + hr = wgi.WindowsCreateStringReference(RuntimeClass_Windows_Gaming_Input_ArcadeStick, (UINT32)SDL_wcslen(RuntimeClass_Windows_Gaming_Input_ArcadeStick), &class_name_header, &class_name); + if (SUCCEEDED(hr)) { + hr = wgi.RoGetActivationFactory(class_name, &IID___x_ABI_CWindows_CGaming_CInput_CIArcadeStickStatics, (void **)&wgi.arcade_stick_statics); + if (SUCCEEDED(hr)) { + __x_ABI_CWindows_CGaming_CInput_CIArcadeStickStatics_QueryInterface(wgi.arcade_stick_statics, &IID___x_ABI_CWindows_CGaming_CInput_CIArcadeStickStatics2, (void **)&wgi.arcade_stick_statics2); + } else { + WIN_SetErrorFromHRESULT("Couldn't find Windows.Gaming.Input.IArcadeStickStatics", hr); + } + } + } + + if (!wgi.flight_stick_statics) { + hr = wgi.WindowsCreateStringReference(RuntimeClass_Windows_Gaming_Input_FlightStick, (UINT32)SDL_wcslen(RuntimeClass_Windows_Gaming_Input_FlightStick), &class_name_header, &class_name); + if (SUCCEEDED(hr)) { + hr = wgi.RoGetActivationFactory(class_name, &IID___x_ABI_CWindows_CGaming_CInput_CIFlightStickStatics, (void **)&wgi.flight_stick_statics); + if (!SUCCEEDED(hr)) { + WIN_SetErrorFromHRESULT("Couldn't find Windows.Gaming.Input.IFlightStickStatics", hr); + } + } + } + + if (!wgi.gamepad_statics) { + hr = wgi.WindowsCreateStringReference(RuntimeClass_Windows_Gaming_Input_Gamepad, (UINT32)SDL_wcslen(RuntimeClass_Windows_Gaming_Input_Gamepad), &class_name_header, &class_name); + if (SUCCEEDED(hr)) { + hr = wgi.RoGetActivationFactory(class_name, &IID___x_ABI_CWindows_CGaming_CInput_CIGamepadStatics, (void **)&wgi.gamepad_statics); + if (SUCCEEDED(hr)) { + __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_QueryInterface(wgi.gamepad_statics, &IID___x_ABI_CWindows_CGaming_CInput_CIGamepadStatics2, (void **)&wgi.gamepad_statics2); + } else { + WIN_SetErrorFromHRESULT("Couldn't find Windows.Gaming.Input.IGamepadStatics", hr); + } + } + } + + if (!wgi.racing_wheel_statics) { + hr = wgi.WindowsCreateStringReference(RuntimeClass_Windows_Gaming_Input_RacingWheel, (UINT32)SDL_wcslen(RuntimeClass_Windows_Gaming_Input_RacingWheel), &class_name_header, &class_name); + if (SUCCEEDED(hr)) { + hr = wgi.RoGetActivationFactory(class_name, &IID___x_ABI_CWindows_CGaming_CInput_CIRacingWheelStatics, (void **)&wgi.racing_wheel_statics); + if (SUCCEEDED(hr)) { + __x_ABI_CWindows_CGaming_CInput_CIRacingWheelStatics_QueryInterface(wgi.racing_wheel_statics, &IID___x_ABI_CWindows_CGaming_CInput_CIRacingWheelStatics2, (void **)&wgi.racing_wheel_statics2); + } else { + WIN_SetErrorFromHRESULT("Couldn't find Windows.Gaming.Input.IRacingWheelStatics", hr); + } + } + } +} + +static SDL_JoystickType GetGameControllerType(__x_ABI_CWindows_CGaming_CInput_CIGameController *game_controller) +{ + __x_ABI_CWindows_CGaming_CInput_CIArcadeStick *arcade_stick = NULL; + __x_ABI_CWindows_CGaming_CInput_CIFlightStick *flight_stick = NULL; + __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad = NULL; + __x_ABI_CWindows_CGaming_CInput_CIRacingWheel *racing_wheel = NULL; + + /* Wait to initialize these interfaces until we need them. + * Initializing the gamepad interface will switch Bluetooth PS4 controllers into enhanced mode, breaking DirectInput + */ + WGI_LoadOtherControllerStatics(); + + if (wgi.gamepad_statics2 && SUCCEEDED(__x_ABI_CWindows_CGaming_CInput_CIGamepadStatics2_FromGameController(wgi.gamepad_statics2, game_controller, &gamepad)) && gamepad) { + __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad); + return SDL_JOYSTICK_TYPE_GAMEPAD; + } + + if (wgi.arcade_stick_statics2 && SUCCEEDED(__x_ABI_CWindows_CGaming_CInput_CIArcadeStickStatics2_FromGameController(wgi.arcade_stick_statics2, game_controller, &arcade_stick)) && arcade_stick) { + __x_ABI_CWindows_CGaming_CInput_CIArcadeStick_Release(arcade_stick); + return SDL_JOYSTICK_TYPE_ARCADE_STICK; + } + + if (wgi.flight_stick_statics && SUCCEEDED(__x_ABI_CWindows_CGaming_CInput_CIFlightStickStatics_FromGameController(wgi.flight_stick_statics, game_controller, &flight_stick)) && flight_stick) { + __x_ABI_CWindows_CGaming_CInput_CIFlightStick_Release(flight_stick); + return SDL_JOYSTICK_TYPE_FLIGHT_STICK; + } + + if (wgi.racing_wheel_statics2 && SUCCEEDED(__x_ABI_CWindows_CGaming_CInput_CIRacingWheelStatics2_FromGameController(wgi.racing_wheel_statics2, game_controller, &racing_wheel)) && racing_wheel) { + __x_ABI_CWindows_CGaming_CInput_CIRacingWheel_Release(racing_wheel); + return SDL_JOYSTICK_TYPE_WHEEL; + } + + return SDL_JOYSTICK_TYPE_UNKNOWN; +} + +typedef struct RawGameControllerDelegate +{ + __FIEventHandler_1_Windows__CGaming__CInput__CRawGameController iface; + SDL_AtomicInt refcount; +} RawGameControllerDelegate; + +static HRESULT STDMETHODCALLTYPE IEventHandler_CRawGameControllerVtbl_QueryInterface(__FIEventHandler_1_Windows__CGaming__CInput__CRawGameController *This, REFIID riid, void **ppvObject) +{ + if (!ppvObject) { + return E_INVALIDARG; + } + + *ppvObject = NULL; + if (WIN_IsEqualIID(riid, &IID_IUnknown) || WIN_IsEqualIID(riid, &IID_IAgileObject) || WIN_IsEqualIID(riid, &IID___FIEventHandler_1_Windows__CGaming__CInput__CRawGameController)) { + *ppvObject = This; + __FIEventHandler_1_Windows__CGaming__CInput__CRawGameController_AddRef(This); + return S_OK; + } else if (WIN_IsEqualIID(riid, &IID_IMarshal)) { + // This seems complicated. Let's hope it doesn't happen. + return E_OUTOFMEMORY; + } else { + return E_NOINTERFACE; + } +} + +static ULONG STDMETHODCALLTYPE IEventHandler_CRawGameControllerVtbl_AddRef(__FIEventHandler_1_Windows__CGaming__CInput__CRawGameController *This) +{ + RawGameControllerDelegate *self = (RawGameControllerDelegate *)This; + return SDL_AddAtomicInt(&self->refcount, 1) + 1UL; +} + +static ULONG STDMETHODCALLTYPE IEventHandler_CRawGameControllerVtbl_Release(__FIEventHandler_1_Windows__CGaming__CInput__CRawGameController *This) +{ + RawGameControllerDelegate *self = (RawGameControllerDelegate *)This; + int rc = SDL_AddAtomicInt(&self->refcount, -1) - 1; + // Should never free the static delegate objects + SDL_assert(rc > 0); + return rc; +} + +static int GetSteamVirtualGamepadSlot(__x_ABI_CWindows_CGaming_CInput_CIRawGameController *controller, Uint16 vendor_id, Uint16 product_id) +{ + int slot = -1; + + if (vendor_id == USB_VENDOR_VALVE && + product_id == USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD) { + __x_ABI_CWindows_CGaming_CInput_CIRawGameController2 *controller2 = NULL; + HRESULT hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameController_QueryInterface(controller, &IID___x_ABI_CWindows_CGaming_CInput_CIRawGameController2, (void **)&controller2); + if (SUCCEEDED(hr)) { + HSTRING hString; + hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameController2_get_NonRoamableId(controller2, &hString); + if (SUCCEEDED(hr)) { + PCWSTR string = wgi.WindowsGetStringRawBuffer(hString, NULL); + if (string) { + char *id = WIN_StringToUTF8W(string); + if (id) { + (void)SDL_sscanf(id, "{wgi/nrid/:steam-%*X&%*X&%*X#%d#%*u}", &slot); + SDL_free(id); + } + } + wgi.WindowsDeleteString(hString); + } + __x_ABI_CWindows_CGaming_CInput_CIRawGameController2_Release(controller2); + } + } + return slot; +} + +static HRESULT STDMETHODCALLTYPE IEventHandler_CRawGameControllerVtbl_InvokeAdded(__FIEventHandler_1_Windows__CGaming__CInput__CRawGameController *This, IInspectable *sender, __x_ABI_CWindows_CGaming_CInput_CIRawGameController *e) +{ + HRESULT hr; + __x_ABI_CWindows_CGaming_CInput_CIRawGameController *controller = NULL; + + SDL_LockJoysticks(); + + // We can get delayed calls to InvokeAdded() after WGI_JoystickQuit() + if (SDL_JoysticksQuitting() || !SDL_JoysticksInitialized()) { + SDL_UnlockJoysticks(); + return S_OK; + } + + hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameController_QueryInterface(e, &IID___x_ABI_CWindows_CGaming_CInput_CIRawGameController, (void **)&controller); + if (SUCCEEDED(hr)) { + char *name = NULL; + Uint16 bus = SDL_HARDWARE_BUS_USB; + Uint16 vendor = 0; + Uint16 product = 0; + Uint16 version = 0; + SDL_JoystickType type = SDL_JOYSTICK_TYPE_UNKNOWN; + __x_ABI_CWindows_CGaming_CInput_CIRawGameController2 *controller2 = NULL; + __x_ABI_CWindows_CGaming_CInput_CIGameController *game_controller = NULL; + bool ignore_joystick = false; + + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_get_HardwareVendorId(controller, &vendor); + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_get_HardwareProductId(controller, &product); + + hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameController_QueryInterface(controller, &IID___x_ABI_CWindows_CGaming_CInput_CIGameController, (void **)&game_controller); + if (SUCCEEDED(hr)) { + boolean wireless = 0; + hr = __x_ABI_CWindows_CGaming_CInput_CIGameController_get_IsWireless(game_controller, &wireless); + if (SUCCEEDED(hr) && wireless) { + bus = SDL_HARDWARE_BUS_BLUETOOTH; + + // Fixup for Wireless Xbox 360 Controller + if (product == 0) { + vendor = USB_VENDOR_MICROSOFT; + product = USB_PRODUCT_XBOX360_XUSB_CONTROLLER; + } + } + + __x_ABI_CWindows_CGaming_CInput_CIGameController_Release(game_controller); + } + + hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameController_QueryInterface(controller, &IID___x_ABI_CWindows_CGaming_CInput_CIRawGameController2, (void **)&controller2); + if (SUCCEEDED(hr)) { + HSTRING hString; + hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameController2_get_DisplayName(controller2, &hString); + if (SUCCEEDED(hr)) { + PCWSTR string = wgi.WindowsGetStringRawBuffer(hString, NULL); + if (string) { + name = WIN_StringToUTF8W(string); + } + wgi.WindowsDeleteString(hString); + } + __x_ABI_CWindows_CGaming_CInput_CIRawGameController2_Release(controller2); + } + if (!name) { + name = SDL_strdup(""); + } + + if (!ignore_joystick && SDL_ShouldIgnoreJoystick(vendor, product, version, name)) { + ignore_joystick = true; + } + + if (!ignore_joystick && SDL_JoystickHandledByAnotherDriver(&SDL_WGI_JoystickDriver, vendor, product, version, name)) { + ignore_joystick = true; + } + + if (!ignore_joystick && SDL_IsXInputDevice(vendor, product, name)) { + // This hasn't been detected by the RAWINPUT driver yet, but it will be picked up later. + ignore_joystick = true; + } + + if (!ignore_joystick) { + // New device, add it + WindowsGamingInputControllerState *controllers = SDL_realloc(wgi.controllers, sizeof(wgi.controllers[0]) * (wgi.controller_count + 1)); + if (controllers) { + WindowsGamingInputControllerState *state = &controllers[wgi.controller_count]; + SDL_JoystickID joystickID = SDL_GetNextObjectID(); + + if (game_controller) { + type = GetGameControllerType(game_controller); + } + + SDL_zerop(state); + state->instance_id = joystickID; + state->controller = controller; + state->name = name; + state->guid = SDL_CreateJoystickGUID(bus, vendor, product, version, NULL, name, 'w', (Uint8)type); + state->type = type; + state->steam_virtual_gamepad_slot = GetSteamVirtualGamepadSlot(controller, vendor, product); + + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_AddRef(controller); + + ++wgi.controller_count; + wgi.controllers = controllers; + + SDL_PrivateJoystickAdded(joystickID); + } else { + SDL_free(name); + } + } else { + SDL_free(name); + } + + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_Release(controller); + } + + SDL_UnlockJoysticks(); + + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE IEventHandler_CRawGameControllerVtbl_InvokeRemoved(__FIEventHandler_1_Windows__CGaming__CInput__CRawGameController *This, IInspectable *sender, __x_ABI_CWindows_CGaming_CInput_CIRawGameController *e) +{ + HRESULT hr; + __x_ABI_CWindows_CGaming_CInput_CIRawGameController *controller = NULL; + + SDL_LockJoysticks(); + + // Can we get delayed calls to InvokeRemoved() after WGI_JoystickQuit()? + if (!SDL_JoysticksInitialized()) { + SDL_UnlockJoysticks(); + return S_OK; + } + + hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameController_QueryInterface(e, &IID___x_ABI_CWindows_CGaming_CInput_CIRawGameController, (void **)&controller); + if (SUCCEEDED(hr)) { + int i; + + for (i = 0; i < wgi.controller_count; i++) { + if (wgi.controllers[i].controller == controller) { + WindowsGamingInputControllerState *state = &wgi.controllers[i]; + SDL_JoystickID joystickID = state->instance_id; + + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_Release(state->controller); + + SDL_free(state->name); + + --wgi.controller_count; + if (i < wgi.controller_count) { + SDL_memmove(&wgi.controllers[i], &wgi.controllers[i + 1], (wgi.controller_count - i) * sizeof(wgi.controllers[i])); + } + + SDL_PrivateJoystickRemoved(joystickID); + break; + } + } + + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_Release(controller); + } + + SDL_UnlockJoysticks(); + + return S_OK; +} + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4028) // formal parameter 3 different from declaration, when using older buggy WGI headers +#pragma warning(disable : 4113) // formal parameter 3 different from declaration (a more specific warning added in VS 2022), when using older buggy WGI headers +#endif + +static __FIEventHandler_1_Windows__CGaming__CInput__CRawGameControllerVtbl controller_added_vtbl = { + IEventHandler_CRawGameControllerVtbl_QueryInterface, + IEventHandler_CRawGameControllerVtbl_AddRef, + IEventHandler_CRawGameControllerVtbl_Release, + IEventHandler_CRawGameControllerVtbl_InvokeAdded +}; +static RawGameControllerDelegate controller_added = { + { &controller_added_vtbl }, + { 1 } +}; + +static __FIEventHandler_1_Windows__CGaming__CInput__CRawGameControllerVtbl controller_removed_vtbl = { + IEventHandler_CRawGameControllerVtbl_QueryInterface, + IEventHandler_CRawGameControllerVtbl_AddRef, + IEventHandler_CRawGameControllerVtbl_Release, + IEventHandler_CRawGameControllerVtbl_InvokeRemoved +}; +static RawGameControllerDelegate controller_removed = { + { &controller_removed_vtbl }, + { 1 } +}; + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +static bool WGI_JoystickInit(void) +{ + HRESULT hr; + + if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_WGI, true)) { + return true; + } + + if (FAILED(WIN_RoInitialize())) { + return SDL_SetError("RoInitialize() failed"); + } + +#define RESOLVE(x) wgi.x = (x##_t)WIN_LoadComBaseFunction(#x); if (!wgi.x) return WIN_SetError("GetProcAddress failed for " #x); + RESOLVE(CoIncrementMTAUsage); + RESOLVE(RoGetActivationFactory); + RESOLVE(WindowsCreateStringReference); + RESOLVE(WindowsDeleteString); + RESOLVE(WindowsGetStringRawBuffer); +#undef RESOLVE + + { + /* There seems to be a bug in Windows where a dependency of WGI can be unloaded from memory prior to WGI itself. + * This results in Windows_Gaming_Input!GameController::~GameController() invoking an unloaded DLL and crashing. + * As a workaround, we will keep a reference to the MTA to prevent COM from unloading DLLs later. + * See https://github.com/libsdl-org/SDL/issues/5552 for more details. + */ + static CO_MTA_USAGE_COOKIE cookie = NULL; + if (!cookie) { + hr = wgi.CoIncrementMTAUsage(&cookie); + if (FAILED(hr)) { + return WIN_SetErrorFromHRESULT("CoIncrementMTAUsage() failed", hr); + } + } + } + + WGI_LoadRawGameControllerStatics(); + + if (wgi.controller_statics) { + __FIVectorView_1_Windows__CGaming__CInput__CRawGameController *controllers; + + hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameControllerStatics_add_RawGameControllerAdded(wgi.controller_statics, &controller_added.iface, &wgi.controller_added_token); + if (!SUCCEEDED(hr)) { + WIN_SetErrorFromHRESULT("Windows.Gaming.Input.IRawGameControllerStatics.add_RawGameControllerAdded failed", hr); + } + + hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameControllerStatics_add_RawGameControllerRemoved(wgi.controller_statics, &controller_removed.iface, &wgi.controller_removed_token); + if (!SUCCEEDED(hr)) { + WIN_SetErrorFromHRESULT("Windows.Gaming.Input.IRawGameControllerStatics.add_RawGameControllerRemoved failed", hr); + } + + hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameControllerStatics_get_RawGameControllers(wgi.controller_statics, &controllers); + if (SUCCEEDED(hr)) { + unsigned i, count = 0; + + hr = __FIVectorView_1_Windows__CGaming__CInput__CRawGameController_get_Size(controllers, &count); + if (SUCCEEDED(hr)) { + for (i = 0; i < count; ++i) { + __x_ABI_CWindows_CGaming_CInput_CIRawGameController *controller = NULL; + + hr = __FIVectorView_1_Windows__CGaming__CInput__CRawGameController_GetAt(controllers, i, &controller); + if (SUCCEEDED(hr) && controller) { + IEventHandler_CRawGameControllerVtbl_InvokeAdded(&controller_added.iface, NULL, controller); + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_Release(controller); + } + } + } + + __FIVectorView_1_Windows__CGaming__CInput__CRawGameController_Release(controllers); + } + } + + return true; +} + +static int WGI_JoystickGetCount(void) +{ + return wgi.controller_count; +} + +static void WGI_JoystickDetect(void) +{ +} + +static bool WGI_JoystickIsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ + // We don't override any other drivers + return false; +} + +static const char *WGI_JoystickGetDeviceName(int device_index) +{ + return wgi.controllers[device_index].name; +} + +static const char *WGI_JoystickGetDevicePath(int device_index) +{ + return NULL; +} + +static int WGI_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index) +{ + return wgi.controllers[device_index].steam_virtual_gamepad_slot; +} + +static int WGI_JoystickGetDevicePlayerIndex(int device_index) +{ + return false; +} + +static void WGI_JoystickSetDevicePlayerIndex(int device_index, int player_index) +{ +} + +static SDL_GUID WGI_JoystickGetDeviceGUID(int device_index) +{ + return wgi.controllers[device_index].guid; +} + +static SDL_JoystickID WGI_JoystickGetDeviceInstanceID(int device_index) +{ + return wgi.controllers[device_index].instance_id; +} + +static bool WGI_JoystickOpen(SDL_Joystick *joystick, int device_index) +{ + WindowsGamingInputControllerState *state = &wgi.controllers[device_index]; + struct joystick_hwdata *hwdata; + boolean wireless = false; + + hwdata = (struct joystick_hwdata *)SDL_calloc(1, sizeof(*hwdata)); + if (!hwdata) { + return false; + } + joystick->hwdata = hwdata; + + hwdata->controller = state->controller; + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_AddRef(hwdata->controller); + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_QueryInterface(hwdata->controller, &IID___x_ABI_CWindows_CGaming_CInput_CIGameController, (void **)&hwdata->game_controller); + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_QueryInterface(hwdata->controller, &IID___x_ABI_CWindows_CGaming_CInput_CIGameControllerBatteryInfo, (void **)&hwdata->battery); + + if (wgi.gamepad_statics2) { + __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics2_FromGameController(wgi.gamepad_statics2, hwdata->game_controller, &hwdata->gamepad); + } + + if (hwdata->game_controller) { + __x_ABI_CWindows_CGaming_CInput_CIGameController_get_IsWireless(hwdata->game_controller, &wireless); + } + + // Initialize the joystick capabilities + if (wireless) { + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRELESS; + } else { + joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRED; + } + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_get_ButtonCount(hwdata->controller, &joystick->nbuttons); + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_get_AxisCount(hwdata->controller, &joystick->naxes); + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_get_SwitchCount(hwdata->controller, &joystick->nhats); + + if (hwdata->gamepad) { + // FIXME: Can WGI even tell us if trigger rumble is supported? + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true); + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN, true); + } + return true; +} + +static bool WGI_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + struct joystick_hwdata *hwdata = joystick->hwdata; + + if (hwdata->gamepad) { + HRESULT hr; + + // Note: reusing partially filled vibration data struct + hwdata->vibration.LeftMotor = (DOUBLE)low_frequency_rumble / SDL_MAX_UINT16; + hwdata->vibration.RightMotor = (DOUBLE)high_frequency_rumble / SDL_MAX_UINT16; + hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(hwdata->gamepad, hwdata->vibration); + if (SUCCEEDED(hr)) { + return true; + } else { + return WIN_SetErrorFromHRESULT("Windows.Gaming.Input.IGamepad.put_Vibration failed", hr); + } + } else { + return SDL_Unsupported(); + } +} + +static bool WGI_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + struct joystick_hwdata *hwdata = joystick->hwdata; + + if (hwdata->gamepad) { + HRESULT hr; + + // Note: reusing partially filled vibration data struct + hwdata->vibration.LeftTrigger = (DOUBLE)left_rumble / SDL_MAX_UINT16; + hwdata->vibration.RightTrigger = (DOUBLE)right_rumble / SDL_MAX_UINT16; + hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(hwdata->gamepad, hwdata->vibration); + if (SUCCEEDED(hr)) { + return true; + } else { + return WIN_SetErrorFromHRESULT("Windows.Gaming.Input.IGamepad.put_Vibration failed", hr); + } + } else { + return SDL_Unsupported(); + } +} + +static bool WGI_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool WGI_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool WGI_JoystickSetSensorsEnabled(SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static Uint8 ConvertHatValue(__x_ABI_CWindows_CGaming_CInput_CGameControllerSwitchPosition value) +{ + switch (value) { + case GameControllerSwitchPosition_Up: + return SDL_HAT_UP; + case GameControllerSwitchPosition_UpRight: + return SDL_HAT_RIGHTUP; + case GameControllerSwitchPosition_Right: + return SDL_HAT_RIGHT; + case GameControllerSwitchPosition_DownRight: + return SDL_HAT_RIGHTDOWN; + case GameControllerSwitchPosition_Down: + return SDL_HAT_DOWN; + case GameControllerSwitchPosition_DownLeft: + return SDL_HAT_LEFTDOWN; + case GameControllerSwitchPosition_Left: + return SDL_HAT_LEFT; + case GameControllerSwitchPosition_UpLeft: + return SDL_HAT_LEFTUP; + default: + return SDL_HAT_CENTERED; + } +} + +static void WGI_JoystickUpdate(SDL_Joystick *joystick) +{ + struct joystick_hwdata *hwdata = joystick->hwdata; + HRESULT hr; + UINT32 nbuttons = SDL_min(joystick->nbuttons, SDL_MAX_UINT8); + boolean *buttons = NULL; + UINT32 nhats = SDL_min(joystick->nhats, SDL_MAX_UINT8); + __x_ABI_CWindows_CGaming_CInput_CGameControllerSwitchPosition *hats = NULL; + UINT32 naxes = SDL_min(joystick->naxes, SDL_MAX_UINT8); + DOUBLE *axes = NULL; + UINT64 timestamp; + + if (nbuttons > 0) { + buttons = SDL_stack_alloc(boolean, nbuttons); + } + if (nhats > 0) { + hats = SDL_stack_alloc(__x_ABI_CWindows_CGaming_CInput_CGameControllerSwitchPosition, nhats); + } + if (naxes > 0) { + axes = SDL_stack_alloc(DOUBLE, naxes); + } + + hr = __x_ABI_CWindows_CGaming_CInput_CIRawGameController_GetCurrentReading(hwdata->controller, nbuttons, buttons, nhats, hats, naxes, axes, ×tamp); + if (SUCCEEDED(hr) && (!timestamp || timestamp != hwdata->timestamp)) { + UINT32 i; + bool all_zero = false; + + hwdata->timestamp = timestamp; + + // The axes are all zero when the application loses focus + if (naxes > 0) { + all_zero = true; + for (i = 0; i < naxes; ++i) { + if (axes[i] != 0.0f) { + all_zero = false; + break; + } + } + } + if (all_zero) { + SDL_PrivateJoystickForceRecentering(joystick); + } else { + // FIXME: What units are the timestamp we get from GetCurrentReading()? + timestamp = SDL_GetTicksNS(); + for (i = 0; i < nbuttons; ++i) { + SDL_SendJoystickButton(timestamp, joystick, (Uint8)i, buttons[i]); + } + for (i = 0; i < nhats; ++i) { + SDL_SendJoystickHat(timestamp, joystick, (Uint8)i, ConvertHatValue(hats[i])); + } + for (i = 0; i < naxes; ++i) { + SDL_SendJoystickAxis(timestamp, joystick, (Uint8)i, (Sint16)((int)(axes[i] * 65535) - 32768)); + } + } + } + + SDL_stack_free(buttons); + SDL_stack_free(hats); + SDL_stack_free(axes); + + if (hwdata->battery) { + __x_ABI_CWindows_CDevices_CPower_CIBatteryReport *report = NULL; + + hr = __x_ABI_CWindows_CGaming_CInput_CIGameControllerBatteryInfo_TryGetBatteryReport(hwdata->battery, &report); + if (SUCCEEDED(hr) && report) { + SDL_PowerState state = SDL_POWERSTATE_UNKNOWN; + int percent = 0; + __x_ABI_CWindows_CSystem_CPower_CBatteryStatus status; + int full_capacity = 0, curr_capacity = 0; + __FIReference_1_int *full_capacityP, *curr_capacityP; + + hr = __x_ABI_CWindows_CDevices_CPower_CIBatteryReport_get_Status(report, &status); + if (SUCCEEDED(hr)) { + switch (status) { + case BatteryStatus_NotPresent: + state = SDL_POWERSTATE_NO_BATTERY; + break; + case BatteryStatus_Discharging: + state = SDL_POWERSTATE_ON_BATTERY; + break; + case BatteryStatus_Idle: + state = SDL_POWERSTATE_CHARGED; + break; + case BatteryStatus_Charging: + state = SDL_POWERSTATE_CHARGING; + break; + default: + state = SDL_POWERSTATE_UNKNOWN; + break; + } + } + + hr = __x_ABI_CWindows_CDevices_CPower_CIBatteryReport_get_FullChargeCapacityInMilliwattHours(report, &full_capacityP); + if (SUCCEEDED(hr)) { + __FIReference_1_int_get_Value(full_capacityP, &full_capacity); + __FIReference_1_int_Release(full_capacityP); + } + + hr = __x_ABI_CWindows_CDevices_CPower_CIBatteryReport_get_RemainingCapacityInMilliwattHours(report, &curr_capacityP); + if (SUCCEEDED(hr)) { + __FIReference_1_int_get_Value(curr_capacityP, &curr_capacity); + __FIReference_1_int_Release(curr_capacityP); + } + + if (full_capacity > 0) { + percent = (int)SDL_roundf(((float)curr_capacity / full_capacity) * 100.0f); + } + + SDL_SendJoystickPowerInfo(joystick, state, percent); + + __x_ABI_CWindows_CDevices_CPower_CIBatteryReport_Release(report); + } + } +} + +static void WGI_JoystickClose(SDL_Joystick *joystick) +{ + struct joystick_hwdata *hwdata = joystick->hwdata; + + if (hwdata) { + if (hwdata->controller) { + __x_ABI_CWindows_CGaming_CInput_CIRawGameController_Release(hwdata->controller); + } + if (hwdata->game_controller) { + __x_ABI_CWindows_CGaming_CInput_CIGameController_Release(hwdata->game_controller); + } + if (hwdata->battery) { + __x_ABI_CWindows_CGaming_CInput_CIGameControllerBatteryInfo_Release(hwdata->battery); + } + if (hwdata->gamepad) { + __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(hwdata->gamepad); + } + SDL_free(hwdata); + } + joystick->hwdata = NULL; +} + +static void WGI_JoystickQuit(void) +{ + if (wgi.controller_statics) { + while (wgi.controller_count > 0) { + IEventHandler_CRawGameControllerVtbl_InvokeRemoved(&controller_removed.iface, NULL, wgi.controllers[wgi.controller_count - 1].controller); + } + if (wgi.controllers) { + SDL_free(wgi.controllers); + } + + if (wgi.arcade_stick_statics) { + __x_ABI_CWindows_CGaming_CInput_CIArcadeStickStatics_Release(wgi.arcade_stick_statics); + } + if (wgi.arcade_stick_statics2) { + __x_ABI_CWindows_CGaming_CInput_CIArcadeStickStatics2_Release(wgi.arcade_stick_statics2); + } + if (wgi.flight_stick_statics) { + __x_ABI_CWindows_CGaming_CInput_CIFlightStickStatics_Release(wgi.flight_stick_statics); + } + if (wgi.gamepad_statics) { + __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_Release(wgi.gamepad_statics); + } + if (wgi.gamepad_statics2) { + __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics2_Release(wgi.gamepad_statics2); + } + if (wgi.racing_wheel_statics) { + __x_ABI_CWindows_CGaming_CInput_CIRacingWheelStatics_Release(wgi.racing_wheel_statics); + } + if (wgi.racing_wheel_statics2) { + __x_ABI_CWindows_CGaming_CInput_CIRacingWheelStatics2_Release(wgi.racing_wheel_statics2); + } + + __x_ABI_CWindows_CGaming_CInput_CIRawGameControllerStatics_remove_RawGameControllerAdded(wgi.controller_statics, wgi.controller_added_token); + __x_ABI_CWindows_CGaming_CInput_CIRawGameControllerStatics_remove_RawGameControllerRemoved(wgi.controller_statics, wgi.controller_removed_token); + __x_ABI_CWindows_CGaming_CInput_CIRawGameControllerStatics_Release(wgi.controller_statics); + } + + WIN_RoUninitialize(); + + SDL_zero(wgi); +} + +static bool WGI_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) +{ + return false; +} + +SDL_JoystickDriver SDL_WGI_JoystickDriver = { + WGI_JoystickInit, + WGI_JoystickGetCount, + WGI_JoystickDetect, + WGI_JoystickIsDevicePresent, + WGI_JoystickGetDeviceName, + WGI_JoystickGetDevicePath, + WGI_JoystickGetDeviceSteamVirtualGamepadSlot, + WGI_JoystickGetDevicePlayerIndex, + WGI_JoystickSetDevicePlayerIndex, + WGI_JoystickGetDeviceGUID, + WGI_JoystickGetDeviceInstanceID, + WGI_JoystickOpen, + WGI_JoystickRumble, + WGI_JoystickRumbleTriggers, + WGI_JoystickSetLED, + WGI_JoystickSendEffect, + WGI_JoystickSetSensorsEnabled, + WGI_JoystickUpdate, + WGI_JoystickClose, + WGI_JoystickQuit, + WGI_JoystickGetGamepadMapping +}; + +#endif // SDL_JOYSTICK_WGI diff --git a/thirdparty/sdl/joystick/windows/SDL_windowsjoystick.c b/thirdparty/sdl/joystick/windows/SDL_windowsjoystick.c new file mode 100644 index 00000000000..e7fbfcb3462 --- /dev/null +++ b/thirdparty/sdl/joystick/windows/SDL_windowsjoystick.c @@ -0,0 +1,693 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT) + +/* DirectInput joystick driver; written by Glenn Maynard, based on Andrei de + * A. Formiga's WINMM driver. + * + * Hats and sliders are completely untested; the app I'm writing this for mostly + * doesn't use them and I don't own any joysticks with them. + * + * We don't bother to use event notification here. It doesn't seem to work + * with polled devices, and it's fine to call IDirectInputDevice8_GetDeviceData and + * let it return 0 events. */ + +#include "../SDL_sysjoystick.h" +#include "../../thread/SDL_systhread.h" +#include "../../core/windows/SDL_windows.h" +#include "../../core/windows/SDL_hid.h" +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) +#include +#endif + +#define INITGUID // Only set here, if set twice will cause mingw32 to break. +#include "SDL_windowsjoystick_c.h" +#include "SDL_dinputjoystick_c.h" +#include "SDL_xinputjoystick_c.h" +#include "SDL_rawinputjoystick_c.h" + +#include "../../haptic/windows/SDL_dinputhaptic_c.h" // For haptic hot plugging + +#ifndef DEVICE_NOTIFY_WINDOW_HANDLE +#define DEVICE_NOTIFY_WINDOW_HANDLE 0x00000000 +#endif + +// local variables +static bool s_bJoystickThread = false; +static SDL_Condition *s_condJoystickThread = NULL; +static SDL_Mutex *s_mutexJoyStickEnum = NULL; +static SDL_Thread *s_joystickThread = NULL; +static bool s_bJoystickThreadQuit = false; +static Uint64 s_lastDeviceChange = 0; +static GUID GUID_DEVINTERFACE_HID = { 0x4D1E55B2L, 0xF16F, 0x11CF, { 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } }; + +JoyStick_DeviceData *SYS_Joystick; // array to hold joystick ID values + + +static bool WindowsDeviceChanged(void) +{ + return (s_lastDeviceChange != WIN_GetLastDeviceNotification()); +} + +static void SetWindowsDeviceChanged(void) +{ + s_lastDeviceChange = 0; +} + +void WINDOWS_RAWINPUTEnabledChanged(void) +{ + SetWindowsDeviceChanged(); +} + +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + +typedef struct +{ + HRESULT coinitialized; + WNDCLASSEX wincl; + HWND messageWindow; + HDEVNOTIFY hNotify; +} SDL_DeviceNotificationData; + +#define IDT_SDL_DEVICE_CHANGE_TIMER_1 1200 +#define IDT_SDL_DEVICE_CHANGE_TIMER_2 1201 + +// windowproc for our joystick detect thread message only window, to detect any USB device addition/removal +static LRESULT CALLBACK SDL_PrivateJoystickDetectProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch (msg) { + case WM_DEVICECHANGE: + switch (wParam) { + case DBT_DEVICEARRIVAL: + case DBT_DEVICEREMOVECOMPLETE: + if (((DEV_BROADCAST_HDR *)lParam)->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) { + // notify 300ms and 2 seconds later to ensure all APIs have updated status + SetTimer(hwnd, IDT_SDL_DEVICE_CHANGE_TIMER_1, 300, NULL); + SetTimer(hwnd, IDT_SDL_DEVICE_CHANGE_TIMER_2, 2000, NULL); + } + break; + } + return true; + case WM_TIMER: + if (wParam == IDT_SDL_DEVICE_CHANGE_TIMER_1 || + wParam == IDT_SDL_DEVICE_CHANGE_TIMER_2) { + KillTimer(hwnd, wParam); + SetWindowsDeviceChanged(); + return true; + } + break; + } + +#ifdef SDL_JOYSTICK_RAWINPUT + return CallWindowProc(RAWINPUT_WindowProc, hwnd, msg, wParam, lParam); +#else + return CallWindowProc(DefWindowProc, hwnd, msg, wParam, lParam); +#endif +} + +static void SDL_CleanupDeviceNotification(SDL_DeviceNotificationData *data) +{ +#ifdef SDL_JOYSTICK_RAWINPUT + RAWINPUT_UnregisterNotifications(); +#endif + + if (data->hNotify) { + UnregisterDeviceNotification(data->hNotify); + } + + if (data->messageWindow) { + DestroyWindow(data->messageWindow); + } + + UnregisterClass(data->wincl.lpszClassName, data->wincl.hInstance); + + if (data->coinitialized == S_OK) { + WIN_CoUninitialize(); + } +} + +static bool SDL_CreateDeviceNotification(SDL_DeviceNotificationData *data) +{ + DEV_BROADCAST_DEVICEINTERFACE dbh; + + SDL_zerop(data); + + data->coinitialized = WIN_CoInitialize(); + + data->wincl.hInstance = GetModuleHandle(NULL); + data->wincl.lpszClassName = TEXT("Message"); + data->wincl.lpfnWndProc = SDL_PrivateJoystickDetectProc; // This function is called by windows + data->wincl.cbSize = sizeof(WNDCLASSEX); + + if (!RegisterClassEx(&data->wincl)) { + WIN_SetError("Failed to create register class for joystick autodetect"); + SDL_CleanupDeviceNotification(data); + return false; + } + + data->messageWindow = CreateWindowEx(0, TEXT("Message"), NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL); + if (!data->messageWindow) { + WIN_SetError("Failed to create message window for joystick autodetect"); + SDL_CleanupDeviceNotification(data); + return false; + } + + SDL_zero(dbh); + dbh.dbcc_size = sizeof(dbh); + dbh.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; + dbh.dbcc_classguid = GUID_DEVINTERFACE_HID; + + data->hNotify = RegisterDeviceNotification(data->messageWindow, &dbh, DEVICE_NOTIFY_WINDOW_HANDLE); + if (!data->hNotify) { + WIN_SetError("Failed to create notify device for joystick autodetect"); + SDL_CleanupDeviceNotification(data); + return false; + } + +#ifdef SDL_JOYSTICK_RAWINPUT + RAWINPUT_RegisterNotifications(data->messageWindow); +#endif + return true; +} + +static bool SDL_WaitForDeviceNotification(SDL_DeviceNotificationData *data, SDL_Mutex *mutex) +{ + MSG msg; + int lastret = 1; + + if (!data->messageWindow) { + return false; // device notifications require a window + } + + SDL_UnlockMutex(mutex); + while (lastret > 0 && !WindowsDeviceChanged()) { + lastret = GetMessage(&msg, NULL, 0, 0); // WM_QUIT causes return value of 0 + if (lastret > 0) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } + SDL_LockMutex(mutex); + return (lastret != -1); +} + +#endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) +static SDL_DeviceNotificationData s_notification_data; +#endif + +// Function/thread to scan the system for joysticks. +static int SDLCALL SDL_JoystickThread(void *_data) +{ +#ifdef SDL_JOYSTICK_XINPUT + bool bOpenedXInputDevices[XUSER_MAX_COUNT]; + SDL_zeroa(bOpenedXInputDevices); +#endif + +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + if (!SDL_CreateDeviceNotification(&s_notification_data)) { + return 0; + } +#endif + + SDL_LockMutex(s_mutexJoyStickEnum); + while (s_bJoystickThreadQuit == false) { +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + if (SDL_WaitForDeviceNotification(&s_notification_data, s_mutexJoyStickEnum) == false) { +#else + { +#endif +#ifdef SDL_JOYSTICK_XINPUT + // WM_DEVICECHANGE not working, poll for new XINPUT controllers + SDL_WaitConditionTimeout(s_condJoystickThread, s_mutexJoyStickEnum, 1000); + if (SDL_XINPUT_Enabled()) { + // scan for any change in XInput devices + Uint8 userId; + for (userId = 0; userId < XUSER_MAX_COUNT; userId++) { + XINPUT_CAPABILITIES capabilities; + const DWORD result = XINPUTGETCAPABILITIES(userId, XINPUT_FLAG_GAMEPAD, &capabilities); + const bool available = (result == ERROR_SUCCESS); + if (bOpenedXInputDevices[userId] != available) { + SetWindowsDeviceChanged(); + bOpenedXInputDevices[userId] = available; + } + } + } +#else + // WM_DEVICECHANGE not working, no XINPUT, no point in keeping thread alive + break; +#endif // SDL_JOYSTICK_XINPUT + } + } + + SDL_UnlockMutex(s_mutexJoyStickEnum); + +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + SDL_CleanupDeviceNotification(&s_notification_data); +#endif + + return 1; +} + +// spin up the thread to detect hotplug of devices +static bool SDL_StartJoystickThread(void) +{ + s_mutexJoyStickEnum = SDL_CreateMutex(); + if (!s_mutexJoyStickEnum) { + return false; + } + + s_condJoystickThread = SDL_CreateCondition(); + if (!s_condJoystickThread) { + return false; + } + + s_bJoystickThreadQuit = false; + s_joystickThread = SDL_CreateThread(SDL_JoystickThread, "SDL_joystick", NULL); + if (!s_joystickThread) { + return false; + } + return true; +} + +static void SDL_StopJoystickThread(void) +{ + if (!s_joystickThread) { + return; + } + + SDL_LockMutex(s_mutexJoyStickEnum); + s_bJoystickThreadQuit = true; + SDL_BroadcastCondition(s_condJoystickThread); // signal the joystick thread to quit + SDL_UnlockMutex(s_mutexJoyStickEnum); + PostThreadMessage((DWORD)SDL_GetThreadID(s_joystickThread), WM_QUIT, 0, 0); + + // Unlock joysticks while the joystick thread finishes processing messages + SDL_AssertJoysticksLocked(); + SDL_UnlockJoysticks(); + SDL_WaitThread(s_joystickThread, NULL); // wait for it to bugger off + SDL_LockJoysticks(); + + SDL_DestroyCondition(s_condJoystickThread); + s_condJoystickThread = NULL; + + SDL_DestroyMutex(s_mutexJoyStickEnum); + s_mutexJoyStickEnum = NULL; + + s_joystickThread = NULL; +} + +void WINDOWS_AddJoystickDevice(JoyStick_DeviceData *device) +{ + device->send_add_event = true; + device->nInstanceID = SDL_GetNextObjectID(); + device->pNext = SYS_Joystick; + SYS_Joystick = device; +} + +void WINDOWS_JoystickDetect(void); +void WINDOWS_JoystickQuit(void); + +static bool WINDOWS_JoystickInit(void) +{ + if (!SDL_XINPUT_JoystickInit()) { + WINDOWS_JoystickQuit(); + return false; + } + + if (!SDL_DINPUT_JoystickInit()) { + WINDOWS_JoystickQuit(); + return false; + } + + WIN_InitDeviceNotification(); + +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + s_bJoystickThread = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_THREAD, true); + if (s_bJoystickThread) { + if (!SDL_StartJoystickThread()) { + return false; + } + } else { + if (!SDL_CreateDeviceNotification(&s_notification_data)) { + return false; + } + } +#endif + +#if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) + // On Xbox, force create the joystick thread for device detection (since other methods don't work + s_bJoystickThread = true; + if (!SDL_StartJoystickThread()) { + return false; + } +#endif + + SetWindowsDeviceChanged(); // force a scan of the system for joysticks this first time + + WINDOWS_JoystickDetect(); + + return true; +} + +// return the number of joysticks that are connected right now +static int WINDOWS_JoystickGetCount(void) +{ + int nJoysticks = 0; + JoyStick_DeviceData *device = SYS_Joystick; + while (device) { + nJoysticks++; + device = device->pNext; + } + + return nJoysticks; +} + +// detect any new joysticks being inserted into the system +void WINDOWS_JoystickDetect(void) +{ + JoyStick_DeviceData *pCurList = NULL; + + // only enum the devices if the joystick thread told us something changed + if (!WindowsDeviceChanged()) { + return; // thread hasn't signaled, nothing to do right now. + } + + if (s_mutexJoyStickEnum) { + SDL_LockMutex(s_mutexJoyStickEnum); + } + + s_lastDeviceChange = WIN_GetLastDeviceNotification(); + + pCurList = SYS_Joystick; + SYS_Joystick = NULL; + + // Look for DirectInput joysticks, wheels, head trackers, gamepads, etc.. + SDL_DINPUT_JoystickDetect(&pCurList); + + // Look for XInput devices. Do this last, so they're first in the final list. + SDL_XINPUT_JoystickDetect(&pCurList); + + if (s_mutexJoyStickEnum) { + SDL_UnlockMutex(s_mutexJoyStickEnum); + } + + while (pCurList) { + JoyStick_DeviceData *pListNext = NULL; + + if (!pCurList->bXInputDevice) { +#ifdef SDL_HAPTIC_DINPUT + SDL_DINPUT_HapticMaybeRemoveDevice(&pCurList->dxdevice); +#endif + } + + SDL_PrivateJoystickRemoved(pCurList->nInstanceID); + + pListNext = pCurList->pNext; + SDL_free(pCurList->joystickname); + SDL_free(pCurList); + pCurList = pListNext; + } + + for (pCurList = SYS_Joystick; pCurList; pCurList = pCurList->pNext) { + if (pCurList->send_add_event) { + if (!pCurList->bXInputDevice) { +#ifdef SDL_HAPTIC_DINPUT + SDL_DINPUT_HapticMaybeAddDevice(&pCurList->dxdevice); +#endif + } + + SDL_PrivateJoystickAdded(pCurList->nInstanceID); + + pCurList->send_add_event = false; + } + } +} + +static bool WINDOWS_JoystickIsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) +{ + if (SDL_DINPUT_JoystickPresent(vendor_id, product_id, version)) { + return true; + } + if (SDL_XINPUT_JoystickPresent(vendor_id, product_id, version)) { + return true; + } + return false; +} + +static const char *WINDOWS_JoystickGetDeviceName(int device_index) +{ + JoyStick_DeviceData *device = SYS_Joystick; + int index; + + for (index = device_index; index > 0; index--) { + device = device->pNext; + } + + return device->joystickname; +} + +static const char *WINDOWS_JoystickGetDevicePath(int device_index) +{ + JoyStick_DeviceData *device = SYS_Joystick; + int index; + + for (index = device_index; index > 0; index--) { + device = device->pNext; + } + + return device->path; +} + +static int WINDOWS_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index) +{ + JoyStick_DeviceData *device = SYS_Joystick; + int index; + + for (index = device_index; index > 0; index--) { + device = device->pNext; + } + + if (device->bXInputDevice) { + // The slot for XInput devices can change as controllers are seated + return SDL_XINPUT_GetSteamVirtualGamepadSlot(device->XInputUserId); + } else { + return device->steam_virtual_gamepad_slot; + } +} + +static int WINDOWS_JoystickGetDevicePlayerIndex(int device_index) +{ + JoyStick_DeviceData *device = SYS_Joystick; + int index; + + for (index = device_index; index > 0; index--) { + device = device->pNext; + } + + return device->bXInputDevice ? (int)device->XInputUserId : -1; +} + +static void WINDOWS_JoystickSetDevicePlayerIndex(int device_index, int player_index) +{ +} + +// return the stable device guid for this device index +static SDL_GUID WINDOWS_JoystickGetDeviceGUID(int device_index) +{ + JoyStick_DeviceData *device = SYS_Joystick; + int index; + + for (index = device_index; index > 0; index--) { + device = device->pNext; + } + + return device->guid; +} + +// Function to perform the mapping between current device instance and this joysticks instance id +static SDL_JoystickID WINDOWS_JoystickGetDeviceInstanceID(int device_index) +{ + JoyStick_DeviceData *device = SYS_Joystick; + int index; + + for (index = device_index; index > 0; index--) { + device = device->pNext; + } + + return device->nInstanceID; +} + +/* Function to open a joystick for use. + The joystick to open is specified by the device index. + This should fill the nbuttons and naxes fields of the joystick structure. + It returns 0, or -1 if there is an error. + */ +static bool WINDOWS_JoystickOpen(SDL_Joystick *joystick, int device_index) +{ + JoyStick_DeviceData *device = SYS_Joystick; + int index; + + for (index = device_index; index > 0; index--) { + device = device->pNext; + } + + // allocate memory for system specific hardware data + joystick->hwdata = (struct joystick_hwdata *)SDL_calloc(1, sizeof(struct joystick_hwdata)); + if (!joystick->hwdata) { + return false; + } + joystick->hwdata->guid = device->guid; + + if (device->bXInputDevice) { + return SDL_XINPUT_JoystickOpen(joystick, device); + } else { + return SDL_DINPUT_JoystickOpen(joystick, device); + } +} + +static bool WINDOWS_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + if (joystick->hwdata->bXInputDevice) { + return SDL_XINPUT_JoystickRumble(joystick, low_frequency_rumble, high_frequency_rumble); + } else { + return SDL_DINPUT_JoystickRumble(joystick, low_frequency_rumble, high_frequency_rumble); + } +} + +static bool WINDOWS_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) +{ + return SDL_Unsupported(); +} + +static bool WINDOWS_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) +{ + return SDL_Unsupported(); +} + +static bool WINDOWS_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size) +{ + return SDL_Unsupported(); +} + +static bool WINDOWS_JoystickSetSensorsEnabled(SDL_Joystick *joystick, bool enabled) +{ + return SDL_Unsupported(); +} + +static void WINDOWS_JoystickUpdate(SDL_Joystick *joystick) +{ + if (!joystick->hwdata) { + return; + } + + if (joystick->hwdata->bXInputDevice) { + SDL_XINPUT_JoystickUpdate(joystick); + } else { + SDL_DINPUT_JoystickUpdate(joystick); + } +} + +// Function to close a joystick after use +static void WINDOWS_JoystickClose(SDL_Joystick *joystick) +{ + if (joystick->hwdata->bXInputDevice) { + SDL_XINPUT_JoystickClose(joystick); + } else { + SDL_DINPUT_JoystickClose(joystick); + } + + SDL_free(joystick->hwdata); +} + +// Function to perform any system-specific joystick related cleanup +void WINDOWS_JoystickQuit(void) +{ + JoyStick_DeviceData *device = SYS_Joystick; + + while (device) { + JoyStick_DeviceData *device_next = device->pNext; + SDL_free(device->joystickname); + SDL_free(device); + device = device_next; + } + SYS_Joystick = NULL; + +#if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) + if (s_bJoystickThread) { + SDL_StopJoystickThread(); + } else { + SDL_CleanupDeviceNotification(&s_notification_data); + } +#endif + +#if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) + if (s_bJoystickThread) { + SDL_StopJoystickThread(); + } +#endif + + SDL_DINPUT_JoystickQuit(); + SDL_XINPUT_JoystickQuit(); + + WIN_QuitDeviceNotification(); +} + +static bool WINDOWS_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) +{ + return false; +} + +SDL_JoystickDriver SDL_WINDOWS_JoystickDriver = { + WINDOWS_JoystickInit, + WINDOWS_JoystickGetCount, + WINDOWS_JoystickDetect, + WINDOWS_JoystickIsDevicePresent, + WINDOWS_JoystickGetDeviceName, + WINDOWS_JoystickGetDevicePath, + WINDOWS_JoystickGetDeviceSteamVirtualGamepadSlot, + WINDOWS_JoystickGetDevicePlayerIndex, + WINDOWS_JoystickSetDevicePlayerIndex, + WINDOWS_JoystickGetDeviceGUID, + WINDOWS_JoystickGetDeviceInstanceID, + WINDOWS_JoystickOpen, + WINDOWS_JoystickRumble, + WINDOWS_JoystickRumbleTriggers, + WINDOWS_JoystickSetLED, + WINDOWS_JoystickSendEffect, + WINDOWS_JoystickSetSensorsEnabled, + WINDOWS_JoystickUpdate, + WINDOWS_JoystickClose, + WINDOWS_JoystickQuit, + WINDOWS_JoystickGetGamepadMapping +}; + +#else + +#ifdef SDL_JOYSTICK_RAWINPUT +// The RAWINPUT driver needs the device notification setup above +#error SDL_JOYSTICK_RAWINPUT requires SDL_JOYSTICK_DINPUT || SDL_JOYSTICK_XINPUT +#endif + +#endif // SDL_JOYSTICK_DINPUT || SDL_JOYSTICK_XINPUT diff --git a/thirdparty/sdl/joystick/windows/SDL_windowsjoystick_c.h b/thirdparty/sdl/joystick/windows/SDL_windowsjoystick_c.h new file mode 100644 index 00000000000..16b91848dbf --- /dev/null +++ b/thirdparty/sdl/joystick/windows/SDL_windowsjoystick_c.h @@ -0,0 +1,103 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "../SDL_sysjoystick.h" +#include "../../core/windows/SDL_windows.h" +#include "../../core/windows/SDL_directx.h" + +#define MAX_INPUTS 256 // each joystick can have up to 256 inputs + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct JoyStick_DeviceData +{ + SDL_GUID guid; + char *joystickname; + Uint8 send_add_event; + SDL_JoystickID nInstanceID; + bool bXInputDevice; + BYTE SubType; + Uint8 XInputUserId; + DIDEVICEINSTANCE dxdevice; + char path[MAX_PATH]; + int steam_virtual_gamepad_slot; + struct JoyStick_DeviceData *pNext; +} JoyStick_DeviceData; + +extern JoyStick_DeviceData *SYS_Joystick; // array to hold joystick ID values + +typedef enum Type +{ + BUTTON, + AXIS, + HAT +} Type; + +typedef struct input_t +{ + // DirectInput offset for this input type: + DWORD ofs; + + // Button, axis or hat: + Type type; + + // SDL input offset: + Uint8 num; +} input_t; + +// The private structure used to keep track of a joystick +struct joystick_hwdata +{ + SDL_GUID guid; + +#ifdef SDL_JOYSTICK_DINPUT + LPDIRECTINPUTDEVICE8 InputDevice; + DIDEVCAPS Capabilities; + bool buffered; + bool first_update; + input_t Inputs[MAX_INPUTS]; + int NumInputs; + int NumSliders; + bool ff_initialized; + DIEFFECT *ffeffect; + LPDIRECTINPUTEFFECT ffeffect_ref; +#endif + + bool bXInputDevice; // true if this device supports using the xinput API rather than DirectInput + bool bXInputHaptic; // Supports force feedback via XInput. + Uint8 userid; // XInput userid index for this joystick + DWORD dwPacketNumber; +}; + +#ifdef SDL_JOYSTICK_DINPUT +extern const DIDATAFORMAT SDL_c_dfDIJoystick2; +#endif + +extern void WINDOWS_AddJoystickDevice(JoyStick_DeviceData *device); + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif diff --git a/thirdparty/sdl/joystick/windows/SDL_xinputjoystick.c b/thirdparty/sdl/joystick/windows/SDL_xinputjoystick.c new file mode 100644 index 00000000000..9f6ce103d13 --- /dev/null +++ b/thirdparty/sdl/joystick/windows/SDL_xinputjoystick.c @@ -0,0 +1,473 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "../SDL_sysjoystick.h" + +#ifdef SDL_JOYSTICK_XINPUT + +#include "SDL_windowsjoystick_c.h" +#include "SDL_xinputjoystick_c.h" +#include "SDL_rawinputjoystick_c.h" +#include "../hidapi/SDL_hidapijoystick_c.h" + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Internal stuff. + */ +static bool s_bXInputEnabled = false; + +bool SDL_XINPUT_Enabled(void) +{ + return s_bXInputEnabled; +} + +bool SDL_XINPUT_JoystickInit(void) +{ + bool enabled = SDL_GetHintBoolean(SDL_HINT_XINPUT_ENABLED, true); + + if (enabled && !WIN_LoadXInputDLL()) { + enabled = false; // oh well. + } + s_bXInputEnabled = enabled; + + return true; +} + +static const char *GetXInputName(const Uint8 userid, BYTE SubType) +{ + static char name[32]; + + switch (SubType) { + case XINPUT_DEVSUBTYPE_GAMEPAD: + (void)SDL_snprintf(name, sizeof(name), "XInput Controller #%d", 1 + userid); + break; + case XINPUT_DEVSUBTYPE_WHEEL: + (void)SDL_snprintf(name, sizeof(name), "XInput Wheel #%d", 1 + userid); + break; + case XINPUT_DEVSUBTYPE_ARCADE_STICK: + (void)SDL_snprintf(name, sizeof(name), "XInput ArcadeStick #%d", 1 + userid); + break; + case XINPUT_DEVSUBTYPE_FLIGHT_STICK: + (void)SDL_snprintf(name, sizeof(name), "XInput FlightStick #%d", 1 + userid); + break; + case XINPUT_DEVSUBTYPE_DANCE_PAD: + (void)SDL_snprintf(name, sizeof(name), "XInput DancePad #%d", 1 + userid); + break; + case XINPUT_DEVSUBTYPE_GUITAR: + case XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE: + case XINPUT_DEVSUBTYPE_GUITAR_BASS: + (void)SDL_snprintf(name, sizeof(name), "XInput Guitar #%d", 1 + userid); + break; + case XINPUT_DEVSUBTYPE_DRUM_KIT: + (void)SDL_snprintf(name, sizeof(name), "XInput DrumKit #%d", 1 + userid); + break; + case XINPUT_DEVSUBTYPE_ARCADE_PAD: + (void)SDL_snprintf(name, sizeof(name), "XInput ArcadePad #%d", 1 + userid); + break; + default: + (void)SDL_snprintf(name, sizeof(name), "XInput Device #%d", 1 + userid); + break; + } + return name; +} + +static bool GetXInputDeviceInfo(Uint8 userid, Uint16 *pVID, Uint16 *pPID, Uint16 *pVersion) +{ + SDL_XINPUT_CAPABILITIES_EX capabilities; + + if (!XINPUTGETCAPABILITIESEX || XINPUTGETCAPABILITIESEX(1, userid, 0, &capabilities) != ERROR_SUCCESS) { + // Use a generic VID/PID representing an XInput controller + if (pVID) { + *pVID = USB_VENDOR_MICROSOFT; + } + if (pPID) { + *pPID = USB_PRODUCT_XBOX360_XUSB_CONTROLLER; + } + return false; + } + + // Fixup for Wireless Xbox 360 Controller + if (capabilities.ProductId == 0 && capabilities.Capabilities.Flags & XINPUT_CAPS_WIRELESS) { + capabilities.VendorId = USB_VENDOR_MICROSOFT; + capabilities.ProductId = USB_PRODUCT_XBOX360_XUSB_CONTROLLER; + } + + if (pVID) { + *pVID = capabilities.VendorId; + } + if (pPID) { + *pPID = capabilities.ProductId; + } + if (pVersion) { + *pVersion = capabilities.ProductVersion; + } + return true; +} + +int SDL_XINPUT_GetSteamVirtualGamepadSlot(Uint8 userid) +{ + SDL_XINPUT_CAPABILITIES_EX capabilities; + + if (XINPUTGETCAPABILITIESEX && + XINPUTGETCAPABILITIESEX(1, userid, 0, &capabilities) == ERROR_SUCCESS && + capabilities.VendorId == USB_VENDOR_VALVE && + capabilities.ProductId == USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD) { + return (int)capabilities.unk2; + } + return -1; +} + +static void AddXInputDevice(Uint8 userid, BYTE SubType, JoyStick_DeviceData **pContext) +{ + const char *name = NULL; + Uint16 vendor = 0; + Uint16 product = 0; + Uint16 version = 0; + JoyStick_DeviceData *pPrevJoystick = NULL; + JoyStick_DeviceData *pNewJoystick = *pContext; + +#ifdef SDL_JOYSTICK_RAWINPUT + if (RAWINPUT_IsEnabled()) { + // The raw input driver handles more than 4 controllers, so prefer that when available + /* We do this check here rather than at the top of SDL_XINPUT_JoystickDetect() because + we need to check XInput state before RAWINPUT gets a hold of the device, otherwise + when a controller is connected via the wireless adapter, it will shut down at the + first subsequent XInput call. This seems like a driver stack bug? + + Reference: https://github.com/libsdl-org/SDL/issues/3468 + */ + return; + } +#endif + + if (SubType == XINPUT_DEVSUBTYPE_UNKNOWN) { + return; + } + + while (pNewJoystick) { + if (pNewJoystick->bXInputDevice && (pNewJoystick->XInputUserId == userid) && (pNewJoystick->SubType == SubType)) { + // if we are replacing the front of the list then update it + if (pNewJoystick == *pContext) { + *pContext = pNewJoystick->pNext; + } else if (pPrevJoystick) { + pPrevJoystick->pNext = pNewJoystick->pNext; + } + + pNewJoystick->pNext = SYS_Joystick; + SYS_Joystick = pNewJoystick; + return; // already in the list. + } + + pPrevJoystick = pNewJoystick; + pNewJoystick = pNewJoystick->pNext; + } + + name = GetXInputName(userid, SubType); + GetXInputDeviceInfo(userid, &vendor, &product, &version); + if (SDL_ShouldIgnoreJoystick(vendor, product, version, name) || + SDL_JoystickHandledByAnotherDriver(&SDL_WINDOWS_JoystickDriver, vendor, product, version, name)) { + return; + } + + pNewJoystick = (JoyStick_DeviceData *)SDL_calloc(1, sizeof(JoyStick_DeviceData)); + if (!pNewJoystick) { + return; // better luck next time? + } + + pNewJoystick->bXInputDevice = true; + pNewJoystick->joystickname = SDL_CreateJoystickName(vendor, product, NULL, name); + if (!pNewJoystick->joystickname) { + SDL_free(pNewJoystick); + return; // better luck next time? + } + (void)SDL_snprintf(pNewJoystick->path, sizeof(pNewJoystick->path), "XInput#%u", userid); + pNewJoystick->guid = SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_USB, vendor, product, version, NULL, name, 'x', SubType); + pNewJoystick->SubType = SubType; + pNewJoystick->XInputUserId = userid; + + WINDOWS_AddJoystickDevice(pNewJoystick); +} + +void SDL_XINPUT_JoystickDetect(JoyStick_DeviceData **pContext) +{ + int iuserid; + + if (!s_bXInputEnabled) { + return; + } + + // iterate in reverse, so these are in the final list in ascending numeric order. + for (iuserid = XUSER_MAX_COUNT - 1; iuserid >= 0; iuserid--) { + const Uint8 userid = (Uint8)iuserid; + XINPUT_CAPABILITIES capabilities; + if (XINPUTGETCAPABILITIES(userid, XINPUT_FLAG_GAMEPAD, &capabilities) == ERROR_SUCCESS) { + AddXInputDevice(userid, capabilities.SubType, pContext); + } + } +} + +bool SDL_XINPUT_JoystickPresent(Uint16 vendor, Uint16 product, Uint16 version) +{ + int iuserid; + + if (!s_bXInputEnabled) { + return false; + } + + // iterate in reverse, so these are in the final list in ascending numeric order. + for (iuserid = 0; iuserid < XUSER_MAX_COUNT; ++iuserid) { + const Uint8 userid = (Uint8)iuserid; + Uint16 slot_vendor; + Uint16 slot_product; + Uint16 slot_version; + if (GetXInputDeviceInfo(userid, &slot_vendor, &slot_product, &slot_version)) { + if (vendor == slot_vendor && product == slot_product && version == slot_version) { + return true; + } + } + } + return false; +} + +bool SDL_XINPUT_JoystickOpen(SDL_Joystick *joystick, JoyStick_DeviceData *joystickdevice) +{ + const Uint8 userId = joystickdevice->XInputUserId; + XINPUT_CAPABILITIES capabilities; + XINPUT_VIBRATION state; + + SDL_assert(s_bXInputEnabled); + SDL_assert(XINPUTGETCAPABILITIES); + SDL_assert(XINPUTSETSTATE); + SDL_assert(userId < XUSER_MAX_COUNT); + + joystick->hwdata->bXInputDevice = true; + + if (XINPUTGETCAPABILITIES(userId, XINPUT_FLAG_GAMEPAD, &capabilities) != ERROR_SUCCESS) { + SDL_free(joystick->hwdata); + joystick->hwdata = NULL; + return SDL_SetError("Failed to obtain XInput device capabilities. Device disconnected?"); + } + SDL_zero(state); + joystick->hwdata->bXInputHaptic = (XINPUTSETSTATE(userId, &state) == ERROR_SUCCESS); + joystick->hwdata->userid = userId; + + // The XInput API has a hard coded button/axis mapping, so we just match it + joystick->naxes = 6; + joystick->nbuttons = 11; + joystick->nhats = 1; + + SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true); + + return true; +} + +static void UpdateXInputJoystickBatteryInformation(SDL_Joystick *joystick, XINPUT_BATTERY_INFORMATION_EX *pBatteryInformation) +{ + SDL_PowerState state; + int percent; + switch (pBatteryInformation->BatteryType) { + case BATTERY_TYPE_WIRED: + state = SDL_POWERSTATE_CHARGING; + break; + case BATTERY_TYPE_UNKNOWN: + case BATTERY_TYPE_DISCONNECTED: + state = SDL_POWERSTATE_UNKNOWN; + break; + default: + state = SDL_POWERSTATE_ON_BATTERY; + break; + } + switch (pBatteryInformation->BatteryLevel) { + case BATTERY_LEVEL_EMPTY: + percent = 10; + break; + case BATTERY_LEVEL_LOW: + percent = 40; + break; + case BATTERY_LEVEL_MEDIUM: + percent = 70; + break; + default: + case BATTERY_LEVEL_FULL: + percent = 100; + break; + } + SDL_SendJoystickPowerInfo(joystick, state, percent); +} + +static void UpdateXInputJoystickState(SDL_Joystick *joystick, XINPUT_STATE *pXInputState, XINPUT_BATTERY_INFORMATION_EX *pBatteryInformation) +{ + static WORD s_XInputButtons[] = { + XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_X, XINPUT_GAMEPAD_Y, + XINPUT_GAMEPAD_LEFT_SHOULDER, XINPUT_GAMEPAD_RIGHT_SHOULDER, XINPUT_GAMEPAD_BACK, XINPUT_GAMEPAD_START, + XINPUT_GAMEPAD_LEFT_THUMB, XINPUT_GAMEPAD_RIGHT_THUMB, + XINPUT_GAMEPAD_GUIDE + }; + WORD wButtons = pXInputState->Gamepad.wButtons; + Uint8 button; + Uint8 hat = SDL_HAT_CENTERED; + Uint64 timestamp = SDL_GetTicksNS(); + + SDL_SendJoystickAxis(timestamp, joystick, 0, pXInputState->Gamepad.sThumbLX); + SDL_SendJoystickAxis(timestamp, joystick, 1, ~pXInputState->Gamepad.sThumbLY); + SDL_SendJoystickAxis(timestamp, joystick, 2, ((int)pXInputState->Gamepad.bLeftTrigger * 257) - 32768); + SDL_SendJoystickAxis(timestamp, joystick, 3, pXInputState->Gamepad.sThumbRX); + SDL_SendJoystickAxis(timestamp, joystick, 4, ~pXInputState->Gamepad.sThumbRY); + SDL_SendJoystickAxis(timestamp, joystick, 5, ((int)pXInputState->Gamepad.bRightTrigger * 257) - 32768); + + for (button = 0; button < (Uint8)SDL_arraysize(s_XInputButtons); ++button) { + bool down = ((wButtons & s_XInputButtons[button]) != 0); + SDL_SendJoystickButton(timestamp, joystick, button, down); + } + + if (wButtons & XINPUT_GAMEPAD_DPAD_UP) { + hat |= SDL_HAT_UP; + } + if (wButtons & XINPUT_GAMEPAD_DPAD_DOWN) { + hat |= SDL_HAT_DOWN; + } + if (wButtons & XINPUT_GAMEPAD_DPAD_LEFT) { + hat |= SDL_HAT_LEFT; + } + if (wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) { + hat |= SDL_HAT_RIGHT; + } + SDL_SendJoystickHat(timestamp, joystick, 0, hat); + + UpdateXInputJoystickBatteryInformation(joystick, pBatteryInformation); +} + +bool SDL_XINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + XINPUT_VIBRATION XVibration; + + if (!XINPUTSETSTATE) { + return SDL_Unsupported(); + } + + XVibration.wLeftMotorSpeed = low_frequency_rumble; + XVibration.wRightMotorSpeed = high_frequency_rumble; + if (XINPUTSETSTATE(joystick->hwdata->userid, &XVibration) != ERROR_SUCCESS) { + return SDL_SetError("XInputSetState() failed"); + } + return true; +} + +void SDL_XINPUT_JoystickUpdate(SDL_Joystick *joystick) +{ + DWORD result; + XINPUT_STATE XInputState; + XINPUT_BATTERY_INFORMATION_EX XBatteryInformation; + + if (!XINPUTGETSTATE) { + return; + } + + result = XINPUTGETSTATE(joystick->hwdata->userid, &XInputState); + if (result == ERROR_DEVICE_NOT_CONNECTED) { + return; + } + + SDL_zero(XBatteryInformation); + if (XINPUTGETBATTERYINFORMATION) { + result = XINPUTGETBATTERYINFORMATION(joystick->hwdata->userid, BATTERY_DEVTYPE_GAMEPAD, &XBatteryInformation); + } + +#if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES) + // XInputOnGameInput doesn't ever change dwPacketNumber, so have to just update every frame + UpdateXInputJoystickState(joystick, &XInputState, &XBatteryInformation); +#else + // only fire events if the data changed from last time + if (XInputState.dwPacketNumber && XInputState.dwPacketNumber != joystick->hwdata->dwPacketNumber) { + UpdateXInputJoystickState(joystick, &XInputState, &XBatteryInformation); + joystick->hwdata->dwPacketNumber = XInputState.dwPacketNumber; + } +#endif +} + +void SDL_XINPUT_JoystickClose(SDL_Joystick *joystick) +{ +} + +void SDL_XINPUT_JoystickQuit(void) +{ + if (s_bXInputEnabled) { + s_bXInputEnabled = false; + WIN_UnloadXInputDLL(); + } +} + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif + +#else // !SDL_JOYSTICK_XINPUT + +typedef struct JoyStick_DeviceData JoyStick_DeviceData; + +bool SDL_XINPUT_Enabled(void) +{ + return false; +} + +bool SDL_XINPUT_JoystickInit(void) +{ + return true; +} + +void SDL_XINPUT_JoystickDetect(JoyStick_DeviceData **pContext) +{ +} + +bool SDL_XINPUT_JoystickPresent(Uint16 vendor, Uint16 product, Uint16 version) +{ + return false; +} + +bool SDL_XINPUT_JoystickOpen(SDL_Joystick *joystick, JoyStick_DeviceData *joystickdevice) +{ + return SDL_Unsupported(); +} + +bool SDL_XINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) +{ + return SDL_Unsupported(); +} + +void SDL_XINPUT_JoystickUpdate(SDL_Joystick *joystick) +{ +} + +void SDL_XINPUT_JoystickClose(SDL_Joystick *joystick) +{ +} + +void SDL_XINPUT_JoystickQuit(void) +{ +} + +#endif // SDL_JOYSTICK_XINPUT diff --git a/thirdparty/sdl/joystick/windows/SDL_xinputjoystick_c.h b/thirdparty/sdl/joystick/windows/SDL_xinputjoystick_c.h new file mode 100644 index 00000000000..305b0909af6 --- /dev/null +++ b/thirdparty/sdl/joystick/windows/SDL_xinputjoystick_c.h @@ -0,0 +1,44 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "../../core/windows/SDL_xinput.h" + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +extern bool SDL_XINPUT_Enabled(void); +extern bool SDL_XINPUT_JoystickInit(void); +extern void SDL_XINPUT_JoystickDetect(JoyStick_DeviceData **pContext); +extern bool SDL_XINPUT_JoystickPresent(Uint16 vendor, Uint16 product, Uint16 version); +extern bool SDL_XINPUT_JoystickOpen(SDL_Joystick *joystick, JoyStick_DeviceData *joystickdevice); +extern bool SDL_XINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble); +extern void SDL_XINPUT_JoystickUpdate(SDL_Joystick *joystick); +extern void SDL_XINPUT_JoystickClose(SDL_Joystick *joystick); +extern void SDL_XINPUT_JoystickQuit(void); +extern int SDL_XINPUT_GetSteamVirtualGamepadSlot(Uint8 userid); + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif diff --git a/thirdparty/sdl/libm/e_atan2.c b/thirdparty/sdl/libm/e_atan2.c new file mode 100644 index 00000000000..0f5b2c07169 --- /dev/null +++ b/thirdparty/sdl/libm/e_atan2.c @@ -0,0 +1,135 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* __ieee754_atan2(y,x) + * Method : + * 1. Reduce y to positive by atan2(y,x)=-atan2(-y,x). + * 2. Reduce x to positive by (if x and y are unexceptional): + * ARG (x+iy) = arctan(y/x) ... if x > 0, + * ARG (x+iy) = pi - arctan[y/(-x)] ... if x < 0, + * + * Special cases: + * + * ATAN2((anything), NaN ) is NaN; + * ATAN2(NAN , (anything) ) is NaN; + * ATAN2(+-0, +(anything but NaN)) is +-0 ; + * ATAN2(+-0, -(anything but NaN)) is +-pi ; + * ATAN2(+-(anything but 0 and NaN), 0) is +-pi/2; + * ATAN2(+-(anything but INF and NaN), +INF) is +-0 ; + * ATAN2(+-(anything but INF and NaN), -INF) is +-pi; + * ATAN2(+-INF,+INF ) is +-pi/4 ; + * ATAN2(+-INF,-INF ) is +-3pi/4; + * ATAN2(+-INF, (anything but,0,NaN, and INF)) is +-pi/2; + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include "math_libm.h" +#include "math_private.h" + +static const double +tiny = 1.0e-300, +zero = 0.0, +pi_o_4 = 7.8539816339744827900E-01, /* 0x3FE921FB, 0x54442D18 */ +pi_o_2 = 1.5707963267948965580E+00, /* 0x3FF921FB, 0x54442D18 */ +pi = 3.1415926535897931160E+00, /* 0x400921FB, 0x54442D18 */ +pi_lo = 1.2246467991473531772E-16; /* 0x3CA1A626, 0x33145C07 */ + +double attribute_hidden __ieee754_atan2(double y, double x) +{ + double z; + int32_t k,m,hx,hy,ix,iy; + u_int32_t lx,ly; + + EXTRACT_WORDS(hx,lx,x); + ix = hx&0x7fffffff; + EXTRACT_WORDS(hy,ly,y); + iy = hy&0x7fffffff; + if(((ix|((lx|-(int32_t)lx)>>31))>0x7ff00000)|| + ((iy|((ly|-(int32_t)ly)>>31))>0x7ff00000)) /* x or y is NaN */ + return x+y; + if(((hx-0x3ff00000)|lx)==0) return atan(y); /* x=1.0 */ + m = ((hy>>31)&1)|((hx>>30)&2); /* 2*sign(x)+sign(y) */ + + /* when y = 0 */ + if((iy|ly)==0) { + switch(m) { + case 0: + case 1: return y; /* atan(+-0,+anything)=+-0 */ + case 2: return pi+tiny;/* atan(+0,-anything) = pi */ + case 3: return -pi-tiny;/* atan(-0,-anything) =-pi */ + } + } + /* when x = 0 */ + if((ix|lx)==0) return (hy<0)? -pi_o_2-tiny: pi_o_2+tiny; + + /* when x is INF */ + if(ix==0x7ff00000) { + if(iy==0x7ff00000) { + switch(m) { + case 0: return pi_o_4+tiny;/* atan(+INF,+INF) */ + case 1: return -pi_o_4-tiny;/* atan(-INF,+INF) */ + case 2: return 3.0*pi_o_4+tiny;/*atan(+INF,-INF)*/ + case 3: return -3.0*pi_o_4-tiny;/*atan(-INF,-INF)*/ + } + } else { + switch(m) { + case 0: return zero ; /* atan(+...,+INF) */ + case 1: return -zero ; /* atan(-...,+INF) */ + case 2: return pi+tiny ; /* atan(+...,-INF) */ + case 3: return -pi-tiny ; /* atan(-...,-INF) */ + } + } + } + /* when y is INF */ + if(iy==0x7ff00000) return (hy<0)? -pi_o_2-tiny: pi_o_2+tiny; + + /* compute y/x */ + k = (iy-ix)>>20; + if(k > 60) z=pi_o_2+0.5*pi_lo; /* |y/x| > 2**60 */ + else if(hx<0&&k<-60) z=0.0; /* |y|/x < -2**60 */ + else z=atan(fabs(y/x)); /* safe to do y/x */ + switch (m) { + case 0: return z ; /* atan(+,+) */ + case 1: { + u_int32_t zh; + GET_HIGH_WORD(zh,z); + SET_HIGH_WORD(z,zh ^ 0x80000000); + } + return z ; /* atan(-,+) */ + case 2: return pi-(z-pi_lo);/* atan(+,-) */ + default: /* case 3 */ + return (z-pi_lo)-pi;/* atan(-,-) */ + } +} + +/* + * wrapper atan2(y,x) + */ +#ifndef _IEEE_LIBM +double atan2(double y, double x) +{ + double z = __ieee754_atan2(y, x); + if (_LIB_VERSION == _IEEE_ || isnan(x) || isnan(y)) + return z; + if (x == 0.0 && y == 0.0) + return __kernel_standard(y,x,3); /* atan2(+-0,+-0) */ + return z; +} +#else +strong_alias(__ieee754_atan2, atan2) +#endif +libm_hidden_def(atan2) diff --git a/thirdparty/sdl/libm/e_exp.c b/thirdparty/sdl/libm/e_exp.c new file mode 100644 index 00000000000..f39bb5c5394 --- /dev/null +++ b/thirdparty/sdl/libm/e_exp.c @@ -0,0 +1,201 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* __ieee754_exp(x) + * Returns the exponential of x. + * + * Method + * 1. Argument reduction: + * Reduce x to an r so that |r| <= 0.5*ln2 ~ 0.34658. + * Given x, find r and integer k such that + * + * x = k*ln2 + r, |r| <= 0.5*ln2. + * + * Here r will be represented as r = hi-lo for better + * accuracy. + * + * 2. Approximation of exp(r) by a special rational function on + * the interval [0,0.34658]: + * Write + * R(r**2) = r*(exp(r)+1)/(exp(r)-1) = 2 + r*r/6 - r**4/360 + ... + * We use a special Reme algorithm on [0,0.34658] to generate + * a polynomial of degree 5 to approximate R. The maximum error + * of this polynomial approximation is bounded by 2**-59. In + * other words, + * R(z) ~ 2.0 + P1*z + P2*z**2 + P3*z**3 + P4*z**4 + P5*z**5 + * (where z=r*r, and the values of P1 to P5 are listed below) + * and + * | 5 | -59 + * | 2.0+P1*z+...+P5*z - R(z) | <= 2 + * | | + * The computation of exp(r) thus becomes + * 2*r + * exp(r) = 1 + ------- + * R - r + * r*R1(r) + * = 1 + r + ----------- (for better accuracy) + * 2 - R1(r) + * where + * 2 4 10 + * R1(r) = r - (P1*r + P2*r + ... + P5*r ). + * + * 3. Scale back to obtain exp(x): + * From step 1, we have + * exp(x) = 2^k * exp(r) + * + * Special cases: + * exp(INF) is INF, exp(NaN) is NaN; + * exp(-INF) is 0, and + * for finite argument, only exp(0)=1 is exact. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Misc. info. + * For IEEE double + * if x > 7.09782712893383973096e+02 then exp(x) overflow + * if x < -7.45133219101941108420e+02 then exp(x) underflow + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include "math_libm.h" +#include "math_private.h" + +#ifdef __WATCOMC__ /* Watcom defines huge=__huge */ +#undef huge +#endif + +static const double +one = 1.0, +halF[2] = {0.5,-0.5,}, +huge = 1.0e+300, +twom1000= 9.33263618503218878990e-302, /* 2**-1000=0x01700000,0*/ +o_threshold= 7.09782712893383973096e+02, /* 0x40862E42, 0xFEFA39EF */ +u_threshold= -7.45133219101941108420e+02, /* 0xc0874910, 0xD52D3051 */ +ln2HI[2] ={ 6.93147180369123816490e-01, /* 0x3fe62e42, 0xfee00000 */ + -6.93147180369123816490e-01,},/* 0xbfe62e42, 0xfee00000 */ +ln2LO[2] ={ 1.90821492927058770002e-10, /* 0x3dea39ef, 0x35793c76 */ + -1.90821492927058770002e-10,},/* 0xbdea39ef, 0x35793c76 */ +invln2 = 1.44269504088896338700e+00, /* 0x3ff71547, 0x652b82fe */ +P1 = 1.66666666666666019037e-01, /* 0x3FC55555, 0x5555553E */ +P2 = -2.77777777770155933842e-03, /* 0xBF66C16C, 0x16BEBD93 */ +P3 = 6.61375632143793436117e-05, /* 0x3F11566A, 0xAF25DE2C */ +P4 = -1.65339022054652515390e-06, /* 0xBEBBBD41, 0xC5D26BF1 */ +P5 = 4.13813679705723846039e-08; /* 0x3E663769, 0x72BEA4D0 */ + +union { + Uint64 u64; + double d; +} inf_union = { + SDL_UINT64_C(0x7ff0000000000000) /* Binary representation of a 64-bit infinite double (sign=0, exponent=2047, mantissa=0) */ +}; + +double __ieee754_exp(double x) /* default IEEE double exp */ +{ + double y; + double hi = 0.0; + double lo = 0.0; + double c; + double t; + int32_t k=0; + int32_t xsb; + u_int32_t hx; + + GET_HIGH_WORD(hx,x); + xsb = (hx>>31)&1; /* sign bit of x */ + hx &= 0x7fffffff; /* high word of |x| */ + + /* filter out non-finite argument */ + if(hx >= 0x40862E42) { /* if |x|>=709.78... */ + if(hx>=0x7ff00000) { + u_int32_t lx; + GET_LOW_WORD(lx,x); + if(((hx&0xfffff)|lx)!=0) + return x+x; /* NaN */ + else return (xsb==0)? x:0.0; /* exp(+-inf)={inf,0} */ + } + #if 1 + if(x > o_threshold) return inf_union.d; /* overflow */ + #elif 1 + if(x > o_threshold) return huge*huge; /* overflow */ + #else /* !!! FIXME: check this: "huge * huge" is a compiler warning, maybe they wanted +Inf? */ + if(x > o_threshold) return INFINITY; /* overflow */ + #endif + + if(x < u_threshold) return twom1000*twom1000; /* underflow */ + } + + /* argument reduction */ + if(hx > 0x3fd62e42) { /* if |x| > 0.5 ln2 */ + if(hx < 0x3FF0A2B2) { /* and |x| < 1.5 ln2 */ + hi = x-ln2HI[xsb]; lo=ln2LO[xsb]; k = 1-xsb-xsb; + } else { + k = (int32_t) (invln2*x+halF[xsb]); + t = k; + hi = x - t*ln2HI[0]; /* t*ln2HI is exact here */ + lo = t*ln2LO[0]; + } + x = hi - lo; + } + else if(hx < 0x3e300000) { /* when |x|<2**-28 */ + if(huge+x>one) return one+x;/* trigger inexact */ + } + else k = 0; + + /* x is now in primary range */ + t = x*x; + c = x - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))); + if(k==0) return one-((x*c)/(c-2.0)-x); + else y = one-((lo-(x*c)/(2.0-c))-hi); + if(k >= -1021) { + u_int32_t hy; + GET_HIGH_WORD(hy,y); + SET_HIGH_WORD(y,hy+(k<<20)); /* add k to y's exponent */ + return y; + } else { + u_int32_t hy; + GET_HIGH_WORD(hy,y); + SET_HIGH_WORD(y,hy+((k+1000)<<20)); /* add k to y's exponent */ + return y*twom1000; + } +} + +/* + * wrapper exp(x) + */ +#ifndef _IEEE_LIBM +double exp(double x) +{ + static const double o_threshold = 7.09782712893383973096e+02; /* 0x40862E42, 0xFEFA39EF */ + static const double u_threshold = -7.45133219101941108420e+02; /* 0xc0874910, 0xD52D3051 */ + + double z = __ieee754_exp(x); + if (_LIB_VERSION == _IEEE_) + return z; + if (isfinite(x)) { + if (x > o_threshold) + return __kernel_standard(x, x, 6); /* exp overflow */ + if (x < u_threshold) + return __kernel_standard(x, x, 7); /* exp underflow */ + } + return z; +} +#else +strong_alias(__ieee754_exp, exp) +#endif +libm_hidden_def(exp) diff --git a/thirdparty/sdl/libm/e_fmod.c b/thirdparty/sdl/libm/e_fmod.c new file mode 100644 index 00000000000..32c02492585 --- /dev/null +++ b/thirdparty/sdl/libm/e_fmod.c @@ -0,0 +1,145 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * __ieee754_fmod(x,y) + * Return x mod y in exact arithmetic + * Method: shift and subtract + */ + +#include "math_libm.h" +#include "math_private.h" + +static const double one = 1.0, Zero[] = {0.0, -0.0,}; + +double attribute_hidden __ieee754_fmod(double x, double y) +{ + int32_t n,hx,hy,hz,ix,iy,sx,i; + u_int32_t lx,ly,lz; + + EXTRACT_WORDS(hx,lx,x); + EXTRACT_WORDS(hy,ly,y); + sx = hx&0x80000000; /* sign of x */ + hx ^=sx; /* |x| */ + hy &= 0x7fffffff; /* |y| */ + + /* purge off exception values */ + if((hy|ly)==0||(hx>=0x7ff00000)|| /* y=0,or x not finite */ + ((hy|((ly|-(int32_t)ly)>>31))>0x7ff00000)) /* or y is NaN */ + return (x*y)/(x*y); + if(hx<=hy) { + if((hx>31]; /* |x|=|y| return x*0*/ + } + + /* determine ix = ilogb(x) */ + if(hx<0x00100000) { /* subnormal x */ + if(hx==0) { + for (ix = -1043, i=lx; i>0; i<<=1) ix -=1; + } else { + for (ix = -1022,i=(hx<<11); i>0; i<<=1) ix -=1; + } + } else ix = (hx>>20)-1023; + + /* determine iy = ilogb(y) */ + if(hy<0x00100000) { /* subnormal y */ + if(hy==0) { + for (iy = -1043, i=ly; i>0; i<<=1) iy -=1; + } else { + for (iy = -1022,i=(hy<<11); i>0; i<<=1) iy -=1; + } + } else iy = (hy>>20)-1023; + + /* set up {hx,lx}, {hy,ly} and align y to x */ + if(ix >= -1022) + hx = 0x00100000|(0x000fffff&hx); + else { /* subnormal x, shift x to normal */ + n = -1022-ix; + if(n<=31) { + hx = (hx<>(32-n)); + lx <<= n; + } else { + hx = lx<<(n-32); + lx = 0; + } + } + if(iy >= -1022) + hy = 0x00100000|(0x000fffff&hy); + else { /* subnormal y, shift y to normal */ + n = -1022-iy; + if(n<=31) { + hy = (hy<>(32-n)); + ly <<= n; + } else { + hy = ly<<(n-32); + ly = 0; + } + } + + /* fix point fmod */ + n = ix - iy; + while(n--) { + hz=hx-hy;lz=lx-ly; if(lx>31); lx = lx+lx;} + else { + if((hz|lz)==0) /* return sign(x)*0 */ + return Zero[(u_int32_t)sx>>31]; + hx = hz+hz+(lz>>31); lx = lz+lz; + } + } + hz=hx-hy;lz=lx-ly; if(lx=0) {hx=hz;lx=lz;} + + /* convert back to floating value and restore the sign */ + if((hx|lx)==0) /* return sign(x)*0 */ + return Zero[(u_int32_t)sx>>31]; + while(hx<0x00100000) { /* normalize x */ + hx = hx+hx+(lx>>31); lx = lx+lx; + iy -= 1; + } + if(iy>= -1022) { /* normalize output */ + hx = ((hx-0x00100000)|((iy+1023)<<20)); + INSERT_WORDS(x,hx|sx,lx); + } else { /* subnormal output */ + n = -1022 - iy; + if(n<=20) { + lx = (lx>>n)|((u_int32_t)hx<<(32-n)); + hx >>= n; + } else if (n<=31) { + lx = (hx<<(32-n))|(lx>>n); hx = sx; + } else { + lx = hx>>(n-32); hx = sx; + } + INSERT_WORDS(x,hx|sx,lx); + x *= one; /* create necessary signal */ + } + return x; /* exact output */ +} + +/* + * wrapper fmod(x,y) + */ +#ifndef _IEEE_LIBM +double fmod(double x, double y) +{ + double z = __ieee754_fmod(x, y); + if (_LIB_VERSION == _IEEE_ || isnan(y) || isnan(x)) + return z; + if (y == 0.0) + return __kernel_standard(x, y, 27); /* fmod(x,0) */ + return z; +} +#else +strong_alias(__ieee754_fmod, fmod) +#endif +libm_hidden_def(fmod) diff --git a/thirdparty/sdl/libm/e_log.c b/thirdparty/sdl/libm/e_log.c new file mode 100644 index 00000000000..f935fa70f40 --- /dev/null +++ b/thirdparty/sdl/libm/e_log.c @@ -0,0 +1,153 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#if defined(_MSC_VER) /* Handle Microsoft VC++ compiler specifics. */ +/* C4723: potential divide by zero. */ +#pragma warning ( disable : 4723 ) +#endif + +/* __ieee754_log(x) + * Return the logrithm of x + * + * Method : + * 1. Argument Reduction: find k and f such that + * x = 2^k * (1+f), + * where sqrt(2)/2 < 1+f < sqrt(2) . + * + * 2. Approximation of log(1+f). + * Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s) + * = 2s + 2/3 s**3 + 2/5 s**5 + ....., + * = 2s + s*R + * We use a special Reme algorithm on [0,0.1716] to generate + * a polynomial of degree 14 to approximate R The maximum error + * of this polynomial approximation is bounded by 2**-58.45. In + * other words, + * 2 4 6 8 10 12 14 + * R(z) ~ Lg1*s +Lg2*s +Lg3*s +Lg4*s +Lg5*s +Lg6*s +Lg7*s + * (the values of Lg1 to Lg7 are listed in the program) + * and + * | 2 14 | -58.45 + * | Lg1*s +...+Lg7*s - R(z) | <= 2 + * | | + * Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2. + * In order to guarantee error in log below 1ulp, we compute log + * by + * log(1+f) = f - s*(f - R) (if f is not too large) + * log(1+f) = f - (hfsq - s*(hfsq+R)). (better accuracy) + * + * 3. Finally, log(x) = k*ln2 + log(1+f). + * = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo))) + * Here ln2 is split into two floating point number: + * ln2_hi + ln2_lo, + * where n*ln2_hi is always exact for |n| < 2000. + * + * Special cases: + * log(x) is NaN with signal if x < 0 (including -INF) ; + * log(+INF) is +INF; log(0) is -INF with signal; + * log(NaN) is that NaN with no signal. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include "math_libm.h" +#include "math_private.h" + +static const double +ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */ +ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */ +two54 = 1.80143985094819840000e+16, /* 43500000 00000000 */ +Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ +Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ +Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ +Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ +Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ +Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ +Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ + +static const double zero = 0.0; + +double attribute_hidden __ieee754_log(double x) +{ + double hfsq,f,s,z,R,w,t1,t2,dk; + int32_t k,hx,i,j; + u_int32_t lx; + + EXTRACT_WORDS(hx,lx,x); + + k=0; + if (hx < 0x00100000) { /* x < 2**-1022 */ + if (((hx&0x7fffffff)|lx)==0) + return -two54/zero; /* log(+-0)=-inf */ + if (hx<0) return (x-x)/zero; /* log(-#) = NaN */ + k -= 54; x *= two54; /* subnormal number, scale up x */ + GET_HIGH_WORD(hx,x); + } + if (hx >= 0x7ff00000) return x+x; + k += (hx>>20)-1023; + hx &= 0x000fffff; + i = (hx+0x95f64)&0x100000; + SET_HIGH_WORD(x,hx|(i^0x3ff00000)); /* normalize x or x/2 */ + k += (i>>20); + f = x-1.0; + if((0x000fffff&(2+hx))<3) { /* |f| < 2**-20 */ + if(f==zero) {if(k==0) return zero; else {dk=(double)k; + return dk*ln2_hi+dk*ln2_lo;} + } + R = f*f*(0.5-0.33333333333333333*f); + if(k==0) return f-R; else {dk=(double)k; + return dk*ln2_hi-((R-dk*ln2_lo)-f);} + } + s = f/(2.0+f); + dk = (double)k; + z = s*s; + i = hx-0x6147a; + w = z*z; + j = 0x6b851-hx; + t1= w*(Lg2+w*(Lg4+w*Lg6)); + t2= z*(Lg1+w*(Lg3+w*(Lg5+w*Lg7))); + i |= j; + R = t2+t1; + if(i>0) { + hfsq=0.5*f*f; + if(k==0) return f-(hfsq-s*(hfsq+R)); else + return dk*ln2_hi-((hfsq-(s*(hfsq+R)+dk*ln2_lo))-f); + } else { + if(k==0) return f-s*(f-R); else + return dk*ln2_hi-((s*(f-R)-dk*ln2_lo)-f); + } +} + +/* + * wrapper log(x) + */ +#ifndef _IEEE_LIBM +double log(double x) +{ + double z = __ieee754_log(x); + if (_LIB_VERSION == _IEEE_ || isnan(x) || x > 0.0) + return z; + if (x == 0.0) + return __kernel_standard(x, x, 16); /* log(0) */ + return __kernel_standard(x, x, 17); /* log(x<0) */ +} +#else +strong_alias(__ieee754_log, log) +#endif +libm_hidden_def(log) diff --git a/thirdparty/sdl/libm/e_log10.c b/thirdparty/sdl/libm/e_log10.c new file mode 100644 index 00000000000..b6e736bd52d --- /dev/null +++ b/thirdparty/sdl/libm/e_log10.c @@ -0,0 +1,107 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#if defined(_MSC_VER) /* Handle Microsoft VC++ compiler specifics. */ +/* C4723: potential divide by zero. */ +#pragma warning ( disable : 4723 ) +#endif + +/* __ieee754_log10(x) + * Return the base 10 logarithm of x + * + * Method : + * Let log10_2hi = leading 40 bits of log10(2) and + * log10_2lo = log10(2) - log10_2hi, + * ivln10 = 1/log(10) rounded. + * Then + * n = ilogb(x), + * if(n<0) n = n+1; + * x = scalbn(x,-n); + * log10(x) := n*log10_2hi + (n*log10_2lo + ivln10*log(x)) + * + * Note 1: + * To guarantee log10(10**n)=n, where 10**n is normal, the rounding + * mode must set to Round-to-Nearest. + * Note 2: + * [1/log(10)] rounded to 53 bits has error .198 ulps; + * log10 is monotonic at all binary break points. + * + * Special cases: + * log10(x) is NaN with signal if x < 0; + * log10(+INF) is +INF with no signal; log10(0) is -INF with signal; + * log10(NaN) is that NaN with no signal; + * log10(10**N) = N for N=0,1,...,22. + * + * Constants: + * The hexadecimal values are the intended ones for the following constants. + * The decimal values may be used, provided that the compiler will convert + * from decimal to binary accurately enough to produce the hexadecimal values + * shown. + */ + +#include "math_libm.h" +#include "math_private.h" + +static const double +two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ +ivln10 = 4.34294481903251816668e-01, /* 0x3FDBCB7B, 0x1526E50E */ +log10_2hi = 3.01029995663611771306e-01, /* 0x3FD34413, 0x509F6000 */ +log10_2lo = 3.69423907715893078616e-13; /* 0x3D59FEF3, 0x11F12B36 */ + +static const double zero = 0.0; + +double attribute_hidden __ieee754_log10(double x) +{ + double y,z; + int32_t i,k,hx; + u_int32_t lx; + + EXTRACT_WORDS(hx,lx,x); + + k=0; + if (hx < 0x00100000) { /* x < 2**-1022 */ + if (((hx&0x7fffffff)|lx)==0) + return -two54/zero; /* log(+-0)=-inf */ + if (hx<0) return (x-x)/zero; /* log(-#) = NaN */ + k -= 54; x *= two54; /* subnormal number, scale up x */ + GET_HIGH_WORD(hx,x); + } + if (hx >= 0x7ff00000) return x+x; + k += (hx>>20)-1023; + i = ((u_int32_t)k&0x80000000)>>31; + hx = (hx&0x000fffff)|((0x3ff-i)<<20); + y = (double)(k+i); + SET_HIGH_WORD(x,hx); + z = y*log10_2lo + ivln10*__ieee754_log(x); + return z+y*log10_2hi; +} + +/* + * wrapper log10(X) + */ +#ifndef _IEEE_LIBM +double log10(double x) +{ + double z = __ieee754_log10(x); + if (_LIB_VERSION == _IEEE_ || isnan(x)) + return z; + if (x <= 0.0) { + if(x == 0.0) + return __kernel_standard(x, x, 18); /* log10(0) */ + return __kernel_standard(x, x, 19); /* log10(x<0) */ + } + return z; +} +#else +strong_alias(__ieee754_log10, log10) +#endif +libm_hidden_def(log10) diff --git a/thirdparty/sdl/libm/e_pow.c b/thirdparty/sdl/libm/e_pow.c new file mode 100644 index 00000000000..d1a141ec4be --- /dev/null +++ b/thirdparty/sdl/libm/e_pow.c @@ -0,0 +1,348 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* __ieee754_pow(x,y) return x**y + * + * n + * Method: Let x = 2 * (1+f) + * 1. Compute and return log2(x) in two pieces: + * log2(x) = w1 + w2, + * where w1 has 53-24 = 29 bit trailing zeros. + * 2. Perform y*log2(x) = n+y' by simulating muti-precision + * arithmetic, where |y'|<=0.5. + * 3. Return x**y = 2**n*exp(y'*log2) + * + * Special cases: + * 1. +-1 ** anything is 1.0 + * 2. +-1 ** +-INF is 1.0 + * 3. (anything) ** 0 is 1 + * 4. (anything) ** 1 is itself + * 5. (anything) ** NAN is NAN + * 6. NAN ** (anything except 0) is NAN + * 7. +-(|x| > 1) ** +INF is +INF + * 8. +-(|x| > 1) ** -INF is +0 + * 9. +-(|x| < 1) ** +INF is +0 + * 10 +-(|x| < 1) ** -INF is +INF + * 11. +0 ** (+anything except 0, NAN) is +0 + * 12. -0 ** (+anything except 0, NAN, odd integer) is +0 + * 13. +0 ** (-anything except 0, NAN) is +INF + * 14. -0 ** (-anything except 0, NAN, odd integer) is +INF + * 15. -0 ** (odd integer) = -( +0 ** (odd integer) ) + * 16. +INF ** (+anything except 0,NAN) is +INF + * 17. +INF ** (-anything except 0,NAN) is +0 + * 18. -INF ** (anything) = -0 ** (-anything) + * 19. (-anything) ** (integer) is (-1)**(integer)*(+anything**integer) + * 20. (-anything except 0 and inf) ** (non-integer) is NAN + * + * Accuracy: + * pow(x,y) returns x**y nearly rounded. In particular + * pow(integer,integer) + * always returns the correct integer provided it is + * representable. + * + * Constants : + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include "math_libm.h" +#include "math_private.h" + +#if defined(_MSC_VER) /* Handle Microsoft VC++ compiler specifics. */ +/* C4756: overflow in constant arithmetic */ +#pragma warning ( disable : 4756 ) +#endif + +#ifdef __WATCOMC__ /* Watcom defines huge=__huge */ +#undef huge +#endif + +static const double +bp[] = {1.0, 1.5,}, +dp_h[] = { 0.0, 5.84962487220764160156e-01,}, /* 0x3FE2B803, 0x40000000 */ +dp_l[] = { 0.0, 1.35003920212974897128e-08,}, /* 0x3E4CFDEB, 0x43CFD006 */ +zero = 0.0, +one = 1.0, +two = 2.0, +two53 = 9007199254740992.0, /* 0x43400000, 0x00000000 */ +huge = 1.0e300, +tiny = 1.0e-300, + /* poly coefs for (3/2)*(log(x)-2s-2/3*s**3 */ +L1 = 5.99999999999994648725e-01, /* 0x3FE33333, 0x33333303 */ +L2 = 4.28571428578550184252e-01, /* 0x3FDB6DB6, 0xDB6FABFF */ +L3 = 3.33333329818377432918e-01, /* 0x3FD55555, 0x518F264D */ +L4 = 2.72728123808534006489e-01, /* 0x3FD17460, 0xA91D4101 */ +L5 = 2.30660745775561754067e-01, /* 0x3FCD864A, 0x93C9DB65 */ +L6 = 2.06975017800338417784e-01, /* 0x3FCA7E28, 0x4A454EEF */ +P1 = 1.66666666666666019037e-01, /* 0x3FC55555, 0x5555553E */ +P2 = -2.77777777770155933842e-03, /* 0xBF66C16C, 0x16BEBD93 */ +P3 = 6.61375632143793436117e-05, /* 0x3F11566A, 0xAF25DE2C */ +P4 = -1.65339022054652515390e-06, /* 0xBEBBBD41, 0xC5D26BF1 */ +P5 = 4.13813679705723846039e-08, /* 0x3E663769, 0x72BEA4D0 */ +lg2 = 6.93147180559945286227e-01, /* 0x3FE62E42, 0xFEFA39EF */ +lg2_h = 6.93147182464599609375e-01, /* 0x3FE62E43, 0x00000000 */ +lg2_l = -1.90465429995776804525e-09, /* 0xBE205C61, 0x0CA86C39 */ +ovt = 8.0085662595372944372e-0017, /* -(1024-log2(ovfl+.5ulp)) */ +cp = 9.61796693925975554329e-01, /* 0x3FEEC709, 0xDC3A03FD =2/(3ln2) */ +cp_h = 9.61796700954437255859e-01, /* 0x3FEEC709, 0xE0000000 =(float)cp */ +cp_l = -7.02846165095275826516e-09, /* 0xBE3E2FE0, 0x145B01F5 =tail of cp_h*/ +ivln2 = 1.44269504088896338700e+00, /* 0x3FF71547, 0x652B82FE =1/ln2 */ +ivln2_h = 1.44269502162933349609e+00, /* 0x3FF71547, 0x60000000 =24b 1/ln2*/ +ivln2_l = 1.92596299112661746887e-08; /* 0x3E54AE0B, 0xF85DDF44 =1/ln2 tail*/ + +double attribute_hidden __ieee754_pow(double x, double y) +{ + double z,ax,z_h,z_l,p_h,p_l; + double y1,t1,t2,r,s,t,u,v,w; + int32_t i,j,k,yisint,n; + int32_t hx,hy,ix,iy; + u_int32_t lx,ly; + + EXTRACT_WORDS(hx,lx,x); + /* x==1: 1**y = 1 (even if y is NaN) */ + if (hx==0x3ff00000 && lx==0) { + return x; + } + ix = hx&0x7fffffff; + + EXTRACT_WORDS(hy,ly,y); + iy = hy&0x7fffffff; + + /* y==zero: x**0 = 1 */ + if((iy|ly)==0) return one; + + /* +-NaN return x+y */ + if(ix > 0x7ff00000 || ((ix==0x7ff00000)&&(lx!=0)) || + iy > 0x7ff00000 || ((iy==0x7ff00000)&&(ly!=0))) + return x+y; + + /* determine if y is an odd int when x < 0 + * yisint = 0 ... y is not an integer + * yisint = 1 ... y is an odd int + * yisint = 2 ... y is an even int + */ + yisint = 0; + if(hx<0) { + if(iy>=0x43400000) yisint = 2; /* even integer y */ + else if(iy>=0x3ff00000) { + k = (iy>>20)-0x3ff; /* exponent */ + if(k>20) { + j = ly>>(52-k); + if(((u_int32_t)j<<(52-k))==ly) yisint = 2-(j&1); + } else if(ly==0) { + j = iy>>(20-k); + if((j<<(20-k))==iy) yisint = 2-(j&1); + } + } + } + + /* special value of y */ + if(ly==0) { + if (iy==0x7ff00000) { /* y is +-inf */ + if (((ix-0x3ff00000)|lx)==0) + return one; /* +-1**+-inf is 1 (yes, weird rule) */ + if (ix >= 0x3ff00000) /* (|x|>1)**+-inf = inf,0 */ + return (hy>=0) ? y : zero; + /* (|x|<1)**-,+inf = inf,0 */ + return (hy<0) ? -y : zero; + } + if(iy==0x3ff00000) { /* y is +-1 */ + if(hy<0) return one/x; else return x; + } + if(hy==0x40000000) return x*x; /* y is 2 */ + if(hy==0x3fe00000) { /* y is 0.5 */ + if(hx>=0) /* x >= +0 */ + return __ieee754_sqrt(x); + } + } + + ax = fabs(x); + /* special value of x */ + if(lx==0) { + if(ix==0x7ff00000||ix==0||ix==0x3ff00000){ + z = ax; /*x is +-0,+-inf,+-1*/ + if(hy<0) z = one/z; /* z = (1/|x|) */ + if(hx<0) { + if(((ix-0x3ff00000)|yisint)==0) { + z = (z-z)/(z-z); /* (-1)**non-int is NaN */ + } else if(yisint==1) + z = -z; /* (x<0)**odd = -(|x|**odd) */ + } + return z; + } + } + + /* (x<0)**(non-int) is NaN */ + if(((((u_int32_t)hx>>31)-1)|yisint)==0) return (x-x)/(x-x); + + /* |y| is huge */ + if(iy>0x41e00000) { /* if |y| > 2**31 */ + if(iy>0x43f00000){ /* if |y| > 2**64, must o/uflow */ + if(ix<=0x3fefffff) return (hy<0)? huge*huge:tiny*tiny; + if(ix>=0x3ff00000) return (hy>0)? huge*huge:tiny*tiny; + } + /* over/underflow if x is not close to one */ + if(ix<0x3fefffff) return (hy<0)? huge*huge:tiny*tiny; + if(ix>0x3ff00000) return (hy>0)? huge*huge:tiny*tiny; + /* now |1-x| is tiny <= 2**-20, suffice to compute + log(x) by x-x^2/2+x^3/3-x^4/4 */ + t = x-1; /* t has 20 trailing zeros */ + w = (t*t)*(0.5-t*(0.3333333333333333333333-t*0.25)); + u = ivln2_h*t; /* ivln2_h has 21 sig. bits */ + v = t*ivln2_l-w*ivln2; + t1 = u+v; + SET_LOW_WORD(t1,0); + t2 = v-(t1-u); + } else { + double s2,s_h,s_l,t_h,t_l; + n = 0; + /* take care subnormal number */ + if(ix<0x00100000) + {ax *= two53; n -= 53; GET_HIGH_WORD(ix,ax); } + n += ((ix)>>20)-0x3ff; + j = ix&0x000fffff; + /* determine interval */ + ix = j|0x3ff00000; /* normalize ix */ + if(j<=0x3988E) k=0; /* |x|>1)|0x20000000)+0x00080000+(k<<18)); + t_l = ax - (t_h-bp[k]); + s_l = v*((u-s_h*t_h)-s_h*t_l); + /* compute log(ax) */ + s2 = s*s; + r = s2*s2*(L1+s2*(L2+s2*(L3+s2*(L4+s2*(L5+s2*L6))))); + r += s_l*(s_h+s); + s2 = s_h*s_h; + t_h = 3.0+s2+r; + SET_LOW_WORD(t_h,0); + t_l = r-((t_h-3.0)-s2); + /* u+v = s*(1+...) */ + u = s_h*t_h; + v = s_l*t_h+t_l*s; + /* 2/(3log2)*(s+...) */ + p_h = u+v; + SET_LOW_WORD(p_h,0); + p_l = v-(p_h-u); + z_h = cp_h*p_h; /* cp_h+cp_l = 2/(3*log2) */ + z_l = cp_l*p_h+p_l*cp+dp_l[k]; + /* log2(ax) = (s+..)*2/(3*log2) = n + dp_h + z_h + z_l */ + t = (double)n; + t1 = (((z_h+z_l)+dp_h[k])+t); + SET_LOW_WORD(t1,0); + t2 = z_l-(((t1-t)-dp_h[k])-z_h); + } + + s = one; /* s (sign of result -ve**odd) = -1 else = 1 */ + if(((((u_int32_t)hx>>31)-1)|(yisint-1))==0) + s = -one;/* (-ve)**(odd int) */ + + /* split up y into y1+y2 and compute (y1+y2)*(t1+t2) */ + y1 = y; + SET_LOW_WORD(y1,0); + p_l = (y-y1)*t1+y*t2; + p_h = y1*t1; + z = p_l+p_h; + EXTRACT_WORDS(j,i,z); + if (j>=0x40900000) { /* z >= 1024 */ + if(((j-0x40900000)|i)!=0) /* if z > 1024 */ + return s*huge*huge; /* overflow */ + else { + if(p_l+ovt>z-p_h) return s*huge*huge; /* overflow */ + } + } else if((j&0x7fffffff)>=0x4090cc00 ) { /* z <= -1075 */ + if(((j-0xc090cc00)|i)!=0) /* z < -1075 */ + return s*tiny*tiny; /* underflow */ + else { + if(p_l<=z-p_h) return s*tiny*tiny; /* underflow */ + } + } + /* + * compute 2**(p_h+p_l) + */ + i = j&0x7fffffff; + k = (i>>20)-0x3ff; + n = 0; + if(i>0x3fe00000) { /* if |z| > 0.5, set n = [z+0.5] */ + n = j+(0x00100000>>(k+1)); + k = ((n&0x7fffffff)>>20)-0x3ff; /* new k for n */ + t = zero; + SET_HIGH_WORD(t,n&~(0x000fffff>>k)); + n = ((n&0x000fffff)|0x00100000)>>(20-k); + if(j<0) n = -n; + p_h -= t; + } + t = p_l+p_h; + SET_LOW_WORD(t,0); + u = t*lg2_h; + v = (p_l-(t-p_h))*lg2+t*lg2_l; + z = u+v; + w = v-(z-u); + t = z*z; + t1 = z - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))); + r = (z*t1)/(t1-two)-(w+z*w); + z = one-(r-z); + GET_HIGH_WORD(j,z); + j += (n<<20); + if((j>>20)<=0) z = scalbn(z,n); /* subnormal output */ + else SET_HIGH_WORD(z,j); + return s*z; +} + +/* + * wrapper pow(x,y) return x**y + */ +#ifndef _IEEE_LIBM +double pow(double x, double y) +{ + double z = __ieee754_pow(x, y); + if (_LIB_VERSION == _IEEE_|| isnan(y)) + return z; + if (isnan(x)) { + if (y == 0.0) + return __kernel_standard(x, y, 42); /* pow(NaN,0.0) */ + return z; + } + if (x == 0.0) { + if (y == 0.0) + return __kernel_standard(x, y, 20); /* pow(0.0,0.0) */ + if (isfinite(y) && y < 0.0) + return __kernel_standard(x,y,23); /* pow(0.0,negative) */ + return z; + } + if (!isfinite(z)) { + if (isfinite(x) && isfinite(y)) { + if (isnan(z)) + return __kernel_standard(x, y, 24); /* pow neg**non-int */ + return __kernel_standard(x, y, 21); /* pow overflow */ + } + } + if (z == 0.0 && isfinite(x) && isfinite(y)) + return __kernel_standard(x, y, 22); /* pow underflow */ + return z; +} +#else +strong_alias(__ieee754_pow, pow) +#endif +libm_hidden_def(pow) diff --git a/thirdparty/sdl/libm/e_rem_pio2.c b/thirdparty/sdl/libm/e_rem_pio2.c new file mode 100644 index 00000000000..851560fe515 --- /dev/null +++ b/thirdparty/sdl/libm/e_rem_pio2.c @@ -0,0 +1,162 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* __ieee754_rem_pio2(x,y) + * + * return the remainder of x rem pi/2 in y[0]+y[1] + * use __kernel_rem_pio2() + */ + +#include "math_libm.h" +#include "math_private.h" + +/* + * Table of constants for 2/pi, 396 Hex digits (476 decimal) of 2/pi + */ +static const int32_t two_over_pi[] = { +0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62, +0x95993C, 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A, +0x424DD2, 0xE00649, 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129, +0xA73EE8, 0x8235F5, 0x2EBB44, 0x84E99C, 0x7026B4, 0x5F7E41, +0x3991D6, 0x398353, 0x39F49C, 0x845F8B, 0xBDF928, 0x3B1FF8, +0x97FFDE, 0x05980F, 0xEF2F11, 0x8B5A0A, 0x6D1F6D, 0x367ECF, +0x27CB09, 0xB74F46, 0x3F669E, 0x5FEA2D, 0x7527BA, 0xC7EBE5, +0xF17B3D, 0x0739F7, 0x8A5292, 0xEA6BFB, 0x5FB11F, 0x8D5D08, +0x560330, 0x46FC7B, 0x6BABF0, 0xCFBC20, 0x9AF436, 0x1DA9E3, +0x91615E, 0xE61B08, 0x659985, 0x5F14A0, 0x68408D, 0xFFD880, +0x4D7327, 0x310606, 0x1556CA, 0x73A8C9, 0x60E27B, 0xC08C6B, +}; + +static const int32_t npio2_hw[] = { +0x3FF921FB, 0x400921FB, 0x4012D97C, 0x401921FB, 0x401F6A7A, 0x4022D97C, +0x4025FDBB, 0x402921FB, 0x402C463A, 0x402F6A7A, 0x4031475C, 0x4032D97C, +0x40346B9C, 0x4035FDBB, 0x40378FDB, 0x403921FB, 0x403AB41B, 0x403C463A, +0x403DD85A, 0x403F6A7A, 0x40407E4C, 0x4041475C, 0x4042106C, 0x4042D97C, +0x4043A28C, 0x40446B9C, 0x404534AC, 0x4045FDBB, 0x4046C6CB, 0x40478FDB, +0x404858EB, 0x404921FB, +}; + +/* + * invpio2: 53 bits of 2/pi + * pio2_1: first 33 bit of pi/2 + * pio2_1t: pi/2 - pio2_1 + * pio2_2: second 33 bit of pi/2 + * pio2_2t: pi/2 - (pio2_1+pio2_2) + * pio2_3: third 33 bit of pi/2 + * pio2_3t: pi/2 - (pio2_1+pio2_2+pio2_3) + */ + +static const double +zero = 0.00000000000000000000e+00, /* 0x00000000, 0x00000000 */ +half = 5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */ +two24 = 1.67772160000000000000e+07, /* 0x41700000, 0x00000000 */ +invpio2 = 6.36619772367581382433e-01, /* 0x3FE45F30, 0x6DC9C883 */ +pio2_1 = 1.57079632673412561417e+00, /* 0x3FF921FB, 0x54400000 */ +pio2_1t = 6.07710050650619224932e-11, /* 0x3DD0B461, 0x1A626331 */ +pio2_2 = 6.07710050630396597660e-11, /* 0x3DD0B461, 0x1A600000 */ +pio2_2t = 2.02226624879595063154e-21, /* 0x3BA3198A, 0x2E037073 */ +pio2_3 = 2.02226624871116645580e-21, /* 0x3BA3198A, 0x2E000000 */ +pio2_3t = 8.47842766036889956997e-32; /* 0x397B839A, 0x252049C1 */ + +int32_t attribute_hidden __ieee754_rem_pio2(double x, double *y) +{ + double z=0.0,w,t,r,fn; + double tx[3]; + int32_t e0,i,j,nx,n,ix,hx; + u_int32_t low; + + GET_HIGH_WORD(hx,x); /* high word of x */ + ix = hx&0x7fffffff; + if(ix<=0x3fe921fb) /* |x| ~<= pi/4 , no need for reduction */ + {y[0] = x; y[1] = 0; return 0;} + if(ix<0x4002d97c) { /* |x| < 3pi/4, special case with n=+-1 */ + if(hx>0) { + z = x - pio2_1; + if(ix!=0x3ff921fb) { /* 33+53 bit pi is good enough */ + y[0] = z - pio2_1t; + y[1] = (z-y[0])-pio2_1t; + } else { /* near pi/2, use 33+33+53 bit pi */ + z -= pio2_2; + y[0] = z - pio2_2t; + y[1] = (z-y[0])-pio2_2t; + } + return 1; + } else { /* negative x */ + z = x + pio2_1; + if(ix!=0x3ff921fb) { /* 33+53 bit pi is good enough */ + y[0] = z + pio2_1t; + y[1] = (z-y[0])+pio2_1t; + } else { /* near pi/2, use 33+33+53 bit pi */ + z += pio2_2; + y[0] = z + pio2_2t; + y[1] = (z-y[0])+pio2_2t; + } + return -1; + } + } + if(ix<=0x413921fb) { /* |x| ~<= 2^19*(pi/2), medium size */ + t = fabs(x); + n = (int32_t) (t*invpio2+half); + fn = (double)n; + r = t-fn*pio2_1; + w = fn*pio2_1t; /* 1st round good to 85 bit */ + if(n<32&&ix!=npio2_hw[n-1]) { + y[0] = r-w; /* quick check no cancellation */ + } else { + u_int32_t high; + j = ix>>20; + y[0] = r-w; + GET_HIGH_WORD(high,y[0]); + i = j-((high>>20)&0x7ff); + if(i>16) { /* 2nd iteration needed, good to 118 */ + t = r; + w = fn*pio2_2; + r = t-w; + w = fn*pio2_2t-((t-r)-w); + y[0] = r-w; + GET_HIGH_WORD(high,y[0]); + i = j-((high>>20)&0x7ff); + if(i>49) { /* 3rd iteration need, 151 bits acc */ + t = r; /* will cover all possible cases */ + w = fn*pio2_3; + r = t-w; + w = fn*pio2_3t-((t-r)-w); + y[0] = r-w; + } + } + } + y[1] = (r-y[0])-w; + if(hx<0) {y[0] = -y[0]; y[1] = -y[1]; return -n;} + else return n; + } + /* + * all other (large) arguments + */ + if(ix>=0x7ff00000) { /* x is inf or NaN */ + y[0]=y[1]=x-x; return 0; + } + /* set z = scalbn(|x|,ilogb(x)-23) */ + GET_LOW_WORD(low,x); + SET_LOW_WORD(z,low); + e0 = (ix>>20)-1046; /* e0 = ilogb(z)-23; */ + SET_HIGH_WORD(z, ix - ((int32_t)(e0<<20))); + for(i=0;i<2;i++) { + tx[i] = (double)((int32_t)(z)); + z = (z-tx[i])*two24; + } + tx[2] = z; + nx = 3; + while((nx > 0) && tx[nx-1]==zero) nx--; /* skip zero term */ + n = __kernel_rem_pio2(tx,y,e0,nx,2,two_over_pi); + if(hx<0) {y[0] = -y[0]; y[1] = -y[1]; return -n;} + return n; +} diff --git a/thirdparty/sdl/libm/e_sqrt.c b/thirdparty/sdl/libm/e_sqrt.c new file mode 100644 index 00000000000..8ac58c62ac5 --- /dev/null +++ b/thirdparty/sdl/libm/e_sqrt.c @@ -0,0 +1,458 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* __ieee754_sqrt(x) + * Return correctly rounded sqrt. + * ------------------------------------------ + * | Use the hardware sqrt if you have one | + * ------------------------------------------ + * Method: + * Bit by bit method using integer arithmetic. (Slow, but portable) + * 1. Normalization + * Scale x to y in [1,4) with even powers of 2: + * find an integer k such that 1 <= (y=x*2^(2k)) < 4, then + * sqrt(x) = 2^k * sqrt(y) + * 2. Bit by bit computation + * Let q = sqrt(y) truncated to i bit after binary point (q = 1), + * i 0 + * i+1 2 + * s = 2*q , and y = 2 * ( y - q ). (1) + * i i i i + * + * To compute q from q , one checks whether + * i+1 i + * + * -(i+1) 2 + * (q + 2 ) <= y. (2) + * i + * -(i+1) + * If (2) is false, then q = q ; otherwise q = q + 2 . + * i+1 i i+1 i + * + * With some algebric manipulation, it is not difficult to see + * that (2) is equivalent to + * -(i+1) + * s + 2 <= y (3) + * i i + * + * The advantage of (3) is that s and y can be computed by + * i i + * the following recurrence formula: + * if (3) is false + * + * s = s , y = y ; (4) + * i+1 i i+1 i + * + * otherwise, + * -i -(i+1) + * s = s + 2 , y = y - s - 2 (5) + * i+1 i i+1 i i + * + * One may easily use induction to prove (4) and (5). + * Note. Since the left hand side of (3) contain only i+2 bits, + * it does not necessary to do a full (53-bit) comparison + * in (3). + * 3. Final rounding + * After generating the 53 bits result, we compute one more bit. + * Together with the remainder, we can decide whether the + * result is exact, bigger than 1/2ulp, or less than 1/2ulp + * (it will never equal to 1/2ulp). + * The rounding mode can be detected by checking whether + * huge + tiny is equal to huge, and whether huge - tiny is + * equal to huge for some floating point number "huge" and "tiny". + * + * Special cases: + * sqrt(+-0) = +-0 ... exact + * sqrt(inf) = inf + * sqrt(-ve) = NaN ... with invalid signal + * sqrt(NaN) = NaN ... with invalid signal for signaling NaN + * + * Other methods : see the appended file at the end of the program below. + *--------------- + */ + +#include "math_libm.h" +#include "math_private.h" + +static const double one = 1.0, tiny = 1.0e-300; + +double attribute_hidden __ieee754_sqrt(double x) +{ + double z; + int32_t sign = (int)0x80000000; + int32_t ix0,s0,q,m,t,i; + u_int32_t r,t1,s1,ix1,q1; + + EXTRACT_WORDS(ix0,ix1,x); + + /* take care of Inf and NaN */ + if((ix0&0x7ff00000)==0x7ff00000) { + return x*x+x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf + sqrt(-inf)=sNaN */ + } + /* take care of zero */ + if(ix0<=0) { + if(((ix0&(~sign))|ix1)==0) return x;/* sqrt(+-0) = +-0 */ + else if(ix0<0) + return (x-x)/(x-x); /* sqrt(-ve) = sNaN */ + } + /* normalize x */ + m = (ix0>>20); + if(m==0) { /* subnormal x */ + while(ix0==0) { + m -= 21; + ix0 |= (ix1>>11); ix1 <<= 21; + } + for(i=0;(ix0&0x00100000)==0;i++) ix0<<=1; + m -= i-1; + ix0 |= (ix1>>(32-i)); + ix1 <<= i; + } + m -= 1023; /* unbias exponent */ + ix0 = (ix0&0x000fffff)|0x00100000; + if(m&1){ /* odd m, double x to make it even */ + ix0 += ix0 + ((ix1&sign)>>31); + ix1 += ix1; + } + m >>= 1; /* m = [m/2] */ + + /* generate sqrt(x) bit by bit */ + ix0 += ix0 + ((ix1&sign)>>31); + ix1 += ix1; + q = q1 = s0 = s1 = 0; /* [q,q1] = sqrt(x) */ + r = 0x00200000; /* r = moving bit from right to left */ + + while(r!=0) { + t = s0+r; + if(t<=ix0) { + s0 = t+r; + ix0 -= t; + q += r; + } + ix0 += ix0 + ((ix1&sign)>>31); + ix1 += ix1; + r>>=1; + } + + r = sign; + while(r!=0) { + t1 = s1+r; + t = s0; + if((t>31); + ix1 += ix1; + r>>=1; + } + + /* use floating add to find out rounding direction */ + if((ix0|ix1)!=0) { + z = one-tiny; /* trigger inexact flag */ + if (z>=one) { + z = one+tiny; + if (q1==(u_int32_t)0xffffffff) { q1=0; q += 1;} + else if (z>one) { + if (q1==(u_int32_t)0xfffffffe) q+=1; + q1+=2; + } else + q1 += (q1&1); + } + } + ix0 = (q>>1)+0x3fe00000; + ix1 = q1>>1; + if ((q&1)==1) ix1 |= sign; + ix0 += (m <<20); + INSERT_WORDS(z,ix0,ix1); + return z; +} + +/* + * wrapper sqrt(x) + */ +#ifndef _IEEE_LIBM +double sqrt(double x) +{ + double z = __ieee754_sqrt(x); + if (_LIB_VERSION == _IEEE_ || isnan(x)) + return z; + if (x < 0.0) + return __kernel_standard(x, x, 26); /* sqrt(negative) */ + return z; +} +#else +strong_alias(__ieee754_sqrt, sqrt) +#endif +libm_hidden_def(sqrt) + + +/* +Other methods (use floating-point arithmetic) +------------- +(This is a copy of a drafted paper by Prof W. Kahan +and K.C. Ng, written in May, 1986) + + Two algorithms are given here to implement sqrt(x) + (IEEE double precision arithmetic) in software. + Both supply sqrt(x) correctly rounded. The first algorithm (in + Section A) uses newton iterations and involves four divisions. + The second one uses reciproot iterations to avoid division, but + requires more multiplications. Both algorithms need the ability + to chop results of arithmetic operations instead of round them, + and the INEXACT flag to indicate when an arithmetic operation + is executed exactly with no roundoff error, all part of the + standard (IEEE 754-1985). The ability to perform shift, add, + subtract and logical AND operations upon 32-bit words is needed + too, though not part of the standard. + +A. sqrt(x) by Newton Iteration + + (1) Initial approximation + + Let x0 and x1 be the leading and the trailing 32-bit words of + a floating point number x (in IEEE double format) respectively + + 1 11 52 ...widths + ------------------------------------------------------ + x: |s| e | f | + ------------------------------------------------------ + msb lsb msb lsb ...order + + + ------------------------ ------------------------ + x0: |s| e | f1 | x1: | f2 | + ------------------------ ------------------------ + + By performing shifts and subtracts on x0 and x1 (both regarded + as integers), we obtain an 8-bit approximation of sqrt(x) as + follows. + + k := (x0>>1) + 0x1ff80000; + y0 := k - T1[31&(k>>15)]. ... y ~ sqrt(x) to 8 bits + Here k is a 32-bit integer and T1[] is an integer array containing + correction terms. Now magically the floating value of y (y's + leading 32-bit word is y0, the value of its trailing word is 0) + approximates sqrt(x) to almost 8-bit. + + Value of T1: + static int T1[32]= { + 0, 1024, 3062, 5746, 9193, 13348, 18162, 23592, + 29598, 36145, 43202, 50740, 58733, 67158, 75992, 85215, + 83599, 71378, 60428, 50647, 41945, 34246, 27478, 21581, + 16499, 12183, 8588, 5674, 3403, 1742, 661, 130,}; + + (2) Iterative refinement + + Apply Heron's rule three times to y, we have y approximates + sqrt(x) to within 1 ulp (Unit in the Last Place): + + y := (y+x/y)/2 ... almost 17 sig. bits + y := (y+x/y)/2 ... almost 35 sig. bits + y := y-(y-x/y)/2 ... within 1 ulp + + + Remark 1. + Another way to improve y to within 1 ulp is: + + y := (y+x/y) ... almost 17 sig. bits to 2*sqrt(x) + y := y - 0x00100006 ... almost 18 sig. bits to sqrt(x) + + 2 + (x-y )*y + y := y + 2* ---------- ...within 1 ulp + 2 + 3y + x + + + This formula has one division fewer than the one above; however, + it requires more multiplications and additions. Also x must be + scaled in advance to avoid spurious overflow in evaluating the + expression 3y*y+x. Hence it is not recommended uless division + is slow. If division is very slow, then one should use the + reciproot algorithm given in section B. + + (3) Final adjustment + + By twiddling y's last bit it is possible to force y to be + correctly rounded according to the prevailing rounding mode + as follows. Let r and i be copies of the rounding mode and + inexact flag before entering the square root program. Also we + use the expression y+-ulp for the next representable floating + numbers (up and down) of y. Note that y+-ulp = either fixed + point y+-1, or multiply y by nextafter(1,+-inf) in chopped + mode. + + I := FALSE; ... reset INEXACT flag I + R := RZ; ... set rounding mode to round-toward-zero + z := x/y; ... chopped quotient, possibly inexact + If(not I) then { ... if the quotient is exact + if(z=y) { + I := i; ... restore inexact flag + R := r; ... restore rounded mode + return sqrt(x):=y. + } else { + z := z - ulp; ... special rounding + } + } + i := TRUE; ... sqrt(x) is inexact + If (r=RN) then z=z+ulp ... rounded-to-nearest + If (r=RP) then { ... round-toward-+inf + y = y+ulp; z=z+ulp; + } + y := y+z; ... chopped sum + y0:=y0-0x00100000; ... y := y/2 is correctly rounded. + I := i; ... restore inexact flag + R := r; ... restore rounded mode + return sqrt(x):=y. + + (4) Special cases + + Square root of +inf, +-0, or NaN is itself; + Square root of a negative number is NaN with invalid signal. + + +B. sqrt(x) by Reciproot Iteration + + (1) Initial approximation + + Let x0 and x1 be the leading and the trailing 32-bit words of + a floating point number x (in IEEE double format) respectively + (see section A). By performing shifs and subtracts on x0 and y0, + we obtain a 7.8-bit approximation of 1/sqrt(x) as follows. + + k := 0x5fe80000 - (x0>>1); + y0:= k - T2[63&(k>>14)]. ... y ~ 1/sqrt(x) to 7.8 bits + + Here k is a 32-bit integer and T2[] is an integer array + containing correction terms. Now magically the floating + value of y (y's leading 32-bit word is y0, the value of + its trailing word y1 is set to zero) approximates 1/sqrt(x) + to almost 7.8-bit. + + Value of T2: + static int T2[64]= { + 0x1500, 0x2ef8, 0x4d67, 0x6b02, 0x87be, 0xa395, 0xbe7a, 0xd866, + 0xf14a, 0x1091b,0x11fcd,0x13552,0x14999,0x15c98,0x16e34,0x17e5f, + 0x18d03,0x19a01,0x1a545,0x1ae8a,0x1b5c4,0x1bb01,0x1bfde,0x1c28d, + 0x1c2de,0x1c0db,0x1ba73,0x1b11c,0x1a4b5,0x1953d,0x18266,0x16be0, + 0x1683e,0x179d8,0x18a4d,0x19992,0x1a789,0x1b445,0x1bf61,0x1c989, + 0x1d16d,0x1d77b,0x1dddf,0x1e2ad,0x1e5bf,0x1e6e8,0x1e654,0x1e3cd, + 0x1df2a,0x1d635,0x1cb16,0x1be2c,0x1ae4e,0x19bde,0x1868e,0x16e2e, + 0x1527f,0x1334a,0x11051,0xe951, 0xbe01, 0x8e0d, 0x5924, 0x1edd,}; + + (2) Iterative refinement + + Apply Reciproot iteration three times to y and multiply the + result by x to get an approximation z that matches sqrt(x) + to about 1 ulp. To be exact, we will have + -1ulp < sqrt(x)-z<1.0625ulp. + + ... set rounding mode to Round-to-nearest + y := y*(1.5-0.5*x*y*y) ... almost 15 sig. bits to 1/sqrt(x) + y := y*((1.5-2^-30)+0.5*x*y*y)... about 29 sig. bits to 1/sqrt(x) + ... special arrangement for better accuracy + z := x*y ... 29 bits to sqrt(x), with z*y<1 + z := z + 0.5*z*(1-z*y) ... about 1 ulp to sqrt(x) + + Remark 2. The constant 1.5-2^-30 is chosen to bias the error so that + (a) the term z*y in the final iteration is always less than 1; + (b) the error in the final result is biased upward so that + -1 ulp < sqrt(x) - z < 1.0625 ulp + instead of |sqrt(x)-z|<1.03125ulp. + + (3) Final adjustment + + By twiddling y's last bit it is possible to force y to be + correctly rounded according to the prevailing rounding mode + as follows. Let r and i be copies of the rounding mode and + inexact flag before entering the square root program. Also we + use the expression y+-ulp for the next representable floating + numbers (up and down) of y. Note that y+-ulp = either fixed + point y+-1, or multiply y by nextafter(1,+-inf) in chopped + mode. + + R := RZ; ... set rounding mode to round-toward-zero + switch(r) { + case RN: ... round-to-nearest + if(x<= z*(z-ulp)...chopped) z = z - ulp; else + if(x<= z*(z+ulp)...chopped) z = z; else z = z+ulp; + break; + case RZ:case RM: ... round-to-zero or round-to--inf + R:=RP; ... reset rounding mod to round-to-+inf + if(x=(z+ulp)*(z+ulp) ...rounded up) z = z+ulp; + break; + case RP: ... round-to-+inf + if(x>(z+ulp)*(z+ulp)...chopped) z = z+2*ulp; else + if(x>z*z ...chopped) z = z+ulp; + break; + } + + Remark 3. The above comparisons can be done in fixed point. For + example, to compare x and w=z*z chopped, it suffices to compare + x1 and w1 (the trailing parts of x and w), regarding them as + two's complement integers. + + ...Is z an exact square root? + To determine whether z is an exact square root of x, let z1 be the + trailing part of z, and also let x0 and x1 be the leading and + trailing parts of x. + + If ((z1&0x03ffffff)!=0) ... not exact if trailing 26 bits of z!=0 + I := 1; ... Raise Inexact flag: z is not exact + else { + j := 1 - [(x0>>20)&1] ... j = logb(x) mod 2 + k := z1 >> 26; ... get z's 25-th and 26-th + fraction bits + I := i or (k&j) or ((k&(j+j+1))!=(x1&3)); + } + R:= r ... restore rounded mode + return sqrt(x):=z. + + If multiplication is cheaper then the foregoing red tape, the + Inexact flag can be evaluated by + + I := i; + I := (z*z!=x) or I. + + Note that z*z can overwrite I; this value must be sensed if it is + True. + + Remark 4. If z*z = x exactly, then bit 25 to bit 0 of z1 must be + zero. + + -------------------- + z1: | f2 | + -------------------- + bit 31 bit 0 + + Further more, bit 27 and 26 of z1, bit 0 and 1 of x1, and the odd + or even of logb(x) have the following relations: + + ------------------------------------------------- + bit 27,26 of z1 bit 1,0 of x1 logb(x) + ------------------------------------------------- + 00 00 odd and even + 01 01 even + 10 10 odd + 10 00 even + 11 01 even + ------------------------------------------------- + + (4) Special cases (see (4) of Section A). + + */ diff --git a/thirdparty/sdl/libm/k_cos.c b/thirdparty/sdl/libm/k_cos.c new file mode 100644 index 00000000000..399a40c78da --- /dev/null +++ b/thirdparty/sdl/libm/k_cos.c @@ -0,0 +1,83 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * __kernel_cos( x, y ) + * kernel cos function on [-pi/4, pi/4], pi/4 ~ 0.785398164 + * Input x is assumed to be bounded by ~pi/4 in magnitude. + * Input y is the tail of x. + * + * Algorithm + * 1. Since cos(-x) = cos(x), we need only to consider positive x. + * 2. if x < 2^-27 (hx<0x3e400000 0), return 1 with inexact if x!=0. + * 3. cos(x) is approximated by a polynomial of degree 14 on + * [0,pi/4] + * 4 14 + * cos(x) ~ 1 - x*x/2 + C1*x + ... + C6*x + * where the remez error is + * + * | 2 4 6 8 10 12 14 | -58 + * |cos(x)-(1-.5*x +C1*x +C2*x +C3*x +C4*x +C5*x +C6*x )| <= 2 + * | | + * + * 4 6 8 10 12 14 + * 4. let r = C1*x +C2*x +C3*x +C4*x +C5*x +C6*x , then + * cos(x) = 1 - x*x/2 + r + * since cos(x+y) ~ cos(x) - sin(x)*y + * ~ cos(x) - x*y, + * a correction term is necessary in cos(x) and hence + * cos(x+y) = 1 - (x*x/2 - (r - x*y)) + * For better accuracy when x > 0.3, let qx = |x|/4 with + * the last 32 bits mask off, and if x > 0.78125, let qx = 0.28125. + * Then + * cos(x+y) = (1-qx) - ((x*x/2-qx) - (r-x*y)). + * Note that 1-qx and (x*x/2-qx) is EXACT here, and the + * magnitude of the latter is at least a quarter of x*x/2, + * thus, reducing the rounding error in the subtraction. + */ + +#include "math_libm.h" +#include "math_private.h" + +static const double +one = 1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */ +C1 = 4.16666666666666019037e-02, /* 0x3FA55555, 0x5555554C */ +C2 = -1.38888888888741095749e-03, /* 0xBF56C16C, 0x16C15177 */ +C3 = 2.48015872894767294178e-05, /* 0x3EFA01A0, 0x19CB1590 */ +C4 = -2.75573143513906633035e-07, /* 0xBE927E4F, 0x809C52AD */ +C5 = 2.08757232129817482790e-09, /* 0x3E21EE9E, 0xBDB4B1C4 */ +C6 = -1.13596475577881948265e-11; /* 0xBDA8FAE9, 0xBE8838D4 */ + +double attribute_hidden __kernel_cos(double x, double y) +{ + double a,hz,z,r,qx; + int32_t ix; + GET_HIGH_WORD(ix,x); + ix &= 0x7fffffff; /* ix = |x|'s high word*/ + if(ix<0x3e400000) { /* if x < 2**27 */ + if(((int)x)==0) return one; /* generate inexact */ + } + z = x*x; + r = z*(C1+z*(C2+z*(C3+z*(C4+z*(C5+z*C6))))); + if(ix < 0x3FD33333) /* if |x| < 0.3 */ + return one - (0.5*z - (z*r - x*y)); + else { + if(ix > 0x3fe90000) { /* x > 0.78125 */ + qx = 0.28125; + } else { + INSERT_WORDS(qx,ix-0x00200000,0); /* x/4 */ + } + hz = 0.5*z-qx; + a = one-qx; + return a - (hz - (z*r-x*y)); + } +} diff --git a/thirdparty/sdl/libm/k_rem_pio2.c b/thirdparty/sdl/libm/k_rem_pio2.c new file mode 100644 index 00000000000..3dd5b2bf1dd --- /dev/null +++ b/thirdparty/sdl/libm/k_rem_pio2.c @@ -0,0 +1,315 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * __kernel_rem_pio2(x,y,e0,nx,prec,ipio2) + * double x[],y[]; int e0,nx,prec; int ipio2[]; + * + * __kernel_rem_pio2 return the last three digits of N with + * y = x - N*pi/2 + * so that |y| < pi/2. + * + * The method is to compute the integer (mod 8) and fraction parts of + * (2/pi)*x without doing the full multiplication. In general we + * skip the part of the product that are known to be a huge integer ( + * more accurately, = 0 mod 8 ). Thus the number of operations are + * independent of the exponent of the input. + * + * (2/pi) is represented by an array of 24-bit integers in ipio2[]. + * + * Input parameters: + * x[] The input value (must be positive) is broken into nx + * pieces of 24-bit integers in double precision format. + * x[i] will be the i-th 24 bit of x. The scaled exponent + * of x[0] is given in input parameter e0 (i.e., x[0]*2^e0 + * match x's up to 24 bits. + * + * Example of breaking a double positive z into x[0]+x[1]+x[2]: + * e0 = ilogb(z)-23 + * z = scalbn(z,-e0) + * for i = 0,1,2 + * x[i] = floor(z) + * z = (z-x[i])*2**24 + * + * + * y[] ouput result in an array of double precision numbers. + * The dimension of y[] is: + * 24-bit precision 1 + * 53-bit precision 2 + * 64-bit precision 2 + * 113-bit precision 3 + * The actual value is the sum of them. Thus for 113-bit + * precison, one may have to do something like: + * + * long double t,w,r_head, r_tail; + * t = (long double)y[2] + (long double)y[1]; + * w = (long double)y[0]; + * r_head = t+w; + * r_tail = w - (r_head - t); + * + * e0 The exponent of x[0] + * + * nx dimension of x[] + * + * prec an integer indicating the precision: + * 0 24 bits (single) + * 1 53 bits (double) + * 2 64 bits (extended) + * 3 113 bits (quad) + * + * ipio2[] + * integer array, contains the (24*i)-th to (24*i+23)-th + * bit of 2/pi after binary point. The corresponding + * floating value is + * + * ipio2[i] * 2^(-24(i+1)). + * + * External function: + * double scalbn(), floor(); + * + * + * Here is the description of some local variables: + * + * jk jk+1 is the initial number of terms of ipio2[] needed + * in the computation. The recommended value is 2,3,4, + * 6 for single, double, extended,and quad. + * + * jz local integer variable indicating the number of + * terms of ipio2[] used. + * + * jx nx - 1 + * + * jv index for pointing to the suitable ipio2[] for the + * computation. In general, we want + * ( 2^e0*x[0] * ipio2[jv-1]*2^(-24jv) )/8 + * is an integer. Thus + * e0-3-24*jv >= 0 or (e0-3)/24 >= jv + * Hence jv = max(0,(e0-3)/24). + * + * jp jp+1 is the number of terms in PIo2[] needed, jp = jk. + * + * q[] double array with integral value, representing the + * 24-bits chunk of the product of x and 2/pi. + * + * q0 the corresponding exponent of q[0]. Note that the + * exponent for q[i] would be q0-24*i. + * + * PIo2[] double precision array, obtained by cutting pi/2 + * into 24 bits chunks. + * + * f[] ipio2[] in floating point + * + * iq[] integer array by breaking up q[] in 24-bits chunk. + * + * fq[] final product of x*(2/pi) in fq[0],..,fq[jk] + * + * ih integer. If >0 it indicates q[] is >= 0.5, hence + * it also indicates the *sign* of the result. + * + */ + + +/* + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include "math_libm.h" +#include "math_private.h" + + +static const int init_jk[] = {2,3,4,6}; /* initial value for jk */ + +static const double PIo2[] = { + 1.57079625129699707031e+00, /* 0x3FF921FB, 0x40000000 */ + 7.54978941586159635335e-08, /* 0x3E74442D, 0x00000000 */ + 5.39030252995776476554e-15, /* 0x3CF84698, 0x80000000 */ + 3.28200341580791294123e-22, /* 0x3B78CC51, 0x60000000 */ + 1.27065575308067607349e-29, /* 0x39F01B83, 0x80000000 */ + 1.22933308981111328932e-36, /* 0x387A2520, 0x40000000 */ + 2.73370053816464559624e-44, /* 0x36E38222, 0x80000000 */ + 2.16741683877804819444e-51, /* 0x3569F31D, 0x00000000 */ +}; + +static const double +zero = 0.0, +one = 1.0, +two24 = 1.67772160000000000000e+07, /* 0x41700000, 0x00000000 */ +twon24 = 5.96046447753906250000e-08; /* 0x3E700000, 0x00000000 */ + +int32_t attribute_hidden __kernel_rem_pio2(const double *x, double *y, int e0, int nx, const unsigned int prec, const int32_t *ipio2) +{ + int32_t jz,jx,jv,jp,jk,carry,n,iq[20],i,j,k,m,q0,ih; + double z,fw,f[20],fq[20],q[20]; + + if (nx < 1) { + return 0; + } + + /* initialize jk*/ + SDL_assert(prec < SDL_arraysize(init_jk)); + jk = init_jk[prec]; + SDL_assert(jk > 0); + jp = jk; + + /* determine jx,jv,q0, note that 3>q0 */ + jx = nx-1; + jv = (e0-3)/24; if(jv<0) jv=0; + q0 = e0-24*(jv+1); + + /* set up f[0] to f[jx+jk] where f[jx+jk] = ipio2[jv+jk] */ + j = jv-jx; m = jx+jk; + for(i=0;i<=m;i++,j++) f[i] = (j<0)? zero : (double) ipio2[j]; + if ((m+1) < SDL_arraysize(f)) { + SDL_memset(&f[m+1], 0, sizeof (f) - ((m+1) * sizeof (f[0]))); + } + + /* compute q[0],q[1],...q[jk] */ + for (i=0;i<=jk;i++) { + for(j=0,fw=0.0;j<=jx;j++) fw += x[j]*f[jx+i-j]; + q[i] = fw; + } + + jz = jk; +recompute: + /* distill q[] into iq[] reversingly */ + for(i=0,j=jz,z=q[jz];j>0;i++,j--) { + fw = (double)((int32_t)(twon24* z)); + iq[i] = (int32_t)(z-two24*fw); + z = q[j-1]+fw; + } + if (jz < SDL_arraysize(iq)) { + SDL_memset(&iq[jz], 0, sizeof (iq) - (jz * sizeof (iq[0]))); + } + + /* compute n */ + z = scalbn(z,q0); /* actual value of z */ + z -= 8.0*floor(z*0.125); /* trim off integer >= 8 */ + n = (int32_t) z; + z -= (double)n; + ih = 0; + if(q0>0) { /* need iq[jz-1] to determine n */ + i = (iq[jz-1]>>(24-q0)); n += i; + iq[jz-1] -= i<<(24-q0); + ih = iq[jz-1]>>(23-q0); + } + else if(q0==0) ih = iq[jz-1]>>23; + else if(z>=0.5) ih=2; + + if(ih>0) { /* q > 0.5 */ + n += 1; carry = 0; + for(i=0;i0) { /* rare case: chance is 1 in 12 */ + switch(q0) { + case 1: + iq[jz-1] &= 0x7fffff; break; + case 2: + iq[jz-1] &= 0x3fffff; break; + } + } + if(ih==2) { + z = one - z; + if(carry!=0) z -= scalbn(one,q0); + } + } + + /* check if recomputation is needed */ + if(z==zero) { + j = 0; + for (i=jz-1;i>=jk;i--) j |= iq[i]; + if(j==0) { /* need recomputation */ + for(k=1;iq[jk-k]==0;k++); /* k = no. of terms needed */ + + for(i=jz+1;i<=jz+k;i++) { /* add q[jz+1] to q[jz+k] */ + f[jx+i] = (double) ipio2[jv+i]; + for(j=0,fw=0.0;j<=jx;j++) fw += x[j]*f[jx+i-j]; + q[i] = fw; + } + jz += k; + goto recompute; + } + } + + /* chop off zero terms */ + if(z==0.0) { + jz -= 1; q0 -= 24; + SDL_assert(jz >= 0); + while(iq[jz]==0) { jz--; SDL_assert(jz >= 0); q0-=24;} + } else { /* break z into 24-bit if necessary */ + z = scalbn(z,-q0); + if(z>=two24) { + fw = (double)((int32_t)(twon24*z)); + iq[jz] = (int32_t)(z-two24*fw); + jz += 1; q0 += 24; + iq[jz] = (int32_t) fw; + } else iq[jz] = (int32_t) z ; + } + + /* convert integer "bit" chunk to floating-point value */ + fw = scalbn(one,q0); + for(i=jz;i>=0;i--) { + q[i] = fw*(double)iq[i]; fw*=twon24; + } + + /* compute PIo2[0,...,jp]*q[jz,...,0] */ + SDL_zero(fq); + for(i=jz;i>=0;i--) { + for(fw=0.0,k=0;k<=jp&&k<=jz-i;k++) fw += PIo2[k]*q[i+k]; + fq[jz-i] = fw; + } + + /* compress fq[] into y[] */ + switch(prec) { + case 0: + fw = 0.0; + for (i=jz;i>=0;i--) fw += fq[i]; + y[0] = (ih==0)? fw: -fw; + break; + case 1: + case 2: + fw = 0.0; + for (i=jz;i>=0;i--) fw += fq[i]; + y[0] = (ih==0)? fw: -fw; + fw = fq[0]-fw; + for (i=1;i<=jz;i++) fw += fq[i]; + y[1] = (ih==0)? fw: -fw; + break; + case 3: /* painful */ + for (i=jz;i>0;i--) { + fw = fq[i-1]+fq[i]; + fq[i] += fq[i-1]-fw; + fq[i-1] = fw; + } + for (i=jz;i>1;i--) { + fw = fq[i-1]+fq[i]; + fq[i] += fq[i-1]-fw; + fq[i-1] = fw; + } + for (fw=0.0,i=jz;i>=2;i--) fw += fq[i]; + if(ih==0) { + y[0] = fq[0]; y[1] = fq[1]; y[2] = fw; + } else { + y[0] = -fq[0]; y[1] = -fq[1]; y[2] = -fw; + } + } + return n&7; +} diff --git a/thirdparty/sdl/libm/k_sin.c b/thirdparty/sdl/libm/k_sin.c new file mode 100644 index 00000000000..b7596ae50d9 --- /dev/null +++ b/thirdparty/sdl/libm/k_sin.c @@ -0,0 +1,66 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* __kernel_sin( x, y, iy) + * kernel sin function on [-pi/4, pi/4], pi/4 ~ 0.7854 + * Input x is assumed to be bounded by ~pi/4 in magnitude. + * Input y is the tail of x. + * Input iy indicates whether y is 0. (if iy=0, y assume to be 0). + * + * Algorithm + * 1. Since sin(-x) = -sin(x), we need only to consider positive x. + * 2. if x < 2^-27 (hx<0x3e400000 0), return x with inexact if x!=0. + * 3. sin(x) is approximated by a polynomial of degree 13 on + * [0,pi/4] + * 3 13 + * sin(x) ~ x + S1*x + ... + S6*x + * where + * + * |sin(x) 2 4 6 8 10 12 | -58 + * |----- - (1+S1*x +S2*x +S3*x +S4*x +S5*x +S6*x )| <= 2 + * | x | + * + * 4. sin(x+y) = sin(x) + sin'(x')*y + * ~ sin(x) + (1-x*x/2)*y + * For better accuracy, let + * 3 2 2 2 2 + * r = x *(S2+x *(S3+x *(S4+x *(S5+x *S6)))) + * then 3 2 + * sin(x) = x + (S1*x + (x *(r-y/2)+y)) + */ + +#include "math_libm.h" +#include "math_private.h" + +static const double +half = 5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */ +S1 = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */ +S2 = 8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */ +S3 = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */ +S4 = 2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */ +S5 = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */ +S6 = 1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */ + +double attribute_hidden __kernel_sin(double x, double y, int iy) +{ + double z,r,v; + int32_t ix; + GET_HIGH_WORD(ix,x); + ix &= 0x7fffffff; /* high word of x */ + if(ix<0x3e400000) /* |x| < 2**-27 */ + {if((int)x==0) return x;} /* generate inexact */ + z = x*x; + v = z*x; + r = S2+z*(S3+z*(S4+z*(S5+z*S6))); + if(iy==0) return x+v*(S1+z*r); + else return x-((z*(half*y-v*r)-y)-v*S1); +} diff --git a/thirdparty/sdl/libm/k_tan.c b/thirdparty/sdl/libm/k_tan.c new file mode 100644 index 00000000000..1405e034ab5 --- /dev/null +++ b/thirdparty/sdl/libm/k_tan.c @@ -0,0 +1,119 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* __kernel_tan( x, y, k ) + * kernel tan function on [-pi/4, pi/4], pi/4 ~ 0.7854 + * Input x is assumed to be bounded by ~pi/4 in magnitude. + * Input y is the tail of x. + * Input k indicates whether tan (if k=1) or + * -1/tan (if k= -1) is returned. + * + * Algorithm + * 1. Since tan(-x) = -tan(x), we need only to consider positive x. + * 2. if x < 2^-28 (hx<0x3e300000 0), return x with inexact if x!=0. + * 3. tan(x) is approximated by a odd polynomial of degree 27 on + * [0,0.67434] + * 3 27 + * tan(x) ~ x + T1*x + ... + T13*x + * where + * + * |tan(x) 2 4 26 | -59.2 + * |----- - (1+T1*x +T2*x +.... +T13*x )| <= 2 + * | x | + * + * Note: tan(x+y) = tan(x) + tan'(x)*y + * ~ tan(x) + (1+x*x)*y + * Therefore, for better accuracy in computing tan(x+y), let + * 3 2 2 2 2 + * r = x *(T2+x *(T3+x *(...+x *(T12+x *T13)))) + * then + * 3 2 + * tan(x+y) = x + (T1*x + (x *(r+y)+y)) + * + * 4. For x in [0.67434,pi/4], let y = pi/4 - x, then + * tan(x) = tan(pi/4-y) = (1-tan(y))/(1+tan(y)) + * = 1 - 2*(tan(y) - (tan(y)^2)/(1+tan(y))) + */ + +#include "math_libm.h" +#include "math_private.h" + +static const double +one = 1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */ +pio4 = 7.85398163397448278999e-01, /* 0x3FE921FB, 0x54442D18 */ +pio4lo= 3.06161699786838301793e-17, /* 0x3C81A626, 0x33145C07 */ +T[] = { + 3.33333333333334091986e-01, /* 0x3FD55555, 0x55555563 */ + 1.33333333333201242699e-01, /* 0x3FC11111, 0x1110FE7A */ + 5.39682539762260521377e-02, /* 0x3FABA1BA, 0x1BB341FE */ + 2.18694882948595424599e-02, /* 0x3F9664F4, 0x8406D637 */ + 8.86323982359930005737e-03, /* 0x3F8226E3, 0xE96E8493 */ + 3.59207910759131235356e-03, /* 0x3F6D6D22, 0xC9560328 */ + 1.45620945432529025516e-03, /* 0x3F57DBC8, 0xFEE08315 */ + 5.88041240820264096874e-04, /* 0x3F4344D8, 0xF2F26501 */ + 2.46463134818469906812e-04, /* 0x3F3026F7, 0x1A8D1068 */ + 7.81794442939557092300e-05, /* 0x3F147E88, 0xA03792A6 */ + 7.14072491382608190305e-05, /* 0x3F12B80F, 0x32F0A7E9 */ + -1.85586374855275456654e-05, /* 0xBEF375CB, 0xDB605373 */ + 2.59073051863633712884e-05, /* 0x3EFB2A70, 0x74BF7AD4 */ +}; + +double attribute_hidden __kernel_tan(double x, double y, int iy) +{ + double z,r,v,w,s; + int32_t ix,hx; + GET_HIGH_WORD(hx,x); + ix = hx&0x7fffffff; /* high word of |x| */ + if(ix<0x3e300000) /* x < 2**-28 */ + {if((int)x==0) { /* generate inexact */ + u_int32_t low; + GET_LOW_WORD(low,x); + if(((ix|low)|(iy+1))==0) return one/fabs(x); + else return (iy==1)? x: -one/x; + } + } + if(ix>=0x3FE59428) { /* |x|>=0.6744 */ + if(hx<0) {x = -x; y = -y;} + z = pio4-x; + w = pio4lo-y; + x = z+w; y = 0.0; + } + z = x*x; + w = z*z; + /* Break x^5*(T[1]+x^2*T[2]+...) into + * x^5(T[1]+x^4*T[3]+...+x^20*T[11]) + + * x^5(x^2*(T[2]+x^4*T[4]+...+x^22*[T12])) + */ + r = T[1]+w*(T[3]+w*(T[5]+w*(T[7]+w*(T[9]+w*T[11])))); + v = z*(T[2]+w*(T[4]+w*(T[6]+w*(T[8]+w*(T[10]+w*T[12]))))); + s = z*x; + r = y + z*(s*(r+v)+y); + r += T[0]*s; + w = x+r; + if(ix>=0x3FE59428) { + v = (double)iy; + return (double)(1-((hx>>30)&2))*(v-2.0*(x-(w*w/(w+v)-r))); + } + if(iy==1) return w; + else { /* if allow error up to 2 ulp, + simply return -1.0/(x+r) here */ + /* compute -1.0/(x+r) accurately */ + double a,t; + z = w; + SET_LOW_WORD(z,0); + v = r-(z - x); /* z+v = r+x */ + t = a = -1.0/w; /* a = -1.0/w */ + SET_LOW_WORD(t,0); + s = 1.0+t*z; + return t+a*(s+t*v); + } +} diff --git a/thirdparty/sdl/libm/math_libm.h b/thirdparty/sdl/libm/math_libm.h new file mode 100644 index 00000000000..b7b1614045c --- /dev/null +++ b/thirdparty/sdl/libm/math_libm.h @@ -0,0 +1,50 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef math_libm_h_ +#define math_libm_h_ + +#include "SDL_internal.h" + +/* Math routines from uClibc: http://www.uclibc.org */ + +extern double SDL_uclibc_atan(double x); +extern double SDL_uclibc_atan2(double y, double x); +extern double SDL_uclibc_copysign(double x, double y); +extern double SDL_uclibc_cos(double x); +extern double SDL_uclibc_exp(double x); +extern double SDL_uclibc_fabs(double x); +extern double SDL_uclibc_floor(double x); +extern double SDL_uclibc_fmod(double x, double y); +extern int SDL_uclibc_isinf(double x); +extern int SDL_uclibc_isinff(float x); +extern int SDL_uclibc_isnan(double x); +extern int SDL_uclibc_isnanf(float x); +extern double SDL_uclibc_log(double x); +extern double SDL_uclibc_log10(double x); +extern double SDL_uclibc_modf(double x, double *y); +extern double SDL_uclibc_pow(double x, double y); +extern double SDL_uclibc_scalbn(double x, int n); +extern double SDL_uclibc_sin(double x); +extern double SDL_uclibc_sqrt(double x); +extern double SDL_uclibc_tan(double x); + +#endif /* math_libm_h_ */ diff --git a/thirdparty/sdl/libm/math_private.h b/thirdparty/sdl/libm/math_private.h new file mode 100644 index 00000000000..b7d60e43107 --- /dev/null +++ b/thirdparty/sdl/libm/math_private.h @@ -0,0 +1,234 @@ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * from: @(#)fdlibm.h 5.1 93/09/24 + * $Id: math_private.h,v 1.3 2004/02/09 07:10:38 andersen Exp $ + */ + +#ifndef _MATH_PRIVATE_H_ +#define _MATH_PRIVATE_H_ + +/* #include */ +/* #include */ + +#define _IEEE_LIBM +#define attribute_hidden +#define libm_hidden_proto(x) +#define libm_hidden_def(x) +#define strong_alias(x, y) +#define weak_alias(x, y) + +#if !defined(SDL_PLATFORM_HAIKU) && !defined(SDL_PLATFORM_PSP) && !defined(SDL_PLATFORM_3DS) && !defined(SDL_PLATFORM_PS2) /* already defined in a system header. */ +typedef unsigned int u_int32_t; +#endif + +#define atan SDL_uclibc_atan +#define __ieee754_atan2 SDL_uclibc_atan2 +#define copysign SDL_uclibc_copysign +#define cos SDL_uclibc_cos +#define __ieee754_exp SDL_uclibc_exp +#define fabs SDL_uclibc_fabs +#define floor SDL_uclibc_floor +#define __ieee754_fmod SDL_uclibc_fmod +#undef __isinf +#define __isinf SDL_uclibc_isinf +#undef __isinff +#define __isinff SDL_uclibc_isinff +#undef __isnan +#define __isnan SDL_uclibc_isnan +#undef __isnanf +#define __isnanf SDL_uclibc_isnanf +#define __ieee754_log SDL_uclibc_log +#define __ieee754_log10 SDL_uclibc_log10 +#define modf SDL_uclibc_modf +#define __ieee754_pow SDL_uclibc_pow +#define scalbln SDL_uclibc_scalbln +#define scalbn SDL_uclibc_scalbn +#define sin SDL_uclibc_sin +#define __ieee754_sqrt SDL_uclibc_sqrt +#define tan SDL_uclibc_tan + +/* The original fdlibm code used statements like: + n0 = ((*(int*)&one)>>29)^1; * index of high word * + ix0 = *(n0+(int*)&x); * high word of x * + ix1 = *((1-n0)+(int*)&x); * low word of x * + to dig two 32 bit words out of the 64 bit IEEE floating point + value. That is non-ANSI, and, moreover, the gcc instruction + scheduler gets it wrong. We instead use the following macros. + Unlike the original code, we determine the endianness at compile + time, not at run time; I don't see much benefit to selecting + endianness at run time. */ + +/* A union which permits us to convert between a double and two 32 bit + ints. */ + +/* + * Math on arm is special: + * For FPA, float words are always big-endian. + * For VFP, floats words follow the memory system mode. + * For Maverick, float words are always little-endian. + */ + +#if (SDL_FLOATWORDORDER == SDL_BIG_ENDIAN) + +typedef union +{ + double value; + struct + { + u_int32_t msw; + u_int32_t lsw; + } parts; +} ieee_double_shape_type; + +#else + +typedef union +{ + double value; + struct + { + u_int32_t lsw; + u_int32_t msw; + } parts; +} ieee_double_shape_type; + +#endif + +/* Get two 32 bit ints from a double. */ + +#define EXTRACT_WORDS(ix0,ix1,d) \ +do { \ + ieee_double_shape_type ew_u; \ + ew_u.value = (d); \ + (ix0) = ew_u.parts.msw; \ + (ix1) = ew_u.parts.lsw; \ +} while (0) + +/* Get the more significant 32 bit int from a double. */ + +#define GET_HIGH_WORD(i,d) \ +do { \ + ieee_double_shape_type gh_u; \ + gh_u.value = (d); \ + (i) = gh_u.parts.msw; \ +} while (0) + +/* Get the less significant 32 bit int from a double. */ + +#define GET_LOW_WORD(i,d) \ +do { \ + ieee_double_shape_type gl_u; \ + gl_u.value = (d); \ + (i) = gl_u.parts.lsw; \ +} while (0) + +/* Set a double from two 32 bit ints. */ + +#define INSERT_WORDS(d,ix0,ix1) \ +do { \ + ieee_double_shape_type iw_u; \ + iw_u.parts.msw = (ix0); \ + iw_u.parts.lsw = (ix1); \ + (d) = iw_u.value; \ +} while (0) + +/* Set the more significant 32 bits of a double from an int. */ + +#define SET_HIGH_WORD(d,v) \ +do { \ + ieee_double_shape_type sh_u; \ + sh_u.value = (d); \ + sh_u.parts.msw = (v); \ + (d) = sh_u.value; \ +} while (0) + +/* Set the less significant 32 bits of a double from an int. */ + +#define SET_LOW_WORD(d,v) \ +do { \ + ieee_double_shape_type sl_u; \ + sl_u.value = (d); \ + sl_u.parts.lsw = (v); \ + (d) = sl_u.value; \ +} while (0) + +/* A union which permits us to convert between a float and a 32 bit + int. */ + +typedef union +{ + float value; + u_int32_t word; +} ieee_float_shape_type; + +/* Get a 32 bit int from a float. */ + +#define GET_FLOAT_WORD(i,d) \ +do { \ + ieee_float_shape_type gf_u; \ + gf_u.value = (d); \ + (i) = gf_u.word; \ +} while (0) + +/* Set a float from a 32 bit int. */ + +#define SET_FLOAT_WORD(d,i) \ +do { \ + ieee_float_shape_type sf_u; \ + sf_u.word = (i); \ + (d) = sf_u.value; \ +} while (0) + +/* ieee style elementary functions */ +extern double __ieee754_sqrt(double) attribute_hidden; +extern double __ieee754_acos(double) attribute_hidden; +extern double __ieee754_acosh(double) attribute_hidden; +extern double __ieee754_log(double) attribute_hidden; +extern double __ieee754_atanh(double) attribute_hidden; +extern double __ieee754_asin(double) attribute_hidden; +extern double __ieee754_atan2(double, double) attribute_hidden; +extern double __ieee754_exp(double) attribute_hidden; +extern double __ieee754_cosh(double) attribute_hidden; +extern double __ieee754_fmod(double, double) attribute_hidden; +extern double __ieee754_pow(double, double) attribute_hidden; +extern double __ieee754_lgamma_r(double, int *) attribute_hidden; +extern double __ieee754_gamma_r(double, int *) attribute_hidden; +extern double __ieee754_lgamma(double) attribute_hidden; +extern double __ieee754_gamma(double) attribute_hidden; +extern double __ieee754_log10(double) attribute_hidden; +extern double __ieee754_sinh(double) attribute_hidden; +extern double __ieee754_hypot(double, double) attribute_hidden; +extern double __ieee754_j0(double) attribute_hidden; +extern double __ieee754_j1(double) attribute_hidden; +extern double __ieee754_y0(double) attribute_hidden; +extern double __ieee754_y1(double) attribute_hidden; +extern double __ieee754_jn(int, double) attribute_hidden; +extern double __ieee754_yn(int, double) attribute_hidden; +extern double __ieee754_remainder(double, double) attribute_hidden; +extern int32_t __ieee754_rem_pio2(double, double *) attribute_hidden; +#if defined(_SCALB_INT) +extern double __ieee754_scalb(double, int) attribute_hidden; +#else +extern double __ieee754_scalb(double, double) attribute_hidden; +#endif + +/* fdlibm kernel function */ +#ifndef _IEEE_LIBM +extern double __kernel_standard(double, double, int) attribute_hidden; +#endif +extern double __kernel_sin(double, double, int) attribute_hidden; +extern double __kernel_cos(double, double) attribute_hidden; +extern double __kernel_tan(double, double, int) attribute_hidden; +extern int32_t __kernel_rem_pio2(const double *, double *, int, int, const unsigned int, const int32_t *) attribute_hidden; + +#endif /* _MATH_PRIVATE_H_ */ diff --git a/thirdparty/sdl/libm/s_atan.c b/thirdparty/sdl/libm/s_atan.c new file mode 100644 index 00000000000..ce429d22698 --- /dev/null +++ b/thirdparty/sdl/libm/s_atan.c @@ -0,0 +1,119 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* atan(x) + * Method + * 1. Reduce x to positive by atan(x) = -atan(-x). + * 2. According to the integer k=4t+0.25 chopped, t=x, the argument + * is further reduced to one of the following intervals and the + * arctangent of t is evaluated by the corresponding formula: + * + * [0,7/16] atan(x) = t-t^3*(a1+t^2*(a2+...(a10+t^2*a11)...) + * [7/16,11/16] atan(x) = atan(1/2) + atan( (t-0.5)/(1+t/2) ) + * [11/16.19/16] atan(x) = atan( 1 ) + atan( (t-1)/(1+t) ) + * [19/16,39/16] atan(x) = atan(3/2) + atan( (t-1.5)/(1+1.5t) ) + * [39/16,INF] atan(x) = atan(INF) + atan( -1/t ) + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include "math_libm.h" +#include "math_private.h" + +static const double atanhi[] = { + 4.63647609000806093515e-01, /* atan(0.5)hi 0x3FDDAC67, 0x0561BB4F */ + 7.85398163397448278999e-01, /* atan(1.0)hi 0x3FE921FB, 0x54442D18 */ + 9.82793723247329054082e-01, /* atan(1.5)hi 0x3FEF730B, 0xD281F69B */ + 1.57079632679489655800e+00, /* atan(inf)hi 0x3FF921FB, 0x54442D18 */ +}; + +static const double atanlo[] = { + 2.26987774529616870924e-17, /* atan(0.5)lo 0x3C7A2B7F, 0x222F65E2 */ + 3.06161699786838301793e-17, /* atan(1.0)lo 0x3C81A626, 0x33145C07 */ + 1.39033110312309984516e-17, /* atan(1.5)lo 0x3C700788, 0x7AF0CBBD */ + 6.12323399573676603587e-17, /* atan(inf)lo 0x3C91A626, 0x33145C07 */ +}; + +static const double aT[] = { + 3.33333333333329318027e-01, /* 0x3FD55555, 0x5555550D */ + -1.99999999998764832476e-01, /* 0xBFC99999, 0x9998EBC4 */ + 1.42857142725034663711e-01, /* 0x3FC24924, 0x920083FF */ + -1.11111104054623557880e-01, /* 0xBFBC71C6, 0xFE231671 */ + 9.09088713343650656196e-02, /* 0x3FB745CD, 0xC54C206E */ + -7.69187620504482999495e-02, /* 0xBFB3B0F2, 0xAF749A6D */ + 6.66107313738753120669e-02, /* 0x3FB10D66, 0xA0D03D51 */ + -5.83357013379057348645e-02, /* 0xBFADDE2D, 0x52DEFD9A */ + 4.97687799461593236017e-02, /* 0x3FA97B4B, 0x24760DEB */ + -3.65315727442169155270e-02, /* 0xBFA2B444, 0x2C6A6C2F */ + 1.62858201153657823623e-02, /* 0x3F90AD3A, 0xE322DA11 */ +}; + +#ifdef __WATCOMC__ /* Watcom defines huge=__huge */ +#undef huge +#endif + +static const double +one = 1.0, +huge = 1.0e300; + +double atan(double x) +{ + double w,s1,s2,z; + int32_t ix,hx,id; + + GET_HIGH_WORD(hx,x); + ix = hx&0x7fffffff; + if(ix>=0x44100000) { /* if |x| >= 2^66 */ + u_int32_t low; + GET_LOW_WORD(low,x); + if(ix>0x7ff00000|| + (ix==0x7ff00000&&(low!=0))) + return x+x; /* NaN */ + if(hx>0) return atanhi[3]+atanlo[3]; + else return -atanhi[3]-atanlo[3]; + } if (ix < 0x3fdc0000) { /* |x| < 0.4375 */ + if (ix < 0x3e200000) { /* |x| < 2^-29 */ + if(huge+x>one) return x; /* raise inexact */ + } + id = -1; + } else { + x = fabs(x); + if (ix < 0x3ff30000) { /* |x| < 1.1875 */ + if (ix < 0x3fe60000) { /* 7/16 <=|x|<11/16 */ + id = 0; x = (2.0*x-one)/(2.0+x); + } else { /* 11/16<=|x|< 19/16 */ + id = 1; x = (x-one)/(x+one); + } + } else { + if (ix < 0x40038000) { /* |x| < 2.4375 */ + id = 2; x = (x-1.5)/(one+1.5*x); + } else { /* 2.4375 <= |x| < 2^66 */ + id = 3; x = -1.0/x; + } + }} + /* end of argument reduction */ + z = x*x; + w = z*z; + /* break sum from i=0 to 10 aT[i]z**(i+1) into odd and even poly */ + s1 = z*(aT[0]+w*(aT[2]+w*(aT[4]+w*(aT[6]+w*(aT[8]+w*aT[10]))))); + s2 = w*(aT[1]+w*(aT[3]+w*(aT[5]+w*(aT[7]+w*aT[9])))); + if (id<0) return x - x*(s1+s2); + else { + z = atanhi[id] - ((x*(s1+s2) - atanlo[id]) - x); + return (hx<0)? -z:z; + } +} +libm_hidden_def(atan) diff --git a/thirdparty/sdl/libm/s_copysign.c b/thirdparty/sdl/libm/s_copysign.c new file mode 100644 index 00000000000..630f4772a6b --- /dev/null +++ b/thirdparty/sdl/libm/s_copysign.c @@ -0,0 +1,30 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * copysign(double x, double y) + * copysign(x,y) returns a value with the magnitude of x and + * with the sign bit of y. + */ + +#include "math_libm.h" +#include "math_private.h" + +double copysign(double x, double y) +{ + u_int32_t hx,hy; + GET_HIGH_WORD(hx,x); + GET_HIGH_WORD(hy,y); + SET_HIGH_WORD(x,(hx&0x7fffffff)|(hy&0x80000000)); + return x; +} +libm_hidden_def(copysign) diff --git a/thirdparty/sdl/libm/s_cos.c b/thirdparty/sdl/libm/s_cos.c new file mode 100644 index 00000000000..ef85e71b2b4 --- /dev/null +++ b/thirdparty/sdl/libm/s_cos.c @@ -0,0 +1,74 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* cos(x) + * Return cosine function of x. + * + * kernel function: + * __kernel_sin ... sine function on [-pi/4,pi/4] + * __kernel_cos ... cosine function on [-pi/4,pi/4] + * __ieee754_rem_pio2 ... argument reduction routine + * + * Method. + * Let S,C and T denote the sin, cos and tan respectively on + * [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2 + * in [-pi/4 , +pi/4], and let n = k mod 4. + * We have + * + * n sin(x) cos(x) tan(x) + * ---------------------------------------------------------- + * 0 S C T + * 1 C -S -1/T + * 2 -S -C T + * 3 -C S -1/T + * ---------------------------------------------------------- + * + * Special cases: + * Let trig be any of sin, cos, or tan. + * trig(+-INF) is NaN, with signals; + * trig(NaN) is that NaN; + * + * Accuracy: + * TRIG(x) returns trig(x) nearly rounded + */ + +#include "math_libm.h" +#include "math_private.h" + +double cos(double x) +{ + double y[2],z=0.0; + int32_t n, ix; + + /* High word of x. */ + GET_HIGH_WORD(ix,x); + + /* |x| ~< pi/4 */ + ix &= 0x7fffffff; + if(ix <= 0x3fe921fb) return __kernel_cos(x,z); + + /* cos(Inf or NaN) is NaN */ + else if (ix>=0x7ff00000) return x-x; + + /* argument reduction needed */ + else { + n = __ieee754_rem_pio2(x,y); + switch(n&3) { + case 0: return __kernel_cos(y[0],y[1]); + case 1: return -__kernel_sin(y[0],y[1],1); + case 2: return -__kernel_cos(y[0],y[1]); + default: + return __kernel_sin(y[0],y[1],1); + } + } +} +libm_hidden_def(cos) diff --git a/thirdparty/sdl/libm/s_fabs.c b/thirdparty/sdl/libm/s_fabs.c new file mode 100644 index 00000000000..782b6f7fd8a --- /dev/null +++ b/thirdparty/sdl/libm/s_fabs.c @@ -0,0 +1,30 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * fabs(x) returns the absolute value of x. + */ + +/*#include */ +/* Prevent math.h from defining a colliding inline */ +#undef __USE_EXTERN_INLINES +#include "math_libm.h" +#include "math_private.h" + +double fabs(double x) +{ + u_int32_t high; + GET_HIGH_WORD(high,x); + SET_HIGH_WORD(x,high&0x7fffffff); + return x; +} +libm_hidden_def(fabs) diff --git a/thirdparty/sdl/libm/s_floor.c b/thirdparty/sdl/libm/s_floor.c new file mode 100644 index 00000000000..4809af1551e --- /dev/null +++ b/thirdparty/sdl/libm/s_floor.c @@ -0,0 +1,76 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * floor(x) + * Return x rounded toward -inf to integral value + * Method: + * Bit twiddling. + * Exception: + * Inexact flag raised if x not equal to floor(x). + */ + +/*#include */ +/* Prevent math.h from defining a colliding inline */ +#undef __USE_EXTERN_INLINES +#include "math_libm.h" +#include "math_private.h" + +#ifdef __WATCOMC__ /* Watcom defines huge=__huge */ +#undef huge +#endif + +static const double huge = 1.0e300; + +double floor(double x) +{ + int32_t i0,i1,j0; + u_int32_t i,j; + EXTRACT_WORDS(i0,i1,x); + j0 = ((i0>>20)&0x7ff)-0x3ff; + if(j0<20) { + if(j0<0) { /* raise inexact if x != 0 */ + if(huge+x>0.0) {/* return 0*sign(x) if |x|<1 */ + if(i0>=0) {i0=i1=0;} + else if(((i0&0x7fffffff)|i1)!=0) + { i0=0xbff00000;i1=0;} + } + } else { + i = (0x000fffff)>>j0; + if(((i0&i)|i1)==0) return x; /* x is integral */ + if(huge+x>0.0) { /* raise inexact flag */ + if(i0<0) i0 += (0x00100000)>>j0; + i0 &= (~i); i1=0; + } + } + } else if (j0>51) { + if(j0==0x400) return x+x; /* inf or NaN */ + else return x; /* x is integral */ + } else { + i = ((u_int32_t)(0xffffffff))>>(j0-20); + if((i1&i)==0) return x; /* x is integral */ + if(huge+x>0.0) { /* raise inexact flag */ + if(i0<0) { + if(j0==20) i0+=1; + else { + j = i1+(1<<(52-j0)); + if(j<(u_int32_t)i1) i0 +=1 ; /* got a carry */ + i1=j; + } + } + i1 &= (~i); + } + } + INSERT_WORDS(x,i0,i1); + return x; +} +libm_hidden_def(floor) diff --git a/thirdparty/sdl/libm/s_isinf.c b/thirdparty/sdl/libm/s_isinf.c new file mode 100644 index 00000000000..9486b05903f --- /dev/null +++ b/thirdparty/sdl/libm/s_isinf.c @@ -0,0 +1,24 @@ +#include "SDL_internal.h" +/* + * Written by J.T. Conklin . + * Changed to return -1 for -Inf by Ulrich Drepper . + * Public domain. + */ + +/* + * isinf(x) returns 1 is x is inf, -1 if x is -inf, else 0; + * no branching! + */ + +#include "math.h" +#include "math_private.h" + +int __isinf(double x) +{ + int32_t hx,lx; + EXTRACT_WORDS(hx,lx,x); + lx |= (hx & 0x7fffffff) ^ 0x7ff00000; + lx |= -lx; + return ~(lx >> 31) & (hx >> 30); +} +libm_hidden_def(__isinf) diff --git a/thirdparty/sdl/libm/s_isinff.c b/thirdparty/sdl/libm/s_isinff.c new file mode 100644 index 00000000000..184c9aa6caf --- /dev/null +++ b/thirdparty/sdl/libm/s_isinff.c @@ -0,0 +1,24 @@ +#include "SDL_internal.h" +/* + * Written by J.T. Conklin . + * Public domain. + */ + +/* + * isinff(x) returns 1 if x is inf, -1 if x is -inf, else 0; + * no branching! + */ + +#include "math.h" +#include "math_private.h" + +int __isinff (float x) +{ + int32_t ix,t; + GET_FLOAT_WORD(ix,x); + t = ix & 0x7fffffff; + t ^= 0x7f800000; + t |= -t; + return ~(t >> 31) & (ix >> 30); +} +libm_hidden_def(__isinff) diff --git a/thirdparty/sdl/libm/s_isnan.c b/thirdparty/sdl/libm/s_isnan.c new file mode 100644 index 00000000000..4831086adcc --- /dev/null +++ b/thirdparty/sdl/libm/s_isnan.c @@ -0,0 +1,31 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * isnan(x) returns 1 is x is nan, else 0; + * no branching! + */ + +#include "math.h" +#include "math_private.h" + +int __isnan(double x) +{ + int32_t hx,lx; + EXTRACT_WORDS(hx,lx,x); + hx &= 0x7fffffff; + hx |= (u_int32_t)(lx|(-lx))>>31; + hx = 0x7ff00000 - hx; + return (int)(((u_int32_t)hx)>>31); +} +weak_alias(__isnan, isnan) +libm_hidden_def(__isnan) diff --git a/thirdparty/sdl/libm/s_isnanf.c b/thirdparty/sdl/libm/s_isnanf.c new file mode 100644 index 00000000000..1cb308cfa98 --- /dev/null +++ b/thirdparty/sdl/libm/s_isnanf.c @@ -0,0 +1,33 @@ +#include "SDL_internal.h" +/* s_isnanf.c -- float version of s_isnan.c. + * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. + */ + +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * isnanf(x) returns 1 is x is nan, else 0; + * no branching! + */ + +#include "math.h" +#include "math_private.h" + +int __isnanf(float x) +{ + int32_t ix; + GET_FLOAT_WORD(ix,x); + ix &= 0x7fffffff; + ix = 0x7f800000 - ix; + return (int)(((u_int32_t)(ix))>>31); +} +libm_hidden_def(__isnanf) diff --git a/thirdparty/sdl/libm/s_modf.c b/thirdparty/sdl/libm/s_modf.c new file mode 100644 index 00000000000..55f83ba8ded --- /dev/null +++ b/thirdparty/sdl/libm/s_modf.c @@ -0,0 +1,68 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * modf(double x, double *iptr) + * return fraction part of x, and return x's integral part in *iptr. + * Method: + * Bit twiddling. + * + * Exception: + * No exception. + */ + +#include "math_libm.h" +#include "math_private.h" + +static const double one = 1.0; + +double modf(double x, double *iptr) +{ + int32_t i0,i1,_j0; + u_int32_t i; + EXTRACT_WORDS(i0,i1,x); + _j0 = ((i0>>20)&0x7ff)-0x3ff; /* exponent of x */ + if(_j0<20) { /* integer part in high x */ + if(_j0<0) { /* |x|<1 */ + INSERT_WORDS(*iptr,i0&0x80000000,0); /* *iptr = +-0 */ + return x; + } else { + i = (0x000fffff)>>_j0; + if(((i0&i)|i1)==0) { /* x is integral */ + *iptr = x; + INSERT_WORDS(x,i0&0x80000000,0); /* return +-0 */ + return x; + } else { + INSERT_WORDS(*iptr,i0&(~i),0); + return x - *iptr; + } + } + } else if (_j0>51) { /* no fraction part */ + *iptr = x*one; + /* We must handle NaNs separately. */ + if (_j0 == 0x400 && ((i0 & 0xfffff) | i1)) + return x*one; + INSERT_WORDS(x,i0&0x80000000,0); /* return +-0 */ + return x; + } else { /* fraction part in low x */ + i = ((u_int32_t)(0xffffffff))>>(_j0-20); + if((i1&i)==0) { /* x is integral */ + *iptr = x; + INSERT_WORDS(x,i0&0x80000000,0); /* return +-0 */ + return x; + } else { + INSERT_WORDS(*iptr,i0,i1&(~i)); + return x - *iptr; + } + } +} +libm_hidden_def(modf) diff --git a/thirdparty/sdl/libm/s_scalbn.c b/thirdparty/sdl/libm/s_scalbn.c new file mode 100644 index 00000000000..b3a06044ab2 --- /dev/null +++ b/thirdparty/sdl/libm/s_scalbn.c @@ -0,0 +1,74 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * scalbln(double x, long n) + * scalbln(x,n) returns x * 2**n computed by exponent + * manipulation rather than by actually performing an + * exponentiation or a multiplication. + */ + +#include "math_libm.h" +#include "math_private.h" +#include + +#ifdef __WATCOMC__ /* Watcom defines huge=__huge */ +#undef huge +#endif + +static const double +two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ +twom54 = 5.55111512312578270212e-17, /* 0x3C900000, 0x00000000 */ +huge = 1.0e+300, +tiny = 1.0e-300; + +double scalbln(double x, long n) +{ + int32_t k, hx, lx; + + EXTRACT_WORDS(hx, lx, x); + k = (hx & 0x7ff00000) >> 20; /* extract exponent */ + if (k == 0) { /* 0 or subnormal x */ + if ((lx | (hx & 0x7fffffff)) == 0) + return x; /* +-0 */ + x *= two54; + GET_HIGH_WORD(hx, x); + k = ((hx & 0x7ff00000) >> 20) - 54; + } + if (k == 0x7ff) + return x + x; /* NaN or Inf */ + k = (int32_t)(k + n); + if (k > 0x7fe) + return huge * copysign(huge, x); /* overflow */ + if (n < -50000) + return tiny * copysign(tiny, x); /* underflow */ + if (k > 0) { /* normal result */ + SET_HIGH_WORD(x, (hx & 0x800fffff) | (k << 20)); + return x; + } + if (k <= -54) { + if (n > 50000) /* in case integer overflow in n+k */ + return huge * copysign(huge, x); /* overflow */ + return tiny * copysign(tiny, x); /* underflow */ + } + k += 54; /* subnormal result */ + SET_HIGH_WORD(x, (hx & 0x800fffff) | (k << 20)); + return x * twom54; +} +libm_hidden_def(scalbln) + + +double scalbn(double x, int n) +{ + return scalbln(x, n); +} +libm_hidden_def(scalbn) diff --git a/thirdparty/sdl/libm/s_sin.c b/thirdparty/sdl/libm/s_sin.c new file mode 100644 index 00000000000..511bc21ac5c --- /dev/null +++ b/thirdparty/sdl/libm/s_sin.c @@ -0,0 +1,74 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* sin(x) + * Return sine function of x. + * + * kernel function: + * __kernel_sin ... sine function on [-pi/4,pi/4] + * __kernel_cos ... cose function on [-pi/4,pi/4] + * __ieee754_rem_pio2 ... argument reduction routine + * + * Method. + * Let S,C and T denote the sin, cos and tan respectively on + * [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2 + * in [-pi/4 , +pi/4], and let n = k mod 4. + * We have + * + * n sin(x) cos(x) tan(x) + * ---------------------------------------------------------- + * 0 S C T + * 1 C -S -1/T + * 2 -S -C T + * 3 -C S -1/T + * ---------------------------------------------------------- + * + * Special cases: + * Let trig be any of sin, cos, or tan. + * trig(+-INF) is NaN, with signals; + * trig(NaN) is that NaN; + * + * Accuracy: + * TRIG(x) returns trig(x) nearly rounded + */ + +#include "math_libm.h" +#include "math_private.h" + +double sin(double x) +{ + double y[2],z=0.0; + int32_t n, ix; + + /* High word of x. */ + GET_HIGH_WORD(ix,x); + + /* |x| ~< pi/4 */ + ix &= 0x7fffffff; + if(ix <= 0x3fe921fb) return __kernel_sin(x,z,0); + + /* sin(Inf or NaN) is NaN */ + else if (ix>=0x7ff00000) return x-x; + + /* argument reduction needed */ + else { + n = __ieee754_rem_pio2(x,y); + switch(n&3) { + case 0: return __kernel_sin(y[0],y[1],1); + case 1: return __kernel_cos(y[0],y[1]); + case 2: return -__kernel_sin(y[0],y[1],1); + default: + return -__kernel_cos(y[0],y[1]); + } + } +} +libm_hidden_def(sin) diff --git a/thirdparty/sdl/libm/s_tan.c b/thirdparty/sdl/libm/s_tan.c new file mode 100644 index 00000000000..dc10a1e5c39 --- /dev/null +++ b/thirdparty/sdl/libm/s_tan.c @@ -0,0 +1,68 @@ +#include "SDL_internal.h" +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* tan(x) + * Return tangent function of x. + * + * kernel function: + * __kernel_tan ... tangent function on [-pi/4,pi/4] + * __ieee754_rem_pio2 ... argument reduction routine + * + * Method. + * Let S,C and T denote the sin, cos and tan respectively on + * [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2 + * in [-pi/4 , +pi/4], and let n = k mod 4. + * We have + * + * n sin(x) cos(x) tan(x) + * ---------------------------------------------------------- + * 0 S C T + * 1 C -S -1/T + * 2 -S -C T + * 3 -C S -1/T + * ---------------------------------------------------------- + * + * Special cases: + * Let trig be any of sin, cos, or tan. + * trig(+-INF) is NaN, with signals; + * trig(NaN) is that NaN; + * + * Accuracy: + * TRIG(x) returns trig(x) nearly rounded + */ + +#include "math_libm.h" +#include "math_private.h" + +double tan(double x) +{ + double y[2],z=0.0; + int32_t n, ix; + + /* High word of x. */ + GET_HIGH_WORD(ix,x); + + /* |x| ~< pi/4 */ + ix &= 0x7fffffff; + if(ix <= 0x3fe921fb) return __kernel_tan(x,z,1); + + /* tan(Inf or NaN) is NaN */ + else if (ix>=0x7ff00000) return x-x; /* NaN */ + + /* argument reduction needed */ + else { + n = __ieee754_rem_pio2(x,y); + return __kernel_tan(y[0],y[1],1-((n&1)<<1)); /* 1 -- n even + -1 -- n odd */ + } +} +libm_hidden_def(tan) diff --git a/thirdparty/sdl/loadso/dlopen/SDL_sysloadso.c b/thirdparty/sdl/loadso/dlopen/SDL_sysloadso.c new file mode 100644 index 00000000000..c84d1a1b5f9 --- /dev/null +++ b/thirdparty/sdl/loadso/dlopen/SDL_sysloadso.c @@ -0,0 +1,82 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_LOADSO_DLOPEN + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +// System dependent library loading routines + +#include +#include + +#ifdef SDL_VIDEO_DRIVER_UIKIT +#include "../../video/uikit/SDL_uikitvideo.h" +#endif + +SDL_SharedObject *SDL_LoadObject(const char *sofile) +{ + void *handle; + const char *loaderror; + +#ifdef SDL_VIDEO_DRIVER_UIKIT + if (!UIKit_IsSystemVersionAtLeast(8.0)) { + SDL_SetError("SDL_LoadObject requires iOS 8+"); + return NULL; + } +#endif + + handle = dlopen(sofile, RTLD_NOW | RTLD_LOCAL); + loaderror = dlerror(); + if (!handle) { + SDL_SetError("Failed loading %s: %s", sofile, loaderror); + } + return (SDL_SharedObject *) handle; +} + +SDL_FunctionPointer SDL_LoadFunction(SDL_SharedObject *handle, const char *name) +{ + void *symbol = dlsym(handle, name); + if (!symbol) { + // prepend an underscore for platforms that need that. + bool isstack; + size_t len = SDL_strlen(name) + 1; + char *_name = SDL_small_alloc(char, len + 1, &isstack); + _name[0] = '_'; + SDL_memcpy(&_name[1], name, len); + symbol = dlsym(handle, _name); + SDL_small_free(_name, isstack); + if (!symbol) { + SDL_SetError("Failed loading %s: %s", name, + (const char *)dlerror()); + } + } + return symbol; +} + +void SDL_UnloadObject(SDL_SharedObject *handle) +{ + if (handle) { + dlclose(handle); + } +} + +#endif // SDL_LOADSO_DLOPEN diff --git a/thirdparty/sdl/patches/0001-remove-unnecessary-subsystems.patch b/thirdparty/sdl/patches/0001-remove-unnecessary-subsystems.patch new file mode 100644 index 00000000000..6849a95ab13 --- /dev/null +++ b/thirdparty/sdl/patches/0001-remove-unnecessary-subsystems.patch @@ -0,0 +1,917 @@ +diff --git a/thirdparty/sdl/SDL.c b/thirdparty/sdl/SDL.c +index 502f6617a4..dd0b823634 100644 +--- a/thirdparty/sdl/SDL.c ++++ b/thirdparty/sdl/SDL.c +@@ -40,23 +40,14 @@ + #include "SDL_hints_c.h" + #include "SDL_log_c.h" + #include "SDL_properties_c.h" +-#include "audio/SDL_sysaudio.h" +-#include "camera/SDL_camera_c.h" +-#include "cpuinfo/SDL_cpuinfo_c.h" ++//#include "audio/SDL_sysaudio.h" + #include "events/SDL_events_c.h" + #include "haptic/SDL_haptic_c.h" + #include "joystick/SDL_gamepad_c.h" + #include "joystick/SDL_joystick_c.h" +-#include "render/SDL_sysrender.h" + #include "sensor/SDL_sensor_c.h" + #include "stdlib/SDL_getenv_c.h" + #include "thread/SDL_thread_c.h" +-#include "tray/SDL_tray_utils.h" +-#include "video/SDL_pixels_c.h" +-#include "video/SDL_surface_c.h" +-#include "video/SDL_video_c.h" +-#include "filesystem/SDL_filesystem_c.h" +-#include "io/SDL_asyncio_c.h" + #ifdef SDL_PLATFORM_ANDROID + #include "core/android/SDL_android.h" + #endif +@@ -278,7 +269,7 @@ void SDL_InitMainThread(void) + SDL_InitTLSData(); + SDL_InitEnvironment(); + SDL_InitTicks(); +- SDL_InitFilesystem(); ++ //SDL_InitFilesystem(); + + if (!done_info) { + const char *value; +@@ -297,7 +288,7 @@ void SDL_InitMainThread(void) + + static void SDL_QuitMainThread(void) + { +- SDL_QuitFilesystem(); ++ //SDL_QuitFilesystem(); + SDL_QuitTicks(); + SDL_QuitEnvironment(); + SDL_QuitTLSData(); +@@ -657,21 +648,21 @@ void SDL_Quit(void) + SDL_HelperWindowDestroy(); + #endif + SDL_QuitSubSystem(SDL_INIT_EVERYTHING); +- SDL_CleanupTrays(); ++ //SDL_CleanupTrays(); + + #ifdef SDL_USE_LIBDBUS + SDL_DBus_Quit(); + #endif + + SDL_QuitTimers(); +- SDL_QuitAsyncIO(); ++ //SDL_QuitAsyncIO(); + + SDL_SetObjectsInvalid(); + SDL_AssertionsQuit(); + +- SDL_QuitPixelFormatDetails(); ++ //SDL_QuitPixelFormatDetails(); + +- SDL_QuitCPUInfo(); ++ //SDL_QuitCPUInfo(); + + /* Now that every subsystem has been quit, we reset the subsystem refcount + * and the list of initialized subsystems. +diff --git a/thirdparty/sdl/SDL_assert.c b/thirdparty/sdl/SDL_assert.c +index 2440d04b1e..af904039a4 100644 +--- a/thirdparty/sdl/SDL_assert.c ++++ b/thirdparty/sdl/SDL_assert.c +@@ -25,7 +25,7 @@ + #endif + + #include "SDL_assert_c.h" +-#include "video/SDL_sysvideo.h" ++//#include "video/SDL_sysvideo.h" + + #if defined(SDL_PLATFORM_WINDOWS) + #ifndef WS_OVERLAPPEDWINDOW +@@ -209,18 +209,6 @@ static SDL_AssertState SDLCALL SDL_PromptAssertion(const SDL_AssertData *data, v + } + } + +- // Leave fullscreen mode, if possible (scary!) +- window = SDL_GetToplevelForKeyboardFocus(); +- if (window) { +- if (window->fullscreen_exclusive) { +- SDL_MinimizeWindow(window); +- } else { +- // !!! FIXME: ungrab the input if we're not fullscreen? +- // No need to mess with the window +- window = NULL; +- } +- } +- + // Show a messagebox if we can, otherwise fall back to stdio + SDL_zero(messagebox); + messagebox.flags = SDL_MESSAGEBOX_WARNING; +@@ -230,7 +218,8 @@ static SDL_AssertState SDLCALL SDL_PromptAssertion(const SDL_AssertData *data, v + messagebox.numbuttons = SDL_arraysize(buttons); + messagebox.buttons = buttons; + +- if (SDL_ShowMessageBox(&messagebox, &selected)) { ++ //if (SDL_ShowMessageBox(&messagebox, &selected)) { ++ if (false) { + if (selected == -1) { + state = SDL_ASSERTION_IGNORE; + } else { +@@ -311,13 +300,13 @@ static SDL_AssertState SDLCALL SDL_PromptAssertion(const SDL_AssertData *data, v + } + } + #else +- SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Assertion Failed", message, window); ++ //SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Assertion Failed", message, window); + #endif // HAVE_STDIO_H + } + + // Re-enter fullscreen mode + if (window) { +- SDL_RestoreWindow(window); ++ //SDL_RestoreWindow(window); + } + + if (message != stack_buf) { +diff --git a/thirdparty/sdl/SDL_internal.h b/thirdparty/sdl/SDL_internal.h +index 8fcd96a7fa..20ec0fcb91 100644 +--- a/thirdparty/sdl/SDL_internal.h ++++ b/thirdparty/sdl/SDL_internal.h +@@ -62,7 +62,7 @@ + + #include "SDL_build_config.h" + +-#include "dynapi/SDL_dynapi.h" ++//#include "dynapi/SDL_dynapi.h" + + #if SDL_DYNAMIC_API + #include "dynapi/SDL_dynapi_overrides.h" +diff --git a/thirdparty/sdl/SDL_properties.c b/thirdparty/sdl/SDL_properties.c +index 166ea0f918..42d4845458 100644 +--- a/thirdparty/sdl/SDL_properties.c ++++ b/thirdparty/sdl/SDL_properties.c +@@ -409,7 +409,7 @@ static void SDLCALL CleanupSurface(void *userdata, void *value) + { + SDL_Surface *surface = (SDL_Surface *)value; + +- SDL_DestroySurface(surface); ++ //SDL_DestroySurface(surface); + } + + bool SDL_SetSurfaceProperty(SDL_PropertiesID props, const char *name, SDL_Surface *surface) +diff --git a/thirdparty/sdl/core/linux/SDL_evdev.c b/thirdparty/sdl/core/linux/SDL_evdev.c +index 5746e2ef98..04e3e9d6b6 100644 +--- a/thirdparty/sdl/core/linux/SDL_evdev.c ++++ b/thirdparty/sdl/core/linux/SDL_evdev.c +@@ -39,7 +39,6 @@ + #include + + #include "../../events/SDL_events_c.h" +-#include "../../events/SDL_scancode_tables_c.h" + #include "../../core/linux/SDL_evdev_capabilities.h" + #include "../../core/linux/SDL_udev.h" + +@@ -221,7 +220,7 @@ bool SDL_EVDEV_Init(void) + SDL_EVDEV_UpdateKeyboardMute(); + } + +- SDL_GetMouse()->SetRelativeMouseMode = SDL_EVDEV_SetRelativeMouseMode; ++ //SDL_GetMouse()->SetRelativeMouseMode = SDL_EVDEV_SetRelativeMouseMode; + + _this->ref_count += 1; + +@@ -328,7 +327,7 @@ void SDL_EVDEV_Poll(void) + + SDL_EVDEV_kbd_update(_this->kbd); + +- mouse = SDL_GetMouse(); ++ mouse = NULL; //SDL_GetMouse(); + + for (item = _this->first; item; item = item->next) { + while ((len = read(item->fd, events, sizeof(events))) > 0) { +@@ -345,10 +344,11 @@ void SDL_EVDEV_Poll(void) + + switch (event->type) { + case EV_KEY: ++ break; + if (event->code >= BTN_MOUSE && event->code < BTN_MOUSE + SDL_arraysize(EVDEV_MouseButtons)) { + Uint64 timestamp = SDL_EVDEV_GetEventTimestamp(event); + mouse_button = event->code - BTN_MOUSE; +- SDL_SendMouseButton(timestamp, mouse->focus, (SDL_MouseID)item->fd, EVDEV_MouseButtons[mouse_button], (event->value != 0)); ++ //SDL_SendMouseButton(timestamp, mouse->focus, (SDL_MouseID)item->fd, EVDEV_MouseButtons[mouse_button], (event->value != 0)); + break; + } + +@@ -371,11 +371,11 @@ void SDL_EVDEV_Poll(void) + { + Uint64 timestamp = SDL_EVDEV_GetEventTimestamp(event); + scancode = SDL_EVDEV_translate_keycode(event->code); +- if (event->value == 0) { +- SDL_SendKeyboardKey(timestamp, (SDL_KeyboardID)item->fd, event->code, scancode, false); +- } else if (event->value == 1 || event->value == 2 /* key repeated */) { +- SDL_SendKeyboardKey(timestamp, (SDL_KeyboardID)item->fd, event->code, scancode, true); +- } ++ // if (event->value == 0) { ++ // SDL_SendKeyboardKey(timestamp, (SDL_KeyboardID)item->fd, event->code, scancode, false); ++ // } else if (event->value == 1 || event->value == 2 /* key repeated */) { ++ // SDL_SendKeyboardKey(timestamp, (SDL_KeyboardID)item->fd, event->code, scancode, true); ++ // } + SDL_EVDEV_kbd_keycode(_this->kbd, event->code, event->value); + } + break; +@@ -490,36 +490,30 @@ void SDL_EVDEV_Poll(void) + if (item->relative_mouse) { + if (item->mouse_x != 0 || item->mouse_y != 0) { + Uint64 timestamp = SDL_EVDEV_GetEventTimestamp(event); +- SDL_SendMouseMotion(timestamp, mouse->focus, (SDL_MouseID)item->fd, item->relative_mouse, (float)item->mouse_x, (float)item->mouse_y); ++ //SDL_SendMouseMotion(timestamp, mouse->focus, (SDL_MouseID)item->fd, item->relative_mouse, (float)item->mouse_x, (float)item->mouse_y); + item->mouse_x = item->mouse_y = 0; + } + } else if (item->range_x > 0 && item->range_y > 0) { + int screen_w = 0, screen_h = 0; + const SDL_DisplayMode *mode = NULL; + +- if (mouse->focus) { +- mode = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(mouse->focus)); +- } +- if (!mode) { +- mode = SDL_GetCurrentDisplayMode(SDL_GetPrimaryDisplay()); +- } + if (mode) { + screen_w = mode->w; + screen_h = mode->h; + } +- SDL_SendMouseMotion(SDL_EVDEV_GetEventTimestamp(event), mouse->focus, (SDL_MouseID)item->fd, item->relative_mouse, +- (float)(item->mouse_x - item->min_x) * screen_w / item->range_x, +- (float)(item->mouse_y - item->min_y) * screen_h / item->range_y); ++ //SDL_SendMouseMotion(SDL_EVDEV_GetEventTimestamp(event), mouse->focus, (SDL_MouseID)item->fd, item->relative_mouse, ++ // (float)(item->mouse_x - item->min_x) * screen_w / item->range_x, ++ // (float)(item->mouse_y - item->min_y) * screen_h / item->range_y); + } + + if (item->mouse_wheel != 0 || item->mouse_hwheel != 0) { + Uint64 timestamp = SDL_EVDEV_GetEventTimestamp(event); + const float denom = (item->high_res_hwheel ? 120.0f : 1.0f); +- SDL_SendMouseWheel(timestamp, +- mouse->focus, (SDL_MouseID)item->fd, +- item->mouse_hwheel / denom, +- item->mouse_wheel / denom, +- SDL_MOUSEWHEEL_NORMAL); ++ //SDL_SendMouseWheel(timestamp, ++ // mouse->focus, (SDL_MouseID)item->fd, ++ // item->mouse_hwheel / denom, ++ // item->mouse_wheel / denom, ++ // SDL_MOUSEWHEEL_NORMAL); + item->mouse_wheel = item->mouse_hwheel = 0; + } + +@@ -546,16 +540,16 @@ void SDL_EVDEV_Poll(void) + * be window-relative in that case. */ + switch (item->touchscreen_data->slots[j].delta) { + case EVDEV_TOUCH_SLOTDELTA_DOWN: +- SDL_SendTouch(SDL_EVDEV_GetEventTimestamp(event), item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, SDL_EVENT_FINGER_DOWN, norm_x, norm_y, norm_pressure); ++ //SDL_SendTouch(SDL_EVDEV_GetEventTimestamp(event), item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, SDL_EVENT_FINGER_DOWN, norm_x, norm_y, norm_pressure); + item->touchscreen_data->slots[j].delta = EVDEV_TOUCH_SLOTDELTA_NONE; + break; + case EVDEV_TOUCH_SLOTDELTA_UP: +- SDL_SendTouch(SDL_EVDEV_GetEventTimestamp(event), item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, SDL_EVENT_FINGER_UP, norm_x, norm_y, norm_pressure); ++ //SDL_SendTouch(SDL_EVDEV_GetEventTimestamp(event), item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, SDL_EVENT_FINGER_UP, norm_x, norm_y, norm_pressure); + item->touchscreen_data->slots[j].tracking_id = 0; + item->touchscreen_data->slots[j].delta = EVDEV_TOUCH_SLOTDELTA_NONE; + break; + case EVDEV_TOUCH_SLOTDELTA_MOVE: +- SDL_SendTouchMotion(SDL_EVDEV_GetEventTimestamp(event), item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, norm_x, norm_y, norm_pressure); ++ //SDL_SendTouchMotion(SDL_EVDEV_GetEventTimestamp(event), item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, norm_x, norm_y, norm_pressure); + item->touchscreen_data->slots[j].delta = EVDEV_TOUCH_SLOTDELTA_NONE; + break; + default: +@@ -585,7 +579,7 @@ void SDL_EVDEV_Poll(void) + + static SDL_Scancode SDL_EVDEV_translate_keycode(int keycode) + { +- SDL_Scancode scancode = SDL_GetScancodeFromTable(SDL_SCANCODE_TABLE_LINUX, keycode); ++ //SDL_Scancode scancode = SDL_GetScancodeFromTable(SDL_SCANCODE_TABLE_LINUX, keycode); + + #ifdef DEBUG_SCANCODES + if (scancode == SDL_SCANCODE_UNKNOWN) { +@@ -602,7 +596,7 @@ static SDL_Scancode SDL_EVDEV_translate_keycode(int keycode) + } + #endif // DEBUG_SCANCODES + +- return scancode; ++ return 0; //scancode; + } + + static bool SDL_EVDEV_init_keyboard(SDL_evdevlist_item *item, int udev_class) +@@ -612,14 +606,14 @@ static bool SDL_EVDEV_init_keyboard(SDL_evdevlist_item *item, int udev_class) + name[0] = '\0'; + ioctl(item->fd, EVIOCGNAME(sizeof(name)), name); + +- SDL_AddKeyboard((SDL_KeyboardID)item->fd, name, true); ++ //SDL_AddKeyboard((SDL_KeyboardID)item->fd, name, true); + + return true; + } + + static void SDL_EVDEV_destroy_keyboard(SDL_evdevlist_item *item) + { +- SDL_RemoveKeyboard((SDL_KeyboardID)item->fd, true); ++ //SDL_RemoveKeyboard((SDL_KeyboardID)item->fd, true); + } + + static bool SDL_EVDEV_init_mouse(SDL_evdevlist_item *item, int udev_class) +@@ -631,7 +625,7 @@ static bool SDL_EVDEV_init_mouse(SDL_evdevlist_item *item, int udev_class) + name[0] = '\0'; + ioctl(item->fd, EVIOCGNAME(sizeof(name)), name); + +- SDL_AddMouse((SDL_MouseID)item->fd, name, true); ++ //SDL_AddMouse((SDL_MouseID)item->fd, name, true); + + ret = ioctl(item->fd, EVIOCGABS(ABS_X), &abs_info); + if (ret < 0) { +@@ -656,7 +650,7 @@ static bool SDL_EVDEV_init_mouse(SDL_evdevlist_item *item, int udev_class) + + static void SDL_EVDEV_destroy_mouse(SDL_evdevlist_item *item) + { +- SDL_RemoveMouse((SDL_MouseID)item->fd, true); ++ //SDL_RemoveMouse((SDL_MouseID)item->fd, true); + } + + static bool SDL_EVDEV_init_touchscreen(SDL_evdevlist_item *item, int udev_class) +@@ -743,9 +737,10 @@ static bool SDL_EVDEV_init_touchscreen(SDL_evdevlist_item *item, int udev_class) + return false; + } + +- ret = SDL_AddTouch(item->fd, // I guess our fd is unique enough +- (udev_class & SDL_UDEV_DEVICE_TOUCHPAD) ? SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE : SDL_TOUCH_DEVICE_DIRECT, +- item->touchscreen_data->name); ++ //ret = SDL_AddTouch(item->fd, // I guess our fd is unique enough ++ // (udev_class & SDL_UDEV_DEVICE_TOUCHPAD) ? SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE : SDL_TOUCH_DEVICE_DIRECT, ++ // item->touchscreen_data->name); ++ ret = -1; + if (ret < 0) { + SDL_free(item->touchscreen_data->slots); + SDL_free(item->touchscreen_data->name); +@@ -762,7 +757,7 @@ static void SDL_EVDEV_destroy_touchscreen(SDL_evdevlist_item *item) + return; + } + +- SDL_DelTouch(item->fd); ++ //SDL_DelTouch(item->fd); + SDL_free(item->touchscreen_data->slots); + SDL_free(item->touchscreen_data->name); + SDL_free(item->touchscreen_data); +diff --git a/thirdparty/sdl/core/linux/SDL_fcitx.c b/thirdparty/sdl/core/linux/SDL_fcitx.c +index d7a9ed6656..c6bce5f796 100644 +--- a/thirdparty/sdl/core/linux/SDL_fcitx.c ++++ b/thirdparty/sdl/core/linux/SDL_fcitx.c +@@ -23,8 +23,7 @@ + #include + + #include "SDL_fcitx.h" +-#include "../../video/SDL_sysvideo.h" +-#include "../../events/SDL_keyboard_c.h" ++//#include "../../video/SDL_sysvideo.h" + #include "SDL_dbus.h" + + #ifdef SDL_VIDEO_DRIVER_X11 +@@ -192,7 +191,7 @@ static DBusHandlerResult DBus_MessageFilter(DBusConnection *conn, DBusMessage *m + dbus->message_iter_init(msg, &iter); + dbus->message_iter_get_basic(&iter, &text); + +- SDL_SendKeyboardText(text); ++ //SDL_SendKeyboardText(text); + + return DBUS_HANDLER_RESULT_HANDLED; + } +@@ -206,13 +205,13 @@ static DBusHandlerResult DBus_MessageFilter(DBusConnection *conn, DBusMessage *m + Sint32 byte_pos = Fcitx_GetPreeditCursorByte(dbus, msg); + start_pos = byte_pos >= 0 ? SDL_utf8strnlen(text, byte_pos) : -1; + } +- SDL_SendEditingText(text, start_pos, end_pos >= 0 ? end_pos - start_pos : -1); ++ //SDL_SendEditingText(text, start_pos, end_pos >= 0 ? end_pos - start_pos : -1); + SDL_free(text); + } else { +- SDL_SendEditingText("", 0, 0); ++ //SDL_SendEditingText("", 0, 0); + } + +- SDL_Fcitx_UpdateTextInputArea(SDL_GetKeyboardFocus()); ++ //SDL_Fcitx_UpdateTextInputArea(SDL_GetKeyboardFocus()); + return DBUS_HANDLER_RESULT_HANDLED; + } + +@@ -394,7 +393,7 @@ bool SDL_Fcitx_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, bool down) + DBUS_TYPE_UINT32, &keysym, DBUS_TYPE_UINT32, &keycode, DBUS_TYPE_UINT32, &mod_state, DBUS_TYPE_BOOLEAN, &is_release, DBUS_TYPE_UINT32, &event_time, DBUS_TYPE_INVALID, + DBUS_TYPE_BOOLEAN, &handled, DBUS_TYPE_INVALID)) { + if (handled) { +- SDL_Fcitx_UpdateTextInputArea(SDL_GetKeyboardFocus()); ++ //SDL_Fcitx_UpdateTextInputArea(SDL_GetKeyboardFocus()); + return true; + } + } +@@ -402,51 +401,6 @@ bool SDL_Fcitx_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, bool down) + return false; + } + +-void SDL_Fcitx_UpdateTextInputArea(SDL_Window *window) +-{ +- int x = 0, y = 0; +- SDL_Rect *cursor = &fcitx_client.cursor_rect; +- +- if (!window) { +- return; +- } +- +- // We'll use a square at the text input cursor location for the cursor_rect +- cursor->x = window->text_input_rect.x + window->text_input_cursor; +- cursor->y = window->text_input_rect.y; +- cursor->w = window->text_input_rect.h; +- cursor->h = window->text_input_rect.h; +- +- SDL_GetWindowPosition(window, &x, &y); +- +-#ifdef SDL_VIDEO_DRIVER_X11 +- { +- SDL_PropertiesID props = SDL_GetWindowProperties(window); +- Display *x_disp = (Display *)SDL_GetPointerProperty(props, SDL_PROP_WINDOW_X11_DISPLAY_POINTER, NULL); +- int x_screen = SDL_GetNumberProperty(props, SDL_PROP_WINDOW_X11_SCREEN_NUMBER, 0); +- Window x_win = SDL_GetNumberProperty(props, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0); +- Window unused; +- if (x_disp && x_win) { +- X11_XTranslateCoordinates(x_disp, x_win, RootWindow(x_disp, x_screen), 0, 0, &x, &y, &unused); +- } +- } +-#endif +- +- if (cursor->x == -1 && cursor->y == -1 && cursor->w == 0 && cursor->h == 0) { +- // move to bottom left +- int w = 0, h = 0; +- SDL_GetWindowSize(window, &w, &h); +- cursor->x = 0; +- cursor->y = h; +- } +- +- x += cursor->x; +- y += cursor->y; +- +- SDL_DBus_CallVoidMethod(FCITX_DBUS_SERVICE, fcitx_client.ic_path, FCITX_IC_DBUS_INTERFACE, "SetCursorRect", +- DBUS_TYPE_INT32, &x, DBUS_TYPE_INT32, &y, DBUS_TYPE_INT32, &cursor->w, DBUS_TYPE_INT32, &cursor->h, DBUS_TYPE_INVALID); +-} +- + void SDL_Fcitx_PumpEvents(void) + { + SDL_DBusContext *dbus = fcitx_client.dbus; +diff --git a/thirdparty/sdl/core/linux/SDL_ibus.c b/thirdparty/sdl/core/linux/SDL_ibus.c +index ea58ed5778..3d4bb83694 100644 +--- a/thirdparty/sdl/core/linux/SDL_ibus.c ++++ b/thirdparty/sdl/core/linux/SDL_ibus.c +@@ -26,7 +26,7 @@ + + #ifdef SDL_USE_LIBDBUS + +-#include "../../video/SDL_sysvideo.h" ++//#include "../../video/SDL_sysvideo.h" + #include "../../events/SDL_keyboard_c.h" + + #ifdef SDL_VIDEO_DRIVER_X11 +@@ -261,7 +261,7 @@ static DBusHandlerResult IBus_MessageHandler(DBusConnection *conn, DBusMessage * + } + } + +- SDL_IBus_UpdateTextInputArea(SDL_GetKeyboardFocus()); ++ //SDL_IBus_UpdateTextInputArea(SDL_GetKeyboardFocus()); + + return DBUS_HANDLER_RESULT_HANDLED; + } +@@ -484,13 +484,6 @@ static bool IBus_SetupConnection(SDL_DBusContext *dbus, const char *addr) + dbus->connection_flush(ibus_conn); + } + +- SDL_Window *window = SDL_GetKeyboardFocus(); +- if (SDL_TextInputActive(window)) { +- SDL_IBus_SetFocus(true); +- SDL_IBus_UpdateTextInputArea(window); +- } else { +- SDL_IBus_SetFocus(false); +- } + return result; + } + +@@ -678,53 +671,11 @@ bool SDL_IBus_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, bool down) + } + } + +- SDL_IBus_UpdateTextInputArea(SDL_GetKeyboardFocus()); ++ //SDL_IBus_UpdateTextInputArea(SDL_GetKeyboardFocus()); + + return (result != 0); + } + +-void SDL_IBus_UpdateTextInputArea(SDL_Window *window) +-{ +- int x = 0, y = 0; +- SDL_DBusContext *dbus; +- +- if (!window) { +- return; +- } +- +- // We'll use a square at the text input cursor location for the ibus_cursor +- ibus_cursor_rect.x = window->text_input_rect.x + window->text_input_cursor; +- ibus_cursor_rect.y = window->text_input_rect.y; +- ibus_cursor_rect.w = window->text_input_rect.h; +- ibus_cursor_rect.h = window->text_input_rect.h; +- +- SDL_GetWindowPosition(window, &x, &y); +- +-#ifdef SDL_VIDEO_DRIVER_X11 +- { +- SDL_PropertiesID props = SDL_GetWindowProperties(window); +- Display *x_disp = (Display *)SDL_GetPointerProperty(props, SDL_PROP_WINDOW_X11_DISPLAY_POINTER, NULL); +- int x_screen = SDL_GetNumberProperty(props, SDL_PROP_WINDOW_X11_SCREEN_NUMBER, 0); +- Window x_win = SDL_GetNumberProperty(props, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0); +- Window unused; +- +- if (x_disp && x_win) { +- X11_XTranslateCoordinates(x_disp, x_win, RootWindow(x_disp, x_screen), 0, 0, &x, &y, &unused); +- } +- } +-#endif +- +- x += ibus_cursor_rect.x; +- y += ibus_cursor_rect.y; +- +- dbus = SDL_DBus_GetContext(); +- +- if (IBus_CheckConnection(dbus)) { +- SDL_DBus_CallVoidMethodOnConnection(ibus_conn, ibus_service, input_ctx_path, ibus_input_interface, "SetCursorLocation", +- DBUS_TYPE_INT32, &x, DBUS_TYPE_INT32, &y, DBUS_TYPE_INT32, &ibus_cursor_rect.w, DBUS_TYPE_INT32, &ibus_cursor_rect.h, DBUS_TYPE_INVALID); +- } +-} +- + void SDL_IBus_PumpEvents(void) + { + SDL_DBusContext *dbus = SDL_DBus_GetContext(); +diff --git a/thirdparty/sdl/core/linux/SDL_system_theme.c b/thirdparty/sdl/core/linux/SDL_system_theme.c +index 6d6087db5a..f5ef92dd05 100644 +--- a/thirdparty/sdl/core/linux/SDL_system_theme.c ++++ b/thirdparty/sdl/core/linux/SDL_system_theme.c +@@ -22,7 +22,7 @@ + + #include "SDL_dbus.h" + #include "SDL_system_theme.h" +-#include "../../video/SDL_sysvideo.h" ++//#include "../../video/SDL_sysvideo.h" + + #include + +@@ -99,7 +99,7 @@ static DBusHandlerResult DBus_MessageFilter(DBusConnection *conn, DBusMessage *m + if (!DBus_ExtractThemeVariant(&signal_iter, &system_theme_data.theme)) + goto not_our_signal; + +- SDL_SetSystemTheme(system_theme_data.theme); ++ //SDL_SetSystemTheme(system_theme_data.theme); + return DBUS_HANDLER_RESULT_HANDLED; + } + not_our_signal: +diff --git a/thirdparty/sdl/events/SDL_events.c b/thirdparty/sdl/events/SDL_events.c +index a151740524..24c2c4270f 100644 +--- a/thirdparty/sdl/events/SDL_events.c ++++ b/thirdparty/sdl/events/SDL_events.c +@@ -24,10 +24,7 @@ + + #include "SDL_events_c.h" + #include "SDL_eventwatch_c.h" +-#include "SDL_windowevents_c.h" + #include "../SDL_hints_c.h" +-#include "../audio/SDL_audio_c.h" +-#include "../camera/SDL_camera_c.h" + #include "../timer/SDL_timer_c.h" + #ifndef SDL_JOYSTICK_DISABLED + #include "../joystick/SDL_joystick_c.h" +@@ -35,7 +32,7 @@ + #ifndef SDL_SENSOR_DISABLED + #include "../sensor/SDL_sensor_c.h" + #endif +-#include "../video/SDL_sysvideo.h" ++//#include "../video/SDL_sysvideo.h" + + #ifdef SDL_PLATFORM_ANDROID + #include "../core/android/SDL_android.h" +@@ -930,7 +927,7 @@ void SDL_StopEventLoop(void) + } + + SDL_QuitEventWatchList(&SDL_event_watchers); +- SDL_QuitWindowEventWatch(); ++ //SDL_QuitWindowEventWatch(); + + SDL_Mutex *lock = NULL; + if (SDL_EventQ.lock) { +@@ -970,7 +967,7 @@ bool SDL_StartEventLoop(void) + } + #endif // !SDL_THREADS_DISABLED + +- SDL_InitWindowEventWatch(); ++ //SDL_InitWindowEventWatch(); + + SDL_EventQ.active = true; + +@@ -1071,17 +1068,6 @@ static void SDL_SendWakeupEvent(void) + { + #ifdef SDL_PLATFORM_ANDROID + Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_WAKE); +-#else +- SDL_VideoDevice *_this = SDL_GetVideoDevice(); +- if (_this == NULL || !_this->SendWakeupEvent) { +- return; +- } +- +- // We only want to do this once while waiting for an event, so set it to NULL atomically here +- SDL_Window *wakeup_window = (SDL_Window *)SDL_SetAtomicPointer(&_this->wakeup_window, NULL); +- if (wakeup_window) { +- _this->SendWakeupEvent(_this, wakeup_window); +- } + #endif + } + +@@ -1420,9 +1406,9 @@ void SDL_PumpEventMaintenance(void) + } + #endif + +- SDL_UpdateTrays(); ++ //SDL_UpdateTrays(); + +- SDL_SendPendingSignalEvents(); // in case we had a signal handler fire, etc. ++ //SDL_SendPendingSignalEvents(); // in case we had a signal handler fire, etc. + } + + // Run the system dependent event loops +@@ -1432,7 +1418,7 @@ static void SDL_PumpEventsInternal(bool push_sentinel) + SDL_FreeTemporaryMemory(); + + // Release any keys held down from last frame +- SDL_ReleaseAutoReleaseKeys(); ++ //SDL_ReleaseAutoReleaseKeys(); + + // Run any pending main thread callbacks + SDL_RunMainThreadCallbacks(); +@@ -1440,12 +1426,6 @@ static void SDL_PumpEventsInternal(bool push_sentinel) + #ifdef SDL_PLATFORM_ANDROID + // Android event processing is independent of the video subsystem + Android_PumpEvents(0); +-#else +- // Get events from the video subsystem +- SDL_VideoDevice *_this = SDL_GetVideoDevice(); +- if (_this) { +- _this->PumpEvents(_this); +- } + #endif + + SDL_PumpEventMaintenance(); +@@ -1476,103 +1456,6 @@ bool SDL_PollEvent(SDL_Event *event) + return SDL_WaitEventTimeoutNS(event, 0); + } + +-#ifndef SDL_PLATFORM_ANDROID +- +-static Sint64 SDL_events_get_polling_interval(void) +-{ +- Sint64 poll_intervalNS = SDL_MAX_SINT64; +- +-#ifndef SDL_JOYSTICK_DISABLED +- if (SDL_WasInit(SDL_INIT_JOYSTICK) && SDL_update_joysticks) { +- if (SDL_JoysticksOpened()) { +- // If we have joysticks open, we need to poll rapidly for events +- poll_intervalNS = SDL_min(poll_intervalNS, EVENT_POLL_INTERVAL_NS); +- } else { +- // If not, just poll every few seconds to enumerate new joysticks +- poll_intervalNS = SDL_min(poll_intervalNS, ENUMERATION_POLL_INTERVAL_NS); +- } +- } +-#endif +- +-#ifndef SDL_SENSOR_DISABLED +- if (SDL_WasInit(SDL_INIT_SENSOR) && SDL_update_sensors && SDL_SensorsOpened()) { +- // If we have sensors open, we need to poll rapidly for events +- poll_intervalNS = SDL_min(poll_intervalNS, EVENT_POLL_INTERVAL_NS); +- } +-#endif +- +- return poll_intervalNS; +-} +- +-static int SDL_WaitEventTimeout_Device(SDL_VideoDevice *_this, SDL_Window *wakeup_window, SDL_Event *event, Uint64 start, Sint64 timeoutNS) +-{ +- Sint64 loop_timeoutNS = timeoutNS; +- Sint64 poll_intervalNS = SDL_events_get_polling_interval(); +- +- for (;;) { +- int status; +- /* Pump events on entry and each time we wake to ensure: +- a) All pending events are batch processed after waking up from a wait +- b) Waiting can be completely skipped if events are already available to be pumped +- c) Periodic processing that takes place in some platform PumpEvents() functions happens +- d) Signals received in WaitEventTimeout() are turned into SDL events +- */ +- SDL_PumpEventsInternal(true); +- +- status = SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST); +- if (status < 0) { +- // Got an error: return +- break; +- } +- if (status > 0) { +- // There is an event, we can return. +- return 1; +- } +- // No events found in the queue, call WaitEventTimeout to wait for an event. +- if (timeoutNS > 0) { +- Sint64 elapsed = SDL_GetTicksNS() - start; +- if (elapsed >= timeoutNS) { +- return 0; +- } +- loop_timeoutNS = (timeoutNS - elapsed); +- } +- // Adjust the timeout for any polling requirements we currently have. +- if (poll_intervalNS != SDL_MAX_SINT64) { +- if (loop_timeoutNS >= 0) { +- loop_timeoutNS = SDL_min(loop_timeoutNS, poll_intervalNS); +- } else { +- loop_timeoutNS = poll_intervalNS; +- } +- } +- SDL_SetAtomicPointer(&_this->wakeup_window, wakeup_window); +- status = _this->WaitEventTimeout(_this, loop_timeoutNS); +- SDL_SetAtomicPointer(&_this->wakeup_window, NULL); +- if (status == 0 && poll_intervalNS != SDL_MAX_SINT64 && loop_timeoutNS == poll_intervalNS) { +- // We may have woken up to poll. Try again +- continue; +- } else if (status <= 0) { +- // There is either an error or the timeout is elapsed: return +- return status; +- } +- /* An event was found and pumped into the SDL events queue. Continue the loop +- to let SDL_PeepEvents pick it up .*/ +- } +- return 0; +-} +- +-static SDL_Window *SDL_find_active_window(SDL_VideoDevice *_this) +-{ +- SDL_Window *window; +- for (window = _this->windows; window; window = window->next) { +- if (!window->is_destroying) { +- return window; +- } +- } +- return NULL; +-} +- +-#endif // !SDL_PLATFORM_ANDROID +- + bool SDL_WaitEvent(SDL_Event *event) + { + return SDL_WaitEventTimeoutNS(event, -1); +@@ -1662,24 +1545,6 @@ bool SDL_WaitEventTimeoutNS(SDL_Event *event, Sint64 timeoutNS) + Android_PumpEvents(delay); + } + #else +- SDL_VideoDevice *_this = SDL_GetVideoDevice(); +- if (_this && _this->WaitEventTimeout && _this->SendWakeupEvent) { +- // Look if a shown window is available to send the wakeup event. +- SDL_Window *wakeup_window = SDL_find_active_window(_this); +- if (wakeup_window) { +- result = SDL_WaitEventTimeout_Device(_this, wakeup_window, event, start, timeoutNS); +- if (result > 0) { +- return true; +- } else if (result == 0) { +- return false; +- } else { +- /* There may be implementation-defined conditions where the backend cannot +- * reliably wait for the next event. If that happens, fall back to polling. +- */ +- } +- } +- } +- + for (;;) { + SDL_PumpEventsInternal(true); + +@@ -1852,7 +1717,7 @@ void SDL_SetEventEnabled(Uint32 type, bool enabled) + /* turn off drag'n'drop support if we've disabled the events. + This might change some UI details at the OS level. */ + if (type == SDL_EVENT_DROP_FILE || type == SDL_EVENT_DROP_TEXT) { +- SDL_ToggleDragAndDropSupport(); ++ //SDL_ToggleDragAndDropSupport(); + } + } + } +@@ -1944,14 +1809,14 @@ bool SDL_InitEvents(void) + return false; + } + +- SDL_InitQuit(); ++ //SDL_InitQuit(); + + return true; + } + + void SDL_QuitEvents(void) + { +- SDL_QuitQuit(); ++ //SDL_QuitQuit(); + SDL_StopEventLoop(); + SDL_QuitMainThreadCallbacks(); + SDL_RemoveHintCallback(SDL_HINT_POLL_SENTINEL, SDL_PollSentinelChanged, NULL); +diff --git a/thirdparty/sdl/events/SDL_events_c.h b/thirdparty/sdl/events/SDL_events_c.h +index e56ac475e5..f3a0744d1c 100644 +--- a/thirdparty/sdl/events/SDL_events_c.h ++++ b/thirdparty/sdl/events/SDL_events_c.h +@@ -25,16 +25,9 @@ + #include "SDL_internal.h" + + // Useful functions and variables from SDL_events.c +-#include "../video/SDL_sysvideo.h" ++//#include "../video/SDL_sysvideo.h" + +-#include "SDL_clipboardevents_c.h" +-#include "SDL_displayevents_c.h" +-#include "SDL_dropevents_c.h" +-#include "SDL_keyboard_c.h" + #include "SDL_mouse_c.h" +-#include "SDL_touch_c.h" +-#include "SDL_pen_c.h" +-#include "SDL_windowevents_c.h" + + // Start and stop the event processing loop + extern bool SDL_StartEventLoop(void); +diff --git a/thirdparty/sdl/include/SDL3/SDL.h b/thirdparty/sdl/include/SDL3/SDL.h +index ed1b32483a..f0671c95c3 100644 +--- a/thirdparty/sdl/include/SDL3/SDL.h ++++ b/thirdparty/sdl/include/SDL3/SDL.h +@@ -47,7 +47,7 @@ + #include + #include + #include +-#include ++//#include + #include + #include + #include +@@ -85,6 +85,6 @@ + #include + #include + #include +-#include ++//#include + + #endif /* SDL_h_ */ +diff --git a/thirdparty/sdl/joystick/SDL_joystick.c b/thirdparty/sdl/joystick/SDL_joystick.c +index 921576854e..f36ca95baa 100644 +--- a/thirdparty/sdl/joystick/SDL_joystick.c ++++ b/thirdparty/sdl/joystick/SDL_joystick.c +@@ -29,7 +29,7 @@ + #include "SDL_steam_virtual_gamepad.h" + + #include "../events/SDL_events_c.h" +-#include "../video/SDL_sysvideo.h" ++//#include "../video/SDL_sysvideo.h" + #include "../sensor/SDL_sensor_c.h" + #include "hidapi/SDL_hidapijoystick_c.h" + +@@ -1011,7 +1011,8 @@ static void AttemptSensorFusion(SDL_Joystick *joystick, bool invert_sensors) + When a phone is being used as a gamepad, its orientation changes, + so adjust sensor axes to match. + */ +- if (SDL_GetNaturalDisplayOrientation(SDL_GetPrimaryDisplay()) == SDL_ORIENTATION_LANDSCAPE) { ++ //if (SDL_GetNaturalDisplayOrientation(SDL_GetPrimaryDisplay()) == SDL_ORIENTATION_LANDSCAPE) { ++ if (true) { + /* When a device in landscape orientation is laid flat, the axes change + orientation as follows: + -X to +X becomes -X to +X +@@ -2068,11 +2069,6 @@ static bool SDL_PrivateJoystickShouldIgnoreEvent(void) + if (SDL_joystick_allows_background_events) { + return false; + } +- +- if (SDL_HasWindows() && SDL_GetKeyboardFocus() == NULL) { +- // We have windows but we don't have focus, ignore the event. +- return true; +- } + return false; + } + +diff --git a/thirdparty/sdl/joystick/windows/SDL_dinputjoystick.c b/thirdparty/sdl/joystick/windows/SDL_dinputjoystick.c +index b00218d969..377992ed9e 100644 +--- a/thirdparty/sdl/joystick/windows/SDL_dinputjoystick.c ++++ b/thirdparty/sdl/joystick/windows/SDL_dinputjoystick.c +@@ -40,11 +40,8 @@ + #define CONVERT_MAGNITUDE(x) (((x)*10000) / 0x7FFF) + + // external variables referenced. +-#ifdef SDL_VIDEO_DRIVER_WINDOWS + extern HWND SDL_HelperWindow; +-#else +-static const HWND SDL_HelperWindow = NULL; +-#endif ++ + + // local variables + static bool coinitialized = false; diff --git a/thirdparty/sdl/patches/0002-msvc-constants-fpstrict.patch b/thirdparty/sdl/patches/0002-msvc-constants-fpstrict.patch new file mode 100644 index 00000000000..3be681fbb11 --- /dev/null +++ b/thirdparty/sdl/patches/0002-msvc-constants-fpstrict.patch @@ -0,0 +1,41 @@ +diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps4.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps4.c +index 7404bf2268..a697cdf6d9 100644 +--- a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps4.c ++++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps4.c +@@ -1003,8 +1003,8 @@ static bool HIDAPI_DriverPS4_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device + + static void HIDAPI_DriverPS4_HandleStatePacket(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverPS4_Context *ctx, PS4StatePacket_t *packet, int size) + { +- static const float TOUCHPAD_SCALEX = 1.0f / 1920; +- static const float TOUCHPAD_SCALEY = 1.0f / 920; // This is noted as being 944 resolution, but 920 feels better ++ static const float TOUCHPAD_SCALEX = 5.20833333e-4f; // 1.0f / 1920 ++ static const float TOUCHPAD_SCALEY = 1.08695652e-3f; // 1.0f / 920 // This is noted as being 944 resolution, but 920 feels better + Sint16 axis; + bool touchpad_down; + int touchpad_x, touchpad_y; +diff --git a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps5.c b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps5.c +index abf59a87f2..a486af6b0f 100644 +--- a/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps5.c ++++ b/thirdparty/sdl/joystick/hidapi/SDL_hidapi_ps5.c +@@ -1355,8 +1355,8 @@ static void HIDAPI_DriverPS5_HandleStatePacketCommon(SDL_Joystick *joystick, SDL + + static void HIDAPI_DriverPS5_HandleStatePacket(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverPS5_Context *ctx, PS5StatePacket_t *packet, Uint64 timestamp) + { +- static const float TOUCHPAD_SCALEX = 1.0f / 1920; +- static const float TOUCHPAD_SCALEY = 1.0f / 1070; ++ static const float TOUCHPAD_SCALEX = 5.20833333e-4f; // 1.0f / 1920 ++ static const float TOUCHPAD_SCALEY = 9.34579439e-4f; // 1.0f / 1070 + bool touchpad_down; + int touchpad_x, touchpad_y; + +@@ -1406,8 +1406,8 @@ static void HIDAPI_DriverPS5_HandleStatePacket(SDL_Joystick *joystick, SDL_hid_d + + static void HIDAPI_DriverPS5_HandleStatePacketAlt(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverPS5_Context *ctx, PS5StatePacketAlt_t *packet, Uint64 timestamp) + { +- static const float TOUCHPAD_SCALEX = 1.0f / 1920; +- static const float TOUCHPAD_SCALEY = 1.0f / 1070; ++ static const float TOUCHPAD_SCALEX = 5.20833333e-4f; // 1.0f / 1920 ++ static const float TOUCHPAD_SCALEY = 9.34579439e-4f; // 1.0f / 1070 + bool touchpad_down; + int touchpad_x, touchpad_y; + diff --git a/thirdparty/sdl/sensor/SDL_sensor.c b/thirdparty/sdl/sensor/SDL_sensor.c new file mode 100644 index 00000000000..60e829a982b --- /dev/null +++ b/thirdparty/sdl/sensor/SDL_sensor.c @@ -0,0 +1,622 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This is the sensor API for Simple DirectMedia Layer + +#include "SDL_syssensor.h" + +#include "../events/SDL_events_c.h" +#include "../joystick/SDL_gamepad_c.h" + +static SDL_SensorDriver *SDL_sensor_drivers[] = { +#ifdef SDL_SENSOR_ANDROID + &SDL_ANDROID_SensorDriver, +#endif +#ifdef SDL_SENSOR_COREMOTION + &SDL_COREMOTION_SensorDriver, +#endif +#ifdef SDL_SENSOR_WINDOWS + &SDL_WINDOWS_SensorDriver, +#endif +#ifdef SDL_SENSOR_VITA + &SDL_VITA_SensorDriver, +#endif +#ifdef SDL_SENSOR_N3DS + &SDL_N3DS_SensorDriver, +#endif +#if defined(SDL_SENSOR_DUMMY) || defined(SDL_SENSOR_DISABLED) + &SDL_DUMMY_SensorDriver +#endif +}; + +#ifndef SDL_THREAD_SAFETY_ANALYSIS +static +#endif +SDL_Mutex *SDL_sensor_lock = NULL; // This needs to support recursive locks +static SDL_AtomicInt SDL_sensor_lock_pending; +static int SDL_sensors_locked; +static bool SDL_sensors_initialized; +static SDL_Sensor *SDL_sensors SDL_GUARDED_BY(SDL_sensor_lock) = NULL; + +#define CHECK_SENSOR_MAGIC(sensor, result) \ + if (!SDL_ObjectValid(sensor, SDL_OBJECT_TYPE_SENSOR)) { \ + SDL_InvalidParamError("sensor"); \ + SDL_UnlockSensors(); \ + return result; \ + } + +bool SDL_SensorsInitialized(void) +{ + return SDL_sensors_initialized; +} + +void SDL_LockSensors(void) +{ + (void)SDL_AtomicIncRef(&SDL_sensor_lock_pending); + SDL_LockMutex(SDL_sensor_lock); + (void)SDL_AtomicDecRef(&SDL_sensor_lock_pending); + + ++SDL_sensors_locked; +} + +void SDL_UnlockSensors(void) +{ + bool last_unlock = false; + + --SDL_sensors_locked; + + if (!SDL_sensors_initialized) { + // NOTE: There's a small window here where another thread could lock the mutex after we've checked for pending locks + if (!SDL_sensors_locked && SDL_GetAtomicInt(&SDL_sensor_lock_pending) == 0) { + last_unlock = true; + } + } + + /* The last unlock after sensors are uninitialized will cleanup the mutex, + * allowing applications to lock sensors while reinitializing the system. + */ + if (last_unlock) { + SDL_Mutex *sensor_lock = SDL_sensor_lock; + + SDL_LockMutex(sensor_lock); + { + SDL_UnlockMutex(SDL_sensor_lock); + + SDL_sensor_lock = NULL; + } + SDL_UnlockMutex(sensor_lock); + SDL_DestroyMutex(sensor_lock); + } else { + SDL_UnlockMutex(SDL_sensor_lock); + } +} + +bool SDL_SensorsLocked(void) +{ + return (SDL_sensors_locked > 0); +} + +void SDL_AssertSensorsLocked(void) +{ + SDL_assert(SDL_SensorsLocked()); +} + +bool SDL_InitSensors(void) +{ + int i; + bool status; + + // Create the sensor list lock + if (SDL_sensor_lock == NULL) { + SDL_sensor_lock = SDL_CreateMutex(); + } + + if (!SDL_InitSubSystem(SDL_INIT_EVENTS)) { + return false; + } + + SDL_LockSensors(); + + SDL_sensors_initialized = true; + + status = false; + for (i = 0; i < SDL_arraysize(SDL_sensor_drivers); ++i) { + if (SDL_sensor_drivers[i]->Init()) { + status = true; + } + } + + SDL_UnlockSensors(); + + if (!status) { + SDL_QuitSensors(); + } + + return status; +} + +bool SDL_SensorsOpened(void) +{ + bool opened; + + SDL_LockSensors(); + { + if (SDL_sensors != NULL) { + opened = true; + } else { + opened = false; + } + } + SDL_UnlockSensors(); + + return opened; +} + +SDL_SensorID *SDL_GetSensors(int *count) +{ + int i, num_sensors, device_index; + int sensor_index = 0, total_sensors = 0; + SDL_SensorID *sensors; + + SDL_LockSensors(); + { + for (i = 0; i < SDL_arraysize(SDL_sensor_drivers); ++i) { + total_sensors += SDL_sensor_drivers[i]->GetCount(); + } + + sensors = (SDL_SensorID *)SDL_malloc((total_sensors + 1) * sizeof(*sensors)); + if (sensors) { + if (count) { + *count = total_sensors; + } + + for (i = 0; i < SDL_arraysize(SDL_sensor_drivers); ++i) { + num_sensors = SDL_sensor_drivers[i]->GetCount(); + for (device_index = 0; device_index < num_sensors; ++device_index) { + SDL_assert(sensor_index < total_sensors); + sensors[sensor_index] = SDL_sensor_drivers[i]->GetDeviceInstanceID(device_index); + SDL_assert(sensors[sensor_index] > 0); + ++sensor_index; + } + } + SDL_assert(sensor_index == total_sensors); + sensors[sensor_index] = 0; + } else { + if (count) { + *count = 0; + } + } + } + SDL_UnlockSensors(); + + return sensors; +} + +/* + * Get the driver and device index for a sensor instance ID + * This should be called while the sensor lock is held, to prevent another thread from updating the list + */ +static bool SDL_GetDriverAndSensorIndex(SDL_SensorID instance_id, SDL_SensorDriver **driver, int *driver_index) +{ + int i, num_sensors, device_index; + + if (instance_id > 0) { + for (i = 0; i < SDL_arraysize(SDL_sensor_drivers); ++i) { + num_sensors = SDL_sensor_drivers[i]->GetCount(); + for (device_index = 0; device_index < num_sensors; ++device_index) { + SDL_SensorID sensor_id = SDL_sensor_drivers[i]->GetDeviceInstanceID(device_index); + if (sensor_id == instance_id) { + *driver = SDL_sensor_drivers[i]; + *driver_index = device_index; + return true; + } + } + } + } + SDL_SetError("Sensor %" SDL_PRIu32 " not found", instance_id); + return false; +} + +/* + * Get the implementation dependent name of a sensor + */ +const char *SDL_GetSensorNameForID(SDL_SensorID instance_id) +{ + SDL_SensorDriver *driver; + int device_index; + const char *name = NULL; + + SDL_LockSensors(); + if (SDL_GetDriverAndSensorIndex(instance_id, &driver, &device_index)) { + name = SDL_GetPersistentString(driver->GetDeviceName(device_index)); + } + SDL_UnlockSensors(); + + return name; +} + +SDL_SensorType SDL_GetSensorTypeForID(SDL_SensorID instance_id) +{ + SDL_SensorDriver *driver; + int device_index; + SDL_SensorType type = SDL_SENSOR_INVALID; + + SDL_LockSensors(); + if (SDL_GetDriverAndSensorIndex(instance_id, &driver, &device_index)) { + type = driver->GetDeviceType(device_index); + } + SDL_UnlockSensors(); + + return type; +} + +int SDL_GetSensorNonPortableTypeForID(SDL_SensorID instance_id) +{ + SDL_SensorDriver *driver; + int device_index; + int type = -1; + + SDL_LockSensors(); + if (SDL_GetDriverAndSensorIndex(instance_id, &driver, &device_index)) { + type = driver->GetDeviceNonPortableType(device_index); + } + SDL_UnlockSensors(); + + return type; +} + +/* + * Open a sensor for use - the index passed as an argument refers to + * the N'th sensor on the system. This index is the value which will + * identify this sensor in future sensor events. + * + * This function returns a sensor identifier, or NULL if an error occurred. + */ +SDL_Sensor *SDL_OpenSensor(SDL_SensorID instance_id) +{ + SDL_SensorDriver *driver; + int device_index; + SDL_Sensor *sensor; + SDL_Sensor *sensorlist; + const char *sensorname = NULL; + + SDL_LockSensors(); + + if (!SDL_GetDriverAndSensorIndex(instance_id, &driver, &device_index)) { + SDL_UnlockSensors(); + return NULL; + } + + sensorlist = SDL_sensors; + /* If the sensor is already open, return it + * it is important that we have a single sensor * for each instance id + */ + while (sensorlist) { + if (instance_id == sensorlist->instance_id) { + sensor = sensorlist; + ++sensor->ref_count; + SDL_UnlockSensors(); + return sensor; + } + sensorlist = sensorlist->next; + } + + // Create and initialize the sensor + sensor = (SDL_Sensor *)SDL_calloc(1, sizeof(*sensor)); + if (!sensor) { + SDL_UnlockSensors(); + return NULL; + } + SDL_SetObjectValid(sensor, SDL_OBJECT_TYPE_SENSOR, true); + sensor->driver = driver; + sensor->instance_id = instance_id; + sensor->type = driver->GetDeviceType(device_index); + sensor->non_portable_type = driver->GetDeviceNonPortableType(device_index); + + if (!driver->Open(sensor, device_index)) { + SDL_SetObjectValid(sensor, SDL_OBJECT_TYPE_SENSOR, false); + SDL_free(sensor); + SDL_UnlockSensors(); + return NULL; + } + + sensorname = driver->GetDeviceName(device_index); + if (sensorname) { + sensor->name = SDL_strdup(sensorname); + } else { + sensor->name = NULL; + } + + // Add sensor to list + ++sensor->ref_count; + // Link the sensor in the list + sensor->next = SDL_sensors; + SDL_sensors = sensor; + + driver->Update(sensor); + + SDL_UnlockSensors(); + + return sensor; +} + +/* + * Find the SDL_Sensor that owns this instance id + */ +SDL_Sensor *SDL_GetSensorFromID(SDL_SensorID instance_id) +{ + SDL_Sensor *sensor; + + SDL_LockSensors(); + for (sensor = SDL_sensors; sensor; sensor = sensor->next) { + if (sensor->instance_id == instance_id) { + break; + } + } + SDL_UnlockSensors(); + return sensor; +} + +/* + * Get the properties associated with a sensor. + */ +SDL_PropertiesID SDL_GetSensorProperties(SDL_Sensor *sensor) +{ + SDL_PropertiesID result; + + SDL_LockSensors(); + { + CHECK_SENSOR_MAGIC(sensor, 0); + + if (sensor->props == 0) { + sensor->props = SDL_CreateProperties(); + } + result = sensor->props; + } + SDL_UnlockSensors(); + + return result; +} + +/* + * Get the friendly name of this sensor + */ +const char *SDL_GetSensorName(SDL_Sensor *sensor) +{ + const char *result; + + SDL_LockSensors(); + { + CHECK_SENSOR_MAGIC(sensor, NULL); + + result = SDL_GetPersistentString(sensor->name); + } + SDL_UnlockSensors(); + + return result; +} + +/* + * Get the type of this sensor + */ +SDL_SensorType SDL_GetSensorType(SDL_Sensor *sensor) +{ + SDL_SensorType result; + + SDL_LockSensors(); + { + CHECK_SENSOR_MAGIC(sensor, SDL_SENSOR_INVALID); + + result = sensor->type; + } + SDL_UnlockSensors(); + + return result; +} + +/* + * Get the platform dependent type of this sensor + */ +int SDL_GetSensorNonPortableType(SDL_Sensor *sensor) +{ + int result; + + SDL_LockSensors(); + { + CHECK_SENSOR_MAGIC(sensor, -1); + + result = sensor->non_portable_type; + } + SDL_UnlockSensors(); + + return result; +} + +/* + * Get the instance id for this opened sensor + */ +SDL_SensorID SDL_GetSensorID(SDL_Sensor *sensor) +{ + SDL_SensorID result; + + SDL_LockSensors(); + { + CHECK_SENSOR_MAGIC(sensor, 0); + + result = sensor->instance_id; + } + SDL_UnlockSensors(); + + return result; +} + +/* + * Get the current state of this sensor + */ +bool SDL_GetSensorData(SDL_Sensor *sensor, float *data, int num_values) +{ + SDL_LockSensors(); + { + CHECK_SENSOR_MAGIC(sensor, false); + + num_values = SDL_min(num_values, SDL_arraysize(sensor->data)); + SDL_memcpy(data, sensor->data, num_values * sizeof(*data)); + } + SDL_UnlockSensors(); + + return true; +} + +/* + * Close a sensor previously opened with SDL_OpenSensor() + */ +void SDL_CloseSensor(SDL_Sensor *sensor) +{ + SDL_Sensor *sensorlist; + SDL_Sensor *sensorlistprev; + + SDL_LockSensors(); + { + CHECK_SENSOR_MAGIC(sensor,); + + // First decrement ref count + if (--sensor->ref_count > 0) { + SDL_UnlockSensors(); + return; + } + + SDL_DestroyProperties(sensor->props); + + sensor->driver->Close(sensor); + sensor->hwdata = NULL; + SDL_SetObjectValid(sensor, SDL_OBJECT_TYPE_SENSOR, false); + + sensorlist = SDL_sensors; + sensorlistprev = NULL; + while (sensorlist) { + if (sensor == sensorlist) { + if (sensorlistprev) { + // unlink this entry + sensorlistprev->next = sensorlist->next; + } else { + SDL_sensors = sensor->next; + } + break; + } + sensorlistprev = sensorlist; + sensorlist = sensorlist->next; + } + + // Free the data associated with this sensor + SDL_free(sensor->name); + SDL_free(sensor); + } + SDL_UnlockSensors(); +} + +void SDL_QuitSensors(void) +{ + int i; + + SDL_LockSensors(); + + // Stop the event polling + while (SDL_sensors) { + SDL_sensors->ref_count = 1; + SDL_CloseSensor(SDL_sensors); + } + + // Quit the sensor setup + for (i = 0; i < SDL_arraysize(SDL_sensor_drivers); ++i) { + SDL_sensor_drivers[i]->Quit(); + } + + SDL_QuitSubSystem(SDL_INIT_EVENTS); + + SDL_sensors_initialized = false; + + SDL_UnlockSensors(); +} + +// These are global for SDL_syssensor.c and SDL_events.c + +void SDL_SendSensorUpdate(Uint64 timestamp, SDL_Sensor *sensor, Uint64 sensor_timestamp, float *data, int num_values) +{ + SDL_AssertSensorsLocked(); + + // Allow duplicate events, for things like steps and heartbeats + + // Update internal sensor state + num_values = SDL_min(num_values, SDL_arraysize(sensor->data)); + SDL_memcpy(sensor->data, data, num_values * sizeof(*data)); + + // Post the event, if desired + if (SDL_EventEnabled(SDL_EVENT_SENSOR_UPDATE)) { + SDL_Event event; + event.type = SDL_EVENT_SENSOR_UPDATE; + event.common.timestamp = timestamp; + event.sensor.which = sensor->instance_id; + num_values = SDL_min(num_values, SDL_arraysize(event.sensor.data)); + SDL_memset(event.sensor.data, 0, sizeof(event.sensor.data)); + SDL_memcpy(event.sensor.data, data, num_values * sizeof(*data)); + event.sensor.sensor_timestamp = sensor_timestamp; + SDL_PushEvent(&event); + } + + SDL_GamepadSensorWatcher(timestamp, sensor->instance_id, sensor_timestamp, data, num_values); +} + +void SDL_UpdateSensor(SDL_Sensor *sensor) +{ + SDL_LockSensors(); + { + CHECK_SENSOR_MAGIC(sensor,); + + sensor->driver->Update(sensor); + } + SDL_UnlockSensors(); +} + +void SDL_UpdateSensors(void) +{ + int i; + SDL_Sensor *sensor; + + if (!SDL_WasInit(SDL_INIT_SENSOR)) { + return; + } + + SDL_LockSensors(); + + for (sensor = SDL_sensors; sensor; sensor = sensor->next) { + sensor->driver->Update(sensor); + } + + /* this needs to happen AFTER walking the sensor list above, so that any + dangling hardware data from removed devices can be free'd + */ + for (i = 0; i < SDL_arraysize(SDL_sensor_drivers); ++i) { + SDL_sensor_drivers[i]->Detect(); + } + + SDL_UnlockSensors(); +} diff --git a/thirdparty/sdl/sensor/SDL_sensor_c.h b/thirdparty/sdl/sensor/SDL_sensor_c.h new file mode 100644 index 00000000000..26a988efce2 --- /dev/null +++ b/thirdparty/sdl/sensor/SDL_sensor_c.h @@ -0,0 +1,59 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_sensor_c_h_ +#define SDL_sensor_c_h_ + +#ifdef SDL_THREAD_SAFETY_ANALYSIS +extern SDL_Mutex *SDL_sensor_lock; +#endif + +struct SDL_SensorDriver; + +// Useful functions and variables from SDL_sensor.c + +// Initialization and shutdown functions +extern bool SDL_InitSensors(void); +extern void SDL_QuitSensors(void); + +// Return whether the sensor system is currently initialized +extern bool SDL_SensorsInitialized(void); + +// Return whether the sensors are currently locked +extern bool SDL_SensorsLocked(void); + +// Make sure we currently have the sensors locked +extern void SDL_AssertSensorsLocked(void) SDL_ASSERT_CAPABILITY(SDL_sensor_lock); + +extern void SDL_LockSensors(void) SDL_ACQUIRE(SDL_sensor_lock); +extern void SDL_UnlockSensors(void) SDL_RELEASE(SDL_sensor_lock); + +// Function to return whether there are any sensors opened by the application +extern bool SDL_SensorsOpened(void); + +// Update an individual sensor, used by gamepad sensor fusion +extern void SDL_UpdateSensor(SDL_Sensor *sensor); + +// Internal event queueing functions +extern void SDL_SendSensorUpdate(Uint64 timestamp, SDL_Sensor *sensor, Uint64 sensor_timestamp, float *data, int num_values); + +#endif // SDL_sensor_c_h_ diff --git a/thirdparty/sdl/sensor/SDL_syssensor.h b/thirdparty/sdl/sensor/SDL_syssensor.h new file mode 100644 index 00000000000..1ce63e5d7fa --- /dev/null +++ b/thirdparty/sdl/sensor/SDL_syssensor.h @@ -0,0 +1,110 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_syssensor_c_h_ +#define SDL_syssensor_c_h_ + +// This is the system specific header for the SDL sensor API + +#include "SDL_sensor_c.h" + +#define _guarded SDL_GUARDED_BY(SDL_sensor_lock) + +// The SDL sensor structure +struct SDL_Sensor +{ + SDL_SensorID instance_id _guarded; // Device instance, monotonically increasing from 0 + char *name _guarded; // Sensor name - system dependent + SDL_SensorType type _guarded; // Type of the sensor + int non_portable_type _guarded; // Platform dependent type of the sensor + + float data[16] _guarded; // The current state of the sensor + + struct SDL_SensorDriver *driver _guarded; + + struct sensor_hwdata *hwdata _guarded; // Driver dependent information + + SDL_PropertiesID props _guarded; + + int ref_count _guarded; // Reference count for multiple opens + + struct SDL_Sensor *next _guarded; // pointer to next sensor we have allocated +}; + +#undef _guarded + +typedef struct SDL_SensorDriver +{ + /* Function to scan the system for sensors. + * sensor 0 should be the system default sensor. + * This function should return 0, or -1 on an unrecoverable fatal error. + */ + bool (*Init)(void); + + // Function to return the number of sensors available right now + int (*GetCount)(void); + + // Function to check to see if the available sensors have changed + void (*Detect)(void); + + // Function to get the device-dependent name of a sensor + const char *(*GetDeviceName)(int device_index); + + // Function to get the type of a sensor + SDL_SensorType (*GetDeviceType)(int device_index); + + // Function to get the platform dependent type of a sensor + int (*GetDeviceNonPortableType)(int device_index); + + // Function to get the current instance id of the sensor located at device_index + SDL_SensorID (*GetDeviceInstanceID)(int device_index); + + /* Function to open a sensor for use. + The sensor to open is specified by the device index. + It returns 0, or -1 if there is an error. + */ + bool (*Open)(SDL_Sensor *sensor, int device_index); + + /* Function to update the state of a sensor - called as a device poll. + * This function shouldn't update the sensor structure directly, + * but instead should call SDL_SendSensorUpdate() to deliver events + * and update sensor device state. + */ + void (*Update)(SDL_Sensor *sensor); + + // Function to close a sensor after use + void (*Close)(SDL_Sensor *sensor); + + // Function to perform any system-specific sensor related cleanup + void (*Quit)(void); + +} SDL_SensorDriver; + +// The available sensor drivers +extern SDL_SensorDriver SDL_ANDROID_SensorDriver; +extern SDL_SensorDriver SDL_COREMOTION_SensorDriver; +extern SDL_SensorDriver SDL_WINDOWS_SensorDriver; +extern SDL_SensorDriver SDL_DUMMY_SensorDriver; +extern SDL_SensorDriver SDL_VITA_SensorDriver; +extern SDL_SensorDriver SDL_N3DS_SensorDriver; + +#endif // SDL_syssensor_h_ diff --git a/thirdparty/sdl/sensor/dummy/SDL_dummysensor.c b/thirdparty/sdl/sensor/dummy/SDL_dummysensor.c new file mode 100644 index 00000000000..ce8145da3e2 --- /dev/null +++ b/thirdparty/sdl/sensor/dummy/SDL_dummysensor.c @@ -0,0 +1,93 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(SDL_SENSOR_DUMMY) || defined(SDL_SENSOR_DISABLED) + +#include "SDL_dummysensor.h" +#include "../SDL_syssensor.h" + +static bool SDL_DUMMY_SensorInit(void) +{ + return true; +} + +static int SDL_DUMMY_SensorGetCount(void) +{ + return 0; +} + +static void SDL_DUMMY_SensorDetect(void) +{ +} + +static const char *SDL_DUMMY_SensorGetDeviceName(int device_index) +{ + return NULL; +} + +static SDL_SensorType SDL_DUMMY_SensorGetDeviceType(int device_index) +{ + return SDL_SENSOR_INVALID; +} + +static int SDL_DUMMY_SensorGetDeviceNonPortableType(int device_index) +{ + return -1; +} + +static SDL_SensorID SDL_DUMMY_SensorGetDeviceInstanceID(int device_index) +{ + return -1; +} + +static bool SDL_DUMMY_SensorOpen(SDL_Sensor *sensor, int device_index) +{ + return SDL_Unsupported(); +} + +static void SDL_DUMMY_SensorUpdate(SDL_Sensor *sensor) +{ +} + +static void SDL_DUMMY_SensorClose(SDL_Sensor *sensor) +{ +} + +static void SDL_DUMMY_SensorQuit(void) +{ +} + +SDL_SensorDriver SDL_DUMMY_SensorDriver = { + SDL_DUMMY_SensorInit, + SDL_DUMMY_SensorGetCount, + SDL_DUMMY_SensorDetect, + SDL_DUMMY_SensorGetDeviceName, + SDL_DUMMY_SensorGetDeviceType, + SDL_DUMMY_SensorGetDeviceNonPortableType, + SDL_DUMMY_SensorGetDeviceInstanceID, + SDL_DUMMY_SensorOpen, + SDL_DUMMY_SensorUpdate, + SDL_DUMMY_SensorClose, + SDL_DUMMY_SensorQuit, +}; + +#endif // SDL_SENSOR_DUMMY || SDL_SENSOR_DISABLED diff --git a/thirdparty/sdl/sensor/dummy/SDL_dummysensor.h b/thirdparty/sdl/sensor/dummy/SDL_dummysensor.h new file mode 100644 index 00000000000..4b0c6f8fcc8 --- /dev/null +++ b/thirdparty/sdl/sensor/dummy/SDL_dummysensor.h @@ -0,0 +1,21 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" diff --git a/thirdparty/sdl/stdlib/SDL_casefolding.h b/thirdparty/sdl/stdlib/SDL_casefolding.h new file mode 100644 index 00000000000..6fbe0a7f7c0 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_casefolding.h @@ -0,0 +1,2769 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * This data was generated by SDL/build-scripts/makecasefoldhashtable.pl + * + * Do not manually edit this file! + */ + +#ifndef SDL_casefolding_h_ +#define SDL_casefolding_h_ + +/* We build three simple hashmaps here: one that maps Unicode codepoints to +a one, two, or three lowercase codepoints. To retrieve this info: look at +case_fold_hashX, where X is 1, 2, or 3. Most foldable codepoints fold to one, +a few dozen fold to two, and a handful fold to three. If the codepoint isn't +in any of these hashes, it doesn't fold (no separate upper and lowercase). + +Almost all these codepoints fit into 16 bits, so we hash them as such to save +memory. If a codepoint is > 0xFFFF, we have separate hashes for them, +since there are (currently) only about 120 of them and (currently) all of them +map to a single lowercase codepoint. */ + +typedef struct CaseFoldMapping1_32 +{ + Uint32 from; + Uint32 to0; +} CaseFoldMapping1_32; + +typedef struct CaseFoldMapping1_16 +{ + Uint16 from; + Uint16 to0; +} CaseFoldMapping1_16; + +typedef struct CaseFoldMapping2_16 +{ + Uint16 from; + Uint16 to0; + Uint16 to1; +} CaseFoldMapping2_16; + +typedef struct CaseFoldMapping3_16 +{ + Uint16 from; + Uint16 to0; + Uint16 to1; + Uint16 to2; +} CaseFoldMapping3_16; + +typedef struct CaseFoldHashBucket1_16 +{ + const CaseFoldMapping1_16 *list; + const Uint8 count; +} CaseFoldHashBucket1_16; + +typedef struct CaseFoldHashBucket1_32 +{ + const CaseFoldMapping1_32 *list; + const Uint8 count; +} CaseFoldHashBucket1_32; + +typedef struct CaseFoldHashBucket2_16 +{ + const CaseFoldMapping2_16 *list; + const Uint8 count; +} CaseFoldHashBucket2_16; + +typedef struct CaseFoldHashBucket3_16 +{ + const CaseFoldMapping3_16 *list; + const Uint8 count; +} CaseFoldHashBucket3_16; + +static const CaseFoldMapping1_16 case_fold1_16_000[] = { + { 0x0202, 0x0203 }, + { 0x0404, 0x0454 }, + { 0x1E1E, 0x1E1F }, + { 0x2C2C, 0x2C5C }, + { 0xABAB, 0x13DB } +}; + +static const CaseFoldMapping1_16 case_fold1_16_001[] = { + { 0x0100, 0x0101 }, + { 0x0405, 0x0455 }, + { 0x0504, 0x0505 }, + { 0x2C2D, 0x2C5D }, + { 0xA7A6, 0xA7A7 }, + { 0xABAA, 0x13DA } +}; + +static const CaseFoldMapping1_16 case_fold1_16_002[] = { + { 0x0200, 0x0201 }, + { 0x0406, 0x0456 }, + { 0x1E1C, 0x1E1D }, + { 0x1F1D, 0x1F15 }, + { 0x2C2E, 0x2C5E }, + { 0xABA9, 0x13D9 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_003[] = { + { 0x0102, 0x0103 }, + { 0x0407, 0x0457 }, + { 0x0506, 0x0507 }, + { 0x1F1C, 0x1F14 }, + { 0x2C2F, 0x2C5F }, + { 0xA7A4, 0xA7A5 }, + { 0xABA8, 0x13D8 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_004[] = { + { 0x0206, 0x0207 }, + { 0x0400, 0x0450 }, + { 0x1E1A, 0x1E1B }, + { 0x1F1B, 0x1F13 }, + { 0x2C28, 0x2C58 }, + { 0xABAF, 0x13DF } +}; + +static const CaseFoldMapping1_16 case_fold1_16_005[] = { + { 0x0104, 0x0105 }, + { 0x0401, 0x0451 }, + { 0x0500, 0x0501 }, + { 0x1F1A, 0x1F12 }, + { 0x2C29, 0x2C59 }, + { 0xA7A2, 0xA7A3 }, + { 0xABAE, 0x13DE } +}; + +static const CaseFoldMapping1_16 case_fold1_16_006[] = { + { 0x0204, 0x0205 }, + { 0x0402, 0x0452 }, + { 0x1E18, 0x1E19 }, + { 0x1F19, 0x1F11 }, + { 0x2C2A, 0x2C5A }, + { 0xABAD, 0x13DD } +}; + +static const CaseFoldMapping1_16 case_fold1_16_007[] = { + { 0x0106, 0x0107 }, + { 0x0403, 0x0453 }, + { 0x0502, 0x0503 }, + { 0x1F18, 0x1F10 }, + { 0x2126, 0x03C9 }, + { 0x2C2B, 0x2C5B }, + { 0xA7A0, 0xA7A1 }, + { 0xABAC, 0x13DC } +}; + +static const CaseFoldMapping1_16 case_fold1_16_008[] = { + { 0x020A, 0x020B }, + { 0x040C, 0x045C }, + { 0x1E16, 0x1E17 }, + { 0x2C24, 0x2C54 }, + { 0xABA3, 0x13D3 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_009[] = { + { 0x0108, 0x0109 }, + { 0x040D, 0x045D }, + { 0x050C, 0x050D }, + { 0x2C25, 0x2C55 }, + { 0xA7AE, 0x026A }, + { 0xABA2, 0x13D2 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_010[] = { + { 0x0208, 0x0209 }, + { 0x040E, 0x045E }, + { 0x1E14, 0x1E15 }, + { 0x212B, 0x00E5 }, + { 0x2C26, 0x2C56 }, + { 0xA7AD, 0x026C }, + { 0xABA1, 0x13D1 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_011[] = { + { 0x010A, 0x010B }, + { 0x040F, 0x045F }, + { 0x050E, 0x050F }, + { 0x212A, 0x006B }, + { 0x2C27, 0x2C57 }, + { 0xA7AC, 0x0261 }, + { 0xABA0, 0x13D0 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_012[] = { + { 0x020E, 0x020F }, + { 0x0408, 0x0458 }, + { 0x1E12, 0x1E13 }, + { 0x2C20, 0x2C50 }, + { 0xA7AB, 0x025C }, + { 0xABA7, 0x13D7 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_013[] = { + { 0x010C, 0x010D }, + { 0x0409, 0x0459 }, + { 0x0508, 0x0509 }, + { 0x2C21, 0x2C51 }, + { 0xA7AA, 0x0266 }, + { 0xABA6, 0x13D6 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_014[] = { + { 0x020C, 0x020D }, + { 0x040A, 0x045A }, + { 0x1E10, 0x1E11 }, + { 0x2C22, 0x2C52 }, + { 0xABA5, 0x13D5 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_015[] = { + { 0x010E, 0x010F }, + { 0x040B, 0x045B }, + { 0x050A, 0x050B }, + { 0x2C23, 0x2C53 }, + { 0xA7A8, 0xA7A9 }, + { 0xABA4, 0x13D4 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_016[] = { + { 0x0212, 0x0213 }, + { 0x0414, 0x0434 }, + { 0x1E0E, 0x1E0F }, + { 0x1F0F, 0x1F07 }, + { 0xABBB, 0x13EB } +}; + +static const CaseFoldMapping1_16 case_fold1_16_017[] = { + { 0x0110, 0x0111 }, + { 0x0415, 0x0435 }, + { 0x0514, 0x0515 }, + { 0x1F0E, 0x1F06 }, + { 0xA7B6, 0xA7B7 }, + { 0xABBA, 0x13EA } +}; + +static const CaseFoldMapping1_16 case_fold1_16_018[] = { + { 0x0210, 0x0211 }, + { 0x0416, 0x0436 }, + { 0x1E0C, 0x1E0D }, + { 0x1F0D, 0x1F05 }, + { 0xABB9, 0x13E9 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_019[] = { + { 0x0112, 0x0113 }, + { 0x0417, 0x0437 }, + { 0x0516, 0x0517 }, + { 0x1F0C, 0x1F04 }, + { 0x2132, 0x214E }, + { 0xA7B4, 0xA7B5 }, + { 0xABB8, 0x13E8 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_020[] = { + { 0x0216, 0x0217 }, + { 0x0410, 0x0430 }, + { 0x1E0A, 0x1E0B }, + { 0x1F0B, 0x1F03 }, + { 0xA7B3, 0xAB53 }, + { 0xABBF, 0x13EF } +}; + +static const CaseFoldMapping1_16 case_fold1_16_021[] = { + { 0x0114, 0x0115 }, + { 0x0411, 0x0431 }, + { 0x0510, 0x0511 }, + { 0x1F0A, 0x1F02 }, + { 0xA7B2, 0x029D }, + { 0xABBE, 0x13EE } +}; + +static const CaseFoldMapping1_16 case_fold1_16_022[] = { + { 0x0214, 0x0215 }, + { 0x0412, 0x0432 }, + { 0x1E08, 0x1E09 }, + { 0x1F09, 0x1F01 }, + { 0xA7B1, 0x0287 }, + { 0xABBD, 0x13ED } +}; + +static const CaseFoldMapping1_16 case_fold1_16_023[] = { + { 0x0116, 0x0117 }, + { 0x0413, 0x0433 }, + { 0x0512, 0x0513 }, + { 0x1F08, 0x1F00 }, + { 0xA7B0, 0x029E }, + { 0xABBC, 0x13EC } +}; + +static const CaseFoldMapping1_16 case_fold1_16_024[] = { + { 0x021A, 0x021B }, + { 0x041C, 0x043C }, + { 0x1E06, 0x1E07 }, + { 0xABB3, 0x13E3 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_025[] = { + { 0x0118, 0x0119 }, + { 0x041D, 0x043D }, + { 0x051C, 0x051D }, + { 0xA7BE, 0xA7BF }, + { 0xABB2, 0x13E2 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_026[] = { + { 0x0218, 0x0219 }, + { 0x041E, 0x043E }, + { 0x1E04, 0x1E05 }, + { 0xABB1, 0x13E1 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_027[] = { + { 0x011A, 0x011B }, + { 0x041F, 0x043F }, + { 0x051E, 0x051F }, + { 0xA7BC, 0xA7BD }, + { 0xABB0, 0x13E0 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_028[] = { + { 0x021E, 0x021F }, + { 0x0418, 0x0438 }, + { 0x1E02, 0x1E03 }, + { 0xABB7, 0x13E7 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_029[] = { + { 0x011C, 0x011D }, + { 0x0419, 0x0439 }, + { 0x0518, 0x0519 }, + { 0xA7BA, 0xA7BB }, + { 0xABB6, 0x13E6 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_030[] = { + { 0x021C, 0x021D }, + { 0x041A, 0x043A }, + { 0x1E00, 0x1E01 }, + { 0xABB5, 0x13E5 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_031[] = { + { 0x011E, 0x011F }, + { 0x041B, 0x043B }, + { 0x051A, 0x051B }, + { 0xA7B8, 0xA7B9 }, + { 0xABB4, 0x13E4 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_032[] = { + { 0x0222, 0x0223 }, + { 0x0424, 0x0444 }, + { 0x1E3E, 0x1E3F }, + { 0x1F3F, 0x1F37 }, + { 0x2C0C, 0x2C3C }, + { 0xA686, 0xA687 }, + { 0xAB8B, 0x13BB } +}; + +static const CaseFoldMapping1_16 case_fold1_16_033[] = { + { 0x0120, 0x0121 }, + { 0x0425, 0x0445 }, + { 0x0524, 0x0525 }, + { 0x1F3E, 0x1F36 }, + { 0x2C0D, 0x2C3D }, + { 0xA786, 0xA787 }, + { 0xAB8A, 0x13BA } +}; + +static const CaseFoldMapping1_16 case_fold1_16_034[] = { + { 0x0220, 0x019E }, + { 0x0426, 0x0446 }, + { 0x1E3C, 0x1E3D }, + { 0x1F3D, 0x1F35 }, + { 0x2C0E, 0x2C3E }, + { 0xA684, 0xA685 }, + { 0xAB89, 0x13B9 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_035[] = { + { 0x0122, 0x0123 }, + { 0x0427, 0x0447 }, + { 0x0526, 0x0527 }, + { 0x1F3C, 0x1F34 }, + { 0x2C0F, 0x2C3F }, + { 0xA784, 0xA785 }, + { 0xAB88, 0x13B8 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_036[] = { + { 0x0226, 0x0227 }, + { 0x0420, 0x0440 }, + { 0x1E3A, 0x1E3B }, + { 0x1F3B, 0x1F33 }, + { 0x2C08, 0x2C38 }, + { 0xA682, 0xA683 }, + { 0xAB8F, 0x13BF } +}; + +static const CaseFoldMapping1_16 case_fold1_16_037[] = { + { 0x0124, 0x0125 }, + { 0x0421, 0x0441 }, + { 0x0520, 0x0521 }, + { 0x1F3A, 0x1F32 }, + { 0x2C09, 0x2C39 }, + { 0xA782, 0xA783 }, + { 0xAB8E, 0x13BE } +}; + +static const CaseFoldMapping1_16 case_fold1_16_038[] = { + { 0x0224, 0x0225 }, + { 0x0422, 0x0442 }, + { 0x1E38, 0x1E39 }, + { 0x1F39, 0x1F31 }, + { 0x2C0A, 0x2C3A }, + { 0xA680, 0xA681 }, + { 0xAB8D, 0x13BD } +}; + +static const CaseFoldMapping1_16 case_fold1_16_039[] = { + { 0x0126, 0x0127 }, + { 0x0423, 0x0443 }, + { 0x0522, 0x0523 }, + { 0x1F38, 0x1F30 }, + { 0x2C0B, 0x2C3B }, + { 0xA780, 0xA781 }, + { 0xAB8C, 0x13BC } +}; + +static const CaseFoldMapping1_16 case_fold1_16_040[] = { + { 0x022A, 0x022B }, + { 0x042C, 0x044C }, + { 0x1E36, 0x1E37 }, + { 0x2C04, 0x2C34 }, + { 0xA68E, 0xA68F }, + { 0xAB83, 0x13B3 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_041[] = { + { 0x0128, 0x0129 }, + { 0x042D, 0x044D }, + { 0x052C, 0x052D }, + { 0x2C05, 0x2C35 }, + { 0xAB82, 0x13B2 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_042[] = { + { 0x0228, 0x0229 }, + { 0x042E, 0x044E }, + { 0x1E34, 0x1E35 }, + { 0x2C06, 0x2C36 }, + { 0xA68C, 0xA68D }, + { 0xA78D, 0x0265 }, + { 0xAB81, 0x13B1 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_043[] = { + { 0x012A, 0x012B }, + { 0x042F, 0x044F }, + { 0x052E, 0x052F }, + { 0x2C07, 0x2C37 }, + { 0xAB80, 0x13B0 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_044[] = { + { 0x022E, 0x022F }, + { 0x0428, 0x0448 }, + { 0x1E32, 0x1E33 }, + { 0x2C00, 0x2C30 }, + { 0xA68A, 0xA68B }, + { 0xA78B, 0xA78C }, + { 0xAB87, 0x13B7 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_045[] = { + { 0x012C, 0x012D }, + { 0x0429, 0x0449 }, + { 0x0528, 0x0529 }, + { 0x2C01, 0x2C31 }, + { 0xAB86, 0x13B6 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_046[] = { + { 0x022C, 0x022D }, + { 0x042A, 0x044A }, + { 0x1E30, 0x1E31 }, + { 0x2C02, 0x2C32 }, + { 0xA688, 0xA689 }, + { 0xAB85, 0x13B5 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_047[] = { + { 0x012E, 0x012F }, + { 0x042B, 0x044B }, + { 0x052A, 0x052B }, + { 0x2C03, 0x2C33 }, + { 0xAB84, 0x13B4 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_048[] = { + { 0x0232, 0x0233 }, + { 0x0535, 0x0565 }, + { 0x1E2E, 0x1E2F }, + { 0x1F2F, 0x1F27 }, + { 0x2C1C, 0x2C4C }, + { 0xA696, 0xA697 }, + { 0xAB9B, 0x13CB } +}; + +static const CaseFoldMapping1_16 case_fold1_16_049[] = { + { 0x0534, 0x0564 }, + { 0x1F2E, 0x1F26 }, + { 0x2C1D, 0x2C4D }, + { 0xA796, 0xA797 }, + { 0xAB9A, 0x13CA } +}; + +static const CaseFoldMapping1_16 case_fold1_16_050[] = { + { 0x0230, 0x0231 }, + { 0x0537, 0x0567 }, + { 0x1E2C, 0x1E2D }, + { 0x1F2D, 0x1F25 }, + { 0x2C1E, 0x2C4E }, + { 0xA694, 0xA695 }, + { 0xAB99, 0x13C9 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_051[] = { + { 0x0132, 0x0133 }, + { 0x0536, 0x0566 }, + { 0x1F2C, 0x1F24 }, + { 0x2C1F, 0x2C4F }, + { 0xAB98, 0x13C8 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_052[] = { + { 0x0531, 0x0561 }, + { 0x1E2A, 0x1E2B }, + { 0x1F2B, 0x1F23 }, + { 0x2C18, 0x2C48 }, + { 0xA692, 0xA693 }, + { 0xAB9F, 0x13CF } +}; + +static const CaseFoldMapping1_16 case_fold1_16_053[] = { + { 0x0134, 0x0135 }, + { 0x1F2A, 0x1F22 }, + { 0x2C19, 0x2C49 }, + { 0xA792, 0xA793 }, + { 0xAB9E, 0x13CE } +}; + +static const CaseFoldMapping1_16 case_fold1_16_054[] = { + { 0x0533, 0x0563 }, + { 0x1E28, 0x1E29 }, + { 0x1F29, 0x1F21 }, + { 0x2C1A, 0x2C4A }, + { 0xA690, 0xA691 }, + { 0xAB9D, 0x13CD } +}; + +static const CaseFoldMapping1_16 case_fold1_16_055[] = { + { 0x0136, 0x0137 }, + { 0x0532, 0x0562 }, + { 0x1F28, 0x1F20 }, + { 0x2C1B, 0x2C4B }, + { 0xA790, 0xA791 }, + { 0xAB9C, 0x13CC } +}; + +static const CaseFoldMapping1_16 case_fold1_16_056[] = { + { 0x0139, 0x013A }, + { 0x023A, 0x2C65 }, + { 0x053D, 0x056D }, + { 0x1E26, 0x1E27 }, + { 0x2C14, 0x2C44 }, + { 0xAB93, 0x13C3 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_057[] = { + { 0x023B, 0x023C }, + { 0x053C, 0x056C }, + { 0x2C15, 0x2C45 }, + { 0xA79E, 0xA79F }, + { 0xAB92, 0x13C2 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_058[] = { + { 0x013B, 0x013C }, + { 0x053F, 0x056F }, + { 0x1E24, 0x1E25 }, + { 0x2C16, 0x2C46 }, + { 0xAB91, 0x13C1 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_059[] = { + { 0x053E, 0x056E }, + { 0x2C17, 0x2C47 }, + { 0xA79C, 0xA79D }, + { 0xAB90, 0x13C0 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_060[] = { + { 0x013D, 0x013E }, + { 0x023E, 0x2C66 }, + { 0x0539, 0x0569 }, + { 0x1E22, 0x1E23 }, + { 0x2C10, 0x2C40 }, + { 0xA69A, 0xA69B }, + { 0xAB97, 0x13C7 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_061[] = { + { 0x0538, 0x0568 }, + { 0x2C11, 0x2C41 }, + { 0xA79A, 0xA79B }, + { 0xAB96, 0x13C6 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_062[] = { + { 0x013F, 0x0140 }, + { 0x053B, 0x056B }, + { 0x1E20, 0x1E21 }, + { 0x2C12, 0x2C42 }, + { 0xA698, 0xA699 }, + { 0xAB95, 0x13C5 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_063[] = { + { 0x023D, 0x019A }, + { 0x053A, 0x056A }, + { 0x2C13, 0x2C43 }, + { 0xA798, 0xA799 }, + { 0xAB94, 0x13C4 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_064[] = { + { 0x0141, 0x0142 }, + { 0x0545, 0x0575 }, + { 0x1E5E, 0x1E5F }, + { 0x1F5F, 0x1F57 }, + { 0x2161, 0x2171 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_065[] = { + { 0x0243, 0x0180 }, + { 0x0544, 0x0574 }, + { 0x2160, 0x2170 }, + { 0x2C6D, 0x0251 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_066[] = { + { 0x0143, 0x0144 }, + { 0x0547, 0x0577 }, + { 0x1E5C, 0x1E5D }, + { 0x1F5D, 0x1F55 }, + { 0x2163, 0x2173 }, + { 0x2C6E, 0x0271 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_067[] = { + { 0x0241, 0x0242 }, + { 0x0546, 0x0576 }, + { 0x2162, 0x2172 }, + { 0x2C6F, 0x0250 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_068[] = { + { 0x0145, 0x0146 }, + { 0x0246, 0x0247 }, + { 0x0541, 0x0571 }, + { 0x1E5A, 0x1E5B }, + { 0x1F5B, 0x1F53 }, + { 0x2165, 0x2175 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_069[] = { + { 0x0540, 0x0570 }, + { 0x2164, 0x2174 }, + { 0x2C69, 0x2C6A } +}; + +static const CaseFoldMapping1_16 case_fold1_16_070[] = { + { 0x0147, 0x0148 }, + { 0x0244, 0x0289 }, + { 0x0345, 0x03B9 }, + { 0x0543, 0x0573 }, + { 0x1E58, 0x1E59 }, + { 0x1F59, 0x1F51 }, + { 0x2167, 0x2177 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_071[] = { + { 0x0245, 0x028C }, + { 0x0542, 0x0572 }, + { 0x2166, 0x2176 }, + { 0x2C6B, 0x2C6C } +}; + +static const CaseFoldMapping1_16 case_fold1_16_072[] = { + { 0x024A, 0x024B }, + { 0x054D, 0x057D }, + { 0x1E56, 0x1E57 }, + { 0x2169, 0x2179 }, + { 0x2C64, 0x027D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_073[] = { + { 0x054C, 0x057C }, + { 0x2168, 0x2178 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_074[] = { + { 0x0248, 0x0249 }, + { 0x054F, 0x057F }, + { 0x1E54, 0x1E55 }, + { 0x216B, 0x217B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_075[] = { + { 0x014A, 0x014B }, + { 0x054E, 0x057E }, + { 0x216A, 0x217A }, + { 0x2C67, 0x2C68 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_076[] = { + { 0x024E, 0x024F }, + { 0x0549, 0x0579 }, + { 0x1E52, 0x1E53 }, + { 0x216D, 0x217D }, + { 0x2C60, 0x2C61 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_077[] = { + { 0x014C, 0x014D }, + { 0x0548, 0x0578 }, + { 0x216C, 0x217C } +}; + +static const CaseFoldMapping1_16 case_fold1_16_078[] = { + { 0x024C, 0x024D }, + { 0x054B, 0x057B }, + { 0x1E50, 0x1E51 }, + { 0x216F, 0x217F }, + { 0x2C62, 0x026B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_079[] = { + { 0x014E, 0x014F }, + { 0x054A, 0x057A }, + { 0x216E, 0x217E }, + { 0x2C63, 0x1D7D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_080[] = { + { 0x0555, 0x0585 }, + { 0x1E4E, 0x1E4F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_081[] = { + { 0x0150, 0x0151 }, + { 0x0554, 0x0584 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_082[] = { + { 0x1E4C, 0x1E4D }, + { 0x1F4D, 0x1F45 }, + { 0x2C7E, 0x023F }, + { 0xA7F5, 0xA7F6 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_083[] = { + { 0x0152, 0x0153 }, + { 0x0556, 0x0586 }, + { 0x1F4C, 0x1F44 }, + { 0x2C7F, 0x0240 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_084[] = { + { 0x0551, 0x0581 }, + { 0x1E4A, 0x1E4B }, + { 0x1F4B, 0x1F43 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_085[] = { + { 0x0154, 0x0155 }, + { 0x0550, 0x0580 }, + { 0x1F4A, 0x1F42 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_086[] = { + { 0x0553, 0x0583 }, + { 0x1E48, 0x1E49 }, + { 0x1F49, 0x1F41 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_087[] = { + { 0x0156, 0x0157 }, + { 0x0552, 0x0582 }, + { 0x1F48, 0x1F40 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_088[] = { + { 0x1E46, 0x1E47 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_089[] = { + { 0x0158, 0x0159 }, + { 0x2C75, 0x2C76 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_090[] = { + { 0x1E44, 0x1E45 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_091[] = { + { 0x015A, 0x015B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_092[] = { + { 0x1E42, 0x1E43 }, + { 0x2C70, 0x0252 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_093[] = { + { 0x015C, 0x015D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_094[] = { + { 0x1E40, 0x1E41 }, + { 0x2C72, 0x2C73 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_095[] = { + { 0x015E, 0x015F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_096[] = { + { 0x0464, 0x0465 }, + { 0x1E7E, 0x1E7F }, + { 0xA7C7, 0xA7C8 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_097[] = { + { 0x0160, 0x0161 }, + { 0xA7C6, 0x1D8E } +}; + +static const CaseFoldMapping1_16 case_fold1_16_098[] = { + { 0x0466, 0x0467 }, + { 0x1E7C, 0x1E7D }, + { 0xA7C5, 0x0282 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_099[] = { + { 0x0162, 0x0163 }, + { 0xA7C4, 0xA794 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_100[] = { + { 0x0460, 0x0461 }, + { 0x1E7A, 0x1E7B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_101[] = { + { 0x0164, 0x0165 }, + { 0xA7C2, 0xA7C3 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_102[] = { + { 0x0462, 0x0463 }, + { 0x1E78, 0x1E79 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_103[] = { + { 0x0166, 0x0167 }, + { 0xA7C0, 0xA7C1 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_104[] = { + { 0x046C, 0x046D }, + { 0x1E76, 0x1E77 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_105[] = { + { 0x0168, 0x0169 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_106[] = { + { 0x046E, 0x046F }, + { 0x1E74, 0x1E75 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_107[] = { + { 0x016A, 0x016B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_108[] = { + { 0x0468, 0x0469 }, + { 0x1E72, 0x1E73 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_109[] = { + { 0x016C, 0x016D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_110[] = { + { 0x046A, 0x046B }, + { 0x1E70, 0x1E71 }, + { 0xA7C9, 0xA7CA } +}; + +static const CaseFoldMapping1_16 case_fold1_16_111[] = { + { 0x016E, 0x016F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_112[] = { + { 0x0474, 0x0475 }, + { 0x1E6E, 0x1E6F }, + { 0x1F6F, 0x1F67 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_113[] = { + { 0x0170, 0x0171 }, + { 0x0372, 0x0373 }, + { 0x1F6E, 0x1F66 }, + { 0xA7D6, 0xA7D7 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_114[] = { + { 0x0476, 0x0477 }, + { 0x1E6C, 0x1E6D }, + { 0x1F6D, 0x1F65 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_115[] = { + { 0x0172, 0x0173 }, + { 0x0370, 0x0371 }, + { 0x1F6C, 0x1F64 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_116[] = { + { 0x0470, 0x0471 }, + { 0x1E6A, 0x1E6B }, + { 0x1F6B, 0x1F63 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_117[] = { + { 0x0174, 0x0175 }, + { 0x0376, 0x0377 }, + { 0x1F6A, 0x1F62 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_118[] = { + { 0x0472, 0x0473 }, + { 0x1E68, 0x1E69 }, + { 0x1F69, 0x1F61 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_119[] = { + { 0x0176, 0x0177 }, + { 0x1F68, 0x1F60 }, + { 0xA7D0, 0xA7D1 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_120[] = { + { 0x0179, 0x017A }, + { 0x047C, 0x047D }, + { 0x1E66, 0x1E67 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_121[] = { + { 0x0178, 0x00FF } +}; + +static const CaseFoldMapping1_16 case_fold1_16_122[] = { + { 0x017B, 0x017C }, + { 0x047E, 0x047F }, + { 0x1E64, 0x1E65 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_124[] = { + { 0x017D, 0x017E }, + { 0x037F, 0x03F3 }, + { 0x0478, 0x0479 }, + { 0x1E62, 0x1E63 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_126[] = { + { 0x017F, 0x0073 }, + { 0x047A, 0x047B }, + { 0x1E60, 0x1E61 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_127[] = { + { 0xA7D8, 0xA7D9 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_128[] = { + { 0x0181, 0x0253 }, + { 0x1C9C, 0x10DC }, + { 0x2CAC, 0x2CAD } +}; + +static const CaseFoldMapping1_16 case_fold1_16_129[] = { + { 0x1C9D, 0x10DD }, + { 0xA726, 0xA727 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_130[] = { + { 0x1C9E, 0x10DE }, + { 0x2CAE, 0x2CAF } +}; + +static const CaseFoldMapping1_16 case_fold1_16_131[] = { + { 0x0182, 0x0183 }, + { 0x1C9F, 0x10DF }, + { 0xA724, 0xA725 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_132[] = { + { 0x0480, 0x0481 }, + { 0x1C98, 0x10D8 }, + { 0x2CA8, 0x2CA9 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_133[] = { + { 0x0184, 0x0185 }, + { 0x0386, 0x03AC }, + { 0x1C99, 0x10D9 }, + { 0x1E9B, 0x1E61 }, + { 0xA722, 0xA723 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_134[] = { + { 0x0187, 0x0188 }, + { 0x1C9A, 0x10DA }, + { 0x2CAA, 0x2CAB } +}; + +static const CaseFoldMapping1_16 case_fold1_16_135[] = { + { 0x0186, 0x0254 }, + { 0x1C9B, 0x10DB } +}; + +static const CaseFoldMapping1_16 case_fold1_16_136[] = { + { 0x0189, 0x0256 }, + { 0x048C, 0x048D }, + { 0x1C94, 0x10D4 }, + { 0x2CA4, 0x2CA5 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_137[] = { + { 0x038A, 0x03AF }, + { 0x1C95, 0x10D5 }, + { 0xA72E, 0xA72F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_138[] = { + { 0x018B, 0x018C }, + { 0x0389, 0x03AE }, + { 0x048E, 0x048F }, + { 0x1C96, 0x10D6 }, + { 0x1E94, 0x1E95 }, + { 0x2CA6, 0x2CA7 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_139[] = { + { 0x018A, 0x0257 }, + { 0x0388, 0x03AD }, + { 0x1C97, 0x10D7 }, + { 0xA72C, 0xA72D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_140[] = { + { 0x038F, 0x03CE }, + { 0x1C90, 0x10D0 }, + { 0x1E92, 0x1E93 }, + { 0x2CA0, 0x2CA1 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_141[] = { + { 0x038E, 0x03CD }, + { 0x1C91, 0x10D1 }, + { 0xA72A, 0xA72B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_142[] = { + { 0x018F, 0x0259 }, + { 0x048A, 0x048B }, + { 0x1C92, 0x10D2 }, + { 0x1E90, 0x1E91 }, + { 0x2CA2, 0x2CA3 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_143[] = { + { 0x018E, 0x01DD }, + { 0x038C, 0x03CC }, + { 0x1C93, 0x10D3 }, + { 0xA728, 0xA729 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_144[] = { + { 0x0191, 0x0192 }, + { 0x0393, 0x03B3 }, + { 0x0494, 0x0495 }, + { 0x1E8E, 0x1E8F }, + { 0x2CBC, 0x2CBD } +}; + +static const CaseFoldMapping1_16 case_fold1_16_145[] = { + { 0x0190, 0x025B }, + { 0x0392, 0x03B2 }, + { 0xA736, 0xA737 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_146[] = { + { 0x0193, 0x0260 }, + { 0x0391, 0x03B1 }, + { 0x0496, 0x0497 }, + { 0x1E8C, 0x1E8D }, + { 0x24B6, 0x24D0 }, + { 0x2CBE, 0x2CBF } +}; + +static const CaseFoldMapping1_16 case_fold1_16_147[] = { + { 0x24B7, 0x24D1 }, + { 0xA734, 0xA735 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_148[] = { + { 0x0397, 0x03B7 }, + { 0x0490, 0x0491 }, + { 0x1C88, 0xA64B }, + { 0x1E8A, 0x1E8B }, + { 0x2CB8, 0x2CB9 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_149[] = { + { 0x0194, 0x0263 }, + { 0x0396, 0x03B6 }, + { 0xA732, 0xA733 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_150[] = { + { 0x0197, 0x0268 }, + { 0x0395, 0x03B5 }, + { 0x0492, 0x0493 }, + { 0x1E88, 0x1E89 }, + { 0x2CBA, 0x2CBB } +}; + +static const CaseFoldMapping1_16 case_fold1_16_151[] = { + { 0x0196, 0x0269 }, + { 0x0394, 0x03B4 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_152[] = { + { 0x039B, 0x03BB }, + { 0x049C, 0x049D }, + { 0x1C84, 0x0442 }, + { 0x1E86, 0x1E87 }, + { 0x24BC, 0x24D6 }, + { 0x2CB4, 0x2CB5 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_153[] = { + { 0x0198, 0x0199 }, + { 0x039A, 0x03BA }, + { 0x1C85, 0x0442 }, + { 0x24BD, 0x24D7 }, + { 0xA73E, 0xA73F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_154[] = { + { 0x0399, 0x03B9 }, + { 0x049E, 0x049F }, + { 0x1C86, 0x044A }, + { 0x1E84, 0x1E85 }, + { 0x24BE, 0x24D8 }, + { 0x2CB6, 0x2CB7 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_155[] = { + { 0x0398, 0x03B8 }, + { 0x1C87, 0x0463 }, + { 0x24BF, 0x24D9 }, + { 0xA73C, 0xA73D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_156[] = { + { 0x019D, 0x0272 }, + { 0x039F, 0x03BF }, + { 0x0498, 0x0499 }, + { 0x1C80, 0x0432 }, + { 0x1E82, 0x1E83 }, + { 0x24B8, 0x24D2 }, + { 0x2CB0, 0x2CB1 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_157[] = { + { 0x019C, 0x026F }, + { 0x039E, 0x03BE }, + { 0x1C81, 0x0434 }, + { 0x24B9, 0x24D3 }, + { 0xA73A, 0xA73B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_158[] = { + { 0x019F, 0x0275 }, + { 0x039D, 0x03BD }, + { 0x049A, 0x049B }, + { 0x1C82, 0x043E }, + { 0x1E80, 0x1E81 }, + { 0x24BA, 0x24D4 }, + { 0x2CB2, 0x2CB3 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_159[] = { + { 0x039C, 0x03BC }, + { 0x1C83, 0x0441 }, + { 0x24BB, 0x24D5 }, + { 0xA738, 0xA739 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_160[] = { + { 0x03A3, 0x03C3 }, + { 0x04A4, 0x04A5 }, + { 0x10B0, 0x2D10 }, + { 0x1EBE, 0x1EBF }, + { 0x2C8C, 0x2C8D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_161[] = { + { 0x01A0, 0x01A1 }, + { 0x10B1, 0x2D11 }, + { 0x1CBD, 0x10FD }, + { 0x1FBE, 0x03B9 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_162[] = { + { 0x03A1, 0x03C1 }, + { 0x04A6, 0x04A7 }, + { 0x10B2, 0x2D12 }, + { 0x1CBE, 0x10FE }, + { 0x1EBC, 0x1EBD }, + { 0x2183, 0x2184 }, + { 0x2C8E, 0x2C8F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_163[] = { + { 0x01A2, 0x01A3 }, + { 0x03A0, 0x03C0 }, + { 0x10B3, 0x2D13 }, + { 0x1CBF, 0x10FF } +}; + +static const CaseFoldMapping1_16 case_fold1_16_164[] = { + { 0x03A7, 0x03C7 }, + { 0x04A0, 0x04A1 }, + { 0x10B4, 0x2D14 }, + { 0x1CB8, 0x10F8 }, + { 0x1EBA, 0x1EBB }, + { 0x1FBB, 0x1F71 }, + { 0x2C88, 0x2C89 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_165[] = { + { 0x01A4, 0x01A5 }, + { 0x03A6, 0x03C6 }, + { 0x10B5, 0x2D15 }, + { 0x1CB9, 0x10F9 }, + { 0x1FBA, 0x1F70 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_166[] = { + { 0x01A7, 0x01A8 }, + { 0x03A5, 0x03C5 }, + { 0x04A2, 0x04A3 }, + { 0x10B6, 0x2D16 }, + { 0x1CBA, 0x10FA }, + { 0x1EB8, 0x1EB9 }, + { 0x1FB9, 0x1FB1 }, + { 0x2C8A, 0x2C8B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_167[] = { + { 0x01A6, 0x0280 }, + { 0x03A4, 0x03C4 }, + { 0x10B7, 0x2D17 }, + { 0x1FB8, 0x1FB0 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_168[] = { + { 0x01A9, 0x0283 }, + { 0x03AB, 0x03CB }, + { 0x04AC, 0x04AD }, + { 0x10B8, 0x2D18 }, + { 0x1CB4, 0x10F4 }, + { 0x1EB6, 0x1EB7 }, + { 0x2C84, 0x2C85 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_169[] = { + { 0x03AA, 0x03CA }, + { 0x10B9, 0x2D19 }, + { 0x1CB5, 0x10F5 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_170[] = { + { 0x03A9, 0x03C9 }, + { 0x04AE, 0x04AF }, + { 0x10BA, 0x2D1A }, + { 0x1CB6, 0x10F6 }, + { 0x1EB4, 0x1EB5 }, + { 0x2C86, 0x2C87 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_171[] = { + { 0x03A8, 0x03C8 }, + { 0x10BB, 0x2D1B }, + { 0x1CB7, 0x10F7 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_172[] = { + { 0x04A8, 0x04A9 }, + { 0x10BC, 0x2D1C }, + { 0x1CB0, 0x10F0 }, + { 0x1EB2, 0x1EB3 }, + { 0x2C80, 0x2C81 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_173[] = { + { 0x01AC, 0x01AD }, + { 0x10BD, 0x2D1D }, + { 0x1CB1, 0x10F1 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_174[] = { + { 0x01AF, 0x01B0 }, + { 0x04AA, 0x04AB }, + { 0x10BE, 0x2D1E }, + { 0x1CB2, 0x10F2 }, + { 0x1EB0, 0x1EB1 }, + { 0x2C82, 0x2C83 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_175[] = { + { 0x01AE, 0x0288 }, + { 0x10BF, 0x2D1F }, + { 0x1CB3, 0x10F3 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_176[] = { + { 0x01B1, 0x028A }, + { 0x04B4, 0x04B5 }, + { 0x10A0, 0x2D00 }, + { 0x1CAC, 0x10EC }, + { 0x1EAE, 0x1EAF }, + { 0x2C9C, 0x2C9D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_177[] = { + { 0x10A1, 0x2D01 }, + { 0x1CAD, 0x10ED } +}; + +static const CaseFoldMapping1_16 case_fold1_16_178[] = { + { 0x01B3, 0x01B4 }, + { 0x04B6, 0x04B7 }, + { 0x10A2, 0x2D02 }, + { 0x1CAE, 0x10EE }, + { 0x1EAC, 0x1EAD }, + { 0x2C9E, 0x2C9F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_179[] = { + { 0x01B2, 0x028B }, + { 0x10A3, 0x2D03 }, + { 0x1CAF, 0x10EF } +}; + +static const CaseFoldMapping1_16 case_fold1_16_180[] = { + { 0x01B5, 0x01B6 }, + { 0x04B0, 0x04B1 }, + { 0x10A4, 0x2D04 }, + { 0x1CA8, 0x10E8 }, + { 0x1EAA, 0x1EAB }, + { 0x2C98, 0x2C99 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_181[] = { + { 0x00B5, 0x03BC }, + { 0x10A5, 0x2D05 }, + { 0x1CA9, 0x10E9 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_182[] = { + { 0x01B7, 0x0292 }, + { 0x04B2, 0x04B3 }, + { 0x10A6, 0x2D06 }, + { 0x1CAA, 0x10EA }, + { 0x1EA8, 0x1EA9 }, + { 0x2C9A, 0x2C9B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_183[] = { + { 0x10A7, 0x2D07 }, + { 0x1CAB, 0x10EB } +}; + +static const CaseFoldMapping1_16 case_fold1_16_184[] = { + { 0x04BC, 0x04BD }, + { 0x10A8, 0x2D08 }, + { 0x1CA4, 0x10E4 }, + { 0x1EA6, 0x1EA7 }, + { 0x2C94, 0x2C95 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_185[] = { + { 0x01B8, 0x01B9 }, + { 0x10A9, 0x2D09 }, + { 0x1CA5, 0x10E5 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_186[] = { + { 0x04BE, 0x04BF }, + { 0x10AA, 0x2D0A }, + { 0x1CA6, 0x10E6 }, + { 0x1EA4, 0x1EA5 }, + { 0x2C96, 0x2C97 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_187[] = { + { 0x10AB, 0x2D0B }, + { 0x1CA7, 0x10E7 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_188[] = { + { 0x04B8, 0x04B9 }, + { 0x10AC, 0x2D0C }, + { 0x1CA0, 0x10E0 }, + { 0x1EA2, 0x1EA3 }, + { 0x2C90, 0x2C91 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_189[] = { + { 0x01BC, 0x01BD }, + { 0x10AD, 0x2D0D }, + { 0x1CA1, 0x10E1 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_190[] = { + { 0x04BA, 0x04BB }, + { 0x10AE, 0x2D0E }, + { 0x1CA2, 0x10E2 }, + { 0x1EA0, 0x1EA1 }, + { 0x2C92, 0x2C93 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_191[] = { + { 0x10AF, 0x2D0F }, + { 0x1CA3, 0x10E3 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_192[] = { + { 0x00C0, 0x00E0 }, + { 0x1EDE, 0x1EDF }, + { 0xA666, 0xA667 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_193[] = { + { 0x00C1, 0x00E1 }, + { 0x03C2, 0x03C3 }, + { 0x04C5, 0x04C6 }, + { 0x2CED, 0x2CEE }, + { 0xA766, 0xA767 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_194[] = { + { 0x00C2, 0x00E2 }, + { 0x1EDC, 0x1EDD }, + { 0xA664, 0xA665 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_195[] = { + { 0x00C3, 0x00E3 }, + { 0x04C7, 0x04C8 }, + { 0xA764, 0xA765 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_196[] = { + { 0x00C4, 0x00E4 }, + { 0x01C5, 0x01C6 }, + { 0x04C0, 0x04CF }, + { 0x1EDA, 0x1EDB }, + { 0x1FDB, 0x1F77 }, + { 0xA662, 0xA663 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_197[] = { + { 0x00C5, 0x00E5 }, + { 0x01C4, 0x01C6 }, + { 0x04C1, 0x04C2 }, + { 0x1FDA, 0x1F76 }, + { 0xA762, 0xA763 }, + { 0xFF3A, 0xFF5A } +}; + +static const CaseFoldMapping1_16 case_fold1_16_198[] = { + { 0x00C6, 0x00E6 }, + { 0x01C7, 0x01C9 }, + { 0x1ED8, 0x1ED9 }, + { 0x1FD9, 0x1FD1 }, + { 0xA660, 0xA661 }, + { 0xFF39, 0xFF59 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_199[] = { + { 0x00C7, 0x00E7 }, + { 0x04C3, 0x04C4 }, + { 0x1FD8, 0x1FD0 }, + { 0x2CEB, 0x2CEC }, + { 0xA760, 0xA761 }, + { 0xFF38, 0xFF58 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_200[] = { + { 0x00C8, 0x00E8 }, + { 0x1ED6, 0x1ED7 }, + { 0xFF37, 0xFF57 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_201[] = { + { 0x00C9, 0x00E9 }, + { 0x01C8, 0x01C9 }, + { 0x04CD, 0x04CE }, + { 0xA76E, 0xA76F }, + { 0xFF36, 0xFF56 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_202[] = { + { 0x00CA, 0x00EA }, + { 0x01CB, 0x01CC }, + { 0x1ED4, 0x1ED5 }, + { 0xA66C, 0xA66D }, + { 0xFF35, 0xFF55 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_203[] = { + { 0x00CB, 0x00EB }, + { 0x01CA, 0x01CC }, + { 0xA76C, 0xA76D }, + { 0xFF34, 0xFF54 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_204[] = { + { 0x00CC, 0x00EC }, + { 0x01CD, 0x01CE }, + { 0x03CF, 0x03D7 }, + { 0x1ED2, 0x1ED3 }, + { 0x2CE0, 0x2CE1 }, + { 0xA66A, 0xA66B }, + { 0xFF33, 0xFF53 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_205[] = { + { 0x00CD, 0x00ED }, + { 0x04C9, 0x04CA }, + { 0xA76A, 0xA76B }, + { 0xFF32, 0xFF52 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_206[] = { + { 0x00CE, 0x00EE }, + { 0x01CF, 0x01D0 }, + { 0x1ED0, 0x1ED1 }, + { 0x2CE2, 0x2CE3 }, + { 0xA668, 0xA669 }, + { 0xFF31, 0xFF51 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_207[] = { + { 0x00CF, 0x00EF }, + { 0x04CB, 0x04CC }, + { 0xA768, 0xA769 }, + { 0xFF30, 0xFF50 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_208[] = { + { 0x00D0, 0x00F0 }, + { 0x01D1, 0x01D2 }, + { 0x04D4, 0x04D5 }, + { 0x10C0, 0x2D20 }, + { 0x1ECE, 0x1ECF }, + { 0xAB7B, 0x13AB }, + { 0xFF2F, 0xFF4F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_209[] = { + { 0x00D1, 0x00F1 }, + { 0x10C1, 0x2D21 }, + { 0xAB7A, 0x13AA }, + { 0xFF2E, 0xFF4E } +}; + +static const CaseFoldMapping1_16 case_fold1_16_210[] = { + { 0x00D2, 0x00F2 }, + { 0x01D3, 0x01D4 }, + { 0x03D1, 0x03B8 }, + { 0x04D6, 0x04D7 }, + { 0x10C2, 0x2D22 }, + { 0x1ECC, 0x1ECD }, + { 0xAB79, 0x13A9 }, + { 0xFF2D, 0xFF4D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_211[] = { + { 0x00D3, 0x00F3 }, + { 0x03D0, 0x03B2 }, + { 0x10C3, 0x2D23 }, + { 0xAB78, 0x13A8 }, + { 0xFF2C, 0xFF4C } +}; + +static const CaseFoldMapping1_16 case_fold1_16_212[] = { + { 0x00D4, 0x00F4 }, + { 0x01D5, 0x01D6 }, + { 0x04D0, 0x04D1 }, + { 0x10C4, 0x2D24 }, + { 0x1ECA, 0x1ECB }, + { 0x1FCB, 0x1F75 }, + { 0xAB7F, 0x13AF }, + { 0xFF2B, 0xFF4B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_213[] = { + { 0x00D5, 0x00F5 }, + { 0x03D6, 0x03C0 }, + { 0x10C5, 0x2D25 }, + { 0x1FCA, 0x1F74 }, + { 0xAB7E, 0x13AE }, + { 0xFF2A, 0xFF4A } +}; + +static const CaseFoldMapping1_16 case_fold1_16_214[] = { + { 0x00D6, 0x00F6 }, + { 0x01D7, 0x01D8 }, + { 0x03D5, 0x03C6 }, + { 0x04D2, 0x04D3 }, + { 0x1EC8, 0x1EC9 }, + { 0x1FC9, 0x1F73 }, + { 0xAB7D, 0x13AD }, + { 0xFF29, 0xFF49 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_215[] = { + { 0x10C7, 0x2D27 }, + { 0x1FC8, 0x1F72 }, + { 0xAB7C, 0x13AC }, + { 0xFF28, 0xFF48 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_216[] = { + { 0x00D8, 0x00F8 }, + { 0x01D9, 0x01DA }, + { 0x04DC, 0x04DD }, + { 0x1EC6, 0x1EC7 }, + { 0xAB73, 0x13A3 }, + { 0xFF27, 0xFF47 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_217[] = { + { 0x00D9, 0x00F9 }, + { 0x03DA, 0x03DB }, + { 0xA77E, 0xA77F }, + { 0xAB72, 0x13A2 }, + { 0xFF26, 0xFF46 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_218[] = { + { 0x00DA, 0x00FA }, + { 0x01DB, 0x01DC }, + { 0x04DE, 0x04DF }, + { 0x1EC4, 0x1EC5 }, + { 0xA77D, 0x1D79 }, + { 0xAB71, 0x13A1 }, + { 0xFF25, 0xFF45 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_219[] = { + { 0x00DB, 0x00FB }, + { 0x03D8, 0x03D9 }, + { 0xAB70, 0x13A0 }, + { 0xFF24, 0xFF44 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_220[] = { + { 0x00DC, 0x00FC }, + { 0x04D8, 0x04D9 }, + { 0x1EC2, 0x1EC3 }, + { 0xA77B, 0xA77C }, + { 0xAB77, 0x13A7 }, + { 0xFF23, 0xFF43 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_221[] = { + { 0x00DD, 0x00FD }, + { 0x03DE, 0x03DF }, + { 0x10CD, 0x2D2D }, + { 0xAB76, 0x13A6 }, + { 0xFF22, 0xFF42 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_222[] = { + { 0x00DE, 0x00FE }, + { 0x04DA, 0x04DB }, + { 0x1EC0, 0x1EC1 }, + { 0x2CF2, 0x2CF3 }, + { 0xA779, 0xA77A }, + { 0xAB75, 0x13A5 }, + { 0xFF21, 0xFF41 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_223[] = { + { 0x01DE, 0x01DF }, + { 0x03DC, 0x03DD }, + { 0xAB74, 0x13A4 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_224[] = { + { 0x04E4, 0x04E5 }, + { 0x1EFE, 0x1EFF }, + { 0x24C4, 0x24DE }, + { 0x2CCC, 0x2CCD }, + { 0xA646, 0xA647 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_225[] = { + { 0x01E0, 0x01E1 }, + { 0x03E2, 0x03E3 }, + { 0x24C5, 0x24DF }, + { 0xA746, 0xA747 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_226[] = { + { 0x04E6, 0x04E7 }, + { 0x1EFC, 0x1EFD }, + { 0x24C6, 0x24E0 }, + { 0x2CCE, 0x2CCF }, + { 0xA644, 0xA645 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_227[] = { + { 0x01E2, 0x01E3 }, + { 0x03E0, 0x03E1 }, + { 0x24C7, 0x24E1 }, + { 0xA744, 0xA745 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_228[] = { + { 0x04E0, 0x04E1 }, + { 0x1EFA, 0x1EFB }, + { 0x1FFB, 0x1F7D }, + { 0x24C0, 0x24DA }, + { 0x2CC8, 0x2CC9 }, + { 0xA642, 0xA643 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_229[] = { + { 0x01E4, 0x01E5 }, + { 0x03E6, 0x03E7 }, + { 0x1FFA, 0x1F7C }, + { 0x24C1, 0x24DB }, + { 0xA742, 0xA743 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_230[] = { + { 0x04E2, 0x04E3 }, + { 0x1EF8, 0x1EF9 }, + { 0x1FF9, 0x1F79 }, + { 0x24C2, 0x24DC }, + { 0x2CCA, 0x2CCB }, + { 0xA640, 0xA641 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_231[] = { + { 0x01E6, 0x01E7 }, + { 0x03E4, 0x03E5 }, + { 0x1FF8, 0x1F78 }, + { 0x24C3, 0x24DD }, + { 0xA740, 0xA741 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_232[] = { + { 0x04EC, 0x04ED }, + { 0x13FB, 0x13F3 }, + { 0x1EF6, 0x1EF7 }, + { 0x24CC, 0x24E6 }, + { 0x2CC4, 0x2CC5 }, + { 0xA64E, 0xA64F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_233[] = { + { 0x01E8, 0x01E9 }, + { 0x03EA, 0x03EB }, + { 0x13FA, 0x13F2 }, + { 0x24CD, 0x24E7 }, + { 0xA74E, 0xA74F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_234[] = { + { 0x04EE, 0x04EF }, + { 0x13F9, 0x13F1 }, + { 0x1EF4, 0x1EF5 }, + { 0x24CE, 0x24E8 }, + { 0x2CC6, 0x2CC7 }, + { 0xA64C, 0xA64D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_235[] = { + { 0x01EA, 0x01EB }, + { 0x03E8, 0x03E9 }, + { 0x13F8, 0x13F0 }, + { 0x24CF, 0x24E9 }, + { 0xA74C, 0xA74D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_236[] = { + { 0x04E8, 0x04E9 }, + { 0x1EF2, 0x1EF3 }, + { 0x24C8, 0x24E2 }, + { 0x2CC0, 0x2CC1 }, + { 0xA64A, 0xA64B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_237[] = { + { 0x01EC, 0x01ED }, + { 0x03EE, 0x03EF }, + { 0x24C9, 0x24E3 }, + { 0xA74A, 0xA74B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_238[] = { + { 0x04EA, 0x04EB }, + { 0x13FD, 0x13F5 }, + { 0x1EF0, 0x1EF1 }, + { 0x24CA, 0x24E4 }, + { 0x2CC2, 0x2CC3 }, + { 0xA648, 0xA649 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_239[] = { + { 0x01EE, 0x01EF }, + { 0x03EC, 0x03ED }, + { 0x13FC, 0x13F4 }, + { 0x24CB, 0x24E5 }, + { 0xA748, 0xA749 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_240[] = { + { 0x01F1, 0x01F3 }, + { 0x04F4, 0x04F5 }, + { 0x1EEE, 0x1EEF }, + { 0x2CDC, 0x2CDD }, + { 0xA656, 0xA657 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_241[] = { + { 0xA756, 0xA757 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_242[] = { + { 0x03F1, 0x03C1 }, + { 0x04F6, 0x04F7 }, + { 0x1EEC, 0x1EED }, + { 0x2CDE, 0x2CDF }, + { 0xA654, 0xA655 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_243[] = { + { 0x01F2, 0x01F3 }, + { 0x03F0, 0x03BA }, + { 0x1FEC, 0x1FE5 }, + { 0xA754, 0xA755 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_244[] = { + { 0x03F7, 0x03F8 }, + { 0x04F0, 0x04F1 }, + { 0x1EEA, 0x1EEB }, + { 0x1FEB, 0x1F7B }, + { 0x2CD8, 0x2CD9 }, + { 0xA652, 0xA653 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_245[] = { + { 0x01F4, 0x01F5 }, + { 0x1FEA, 0x1F7A }, + { 0xA752, 0xA753 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_246[] = { + { 0x01F7, 0x01BF }, + { 0x03F5, 0x03B5 }, + { 0x04F2, 0x04F3 }, + { 0x1EE8, 0x1EE9 }, + { 0x1FE9, 0x1FE1 }, + { 0x2CDA, 0x2CDB }, + { 0xA650, 0xA651 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_247[] = { + { 0x01F6, 0x0195 }, + { 0x03F4, 0x03B8 }, + { 0x1FE8, 0x1FE0 }, + { 0xA750, 0xA751 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_248[] = { + { 0x04FC, 0x04FD }, + { 0x1EE6, 0x1EE7 }, + { 0x2CD4, 0x2CD5 }, + { 0xA65E, 0xA65F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_249[] = { + { 0x01F8, 0x01F9 }, + { 0x03FA, 0x03FB }, + { 0xA75E, 0xA75F } +}; + +static const CaseFoldMapping1_16 case_fold1_16_250[] = { + { 0x03F9, 0x03F2 }, + { 0x04FE, 0x04FF }, + { 0x1EE4, 0x1EE5 }, + { 0x2CD6, 0x2CD7 }, + { 0xA65C, 0xA65D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_251[] = { + { 0x01FA, 0x01FB }, + { 0xA75C, 0xA75D } +}; + +static const CaseFoldMapping1_16 case_fold1_16_252[] = { + { 0x03FF, 0x037D }, + { 0x04F8, 0x04F9 }, + { 0x1EE2, 0x1EE3 }, + { 0x2CD0, 0x2CD1 }, + { 0xA65A, 0xA65B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_253[] = { + { 0x01FC, 0x01FD }, + { 0x03FE, 0x037C }, + { 0xA75A, 0xA75B } +}; + +static const CaseFoldMapping1_16 case_fold1_16_254[] = { + { 0x03FD, 0x037B }, + { 0x04FA, 0x04FB }, + { 0x1EE0, 0x1EE1 }, + { 0x2CD2, 0x2CD3 }, + { 0xA658, 0xA659 } +}; + +static const CaseFoldMapping1_16 case_fold1_16_255[] = { + { 0x01FE, 0x01FF }, + { 0xA758, 0xA759 } +}; + +static const CaseFoldMapping1_32 case_fold1_32_000[] = { + { 0x10404, 0x1042C }, + { 0x10414, 0x1043C }, + { 0x10424, 0x1044C }, + { 0x104B4, 0x104DC }, + { 0x104C4, 0x104EC }, + { 0x10575, 0x1059C }, + { 0x10585, 0x105AC }, + { 0x10595, 0x105BC }, + { 0x10C8C, 0x10CCC }, + { 0x10C9C, 0x10CDC }, + { 0x10CAC, 0x10CEC }, + { 0x118A8, 0x118C8 }, + { 0x118B8, 0x118D8 }, + { 0x16E4E, 0x16E6E }, + { 0x16E5E, 0x16E7E }, + { 0x1E909, 0x1E92B }, + { 0x1E919, 0x1E93B } +}; + +static const CaseFoldMapping1_32 case_fold1_32_001[] = { + { 0x10405, 0x1042D }, + { 0x10415, 0x1043D }, + { 0x10425, 0x1044D }, + { 0x104B5, 0x104DD }, + { 0x104C5, 0x104ED }, + { 0x10574, 0x1059B }, + { 0x10584, 0x105AB }, + { 0x10594, 0x105BB }, + { 0x10C8D, 0x10CCD }, + { 0x10C9D, 0x10CDD }, + { 0x10CAD, 0x10CED }, + { 0x118A9, 0x118C9 }, + { 0x118B9, 0x118D9 }, + { 0x16E4F, 0x16E6F }, + { 0x16E5F, 0x16E7F }, + { 0x1E908, 0x1E92A }, + { 0x1E918, 0x1E93A } +}; + +static const CaseFoldMapping1_32 case_fold1_32_002[] = { + { 0x10406, 0x1042E }, + { 0x10416, 0x1043E }, + { 0x10426, 0x1044E }, + { 0x104B6, 0x104DE }, + { 0x104C6, 0x104EE }, + { 0x10577, 0x1059E }, + { 0x10587, 0x105AE }, + { 0x10C8E, 0x10CCE }, + { 0x10C9E, 0x10CDE }, + { 0x10CAE, 0x10CEE }, + { 0x118AA, 0x118CA }, + { 0x118BA, 0x118DA }, + { 0x16E4C, 0x16E6C }, + { 0x16E5C, 0x16E7C }, + { 0x1E90B, 0x1E92D }, + { 0x1E91B, 0x1E93D } +}; + +static const CaseFoldMapping1_32 case_fold1_32_003[] = { + { 0x10407, 0x1042F }, + { 0x10417, 0x1043F }, + { 0x10427, 0x1044F }, + { 0x104B7, 0x104DF }, + { 0x104C7, 0x104EF }, + { 0x10576, 0x1059D }, + { 0x10586, 0x105AD }, + { 0x10C8F, 0x10CCF }, + { 0x10C9F, 0x10CDF }, + { 0x10CAF, 0x10CEF }, + { 0x118AB, 0x118CB }, + { 0x118BB, 0x118DB }, + { 0x16E4D, 0x16E6D }, + { 0x16E5D, 0x16E7D }, + { 0x1E90A, 0x1E92C }, + { 0x1E91A, 0x1E93C } +}; + +static const CaseFoldMapping1_32 case_fold1_32_004[] = { + { 0x10400, 0x10428 }, + { 0x10410, 0x10438 }, + { 0x10420, 0x10448 }, + { 0x104B0, 0x104D8 }, + { 0x104C0, 0x104E8 }, + { 0x104D0, 0x104F8 }, + { 0x10571, 0x10598 }, + { 0x10581, 0x105A8 }, + { 0x10591, 0x105B8 }, + { 0x10C88, 0x10CC8 }, + { 0x10C98, 0x10CD8 }, + { 0x10CA8, 0x10CE8 }, + { 0x118AC, 0x118CC }, + { 0x118BC, 0x118DC }, + { 0x16E4A, 0x16E6A }, + { 0x16E5A, 0x16E7A }, + { 0x1E90D, 0x1E92F }, + { 0x1E91D, 0x1E93F } +}; + +static const CaseFoldMapping1_32 case_fold1_32_005[] = { + { 0x10401, 0x10429 }, + { 0x10411, 0x10439 }, + { 0x10421, 0x10449 }, + { 0x104B1, 0x104D9 }, + { 0x104C1, 0x104E9 }, + { 0x104D1, 0x104F9 }, + { 0x10570, 0x10597 }, + { 0x10580, 0x105A7 }, + { 0x10590, 0x105B7 }, + { 0x10C89, 0x10CC9 }, + { 0x10C99, 0x10CD9 }, + { 0x10CA9, 0x10CE9 }, + { 0x118AD, 0x118CD }, + { 0x118BD, 0x118DD }, + { 0x16E4B, 0x16E6B }, + { 0x16E5B, 0x16E7B }, + { 0x1E90C, 0x1E92E }, + { 0x1E91C, 0x1E93E } +}; + +static const CaseFoldMapping1_32 case_fold1_32_006[] = { + { 0x10402, 0x1042A }, + { 0x10412, 0x1043A }, + { 0x10422, 0x1044A }, + { 0x104B2, 0x104DA }, + { 0x104C2, 0x104EA }, + { 0x104D2, 0x104FA }, + { 0x10573, 0x1059A }, + { 0x10583, 0x105AA }, + { 0x10C8A, 0x10CCA }, + { 0x10C9A, 0x10CDA }, + { 0x10CAA, 0x10CEA }, + { 0x118AE, 0x118CE }, + { 0x118BE, 0x118DE }, + { 0x16E48, 0x16E68 }, + { 0x16E58, 0x16E78 }, + { 0x1E90F, 0x1E931 }, + { 0x1E91F, 0x1E941 } +}; + +static const CaseFoldMapping1_32 case_fold1_32_007[] = { + { 0x10403, 0x1042B }, + { 0x10413, 0x1043B }, + { 0x10423, 0x1044B }, + { 0x104B3, 0x104DB }, + { 0x104C3, 0x104EB }, + { 0x104D3, 0x104FB }, + { 0x10572, 0x10599 }, + { 0x10582, 0x105A9 }, + { 0x10592, 0x105B9 }, + { 0x10C8B, 0x10CCB }, + { 0x10C9B, 0x10CDB }, + { 0x10CAB, 0x10CEB }, + { 0x118AF, 0x118CF }, + { 0x118BF, 0x118DF }, + { 0x16E49, 0x16E69 }, + { 0x16E59, 0x16E79 }, + { 0x1E90E, 0x1E930 }, + { 0x1E91E, 0x1E940 } +}; + +static const CaseFoldMapping1_32 case_fold1_32_008[] = { + { 0x1040C, 0x10434 }, + { 0x1041C, 0x10444 }, + { 0x104BC, 0x104E4 }, + { 0x104CC, 0x104F4 }, + { 0x1057D, 0x105A4 }, + { 0x1058D, 0x105B4 }, + { 0x10C84, 0x10CC4 }, + { 0x10C94, 0x10CD4 }, + { 0x10CA4, 0x10CE4 }, + { 0x118A0, 0x118C0 }, + { 0x118B0, 0x118D0 }, + { 0x16E46, 0x16E66 }, + { 0x16E56, 0x16E76 }, + { 0x1E901, 0x1E923 }, + { 0x1E911, 0x1E933 }, + { 0x1E921, 0x1E943 } +}; + +static const CaseFoldMapping1_32 case_fold1_32_009[] = { + { 0x1040D, 0x10435 }, + { 0x1041D, 0x10445 }, + { 0x104BD, 0x104E5 }, + { 0x104CD, 0x104F5 }, + { 0x1057C, 0x105A3 }, + { 0x1058C, 0x105B3 }, + { 0x10C85, 0x10CC5 }, + { 0x10C95, 0x10CD5 }, + { 0x10CA5, 0x10CE5 }, + { 0x118A1, 0x118C1 }, + { 0x118B1, 0x118D1 }, + { 0x16E47, 0x16E67 }, + { 0x16E57, 0x16E77 }, + { 0x1E900, 0x1E922 }, + { 0x1E910, 0x1E932 }, + { 0x1E920, 0x1E942 } +}; + +static const CaseFoldMapping1_32 case_fold1_32_010[] = { + { 0x1040E, 0x10436 }, + { 0x1041E, 0x10446 }, + { 0x104BE, 0x104E6 }, + { 0x104CE, 0x104F6 }, + { 0x1057F, 0x105A6 }, + { 0x1058F, 0x105B6 }, + { 0x10C86, 0x10CC6 }, + { 0x10C96, 0x10CD6 }, + { 0x10CA6, 0x10CE6 }, + { 0x118A2, 0x118C2 }, + { 0x118B2, 0x118D2 }, + { 0x16E44, 0x16E64 }, + { 0x16E54, 0x16E74 }, + { 0x1E903, 0x1E925 }, + { 0x1E913, 0x1E935 } +}; + +static const CaseFoldMapping1_32 case_fold1_32_011[] = { + { 0x1040F, 0x10437 }, + { 0x1041F, 0x10447 }, + { 0x104BF, 0x104E7 }, + { 0x104CF, 0x104F7 }, + { 0x1057E, 0x105A5 }, + { 0x1058E, 0x105B5 }, + { 0x10C87, 0x10CC7 }, + { 0x10C97, 0x10CD7 }, + { 0x10CA7, 0x10CE7 }, + { 0x118A3, 0x118C3 }, + { 0x118B3, 0x118D3 }, + { 0x16E45, 0x16E65 }, + { 0x16E55, 0x16E75 }, + { 0x1E902, 0x1E924 }, + { 0x1E912, 0x1E934 } +}; + +static const CaseFoldMapping1_32 case_fold1_32_012[] = { + { 0x10408, 0x10430 }, + { 0x10418, 0x10440 }, + { 0x104B8, 0x104E0 }, + { 0x104C8, 0x104F0 }, + { 0x10579, 0x105A0 }, + { 0x10589, 0x105B0 }, + { 0x10C80, 0x10CC0 }, + { 0x10C90, 0x10CD0 }, + { 0x10CA0, 0x10CE0 }, + { 0x10CB0, 0x10CF0 }, + { 0x118A4, 0x118C4 }, + { 0x118B4, 0x118D4 }, + { 0x16E42, 0x16E62 }, + { 0x16E52, 0x16E72 }, + { 0x1E905, 0x1E927 }, + { 0x1E915, 0x1E937 } +}; + +static const CaseFoldMapping1_32 case_fold1_32_013[] = { + { 0x10409, 0x10431 }, + { 0x10419, 0x10441 }, + { 0x104B9, 0x104E1 }, + { 0x104C9, 0x104F1 }, + { 0x10578, 0x1059F }, + { 0x10588, 0x105AF }, + { 0x10C81, 0x10CC1 }, + { 0x10C91, 0x10CD1 }, + { 0x10CA1, 0x10CE1 }, + { 0x10CB1, 0x10CF1 }, + { 0x118A5, 0x118C5 }, + { 0x118B5, 0x118D5 }, + { 0x16E43, 0x16E63 }, + { 0x16E53, 0x16E73 }, + { 0x1E904, 0x1E926 }, + { 0x1E914, 0x1E936 } +}; + +static const CaseFoldMapping1_32 case_fold1_32_014[] = { + { 0x1040A, 0x10432 }, + { 0x1041A, 0x10442 }, + { 0x104BA, 0x104E2 }, + { 0x104CA, 0x104F2 }, + { 0x10C82, 0x10CC2 }, + { 0x10C92, 0x10CD2 }, + { 0x10CA2, 0x10CE2 }, + { 0x10CB2, 0x10CF2 }, + { 0x118A6, 0x118C6 }, + { 0x118B6, 0x118D6 }, + { 0x16E40, 0x16E60 }, + { 0x16E50, 0x16E70 }, + { 0x1E907, 0x1E929 }, + { 0x1E917, 0x1E939 } +}; + +static const CaseFoldMapping1_32 case_fold1_32_015[] = { + { 0x1040B, 0x10433 }, + { 0x1041B, 0x10443 }, + { 0x104BB, 0x104E3 }, + { 0x104CB, 0x104F3 }, + { 0x1057A, 0x105A1 }, + { 0x1058A, 0x105B1 }, + { 0x10C83, 0x10CC3 }, + { 0x10C93, 0x10CD3 }, + { 0x10CA3, 0x10CE3 }, + { 0x118A7, 0x118C7 }, + { 0x118B7, 0x118D7 }, + { 0x16E41, 0x16E61 }, + { 0x16E51, 0x16E71 }, + { 0x1E906, 0x1E928 }, + { 0x1E916, 0x1E938 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_000[] = { + { 0x1E9E, 0x0073, 0x0073 }, + { 0x1F8F, 0x1F07, 0x03B9 }, + { 0x1F9F, 0x1F27, 0x03B9 }, + { 0x1FAF, 0x1F67, 0x03B9 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_001[] = { + { 0x0130, 0x0069, 0x0307 }, + { 0x01F0, 0x006A, 0x030C }, + { 0x1F8E, 0x1F06, 0x03B9 }, + { 0x1F9E, 0x1F26, 0x03B9 }, + { 0x1FAE, 0x1F66, 0x03B9 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_002[] = { + { 0x0587, 0x0565, 0x0582 }, + { 0x1F8D, 0x1F05, 0x03B9 }, + { 0x1F9D, 0x1F25, 0x03B9 }, + { 0x1FAD, 0x1F65, 0x03B9 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_003[] = { + { 0x1F8C, 0x1F04, 0x03B9 }, + { 0x1F9C, 0x1F24, 0x03B9 }, + { 0x1FAC, 0x1F64, 0x03B9 }, + { 0x1FBC, 0x03B1, 0x03B9 }, + { 0x1FCC, 0x03B7, 0x03B9 }, + { 0x1FFC, 0x03C9, 0x03B9 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_004[] = { + { 0x1E9A, 0x0061, 0x02BE }, + { 0x1F8B, 0x1F03, 0x03B9 }, + { 0x1F9B, 0x1F23, 0x03B9 }, + { 0x1FAB, 0x1F63, 0x03B9 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_005[] = { + { 0x1F8A, 0x1F02, 0x03B9 }, + { 0x1F9A, 0x1F22, 0x03B9 }, + { 0x1FAA, 0x1F62, 0x03B9 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_006[] = { + { 0x1E98, 0x0077, 0x030A }, + { 0x1F89, 0x1F01, 0x03B9 }, + { 0x1F99, 0x1F21, 0x03B9 }, + { 0x1FA9, 0x1F61, 0x03B9 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_007[] = { + { 0x1E99, 0x0079, 0x030A }, + { 0x1F88, 0x1F00, 0x03B9 }, + { 0x1F98, 0x1F20, 0x03B9 }, + { 0x1FA8, 0x1F60, 0x03B9 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_008[] = { + { 0x0149, 0x02BC, 0x006E }, + { 0x1E96, 0x0068, 0x0331 }, + { 0x1F87, 0x1F07, 0x03B9 }, + { 0x1F97, 0x1F27, 0x03B9 }, + { 0x1FA7, 0x1F67, 0x03B9 }, + { 0xFB13, 0x0574, 0x0576 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_009[] = { + { 0x1E97, 0x0074, 0x0308 }, + { 0x1F86, 0x1F06, 0x03B9 }, + { 0x1F96, 0x1F26, 0x03B9 }, + { 0x1FA6, 0x1F66, 0x03B9 }, + { 0x1FB6, 0x03B1, 0x0342 }, + { 0x1FC6, 0x03B7, 0x0342 }, + { 0x1FD6, 0x03B9, 0x0342 }, + { 0x1FE6, 0x03C5, 0x0342 }, + { 0x1FF6, 0x03C9, 0x0342 }, + { 0xFB02, 0x0066, 0x006C } +}; + +static const CaseFoldMapping2_16 case_fold2_16_010[] = { + { 0x1F85, 0x1F05, 0x03B9 }, + { 0x1F95, 0x1F25, 0x03B9 }, + { 0x1FA5, 0x1F65, 0x03B9 }, + { 0xFB01, 0x0066, 0x0069 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_011[] = { + { 0x1F84, 0x1F04, 0x03B9 }, + { 0x1F94, 0x1F24, 0x03B9 }, + { 0x1FA4, 0x1F64, 0x03B9 }, + { 0x1FB4, 0x03AC, 0x03B9 }, + { 0x1FC4, 0x03AE, 0x03B9 }, + { 0x1FE4, 0x03C1, 0x0313 }, + { 0x1FF4, 0x03CE, 0x03B9 }, + { 0xFB00, 0x0066, 0x0066 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_012[] = { + { 0x1F83, 0x1F03, 0x03B9 }, + { 0x1F93, 0x1F23, 0x03B9 }, + { 0x1FA3, 0x1F63, 0x03B9 }, + { 0x1FB3, 0x03B1, 0x03B9 }, + { 0x1FC3, 0x03B7, 0x03B9 }, + { 0x1FF3, 0x03C9, 0x03B9 }, + { 0xFB17, 0x0574, 0x056D } +}; + +static const CaseFoldMapping2_16 case_fold2_16_013[] = { + { 0x1F82, 0x1F02, 0x03B9 }, + { 0x1F92, 0x1F22, 0x03B9 }, + { 0x1FA2, 0x1F62, 0x03B9 }, + { 0x1FB2, 0x1F70, 0x03B9 }, + { 0x1FC2, 0x1F74, 0x03B9 }, + { 0x1FF2, 0x1F7C, 0x03B9 }, + { 0xFB06, 0x0073, 0x0074 }, + { 0xFB16, 0x057E, 0x0576 } +}; + +static const CaseFoldMapping2_16 case_fold2_16_014[] = { + { 0x1F81, 0x1F01, 0x03B9 }, + { 0x1F91, 0x1F21, 0x03B9 }, + { 0x1FA1, 0x1F61, 0x03B9 }, + { 0xFB05, 0x0073, 0x0074 }, + { 0xFB15, 0x0574, 0x056B } +}; + +static const CaseFoldMapping2_16 case_fold2_16_015[] = { + { 0x00DF, 0x0073, 0x0073 }, + { 0x1F50, 0x03C5, 0x0313 }, + { 0x1F80, 0x1F00, 0x03B9 }, + { 0x1F90, 0x1F20, 0x03B9 }, + { 0x1FA0, 0x1F60, 0x03B9 }, + { 0xFB14, 0x0574, 0x0565 } +}; + +static const CaseFoldMapping3_16 case_fold3_16_000[] = { + { 0x1FB7, 0x03B1, 0x0342, 0x03B9 }, + { 0x1FC7, 0x03B7, 0x0342, 0x03B9 }, + { 0x1FD3, 0x03B9, 0x0308, 0x0301 }, + { 0x1FD7, 0x03B9, 0x0308, 0x0342 }, + { 0x1FE3, 0x03C5, 0x0308, 0x0301 }, + { 0x1FE7, 0x03C5, 0x0308, 0x0342 }, + { 0x1FF7, 0x03C9, 0x0342, 0x03B9 }, + { 0xFB03, 0x0066, 0x0066, 0x0069 } +}; + +static const CaseFoldMapping3_16 case_fold3_16_001[] = { + { 0x1F52, 0x03C5, 0x0313, 0x0300 }, + { 0x1F56, 0x03C5, 0x0313, 0x0342 }, + { 0x1FD2, 0x03B9, 0x0308, 0x0300 }, + { 0x1FE2, 0x03C5, 0x0308, 0x0300 } +}; + +static const CaseFoldMapping3_16 case_fold3_16_003[] = { + { 0x0390, 0x03B9, 0x0308, 0x0301 }, + { 0x03B0, 0x03C5, 0x0308, 0x0301 }, + { 0x1F54, 0x03C5, 0x0313, 0x0301 }, + { 0xFB04, 0x0066, 0x0066, 0x006C } +}; + +static const CaseFoldHashBucket1_16 case_fold_hash1_16[] = { + { case_fold1_16_000, SDL_arraysize(case_fold1_16_000) }, + { case_fold1_16_001, SDL_arraysize(case_fold1_16_001) }, + { case_fold1_16_002, SDL_arraysize(case_fold1_16_002) }, + { case_fold1_16_003, SDL_arraysize(case_fold1_16_003) }, + { case_fold1_16_004, SDL_arraysize(case_fold1_16_004) }, + { case_fold1_16_005, SDL_arraysize(case_fold1_16_005) }, + { case_fold1_16_006, SDL_arraysize(case_fold1_16_006) }, + { case_fold1_16_007, SDL_arraysize(case_fold1_16_007) }, + { case_fold1_16_008, SDL_arraysize(case_fold1_16_008) }, + { case_fold1_16_009, SDL_arraysize(case_fold1_16_009) }, + { case_fold1_16_010, SDL_arraysize(case_fold1_16_010) }, + { case_fold1_16_011, SDL_arraysize(case_fold1_16_011) }, + { case_fold1_16_012, SDL_arraysize(case_fold1_16_012) }, + { case_fold1_16_013, SDL_arraysize(case_fold1_16_013) }, + { case_fold1_16_014, SDL_arraysize(case_fold1_16_014) }, + { case_fold1_16_015, SDL_arraysize(case_fold1_16_015) }, + { case_fold1_16_016, SDL_arraysize(case_fold1_16_016) }, + { case_fold1_16_017, SDL_arraysize(case_fold1_16_017) }, + { case_fold1_16_018, SDL_arraysize(case_fold1_16_018) }, + { case_fold1_16_019, SDL_arraysize(case_fold1_16_019) }, + { case_fold1_16_020, SDL_arraysize(case_fold1_16_020) }, + { case_fold1_16_021, SDL_arraysize(case_fold1_16_021) }, + { case_fold1_16_022, SDL_arraysize(case_fold1_16_022) }, + { case_fold1_16_023, SDL_arraysize(case_fold1_16_023) }, + { case_fold1_16_024, SDL_arraysize(case_fold1_16_024) }, + { case_fold1_16_025, SDL_arraysize(case_fold1_16_025) }, + { case_fold1_16_026, SDL_arraysize(case_fold1_16_026) }, + { case_fold1_16_027, SDL_arraysize(case_fold1_16_027) }, + { case_fold1_16_028, SDL_arraysize(case_fold1_16_028) }, + { case_fold1_16_029, SDL_arraysize(case_fold1_16_029) }, + { case_fold1_16_030, SDL_arraysize(case_fold1_16_030) }, + { case_fold1_16_031, SDL_arraysize(case_fold1_16_031) }, + { case_fold1_16_032, SDL_arraysize(case_fold1_16_032) }, + { case_fold1_16_033, SDL_arraysize(case_fold1_16_033) }, + { case_fold1_16_034, SDL_arraysize(case_fold1_16_034) }, + { case_fold1_16_035, SDL_arraysize(case_fold1_16_035) }, + { case_fold1_16_036, SDL_arraysize(case_fold1_16_036) }, + { case_fold1_16_037, SDL_arraysize(case_fold1_16_037) }, + { case_fold1_16_038, SDL_arraysize(case_fold1_16_038) }, + { case_fold1_16_039, SDL_arraysize(case_fold1_16_039) }, + { case_fold1_16_040, SDL_arraysize(case_fold1_16_040) }, + { case_fold1_16_041, SDL_arraysize(case_fold1_16_041) }, + { case_fold1_16_042, SDL_arraysize(case_fold1_16_042) }, + { case_fold1_16_043, SDL_arraysize(case_fold1_16_043) }, + { case_fold1_16_044, SDL_arraysize(case_fold1_16_044) }, + { case_fold1_16_045, SDL_arraysize(case_fold1_16_045) }, + { case_fold1_16_046, SDL_arraysize(case_fold1_16_046) }, + { case_fold1_16_047, SDL_arraysize(case_fold1_16_047) }, + { case_fold1_16_048, SDL_arraysize(case_fold1_16_048) }, + { case_fold1_16_049, SDL_arraysize(case_fold1_16_049) }, + { case_fold1_16_050, SDL_arraysize(case_fold1_16_050) }, + { case_fold1_16_051, SDL_arraysize(case_fold1_16_051) }, + { case_fold1_16_052, SDL_arraysize(case_fold1_16_052) }, + { case_fold1_16_053, SDL_arraysize(case_fold1_16_053) }, + { case_fold1_16_054, SDL_arraysize(case_fold1_16_054) }, + { case_fold1_16_055, SDL_arraysize(case_fold1_16_055) }, + { case_fold1_16_056, SDL_arraysize(case_fold1_16_056) }, + { case_fold1_16_057, SDL_arraysize(case_fold1_16_057) }, + { case_fold1_16_058, SDL_arraysize(case_fold1_16_058) }, + { case_fold1_16_059, SDL_arraysize(case_fold1_16_059) }, + { case_fold1_16_060, SDL_arraysize(case_fold1_16_060) }, + { case_fold1_16_061, SDL_arraysize(case_fold1_16_061) }, + { case_fold1_16_062, SDL_arraysize(case_fold1_16_062) }, + { case_fold1_16_063, SDL_arraysize(case_fold1_16_063) }, + { case_fold1_16_064, SDL_arraysize(case_fold1_16_064) }, + { case_fold1_16_065, SDL_arraysize(case_fold1_16_065) }, + { case_fold1_16_066, SDL_arraysize(case_fold1_16_066) }, + { case_fold1_16_067, SDL_arraysize(case_fold1_16_067) }, + { case_fold1_16_068, SDL_arraysize(case_fold1_16_068) }, + { case_fold1_16_069, SDL_arraysize(case_fold1_16_069) }, + { case_fold1_16_070, SDL_arraysize(case_fold1_16_070) }, + { case_fold1_16_071, SDL_arraysize(case_fold1_16_071) }, + { case_fold1_16_072, SDL_arraysize(case_fold1_16_072) }, + { case_fold1_16_073, SDL_arraysize(case_fold1_16_073) }, + { case_fold1_16_074, SDL_arraysize(case_fold1_16_074) }, + { case_fold1_16_075, SDL_arraysize(case_fold1_16_075) }, + { case_fold1_16_076, SDL_arraysize(case_fold1_16_076) }, + { case_fold1_16_077, SDL_arraysize(case_fold1_16_077) }, + { case_fold1_16_078, SDL_arraysize(case_fold1_16_078) }, + { case_fold1_16_079, SDL_arraysize(case_fold1_16_079) }, + { case_fold1_16_080, SDL_arraysize(case_fold1_16_080) }, + { case_fold1_16_081, SDL_arraysize(case_fold1_16_081) }, + { case_fold1_16_082, SDL_arraysize(case_fold1_16_082) }, + { case_fold1_16_083, SDL_arraysize(case_fold1_16_083) }, + { case_fold1_16_084, SDL_arraysize(case_fold1_16_084) }, + { case_fold1_16_085, SDL_arraysize(case_fold1_16_085) }, + { case_fold1_16_086, SDL_arraysize(case_fold1_16_086) }, + { case_fold1_16_087, SDL_arraysize(case_fold1_16_087) }, + { case_fold1_16_088, SDL_arraysize(case_fold1_16_088) }, + { case_fold1_16_089, SDL_arraysize(case_fold1_16_089) }, + { case_fold1_16_090, SDL_arraysize(case_fold1_16_090) }, + { case_fold1_16_091, SDL_arraysize(case_fold1_16_091) }, + { case_fold1_16_092, SDL_arraysize(case_fold1_16_092) }, + { case_fold1_16_093, SDL_arraysize(case_fold1_16_093) }, + { case_fold1_16_094, SDL_arraysize(case_fold1_16_094) }, + { case_fold1_16_095, SDL_arraysize(case_fold1_16_095) }, + { case_fold1_16_096, SDL_arraysize(case_fold1_16_096) }, + { case_fold1_16_097, SDL_arraysize(case_fold1_16_097) }, + { case_fold1_16_098, SDL_arraysize(case_fold1_16_098) }, + { case_fold1_16_099, SDL_arraysize(case_fold1_16_099) }, + { case_fold1_16_100, SDL_arraysize(case_fold1_16_100) }, + { case_fold1_16_101, SDL_arraysize(case_fold1_16_101) }, + { case_fold1_16_102, SDL_arraysize(case_fold1_16_102) }, + { case_fold1_16_103, SDL_arraysize(case_fold1_16_103) }, + { case_fold1_16_104, SDL_arraysize(case_fold1_16_104) }, + { case_fold1_16_105, SDL_arraysize(case_fold1_16_105) }, + { case_fold1_16_106, SDL_arraysize(case_fold1_16_106) }, + { case_fold1_16_107, SDL_arraysize(case_fold1_16_107) }, + { case_fold1_16_108, SDL_arraysize(case_fold1_16_108) }, + { case_fold1_16_109, SDL_arraysize(case_fold1_16_109) }, + { case_fold1_16_110, SDL_arraysize(case_fold1_16_110) }, + { case_fold1_16_111, SDL_arraysize(case_fold1_16_111) }, + { case_fold1_16_112, SDL_arraysize(case_fold1_16_112) }, + { case_fold1_16_113, SDL_arraysize(case_fold1_16_113) }, + { case_fold1_16_114, SDL_arraysize(case_fold1_16_114) }, + { case_fold1_16_115, SDL_arraysize(case_fold1_16_115) }, + { case_fold1_16_116, SDL_arraysize(case_fold1_16_116) }, + { case_fold1_16_117, SDL_arraysize(case_fold1_16_117) }, + { case_fold1_16_118, SDL_arraysize(case_fold1_16_118) }, + { case_fold1_16_119, SDL_arraysize(case_fold1_16_119) }, + { case_fold1_16_120, SDL_arraysize(case_fold1_16_120) }, + { case_fold1_16_121, SDL_arraysize(case_fold1_16_121) }, + { case_fold1_16_122, SDL_arraysize(case_fold1_16_122) }, + { NULL, 0 }, + { case_fold1_16_124, SDL_arraysize(case_fold1_16_124) }, + { NULL, 0 }, + { case_fold1_16_126, SDL_arraysize(case_fold1_16_126) }, + { case_fold1_16_127, SDL_arraysize(case_fold1_16_127) }, + { case_fold1_16_128, SDL_arraysize(case_fold1_16_128) }, + { case_fold1_16_129, SDL_arraysize(case_fold1_16_129) }, + { case_fold1_16_130, SDL_arraysize(case_fold1_16_130) }, + { case_fold1_16_131, SDL_arraysize(case_fold1_16_131) }, + { case_fold1_16_132, SDL_arraysize(case_fold1_16_132) }, + { case_fold1_16_133, SDL_arraysize(case_fold1_16_133) }, + { case_fold1_16_134, SDL_arraysize(case_fold1_16_134) }, + { case_fold1_16_135, SDL_arraysize(case_fold1_16_135) }, + { case_fold1_16_136, SDL_arraysize(case_fold1_16_136) }, + { case_fold1_16_137, SDL_arraysize(case_fold1_16_137) }, + { case_fold1_16_138, SDL_arraysize(case_fold1_16_138) }, + { case_fold1_16_139, SDL_arraysize(case_fold1_16_139) }, + { case_fold1_16_140, SDL_arraysize(case_fold1_16_140) }, + { case_fold1_16_141, SDL_arraysize(case_fold1_16_141) }, + { case_fold1_16_142, SDL_arraysize(case_fold1_16_142) }, + { case_fold1_16_143, SDL_arraysize(case_fold1_16_143) }, + { case_fold1_16_144, SDL_arraysize(case_fold1_16_144) }, + { case_fold1_16_145, SDL_arraysize(case_fold1_16_145) }, + { case_fold1_16_146, SDL_arraysize(case_fold1_16_146) }, + { case_fold1_16_147, SDL_arraysize(case_fold1_16_147) }, + { case_fold1_16_148, SDL_arraysize(case_fold1_16_148) }, + { case_fold1_16_149, SDL_arraysize(case_fold1_16_149) }, + { case_fold1_16_150, SDL_arraysize(case_fold1_16_150) }, + { case_fold1_16_151, SDL_arraysize(case_fold1_16_151) }, + { case_fold1_16_152, SDL_arraysize(case_fold1_16_152) }, + { case_fold1_16_153, SDL_arraysize(case_fold1_16_153) }, + { case_fold1_16_154, SDL_arraysize(case_fold1_16_154) }, + { case_fold1_16_155, SDL_arraysize(case_fold1_16_155) }, + { case_fold1_16_156, SDL_arraysize(case_fold1_16_156) }, + { case_fold1_16_157, SDL_arraysize(case_fold1_16_157) }, + { case_fold1_16_158, SDL_arraysize(case_fold1_16_158) }, + { case_fold1_16_159, SDL_arraysize(case_fold1_16_159) }, + { case_fold1_16_160, SDL_arraysize(case_fold1_16_160) }, + { case_fold1_16_161, SDL_arraysize(case_fold1_16_161) }, + { case_fold1_16_162, SDL_arraysize(case_fold1_16_162) }, + { case_fold1_16_163, SDL_arraysize(case_fold1_16_163) }, + { case_fold1_16_164, SDL_arraysize(case_fold1_16_164) }, + { case_fold1_16_165, SDL_arraysize(case_fold1_16_165) }, + { case_fold1_16_166, SDL_arraysize(case_fold1_16_166) }, + { case_fold1_16_167, SDL_arraysize(case_fold1_16_167) }, + { case_fold1_16_168, SDL_arraysize(case_fold1_16_168) }, + { case_fold1_16_169, SDL_arraysize(case_fold1_16_169) }, + { case_fold1_16_170, SDL_arraysize(case_fold1_16_170) }, + { case_fold1_16_171, SDL_arraysize(case_fold1_16_171) }, + { case_fold1_16_172, SDL_arraysize(case_fold1_16_172) }, + { case_fold1_16_173, SDL_arraysize(case_fold1_16_173) }, + { case_fold1_16_174, SDL_arraysize(case_fold1_16_174) }, + { case_fold1_16_175, SDL_arraysize(case_fold1_16_175) }, + { case_fold1_16_176, SDL_arraysize(case_fold1_16_176) }, + { case_fold1_16_177, SDL_arraysize(case_fold1_16_177) }, + { case_fold1_16_178, SDL_arraysize(case_fold1_16_178) }, + { case_fold1_16_179, SDL_arraysize(case_fold1_16_179) }, + { case_fold1_16_180, SDL_arraysize(case_fold1_16_180) }, + { case_fold1_16_181, SDL_arraysize(case_fold1_16_181) }, + { case_fold1_16_182, SDL_arraysize(case_fold1_16_182) }, + { case_fold1_16_183, SDL_arraysize(case_fold1_16_183) }, + { case_fold1_16_184, SDL_arraysize(case_fold1_16_184) }, + { case_fold1_16_185, SDL_arraysize(case_fold1_16_185) }, + { case_fold1_16_186, SDL_arraysize(case_fold1_16_186) }, + { case_fold1_16_187, SDL_arraysize(case_fold1_16_187) }, + { case_fold1_16_188, SDL_arraysize(case_fold1_16_188) }, + { case_fold1_16_189, SDL_arraysize(case_fold1_16_189) }, + { case_fold1_16_190, SDL_arraysize(case_fold1_16_190) }, + { case_fold1_16_191, SDL_arraysize(case_fold1_16_191) }, + { case_fold1_16_192, SDL_arraysize(case_fold1_16_192) }, + { case_fold1_16_193, SDL_arraysize(case_fold1_16_193) }, + { case_fold1_16_194, SDL_arraysize(case_fold1_16_194) }, + { case_fold1_16_195, SDL_arraysize(case_fold1_16_195) }, + { case_fold1_16_196, SDL_arraysize(case_fold1_16_196) }, + { case_fold1_16_197, SDL_arraysize(case_fold1_16_197) }, + { case_fold1_16_198, SDL_arraysize(case_fold1_16_198) }, + { case_fold1_16_199, SDL_arraysize(case_fold1_16_199) }, + { case_fold1_16_200, SDL_arraysize(case_fold1_16_200) }, + { case_fold1_16_201, SDL_arraysize(case_fold1_16_201) }, + { case_fold1_16_202, SDL_arraysize(case_fold1_16_202) }, + { case_fold1_16_203, SDL_arraysize(case_fold1_16_203) }, + { case_fold1_16_204, SDL_arraysize(case_fold1_16_204) }, + { case_fold1_16_205, SDL_arraysize(case_fold1_16_205) }, + { case_fold1_16_206, SDL_arraysize(case_fold1_16_206) }, + { case_fold1_16_207, SDL_arraysize(case_fold1_16_207) }, + { case_fold1_16_208, SDL_arraysize(case_fold1_16_208) }, + { case_fold1_16_209, SDL_arraysize(case_fold1_16_209) }, + { case_fold1_16_210, SDL_arraysize(case_fold1_16_210) }, + { case_fold1_16_211, SDL_arraysize(case_fold1_16_211) }, + { case_fold1_16_212, SDL_arraysize(case_fold1_16_212) }, + { case_fold1_16_213, SDL_arraysize(case_fold1_16_213) }, + { case_fold1_16_214, SDL_arraysize(case_fold1_16_214) }, + { case_fold1_16_215, SDL_arraysize(case_fold1_16_215) }, + { case_fold1_16_216, SDL_arraysize(case_fold1_16_216) }, + { case_fold1_16_217, SDL_arraysize(case_fold1_16_217) }, + { case_fold1_16_218, SDL_arraysize(case_fold1_16_218) }, + { case_fold1_16_219, SDL_arraysize(case_fold1_16_219) }, + { case_fold1_16_220, SDL_arraysize(case_fold1_16_220) }, + { case_fold1_16_221, SDL_arraysize(case_fold1_16_221) }, + { case_fold1_16_222, SDL_arraysize(case_fold1_16_222) }, + { case_fold1_16_223, SDL_arraysize(case_fold1_16_223) }, + { case_fold1_16_224, SDL_arraysize(case_fold1_16_224) }, + { case_fold1_16_225, SDL_arraysize(case_fold1_16_225) }, + { case_fold1_16_226, SDL_arraysize(case_fold1_16_226) }, + { case_fold1_16_227, SDL_arraysize(case_fold1_16_227) }, + { case_fold1_16_228, SDL_arraysize(case_fold1_16_228) }, + { case_fold1_16_229, SDL_arraysize(case_fold1_16_229) }, + { case_fold1_16_230, SDL_arraysize(case_fold1_16_230) }, + { case_fold1_16_231, SDL_arraysize(case_fold1_16_231) }, + { case_fold1_16_232, SDL_arraysize(case_fold1_16_232) }, + { case_fold1_16_233, SDL_arraysize(case_fold1_16_233) }, + { case_fold1_16_234, SDL_arraysize(case_fold1_16_234) }, + { case_fold1_16_235, SDL_arraysize(case_fold1_16_235) }, + { case_fold1_16_236, SDL_arraysize(case_fold1_16_236) }, + { case_fold1_16_237, SDL_arraysize(case_fold1_16_237) }, + { case_fold1_16_238, SDL_arraysize(case_fold1_16_238) }, + { case_fold1_16_239, SDL_arraysize(case_fold1_16_239) }, + { case_fold1_16_240, SDL_arraysize(case_fold1_16_240) }, + { case_fold1_16_241, SDL_arraysize(case_fold1_16_241) }, + { case_fold1_16_242, SDL_arraysize(case_fold1_16_242) }, + { case_fold1_16_243, SDL_arraysize(case_fold1_16_243) }, + { case_fold1_16_244, SDL_arraysize(case_fold1_16_244) }, + { case_fold1_16_245, SDL_arraysize(case_fold1_16_245) }, + { case_fold1_16_246, SDL_arraysize(case_fold1_16_246) }, + { case_fold1_16_247, SDL_arraysize(case_fold1_16_247) }, + { case_fold1_16_248, SDL_arraysize(case_fold1_16_248) }, + { case_fold1_16_249, SDL_arraysize(case_fold1_16_249) }, + { case_fold1_16_250, SDL_arraysize(case_fold1_16_250) }, + { case_fold1_16_251, SDL_arraysize(case_fold1_16_251) }, + { case_fold1_16_252, SDL_arraysize(case_fold1_16_252) }, + { case_fold1_16_253, SDL_arraysize(case_fold1_16_253) }, + { case_fold1_16_254, SDL_arraysize(case_fold1_16_254) }, + { case_fold1_16_255, SDL_arraysize(case_fold1_16_255) }, +}; + +static const CaseFoldHashBucket1_32 case_fold_hash1_32[] = { + { case_fold1_32_000, SDL_arraysize(case_fold1_32_000) }, + { case_fold1_32_001, SDL_arraysize(case_fold1_32_001) }, + { case_fold1_32_002, SDL_arraysize(case_fold1_32_002) }, + { case_fold1_32_003, SDL_arraysize(case_fold1_32_003) }, + { case_fold1_32_004, SDL_arraysize(case_fold1_32_004) }, + { case_fold1_32_005, SDL_arraysize(case_fold1_32_005) }, + { case_fold1_32_006, SDL_arraysize(case_fold1_32_006) }, + { case_fold1_32_007, SDL_arraysize(case_fold1_32_007) }, + { case_fold1_32_008, SDL_arraysize(case_fold1_32_008) }, + { case_fold1_32_009, SDL_arraysize(case_fold1_32_009) }, + { case_fold1_32_010, SDL_arraysize(case_fold1_32_010) }, + { case_fold1_32_011, SDL_arraysize(case_fold1_32_011) }, + { case_fold1_32_012, SDL_arraysize(case_fold1_32_012) }, + { case_fold1_32_013, SDL_arraysize(case_fold1_32_013) }, + { case_fold1_32_014, SDL_arraysize(case_fold1_32_014) }, + { case_fold1_32_015, SDL_arraysize(case_fold1_32_015) }, +}; + +static const CaseFoldHashBucket2_16 case_fold_hash2_16[] = { + { case_fold2_16_000, SDL_arraysize(case_fold2_16_000) }, + { case_fold2_16_001, SDL_arraysize(case_fold2_16_001) }, + { case_fold2_16_002, SDL_arraysize(case_fold2_16_002) }, + { case_fold2_16_003, SDL_arraysize(case_fold2_16_003) }, + { case_fold2_16_004, SDL_arraysize(case_fold2_16_004) }, + { case_fold2_16_005, SDL_arraysize(case_fold2_16_005) }, + { case_fold2_16_006, SDL_arraysize(case_fold2_16_006) }, + { case_fold2_16_007, SDL_arraysize(case_fold2_16_007) }, + { case_fold2_16_008, SDL_arraysize(case_fold2_16_008) }, + { case_fold2_16_009, SDL_arraysize(case_fold2_16_009) }, + { case_fold2_16_010, SDL_arraysize(case_fold2_16_010) }, + { case_fold2_16_011, SDL_arraysize(case_fold2_16_011) }, + { case_fold2_16_012, SDL_arraysize(case_fold2_16_012) }, + { case_fold2_16_013, SDL_arraysize(case_fold2_16_013) }, + { case_fold2_16_014, SDL_arraysize(case_fold2_16_014) }, + { case_fold2_16_015, SDL_arraysize(case_fold2_16_015) }, +}; + +static const CaseFoldHashBucket3_16 case_fold_hash3_16[] = { + { case_fold3_16_000, SDL_arraysize(case_fold3_16_000) }, + { case_fold3_16_001, SDL_arraysize(case_fold3_16_001) }, + { NULL, 0 }, + { case_fold3_16_003, SDL_arraysize(case_fold3_16_003) }, +}; + +#endif // SDL_casefolding_h_ + diff --git a/thirdparty/sdl/stdlib/SDL_crc16.c b/thirdparty/sdl/stdlib/SDL_crc16.c new file mode 100644 index 00000000000..828ce942c67 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_crc16.c @@ -0,0 +1,52 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +/* Public domain CRC implementation adapted from: + http://home.thep.lu.se/~bjorn/crc/crc32_simple.c + + This algorithm is compatible with the 16-bit CRC described here: + https://www.lammertbies.nl/comm/info/crc-calculation +*/ +/* NOTE: DO NOT CHANGE THIS ALGORITHM + There is code that relies on this in the joystick code +*/ + +static Uint16 crc16_for_byte(Uint8 r) +{ + Uint16 crc = 0; + int i; + for (i = 0; i < 8; ++i) { + crc = ((crc ^ r) & 1 ? 0xA001 : 0) ^ crc >> 1; + r >>= 1; + } + return crc; +} + +Uint16 SDL_crc16(Uint16 crc, const void *data, size_t len) +{ + // As an optimization we can precalculate a 256 entry table for each byte + size_t i; + for (i = 0; i < len; ++i) { + crc = crc16_for_byte((Uint8)crc ^ ((const Uint8 *)data)[i]) ^ crc >> 8; + } + return crc; +} diff --git a/thirdparty/sdl/stdlib/SDL_crc32.c b/thirdparty/sdl/stdlib/SDL_crc32.c new file mode 100644 index 00000000000..9c2d0977db7 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_crc32.c @@ -0,0 +1,50 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +/* Public domain CRC implementation adapted from: + http://home.thep.lu.se/~bjorn/crc/crc32_simple.c + + This algorithm is compatible with the 32-bit CRC described here: + https://www.lammertbies.nl/comm/info/crc-calculation +*/ +/* NOTE: DO NOT CHANGE THIS ALGORITHM + There is code that relies on this in the joystick code +*/ + +static Uint32 crc32_for_byte(Uint32 r) +{ + int i; + for (i = 0; i < 8; ++i) { + r = (r & 1 ? 0 : (Uint32)0xEDB88320L) ^ r >> 1; + } + return r ^ (Uint32)0xFF000000L; +} + +Uint32 SDL_crc32(Uint32 crc, const void *data, size_t len) +{ + // As an optimization we can precalculate a 256 entry table for each byte + size_t i; + for (i = 0; i < len; ++i) { + crc = crc32_for_byte((Uint8)crc ^ ((const Uint8 *)data)[i]) ^ crc >> 8; + } + return crc; +} diff --git a/thirdparty/sdl/stdlib/SDL_getenv.c b/thirdparty/sdl/stdlib/SDL_getenv.c new file mode 100644 index 00000000000..b4a19224655 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_getenv.c @@ -0,0 +1,601 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_getenv_c.h" + +#if defined(SDL_PLATFORM_WINDOWS) +#include "../core/windows/SDL_windows.h" +#endif + +#ifdef SDL_PLATFORM_ANDROID +#include "../core/android/SDL_android.h" +#endif + +#if defined(SDL_PLATFORM_WINDOWS) +#define HAVE_WIN32_ENVIRONMENT +#elif defined(HAVE_GETENV) && \ + (defined(HAVE_SETENV) || defined(HAVE_PUTENV)) && \ + (defined(HAVE_UNSETENV) || defined(HAVE_PUTENV)) +#define HAVE_LIBC_ENVIRONMENT +#if defined(SDL_PLATFORM_MACOS) +#include +#define environ (*_NSGetEnviron()) +#elif defined(SDL_PLATFORM_FREEBSD) +#include +#define environ ((char **)dlsym(RTLD_DEFAULT, "environ")) +#else +extern char **environ; +#endif +#else +#define HAVE_LOCAL_ENVIRONMENT +static char **environ; +#endif + + +struct SDL_Environment +{ + SDL_Mutex *lock; // !!! FIXME: reuse SDL_HashTable's lock. + SDL_HashTable *strings; +}; +static SDL_Environment *SDL_environment; + +SDL_Environment *SDL_GetEnvironment(void) +{ + if (!SDL_environment) { + SDL_environment = SDL_CreateEnvironment(true); + } + return SDL_environment; +} + +bool SDL_InitEnvironment(void) +{ + return (SDL_GetEnvironment() != NULL); +} + +void SDL_QuitEnvironment(void) +{ + SDL_Environment *env = SDL_environment; + + if (env) { + SDL_environment = NULL; + SDL_DestroyEnvironment(env); + } +} + +SDL_Environment *SDL_CreateEnvironment(bool populated) +{ + SDL_Environment *env = SDL_calloc(1, sizeof(*env)); + if (!env) { + return NULL; + } + + env->strings = SDL_CreateHashTable(0, false, SDL_HashString, SDL_KeyMatchString, SDL_DestroyHashKey, NULL); + if (!env->strings) { + SDL_free(env); + return NULL; + } + + // Don't fail if we can't create a mutex (e.g. on a single-thread environment) // !!! FIXME: single-threaded environments should still return a non-NULL, do-nothing object here. Check for failure! + env->lock = SDL_CreateMutex(); + + if (populated) { +#ifdef SDL_PLATFORM_WINDOWS + LPWCH strings = GetEnvironmentStringsW(); + if (strings) { + for (LPWCH string = strings; *string; string += SDL_wcslen(string) + 1) { + char *variable = WIN_StringToUTF8W(string); + if (!variable) { + continue; + } + + char *value = SDL_strchr(variable, '='); + if (!value || value == variable) { + SDL_free(variable); + continue; + } + *value++ = '\0'; + + SDL_InsertIntoHashTable(env->strings, variable, value, true); + } + FreeEnvironmentStringsW(strings); + } +#else +#ifdef SDL_PLATFORM_ANDROID + // Make sure variables from the application manifest are available + Android_JNI_GetManifestEnvironmentVariables(); +#endif + char **strings = environ; + if (strings) { + for (int i = 0; strings[i]; ++i) { + char *variable = SDL_strdup(strings[i]); + if (!variable) { + continue; + } + + char *value = SDL_strchr(variable, '='); + if (!value || value == variable) { + SDL_free(variable); + continue; + } + *value++ = '\0'; + + SDL_InsertIntoHashTable(env->strings, variable, value, true); + } + } +#endif // SDL_PLATFORM_WINDOWS + } + + return env; +} + +const char *SDL_GetEnvironmentVariable(SDL_Environment *env, const char *name) +{ + const char *result = NULL; + + if (!env) { + return NULL; + } else if (!name || *name == '\0') { + return NULL; + } + + SDL_LockMutex(env->lock); + { + const char *value; + + if (SDL_FindInHashTable(env->strings, name, (const void **)&value)) { + result = SDL_GetPersistentString(value); + } + } + SDL_UnlockMutex(env->lock); + + return result; +} + +typedef struct CountEnvStringsData +{ + size_t count; + size_t length; +} CountEnvStringsData; + +static bool SDLCALL CountEnvStrings(void *userdata, const SDL_HashTable *table, const void *key, const void *value) +{ + CountEnvStringsData *data = (CountEnvStringsData *) userdata; + data->length += SDL_strlen((const char *) key) + 1 + SDL_strlen((const char *) value) + 1; + data->count++; + return true; // keep iterating. +} + +typedef struct CopyEnvStringsData +{ + char **result; + char *string; + size_t count; +} CopyEnvStringsData; + +static bool SDLCALL CopyEnvStrings(void *userdata, const SDL_HashTable *table, const void *vkey, const void *vvalue) +{ + CopyEnvStringsData *data = (CopyEnvStringsData *) userdata; + const char *key = (const char *) vkey; + const char *value = (const char *) vvalue; + size_t len; + + len = SDL_strlen(key); + data->result[data->count] = data->string; + SDL_memcpy(data->string, key, len); + data->string += len; + *(data->string++) = '='; + + len = SDL_strlen(value); + SDL_memcpy(data->string, value, len); + data->string += len; + *(data->string++) = '\0'; + data->count++; + + return true; // keep iterating. +} + +char **SDL_GetEnvironmentVariables(SDL_Environment *env) +{ + char **result = NULL; + + if (!env) { + SDL_InvalidParamError("env"); + return NULL; + } + + SDL_LockMutex(env->lock); + { + // First pass, get the size we need for all the strings + CountEnvStringsData countdata = { 0, 0 }; + SDL_IterateHashTable(env->strings, CountEnvStrings, &countdata); + + // Allocate memory for the strings + result = (char **)SDL_malloc((countdata.count + 1) * sizeof(*result) + countdata.length); + if (result) { + // Second pass, copy the strings + char *string = (char *)(result + countdata.count + 1); + CopyEnvStringsData cpydata = { result, string, 0 }; + SDL_IterateHashTable(env->strings, CopyEnvStrings, &cpydata); + SDL_assert(countdata.count == cpydata.count); + result[cpydata.count] = NULL; + } + } + SDL_UnlockMutex(env->lock); + + return result; +} + +bool SDL_SetEnvironmentVariable(SDL_Environment *env, const char *name, const char *value, bool overwrite) +{ + bool result = false; + + if (!env) { + return SDL_InvalidParamError("env"); + } else if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL) { + return SDL_InvalidParamError("name"); + } else if (!value) { + return SDL_InvalidParamError("value"); + } + + SDL_LockMutex(env->lock); + { + char *string = NULL; + if (SDL_asprintf(&string, "%s=%s", name, value) > 0) { + const size_t len = SDL_strlen(name); + string[len] = '\0'; + const char *origname = name; + name = string; + value = string + len + 1; + result = SDL_InsertIntoHashTable(env->strings, name, value, overwrite); + if (!result) { + SDL_free(string); + if (!overwrite) { + const void *existing_value = NULL; + // !!! FIXME: InsertIntoHashTable does this lookup too, maybe we should have a means to report that, to avoid duplicate work? + if (SDL_FindInHashTable(env->strings, origname, &existing_value)) { + result = true; // it already existed, and we refused to overwrite it. Call it success. + } + } + } + } + } + SDL_UnlockMutex(env->lock); + + return result; +} + +bool SDL_UnsetEnvironmentVariable(SDL_Environment *env, const char *name) +{ + bool result = false; + + if (!env) { + return SDL_InvalidParamError("env"); + } else if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL) { + return SDL_InvalidParamError("name"); + } + + SDL_LockMutex(env->lock); + { + const void *value; + if (SDL_FindInHashTable(env->strings, name, &value)) { + result = SDL_RemoveFromHashTable(env->strings, name); + } else { + result = true; + } + } + SDL_UnlockMutex(env->lock); + + return result; +} + +void SDL_DestroyEnvironment(SDL_Environment *env) +{ + if (!env || env == SDL_environment) { + return; + } + + SDL_DestroyMutex(env->lock); + SDL_DestroyHashTable(env->strings); + SDL_free(env); +} + +// Put a variable into the environment +// Note: Name may not contain a '=' character. (Reference: http://www.unix.com/man-page/Linux/3/setenv/) +#ifdef HAVE_LIBC_ENVIRONMENT +#if defined(HAVE_SETENV) +int SDL_setenv_unsafe(const char *name, const char *value, int overwrite) +{ + // Input validation + if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL || !value) { + return -1; + } + + SDL_SetEnvironmentVariable(SDL_GetEnvironment(), name, value, (overwrite != 0)); + + return setenv(name, value, overwrite); +} +// We have a real environment table, but no real setenv? Fake it w/ putenv. +#else +int SDL_setenv_unsafe(const char *name, const char *value, int overwrite) +{ + char *new_variable; + + // Input validation + if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL || !value) { + return -1; + } + + SDL_SetEnvironmentVariable(SDL_GetEnvironment(), name, value, (overwrite != 0)); + + if (getenv(name) != NULL) { + if (!overwrite) { + return 0; // leave the existing one there. + } + } + + // This leaks. Sorry. Get a better OS so we don't have to do this. + SDL_asprintf(&new_variable, "%s=%s", name, value); + if (!new_variable) { + return -1; + } + return putenv(new_variable); +} +#endif +#elif defined(HAVE_WIN32_ENVIRONMENT) +int SDL_setenv_unsafe(const char *name, const char *value, int overwrite) +{ + // Input validation + if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL || !value) { + return -1; + } + + SDL_SetEnvironmentVariable(SDL_GetEnvironment(), name, value, (overwrite != 0)); + + if (!overwrite) { + if (GetEnvironmentVariableA(name, NULL, 0) > 0) { + return 0; // asked not to overwrite existing value. + } + } + if (!SetEnvironmentVariableA(name, value)) { + return -1; + } + return 0; +} +#else // roll our own + +int SDL_setenv_unsafe(const char *name, const char *value, int overwrite) +{ + int added; + size_t len, i; + char **new_env; + char *new_variable; + + // Input validation + if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL || !value) { + return -1; + } + + // See if it already exists + if (!overwrite && SDL_getenv_unsafe(name)) { + return 0; + } + + SDL_SetEnvironmentVariable(SDL_GetEnvironment(), name, value, (overwrite != 0)); + + // Allocate memory for the variable + len = SDL_strlen(name) + SDL_strlen(value) + 2; + new_variable = (char *)SDL_malloc(len); + if (!new_variable) { + return -1; + } + + SDL_snprintf(new_variable, len, "%s=%s", name, value); + value = new_variable + SDL_strlen(name) + 1; + name = new_variable; + + // Actually put it into the environment + added = 0; + i = 0; + if (environ) { + // Check to see if it's already there... + len = (value - name); + for (; environ[i]; ++i) { + if (SDL_strncmp(environ[i], name, len) == 0) { + // If we found it, just replace the entry + SDL_free(environ[i]); + environ[i] = new_variable; + added = 1; + break; + } + } + } + + // Didn't find it in the environment, expand and add + if (!added) { + new_env = SDL_realloc(environ, (i + 2) * sizeof(char *)); + if (new_env) { + environ = new_env; + environ[i++] = new_variable; + environ[i++] = (char *)0; + added = 1; + } else { + SDL_free(new_variable); + } + } + return added ? 0 : -1; +} +#endif // HAVE_LIBC_ENVIRONMENT + +#ifdef HAVE_LIBC_ENVIRONMENT +#if defined(HAVE_UNSETENV) +int SDL_unsetenv_unsafe(const char *name) +{ + // Input validation + if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL) { + return -1; + } + + SDL_UnsetEnvironmentVariable(SDL_GetEnvironment(), name); + + return unsetenv(name); +} +// We have a real environment table, but no unsetenv? Fake it w/ putenv. +#else +int SDL_unsetenv_unsafe(const char *name) +{ + // Input validation + if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL) { + return -1; + } + + SDL_UnsetEnvironmentVariable(SDL_GetEnvironment(), name); + + // Hope this environment uses the non-standard extension of removing the environment variable if it has no '=' + return putenv(name); +} +#endif +#elif defined(HAVE_WIN32_ENVIRONMENT) +int SDL_unsetenv_unsafe(const char *name) +{ + // Input validation + if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL) { + return -1; + } + + SDL_UnsetEnvironmentVariable(SDL_GetEnvironment(), name); + + if (!SetEnvironmentVariableA(name, NULL)) { + return -1; + } + return 0; +} +#else +int SDL_unsetenv_unsafe(const char *name) +{ + size_t len, i; + + // Input validation + if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL) { + return -1; + } + + SDL_UnsetEnvironmentVariable(SDL_GetEnvironment(), name); + + if (environ) { + len = SDL_strlen(name); + for (i = 0; environ[i]; ++i) { + if ((SDL_strncmp(environ[i], name, len) == 0) && + (environ[i][len] == '=')) { + // Just clear out this entry for now + *environ[i] = '\0'; + break; + } + } + } + return 0; +} +#endif // HAVE_LIBC_ENVIRONMENT + +// Retrieve a variable named "name" from the environment +#ifdef HAVE_LIBC_ENVIRONMENT +const char *SDL_getenv_unsafe(const char *name) +{ +#ifdef SDL_PLATFORM_ANDROID + // Make sure variables from the application manifest are available + Android_JNI_GetManifestEnvironmentVariables(); +#endif + + // Input validation + if (!name || *name == '\0') { + return NULL; + } + + return getenv(name); +} +#elif defined(HAVE_WIN32_ENVIRONMENT) +const char *SDL_getenv_unsafe(const char *name) +{ + DWORD length, maxlen = 0; + char *string = NULL; + const char *result = NULL; + + // Input validation + if (!name || *name == '\0') { + return NULL; + } + + for ( ; ; ) { + SetLastError(ERROR_SUCCESS); + length = GetEnvironmentVariableA(name, string, maxlen); + + if (length > maxlen) { + char *temp = (char *)SDL_realloc(string, length); + if (!temp) { + return NULL; + } + string = temp; + maxlen = length; + } else { + if (GetLastError() != ERROR_SUCCESS) { + if (string) { + SDL_free(string); + } + return NULL; + } + break; + } + } + if (string) { + result = SDL_GetPersistentString(string); + SDL_free(string); + } + return result; +} +#else +const char *SDL_getenv_unsafe(const char *name) +{ + size_t len, i; + const char *value = NULL; + + // Input validation + if (!name || *name == '\0') { + return NULL; + } + + if (environ) { + len = SDL_strlen(name); + for (i = 0; environ[i]; ++i) { + if ((SDL_strncmp(environ[i], name, len) == 0) && + (environ[i][len] == '=')) { + value = &environ[i][len + 1]; + break; + } + } + } + return value; +} +#endif // HAVE_LIBC_ENVIRONMENT + +const char *SDL_getenv(const char *name) +{ + return SDL_GetEnvironmentVariable(SDL_GetEnvironment(), name); +} diff --git a/thirdparty/sdl/stdlib/SDL_getenv_c.h b/thirdparty/sdl/stdlib/SDL_getenv_c.h new file mode 100644 index 00000000000..9cf997da761 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_getenv_c.h @@ -0,0 +1,24 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +extern bool SDL_InitEnvironment(void); +extern void SDL_QuitEnvironment(void); diff --git a/thirdparty/sdl/stdlib/SDL_iconv.c b/thirdparty/sdl/stdlib/SDL_iconv.c new file mode 100644 index 00000000000..fbea0331948 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_iconv.c @@ -0,0 +1,860 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This file contains portable iconv functions for SDL + +#if defined(HAVE_ICONV) && defined(HAVE_ICONV_H) +#ifndef SDL_USE_LIBICONV +// Define LIBICONV_PLUG to use iconv from the base instead of ports and avoid linker errors. +#define LIBICONV_PLUG 1 +#endif +#include +#include + +SDL_COMPILE_TIME_ASSERT(iconv_t, sizeof(iconv_t) <= sizeof(SDL_iconv_t)); + +SDL_iconv_t SDL_iconv_open(const char *tocode, const char *fromcode) +{ + return (SDL_iconv_t)((uintptr_t)iconv_open(tocode, fromcode)); +} + +int SDL_iconv_close(SDL_iconv_t cd) +{ + if ((size_t)cd == SDL_ICONV_ERROR) { + return -1; + } + return iconv_close((iconv_t)((uintptr_t)cd)); +} + +size_t SDL_iconv(SDL_iconv_t cd, + const char **inbuf, size_t *inbytesleft, + char **outbuf, size_t *outbytesleft) +{ + if ((size_t)cd == SDL_ICONV_ERROR) { + return SDL_ICONV_ERROR; + } + /* iconv's second parameter may or may not be `const char const *` depending on the + C runtime's whims. Casting to void * seems to make everyone happy, though. */ + const size_t retCode = iconv((iconv_t)((uintptr_t)cd), (void *)inbuf, inbytesleft, outbuf, outbytesleft); + if (retCode == (size_t)-1) { + switch (errno) { + case E2BIG: + return SDL_ICONV_E2BIG; + case EILSEQ: + return SDL_ICONV_EILSEQ; + case EINVAL: + return SDL_ICONV_EINVAL; + default: + return SDL_ICONV_ERROR; + } + } + return retCode; +} + +#else + +/* Lots of useful information on Unicode at: + http://www.cl.cam.ac.uk/~mgk25/unicode.html +*/ + +#define UNICODE_BOM 0xFEFF + +#define UNKNOWN_ASCII '?' +#define UNKNOWN_UNICODE 0xFFFD + +enum +{ + ENCODING_UNKNOWN, + ENCODING_ASCII, + ENCODING_LATIN1, + ENCODING_UTF8, + ENCODING_UTF16, // Needs byte order marker + ENCODING_UTF16BE, + ENCODING_UTF16LE, + ENCODING_UTF32, // Needs byte order marker + ENCODING_UTF32BE, + ENCODING_UTF32LE, + ENCODING_UCS2BE, + ENCODING_UCS2LE, + ENCODING_UCS4BE, + ENCODING_UCS4LE, +}; +#if SDL_BYTEORDER == SDL_BIG_ENDIAN +#define ENCODING_UTF16NATIVE ENCODING_UTF16BE +#define ENCODING_UTF32NATIVE ENCODING_UTF32BE +#define ENCODING_UCS2NATIVE ENCODING_UCS2BE +#define ENCODING_UCS4NATIVE ENCODING_UCS4BE +#else +#define ENCODING_UTF16NATIVE ENCODING_UTF16LE +#define ENCODING_UTF32NATIVE ENCODING_UTF32LE +#define ENCODING_UCS2NATIVE ENCODING_UCS2LE +#define ENCODING_UCS4NATIVE ENCODING_UCS4LE +#endif + +struct SDL_iconv_data_t +{ + int src_fmt; + int dst_fmt; +}; + +static struct +{ + const char *name; + int format; +} encodings[] = { + /* *INDENT-OFF* */ // clang-format off + { "ASCII", ENCODING_ASCII }, + { "US-ASCII", ENCODING_ASCII }, + { "8859-1", ENCODING_LATIN1 }, + { "ISO-8859-1", ENCODING_LATIN1 }, +#if defined(SDL_PLATFORM_WINDOWS) || defined(SDL_PLATFORM_OS2) + { "WCHAR_T", ENCODING_UTF16LE }, +#else + { "WCHAR_T", ENCODING_UCS4NATIVE }, +#endif + { "UTF8", ENCODING_UTF8 }, + { "UTF-8", ENCODING_UTF8 }, + { "UTF16", ENCODING_UTF16 }, + { "UTF-16", ENCODING_UTF16 }, + { "UTF16BE", ENCODING_UTF16BE }, + { "UTF-16BE", ENCODING_UTF16BE }, + { "UTF16LE", ENCODING_UTF16LE }, + { "UTF-16LE", ENCODING_UTF16LE }, + { "UTF32", ENCODING_UTF32 }, + { "UTF-32", ENCODING_UTF32 }, + { "UTF32BE", ENCODING_UTF32BE }, + { "UTF-32BE", ENCODING_UTF32BE }, + { "UTF32LE", ENCODING_UTF32LE }, + { "UTF-32LE", ENCODING_UTF32LE }, + { "UCS2", ENCODING_UCS2BE }, + { "UCS-2", ENCODING_UCS2BE }, + { "UCS-2LE", ENCODING_UCS2LE }, + { "UCS-2BE", ENCODING_UCS2BE }, + { "UCS-2-INTERNAL", ENCODING_UCS2NATIVE }, + { "UCS4", ENCODING_UCS4BE }, + { "UCS-4", ENCODING_UCS4BE }, + { "UCS-4LE", ENCODING_UCS4LE }, + { "UCS-4BE", ENCODING_UCS4BE }, + { "UCS-4-INTERNAL", ENCODING_UCS4NATIVE }, +/* *INDENT-ON* */ // clang-format on +}; + +static const char *getlocale(char *buffer, size_t bufsize) +{ + const char *lang; + char *ptr; + + lang = SDL_getenv("LC_ALL"); + if (!lang) { + lang = SDL_getenv("LC_CTYPE"); + } + if (!lang) { + lang = SDL_getenv("LC_MESSAGES"); + } + if (!lang) { + lang = SDL_getenv("LANG"); + } + if (!lang || !*lang || SDL_strcmp(lang, "C") == 0) { + lang = "ASCII"; + } + + // We need to trim down strings like "en_US.UTF-8@blah" to "UTF-8" + ptr = SDL_strchr(lang, '.'); + if (ptr) { + lang = ptr + 1; + } + + SDL_strlcpy(buffer, lang, bufsize); + ptr = SDL_strchr(buffer, '@'); + if (ptr) { + *ptr = '\0'; // chop end of string. + } + + return buffer; +} + +SDL_iconv_t SDL_iconv_open(const char *tocode, const char *fromcode) +{ + int src_fmt = ENCODING_UNKNOWN; + int dst_fmt = ENCODING_UNKNOWN; + int i; + char fromcode_buffer[64]; + char tocode_buffer[64]; + + if (!fromcode || !*fromcode) { + fromcode = getlocale(fromcode_buffer, sizeof(fromcode_buffer)); + } + if (!tocode || !*tocode) { + tocode = getlocale(tocode_buffer, sizeof(tocode_buffer)); + } + for (i = 0; i < SDL_arraysize(encodings); ++i) { + if (SDL_strcasecmp(fromcode, encodings[i].name) == 0) { + src_fmt = encodings[i].format; + if (dst_fmt != ENCODING_UNKNOWN) { + break; + } + } + if (SDL_strcasecmp(tocode, encodings[i].name) == 0) { + dst_fmt = encodings[i].format; + if (src_fmt != ENCODING_UNKNOWN) { + break; + } + } + } + if (src_fmt != ENCODING_UNKNOWN && dst_fmt != ENCODING_UNKNOWN) { + SDL_iconv_t cd = (SDL_iconv_t)SDL_malloc(sizeof(*cd)); + if (cd) { + cd->src_fmt = src_fmt; + cd->dst_fmt = dst_fmt; + return cd; + } + } + return (SDL_iconv_t)-1; +} + +size_t SDL_iconv(SDL_iconv_t cd, + const char **inbuf, size_t *inbytesleft, + char **outbuf, size_t *outbytesleft) +{ + // For simplicity, we'll convert everything to and from UCS-4 + const char *src; + char *dst; + size_t srclen, dstlen; + Uint32 ch = 0; + size_t total; + + if ((size_t)cd == SDL_ICONV_ERROR) { + return SDL_ICONV_ERROR; + } + if (!inbuf || !*inbuf) { + // Reset the context + return 0; + } + if (!outbuf || !*outbuf || !outbytesleft || !*outbytesleft) { + return SDL_ICONV_E2BIG; + } + src = *inbuf; + srclen = (inbytesleft ? *inbytesleft : 0); + dst = *outbuf; + dstlen = *outbytesleft; + + switch (cd->src_fmt) { + case ENCODING_UTF16: + // Scan for a byte order marker + { + Uint8 *p = (Uint8 *)src; + size_t n = srclen / 2; + while (n) { + if (p[0] == 0xFF && p[1] == 0xFE) { + cd->src_fmt = ENCODING_UTF16BE; + break; + } else if (p[0] == 0xFE && p[1] == 0xFF) { + cd->src_fmt = ENCODING_UTF16LE; + break; + } + p += 2; + --n; + } + if (n == 0) { + // We can't tell, default to host order + cd->src_fmt = ENCODING_UTF16NATIVE; + } + } + break; + case ENCODING_UTF32: + // Scan for a byte order marker + { + Uint8 *p = (Uint8 *)src; + size_t n = srclen / 4; + while (n) { + if (p[0] == 0xFF && p[1] == 0xFE && + p[2] == 0x00 && p[3] == 0x00) { + cd->src_fmt = ENCODING_UTF32BE; + break; + } else if (p[0] == 0x00 && p[1] == 0x00 && + p[2] == 0xFE && p[3] == 0xFF) { + cd->src_fmt = ENCODING_UTF32LE; + break; + } + p += 4; + --n; + } + if (n == 0) { + // We can't tell, default to host order + cd->src_fmt = ENCODING_UTF32NATIVE; + } + } + break; + } + + switch (cd->dst_fmt) { + case ENCODING_UTF16: + // Default to host order, need to add byte order marker + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + *(Uint16 *)dst = UNICODE_BOM; + dst += 2; + dstlen -= 2; + cd->dst_fmt = ENCODING_UTF16NATIVE; + break; + case ENCODING_UTF32: + // Default to host order, need to add byte order marker + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + *(Uint32 *)dst = UNICODE_BOM; + dst += 4; + dstlen -= 4; + cd->dst_fmt = ENCODING_UTF32NATIVE; + break; + } + + total = 0; + while (srclen > 0) { + // Decode a character + switch (cd->src_fmt) { + case ENCODING_ASCII: + { + Uint8 *p = (Uint8 *)src; + ch = (Uint32)(p[0] & 0x7F); + ++src; + --srclen; + } break; + case ENCODING_LATIN1: + { + Uint8 *p = (Uint8 *)src; + ch = (Uint32)p[0]; + ++src; + --srclen; + } break; + case ENCODING_UTF8: // RFC 3629 + { + Uint8 *p = (Uint8 *)src; + size_t left = 0; + bool overlong = false; + if (p[0] >= 0xF0) { + if ((p[0] & 0xF8) != 0xF0) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } else { + if (p[0] == 0xF0 && srclen > 1 && (p[1] & 0xF0) == 0x80) { + overlong = true; + } + ch = (Uint32)(p[0] & 0x07); + left = 3; + } + } else if (p[0] >= 0xE0) { + if ((p[0] & 0xF0) != 0xE0) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } else { + if (p[0] == 0xE0 && srclen > 1 && (p[1] & 0xE0) == 0x80) { + overlong = true; + } + ch = (Uint32)(p[0] & 0x0F); + left = 2; + } + } else if (p[0] >= 0xC0) { + if ((p[0] & 0xE0) != 0xC0) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } else { + if ((p[0] & 0xDE) == 0xC0) { + overlong = true; + } + ch = (Uint32)(p[0] & 0x1F); + left = 1; + } + } else { + if (p[0] & 0x80) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } else { + ch = (Uint32)p[0]; + } + } + ++src; + --srclen; + if (srclen < left) { + return SDL_ICONV_EINVAL; + } + while (left--) { + ++p; + if ((p[0] & 0xC0) != 0x80) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + break; + } + ch <<= 6; + ch |= (p[0] & 0x3F); + ++src; + --srclen; + } + if (overlong) { + /* Potential security risk + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } + if ((ch >= 0xD800 && ch <= 0xDFFF) || + (ch == 0xFFFE || ch == 0xFFFF) || ch > 0x10FFFF) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } + } break; + case ENCODING_UTF16BE: // RFC 2781 + { + Uint8 *p = (Uint8 *)src; + Uint16 W1, W2; + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + W1 = ((Uint16)p[0] << 8) | (Uint16)p[1]; + src += 2; + srclen -= 2; + if (W1 < 0xD800 || W1 > 0xDFFF) { + ch = (Uint32)W1; + break; + } + if (W1 > 0xDBFF) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + break; + } + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + p = (Uint8 *)src; + W2 = ((Uint16)p[0] << 8) | (Uint16)p[1]; + src += 2; + srclen -= 2; + if (W2 < 0xDC00 || W2 > 0xDFFF) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + break; + } + ch = (((Uint32)(W1 & 0x3FF) << 10) | + (Uint32)(W2 & 0x3FF)) + + 0x10000; + } break; + case ENCODING_UTF16LE: // RFC 2781 + { + Uint8 *p = (Uint8 *)src; + Uint16 W1, W2; + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + W1 = ((Uint16)p[1] << 8) | (Uint16)p[0]; + src += 2; + srclen -= 2; + if (W1 < 0xD800 || W1 > 0xDFFF) { + ch = (Uint32)W1; + break; + } + if (W1 > 0xDBFF) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + break; + } + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + p = (Uint8 *)src; + W2 = ((Uint16)p[1] << 8) | (Uint16)p[0]; + src += 2; + srclen -= 2; + if (W2 < 0xDC00 || W2 > 0xDFFF) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + break; + } + ch = (((Uint32)(W1 & 0x3FF) << 10) | + (Uint32)(W2 & 0x3FF)) + + 0x10000; + } break; + case ENCODING_UCS2LE: + { + Uint8 *p = (Uint8 *)src; + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + ch = ((Uint32)p[1] << 8) | (Uint32)p[0]; + src += 2; + srclen -= 2; + } break; + case ENCODING_UCS2BE: + { + Uint8 *p = (Uint8 *)src; + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + ch = ((Uint32)p[0] << 8) | (Uint32)p[1]; + src += 2; + srclen -= 2; + } break; + case ENCODING_UCS4BE: + case ENCODING_UTF32BE: + { + Uint8 *p = (Uint8 *)src; + if (srclen < 4) { + return SDL_ICONV_EINVAL; + } + ch = ((Uint32)p[0] << 24) | + ((Uint32)p[1] << 16) | + ((Uint32)p[2] << 8) | (Uint32)p[3]; + src += 4; + srclen -= 4; + } break; + case ENCODING_UCS4LE: + case ENCODING_UTF32LE: + { + Uint8 *p = (Uint8 *)src; + if (srclen < 4) { + return SDL_ICONV_EINVAL; + } + ch = ((Uint32)p[3] << 24) | + ((Uint32)p[2] << 16) | + ((Uint32)p[1] << 8) | (Uint32)p[0]; + src += 4; + srclen -= 4; + } break; + } + + // Encode a character + switch (cd->dst_fmt) { + case ENCODING_ASCII: + { + Uint8 *p = (Uint8 *)dst; + if (dstlen < 1) { + return SDL_ICONV_E2BIG; + } + if (ch > 0x7F) { + *p = UNKNOWN_ASCII; + } else { + *p = (Uint8)ch; + } + ++dst; + --dstlen; + } break; + case ENCODING_LATIN1: + { + Uint8 *p = (Uint8 *)dst; + if (dstlen < 1) { + return SDL_ICONV_E2BIG; + } + if (ch > 0xFF) { + *p = UNKNOWN_ASCII; + } else { + *p = (Uint8)ch; + } + ++dst; + --dstlen; + } break; + case ENCODING_UTF8: // RFC 3629 + { + Uint8 *p = (Uint8 *)dst; + if (ch > 0x10FFFF) { + ch = UNKNOWN_UNICODE; + } + if (ch <= 0x7F) { + if (dstlen < 1) { + return SDL_ICONV_E2BIG; + } + *p = (Uint8)ch; + ++dst; + --dstlen; + } else if (ch <= 0x7FF) { + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + p[0] = 0xC0 | (Uint8)((ch >> 6) & 0x1F); + p[1] = 0x80 | (Uint8)(ch & 0x3F); + dst += 2; + dstlen -= 2; + } else if (ch <= 0xFFFF) { + if (dstlen < 3) { + return SDL_ICONV_E2BIG; + } + p[0] = 0xE0 | (Uint8)((ch >> 12) & 0x0F); + p[1] = 0x80 | (Uint8)((ch >> 6) & 0x3F); + p[2] = 0x80 | (Uint8)(ch & 0x3F); + dst += 3; + dstlen -= 3; + } else { + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + p[0] = 0xF0 | (Uint8)((ch >> 18) & 0x07); + p[1] = 0x80 | (Uint8)((ch >> 12) & 0x3F); + p[2] = 0x80 | (Uint8)((ch >> 6) & 0x3F); + p[3] = 0x80 | (Uint8)(ch & 0x3F); + dst += 4; + dstlen -= 4; + } + } break; + case ENCODING_UTF16BE: // RFC 2781 + { + Uint8 *p = (Uint8 *)dst; + if (ch > 0x10FFFF) { + ch = UNKNOWN_UNICODE; + } + if (ch < 0x10000) { + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + p[0] = (Uint8)(ch >> 8); + p[1] = (Uint8)ch; + dst += 2; + dstlen -= 2; + } else { + Uint16 W1, W2; + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + ch = ch - 0x10000; + W1 = 0xD800 | (Uint16)((ch >> 10) & 0x3FF); + W2 = 0xDC00 | (Uint16)(ch & 0x3FF); + p[0] = (Uint8)(W1 >> 8); + p[1] = (Uint8)W1; + p[2] = (Uint8)(W2 >> 8); + p[3] = (Uint8)W2; + dst += 4; + dstlen -= 4; + } + } break; + case ENCODING_UTF16LE: // RFC 2781 + { + Uint8 *p = (Uint8 *)dst; + if (ch > 0x10FFFF) { + ch = UNKNOWN_UNICODE; + } + if (ch < 0x10000) { + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + p[1] = (Uint8)(ch >> 8); + p[0] = (Uint8)ch; + dst += 2; + dstlen -= 2; + } else { + Uint16 W1, W2; + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + ch = ch - 0x10000; + W1 = 0xD800 | (Uint16)((ch >> 10) & 0x3FF); + W2 = 0xDC00 | (Uint16)(ch & 0x3FF); + p[1] = (Uint8)(W1 >> 8); + p[0] = (Uint8)W1; + p[3] = (Uint8)(W2 >> 8); + p[2] = (Uint8)W2; + dst += 4; + dstlen -= 4; + } + } break; + case ENCODING_UCS2BE: + { + Uint8 *p = (Uint8 *)dst; + if (ch > 0xFFFF) { + ch = UNKNOWN_UNICODE; + } + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + p[0] = (Uint8)(ch >> 8); + p[1] = (Uint8)ch; + dst += 2; + dstlen -= 2; + } break; + case ENCODING_UCS2LE: + { + Uint8 *p = (Uint8 *)dst; + if (ch > 0xFFFF) { + ch = UNKNOWN_UNICODE; + } + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + p[1] = (Uint8)(ch >> 8); + p[0] = (Uint8)ch; + dst += 2; + dstlen -= 2; + } break; + case ENCODING_UTF32BE: + if (ch > 0x10FFFF) { + ch = UNKNOWN_UNICODE; + } + SDL_FALLTHROUGH; + case ENCODING_UCS4BE: + if (ch > 0x7FFFFFFF) { + ch = UNKNOWN_UNICODE; + } + { + Uint8 *p = (Uint8 *)dst; + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + p[0] = (Uint8)(ch >> 24); + p[1] = (Uint8)(ch >> 16); + p[2] = (Uint8)(ch >> 8); + p[3] = (Uint8)ch; + dst += 4; + dstlen -= 4; + } + break; + case ENCODING_UTF32LE: + if (ch > 0x10FFFF) { + ch = UNKNOWN_UNICODE; + } + SDL_FALLTHROUGH; + case ENCODING_UCS4LE: + if (ch > 0x7FFFFFFF) { + ch = UNKNOWN_UNICODE; + } + { + Uint8 *p = (Uint8 *)dst; + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + p[3] = (Uint8)(ch >> 24); + p[2] = (Uint8)(ch >> 16); + p[1] = (Uint8)(ch >> 8); + p[0] = (Uint8)ch; + dst += 4; + dstlen -= 4; + } + break; + } + + // Update state + *inbuf = src; + *inbytesleft = srclen; + *outbuf = dst; + *outbytesleft = dstlen; + ++total; + } + return total; +} + +int SDL_iconv_close(SDL_iconv_t cd) +{ + if (cd == (SDL_iconv_t)-1) { + return -1; + } + SDL_free(cd); + return 0; +} + +#endif // !HAVE_ICONV + +char *SDL_iconv_string(const char *tocode, const char *fromcode, const char *inbuf, size_t inbytesleft) +{ + SDL_iconv_t cd; + char *string; + size_t stringsize; + char *outbuf; + size_t outbytesleft; + size_t retCode = 0; + + if (!tocode || !*tocode) { + tocode = "UTF-8"; + } + if (!fromcode || !*fromcode) { + fromcode = "UTF-8"; + } + cd = SDL_iconv_open(tocode, fromcode); + if (cd == (SDL_iconv_t)-1) { + return NULL; + } + + stringsize = inbytesleft; + string = (char *)SDL_malloc(stringsize + sizeof(Uint32)); + if (!string) { + SDL_iconv_close(cd); + return NULL; + } + outbuf = string; + outbytesleft = stringsize; + SDL_memset(outbuf, 0, sizeof(Uint32)); + + while (inbytesleft > 0) { + const size_t oldinbytesleft = inbytesleft; + retCode = SDL_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft); + switch (retCode) { + case SDL_ICONV_E2BIG: + { + const ptrdiff_t diff = (ptrdiff_t) (outbuf - string); + char *oldstring = string; + stringsize *= 2; + string = (char *)SDL_realloc(string, stringsize + sizeof(Uint32)); + if (!string) { + SDL_free(oldstring); + SDL_iconv_close(cd); + return NULL; + } + outbuf = string + diff; + outbytesleft = stringsize - diff; + SDL_memset(outbuf, 0, sizeof(Uint32)); + continue; + } + case SDL_ICONV_EILSEQ: + // Try skipping some input data - not perfect, but... + ++inbuf; + --inbytesleft; + break; + case SDL_ICONV_EINVAL: + case SDL_ICONV_ERROR: + // We can't continue... + inbytesleft = 0; + break; + } + // Avoid infinite loops when nothing gets converted + if (oldinbytesleft == inbytesleft) { + break; + } + } + SDL_memset(outbuf, 0, sizeof(Uint32)); + SDL_iconv_close(cd); + + return string; +} diff --git a/thirdparty/sdl/stdlib/SDL_malloc.c b/thirdparty/sdl/stdlib/SDL_malloc.c new file mode 100644 index 00000000000..008675f312f --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_malloc.c @@ -0,0 +1,6507 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +/* This file contains portable memory management functions for SDL */ + +#ifndef HAVE_MALLOC +#define LACKS_SYS_TYPES_H +#define LACKS_STDIO_H +#define LACKS_STRINGS_H +#define LACKS_STRING_H +#define LACKS_STDLIB_H +#define ABORT +#define NO_MALLOC_STATS 1 +#define USE_LOCKS 1 +#define USE_DL_PREFIX + +/* + This is a version (aka dlmalloc) of malloc/free/realloc written by + Doug Lea and released to the public domain, as explained at + http://creativecommons.org/publicdomain/zero/1.0/ Send questions, + comments, complaints, performance data, etc to dl@cs.oswego.edu + +* Version 2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea + Note: There may be an updated version of this malloc obtainable at + ftp://gee.cs.oswego.edu/pub/misc/malloc.c + Check before installing! + +* Quickstart + + This library is all in one file to simplify the most common usage: + ftp it, compile it (-O3), and link it into another program. All of + the compile-time options default to reasonable values for use on + most platforms. You might later want to step through various + compile-time and dynamic tuning options. + + For convenience, an include file for code using this malloc is at: + ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.6.h + You don't really need this .h file unless you call functions not + defined in your system include files. The .h file contains only the + excerpts from this file needed for using this malloc on ANSI C/C++ + systems, so long as you haven't changed compile-time options about + naming and tuning parameters. If you do, then you can create your + own malloc.h that does include all settings by cutting at the point + indicated below. Note that you may already by default be using a C + library containing a malloc that is based on some version of this + malloc (for example in linux). You might still want to use the one + in this file to customize settings or to avoid overheads associated + with library versions. + +* Vital statistics: + + Supported pointer/size_t representation: 4 or 8 bytes + size_t MUST be an unsigned type of the same width as + pointers. (If you are using an ancient system that declares + size_t as a signed type, or need it to be a different width + than pointers, you can use a previous release of this malloc + (e.g. 2.7.2) supporting these.) + + Alignment: 8 bytes (minimum) + This suffices for nearly all current machines and C compilers. + However, you can define MALLOC_ALIGNMENT to be wider than this + if necessary (up to 128bytes), at the expense of using more space. + + Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes) + 8 or 16 bytes (if 8byte sizes) + Each malloced chunk has a hidden word of overhead holding size + and status information, and additional cross-check word + if FOOTERS is defined. + + Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead) + 8-byte ptrs: 32 bytes (including overhead) + + Even a request for zero bytes (i.e., malloc(0)) returns a + pointer to something of the minimum allocatable size. + The maximum overhead wastage (i.e., number of extra bytes + allocated than were requested in malloc) is less than or equal + to the minimum size, except for requests >= mmap_threshold that + are serviced via mmap(), where the worst case wastage is about + 32 bytes plus the remainder from a system page (the minimal + mmap unit); typically 4096 or 8192 bytes. + + Security: static-safe; optionally more or less + The "security" of malloc refers to the ability of malicious + code to accentuate the effects of errors (for example, freeing + space that is not currently malloc'ed or overwriting past the + ends of chunks) in code that calls malloc. This malloc + guarantees not to modify any memory locations below the base of + heap, i.e., static variables, even in the presence of usage + errors. The routines additionally detect most improper frees + and reallocs. All this holds as long as the static bookkeeping + for malloc itself is not corrupted by some other means. This + is only one aspect of security -- these checks do not, and + cannot, detect all possible programming errors. + + If FOOTERS is defined nonzero, then each allocated chunk + carries an additional check word to verify that it was malloced + from its space. These check words are the same within each + execution of a program using malloc, but differ across + executions, so externally crafted fake chunks cannot be + freed. This improves security by rejecting frees/reallocs that + could corrupt heap memory, in addition to the checks preventing + writes to statics that are always on. This may further improve + security at the expense of time and space overhead. (Note that + FOOTERS may also be worth using with MSPACES.) + + By default detected errors cause the program to abort (calling + "abort()"). You can override this to instead proceed past + errors by defining PROCEED_ON_ERROR. In this case, a bad free + has no effect, and a malloc that encounters a bad address + caused by user overwrites will ignore the bad address by + dropping pointers and indices to all known memory. This may + be appropriate for programs that should continue if at all + possible in the face of programming errors, although they may + run out of memory because dropped memory is never reclaimed. + + If you don't like either of these options, you can define + CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything + else. And if if you are sure that your program using malloc has + no errors or vulnerabilities, you can define INSECURE to 1, + which might (or might not) provide a small performance improvement. + + It is also possible to limit the maximum total allocatable + space, using malloc_set_footprint_limit. This is not + designed as a security feature in itself (calls to set limits + are not screened or privileged), but may be useful as one + aspect of a secure implementation. + + Thread-safety: NOT thread-safe unless USE_LOCKS defined non-zero + When USE_LOCKS is defined, each public call to malloc, free, + etc is surrounded with a lock. By default, this uses a plain + pthread mutex, win32 critical section, or a spin-lock if if + available for the platform and not disabled by setting + USE_SPIN_LOCKS=0. However, if USE_RECURSIVE_LOCKS is defined, + recursive versions are used instead (which are not required for + base functionality but may be needed in layered extensions). + Using a global lock is not especially fast, and can be a major + bottleneck. It is designed only to provide minimal protection + in concurrent environments, and to provide a basis for + extensions. If you are using malloc in a concurrent program, + consider instead using nedmalloc + (http://www.nedprod.com/programs/portable/nedmalloc/) or + ptmalloc (See http://www.malloc.de), which are derived from + versions of this malloc. + + System requirements: Any combination of MORECORE and/or MMAP/MUNMAP + This malloc can use unix sbrk or any emulation (invoked using + the CALL_MORECORE macro) and/or mmap/munmap or any emulation + (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system + memory. On most unix systems, it tends to work best if both + MORECORE and MMAP are enabled. On Win32, it uses emulations + based on VirtualAlloc. It also uses common C library functions + like memset. + + Compliance: I believe it is compliant with the Single Unix Specification + (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably + others as well. + +* Overview of algorithms + + This is not the fastest, most space-conserving, most portable, or + most tunable malloc ever written. However it is among the fastest + while also being among the most space-conserving, portable and + tunable. Consistent balance across these factors results in a good + general-purpose allocator for malloc-intensive programs. + + In most ways, this malloc is a best-fit allocator. Generally, it + chooses the best-fitting existing chunk for a request, with ties + broken in approximately least-recently-used order. (This strategy + normally maintains low fragmentation.) However, for requests less + than 256bytes, it deviates from best-fit when there is not an + exactly fitting available chunk by preferring to use space adjacent + to that used for the previous small request, as well as by breaking + ties in approximately most-recently-used order. (These enhance + locality of series of small allocations.) And for very large requests + (>= 256Kb by default), it relies on system memory mapping + facilities, if supported. (This helps avoid carrying around and + possibly fragmenting memory used only for large chunks.) + + All operations (except malloc_stats and mallinfo) have execution + times that are bounded by a constant factor of the number of bits in + a size_t, not counting any clearing in calloc or copying in realloc, + or actions surrounding MORECORE and MMAP that have times + proportional to the number of non-contiguous regions returned by + system allocation routines, which is often just 1. In real-time + applications, you can optionally suppress segment traversals using + NO_SEGMENT_TRAVERSAL, which assures bounded execution even when + system allocators return non-contiguous spaces, at the typical + expense of carrying around more memory and increased fragmentation. + + The implementation is not very modular and seriously overuses + macros. Perhaps someday all C compilers will do as good a job + inlining modular code as can now be done by brute-force expansion, + but now, enough of them seem not to. + + Some compilers issue a lot of warnings about code that is + dead/unreachable only on some platforms, and also about intentional + uses of negation on unsigned types. All known cases of each can be + ignored. + + For a longer but out of date high-level description, see + http://gee.cs.oswego.edu/dl/html/malloc.html + +* MSPACES + If MSPACES is defined, then in addition to malloc, free, etc., + this file also defines mspace_malloc, mspace_free, etc. These + are versions of malloc routines that take an "mspace" argument + obtained using create_mspace, to control all internal bookkeeping. + If ONLY_MSPACES is defined, only these versions are compiled. + So if you would like to use this allocator for only some allocations, + and your system malloc for others, you can compile with + ONLY_MSPACES and then do something like... + static mspace mymspace = create_mspace(0,0); // for example + #define mymalloc(bytes) mspace_malloc(mymspace, bytes) + + (Note: If you only need one instance of an mspace, you can instead + use "USE_DL_PREFIX" to relabel the global malloc.) + + You can similarly create thread-local allocators by storing + mspaces as thread-locals. For example: + static __thread mspace tlms = 0; + void* tlmalloc(size_t bytes) { + if (tlms == 0) tlms = create_mspace(0, 0); + return mspace_malloc(tlms, bytes); + } + void tlfree(void* mem) { mspace_free(tlms, mem); } + + Unless FOOTERS is defined, each mspace is completely independent. + You cannot allocate from one and free to another (although + conformance is only weakly checked, so usage errors are not always + caught). If FOOTERS is defined, then each chunk carries around a tag + indicating its originating mspace, and frees are directed to their + originating spaces. Normally, this requires use of locks. + + ------------------------- Compile-time options --------------------------- + +Be careful in setting #define values for numerical constants of type +size_t. On some systems, literal values are not automatically extended +to size_t precision unless they are explicitly casted. You can also +use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below. + +WIN32 default: defined if _WIN32 defined + Defining WIN32 sets up defaults for MS environment and compilers. + Otherwise defaults are for unix. Beware that there seem to be some + cases where this malloc might not be a pure drop-in replacement for + Win32 malloc: Random-looking failures from Win32 GDI API's (eg; + SetDIBits()) may be due to bugs in some video driver implementations + when pixel buffers are malloc()ed, and the region spans more than + one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb) + default granularity, pixel buffers may straddle virtual allocation + regions more often than when using the Microsoft allocator. You can + avoid this by using VirtualAlloc() and VirtualFree() for all pixel + buffers rather than using malloc(). If this is not possible, + recompile this malloc with a larger DEFAULT_GRANULARITY. Note: + in cases where MSC and gcc (cygwin) are known to differ on WIN32, + conditions use _MSC_VER to distinguish them. + +DLMALLOC_EXPORT default: extern + Defines how public APIs are declared. If you want to export via a + Windows DLL, you might define this as + #define DLMALLOC_EXPORT extern __declspec(dllexport) + If you want a POSIX ELF shared object, you might use + #define DLMALLOC_EXPORT extern __attribute__((visibility("default"))) + +MALLOC_ALIGNMENT default: (size_t)(2 * sizeof(void *)) + Controls the minimum alignment for malloc'ed chunks. It must be a + power of two and at least 8, even on machines for which smaller + alignments would suffice. It may be defined as larger than this + though. Note however that code and data structures are optimized for + the case of 8-byte alignment. + +MSPACES default: 0 (false) + If true, compile in support for independent allocation spaces. + This is only supported if HAVE_MMAP is true. + +ONLY_MSPACES default: 0 (false) + If true, only compile in mspace versions, not regular versions. + +USE_LOCKS default: 0 (false) + Causes each call to each public routine to be surrounded with + pthread or WIN32 mutex lock/unlock. (If set true, this can be + overridden on a per-mspace basis for mspace versions.) If set to a + non-zero value other than 1, locks are used, but their + implementation is left out, so lock functions must be supplied manually, + as described below. + +USE_SPIN_LOCKS default: 1 iff USE_LOCKS and spin locks available + If true, uses custom spin locks for locking. This is currently + supported only gcc >= 4.1, older gccs on x86 platforms, and recent + MS compilers. Otherwise, posix locks or win32 critical sections are + used. + +USE_RECURSIVE_LOCKS default: not defined + If defined nonzero, uses recursive (aka reentrant) locks, otherwise + uses plain mutexes. This is not required for malloc proper, but may + be needed for layered allocators such as nedmalloc. + +LOCK_AT_FORK default: not defined + If defined nonzero, performs pthread_atfork upon initialization + to initialize child lock while holding parent lock. The implementation + assumes that pthread locks (not custom locks) are being used. In other + cases, you may need to customize the implementation. + +FOOTERS default: 0 + If true, provide extra checking and dispatching by placing + information in the footers of allocated chunks. This adds + space and time overhead. + +INSECURE default: 0 + If true, omit checks for usage errors and heap space overwrites. + +USE_DL_PREFIX default: NOT defined + Causes compiler to prefix all public routines with the string 'dl'. + This can be useful when you only want to use this malloc in one part + of a program, using your regular system malloc elsewhere. + +MALLOC_INSPECT_ALL default: NOT defined + If defined, compiles malloc_inspect_all and mspace_inspect_all, that + perform traversal of all heap space. Unless access to these + functions is otherwise restricted, you probably do not want to + include them in secure implementations. + +ABORT default: defined as abort() + Defines how to abort on failed checks. On most systems, a failed + check cannot die with an "assert" or even print an informative + message, because the underlying print routines in turn call malloc, + which will fail again. Generally, the best policy is to simply call + abort(). It's not very useful to do more than this because many + errors due to overwriting will show up as address faults (null, odd + addresses etc) rather than malloc-triggered checks, so will also + abort. Also, most compilers know that abort() does not return, so + can better optimize code conditionally calling it. + +PROCEED_ON_ERROR default: defined as 0 (false) + Controls whether detected bad addresses cause them to bypassed + rather than aborting. If set, detected bad arguments to free and + realloc are ignored. And all bookkeeping information is zeroed out + upon a detected overwrite of freed heap space, thus losing the + ability to ever return it from malloc again, but enabling the + application to proceed. If PROCEED_ON_ERROR is defined, the + static variable malloc_corruption_error_count is compiled in + and can be examined to see if errors have occurred. This option + generates slower code than the default abort policy. + +DEBUG default: NOT defined + The DEBUG setting is mainly intended for people trying to modify + this code or diagnose problems when porting to new platforms. + However, it may also be able to better isolate user errors than just + using runtime checks. The assertions in the check routines spell + out in more detail the assumptions and invariants underlying the + algorithms. The checking is fairly extensive, and will slow down + execution noticeably. Calling malloc_stats or mallinfo with DEBUG + set will attempt to check every non-mmapped allocated and free chunk + in the course of computing the summaries. + +ABORT_ON_ASSERT_FAILURE default: defined as 1 (true) + Debugging assertion failures can be nearly impossible if your + version of the assert macro causes malloc to be called, which will + lead to a cascade of further failures, blowing the runtime stack. + ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(), + which will usually make debugging easier. + +MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32 + The action to take before "return 0" when malloc fails to be able to + return memory because there is none available. + +HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES + True if this system supports sbrk or an emulation of it. + +MORECORE default: sbrk + The name of the sbrk-style system routine to call to obtain more + memory. See below for guidance on writing custom MORECORE + functions. The type of the argument to sbrk/MORECORE varies across + systems. It cannot be size_t, because it supports negative + arguments, so it is normally the signed type of the same width as + size_t (sometimes declared as "intptr_t"). It doesn't much matter + though. Internally, we only call it with arguments less than half + the max value of a size_t, which should work across all reasonable + possibilities, although sometimes generating compiler warnings. + +MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE + If true, take advantage of fact that consecutive calls to MORECORE + with positive arguments always return contiguous increasing + addresses. This is true of unix sbrk. It does not hurt too much to + set it true anyway, since malloc copes with non-contiguities. + Setting it false when definitely non-contiguous saves time + and possibly wasted space it would take to discover this though. + +MORECORE_CANNOT_TRIM default: NOT defined + True if MORECORE cannot release space back to the system when given + negative arguments. This is generally necessary only if you are + using a hand-crafted MORECORE function that cannot handle negative + arguments. + +NO_SEGMENT_TRAVERSAL default: 0 + If non-zero, suppresses traversals of memory segments + returned by either MORECORE or CALL_MMAP. This disables + merging of segments that are contiguous, and selectively + releasing them to the OS if unused, but bounds execution times. + +HAVE_MMAP default: 1 (true) + True if this system supports mmap or an emulation of it. If so, and + HAVE_MORECORE is not true, MMAP is used for all system + allocation. If set and HAVE_MORECORE is true as well, MMAP is + primarily used to directly allocate very large blocks. It is also + used as a backup strategy in cases where MORECORE fails to provide + space from system. Note: A single call to MUNMAP is assumed to be + able to unmap memory that may have be allocated using multiple calls + to MMAP, so long as they are adjacent. + +HAVE_MREMAP default: 1 on linux, else 0 + If true realloc() uses mremap() to re-allocate large blocks and + extend or shrink allocation spaces. + +MMAP_CLEARS default: 1 except on WINCE. + True if mmap clears memory so calloc doesn't need to. This is true + for standard unix mmap using /dev/zero and on WIN32 except for WINCE. + +USE_BUILTIN_FFS default: 0 (i.e., not used) + Causes malloc to use the builtin ffs() function to compute indices. + Some compilers may recognize and intrinsify ffs to be faster than the + supplied C version. Also, the case of x86 using gcc is special-cased + to an asm instruction, so is already as fast as it can be, and so + this setting has no effect. Similarly for Win32 under recent MS compilers. + (On most x86s, the asm version is only slightly faster than the C version.) + +malloc_getpagesize default: derive from system includes, or 4096. + The system page size. To the extent possible, this malloc manages + memory from the system in page-size units. This may be (and + usually is) a function rather than a constant. This is ignored + if WIN32, where page size is determined using getSystemInfo during + initialization. + +USE_DEV_RANDOM default: 0 (i.e., not used) + Causes malloc to use /dev/random to initialize secure magic seed for + stamping footers. Otherwise, the current time is used. + +NO_MALLINFO default: 0 + If defined, don't compile "mallinfo". This can be a simple way + of dealing with mismatches between system declarations and + those in this file. + +MALLINFO_FIELD_TYPE default: size_t + The type of the fields in the mallinfo struct. This was originally + defined as "int" in SVID etc, but is more usefully defined as + size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set + +NO_MALLOC_STATS default: 0 + If defined, don't compile "malloc_stats". This avoids calls to + fprintf and bringing in stdio dependencies you might not want. + +REALLOC_ZERO_BYTES_FREES default: not defined + This should be set if a call to realloc with zero bytes should + be the same as a call to free. Some people think it should. Otherwise, + since this malloc returns a unique pointer for malloc(0), so does + realloc(p, 0). + +LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H +LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H +LACKS_STDLIB_H LACKS_SCHED_H LACKS_TIME_H default: NOT defined unless on WIN32 + Define these if your system does not have these header files. + You might need to manually insert some of the declarations they provide. + +DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS, + system_info.dwAllocationGranularity in WIN32, + otherwise 64K. + Also settable using mallopt(M_GRANULARITY, x) + The unit for allocating and deallocating memory from the system. On + most systems with contiguous MORECORE, there is no reason to + make this more than a page. However, systems with MMAP tend to + either require or encourage larger granularities. You can increase + this value to prevent system allocation functions to be called so + often, especially if they are slow. The value must be at least one + page and must be a power of two. Setting to 0 causes initialization + to either page size or win32 region size. (Note: In previous + versions of malloc, the equivalent of this option was called + "TOP_PAD") + +DEFAULT_TRIM_THRESHOLD default: 2MB + Also settable using mallopt(M_TRIM_THRESHOLD, x) + The maximum amount of unused top-most memory to keep before + releasing via malloc_trim in free(). Automatic trimming is mainly + useful in long-lived programs using contiguous MORECORE. Because + trimming via sbrk can be slow on some systems, and can sometimes be + wasteful (in cases where programs immediately afterward allocate + more large chunks) the value should be high enough so that your + overall system performance would improve by releasing this much + memory. As a rough guide, you might set to a value close to the + average size of a process (program) running on your system. + Releasing this much memory would allow such a process to run in + memory. Generally, it is worth tuning trim thresholds when a + program undergoes phases where several large chunks are allocated + and released in ways that can reuse each other's storage, perhaps + mixed with phases where there are no such chunks at all. The trim + value must be greater than page size to have any useful effect. To + disable trimming completely, you can set to MAX_SIZE_T. Note that the trick + some people use of mallocing a huge space and then freeing it at + program startup, in an attempt to reserve system memory, doesn't + have the intended effect under automatic trimming, since that memory + will immediately be returned to the system. + +DEFAULT_MMAP_THRESHOLD default: 256K + Also settable using mallopt(M_MMAP_THRESHOLD, x) + The request size threshold for using MMAP to directly service a + request. Requests of at least this size that cannot be allocated + using already-existing space will be serviced via mmap. (If enough + normal freed space already exists it is used instead.) Using mmap + segregates relatively large chunks of memory so that they can be + individually obtained and released from the host system. A request + serviced through mmap is never reused by any other request (at least + not directly; the system may just so happen to remap successive + requests to the same locations). Segregating space in this way has + the benefits that: Mmapped space can always be individually released + back to the system, which helps keep the system level memory demands + of a long-lived program low. Also, mapped memory doesn't become + `locked' between other chunks, as can happen with normally allocated + chunks, which means that even trimming via malloc_trim would not + release them. However, it has the disadvantage that the space + cannot be reclaimed, consolidated, and then used to service later + requests, as happens with normal chunks. The advantages of mmap + nearly always outweigh disadvantages for "large" chunks, but the + value of "large" may vary across systems. The default is an + empirically derived value that works well in most systems. You can + disable mmap by setting to MAX_SIZE_T. + +MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP + The number of consolidated frees between checks to release + unused segments when freeing. When using non-contiguous segments, + especially with multiple mspaces, checking only for topmost space + doesn't always suffice to trigger trimming. To compensate for this, + free() will, with a period of MAX_RELEASE_CHECK_RATE (or the + current number of segments, if greater) try to release unused + segments to the OS when freeing chunks that result in + consolidation. The best value for this parameter is a compromise + between slowing down frees with relatively costly checks that + rarely trigger versus holding on to unused memory. To effectively + disable, set to MAX_SIZE_T. This may lead to a very slight speed + improvement at the expense of carrying around more memory. +*/ + +/* Version identifier to allow people to support multiple versions */ +#ifndef DLMALLOC_VERSION +#define DLMALLOC_VERSION 20806 +#endif /* DLMALLOC_VERSION */ + +#ifndef DLMALLOC_EXPORT +#define DLMALLOC_EXPORT extern +#endif + +#ifndef WIN32 +#ifdef _WIN32 +#define WIN32 1 +#endif /* _WIN32 */ +#ifdef _WIN32_WCE +#define LACKS_FCNTL_H +#define WIN32 1 +#endif /* _WIN32_WCE */ +#endif /* WIN32 */ +#ifdef WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#include +#define HAVE_MMAP 1 +#define HAVE_MORECORE 0 +#define LACKS_UNISTD_H +#define LACKS_SYS_PARAM_H +#define LACKS_SYS_MMAN_H +#define LACKS_STRING_H +#define LACKS_STRINGS_H +#define LACKS_SYS_TYPES_H +#define LACKS_ERRNO_H +#define LACKS_SCHED_H +#ifndef MALLOC_FAILURE_ACTION +#define MALLOC_FAILURE_ACTION +#endif /* MALLOC_FAILURE_ACTION */ +#ifndef MMAP_CLEARS +#ifdef _WIN32_WCE /* WINCE reportedly does not clear */ +#define MMAP_CLEARS 0 +#else +#define MMAP_CLEARS 1 +#endif /* _WIN32_WCE */ +#endif /*MMAP_CLEARS */ +#endif /* WIN32 */ + +#if defined(DARWIN) || defined(_DARWIN) +/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */ +#ifndef HAVE_MORECORE +#define HAVE_MORECORE 0 +#define HAVE_MMAP 1 +/* OSX allocators provide 16 byte alignment */ +#ifndef MALLOC_ALIGNMENT +#define MALLOC_ALIGNMENT ((size_t)16U) +#endif +#endif /* HAVE_MORECORE */ +#endif /* DARWIN */ + +#ifndef LACKS_SYS_TYPES_H +#include /* For size_t */ +#endif /* LACKS_SYS_TYPES_H */ + +/* The maximum possible size_t value has all bits set */ +#define MAX_SIZE_T (~(size_t)0) + +#ifndef USE_LOCKS /* ensure true if spin or recursive locks set */ +#define USE_LOCKS ((defined(USE_SPIN_LOCKS) && USE_SPIN_LOCKS != 0) || \ + (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0)) +#endif /* USE_LOCKS */ + +#if USE_LOCKS /* Spin locks for gcc >= 4.1, older gcc on x86, MSC >= 1310 */ +#if ((defined(__GNUC__) && \ + ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \ + defined(__i386__) || defined(__x86_64__))) || \ + (defined(_MSC_VER) && _MSC_VER>=1310)) +#ifndef USE_SPIN_LOCKS +#define USE_SPIN_LOCKS 1 +#endif /* USE_SPIN_LOCKS */ +#elif USE_SPIN_LOCKS +#error "USE_SPIN_LOCKS defined without implementation" +#endif /* ... locks available... */ +#elif !defined(USE_SPIN_LOCKS) +#define USE_SPIN_LOCKS 0 +#endif /* USE_LOCKS */ + +#ifndef ONLY_MSPACES +#define ONLY_MSPACES 0 +#endif /* ONLY_MSPACES */ +#ifndef MSPACES +#if ONLY_MSPACES +#define MSPACES 1 +#else /* ONLY_MSPACES */ +#define MSPACES 0 +#endif /* ONLY_MSPACES */ +#endif /* MSPACES */ +#ifndef MALLOC_ALIGNMENT +#define MALLOC_ALIGNMENT ((size_t)(2 * sizeof(void *))) +#endif /* MALLOC_ALIGNMENT */ +#ifndef FOOTERS +#define FOOTERS 0 +#endif /* FOOTERS */ +#ifndef ABORT +#define ABORT abort() +#endif /* ABORT */ +#ifndef ABORT_ON_ASSERT_FAILURE +#define ABORT_ON_ASSERT_FAILURE 1 +#endif /* ABORT_ON_ASSERT_FAILURE */ +#ifndef PROCEED_ON_ERROR +#define PROCEED_ON_ERROR 0 +#endif /* PROCEED_ON_ERROR */ + +#ifndef INSECURE +#define INSECURE 0 +#endif /* INSECURE */ +#ifndef MALLOC_INSPECT_ALL +#define MALLOC_INSPECT_ALL 0 +#endif /* MALLOC_INSPECT_ALL */ +#ifndef HAVE_MMAP +#define HAVE_MMAP 1 +#endif /* HAVE_MMAP */ +#ifndef MMAP_CLEARS +#define MMAP_CLEARS 1 +#endif /* MMAP_CLEARS */ +#ifndef HAVE_MREMAP +#ifdef linux +#define HAVE_MREMAP 1 +#define _GNU_SOURCE /* Turns on mremap() definition */ +#else /* linux */ +#define HAVE_MREMAP 0 +#endif /* linux */ +#endif /* HAVE_MREMAP */ +#ifndef MALLOC_FAILURE_ACTION +#define MALLOC_FAILURE_ACTION errno = ENOMEM; +#endif /* MALLOC_FAILURE_ACTION */ +#ifndef HAVE_MORECORE +#if ONLY_MSPACES +#define HAVE_MORECORE 0 +#else /* ONLY_MSPACES */ +#define HAVE_MORECORE 1 +#endif /* ONLY_MSPACES */ +#endif /* HAVE_MORECORE */ +#if !HAVE_MORECORE +#define MORECORE_CONTIGUOUS 0 +#else /* !HAVE_MORECORE */ +#define MORECORE_DEFAULT sbrk +#ifndef MORECORE_CONTIGUOUS +#define MORECORE_CONTIGUOUS 1 +#endif /* MORECORE_CONTIGUOUS */ +#endif /* HAVE_MORECORE */ +#ifndef DEFAULT_GRANULARITY +#if (MORECORE_CONTIGUOUS || defined(WIN32)) +#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ +#else /* MORECORE_CONTIGUOUS */ +#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U) +#endif /* MORECORE_CONTIGUOUS */ +#endif /* DEFAULT_GRANULARITY */ +#ifndef DEFAULT_TRIM_THRESHOLD +#ifndef MORECORE_CANNOT_TRIM +#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U) +#else /* MORECORE_CANNOT_TRIM */ +#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T +#endif /* MORECORE_CANNOT_TRIM */ +#endif /* DEFAULT_TRIM_THRESHOLD */ +#ifndef DEFAULT_MMAP_THRESHOLD +#if HAVE_MMAP +#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U) +#else /* HAVE_MMAP */ +#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T +#endif /* HAVE_MMAP */ +#endif /* DEFAULT_MMAP_THRESHOLD */ +#ifndef MAX_RELEASE_CHECK_RATE +#if HAVE_MMAP +#define MAX_RELEASE_CHECK_RATE 4095 +#else +#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T +#endif /* HAVE_MMAP */ +#endif /* MAX_RELEASE_CHECK_RATE */ +#ifndef USE_BUILTIN_FFS +#define USE_BUILTIN_FFS 0 +#endif /* USE_BUILTIN_FFS */ +#ifndef USE_DEV_RANDOM +#define USE_DEV_RANDOM 0 +#endif /* USE_DEV_RANDOM */ +#ifndef NO_MALLINFO +#define NO_MALLINFO 0 +#endif /* NO_MALLINFO */ +#ifndef MALLINFO_FIELD_TYPE +#define MALLINFO_FIELD_TYPE size_t +#endif /* MALLINFO_FIELD_TYPE */ +#ifndef NO_MALLOC_STATS +#define NO_MALLOC_STATS 0 +#endif /* NO_MALLOC_STATS */ +#ifndef NO_SEGMENT_TRAVERSAL +#define NO_SEGMENT_TRAVERSAL 0 +#endif /* NO_SEGMENT_TRAVERSAL */ + +/* + mallopt tuning options. SVID/XPG defines four standard parameter + numbers for mallopt, normally defined in malloc.h. None of these + are used in this malloc, so setting them has no effect. But this + malloc does support the following options. +*/ + +#define M_TRIM_THRESHOLD (-1) +#define M_GRANULARITY (-2) +#define M_MMAP_THRESHOLD (-3) + +/* ------------------------ Mallinfo declarations ------------------------ */ + +#if !NO_MALLINFO +/* + This version of malloc supports the standard SVID/XPG mallinfo + routine that returns a struct containing usage properties and + statistics. It should work on any system that has a + /usr/include/malloc.h defining struct mallinfo. The main + declaration needed is the mallinfo struct that is returned (by-copy) + by mallinfo(). The malloinfo struct contains a bunch of fields that + are not even meaningful in this version of malloc. These fields are + are instead filled by mallinfo() with other numbers that might be of + interest. + + HAVE_USR_INCLUDE_MALLOC_H should be set if you have a + /usr/include/malloc.h file that includes a declaration of struct + mallinfo. If so, it is included; else a compliant version is + declared below. These must be precisely the same for mallinfo() to + work. The original SVID version of this struct, defined on most + systems with mallinfo, declares all fields as ints. But some others + define as unsigned long. If your system defines the fields using a + type of different width than listed here, you MUST #include your + system version and #define HAVE_USR_INCLUDE_MALLOC_H. +*/ + +/* #define HAVE_USR_INCLUDE_MALLOC_H */ + +#ifdef HAVE_USR_INCLUDE_MALLOC_H +#include "/usr/include/malloc.h" +#else /* HAVE_USR_INCLUDE_MALLOC_H */ +#ifndef STRUCT_MALLINFO_DECLARED +/* HP-UX (and others?) redefines mallinfo unless _STRUCT_MALLINFO is defined */ +#define _STRUCT_MALLINFO +#define STRUCT_MALLINFO_DECLARED 1 +struct mallinfo { + MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ + MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ + MALLINFO_FIELD_TYPE smblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ + MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ + MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ + MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ + MALLINFO_FIELD_TYPE fordblks; /* total free space */ + MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ +}; +#endif /* STRUCT_MALLINFO_DECLARED */ +#endif /* HAVE_USR_INCLUDE_MALLOC_H */ +#endif /* NO_MALLINFO */ + +/* + Try to persuade compilers to inline. The most critical functions for + inlining are defined as macros, so these aren't used for them. +*/ + +#if 0 /* SDL */ +#ifndef FORCEINLINE + #if defined(__GNUC__) +#define FORCEINLINE __inline __attribute__ ((always_inline)) + #elif defined(_MSC_VER) + #define FORCEINLINE __forceinline + #endif +#endif +#endif /* SDL */ +#ifndef NOINLINE + #if defined(__GNUC__) + #define NOINLINE __attribute__ ((noinline)) + #elif defined(_MSC_VER) + #define NOINLINE __declspec(noinline) + #else + #define NOINLINE + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#if 0 /* SDL */ +#ifndef FORCEINLINE + #define FORCEINLINE inline +#endif +#endif /* SDL */ +#endif /* __cplusplus */ +#if 0 /* SDL */ +#ifndef FORCEINLINE + #define FORCEINLINE +#endif +#endif /* SDL_FORCE_INLINE */ + +#if !ONLY_MSPACES + +/* ------------------- Declarations of public routines ------------------- */ + +#ifndef USE_DL_PREFIX +#define dlcalloc calloc +#define dlfree free +#define dlmalloc malloc +#define dlmemalign memalign +#define dlposix_memalign posix_memalign +#define dlrealloc realloc +#define dlrealloc_in_place realloc_in_place +#define dlvalloc valloc +#define dlpvalloc pvalloc +#define dlmallinfo mallinfo +#define dlmallopt mallopt +#define dlmalloc_trim malloc_trim +#define dlmalloc_stats malloc_stats +#define dlmalloc_usable_size malloc_usable_size +#define dlmalloc_footprint malloc_footprint +#define dlmalloc_max_footprint malloc_max_footprint +#define dlmalloc_footprint_limit malloc_footprint_limit +#define dlmalloc_set_footprint_limit malloc_set_footprint_limit +#define dlmalloc_inspect_all malloc_inspect_all +#define dlindependent_calloc independent_calloc +#define dlindependent_comalloc independent_comalloc +#define dlbulk_free bulk_free +#endif /* USE_DL_PREFIX */ + +/* + malloc(size_t n) + Returns a pointer to a newly allocated chunk of at least n bytes, or + null if no space is available, in which case errno is set to ENOMEM + on ANSI C systems. + + If n is zero, malloc returns a minimum-sized chunk. (The minimum + size is 16 bytes on most 32bit systems, and 32 bytes on 64bit + systems.) Note that size_t is an unsigned type, so calls with + arguments that would be negative if signed are interpreted as + requests for huge amounts of space, which will often fail. The + maximum supported value of n differs across systems, but is in all + cases less than the maximum representable value of a size_t. +*/ +DLMALLOC_EXPORT void* dlmalloc(size_t); + +/* + free(void* p) + Releases the chunk of memory pointed to by p, that had been previously + allocated using malloc or a related routine such as realloc. + It has no effect if p is null. If p was not malloced or already + freed, free(p) will by default cause the current program to abort. +*/ +DLMALLOC_EXPORT void dlfree(void*); + +/* + calloc(size_t n_elements, size_t element_size); + Returns a pointer to n_elements * element_size bytes, with all locations + set to zero. +*/ +DLMALLOC_EXPORT void* dlcalloc(size_t, size_t); + +/* + realloc(void* p, size_t n) + Returns a pointer to a chunk of size n that contains the same data + as does chunk p up to the minimum of (n, p's size) bytes, or null + if no space is available. + + The returned pointer may or may not be the same as p. The algorithm + prefers extending p in most cases when possible, otherwise it + employs the equivalent of a malloc-copy-free sequence. + + If p is null, realloc is equivalent to malloc. + + If space is not available, realloc returns null, errno is set (if on + ANSI) and p is NOT freed. + + if n is for fewer bytes than already held by p, the newly unused + space is lopped off and freed if possible. realloc with a size + argument of zero (re)allocates a minimum-sized chunk. + + The old unix realloc convention of allowing the last-free'd chunk + to be used as an argument to realloc is not supported. +*/ +DLMALLOC_EXPORT void* dlrealloc(void*, size_t); + +/* + realloc_in_place(void* p, size_t n) + Resizes the space allocated for p to size n, only if this can be + done without moving p (i.e., only if there is adjacent space + available if n is greater than p's current allocated size, or n is + less than or equal to p's size). This may be used instead of plain + realloc if an alternative allocation strategy is needed upon failure + to expand space; for example, reallocation of a buffer that must be + memory-aligned or cleared. You can use realloc_in_place to trigger + these alternatives only when needed. + + Returns p if successful; otherwise null. +*/ +DLMALLOC_EXPORT void* dlrealloc_in_place(void*, size_t); + +/* + memalign(size_t alignment, size_t n); + Returns a pointer to a newly allocated chunk of n bytes, aligned + in accord with the alignment argument. + + The alignment argument should be a power of two. If the argument is + not a power of two, the nearest greater power is used. + 8-byte alignment is guaranteed by normal malloc calls, so don't + bother calling memalign with an argument of 8 or less. + + Overreliance on memalign is a sure way to fragment space. +*/ +DLMALLOC_EXPORT void* dlmemalign(size_t, size_t); + +/* + int posix_memalign(void** pp, size_t alignment, size_t n); + Allocates a chunk of n bytes, aligned in accord with the alignment + argument. Differs from memalign only in that it (1) assigns the + allocated memory to *pp rather than returning it, (2) fails and + returns EINVAL if the alignment is not a power of two (3) fails and + returns ENOMEM if memory cannot be allocated. +*/ +DLMALLOC_EXPORT int dlposix_memalign(void**, size_t, size_t); + +/* + valloc(size_t n); + Equivalent to memalign(pagesize, n), where pagesize is the page + size of the system. If the pagesize is unknown, 4096 is used. +*/ +DLMALLOC_EXPORT void* dlvalloc(size_t); + +/* + mallopt(int parameter_number, int parameter_value) + Sets tunable parameters The format is to provide a + (parameter-number, parameter-value) pair. mallopt then sets the + corresponding parameter to the argument value if it can (i.e., so + long as the value is meaningful), and returns 1 if successful else + 0. To workaround the fact that mallopt is specified to use int, + not size_t parameters, the value -1 is specially treated as the + maximum unsigned size_t value. + + SVID/XPG/ANSI defines four standard param numbers for mallopt, + normally defined in malloc.h. None of these are use in this malloc, + so setting them has no effect. But this malloc also supports other + options in mallopt. See below for details. Briefly, supported + parameters are as follows (listed defaults are for "typical" + configurations). + + Symbol param # default allowed param values + M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables) + M_GRANULARITY -2 page size any power of 2 >= page size + M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) +*/ +DLMALLOC_EXPORT int dlmallopt(int, int); + +/* + malloc_footprint(); + Returns the number of bytes obtained from the system. The total + number of bytes allocated by malloc, realloc etc., is less than this + value. Unlike mallinfo, this function returns only a precomputed + result, so can be called frequently to monitor memory consumption. + Even if locks are otherwise defined, this function does not use them, + so results might not be up to date. +*/ +DLMALLOC_EXPORT size_t dlmalloc_footprint(void); + +/* + malloc_max_footprint(); + Returns the maximum number of bytes obtained from the system. This + value will be greater than current footprint if deallocated space + has been reclaimed by the system. The peak number of bytes allocated + by malloc, realloc etc., is less than this value. Unlike mallinfo, + this function returns only a precomputed result, so can be called + frequently to monitor memory consumption. Even if locks are + otherwise defined, this function does not use them, so results might + not be up to date. +*/ +DLMALLOC_EXPORT size_t dlmalloc_max_footprint(void); + +/* + malloc_footprint_limit(); + Returns the number of bytes that the heap is allowed to obtain from + the system, returning the last value returned by + malloc_set_footprint_limit, or the maximum size_t value if + never set. The returned value reflects a permission. There is no + guarantee that this number of bytes can actually be obtained from + the system. +*/ +DLMALLOC_EXPORT size_t dlmalloc_footprint_limit(); + +/* + malloc_set_footprint_limit(); + Sets the maximum number of bytes to obtain from the system, causing + failure returns from malloc and related functions upon attempts to + exceed this value. The argument value may be subject to page + rounding to an enforceable limit; this actual value is returned. + Using an argument of the maximum possible size_t effectively + disables checks. If the argument is less than or equal to the + current malloc_footprint, then all future allocations that require + additional system memory will fail. However, invocation cannot + retroactively deallocate existing used memory. +*/ +DLMALLOC_EXPORT size_t dlmalloc_set_footprint_limit(size_t bytes); + +#if MALLOC_INSPECT_ALL +/* + malloc_inspect_all(void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg); + Traverses the heap and calls the given handler for each managed + region, skipping all bytes that are (or may be) used for bookkeeping + purposes. Traversal does not include include chunks that have been + directly memory mapped. Each reported region begins at the start + address, and continues up to but not including the end address. The + first used_bytes of the region contain allocated data. If + used_bytes is zero, the region is unallocated. The handler is + invoked with the given callback argument. If locks are defined, they + are held during the entire traversal. It is a bad idea to invoke + other malloc functions from within the handler. + + For example, to count the number of in-use chunks with size greater + than 1000, you could write: + static int count = 0; + void count_chunks(void* start, void* end, size_t used, void* arg) { + if (used >= 1000) ++count; + } + then: + malloc_inspect_all(count_chunks, NULL); + + malloc_inspect_all is compiled only if MALLOC_INSPECT_ALL is defined. +*/ +DLMALLOC_EXPORT void dlmalloc_inspect_all(void(*handler)(void*, void *, size_t, void*), + void* arg); + +#endif /* MALLOC_INSPECT_ALL */ + +#if !NO_MALLINFO +/* + mallinfo() + Returns (by copy) a struct containing various summary statistics: + + arena: current total non-mmapped bytes allocated from system + ordblks: the number of free chunks + smblks: always zero. + hblks: current number of mmapped regions + hblkhd: total bytes held in mmapped regions + usmblks: the maximum total allocated space. This will be greater + than current total if trimming has occurred. + fsmblks: always zero + uordblks: current total allocated space (normal or mmapped) + fordblks: total free space + keepcost: the maximum number of bytes that could ideally be released + back to system via malloc_trim. ("ideally" means that + it ignores page restrictions etc.) + + Because these fields are ints, but internal bookkeeping may + be kept as longs, the reported values may wrap around zero and + thus be inaccurate. +*/ +DLMALLOC_EXPORT struct mallinfo dlmallinfo(void); +#endif /* NO_MALLINFO */ + +/* + independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); + + independent_calloc is similar to calloc, but instead of returning a + single cleared space, it returns an array of pointers to n_elements + independent elements that can hold contents of size elem_size, each + of which starts out cleared, and can be independently freed, + realloc'ed etc. The elements are guaranteed to be adjacently + allocated (this is not guaranteed to occur with multiple callocs or + mallocs), which may also improve cache locality in some + applications. + + The "chunks" argument is optional (i.e., may be null, which is + probably the most typical usage). If it is null, the returned array + is itself dynamically allocated and should also be freed when it is + no longer needed. Otherwise, the chunks array must be of at least + n_elements in length. It is filled in with the pointers to the + chunks. + + In either case, independent_calloc returns this pointer array, or + null if the allocation failed. If n_elements is zero and "chunks" + is null, it returns a chunk representing an array with zero elements + (which should be freed if not wanted). + + Each element must be freed when it is no longer needed. This can be + done all at once using bulk_free. + + independent_calloc simplifies and speeds up implementations of many + kinds of pools. It may also be useful when constructing large data + structures that initially have a fixed number of fixed-sized nodes, + but the number is not known at compile time, and some of the nodes + may later need to be freed. For example: + + struct Node { int item; struct Node* next; }; + + struct Node* build_list() { + struct Node** pool; + int n = read_number_of_nodes_needed(); + if (n <= 0) return 0; + pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); + if (pool == 0) die(); + // organize into a linked list... + struct Node* first = pool[0]; + for (i = 0; i < n-1; ++i) + pool[i]->next = pool[i+1]; + free(pool); // Can now free the array (or not, if it is needed later) + return first; + } +*/ +DLMALLOC_EXPORT void** dlindependent_calloc(size_t, size_t, void**); + +/* + independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); + + independent_comalloc allocates, all at once, a set of n_elements + chunks with sizes indicated in the "sizes" array. It returns + an array of pointers to these elements, each of which can be + independently freed, realloc'ed etc. The elements are guaranteed to + be adjacently allocated (this is not guaranteed to occur with + multiple callocs or mallocs), which may also improve cache locality + in some applications. + + The "chunks" argument is optional (i.e., may be null). If it is null + the returned array is itself dynamically allocated and should also + be freed when it is no longer needed. Otherwise, the chunks array + must be of at least n_elements in length. It is filled in with the + pointers to the chunks. + + In either case, independent_comalloc returns this pointer array, or + null if the allocation failed. If n_elements is zero and chunks is + null, it returns a chunk representing an array with zero elements + (which should be freed if not wanted). + + Each element must be freed when it is no longer needed. This can be + done all at once using bulk_free. + + independent_comallac differs from independent_calloc in that each + element may have a different size, and also that it does not + automatically clear elements. + + independent_comalloc can be used to speed up allocation in cases + where several structs or objects must always be allocated at the + same time. For example: + + struct Head { ... } + struct Foot { ... } + + void send_message(char* msg) { + int msglen = strlen(msg); + size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; + void* chunks[3]; + if (independent_comalloc(3, sizes, chunks) == 0) + die(); + struct Head* head = (struct Head*)(chunks[0]); + char* body = (char*)(chunks[1]); + struct Foot* foot = (struct Foot*)(chunks[2]); + // ... + } + + In general though, independent_comalloc is worth using only for + larger values of n_elements. For small values, you probably won't + detect enough difference from series of malloc calls to bother. + + Overuse of independent_comalloc can increase overall memory usage, + since it cannot reuse existing noncontiguous small chunks that + might be available for some of the elements. +*/ +DLMALLOC_EXPORT void** dlindependent_comalloc(size_t, size_t*, void**); + +/* + bulk_free(void* array[], size_t n_elements) + Frees and clears (sets to null) each non-null pointer in the given + array. This is likely to be faster than freeing them one-by-one. + If footers are used, pointers that have been allocated in different + mspaces are not freed or cleared, and the count of all such pointers + is returned. For large arrays of pointers with poor locality, it + may be worthwhile to sort this array before calling bulk_free. +*/ +DLMALLOC_EXPORT size_t dlbulk_free(void**, size_t n_elements); + +/* + pvalloc(size_t n); + Equivalent to valloc(minimum-page-that-holds(n)), that is, + round up n to nearest pagesize. + */ +DLMALLOC_EXPORT void* dlpvalloc(size_t); + +/* + malloc_trim(size_t pad); + + If possible, gives memory back to the system (via negative arguments + to sbrk) if there is unused memory at the `high' end of the malloc + pool or in unused MMAP segments. You can call this after freeing + large blocks of memory to potentially reduce the system-level memory + requirements of a program. However, it cannot guarantee to reduce + memory. Under some allocation patterns, some large free blocks of + memory will be locked between two used chunks, so they cannot be + given back to the system. + + The `pad' argument to malloc_trim represents the amount of free + trailing space to leave untrimmed. If this argument is zero, only + the minimum amount of memory to maintain internal data structures + will be left. Non-zero arguments can be supplied to maintain enough + trailing space to service future expected allocations without having + to re-obtain memory from the system. + + Malloc_trim returns 1 if it actually released any memory, else 0. +*/ +DLMALLOC_EXPORT int dlmalloc_trim(size_t); + +/* + malloc_stats(); + Prints on stderr the amount of space obtained from the system (both + via sbrk and mmap), the maximum amount (which may be more than + current if malloc_trim and/or munmap got called), and the current + number of bytes allocated via malloc (or realloc, etc) but not yet + freed. Note that this is the number of bytes allocated, not the + number requested. It will be larger than the number requested + because of alignment and bookkeeping overhead. Because it includes + alignment wastage as being in use, this figure may be greater than + zero even when no user-level chunks are allocated. + + The reported current and maximum system memory can be inaccurate if + a program makes other calls to system memory allocation functions + (normally sbrk) outside of malloc. + + malloc_stats prints only the most commonly interesting statistics. + More information can be obtained by calling mallinfo. +*/ +DLMALLOC_EXPORT void dlmalloc_stats(void); + +/* + malloc_usable_size(void* p); + + Returns the number of bytes you can actually use in + an allocated chunk, which may be more than you requested (although + often not) due to alignment and minimum size constraints. + You can use this many bytes without worrying about + overwriting other allocated objects. This is not a particularly great + programming practice. malloc_usable_size can be more useful in + debugging and assertions, for example: + + p = malloc(n); + assert(malloc_usable_size(p) >= 256); +*/ +size_t dlmalloc_usable_size(void*); + +#endif /* ONLY_MSPACES */ + +#if MSPACES + +/* + mspace is an opaque type representing an independent + region of space that supports mspace_malloc, etc. +*/ +typedef void* mspace; + +/* + create_mspace creates and returns a new independent space with the + given initial capacity, or, if 0, the default granularity size. It + returns null if there is no system memory available to create the + space. If argument locked is non-zero, the space uses a separate + lock to control access. The capacity of the space will grow + dynamically as needed to service mspace_malloc requests. You can + control the sizes of incremental increases of this space by + compiling with a different DEFAULT_GRANULARITY or dynamically + setting with mallopt(M_GRANULARITY, value). +*/ +DLMALLOC_EXPORT mspace create_mspace(size_t capacity, int locked); + +/* + destroy_mspace destroys the given space, and attempts to return all + of its memory back to the system, returning the total number of + bytes freed. After destruction, the results of access to all memory + used by the space become undefined. +*/ +DLMALLOC_EXPORT size_t destroy_mspace(mspace msp); + +/* + create_mspace_with_base uses the memory supplied as the initial base + of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this + space is used for bookkeeping, so the capacity must be at least this + large. (Otherwise 0 is returned.) When this initial space is + exhausted, additional memory will be obtained from the system. + Destroying this space will deallocate all additionally allocated + space (if possible) but not the initial base. +*/ +DLMALLOC_EXPORT mspace create_mspace_with_base(void* base, size_t capacity, int locked); + +/* + mspace_track_large_chunks controls whether requests for large chunks + are allocated in their own untracked mmapped regions, separate from + others in this mspace. By default large chunks are not tracked, + which reduces fragmentation. However, such chunks are not + necessarily released to the system upon destroy_mspace. Enabling + tracking by setting to true may increase fragmentation, but avoids + leakage when relying on destroy_mspace to release all memory + allocated using this space. The function returns the previous + setting. +*/ +DLMALLOC_EXPORT int mspace_track_large_chunks(mspace msp, int enable); + + +/* + mspace_malloc behaves as malloc, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_malloc(mspace msp, size_t bytes); + +/* + mspace_free behaves as free, but operates within + the given space. + + If compiled with FOOTERS==1, mspace_free is not actually needed. + free may be called instead of mspace_free because freed chunks from + any space are handled by their originating spaces. +*/ +DLMALLOC_EXPORT void mspace_free(mspace msp, void* mem); + +/* + mspace_realloc behaves as realloc, but operates within + the given space. + + If compiled with FOOTERS==1, mspace_realloc is not actually + needed. realloc may be called instead of mspace_realloc because + realloced chunks from any space are handled by their originating + spaces. +*/ +DLMALLOC_EXPORT void* mspace_realloc(mspace msp, void* mem, size_t newsize); + +/* + mspace_calloc behaves as calloc, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); + +/* + mspace_memalign behaves as memalign, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_memalign(mspace msp, size_t alignment, size_t bytes); + +/* + mspace_independent_calloc behaves as independent_calloc, but + operates within the given space. +*/ +DLMALLOC_EXPORT void** mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void* chunks[]); + +/* + mspace_independent_comalloc behaves as independent_comalloc, but + operates within the given space. +*/ +DLMALLOC_EXPORT void** mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void* chunks[]); + +/* + mspace_footprint() returns the number of bytes obtained from the + system for this space. +*/ +DLMALLOC_EXPORT size_t mspace_footprint(mspace msp); + +/* + mspace_max_footprint() returns the peak number of bytes obtained from the + system for this space. +*/ +DLMALLOC_EXPORT size_t mspace_max_footprint(mspace msp); + + +#if !NO_MALLINFO +/* + mspace_mallinfo behaves as mallinfo, but reports properties of + the given space. +*/ +DLMALLOC_EXPORT struct mallinfo mspace_mallinfo(mspace msp); +#endif /* NO_MALLINFO */ + +/* + malloc_usable_size(void* p) behaves the same as malloc_usable_size; +*/ +DLMALLOC_EXPORT size_t mspace_usable_size(const void* mem); + +/* + mspace_malloc_stats behaves as malloc_stats, but reports + properties of the given space. +*/ +DLMALLOC_EXPORT void mspace_malloc_stats(mspace msp); + +/* + mspace_trim behaves as malloc_trim, but + operates within the given space. +*/ +DLMALLOC_EXPORT int mspace_trim(mspace msp, size_t pad); + +/* + An alias for mallopt. +*/ +DLMALLOC_EXPORT int mspace_mallopt(int, int); + +#endif /* MSPACES */ + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif /* __cplusplus */ + +/* + ======================================================================== + To make a fully customizable malloc.h header file, cut everything + above this line, put into file malloc.h, edit to suit, and #include it + on the next line, as well as in programs that use this malloc. + ======================================================================== +*/ + +/* #include "malloc.h" */ + +/*------------------------------ internal #includes ---------------------- */ + +#ifdef _MSC_VER +#pragma warning( disable : 4146 ) /* no "unsigned" warnings */ +#endif /* _MSC_VER */ +#if !NO_MALLOC_STATS +#include /* for printing in malloc_stats */ +#endif /* NO_MALLOC_STATS */ +#ifndef LACKS_ERRNO_H +#include /* for MALLOC_FAILURE_ACTION */ +#endif /* LACKS_ERRNO_H */ +#ifdef DEBUG +#if ABORT_ON_ASSERT_FAILURE +#undef assert +#define assert(x) if(!(x)) ABORT +#else /* ABORT_ON_ASSERT_FAILURE */ +#include +#endif /* ABORT_ON_ASSERT_FAILURE */ +#else /* DEBUG */ +#ifndef assert +#define assert(x) +#endif +#define DEBUG 0 +#endif /* DEBUG */ +#if !defined(WIN32) && !defined(LACKS_TIME_H) +#include /* for magic initialization */ +#endif /* WIN32 */ +#ifndef LACKS_STDLIB_H +#include /* for abort() */ +#endif /* LACKS_STDLIB_H */ +#ifndef LACKS_STRING_H +#include /* for memset etc */ +#endif /* LACKS_STRING_H */ +#if USE_BUILTIN_FFS +#ifndef LACKS_STRINGS_H +#include /* for ffs */ +#endif /* LACKS_STRINGS_H */ +#endif /* USE_BUILTIN_FFS */ +#if HAVE_MMAP +#ifndef LACKS_SYS_MMAN_H +/* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */ +#if (defined(linux) && !defined(__USE_GNU)) +#define __USE_GNU 1 +#include /* for mmap */ +#undef __USE_GNU +#else +#include /* for mmap */ +#endif /* linux */ +#endif /* LACKS_SYS_MMAN_H */ +#ifndef LACKS_FCNTL_H +#include +#endif /* LACKS_FCNTL_H */ +#endif /* HAVE_MMAP */ +#ifndef LACKS_UNISTD_H +#include /* for sbrk, sysconf */ +#else /* LACKS_UNISTD_H */ +#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) +extern void* sbrk(ptrdiff_t); +#endif /* FreeBSD etc */ +#endif /* LACKS_UNISTD_H */ + +/* Declarations for locking */ +#if USE_LOCKS +#ifndef WIN32 +#if defined (__SVR4) && defined (__sun) /* solaris */ +#include +#elif !defined(LACKS_SCHED_H) +#include +#endif /* solaris or LACKS_SCHED_H */ +#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) || !USE_SPIN_LOCKS +#include +#endif /* USE_RECURSIVE_LOCKS ... */ +#elif defined(_MSC_VER) +#ifndef _M_AMD64 +/* These are already defined on AMD64 builds */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ +LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp); +LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value); +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* _M_AMD64 */ +#pragma intrinsic (_InterlockedCompareExchange) +#pragma intrinsic (_InterlockedExchange) +#define interlockedcompareexchange _InterlockedCompareExchange +#define interlockedexchange _InterlockedExchange +#elif defined(WIN32) && defined(__GNUC__) +#define interlockedcompareexchange(a, b, c) __sync_val_compare_and_swap(a, c, b) +#define interlockedexchange __sync_lock_test_and_set +#endif /* Win32 */ +#else /* USE_LOCKS */ +#endif /* USE_LOCKS */ + +#ifndef LOCK_AT_FORK +#define LOCK_AT_FORK 0 +#endif + +/* Declarations for bit scanning on win32 */ +#if defined(_MSC_VER) && _MSC_VER>=1300 +#ifndef BitScanForward /* Try to avoid pulling in WinNT.h */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ +unsigned char _BitScanForward(unsigned long *index, unsigned long mask); +unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#define BitScanForward _BitScanForward +#define BitScanReverse _BitScanReverse +#pragma intrinsic(_BitScanForward) +#pragma intrinsic(_BitScanReverse) +#endif /* BitScanForward */ +#endif /* defined(_MSC_VER) && _MSC_VER>=1300 */ + +#ifndef WIN32 +#ifndef malloc_getpagesize +# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ +# ifndef _SC_PAGE_SIZE +# define _SC_PAGE_SIZE _SC_PAGESIZE +# endif +# endif +# ifdef _SC_PAGE_SIZE +# define malloc_getpagesize sysconf(_SC_PAGE_SIZE) +# else +# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) + extern int getpagesize(); +# define malloc_getpagesize getpagesize() +# else +# ifdef WIN32 /* use supplied emulation of getpagesize */ +# define malloc_getpagesize getpagesize() +# else +# ifndef LACKS_SYS_PARAM_H +# include +# endif +# ifdef EXEC_PAGESIZE +# define malloc_getpagesize EXEC_PAGESIZE +# else +# ifdef NBPG +# ifndef CLSIZE +# define malloc_getpagesize NBPG +# else +# define malloc_getpagesize (NBPG * CLSIZE) +# endif +# else +# ifdef NBPC +# define malloc_getpagesize NBPC +# else +# ifdef PAGESIZE +# define malloc_getpagesize PAGESIZE +# else /* just guess */ +# define malloc_getpagesize ((size_t)4096U) +# endif +# endif +# endif +# endif +# endif +# endif +# endif +#endif +#endif + +/* ------------------- size_t and alignment properties -------------------- */ + +/* The byte and bit size of a size_t */ +#define SIZE_T_SIZE (sizeof(size_t)) +#define SIZE_T_BITSIZE (sizeof(size_t) << 3) + +/* Some constants coerced to size_t */ +/* Annoying but necessary to avoid errors on some platforms */ +#define SIZE_T_ZERO ((size_t)0) +#define SIZE_T_ONE ((size_t)1) +#define SIZE_T_TWO ((size_t)2) +#define SIZE_T_FOUR ((size_t)4) +#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1) +#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2) +#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES) +#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U) + +/* The bit mask value corresponding to MALLOC_ALIGNMENT */ +#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE) + +/* True if address a has acceptable alignment */ +#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0) + +/* the number of bytes to offset an address to align it */ +#define align_offset(A)\ + ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\ + ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK)) + +/* -------------------------- MMAP preliminaries ------------------------- */ + +/* + If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and + checks to fail so compiler optimizer can delete code rather than + using so many "#if"s. +*/ + + +/* MORECORE and MMAP must return MFAIL on failure */ +#define MFAIL ((void*)(MAX_SIZE_T)) +#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */ + +#if HAVE_MMAP + +#ifndef WIN32 +#define MUNMAP_DEFAULT(a, s) munmap((a), (s)) +#define MMAP_PROT (PROT_READ|PROT_WRITE) +#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) +#define MAP_ANONYMOUS MAP_ANON +#endif /* MAP_ANON */ +#ifdef MAP_ANONYMOUS +#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS) +#define MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0) +#else /* MAP_ANONYMOUS */ +/* + Nearly all versions of mmap support MAP_ANONYMOUS, so the following + is unlikely to be needed, but is supplied just in case. +*/ +#define MMAP_FLAGS (MAP_PRIVATE) +static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ +#define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \ + (dev_zero_fd = open("/dev/zero", O_RDWR), \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) +#endif /* MAP_ANONYMOUS */ + +#define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s) + +#else /* WIN32 */ + +/* Win32 MMAP via VirtualAlloc */ +SDL_FORCE_INLINE void* win32mmap(size_t size) { + void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); + return (ptr != 0)? ptr: MFAIL; +} + +/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ +SDL_FORCE_INLINE void* win32direct_mmap(size_t size) { + void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, + PAGE_READWRITE); + return (ptr != 0)? ptr: MFAIL; +} + +/* This function supports releasing coalesed segments */ +SDL_FORCE_INLINE int win32munmap(void* ptr, size_t size) { + MEMORY_BASIC_INFORMATION minfo; + char* cptr = (char*)ptr; + while (size) { + if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) + return -1; + if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || + minfo.State != MEM_COMMIT || minfo.RegionSize > size) + return -1; + if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) + return -1; + cptr += minfo.RegionSize; + size -= minfo.RegionSize; + } + return 0; +} + +#define MMAP_DEFAULT(s) win32mmap(s) +#define MUNMAP_DEFAULT(a, s) win32munmap((a), (s)) +#define DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s) +#endif /* WIN32 */ +#endif /* HAVE_MMAP */ + +#if HAVE_MREMAP +#ifndef WIN32 +#define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv)) +#endif /* WIN32 */ +#endif /* HAVE_MREMAP */ + +/** + * Define CALL_MORECORE + */ +#if HAVE_MORECORE + #ifdef MORECORE + #define CALL_MORECORE(S) MORECORE(S) + #else /* MORECORE */ + #define CALL_MORECORE(S) MORECORE_DEFAULT(S) + #endif /* MORECORE */ +#else /* HAVE_MORECORE */ + #define CALL_MORECORE(S) MFAIL +#endif /* HAVE_MORECORE */ + +/** + * Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP + */ +#if HAVE_MMAP + #define USE_MMAP_BIT (SIZE_T_ONE) + + #ifdef MMAP + #define CALL_MMAP(s) MMAP(s) + #else /* MMAP */ + #define CALL_MMAP(s) MMAP_DEFAULT(s) + #endif /* MMAP */ + #ifdef MUNMAP + #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) + #else /* MUNMAP */ + #define CALL_MUNMAP(a, s) MUNMAP_DEFAULT((a), (s)) + #endif /* MUNMAP */ + #ifdef DIRECT_MMAP + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) + #else /* DIRECT_MMAP */ + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s) + #endif /* DIRECT_MMAP */ +#else /* HAVE_MMAP */ + #define USE_MMAP_BIT (SIZE_T_ZERO) + + #define MMAP(s) MFAIL + #define MUNMAP(a, s) (-1) + #define DIRECT_MMAP(s) MFAIL + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) + #define CALL_MMAP(s) MMAP(s) + #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) +#endif /* HAVE_MMAP */ + +/** + * Define CALL_MREMAP + */ +#if HAVE_MMAP && HAVE_MREMAP + #ifdef MREMAP + #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv)) + #else /* MREMAP */ + #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv)) + #endif /* MREMAP */ +#else /* HAVE_MMAP && HAVE_MREMAP */ + #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL +#endif /* HAVE_MMAP && HAVE_MREMAP */ + +/* mstate bit set if continguous morecore disabled or failed */ +#define USE_NONCONTIGUOUS_BIT (4U) + +/* segment bit set in create_mspace_with_base */ +#define EXTERN_BIT (8U) + + +/* --------------------------- Lock preliminaries ------------------------ */ + +/* + When locks are defined, there is one global lock, plus + one per-mspace lock. + + The global lock_ensures that mparams.magic and other unique + mparams values are initialized only once. It also protects + sequences of calls to MORECORE. In many cases sys_alloc requires + two calls, that should not be interleaved with calls by other + threads. This does not protect against direct calls to MORECORE + by other threads not using this lock, so there is still code to + cope the best we can on interference. + + Per-mspace locks surround calls to malloc, free, etc. + By default, locks are simple non-reentrant mutexes. + + Because lock-protected regions generally have bounded times, it is + OK to use the supplied simple spinlocks. Spinlocks are likely to + improve performance for lightly contended applications, but worsen + performance under heavy contention. + + If USE_LOCKS is > 1, the definitions of lock routines here are + bypassed, in which case you will need to define the type MLOCK_T, + and at least INITIAL_LOCK, DESTROY_LOCK, ACQUIRE_LOCK, RELEASE_LOCK + and TRY_LOCK. You must also declare a + static MLOCK_T malloc_global_mutex = { initialization values };. + +*/ + +#if !USE_LOCKS +#define USE_LOCK_BIT (0U) +#define INITIAL_LOCK(l) (0) +#define DESTROY_LOCK(l) (0) +#define ACQUIRE_MALLOC_GLOBAL_LOCK() +#define RELEASE_MALLOC_GLOBAL_LOCK() + +#else +#if USE_LOCKS > 1 +/* ----------------------- User-defined locks ------------------------ */ +/* Define your own lock implementation here */ +/* #define INITIAL_LOCK(lk) ... */ +/* #define DESTROY_LOCK(lk) ... */ +/* #define ACQUIRE_LOCK(lk) ... */ +/* #define RELEASE_LOCK(lk) ... */ +/* #define TRY_LOCK(lk) ... */ +/* static MLOCK_T malloc_global_mutex = ... */ + +#elif USE_SPIN_LOCKS + +/* First, define CAS_LOCK and CLEAR_LOCK on ints */ +/* Note CAS_LOCK defined to return 0 on success */ + +#if defined(__GNUC__)&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) +#define CAS_LOCK(sl) __sync_lock_test_and_set(sl, 1) +#define CLEAR_LOCK(sl) __sync_lock_release(sl) + +#elif (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))) +/* Custom spin locks for older gcc on x86 */ +SDL_FORCE_INLINE int x86_cas_lock(int *sl) { + int ret; + int val = 1; + int cmp = 0; + __asm__ __volatile__ ("lock; cmpxchgl %1, %2" + : "=a" (ret) + : "r" (val), "m" (*(sl)), "0"(cmp) + : "memory", "cc"); + return ret; +} + +SDL_FORCE_INLINE void x86_clear_lock(int* sl) { + assert(*sl != 0); + int prev = 0; + int ret; + __asm__ __volatile__ ("lock; xchgl %0, %1" + : "=r" (ret) + : "m" (*(sl)), "0"(prev) + : "memory"); +} + +#define CAS_LOCK(sl) x86_cas_lock(sl) +#define CLEAR_LOCK(sl) x86_clear_lock(sl) + +#else /* Win32 MSC */ +#define CAS_LOCK(sl) interlockedexchange(sl, (LONG)1) +#define CLEAR_LOCK(sl) interlockedexchange (sl, (LONG)0) + +#endif /* ... gcc spins locks ... */ + +/* How to yield for a spin lock */ +#define SPINS_PER_YIELD 63 +#if defined(_MSC_VER) +#define SLEEP_EX_DURATION 50 /* delay for yield/sleep */ +#define SPIN_LOCK_YIELD SleepEx(SLEEP_EX_DURATION, FALSE) +#elif defined (__SVR4) && defined (__sun) /* solaris */ +#define SPIN_LOCK_YIELD thr_yield(); +#elif !defined(LACKS_SCHED_H) +#define SPIN_LOCK_YIELD sched_yield(); +#else +#define SPIN_LOCK_YIELD +#endif /* ... yield ... */ + +#if !defined(USE_RECURSIVE_LOCKS) || USE_RECURSIVE_LOCKS == 0 +/* Plain spin locks use single word (embedded in malloc_states) */ +static int spin_acquire_lock(volatile long *sl) { + int spins = 0; + while (*sl != 0 || CAS_LOCK(sl)) { + if ((++spins & SPINS_PER_YIELD) == 0) { + SPIN_LOCK_YIELD; + } + } + return 0; +} + +#define MLOCK_T volatile long +#define TRY_LOCK(sl) !CAS_LOCK(sl) +#define RELEASE_LOCK(sl) CLEAR_LOCK(sl) +#define ACQUIRE_LOCK(sl) (CAS_LOCK(sl)? spin_acquire_lock(sl) : 0) +#define INITIAL_LOCK(sl) (*sl = 0) +#define DESTROY_LOCK(sl) (0) +static MLOCK_T malloc_global_mutex = 0; + +#else /* USE_RECURSIVE_LOCKS */ +/* types for lock owners */ +#ifdef WIN32 +#define THREAD_ID_T DWORD +#define CURRENT_THREAD GetCurrentThreadId() +#define EQ_OWNER(X,Y) ((X) == (Y)) +#else +/* + Note: the following assume that pthread_t is a type that can be + initialized to (casted) zero. If this is not the case, you will need to + somehow redefine these or not use spin locks. +*/ +#define THREAD_ID_T pthread_t +#define CURRENT_THREAD pthread_self() +#define EQ_OWNER(X,Y) pthread_equal(X, Y) +#endif + +struct malloc_recursive_lock { + int sl; + unsigned int c; + THREAD_ID_T threadid; +}; + +#define MLOCK_T struct malloc_recursive_lock +static MLOCK_T malloc_global_mutex = { 0, 0, (THREAD_ID_T)0}; + +SDL_FORCE_INLINE void recursive_release_lock(MLOCK_T *lk) { + assert(lk->sl != 0); + if (--lk->c == 0) { + CLEAR_LOCK(&lk->sl); + } +} + +SDL_FORCE_INLINE int recursive_acquire_lock(MLOCK_T *lk) { + THREAD_ID_T mythreadid = CURRENT_THREAD; + int spins = 0; + for (;;) { + if (*((volatile int *)(&lk->sl)) == 0) { + if (!CAS_LOCK(&lk->sl)) { + lk->threadid = mythreadid; + lk->c = 1; + return 0; + } + } + else if (EQ_OWNER(lk->threadid, mythreadid)) { + ++lk->c; + return 0; + } + if ((++spins & SPINS_PER_YIELD) == 0) { + SPIN_LOCK_YIELD; + } + } +} + +SDL_FORCE_INLINE int recursive_try_lock(MLOCK_T *lk) { + THREAD_ID_T mythreadid = CURRENT_THREAD; + if (*((volatile int *)(&lk->sl)) == 0) { + if (!CAS_LOCK(&lk->sl)) { + lk->threadid = mythreadid; + lk->c = 1; + return 1; + } + } + else if (EQ_OWNER(lk->threadid, mythreadid)) { + ++lk->c; + return 1; + } + return 0; +} + +#define RELEASE_LOCK(lk) recursive_release_lock(lk) +#define TRY_LOCK(lk) recursive_try_lock(lk) +#define ACQUIRE_LOCK(lk) recursive_acquire_lock(lk) +#define INITIAL_LOCK(lk) ((lk)->threadid = (THREAD_ID_T)0, (lk)->sl = 0, (lk)->c = 0) +#define DESTROY_LOCK(lk) (0) +#endif /* USE_RECURSIVE_LOCKS */ + +#elif defined(WIN32) /* Win32 critical sections */ +#define MLOCK_T CRITICAL_SECTION +#define ACQUIRE_LOCK(lk) (EnterCriticalSection(lk), 0) +#define RELEASE_LOCK(lk) LeaveCriticalSection(lk) +#define TRY_LOCK(lk) TryEnterCriticalSection(lk) +#define INITIAL_LOCK(lk) (!InitializeCriticalSectionAndSpinCount((lk), 0x80000000|4000)) +#define DESTROY_LOCK(lk) (DeleteCriticalSection(lk), 0) +#define NEED_GLOBAL_LOCK_INIT + +static MLOCK_T malloc_global_mutex; +static volatile LONG malloc_global_mutex_status; + +/* Use spin loop to initialize global lock */ +static void init_malloc_global_mutex() { + for (;;) { + long stat = malloc_global_mutex_status; + if (stat > 0) + return; + /* transition to < 0 while initializing, then to > 0) */ + if (stat == 0 && + interlockedcompareexchange(&malloc_global_mutex_status, (LONG)-1, (LONG)0) == 0) { + InitializeCriticalSection(&malloc_global_mutex); + interlockedexchange(&malloc_global_mutex_status, (LONG)1); + return; + } + SleepEx(0, FALSE); + } +} + +#else /* pthreads-based locks */ +#define MLOCK_T pthread_mutex_t +#define ACQUIRE_LOCK(lk) pthread_mutex_lock(lk) +#define RELEASE_LOCK(lk) pthread_mutex_unlock(lk) +#define TRY_LOCK(lk) (!pthread_mutex_trylock(lk)) +#define INITIAL_LOCK(lk) pthread_init_lock(lk) +#define DESTROY_LOCK(lk) pthread_mutex_destroy(lk) + +#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 && defined(linux) && !defined(PTHREAD_MUTEX_RECURSIVE) +/* Cope with old-style linux recursive lock initialization by adding */ +/* skipped internal declaration from pthread.h */ +extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t *__attr, + int __kind)); +#define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP +#define pthread_mutexattr_settype(x,y) pthread_mutexattr_setkind_np(x,y) +#endif /* USE_RECURSIVE_LOCKS ... */ + +static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER; + +static int pthread_init_lock (MLOCK_T *lk) { + pthread_mutexattr_t attr; + if (pthread_mutexattr_init(&attr)) return 1; +#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 + if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1; +#endif + if (pthread_mutex_init(lk, &attr)) return 1; + if (pthread_mutexattr_destroy(&attr)) return 1; + return 0; +} + +#endif /* ... lock types ... */ + +/* Common code for all lock types */ +#define USE_LOCK_BIT (2U) + +#ifndef ACQUIRE_MALLOC_GLOBAL_LOCK +#define ACQUIRE_MALLOC_GLOBAL_LOCK() ACQUIRE_LOCK(&malloc_global_mutex); +#endif + +#ifndef RELEASE_MALLOC_GLOBAL_LOCK +#define RELEASE_MALLOC_GLOBAL_LOCK() RELEASE_LOCK(&malloc_global_mutex); +#endif + +#endif /* USE_LOCKS */ + +/* ----------------------- Chunk representations ------------------------ */ + +/* + (The following includes lightly edited explanations by Colin Plumb.) + + The malloc_chunk declaration below is misleading (but accurate and + necessary). It declares a "view" into memory allowing access to + necessary fields at known offsets from a given base. + + Chunks of memory are maintained using a `boundary tag' method as + originally described by Knuth. (See the paper by Paul Wilson + ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such + techniques.) Sizes of free chunks are stored both in the front of + each chunk and at the end. This makes consolidating fragmented + chunks into bigger chunks fast. The head fields also hold bits + representing whether chunks are free or in use. + + Here are some pictures to make it clearer. They are "exploded" to + show that the state of a chunk can be thought of as extending from + the high 31 bits of the head field of its header through the + prev_foot and PINUSE_BIT bit of the following chunk header. + + A chunk that's in use looks like: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk (if P = 0) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| + | Size of this chunk 1| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | | + +- -+ + | | + +- -+ + | : + +- size - sizeof(size_t) available payload bytes -+ + : | + chunk-> +- -+ + | | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1| + | Size of next chunk (may or may not be in use) | +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + And if it's free, it looks like this: + + chunk-> +- -+ + | User payload (must be in use, or we would have merged!) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| + | Size of this chunk 0| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Next pointer | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Prev pointer | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | : + +- size - sizeof(struct chunk) unused bytes -+ + : | + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of this chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0| + | Size of next chunk (must be in use, or we would have merged)| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | : + +- User payload -+ + : | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |0| + +-+ + Note that since we always merge adjacent free chunks, the chunks + adjacent to a free chunk must be in use. + + Given a pointer to a chunk (which can be derived trivially from the + payload pointer) we can, in O(1) time, find out whether the adjacent + chunks are free, and if so, unlink them from the lists that they + are on and merge them with the current chunk. + + Chunks always begin on even word boundaries, so the mem portion + (which is returned to the user) is also on an even word boundary, and + thus at least double-word aligned. + + The P (PINUSE_BIT) bit, stored in the unused low-order bit of the + chunk size (which is always a multiple of two words), is an in-use + bit for the *previous* chunk. If that bit is *clear*, then the + word before the current chunk size contains the previous chunk + size, and can be used to find the front of the previous chunk. + The very first chunk allocated always has this bit set, preventing + access to non-existent (or non-owned) memory. If pinuse is set for + any given chunk, then you CANNOT determine the size of the + previous chunk, and might even get a memory addressing fault when + trying to do so. + + The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of + the chunk size redundantly records whether the current chunk is + inuse (unless the chunk is mmapped). This redundancy enables usage + checks within free and realloc, and reduces indirection when freeing + and consolidating chunks. + + Each freshly allocated chunk must have both cinuse and pinuse set. + That is, each allocated chunk borders either a previously allocated + and still in-use chunk, or the base of its memory arena. This is + ensured by making all allocations from the `lowest' part of any + found chunk. Further, no free chunk physically borders another one, + so each free chunk is known to be preceded and followed by either + inuse chunks or the ends of memory. + + Note that the `foot' of the current chunk is actually represented + as the prev_foot of the NEXT chunk. This makes it easier to + deal with alignments etc but can be very confusing when trying + to extend or adapt this code. + + The exceptions to all this are + + 1. The special chunk `top' is the top-most available chunk (i.e., + the one bordering the end of available memory). It is treated + specially. Top is never included in any bin, is used only if + no other chunk is available, and is released back to the + system if it is very large (see M_TRIM_THRESHOLD). In effect, + the top chunk is treated as larger (and thus less well + fitting) than any other available chunk. The top chunk + doesn't update its trailing size field since there is no next + contiguous chunk that would have to index off it. However, + space is still allocated for it (TOP_FOOT_SIZE) to enable + separation or merging when space is extended. + + 3. Chunks allocated via mmap, have both cinuse and pinuse bits + cleared in their head fields. Because they are allocated + one-by-one, each must carry its own prev_foot field, which is + also used to hold the offset this chunk has within its mmapped + region, which is needed to preserve alignment. Each mmapped + chunk is trailed by the first two fields of a fake next-chunk + for sake of usage checks. + +*/ + +struct malloc_chunk { + size_t prev_foot; /* Size of previous chunk (if free). */ + size_t head; /* Size and inuse bits. */ + struct malloc_chunk* fd; /* double links -- used only if free. */ + struct malloc_chunk* bk; +}; + +typedef struct malloc_chunk mchunk; +typedef struct malloc_chunk* mchunkptr; +typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */ +typedef unsigned int bindex_t; /* Described below */ +typedef unsigned int binmap_t; /* Described below */ +typedef unsigned int flag_t; /* The type of various bit flag sets */ + +/* ------------------- Chunks sizes and alignments ----------------------- */ + +#define MCHUNK_SIZE (sizeof(mchunk)) + +#if FOOTERS +#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +#else /* FOOTERS */ +#define CHUNK_OVERHEAD (SIZE_T_SIZE) +#endif /* FOOTERS */ + +/* MMapped chunks need a second word of overhead ... */ +#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +/* ... and additional padding for fake next-chunk at foot */ +#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES) + +/* The smallest size we can malloc is an aligned minimal chunk */ +#define MIN_CHUNK_SIZE\ + ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + +/* conversion from malloc headers to user pointers, and back */ +#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES)) +#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES)) +/* chunk associated with aligned address A */ +#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A))) + +/* Bounds on request (not chunk) sizes. */ +#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2) +#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE) + +/* pad request bytes into a usable size */ +#define pad_request(req) \ + (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + +/* pad request, checking for minimum (but not maximum) */ +#define request2size(req) \ + (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req)) + + +/* ------------------ Operations on head and foot fields ----------------- */ + +/* + The head field of a chunk is or'ed with PINUSE_BIT when previous + adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in + use, unless mmapped, in which case both bits are cleared. + + FLAG4_BIT is not used by this malloc, but might be useful in extensions. +*/ + +#define PINUSE_BIT (SIZE_T_ONE) +#define CINUSE_BIT (SIZE_T_TWO) +#define FLAG4_BIT (SIZE_T_FOUR) +#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT) +#define FLAG_BITS (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT) + +/* Head value for fenceposts */ +#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE) + +/* extraction of fields from head words */ +#define cinuse(p) ((p)->head & CINUSE_BIT) +#define pinuse(p) ((p)->head & PINUSE_BIT) +#define flag4inuse(p) ((p)->head & FLAG4_BIT) +#define is_inuse(p) (((p)->head & INUSE_BITS) != PINUSE_BIT) +#define is_mmapped(p) (((p)->head & INUSE_BITS) == 0) + +#define chunksize(p) ((p)->head & ~(FLAG_BITS)) + +#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT) +#define set_flag4(p) ((p)->head |= FLAG4_BIT) +#define clear_flag4(p) ((p)->head &= ~FLAG4_BIT) + +/* Treat space at ptr +/- offset as a chunk */ +#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s))) +#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s))) + +/* Ptr to next or previous physical malloc_chunk. */ +#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS))) +#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) )) + +/* extract next chunk's pinuse bit */ +#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT) + +/* Get/set size at footer */ +#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot) +#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s)) + +/* Set size, pinuse bit, and foot */ +#define set_size_and_pinuse_of_free_chunk(p, s)\ + ((p)->head = (s|PINUSE_BIT), set_foot(p, s)) + +/* Set size, pinuse bit, foot, and clear next pinuse */ +#define set_free_with_pinuse(p, s, n)\ + (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s)) + +/* Get the internal overhead associated with chunk p */ +#define overhead_for(p)\ + (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD) + +/* Return true if malloced space is not necessarily cleared */ +#if MMAP_CLEARS +#define calloc_must_clear(p) (!is_mmapped(p)) +#else /* MMAP_CLEARS */ +#define calloc_must_clear(p) (1) +#endif /* MMAP_CLEARS */ + +/* ---------------------- Overlaid data structures ----------------------- */ + +/* + When chunks are not in use, they are treated as nodes of either + lists or trees. + + "Small" chunks are stored in circular doubly-linked lists, and look + like this: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `head:' | Size of chunk, in bytes |P| + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Forward pointer to next chunk in list | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Back pointer to previous chunk in list | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Unused space (may be 0 bytes long) . + . . + . | +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `foot:' | Size of chunk, in bytes | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Larger chunks are kept in a form of bitwise digital trees (aka + tries) keyed on chunksizes. Because malloc_tree_chunks are only for + free chunks greater than 256 bytes, their size doesn't impose any + constraints on user chunk sizes. Each node looks like: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `head:' | Size of chunk, in bytes |P| + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Forward pointer to next chunk of same size | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Back pointer to previous chunk of same size | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to left child (child[0]) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to right child (child[1]) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to parent | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | bin index of this chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Unused space . + . | +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `foot:' | Size of chunk, in bytes | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Each tree holding treenodes is a tree of unique chunk sizes. Chunks + of the same size are arranged in a circularly-linked list, with only + the oldest chunk (the next to be used, in our FIFO ordering) + actually in the tree. (Tree members are distinguished by a non-null + parent pointer.) If a chunk with the same size an an existing node + is inserted, it is linked off the existing node using pointers that + work in the same way as fd/bk pointers of small chunks. + + Each tree contains a power of 2 sized range of chunk sizes (the + smallest is 0x100 <= x < 0x180), which is is divided in half at each + tree level, with the chunks in the smaller half of the range (0x100 + <= x < 0x140 for the top nose) in the left subtree and the larger + half (0x140 <= x < 0x180) in the right subtree. This is, of course, + done by inspecting individual bits. + + Using these rules, each node's left subtree contains all smaller + sizes than its right subtree. However, the node at the root of each + subtree has no particular ordering relationship to either. (The + dividing line between the subtree sizes is based on trie relation.) + If we remove the last chunk of a given size from the interior of the + tree, we need to replace it with a leaf node. The tree ordering + rules permit a node to be replaced by any leaf below it. + + The smallest chunk in a tree (a common operation in a best-fit + allocator) can be found by walking a path to the leftmost leaf in + the tree. Unlike a usual binary tree, where we follow left child + pointers until we reach a null, here we follow the right child + pointer any time the left one is null, until we reach a leaf with + both child pointers null. The smallest chunk in the tree will be + somewhere along that path. + + The worst case number of steps to add, find, or remove a node is + bounded by the number of bits differentiating chunks within + bins. Under current bin calculations, this ranges from 6 up to 21 + (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case + is of course much better. +*/ + +struct malloc_tree_chunk { + /* The first four fields must be compatible with malloc_chunk */ + size_t prev_foot; + size_t head; + struct malloc_tree_chunk* fd; + struct malloc_tree_chunk* bk; + + struct malloc_tree_chunk* child[2]; + struct malloc_tree_chunk* parent; + bindex_t index; +}; + +typedef struct malloc_tree_chunk tchunk; +typedef struct malloc_tree_chunk* tchunkptr; +typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */ + +/* A little helper macro for trees */ +#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1]) + +/* ----------------------------- Segments -------------------------------- */ + +/* + Each malloc space may include non-contiguous segments, held in a + list headed by an embedded malloc_segment record representing the + top-most space. Segments also include flags holding properties of + the space. Large chunks that are directly allocated by mmap are not + included in this list. They are instead independently created and + destroyed without otherwise keeping track of them. + + Segment management mainly comes into play for spaces allocated by + MMAP. Any call to MMAP might or might not return memory that is + adjacent to an existing segment. MORECORE normally contiguously + extends the current space, so this space is almost always adjacent, + which is simpler and faster to deal with. (This is why MORECORE is + used preferentially to MMAP when both are available -- see + sys_alloc.) When allocating using MMAP, we don't use any of the + hinting mechanisms (inconsistently) supported in various + implementations of unix mmap, or distinguish reserving from + committing memory. Instead, we just ask for space, and exploit + contiguity when we get it. It is probably possible to do + better than this on some systems, but no general scheme seems + to be significantly better. + + Management entails a simpler variant of the consolidation scheme + used for chunks to reduce fragmentation -- new adjacent memory is + normally prepended or appended to an existing segment. However, + there are limitations compared to chunk consolidation that mostly + reflect the fact that segment processing is relatively infrequent + (occurring only when getting memory from system) and that we + don't expect to have huge numbers of segments: + + * Segments are not indexed, so traversal requires linear scans. (It + would be possible to index these, but is not worth the extra + overhead and complexity for most programs on most platforms.) + * New segments are only appended to old ones when holding top-most + memory; if they cannot be prepended to others, they are held in + different segments. + + Except for the top-most segment of an mstate, each segment record + is kept at the tail of its segment. Segments are added by pushing + segment records onto the list headed by &mstate.seg for the + containing mstate. + + Segment flags control allocation/merge/deallocation policies: + * If EXTERN_BIT set, then we did not allocate this segment, + and so should not try to deallocate or merge with others. + (This currently holds only for the initial segment passed + into create_mspace_with_base.) + * If USE_MMAP_BIT set, the segment may be merged with + other surrounding mmapped segments and trimmed/de-allocated + using munmap. + * If neither bit is set, then the segment was obtained using + MORECORE so can be merged with surrounding MORECORE'd segments + and deallocated/trimmed using MORECORE with negative arguments. +*/ + +struct malloc_segment { + char* base; /* base address */ + size_t size; /* allocated size */ + struct malloc_segment* next; /* ptr to next segment */ + flag_t sflags; /* mmap and extern flag */ +}; + +#define is_mmapped_segment(S) ((S)->sflags & USE_MMAP_BIT) +#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT) + +typedef struct malloc_segment msegment; +typedef struct malloc_segment* msegmentptr; + +/* ---------------------------- malloc_state ----------------------------- */ + +/* + A malloc_state holds all of the bookkeeping for a space. + The main fields are: + + Top + The topmost chunk of the currently active segment. Its size is + cached in topsize. The actual size of topmost space is + topsize+TOP_FOOT_SIZE, which includes space reserved for adding + fenceposts and segment records if necessary when getting more + space from the system. The size at which to autotrim top is + cached from mparams in trim_check, except that it is disabled if + an autotrim fails. + + Designated victim (dv) + This is the preferred chunk for servicing small requests that + don't have exact fits. It is normally the chunk split off most + recently to service another small request. Its size is cached in + dvsize. The link fields of this chunk are not maintained since it + is not kept in a bin. + + SmallBins + An array of bin headers for free chunks. These bins hold chunks + with sizes less than MIN_LARGE_SIZE bytes. Each bin contains + chunks of all the same size, spaced 8 bytes apart. To simplify + use in double-linked lists, each bin header acts as a malloc_chunk + pointing to the real first node, if it exists (else pointing to + itself). This avoids special-casing for headers. But to avoid + waste, we allocate only the fd/bk pointers of bins, and then use + repositioning tricks to treat these as the fields of a chunk. + + TreeBins + Treebins are pointers to the roots of trees holding a range of + sizes. There are 2 equally spaced treebins for each power of two + from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything + larger. + + Bin maps + There is one bit map for small bins ("smallmap") and one for + treebins ("treemap). Each bin sets its bit when non-empty, and + clears the bit when empty. Bit operations are then used to avoid + bin-by-bin searching -- nearly all "search" is done without ever + looking at bins that won't be selected. The bit maps + conservatively use 32 bits per map word, even if on 64bit system. + For a good description of some of the bit-based techniques used + here, see Henry S. Warren Jr's book "Hacker's Delight" (and + supplement at http://hackersdelight.org/). Many of these are + intended to reduce the branchiness of paths through malloc etc, as + well as to reduce the number of memory locations read or written. + + Segments + A list of segments headed by an embedded malloc_segment record + representing the initial space. + + Address check support + The least_addr field is the least address ever obtained from + MORECORE or MMAP. Attempted frees and reallocs of any address less + than this are trapped (unless INSECURE is defined). + + Magic tag + A cross-check field that should always hold same value as mparams.magic. + + Max allowed footprint + The maximum allowed bytes to allocate from system (zero means no limit) + + Flags + Bits recording whether to use MMAP, locks, or contiguous MORECORE + + Statistics + Each space keeps track of current and maximum system memory + obtained via MORECORE or MMAP. + + Trim support + Fields holding the amount of unused topmost memory that should trigger + trimming, and a counter to force periodic scanning to release unused + non-topmost segments. + + Locking + If USE_LOCKS is defined, the "mutex" lock is acquired and released + around every public call using this mspace. + + Extension support + A void* pointer and a size_t field that can be used to help implement + extensions to this malloc. +*/ + +/* Bin types, widths and sizes */ +#define NSMALLBINS (32U) +#define NTREEBINS (32U) +#define SMALLBIN_SHIFT (3U) +#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT) +#define TREEBIN_SHIFT (8U) +#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT) +#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE) +#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD) + +struct malloc_state { + binmap_t smallmap; + binmap_t treemap; + size_t dvsize; + size_t topsize; + char* least_addr; + mchunkptr dv; + mchunkptr top; + size_t trim_check; + size_t release_checks; + size_t magic; + mchunkptr smallbins[(NSMALLBINS+1)*2]; + tbinptr treebins[NTREEBINS]; + size_t footprint; + size_t max_footprint; + size_t footprint_limit; /* zero means no limit */ + flag_t mflags; +#if USE_LOCKS + MLOCK_T mutex; /* locate lock among fields that rarely change */ +#endif /* USE_LOCKS */ + msegment seg; + void* extp; /* Unused but available for extensions */ + size_t exts; +}; + +typedef struct malloc_state* mstate; + +/* ------------- Global malloc_state and malloc_params ------------------- */ + +/* + malloc_params holds global properties, including those that can be + dynamically set using mallopt. There is a single instance, mparams, + initialized in init_mparams. Note that the non-zeroness of "magic" + also serves as an initialization flag. +*/ + +struct malloc_params { + size_t magic; + size_t page_size; + size_t granularity; + size_t mmap_threshold; + size_t trim_threshold; + flag_t default_mflags; +}; + +static struct malloc_params mparams; + +/* Ensure mparams initialized */ +#define ensure_initialization() (void)(mparams.magic != 0 || init_mparams()) + +#if !ONLY_MSPACES + +/* The global malloc_state used for all non-"mspace" calls */ +static struct malloc_state _gm_; +#define gm (&_gm_) +#define is_global(M) ((M) == &_gm_) + +#endif /* !ONLY_MSPACES */ + +#define is_initialized(M) ((M)->top != 0) + +/* -------------------------- system alloc setup ------------------------- */ + +/* Operations on mflags */ + +#define use_lock(M) ((M)->mflags & USE_LOCK_BIT) +#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT) +#if USE_LOCKS +#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT) +#else +#define disable_lock(M) +#endif + +#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT) +#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT) +#if HAVE_MMAP +#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT) +#else +#define disable_mmap(M) +#endif + +#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT) +#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT) + +#define set_lock(M,L)\ + ((M)->mflags = (L)?\ + ((M)->mflags | USE_LOCK_BIT) :\ + ((M)->mflags & ~USE_LOCK_BIT)) + +/* page-align a size */ +#define page_align(S)\ + (((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE)) + +/* granularity-align a size */ +#define granularity_align(S)\ + (((S) + (mparams.granularity - SIZE_T_ONE))\ + & ~(mparams.granularity - SIZE_T_ONE)) + + +/* For mmap, use granularity alignment on windows, else page-align */ +#ifdef WIN32 +#define mmap_align(S) granularity_align(S) +#else +#define mmap_align(S) page_align(S) +#endif + +/* For sys_alloc, enough padding to ensure can malloc request on success */ +#define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT) + +#define is_page_aligned(S)\ + (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0) +#define is_granularity_aligned(S)\ + (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0) + +/* True if segment S holds address A */ +#define segment_holds(S, A)\ + ((char*)(A) >= S->base && (char*)(A) < S->base + S->size) + +/* Return segment holding given address */ +static msegmentptr segment_holding(mstate m, char* addr) { + msegmentptr sp = &m->seg; + for (;;) { + if (addr >= sp->base && addr < sp->base + sp->size) + return sp; + if ((sp = sp->next) == 0) + return 0; + } +} + +/* Return true if segment contains a segment link */ +static int has_segment_link(mstate m, msegmentptr ss) { + msegmentptr sp = &m->seg; + for (;;) { + if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size) + return 1; + if ((sp = sp->next) == 0) + return 0; + } +} + +#ifndef MORECORE_CANNOT_TRIM +#define should_trim(M,s) ((s) > (M)->trim_check) +#else /* MORECORE_CANNOT_TRIM */ +#define should_trim(M,s) (0) +#endif /* MORECORE_CANNOT_TRIM */ + +/* + TOP_FOOT_SIZE is padding at the end of a segment, including space + that may be needed to place segment records and fenceposts when new + noncontiguous segments are added. +*/ +#define TOP_FOOT_SIZE\ + (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE) + + +/* ------------------------------- Hooks -------------------------------- */ + +/* + PREACTION should be defined to return 0 on success, and nonzero on + failure. If you are not using locking, you can redefine these to do + anything you like. +*/ + +#if USE_LOCKS +#define PREACTION(M) ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0) +#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); } +#else /* USE_LOCKS */ + +#ifndef PREACTION +#define PREACTION(M) (0) +#endif /* PREACTION */ + +#ifndef POSTACTION +#define POSTACTION(M) +#endif /* POSTACTION */ + +#endif /* USE_LOCKS */ + +/* + CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses. + USAGE_ERROR_ACTION is triggered on detected bad frees and + reallocs. The argument p is an address that might have triggered the + fault. It is ignored by the two predefined actions, but might be + useful in custom actions that try to help diagnose errors. +*/ + +#if PROCEED_ON_ERROR + +/* A count of the number of corruption errors causing resets */ +int malloc_corruption_error_count; + +/* default corruption action */ +static void reset_on_error(mstate m); + +#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m) +#define USAGE_ERROR_ACTION(m, p) + +#else /* PROCEED_ON_ERROR */ + +#ifndef CORRUPTION_ERROR_ACTION +#define CORRUPTION_ERROR_ACTION(m) ABORT +#endif /* CORRUPTION_ERROR_ACTION */ + +#ifndef USAGE_ERROR_ACTION +#define USAGE_ERROR_ACTION(m,p) ABORT +#endif /* USAGE_ERROR_ACTION */ + +#endif /* PROCEED_ON_ERROR */ + + +/* -------------------------- Debugging setup ---------------------------- */ + +#if ! DEBUG + +#define check_free_chunk(M,P) +#define check_inuse_chunk(M,P) +#define check_malloced_chunk(M,P,N) +#define check_mmapped_chunk(M,P) +#define check_malloc_state(M) +#define check_top_chunk(M,P) + +#else /* DEBUG */ +#define check_free_chunk(M,P) do_check_free_chunk(M,P) +#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P) +#define check_top_chunk(M,P) do_check_top_chunk(M,P) +#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N) +#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P) +#define check_malloc_state(M) do_check_malloc_state(M) + +static void do_check_any_chunk(mstate m, mchunkptr p); +static void do_check_top_chunk(mstate m, mchunkptr p); +static void do_check_mmapped_chunk(mstate m, mchunkptr p); +static void do_check_inuse_chunk(mstate m, mchunkptr p); +static void do_check_free_chunk(mstate m, mchunkptr p); +static void do_check_malloced_chunk(mstate m, void* mem, size_t s); +static void do_check_tree(mstate m, tchunkptr t); +static void do_check_treebin(mstate m, bindex_t i); +static void do_check_smallbin(mstate m, bindex_t i); +static void do_check_malloc_state(mstate m); +static int bin_find(mstate m, mchunkptr x); +static size_t traverse_and_check(mstate m); +#endif /* DEBUG */ + +/* ---------------------------- Indexing Bins ---------------------------- */ + +#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS) +#define small_index(s) (bindex_t)((s) >> SMALLBIN_SHIFT) +#define small_index2size(i) ((i) << SMALLBIN_SHIFT) +#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE)) + +/* addressing by index. See above about smallbin repositioning */ +#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1]))) +#define treebin_at(M,i) (&((M)->treebins[i])) + +/* assign tree index for size S to variable I. Use x86 asm if possible */ +#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +#define compute_tree_index(S, I)\ +{\ + unsigned int X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K = (unsigned) sizeof(X)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz(X); \ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#elif defined (__INTEL_COMPILER) +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K = _bit_scan_reverse (X); \ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#elif defined(_MSC_VER) && _MSC_VER>=1300 +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K;\ + _BitScanReverse((DWORD *) &K, (DWORD) X);\ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#else /* GNUC */ +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int Y = (unsigned int)X;\ + unsigned int N = ((Y - 0x100) >> 16) & 8;\ + unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\ + N += K;\ + N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\ + K = 14 - N + ((Y <<= K) >> 15);\ + I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\ + }\ +} +#endif /* GNUC */ + +/* Bit representing maximum resolved size in a treebin at i */ +#define bit_for_tree_index(i) \ + (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2) + +/* Shift placing maximum resolved bit in a treebin at i as sign bit */ +#define leftshift_for_tree_index(i) \ + ((i == NTREEBINS-1)? 0 : \ + ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2))) + +/* The size of the smallest chunk held in bin with index i */ +#define minsize_for_tree_index(i) \ + ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \ + (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1))) + + +/* ------------------------ Operations on bin maps ----------------------- */ + +/* bit corresponding to given index */ +#define idx2bit(i) ((binmap_t)(1) << (i)) + +/* Mark/Clear bits with given index */ +#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i)) +#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i)) +#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i)) + +#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i)) +#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i)) +#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i)) + +/* isolate the least set bit of a bitmap */ +#define least_bit(x) ((x) & -(x)) + +/* mask with all bits to left of least bit of x on */ +#define left_bits(x) ((x<<1) | -(x<<1)) + +/* mask with all bits to left of or equal to least bit of x on */ +#define same_or_left_bits(x) ((x) | -(x)) + +/* index corresponding to given bit. Use x86 asm if possible */ + +#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + J = __builtin_ctz(X); \ + I = (bindex_t)J;\ +} + +#elif defined (__INTEL_COMPILER) +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + J = _bit_scan_forward (X); \ + I = (bindex_t)J;\ +} + +#elif defined(_MSC_VER) && _MSC_VER>=1300 +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + _BitScanForward((DWORD *) &J, X);\ + I = (bindex_t)J;\ +} + +#elif USE_BUILTIN_FFS +#define compute_bit2idx(X, I) I = ffs(X)-1 + +#else +#define compute_bit2idx(X, I)\ +{\ + unsigned int Y = X - 1;\ + unsigned int K = Y >> (16-4) & 16;\ + unsigned int N = K; Y >>= K;\ + N += K = Y >> (8-3) & 8; Y >>= K;\ + N += K = Y >> (4-2) & 4; Y >>= K;\ + N += K = Y >> (2-1) & 2; Y >>= K;\ + N += K = Y >> (1-0) & 1; Y >>= K;\ + I = (bindex_t)(N + Y);\ +} +#endif /* GNUC */ + + +/* ----------------------- Runtime Check Support ------------------------- */ + +/* + For security, the main invariant is that malloc/free/etc never + writes to a static address other than malloc_state, unless static + malloc_state itself has been corrupted, which cannot occur via + malloc (because of these checks). In essence this means that we + believe all pointers, sizes, maps etc held in malloc_state, but + check all of those linked or offsetted from other embedded data + structures. These checks are interspersed with main code in a way + that tends to minimize their run-time cost. + + When FOOTERS is defined, in addition to range checking, we also + verify footer fields of inuse chunks, which can be used guarantee + that the mstate controlling malloc/free is intact. This is a + streamlined version of the approach described by William Robertson + et al in "Run-time Detection of Heap-based Overflows" LISA'03 + http://www.usenix.org/events/lisa03/tech/robertson.html The footer + of an inuse chunk holds the xor of its mstate and a random seed, + that is checked upon calls to free() and realloc(). This is + (probabalistically) unguessable from outside the program, but can be + computed by any code successfully malloc'ing any chunk, so does not + itself provide protection against code that has already broken + security through some other means. Unlike Robertson et al, we + always dynamically check addresses of all offset chunks (previous, + next, etc). This turns out to be cheaper than relying on hashes. +*/ + +#if !INSECURE +/* Check if address a is at least as high as any from MORECORE or MMAP */ +#define ok_address(M, a) ((char*)(a) >= (M)->least_addr) +/* Check if address of next chunk n is higher than base chunk p */ +#define ok_next(p, n) ((char*)(p) < (char*)(n)) +/* Check if p has inuse status */ +#define ok_inuse(p) is_inuse(p) +/* Check if p has its pinuse bit on */ +#define ok_pinuse(p) pinuse(p) + +#else /* !INSECURE */ +#define ok_address(M, a) (1) +#define ok_next(b, n) (1) +#define ok_inuse(p) (1) +#define ok_pinuse(p) (1) +#endif /* !INSECURE */ + +#if (FOOTERS && !INSECURE) +/* Check if (alleged) mstate m has expected magic field */ +#define ok_magic(M) ((M)->magic == mparams.magic) +#else /* (FOOTERS && !INSECURE) */ +#define ok_magic(M) (1) +#endif /* (FOOTERS && !INSECURE) */ + +/* In gcc, use __builtin_expect to minimize impact of checks */ +#if !INSECURE +#if defined(__GNUC__) && __GNUC__ >= 3 +#define RTCHECK(e) __builtin_expect(e, 1) +#else /* GNUC */ +#define RTCHECK(e) (e) +#endif /* GNUC */ +#else /* !INSECURE */ +#define RTCHECK(e) (1) +#endif /* !INSECURE */ + +/* macros to set up inuse chunks with or without footers */ + +#if !FOOTERS + +#define mark_inuse_foot(M,p,s) + +/* Macros for setting head/foot of non-mmapped chunks */ + +/* Set cinuse bit and pinuse bit of next chunk */ +#define set_inuse(M,p,s)\ + ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ + ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) + +/* Set cinuse and pinuse of this chunk and pinuse of next chunk */ +#define set_inuse_and_pinuse(M,p,s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) + +/* Set size, cinuse and pinuse bit of this chunk */ +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT)) + +#else /* FOOTERS */ + +/* Set foot of inuse chunk to be xor of mstate and seed */ +#define mark_inuse_foot(M,p,s)\ + (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic)) + +#define get_mstate_for(p)\ + ((mstate)(((mchunkptr)((char*)(p) +\ + (chunksize(p))))->prev_foot ^ mparams.magic)) + +#define set_inuse(M,p,s)\ + ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ + (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \ + mark_inuse_foot(M,p,s)) + +#define set_inuse_and_pinuse(M,p,s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\ + mark_inuse_foot(M,p,s)) + +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + mark_inuse_foot(M, p, s)) + +#endif /* !FOOTERS */ + +/* ---------------------------- setting mparams -------------------------- */ + +#if LOCK_AT_FORK +static void pre_fork(void) { ACQUIRE_LOCK(&(gm)->mutex); } +static void post_fork_parent(void) { RELEASE_LOCK(&(gm)->mutex); } +static void post_fork_child(void) { INITIAL_LOCK(&(gm)->mutex); } +#endif /* LOCK_AT_FORK */ + +/* Initialize mparams */ +static int init_mparams(void) { +#ifdef NEED_GLOBAL_LOCK_INIT + if (malloc_global_mutex_status <= 0) + init_malloc_global_mutex(); +#endif + + ACQUIRE_MALLOC_GLOBAL_LOCK(); + if (mparams.magic == 0) { + size_t magic; + size_t psize; + size_t gsize; + +#ifndef WIN32 + psize = malloc_getpagesize; + gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize); +#else /* WIN32 */ + { + SYSTEM_INFO system_info; + GetSystemInfo(&system_info); + psize = system_info.dwPageSize; + gsize = ((DEFAULT_GRANULARITY != 0)? + DEFAULT_GRANULARITY : system_info.dwAllocationGranularity); + } +#endif /* WIN32 */ + + /* Sanity-check configuration: + size_t must be unsigned and as wide as pointer type. + ints must be at least 4 bytes. + alignment must be at least 8. + Alignment, min chunk size, and page size must all be powers of 2. + */ + if ((sizeof(size_t) != sizeof(char*)) || + (MAX_SIZE_T < MIN_CHUNK_SIZE) || + (sizeof(int) < 4) || + (MALLOC_ALIGNMENT < (size_t)8U) || + ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) || + ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) || + ((gsize & (gsize-SIZE_T_ONE)) != 0) || + ((psize & (psize-SIZE_T_ONE)) != 0)) + ABORT; + mparams.granularity = gsize; + mparams.page_size = psize; + mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD; + mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD; +#if MORECORE_CONTIGUOUS + mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT; +#else /* MORECORE_CONTIGUOUS */ + mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT; +#endif /* MORECORE_CONTIGUOUS */ + +#if !ONLY_MSPACES + /* Set up lock for main malloc area */ + gm->mflags = mparams.default_mflags; + (void)INITIAL_LOCK(&gm->mutex); +#endif +#if LOCK_AT_FORK + pthread_atfork(&pre_fork, &post_fork_parent, &post_fork_child); +#endif + + { +#if USE_DEV_RANDOM + int fd; + unsigned char buf[sizeof(size_t)]; + /* Try to use /dev/urandom, else fall back on using time */ + if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 && + read(fd, buf, sizeof(buf)) == sizeof(buf)) { + magic = *((size_t *) buf); + close(fd); + } + else +#endif /* USE_DEV_RANDOM */ +#ifdef WIN32 + magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U); +#elif defined(LACKS_TIME_H) + magic = (size_t)&magic ^ (size_t)0x55555555U; +#else + magic = (size_t)(time(0) ^ (size_t)0x55555555U); +#endif + magic |= (size_t)8U; /* ensure nonzero */ + magic &= ~(size_t)7U; /* improve chances of fault for bad values */ + /* Until memory modes commonly available, use volatile-write */ + (*(volatile size_t *)(&(mparams.magic))) = magic; + } + } + + RELEASE_MALLOC_GLOBAL_LOCK(); + return 1; +} + +/* support for mallopt */ +static int change_mparam(int param_number, int value) { + size_t val; + ensure_initialization(); + val = (value == -1)? MAX_SIZE_T : (size_t)value; + switch(param_number) { + case M_TRIM_THRESHOLD: + mparams.trim_threshold = val; + return 1; + case M_GRANULARITY: + if (val >= mparams.page_size && ((val & (val-1)) == 0)) { + mparams.granularity = val; + return 1; + } + else + return 0; + case M_MMAP_THRESHOLD: + mparams.mmap_threshold = val; + return 1; + default: + return 0; + } +} + +#if DEBUG +/* ------------------------- Debugging Support --------------------------- */ + +/* Check properties of any chunk, whether free, inuse, mmapped etc */ +static void do_check_any_chunk(mstate m, mchunkptr p) { + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); +} + +/* Check properties of top chunk */ +static void do_check_top_chunk(mstate m, mchunkptr p) { + msegmentptr sp = segment_holding(m, (char*)p); + size_t sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */ + assert(sp != 0); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(sz == m->topsize); + assert(sz > 0); + assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE); + assert(pinuse(p)); + assert(!pinuse(chunk_plus_offset(p, sz))); +} + +/* Check properties of (inuse) mmapped chunks */ +static void do_check_mmapped_chunk(mstate m, mchunkptr p) { + size_t sz = chunksize(p); + size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD); + assert(is_mmapped(p)); + assert(use_mmap(m)); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(!is_small(sz)); + assert((len & (mparams.page_size-SIZE_T_ONE)) == 0); + assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD); + assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0); +} + +/* Check properties of inuse chunks */ +static void do_check_inuse_chunk(mstate m, mchunkptr p) { + do_check_any_chunk(m, p); + assert(is_inuse(p)); + assert(next_pinuse(p)); + /* If not pinuse and not mmapped, previous chunk has OK offset */ + assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p); + if (is_mmapped(p)) + do_check_mmapped_chunk(m, p); +} + +/* Check properties of free chunks */ +static void do_check_free_chunk(mstate m, mchunkptr p) { + size_t sz = chunksize(p); + mchunkptr next = chunk_plus_offset(p, sz); + do_check_any_chunk(m, p); + assert(!is_inuse(p)); + assert(!next_pinuse(p)); + assert (!is_mmapped(p)); + if (p != m->dv && p != m->top) { + if (sz >= MIN_CHUNK_SIZE) { + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(is_aligned(chunk2mem(p))); + assert(next->prev_foot == sz); + assert(pinuse(p)); + assert (next == m->top || is_inuse(next)); + assert(p->fd->bk == p); + assert(p->bk->fd == p); + } + else /* markers are always of size SIZE_T_SIZE */ + assert(sz == SIZE_T_SIZE); + } +} + +/* Check properties of malloced chunks at the point they are malloced */ +static void do_check_malloced_chunk(mstate m, void* mem, size_t s) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t sz = p->head & ~INUSE_BITS; + do_check_inuse_chunk(m, p); + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(sz >= MIN_CHUNK_SIZE); + assert(sz >= s); + /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */ + assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE)); + } +} + +/* Check a tree and its subtrees. */ +static void do_check_tree(mstate m, tchunkptr t) { + tchunkptr head = 0; + tchunkptr u = t; + bindex_t tindex = t->index; + size_t tsize = chunksize(t); + bindex_t idx; + compute_tree_index(tsize, idx); + assert(tindex == idx); + assert(tsize >= MIN_LARGE_SIZE); + assert(tsize >= minsize_for_tree_index(idx)); + assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1)))); + + do { /* traverse through chain of same-sized nodes */ + do_check_any_chunk(m, ((mchunkptr)u)); + assert(u->index == tindex); + assert(chunksize(u) == tsize); + assert(!is_inuse(u)); + assert(!next_pinuse(u)); + assert(u->fd->bk == u); + assert(u->bk->fd == u); + if (u->parent == 0) { + assert(u->child[0] == 0); + assert(u->child[1] == 0); + } + else { + assert(head == 0); /* only one node on chain has parent */ + head = u; + assert(u->parent != u); + assert (u->parent->child[0] == u || + u->parent->child[1] == u || + *((tbinptr*)(u->parent)) == u); + if (u->child[0] != 0) { + assert(u->child[0]->parent == u); + assert(u->child[0] != u); + do_check_tree(m, u->child[0]); + } + if (u->child[1] != 0) { + assert(u->child[1]->parent == u); + assert(u->child[1] != u); + do_check_tree(m, u->child[1]); + } + if (u->child[0] != 0 && u->child[1] != 0) { + assert(chunksize(u->child[0]) < chunksize(u->child[1])); + } + } + u = u->fd; + } while (u != t); + assert(head != 0); +} + +/* Check all the chunks in a treebin. */ +static void do_check_treebin(mstate m, bindex_t i) { + tbinptr* tb = treebin_at(m, i); + tchunkptr t = *tb; + int empty = (m->treemap & (1U << i)) == 0; + if (t == 0) + assert(empty); + if (!empty) + do_check_tree(m, t); +} + +/* Check all the chunks in a smallbin. */ +static void do_check_smallbin(mstate m, bindex_t i) { + sbinptr b = smallbin_at(m, i); + mchunkptr p = b->bk; + unsigned int empty = (m->smallmap & (1U << i)) == 0; + if (p == b) + assert(empty); + if (!empty) { + for (; p != b; p = p->bk) { + size_t size = chunksize(p); + mchunkptr q; + /* each chunk claims to be free */ + do_check_free_chunk(m, p); + /* chunk belongs in bin */ + assert(small_index(size) == i); + assert(p->bk == b || chunksize(p->bk) == chunksize(p)); + /* chunk is followed by an inuse chunk */ + q = next_chunk(p); + if (q->head != FENCEPOST_HEAD) + do_check_inuse_chunk(m, q); + } + } +} + +/* Find x in a bin. Used in other check functions. */ +static int bin_find(mstate m, mchunkptr x) { + size_t size = chunksize(x); + if (is_small(size)) { + bindex_t sidx = small_index(size); + sbinptr b = smallbin_at(m, sidx); + if (smallmap_is_marked(m, sidx)) { + mchunkptr p = b; + do { + if (p == x) + return 1; + } while ((p = p->fd) != b); + } + } + else { + bindex_t tidx; + compute_tree_index(size, tidx); + if (treemap_is_marked(m, tidx)) { + tchunkptr t = *treebin_at(m, tidx); + size_t sizebits = size << leftshift_for_tree_index(tidx); + while (t != 0 && chunksize(t) != size) { + t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; + sizebits <<= 1; + } + if (t != 0) { + tchunkptr u = t; + do { + if (u == (tchunkptr)x) + return 1; + } while ((u = u->fd) != t); + } + } + } + return 0; +} + +/* Traverse each chunk and check it; return total */ +static size_t traverse_and_check(mstate m) { + size_t sum = 0; + if (is_initialized(m)) { + msegmentptr s = &m->seg; + sum += m->topsize + TOP_FOOT_SIZE; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + mchunkptr lastq = 0; + assert(pinuse(q)); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + sum += chunksize(q); + if (is_inuse(q)) { + assert(!bin_find(m, q)); + do_check_inuse_chunk(m, q); + } + else { + assert(q == m->dv || bin_find(m, q)); + assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */ + do_check_free_chunk(m, q); + } + lastq = q; + q = next_chunk(q); + } + s = s->next; + } + } + return sum; +} + + +/* Check all properties of malloc_state. */ +static void do_check_malloc_state(mstate m) { + bindex_t i; + size_t total; + /* check bins */ + for (i = 0; i < NSMALLBINS; ++i) + do_check_smallbin(m, i); + for (i = 0; i < NTREEBINS; ++i) + do_check_treebin(m, i); + + if (m->dvsize != 0) { /* check dv chunk */ + do_check_any_chunk(m, m->dv); + assert(m->dvsize == chunksize(m->dv)); + assert(m->dvsize >= MIN_CHUNK_SIZE); + assert(bin_find(m, m->dv) == 0); + } + + if (m->top != 0) { /* check top chunk */ + do_check_top_chunk(m, m->top); + /*assert(m->topsize == chunksize(m->top)); redundant */ + assert(m->topsize > 0); + assert(bin_find(m, m->top) == 0); + } + + total = traverse_and_check(m); + assert(total <= m->footprint); + assert(m->footprint <= m->max_footprint); +} +#endif /* DEBUG */ + +/* ----------------------------- statistics ------------------------------ */ + +#if !NO_MALLINFO +static struct mallinfo internal_mallinfo(mstate m) { + struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + ensure_initialization(); + if (!PREACTION(m)) { + check_malloc_state(m); + if (is_initialized(m)) { + size_t nfree = SIZE_T_ONE; /* top always free */ + size_t mfree = m->topsize + TOP_FOOT_SIZE; + size_t sum = mfree; + msegmentptr s = &m->seg; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + size_t sz = chunksize(q); + sum += sz; + if (!is_inuse(q)) { + mfree += sz; + ++nfree; + } + q = next_chunk(q); + } + s = s->next; + } + + nm.arena = sum; + nm.ordblks = nfree; + nm.hblkhd = m->footprint - sum; + nm.usmblks = m->max_footprint; + nm.uordblks = m->footprint - mfree; + nm.fordblks = mfree; + nm.keepcost = m->topsize; + } + + POSTACTION(m); + } + return nm; +} +#endif /* !NO_MALLINFO */ + +#if !NO_MALLOC_STATS +static void internal_malloc_stats(mstate m) { + ensure_initialization(); + if (!PREACTION(m)) { + size_t maxfp = 0; + size_t fp = 0; + size_t used = 0; + check_malloc_state(m); + if (is_initialized(m)) { + msegmentptr s = &m->seg; + maxfp = m->max_footprint; + fp = m->footprint; + used = fp - (m->topsize + TOP_FOOT_SIZE); + + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + if (!is_inuse(q)) + used -= chunksize(q); + q = next_chunk(q); + } + s = s->next; + } + } + POSTACTION(m); /* drop lock */ + fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp)); + fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp)); + fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used)); + } +} +#endif /* NO_MALLOC_STATS */ + +/* ----------------------- Operations on smallbins ----------------------- */ + +/* + Various forms of linking and unlinking are defined as macros. Even + the ones for trees, which are very long but have very short typical + paths. This is ugly but reduces reliance on inlining support of + compilers. +*/ + +/* Link a free chunk into a smallbin */ +#define insert_small_chunk(M, P, S) {\ + bindex_t I = small_index(S);\ + mchunkptr B = smallbin_at(M, I);\ + mchunkptr F = B;\ + assert(S >= MIN_CHUNK_SIZE);\ + if (!smallmap_is_marked(M, I))\ + mark_smallmap(M, I);\ + else if (RTCHECK(ok_address(M, B->fd)))\ + F = B->fd;\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + B->fd = P;\ + F->bk = P;\ + P->fd = F;\ + P->bk = B;\ +} + +/* Unlink a chunk from a smallbin */ +#define unlink_small_chunk(M, P, S) {\ + mchunkptr F = P->fd;\ + mchunkptr B = P->bk;\ + bindex_t I = small_index(S);\ + assert(P != B);\ + assert(P != F);\ + assert(chunksize(P) == small_index2size(I));\ + if (RTCHECK(F == smallbin_at(M,I) || (ok_address(M, F) && F->bk == P))) { \ + if (B == F) {\ + clear_smallmap(M, I);\ + }\ + else if (RTCHECK(B == smallbin_at(M,I) ||\ + (ok_address(M, B) && B->fd == P))) {\ + F->bk = B;\ + B->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ +} + +/* Unlink the first chunk from a smallbin */ +#define unlink_first_small_chunk(M, B, P, I) {\ + mchunkptr F = P->fd;\ + assert(P != B);\ + assert(P != F);\ + assert(chunksize(P) == small_index2size(I));\ + if (B == F) {\ + clear_smallmap(M, I);\ + }\ + else if (RTCHECK(ok_address(M, F) && F->bk == P)) {\ + F->bk = B;\ + B->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ +} + +/* Replace dv node, binning the old one */ +/* Used only when dvsize known to be small */ +#define replace_dv(M, P, S) {\ + size_t DVS = M->dvsize;\ + assert(is_small(DVS));\ + if (DVS != 0) {\ + mchunkptr DV = M->dv;\ + insert_small_chunk(M, DV, DVS);\ + }\ + M->dvsize = S;\ + M->dv = P;\ +} + +/* ------------------------- Operations on trees ------------------------- */ + +/* Insert chunk into tree */ +#define insert_large_chunk(M, X, S) {\ + tbinptr* H;\ + bindex_t I;\ + compute_tree_index(S, I);\ + H = treebin_at(M, I);\ + X->index = I;\ + X->child[0] = X->child[1] = 0;\ + if (!treemap_is_marked(M, I)) {\ + mark_treemap(M, I);\ + *H = X;\ + X->parent = (tchunkptr)H;\ + X->fd = X->bk = X;\ + }\ + else {\ + tchunkptr T = *H;\ + size_t K = S << leftshift_for_tree_index(I);\ + for (;;) {\ + if (chunksize(T) != S) {\ + tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\ + K <<= 1;\ + if (*C != 0)\ + T = *C;\ + else if (RTCHECK(ok_address(M, C))) {\ + *C = X;\ + X->parent = T;\ + X->fd = X->bk = X;\ + break;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + break;\ + }\ + }\ + else {\ + tchunkptr F = T->fd;\ + if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\ + T->fd = F->bk = X;\ + X->fd = F;\ + X->bk = T;\ + X->parent = 0;\ + break;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + break;\ + }\ + }\ + }\ + }\ +} + +/* + Unlink steps: + + 1. If x is a chained node, unlink it from its same-sized fd/bk links + and choose its bk node as its replacement. + 2. If x was the last node of its size, but not a leaf node, it must + be replaced with a leaf node (not merely one with an open left or + right), to make sure that lefts and rights of descendents + correspond properly to bit masks. We use the rightmost descendent + of x. We could use any other leaf, but this is easy to locate and + tends to counteract removal of leftmosts elsewhere, and so keeps + paths shorter than minimally guaranteed. This doesn't loop much + because on average a node in a tree is near the bottom. + 3. If x is the base of a chain (i.e., has parent links) relink + x's parent and children to x's replacement (or null if none). +*/ + +#define unlink_large_chunk(M, X) {\ + tchunkptr XP = X->parent;\ + tchunkptr R;\ + if (X->bk != X) {\ + tchunkptr F = X->fd;\ + R = X->bk;\ + if (RTCHECK(ok_address(M, F) && F->bk == X && R->fd == X)) {\ + F->bk = R;\ + R->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else {\ + tchunkptr* RP;\ + if (((R = *(RP = &(X->child[1]))) != 0) ||\ + ((R = *(RP = &(X->child[0]))) != 0)) {\ + tchunkptr* CP;\ + while ((*(CP = &(R->child[1])) != 0) ||\ + (*(CP = &(R->child[0])) != 0)) {\ + R = *(RP = CP);\ + }\ + if (RTCHECK(ok_address(M, RP)))\ + *RP = 0;\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + }\ + if (XP != 0) {\ + tbinptr* H = treebin_at(M, X->index);\ + if (X == *H) {\ + if ((*H = R) == 0) \ + clear_treemap(M, X->index);\ + }\ + else if (RTCHECK(ok_address(M, XP))) {\ + if (XP->child[0] == X) \ + XP->child[0] = R;\ + else \ + XP->child[1] = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + if (R != 0) {\ + if (RTCHECK(ok_address(M, R))) {\ + tchunkptr C0, C1;\ + R->parent = XP;\ + if ((C0 = X->child[0]) != 0) {\ + if (RTCHECK(ok_address(M, C0))) {\ + R->child[0] = C0;\ + C0->parent = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + if ((C1 = X->child[1]) != 0) {\ + if (RTCHECK(ok_address(M, C1))) {\ + R->child[1] = C1;\ + C1->parent = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ +} + +/* Relays to large vs small bin operations */ + +#define insert_chunk(M, P, S)\ + if (is_small(S)) insert_small_chunk(M, P, S)\ + else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); } + +#define unlink_chunk(M, P, S)\ + if (is_small(S)) unlink_small_chunk(M, P, S)\ + else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); } + + +/* Relays to internal calls to malloc/free from realloc, memalign etc */ + +#if ONLY_MSPACES +#define internal_malloc(m, b) mspace_malloc(m, b) +#define internal_free(m, mem) mspace_free(m,mem); +#else /* ONLY_MSPACES */ +#if MSPACES +#define internal_malloc(m, b)\ + ((m == gm)? dlmalloc(b) : mspace_malloc(m, b)) +#define internal_free(m, mem)\ + if (m == gm) dlfree(mem); else mspace_free(m,mem); +#else /* MSPACES */ +#define internal_malloc(m, b) dlmalloc(b) +#define internal_free(m, mem) dlfree(mem) +#endif /* MSPACES */ +#endif /* ONLY_MSPACES */ + +/* ----------------------- Direct-mmapping chunks ----------------------- */ + +/* + Directly mmapped chunks are set up with an offset to the start of + the mmapped region stored in the prev_foot field of the chunk. This + allows reconstruction of the required argument to MUNMAP when freed, + and also allows adjustment of the returned chunk to meet alignment + requirements (especially in memalign). +*/ + +/* Malloc using mmap */ +static void* mmap_alloc(mstate m, size_t nb) { + size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + if (m->footprint_limit != 0) { + size_t fp = m->footprint + mmsize; + if (fp <= m->footprint || fp > m->footprint_limit) + return 0; + } + if (mmsize > nb) { /* Check for wrap around 0 */ + char* mm = (char*)(CALL_DIRECT_MMAP(mmsize)); + if (mm != CMFAIL) { + size_t offset = align_offset(chunk2mem(mm)); + size_t psize = mmsize - offset - MMAP_FOOT_PAD; + mchunkptr p = (mchunkptr)(mm + offset); + p->prev_foot = offset; + p->head = psize; + mark_inuse_foot(m, p, psize); + chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0; + + if (m->least_addr == 0 || mm < m->least_addr) + m->least_addr = mm; + if ((m->footprint += mmsize) > m->max_footprint) + m->max_footprint = m->footprint; + assert(is_aligned(chunk2mem(p))); + check_mmapped_chunk(m, p); + return chunk2mem(p); + } + } + return 0; +} + +/* Realloc using mmap */ +static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb, int flags) { + size_t oldsize = chunksize(oldp); + (void)flags; /* placate people compiling -Wunused */ + if (is_small(nb)) /* Can't shrink mmap regions below small size */ + return 0; + /* Keep old chunk if big enough but not too big */ + if (oldsize >= nb + SIZE_T_SIZE && + (oldsize - nb) <= (mparams.granularity << 1)) + return oldp; + else { + size_t offset = oldp->prev_foot; + size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; + size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + char* cp = (char*)CALL_MREMAP((char*)oldp - offset, + oldmmsize, newmmsize, flags); + if (cp != CMFAIL) { + mchunkptr newp = (mchunkptr)(cp + offset); + size_t psize = newmmsize - offset - MMAP_FOOT_PAD; + newp->head = psize; + mark_inuse_foot(m, newp, psize); + chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0; + + if (cp < m->least_addr) + m->least_addr = cp; + if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint) + m->max_footprint = m->footprint; + check_mmapped_chunk(m, newp); + return newp; + } + } + return 0; +} + + +/* -------------------------- mspace management -------------------------- */ + +/* Initialize top chunk and its size */ +static void init_top(mstate m, mchunkptr p, size_t psize) { + /* Ensure alignment */ + size_t offset = align_offset(chunk2mem(p)); + p = (mchunkptr)((char*)p + offset); + psize -= offset; + + m->top = p; + m->topsize = psize; + p->head = psize | PINUSE_BIT; + /* set size of fake trailing chunk holding overhead space only once */ + chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; + m->trim_check = mparams.trim_threshold; /* reset on each update */ +} + +/* Initialize bins for a new mstate that is otherwise zeroed out */ +static void init_bins(mstate m) { + /* Establish circular links for smallbins */ + bindex_t i; + for (i = 0; i < NSMALLBINS; ++i) { + sbinptr bin = smallbin_at(m,i); + bin->fd = bin->bk = bin; + } +} + +#if PROCEED_ON_ERROR + +/* default corruption action */ +static void reset_on_error(mstate m) { + int i; + ++malloc_corruption_error_count; + /* Reinitialize fields to forget about all memory */ + m->smallmap = m->treemap = 0; + m->dvsize = m->topsize = 0; + m->seg.base = 0; + m->seg.size = 0; + m->seg.next = 0; + m->top = m->dv = 0; + for (i = 0; i < NTREEBINS; ++i) + *treebin_at(m, i) = 0; + init_bins(m); +} +#endif /* PROCEED_ON_ERROR */ + +/* Allocate chunk and prepend remainder with chunk in successor base. */ +static void* prepend_alloc(mstate m, char* newbase, char* oldbase, + size_t nb) { + mchunkptr p = align_as_chunk(newbase); + mchunkptr oldfirst = align_as_chunk(oldbase); + size_t psize = (char*)oldfirst - (char*)p; + mchunkptr q = chunk_plus_offset(p, nb); + size_t qsize = psize - nb; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + + assert((char*)oldfirst > (char*)q); + assert(pinuse(oldfirst)); + assert(qsize >= MIN_CHUNK_SIZE); + + /* consolidate remainder with first chunk of old base */ + if (oldfirst == m->top) { + size_t tsize = m->topsize += qsize; + m->top = q; + q->head = tsize | PINUSE_BIT; + check_top_chunk(m, q); + } + else if (oldfirst == m->dv) { + size_t dsize = m->dvsize += qsize; + m->dv = q; + set_size_and_pinuse_of_free_chunk(q, dsize); + } + else { + if (!is_inuse(oldfirst)) { + size_t nsize = chunksize(oldfirst); + unlink_chunk(m, oldfirst, nsize); + oldfirst = chunk_plus_offset(oldfirst, nsize); + qsize += nsize; + } + set_free_with_pinuse(q, qsize, oldfirst); + insert_chunk(m, q, qsize); + check_free_chunk(m, q); + } + + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); +} + +/* Add a segment to hold a new noncontiguous region */ +static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) { + /* Determine locations and sizes of segment, fenceposts, old top */ + char* old_top = (char*)m->top; + msegmentptr oldsp = segment_holding(m, old_top); + char* old_end = oldsp->base + oldsp->size; + size_t ssize = pad_request(sizeof(struct malloc_segment)); + char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + size_t offset = align_offset(chunk2mem(rawsp)); + char* asp = rawsp + offset; + char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp; + mchunkptr sp = (mchunkptr)csp; + msegmentptr ss = (msegmentptr)(chunk2mem(sp)); + mchunkptr tnext = chunk_plus_offset(sp, ssize); + mchunkptr p = tnext; + int nfences = 0; + + /* reset top to new space */ + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + + /* Set up segment record */ + assert(is_aligned(ss)); + set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); + *ss = m->seg; /* Push current record */ + m->seg.base = tbase; + m->seg.size = tsize; + m->seg.sflags = mmapped; + m->seg.next = ss; + + /* Insert trailing fenceposts */ + for (;;) { + mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); + p->head = FENCEPOST_HEAD; + ++nfences; + if ((char*)(&(nextp->head)) < old_end) + p = nextp; + else + break; + } + (void)nfences; + assert(nfences >= 2); + + /* Insert the rest of old top into a bin as an ordinary free chunk */ + if (csp != old_top) { + mchunkptr q = (mchunkptr)old_top; + size_t psize = csp - old_top; + mchunkptr tn = chunk_plus_offset(q, psize); + set_free_with_pinuse(q, psize, tn); + insert_chunk(m, q, psize); + } + + check_top_chunk(m, m->top); +} + +/* -------------------------- System allocation -------------------------- */ + +/* Get memory from system using MORECORE or MMAP */ +static void* sys_alloc(mstate m, size_t nb) { + char* tbase = CMFAIL; + size_t tsize = 0; + flag_t mmap_flag = 0; + size_t asize; /* allocation size */ + + ensure_initialization(); + + /* Directly map large chunks, but only if already initialized */ + if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) { + void* mem = mmap_alloc(m, nb); + if (mem != 0) + return mem; + } + + asize = granularity_align(nb + SYS_ALLOC_PADDING); + if (asize <= nb) + return 0; /* wraparound */ + if (m->footprint_limit != 0) { + size_t fp = m->footprint + asize; + if (fp <= m->footprint || fp > m->footprint_limit) + return 0; + } + + /* + Try getting memory in any of three ways (in most-preferred to + least-preferred order): + 1. A call to MORECORE that can normally contiguously extend memory. + (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or + or main space is mmapped or a previous contiguous call failed) + 2. A call to MMAP new space (disabled if not HAVE_MMAP). + Note that under the default settings, if MORECORE is unable to + fulfill a request, and HAVE_MMAP is true, then mmap is + used as a noncontiguous system allocator. This is a useful backup + strategy for systems with holes in address spaces -- in this case + sbrk cannot contiguously expand the heap, but mmap may be able to + find space. + 3. A call to MORECORE that cannot usually contiguously extend memory. + (disabled if not HAVE_MORECORE) + + In all cases, we need to request enough bytes from system to ensure + we can malloc nb bytes upon success, so pad with enough space for + top_foot, plus alignment-pad to make sure we don't lose bytes if + not on boundary, and round this up to a granularity unit. + */ + + if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) { + char* br = CMFAIL; + size_t ssize = asize; /* sbrk call size */ + msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top); + ACQUIRE_MALLOC_GLOBAL_LOCK(); + + if (ss == 0) { /* First time through or recovery */ + char* base = (char*)CALL_MORECORE(0); + if (base != CMFAIL) { + size_t fp; + /* Adjust to end on a page boundary */ + if (!is_page_aligned(base)) + ssize += (page_align((size_t)base) - (size_t)base); + fp = m->footprint + ssize; /* recheck limits */ + if (ssize > nb && ssize < HALF_MAX_SIZE_T && + (m->footprint_limit == 0 || + (fp > m->footprint && fp <= m->footprint_limit)) && + (br = (char*)(CALL_MORECORE(ssize))) == base) { + tbase = base; + tsize = ssize; + } + } + } + else { + /* Subtract out existing available top space from MORECORE request. */ + ssize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING); + /* Use mem here only if it did continuously extend old space */ + if (ssize < HALF_MAX_SIZE_T && + (br = (char*)(CALL_MORECORE(ssize))) == ss->base+ss->size) { + tbase = br; + tsize = ssize; + } + } + + if (tbase == CMFAIL) { /* Cope with partial failure */ + if (br != CMFAIL) { /* Try to use/extend the space we did get */ + if (ssize < HALF_MAX_SIZE_T && + ssize < nb + SYS_ALLOC_PADDING) { + size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - ssize); + if (esize < HALF_MAX_SIZE_T) { + char* end = (char*)CALL_MORECORE(esize); + if (end != CMFAIL) + ssize += esize; + else { /* Can't use; try to release */ + (void) CALL_MORECORE(-ssize); + br = CMFAIL; + } + } + } + } + if (br != CMFAIL) { /* Use the space we did get */ + tbase = br; + tsize = ssize; + } + else + disable_contiguous(m); /* Don't try contiguous path in the future */ + } + + RELEASE_MALLOC_GLOBAL_LOCK(); + } + + if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */ + char* mp = (char*)(CALL_MMAP(asize)); + if (mp != CMFAIL) { + tbase = mp; + tsize = asize; + mmap_flag = USE_MMAP_BIT; + } + } + + if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */ + if (asize < HALF_MAX_SIZE_T) { + char* br = CMFAIL; + char* end = CMFAIL; + ACQUIRE_MALLOC_GLOBAL_LOCK(); + br = (char*)(CALL_MORECORE(asize)); + end = (char*)(CALL_MORECORE(0)); + RELEASE_MALLOC_GLOBAL_LOCK(); + if (br != CMFAIL && end != CMFAIL && br < end) { + size_t ssize = end - br; + if (ssize > nb + TOP_FOOT_SIZE) { + tbase = br; + tsize = ssize; + } + } + } + } + + if (tbase != CMFAIL) { + + if ((m->footprint += tsize) > m->max_footprint) + m->max_footprint = m->footprint; + + if (!is_initialized(m)) { /* first-time initialization */ + if (m->least_addr == 0 || tbase < m->least_addr) + m->least_addr = tbase; + m->seg.base = tbase; + m->seg.size = tsize; + m->seg.sflags = mmap_flag; + m->magic = mparams.magic; + m->release_checks = MAX_RELEASE_CHECK_RATE; + init_bins(m); +#if !ONLY_MSPACES + if (is_global(m)) + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + else +#endif + { + /* Offset top by embedded malloc_state */ + mchunkptr mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE); + } + } + + else { + /* Try to merge with an existing segment */ + msegmentptr sp = &m->seg; + /* Only consider most recent segment if traversal suppressed */ + while (sp != 0 && tbase != sp->base + sp->size) + sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + (sp->sflags & USE_MMAP_BIT) == mmap_flag && + segment_holds(sp, m->top)) { /* append */ + sp->size += tsize; + init_top(m, m->top, m->topsize + tsize); + } + else { + if (tbase < m->least_addr) + m->least_addr = tbase; + sp = &m->seg; + while (sp != 0 && sp->base != tbase + tsize) + sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + (sp->sflags & USE_MMAP_BIT) == mmap_flag) { + char* oldbase = sp->base; + sp->base = tbase; + sp->size += tsize; + return prepend_alloc(m, tbase, oldbase, nb); + } + else + add_segment(m, tbase, tsize, mmap_flag); + } + } + + if (nb < m->topsize) { /* Allocate from new or extended top space */ + size_t rsize = m->topsize -= nb; + mchunkptr p = m->top; + mchunkptr r = m->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + check_top_chunk(m, m->top); + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); + } + } + + MALLOC_FAILURE_ACTION; + return 0; +} + +/* ----------------------- system deallocation -------------------------- */ + +/* Unmap and unlink any mmapped segments that don't contain used chunks */ +static size_t release_unused_segments(mstate m) { + size_t released = 0; + int nsegs = 0; + msegmentptr pred = &m->seg; + msegmentptr sp = pred->next; + while (sp != 0) { + char* base = sp->base; + size_t size = sp->size; + msegmentptr next = sp->next; + ++nsegs; + if (is_mmapped_segment(sp) && !is_extern_segment(sp)) { + mchunkptr p = align_as_chunk(base); + size_t psize = chunksize(p); + /* Can unmap if first chunk holds entire segment and not pinned */ + if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) { + tchunkptr tp = (tchunkptr)p; + assert(segment_holds(sp, (char*)sp)); + if (p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } + else { + unlink_large_chunk(m, tp); + } + if (CALL_MUNMAP(base, size) == 0) { + released += size; + m->footprint -= size; + /* unlink obsoleted record */ + sp = pred; + sp->next = next; + } + else { /* back out if cannot unmap */ + insert_large_chunk(m, tp, psize); + } + } + } + if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */ + break; + pred = sp; + sp = next; + } + /* Reset check counter */ + m->release_checks = (((size_t) nsegs > (size_t) MAX_RELEASE_CHECK_RATE)? + (size_t) nsegs : (size_t) MAX_RELEASE_CHECK_RATE); + return released; +} + +static int sys_trim(mstate m, size_t pad) { + size_t released = 0; + ensure_initialization(); + if (pad < MAX_REQUEST && is_initialized(m)) { + pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ + + if (m->topsize > pad) { + /* Shrink top space in granularity-size units, keeping at least one */ + size_t unit = mparams.granularity; + size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - + SIZE_T_ONE) * unit; + msegmentptr sp = segment_holding(m, (char*)m->top); + + if (!is_extern_segment(sp)) { + if (is_mmapped_segment(sp)) { + if (HAVE_MMAP && + sp->size >= extra && + !has_segment_link(m, sp)) { /* can't shrink if pinned */ + size_t newsize = sp->size - extra; + (void)newsize; /* placate people compiling -Wunused-variable */ + /* Prefer mremap, fall back to munmap */ + if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) || + (CALL_MUNMAP(sp->base + newsize, extra) == 0)) { + released = extra; + } + } + } + else if (HAVE_MORECORE) { + if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ + extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; + ACQUIRE_MALLOC_GLOBAL_LOCK(); + { + /* Make sure end of memory is where we last set it. */ + char* old_br = (char*)(CALL_MORECORE(0)); + if (old_br == sp->base + sp->size) { + char* rel_br = (char*)(CALL_MORECORE(-extra)); + char* new_br = (char*)(CALL_MORECORE(0)); + if (rel_br != CMFAIL && new_br < old_br) + released = old_br - new_br; + } + } + RELEASE_MALLOC_GLOBAL_LOCK(); + } + } + + if (released != 0) { + sp->size -= released; + m->footprint -= released; + init_top(m, m->top, m->topsize - released); + check_top_chunk(m, m->top); + } + } + + /* Unmap any unused mmapped segments */ + if (HAVE_MMAP) + released += release_unused_segments(m); + + /* On failure, disable autotrim to avoid repeated failed future calls */ + if (released == 0 && m->topsize > m->trim_check) + m->trim_check = MAX_SIZE_T; + } + + return (released != 0)? 1 : 0; +} + +/* Consolidate and bin a chunk. Differs from exported versions + of free mainly in that the chunk need not be marked as inuse. +*/ +static void dispose_chunk(mstate m, mchunkptr p, size_t psize) { + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + mchunkptr prev; + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + m->footprint -= psize; + return; + } + prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(m, prev))) { /* consolidate backward */ + if (p != m->dv) { + unlink_chunk(m, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + m->dvsize = psize; + set_free_with_pinuse(p, psize, next); + return; + } + } + else { + CORRUPTION_ERROR_ACTION(m); + return; + } + } + if (RTCHECK(ok_address(m, next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == m->top) { + size_t tsize = m->topsize += psize; + m->top = p; + p->head = tsize | PINUSE_BIT; + if (p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } + return; + } + else if (next == m->dv) { + size_t dsize = m->dvsize += psize; + m->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + return; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(m, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == m->dv) { + m->dvsize = psize; + return; + } + } + } + else { + set_free_with_pinuse(p, psize, next); + } + insert_chunk(m, p, psize); + } + else { + CORRUPTION_ERROR_ACTION(m); + } +} + +/* ---------------------------- malloc --------------------------- */ + +/* allocate a large request from the best fitting chunk in a treebin */ +static void* tmalloc_large(mstate m, size_t nb) { + tchunkptr v = 0; + size_t rsize = -nb; /* Unsigned negation */ + tchunkptr t; + bindex_t idx; + compute_tree_index(nb, idx); + if ((t = *treebin_at(m, idx)) != 0) { + /* Traverse tree for this bin looking for node with size == nb */ + size_t sizebits = nb << leftshift_for_tree_index(idx); + tchunkptr rst = 0; /* The deepest untaken right subtree */ + for (;;) { + tchunkptr rt; + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + v = t; + if ((rsize = trem) == 0) + break; + } + rt = t->child[1]; + t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; + if (rt != 0 && rt != t) + rst = rt; + if (t == 0) { + t = rst; /* set t to least subtree holding sizes > nb */ + break; + } + sizebits <<= 1; + } + } + if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */ + binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; + if (leftbits != 0) { + bindex_t i; + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + t = *treebin_at(m, i); + } + } + + while (t != 0) { /* find smallest of tree or subtree */ + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + t = leftmost_child(t); + } + + /* If dv is a better fit, return 0 so malloc will use it */ + if (v != 0 && rsize < (size_t)(m->dvsize - nb)) { + if (RTCHECK(ok_address(m, v))) { /* split */ + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + insert_chunk(m, r, rsize); + } + return chunk2mem(v); + } + } + CORRUPTION_ERROR_ACTION(m); + } + return 0; +} + +/* allocate a small request from the best fitting chunk in a treebin */ +static void* tmalloc_small(mstate m, size_t nb) { + tchunkptr t, v; + size_t rsize; + bindex_t i; + binmap_t leastbit = least_bit(m->treemap); + compute_bit2idx(leastbit, i); + v = t = *treebin_at(m, i); + rsize = chunksize(t) - nb; + + while ((t = leftmost_child(t)) != 0) { + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + } + + if (RTCHECK(ok_address(m, v))) { + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(m, r, rsize); + } + return chunk2mem(v); + } + } + + CORRUPTION_ERROR_ACTION(m); + return 0; +} + +#if !ONLY_MSPACES + +void* dlmalloc(size_t bytes) { + /* + Basic algorithm: + If a small request (< 256 bytes minus per-chunk overhead): + 1. If one exists, use a remainderless chunk in associated smallbin. + (Remainderless means that there are too few excess bytes to + represent as a chunk.) + 2. If it is big enough, use the dv chunk, which is normally the + chunk adjacent to the one used for the most recent small request. + 3. If one exists, split the smallest available chunk in a bin, + saving remainder in dv. + 4. If it is big enough, use the top chunk. + 5. If available, get memory from system and use it + Otherwise, for a large request: + 1. Find the smallest available binned chunk that fits, and use it + if it is better fitting than dv chunk, splitting if necessary. + 2. If better fitting than any binned chunk, use the dv chunk. + 3. If it is big enough, use the top chunk. + 4. If request size >= mmap threshold, try to directly mmap this chunk. + 5. If available, get memory from system and use it + + The ugly goto's here ensure that postaction occurs along all paths. + */ + +#if USE_LOCKS + ensure_initialization(); /* initialize in sys_alloc if not using locks */ +#endif + + if (!PREACTION(gm)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = gm->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(gm, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(gm, b, p, idx); + set_inuse_and_pinuse(gm, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (nb > gm->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(gm, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(gm, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(gm, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(gm, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + + if (nb <= gm->dvsize) { + size_t rsize = gm->dvsize - nb; + mchunkptr p = gm->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = gm->dv = chunk_plus_offset(p, nb); + gm->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + } + else { /* exhaust dv */ + size_t dvs = gm->dvsize; + gm->dvsize = 0; + gm->dv = 0; + set_inuse_and_pinuse(gm, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (nb < gm->topsize) { /* Split top */ + size_t rsize = gm->topsize -= nb; + mchunkptr p = gm->top; + mchunkptr r = gm->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + mem = chunk2mem(p); + check_top_chunk(gm, gm->top); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + mem = sys_alloc(gm, nb); + + postaction: + POSTACTION(gm); + return mem; + } + + return 0; +} + +/* ---------------------------- free --------------------------- */ + +void dlfree(void* mem) { + /* + Consolidate freed chunks with preceeding or succeeding bordering + free chunks, if they exist, and then place in a bin. Intermixed + with special cases for top, dv, mmapped chunks, and usage errors. + */ + + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } +#else /* FOOTERS */ +#define fm gm +#endif /* FOOTERS */ + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + + if (is_small(psize)) { + insert_small_chunk(fm, p, psize); + check_free_chunk(fm, p); + } + else { + tchunkptr tp = (tchunkptr)p; + insert_large_chunk(fm, tp, psize); + check_free_chunk(fm, p); + if (--fm->release_checks == 0) + release_unused_segments(fm); + } + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } +#if !FOOTERS +#undef fm +#endif /* FOOTERS */ +} + +void* dlcalloc(size_t n_elements, size_t elem_size) { + void* mem; + size_t req = 0; + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t)0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = dlmalloc(req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; +} + +#endif /* !ONLY_MSPACES */ + +/* ------------ Internal support for realloc, memalign, etc -------------- */ + +/* Try to realloc; only in-place unless can_move true */ +static mchunkptr try_realloc_chunk(mstate m, mchunkptr p, size_t nb, + int can_move) { + mchunkptr newp = 0; + size_t oldsize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, oldsize); + if (RTCHECK(ok_address(m, p) && ok_inuse(p) && + ok_next(p, next) && ok_pinuse(next))) { + if (is_mmapped(p)) { + newp = mmap_resize(m, p, nb, can_move); + } + else if (oldsize >= nb) { /* already big enough */ + size_t rsize = oldsize - nb; + if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */ + mchunkptr r = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, r, rsize); + dispose_chunk(m, r, rsize); + } + newp = p; + } + else if (next == m->top) { /* extend into top */ + if (oldsize + m->topsize > nb) { + size_t newsize = oldsize + m->topsize; + size_t newtopsize = newsize - nb; + mchunkptr newtop = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + newtop->head = newtopsize |PINUSE_BIT; + m->top = newtop; + m->topsize = newtopsize; + newp = p; + } + } + else if (next == m->dv) { /* extend into dv */ + size_t dvs = m->dvsize; + if (oldsize + dvs >= nb) { + size_t dsize = oldsize + dvs - nb; + if (dsize >= MIN_CHUNK_SIZE) { + mchunkptr r = chunk_plus_offset(p, nb); + mchunkptr n = chunk_plus_offset(r, dsize); + set_inuse(m, p, nb); + set_size_and_pinuse_of_free_chunk(r, dsize); + clear_pinuse(n); + m->dvsize = dsize; + m->dv = r; + } + else { /* exhaust dv */ + size_t newsize = oldsize + dvs; + set_inuse(m, p, newsize); + m->dvsize = 0; + m->dv = 0; + } + newp = p; + } + } + else if (!cinuse(next)) { /* extend into next free chunk */ + size_t nextsize = chunksize(next); + if (oldsize + nextsize >= nb) { + size_t rsize = oldsize + nextsize - nb; + unlink_chunk(m, next, nextsize); + if (rsize < MIN_CHUNK_SIZE) { + size_t newsize = oldsize + nextsize; + set_inuse(m, p, newsize); + } + else { + mchunkptr r = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, r, rsize); + dispose_chunk(m, r, rsize); + } + newp = p; + } + } + } + else { + USAGE_ERROR_ACTION(m, chunk2mem(p)); + } + return newp; +} + +static void* internal_memalign(mstate m, size_t alignment, size_t bytes) { + void* mem = 0; + if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */ + alignment = MIN_CHUNK_SIZE; + if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */ + size_t a = MALLOC_ALIGNMENT << 1; + while (a < alignment) a <<= 1; + alignment = a; + } + if (bytes >= MAX_REQUEST - alignment) { + if (m != 0) { /* Test isn't needed but avoids compiler warning */ + MALLOC_FAILURE_ACTION; + } + } + else { + size_t nb = request2size(bytes); + size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; + mem = internal_malloc(m, req); + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (PREACTION(m)) + return 0; + if ((((size_t)(mem)) & (alignment - 1)) != 0) { /* misaligned */ + /* + Find an aligned spot inside chunk. Since we need to give + back leading space in a chunk of at least MIN_CHUNK_SIZE, if + the first calculation places us at a spot with less than + MIN_CHUNK_SIZE leader, we can move to the next aligned spot. + We've allocated enough total room so that this is always + possible. + */ + char* br = (char*)mem2chunk((size_t)(((size_t)((char*)mem + alignment - + SIZE_T_ONE)) & + -alignment)); + char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)? + br : br+alignment; + mchunkptr newp = (mchunkptr)pos; + size_t leadsize = pos - (char*)(p); + size_t newsize = chunksize(p) - leadsize; + + if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ + newp->prev_foot = p->prev_foot + leadsize; + newp->head = newsize; + } + else { /* Otherwise, give back leader, use the rest */ + set_inuse(m, newp, newsize); + set_inuse(m, p, leadsize); + dispose_chunk(m, p, leadsize); + } + p = newp; + } + + /* Give back spare room at the end */ + if (!is_mmapped(p)) { + size_t size = chunksize(p); + if (size > nb + MIN_CHUNK_SIZE) { + size_t remainder_size = size - nb; + mchunkptr remainder = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, remainder, remainder_size); + dispose_chunk(m, remainder, remainder_size); + } + } + + mem = chunk2mem(p); + assert (chunksize(p) >= nb); + assert(((size_t)mem & (alignment - 1)) == 0); + check_inuse_chunk(m, p); + POSTACTION(m); + } + } + return mem; +} + +/* + Common support for independent_X routines, handling + all of the combinations that can result. + The opts arg has: + bit 0 set if all elements are same size (using sizes[0]) + bit 1 set if elements should be zeroed +*/ +static void** ialloc(mstate m, + size_t n_elements, + size_t* sizes, + int opts, + void* chunks[]) { + + size_t element_size; /* chunksize of each element, if all same */ + size_t contents_size; /* total size of elements */ + size_t array_size; /* request size of pointer array */ + void* mem; /* malloced aggregate space */ + mchunkptr p; /* corresponding chunk */ + size_t remainder_size; /* remaining bytes while splitting */ + void** marray; /* either "chunks" or malloced ptr array */ + mchunkptr array_chunk; /* chunk for malloced ptr array */ + flag_t was_enabled; /* to disable mmap */ + size_t size; + size_t i; + + ensure_initialization(); + /* compute array length, if needed */ + if (chunks != 0) { + if (n_elements == 0) + return chunks; /* nothing to do */ + marray = chunks; + array_size = 0; + } + else { + /* if empty req, must still return chunk representing empty array */ + if (n_elements == 0) + return (void**)internal_malloc(m, 0); + marray = 0; + array_size = request2size(n_elements * (sizeof(void*))); + } + + /* compute total element size */ + if (opts & 0x1) { /* all-same-size */ + element_size = request2size(*sizes); + contents_size = n_elements * element_size; + } + else { /* add up all the sizes */ + element_size = 0; + contents_size = 0; + for (i = 0; i != n_elements; ++i) + contents_size += request2size(sizes[i]); + } + + size = contents_size + array_size; + + /* + Allocate the aggregate chunk. First disable direct-mmapping so + malloc won't use it, since we would not be able to later + free/realloc space internal to a segregated mmap region. + */ + was_enabled = use_mmap(m); + disable_mmap(m); + mem = internal_malloc(m, size - CHUNK_OVERHEAD); + if (was_enabled) + enable_mmap(m); + if (mem == 0) + return 0; + + if (PREACTION(m)) return 0; + p = mem2chunk(mem); + remainder_size = chunksize(p); + + assert(!is_mmapped(p)); + + if (opts & 0x2) { /* optionally clear the elements */ + memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size); + } + + /* If not provided, allocate the pointer array as final part of chunk */ + if (marray == 0) { + size_t array_chunk_size; + array_chunk = chunk_plus_offset(p, contents_size); + array_chunk_size = remainder_size - contents_size; + marray = (void**) (chunk2mem(array_chunk)); + set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); + remainder_size = contents_size; + } + + /* split out elements */ + for (i = 0; ; ++i) { + marray[i] = chunk2mem(p); + if (i != n_elements-1) { + if (element_size != 0) + size = element_size; + else + size = request2size(sizes[i]); + remainder_size -= size; + set_size_and_pinuse_of_inuse_chunk(m, p, size); + p = chunk_plus_offset(p, size); + } + else { /* the final element absorbs any overallocation slop */ + set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); + break; + } + } + +#if DEBUG + if (marray != chunks) { + /* final element must have exactly exhausted chunk */ + if (element_size != 0) { + assert(remainder_size == element_size); + } + else { + assert(remainder_size == request2size(sizes[i])); + } + check_inuse_chunk(m, mem2chunk(marray)); + } + for (i = 0; i != n_elements; ++i) + check_inuse_chunk(m, mem2chunk(marray[i])); + +#endif /* DEBUG */ + + POSTACTION(m); + return marray; +} + +/* Try to free all pointers in the given array. + Note: this could be made faster, by delaying consolidation, + at the price of disabling some user integrity checks, We + still optimize some consolidations by combining adjacent + chunks before freeing, which will occur often if allocated + with ialloc or the array is sorted. +*/ +static size_t internal_bulk_free(mstate m, void* array[], size_t nelem) { + size_t unfreed = 0; + if (!PREACTION(m)) { + void** a; + void** fence = &(array[nelem]); + for (a = array; a != fence; ++a) { + void* mem = *a; + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t psize = chunksize(p); +#if FOOTERS + if (get_mstate_for(p) != m) { + ++unfreed; + continue; + } +#endif + check_inuse_chunk(m, p); + *a = 0; + if (RTCHECK(ok_address(m, p) && ok_inuse(p))) { + void ** b = a + 1; /* try to merge with next chunk */ + mchunkptr next = next_chunk(p); + if (b != fence && *b == chunk2mem(next)) { + size_t newsize = chunksize(next) + psize; + set_inuse(m, p, newsize); + *b = chunk2mem(p); + } + else + dispose_chunk(m, p, psize); + } + else { + CORRUPTION_ERROR_ACTION(m); + break; + } + } + } + if (should_trim(m, m->topsize)) + sys_trim(m, 0); + POSTACTION(m); + } + return unfreed; +} + +/* Traversal */ +#if MALLOC_INSPECT_ALL +static void internal_inspect_all(mstate m, + void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + if (is_initialized(m)) { + mchunkptr top = m->top; + msegmentptr s; + for (s = &m->seg; s != 0; s = s->next) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && q->head != FENCEPOST_HEAD) { + mchunkptr next = next_chunk(q); + size_t sz = chunksize(q); + size_t used; + void* start; + if (is_inuse(q)) { + used = sz - CHUNK_OVERHEAD; /* must not be mmapped */ + start = chunk2mem(q); + } + else { + used = 0; + if (is_small(sz)) { /* offset by possible bookkeeping */ + start = (void*)((char*)q + sizeof(struct malloc_chunk)); + } + else { + start = (void*)((char*)q + sizeof(struct malloc_tree_chunk)); + } + } + if (start < (void*)next) /* skip if all space is bookkeeping */ + handler(start, next, used, arg); + if (q == top) + break; + q = next; + } + } + } +} +#endif /* MALLOC_INSPECT_ALL */ + +/* ------------------ Exported realloc, memalign, etc -------------------- */ + +#if !ONLY_MSPACES + +void* dlrealloc(void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem == 0) { + mem = dlmalloc(bytes); + } + else if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } +#ifdef REALLOC_ZERO_BYTES_FREES + else if (bytes == 0) { + dlfree(oldmem); + } +#endif /* REALLOC_ZERO_BYTES_FREES */ + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = gm; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1); + POSTACTION(m); + if (newp != 0) { + check_inuse_chunk(m, newp); + mem = chunk2mem(newp); + } + else { + mem = internal_malloc(m, bytes); + if (mem != 0) { + size_t oc = chunksize(oldp) - overhead_for(oldp); + memcpy(mem, oldmem, (oc < bytes)? oc : bytes); + internal_free(m, oldmem); + } + } + } + } + return mem; +} + +void* dlrealloc_in_place(void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem != 0) { + if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = gm; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0); + POSTACTION(m); + if (newp == oldp) { + check_inuse_chunk(m, newp); + mem = oldmem; + } + } + } + } + return mem; +} + +void* dlmemalign(size_t alignment, size_t bytes) { + if (alignment <= MALLOC_ALIGNMENT) { + return dlmalloc(bytes); + } + return internal_memalign(gm, alignment, bytes); +} + +int dlposix_memalign(void** pp, size_t alignment, size_t bytes) { + void* mem = 0; + if (alignment == MALLOC_ALIGNMENT) + mem = dlmalloc(bytes); + else { + size_t d = alignment / sizeof(void*); + size_t r = alignment % sizeof(void*); + if (r != 0 || d == 0 || (d & (d-SIZE_T_ONE)) != 0) + return EINVAL; + else if (bytes <= MAX_REQUEST - alignment) { + if (alignment < MIN_CHUNK_SIZE) + alignment = MIN_CHUNK_SIZE; + mem = internal_memalign(gm, alignment, bytes); + } + } + if (mem == 0) + return ENOMEM; + else { + *pp = mem; + return 0; + } +} + +void* dlvalloc(size_t bytes) { + size_t pagesz; + ensure_initialization(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, bytes); +} + +void* dlpvalloc(size_t bytes) { + size_t pagesz; + ensure_initialization(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE)); +} + +void** dlindependent_calloc(size_t n_elements, size_t elem_size, + void* chunks[]) { + size_t sz = elem_size; /* serves as 1-element array */ + return ialloc(gm, n_elements, &sz, 3, chunks); +} + +void** dlindependent_comalloc(size_t n_elements, size_t sizes[], + void* chunks[]) { + return ialloc(gm, n_elements, sizes, 0, chunks); +} + +size_t dlbulk_free(void* array[], size_t nelem) { + return internal_bulk_free(gm, array, nelem); +} + +#if MALLOC_INSPECT_ALL +void dlmalloc_inspect_all(void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + ensure_initialization(); + if (!PREACTION(gm)) { + internal_inspect_all(gm, handler, arg); + POSTACTION(gm); + } +} +#endif /* MALLOC_INSPECT_ALL */ + +int dlmalloc_trim(size_t pad) { + int result = 0; + ensure_initialization(); + if (!PREACTION(gm)) { + result = sys_trim(gm, pad); + POSTACTION(gm); + } + return result; +} + +size_t dlmalloc_footprint(void) { + return gm->footprint; +} + +size_t dlmalloc_max_footprint(void) { + return gm->max_footprint; +} + +size_t dlmalloc_footprint_limit(void) { + size_t maf = gm->footprint_limit; + return maf == 0 ? MAX_SIZE_T : maf; +} + +size_t dlmalloc_set_footprint_limit(size_t bytes) { + size_t result; /* invert sense of 0 */ + if (bytes == 0) + result = granularity_align(1); /* Use minimal size */ + if (bytes == MAX_SIZE_T) + result = 0; /* disable */ + else + result = granularity_align(bytes); + return gm->footprint_limit = result; +} + +#if !NO_MALLINFO +struct mallinfo dlmallinfo(void) { + return internal_mallinfo(gm); +} +#endif /* NO_MALLINFO */ + +#if !NO_MALLOC_STATS +void dlmalloc_stats() { + internal_malloc_stats(gm); +} +#endif /* NO_MALLOC_STATS */ + +int dlmallopt(int param_number, int value) { + return change_mparam(param_number, value); +} + +size_t dlmalloc_usable_size(void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (is_inuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; +} + +#endif /* !ONLY_MSPACES */ + +/* ----------------------------- user mspaces ---------------------------- */ + +#if MSPACES + +static mstate init_user_mstate(char* tbase, size_t tsize) { + size_t msize = pad_request(sizeof(struct malloc_state)); + mchunkptr mn; + mchunkptr msp = align_as_chunk(tbase); + mstate m = (mstate)(chunk2mem(msp)); + memset(m, 0, msize); + (void)INITIAL_LOCK(&m->mutex); + msp->head = (msize|INUSE_BITS); + m->seg.base = m->least_addr = tbase; + m->seg.size = m->footprint = m->max_footprint = tsize; + m->magic = mparams.magic; + m->release_checks = MAX_RELEASE_CHECK_RATE; + m->mflags = mparams.default_mflags; + m->extp = 0; + m->exts = 0; + disable_contiguous(m); + init_bins(m); + mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE); + check_top_chunk(m, m->top); + return m; +} + +mspace create_mspace(size_t capacity, int locked) { + mstate m = 0; + size_t msize; + ensure_initialization(); + msize = pad_request(sizeof(struct malloc_state)); + if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { + size_t rs = ((capacity == 0)? mparams.granularity : + (capacity + TOP_FOOT_SIZE + msize)); + size_t tsize = granularity_align(rs); + char* tbase = (char*)(CALL_MMAP(tsize)); + if (tbase != CMFAIL) { + m = init_user_mstate(tbase, tsize); + m->seg.sflags = USE_MMAP_BIT; + set_lock(m, locked); + } + } + return (mspace)m; +} + +mspace create_mspace_with_base(void* base, size_t capacity, int locked) { + mstate m = 0; + size_t msize; + ensure_initialization(); + msize = pad_request(sizeof(struct malloc_state)); + if (capacity > msize + TOP_FOOT_SIZE && + capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { + m = init_user_mstate((char*)base, capacity); + m->seg.sflags = EXTERN_BIT; + set_lock(m, locked); + } + return (mspace)m; +} + +int mspace_track_large_chunks(mspace msp, int enable) { + int ret = 0; + mstate ms = (mstate)msp; + if (!PREACTION(ms)) { + if (!use_mmap(ms)) { + ret = 1; + } + if (!enable) { + enable_mmap(ms); + } else { + disable_mmap(ms); + } + POSTACTION(ms); + } + return ret; +} + +size_t destroy_mspace(mspace msp) { + size_t freed = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + msegmentptr sp = &ms->seg; + (void)DESTROY_LOCK(&ms->mutex); /* destroy before unmapped */ + while (sp != 0) { + char* base = sp->base; + size_t size = sp->size; + flag_t flag = sp->sflags; + (void)base; /* placate people compiling -Wunused-variable */ + sp = sp->next; + if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) && + CALL_MUNMAP(base, size) == 0) + freed += size; + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return freed; +} + +/* + mspace versions of routines are near-clones of the global + versions. This is not so nice but better than the alternatives. +*/ + +void* mspace_malloc(mspace msp, size_t bytes) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (!PREACTION(ms)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = ms->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(ms, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(ms, b, p, idx); + set_inuse_and_pinuse(ms, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb > ms->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(ms, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(ms, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(ms, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(ms, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + + if (nb <= ms->dvsize) { + size_t rsize = ms->dvsize - nb; + mchunkptr p = ms->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = ms->dv = chunk_plus_offset(p, nb); + ms->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + } + else { /* exhaust dv */ + size_t dvs = ms->dvsize; + ms->dvsize = 0; + ms->dv = 0; + set_inuse_and_pinuse(ms, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb < ms->topsize) { /* Split top */ + size_t rsize = ms->topsize -= nb; + mchunkptr p = ms->top; + mchunkptr r = ms->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + mem = chunk2mem(p); + check_top_chunk(ms, ms->top); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + mem = sys_alloc(ms, nb); + + postaction: + POSTACTION(ms); + return mem; + } + + return 0; +} + +void mspace_free(mspace msp, void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); + (void)msp; /* placate people compiling -Wunused */ +#else /* FOOTERS */ + mstate fm = (mstate)msp; +#endif /* FOOTERS */ + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + + if (is_small(psize)) { + insert_small_chunk(fm, p, psize); + check_free_chunk(fm, p); + } + else { + tchunkptr tp = (tchunkptr)p; + insert_large_chunk(fm, tp, psize); + check_free_chunk(fm, p); + if (--fm->release_checks == 0) + release_unused_segments(fm); + } + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } +} + +void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) { + void* mem; + size_t req = 0; + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t)0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = internal_malloc(ms, req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; +} + +void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem == 0) { + mem = mspace_malloc(msp, bytes); + } + else if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } +#ifdef REALLOC_ZERO_BYTES_FREES + else if (bytes == 0) { + mspace_free(msp, oldmem); + } +#endif /* REALLOC_ZERO_BYTES_FREES */ + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = (mstate)msp; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1); + POSTACTION(m); + if (newp != 0) { + check_inuse_chunk(m, newp); + mem = chunk2mem(newp); + } + else { + mem = mspace_malloc(m, bytes); + if (mem != 0) { + size_t oc = chunksize(oldp) - overhead_for(oldp); + memcpy(mem, oldmem, (oc < bytes)? oc : bytes); + mspace_free(m, oldmem); + } + } + } + } + return mem; +} + +void* mspace_realloc_in_place(mspace msp, void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem != 0) { + if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = (mstate)msp; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + (void)msp; /* placate people compiling -Wunused */ + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0); + POSTACTION(m); + if (newp == oldp) { + check_inuse_chunk(m, newp); + mem = oldmem; + } + } + } + } + return mem; +} + +void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (alignment <= MALLOC_ALIGNMENT) + return mspace_malloc(msp, bytes); + return internal_memalign(ms, alignment, bytes); +} + +void** mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void* chunks[]) { + size_t sz = elem_size; /* serves as 1-element array */ + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return ialloc(ms, n_elements, &sz, 3, chunks); +} + +void** mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void* chunks[]) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return ialloc(ms, n_elements, sizes, 0, chunks); +} + +size_t mspace_bulk_free(mspace msp, void* array[], size_t nelem) { + return internal_bulk_free((mstate)msp, array, nelem); +} + +#if MALLOC_INSPECT_ALL +void mspace_inspect_all(mspace msp, + void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (!PREACTION(ms)) { + internal_inspect_all(ms, handler, arg); + POSTACTION(ms); + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } +} +#endif /* MALLOC_INSPECT_ALL */ + +int mspace_trim(mspace msp, size_t pad) { + int result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (!PREACTION(ms)) { + result = sys_trim(ms, pad); + POSTACTION(ms); + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +#if !NO_MALLOC_STATS +void mspace_malloc_stats(mspace msp) { + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + internal_malloc_stats(ms); + } + else { + USAGE_ERROR_ACTION(ms,ms); + } +} +#endif /* NO_MALLOC_STATS */ + +size_t mspace_footprint(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + result = ms->footprint; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_max_footprint(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + result = ms->max_footprint; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_footprint_limit(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + size_t maf = ms->footprint_limit; + result = (maf == 0) ? MAX_SIZE_T : maf; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_set_footprint_limit(mspace msp, size_t bytes) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (bytes == 0) + result = granularity_align(1); /* Use minimal size */ + if (bytes == MAX_SIZE_T) + result = 0; /* disable */ + else + result = granularity_align(bytes); + ms->footprint_limit = result; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +#if !NO_MALLINFO +struct mallinfo mspace_mallinfo(mspace msp) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + } + return internal_mallinfo(ms); +} +#endif /* NO_MALLINFO */ + +size_t mspace_usable_size(const void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (is_inuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; +} + +int mspace_mallopt(int param_number, int value) { + return change_mparam(param_number, value); +} + +#endif /* MSPACES */ + + +/* -------------------- Alternative MORECORE functions ------------------- */ + +/* + Guidelines for creating a custom version of MORECORE: + + * For best performance, MORECORE should allocate in multiples of pagesize. + * MORECORE may allocate more memory than requested. (Or even less, + but this will usually result in a malloc failure.) + * MORECORE must not allocate memory when given argument zero, but + instead return one past the end address of memory from previous + nonzero call. + * For best performance, consecutive calls to MORECORE with positive + arguments should return increasing addresses, indicating that + space has been contiguously extended. + * Even though consecutive calls to MORECORE need not return contiguous + addresses, it must be OK for malloc'ed chunks to span multiple + regions in those cases where they do happen to be contiguous. + * MORECORE need not handle negative arguments -- it may instead + just return MFAIL when given negative arguments. + Negative arguments are always multiples of pagesize. MORECORE + must not misinterpret negative args as large positive unsigned + args. You can suppress all such calls from even occurring by defining + MORECORE_CANNOT_TRIM, + + As an example alternative MORECORE, here is a custom allocator + kindly contributed for pre-OSX macOS. It uses virtually but not + necessarily physically contiguous non-paged memory (locked in, + present and won't get swapped out). You can use it by uncommenting + this section, adding some #includes, and setting up the appropriate + defines above: + + #define MORECORE osMoreCore + + There is also a shutdown routine that should somehow be called for + cleanup upon program exit. + + #define MAX_POOL_ENTRIES 100 + #define MINIMUM_MORECORE_SIZE (64 * 1024U) + static int next_os_pool; + void *our_os_pools[MAX_POOL_ENTRIES]; + + void *osMoreCore(int size) + { + void *ptr = 0; + static void *sbrk_top = 0; + + if (size > 0) + { + if (size < MINIMUM_MORECORE_SIZE) + size = MINIMUM_MORECORE_SIZE; + if (CurrentExecutionLevel() == kTaskLevel) + ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0); + if (ptr == 0) + { + return (void *) MFAIL; + } + // save ptrs so they can be freed during cleanup + our_os_pools[next_os_pool] = ptr; + next_os_pool++; + ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK); + sbrk_top = (char *) ptr + size; + return ptr; + } + else if (size < 0) + { + // we don't currently support shrink behavior + return (void *) MFAIL; + } + else + { + return sbrk_top; + } + } + + // cleanup any allocated memory pools + // called as last thing before shutting down driver + + void osCleanupMem(void) + { + void **ptr; + + for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++) + if (*ptr) + { + PoolDeallocate(*ptr); + *ptr = 0; + } + } + +*/ + + +/* ----------------------------------------------------------------------- +History: + v2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea + * fix bad comparison in dlposix_memalign + * don't reuse adjusted asize in sys_alloc + * add LOCK_AT_FORK -- thanks to Kirill Artamonov for the suggestion + * reduce compiler warnings -- thanks to all who reported/suggested these + + v2.8.5 Sun May 22 10:26:02 2011 Doug Lea (dl at gee) + * Always perform unlink checks unless INSECURE + * Add posix_memalign. + * Improve realloc to expand in more cases; expose realloc_in_place. + Thanks to Peter Buhr for the suggestion. + * Add footprint_limit, inspect_all, bulk_free. Thanks + to Barry Hayes and others for the suggestions. + * Internal refactorings to avoid calls while holding locks + * Use non-reentrant locks by default. Thanks to Roland McGrath + for the suggestion. + * Small fixes to mspace_destroy, reset_on_error. + * Various configuration extensions/changes. Thanks + to all who contributed these. + + V2.8.4a Thu Apr 28 14:39:43 2011 (dl at gee.cs.oswego.edu) + * Update Creative Commons URL + + V2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee) + * Use zeros instead of prev foot for is_mmapped + * Add mspace_track_large_chunks; thanks to Jean Brouwers + * Fix set_inuse in internal_realloc; thanks to Jean Brouwers + * Fix insufficient sys_alloc padding when using 16byte alignment + * Fix bad error check in mspace_footprint + * Adaptations for ptmalloc; thanks to Wolfram Gloger. + * Reentrant spin locks; thanks to Earl Chew and others + * Win32 improvements; thanks to Niall Douglas and Earl Chew + * Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options + * Extension hook in malloc_state + * Various small adjustments to reduce warnings on some compilers + * Various configuration extensions/changes for more platforms. Thanks + to all who contributed these. + + V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee) + * Add max_footprint functions + * Ensure all appropriate literals are size_t + * Fix conditional compilation problem for some #define settings + * Avoid concatenating segments with the one provided + in create_mspace_with_base + * Rename some variables to avoid compiler shadowing warnings + * Use explicit lock initialization. + * Better handling of sbrk interference. + * Simplify and fix segment insertion, trimming and mspace_destroy + * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x + * Thanks especially to Dennis Flanagan for help on these. + + V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee) + * Fix memalign brace error. + + V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee) + * Fix improper #endif nesting in C++ + * Add explicit casts needed for C++ + + V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee) + * Use trees for large bins + * Support mspaces + * Use segments to unify sbrk-based and mmap-based system allocation, + removing need for emulation on most platforms without sbrk. + * Default safety checks + * Optional footer checks. Thanks to William Robertson for the idea. + * Internal code refactoring + * Incorporate suggestions and platform-specific changes. + Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas, + Aaron Bachmann, Emery Berger, and others. + * Speed up non-fastbin processing enough to remove fastbins. + * Remove useless cfree() to avoid conflicts with other apps. + * Remove internal memcpy, memset. Compilers handle builtins better. + * Remove some options that no one ever used and rename others. + + V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee) + * Fix malloc_state bitmap array misdeclaration + + V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee) + * Allow tuning of FIRST_SORTED_BIN_SIZE + * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte. + * Better detection and support for non-contiguousness of MORECORE. + Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger + * Bypass most of malloc if no frees. Thanks To Emery Berger. + * Fix freeing of old top non-contiguous chunk im sysmalloc. + * Raised default trim and map thresholds to 256K. + * Fix mmap-related #defines. Thanks to Lubos Lunak. + * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield. + * Branch-free bin calculation + * Default trim and mmap thresholds now 256K. + + V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee) + * Introduce independent_comalloc and independent_calloc. + Thanks to Michael Pachos for motivation and help. + * Make optional .h file available + * Allow > 2GB requests on 32bit systems. + * new WIN32 sbrk, mmap, munmap, lock code from . + Thanks also to Andreas Mueller , + and Anonymous. + * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for + helping test this.) + * memalign: check alignment arg + * realloc: don't try to shift chunks backwards, since this + leads to more fragmentation in some programs and doesn't + seem to help in any others. + * Collect all cases in malloc requiring system memory into sysmalloc + * Use mmap as backup to sbrk + * Place all internal state in malloc_state + * Introduce fastbins (although similar to 2.5.1) + * Many minor tunings and cosmetic improvements + * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK + * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS + Thanks to Tony E. Bennett and others. + * Include errno.h to support default failure action. + + V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee) + * return null for negative arguments + * Added Several WIN32 cleanups from Martin C. Fong + * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h' + (e.g. WIN32 platforms) + * Cleanup header file inclusion for WIN32 platforms + * Cleanup code to avoid Microsoft Visual C++ compiler complaints + * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing + memory allocation routines + * Set 'malloc_getpagesize' for WIN32 platforms (needs more work) + * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to + usage of 'assert' in non-WIN32 code + * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to + avoid infinite loop + * Always call 'fREe()' rather than 'free()' + + V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee) + * Fixed ordering problem with boundary-stamping + + V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee) + * Added pvalloc, as recommended by H.J. Liu + * Added 64bit pointer support mainly from Wolfram Gloger + * Added anonymously donated WIN32 sbrk emulation + * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen + * malloc_extend_top: fix mask error that caused wastage after + foreign sbrks + * Add linux mremap support code from HJ Liu + + V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee) + * Integrated most documentation with the code. + * Add support for mmap, with help from + Wolfram Gloger (Gloger@lrz.uni-muenchen.de). + * Use last_remainder in more cases. + * Pack bins using idea from colin@nyx10.cs.du.edu + * Use ordered bins instead of best-fit threshhold + * Eliminate block-local decls to simplify tracing and debugging. + * Support another case of realloc via move into top + * Fix error occuring when initial sbrk_base not word-aligned. + * Rely on page size for units instead of SBRK_UNIT to + avoid surprises about sbrk alignment conventions. + * Add mallinfo, mallopt. Thanks to Raymond Nijssen + (raymond@es.ele.tue.nl) for the suggestion. + * Add `pad' argument to malloc_trim and top_pad mallopt parameter. + * More precautions for cases where other routines call sbrk, + courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de). + * Added macros etc., allowing use in linux libc from + H.J. Lu (hjl@gnu.ai.mit.edu) + * Inverted this history list + + V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee) + * Re-tuned and fixed to behave more nicely with V2.6.0 changes. + * Removed all preallocation code since under current scheme + the work required to undo bad preallocations exceeds + the work saved in good cases for most test programs. + * No longer use return list or unconsolidated bins since + no scheme using them consistently outperforms those that don't + given above changes. + * Use best fit for very large chunks to prevent some worst-cases. + * Added some support for debugging + + V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee) + * Removed footers when chunks are in use. Thanks to + Paul Wilson (wilson@cs.texas.edu) for the suggestion. + + V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee) + * Added malloc_trim, with help from Wolfram Gloger + (wmglo@Dent.MED.Uni-Muenchen.DE). + + V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g) + + V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g) + * realloc: try to expand in both directions + * malloc: swap order of clean-bin strategy; + * realloc: only conditionally expand backwards + * Try not to scavenge used bins + * Use bin counts as a guide to preallocation + * Occasionally bin return list chunks in first scan + * Add a few optimizations from colin@nyx10.cs.du.edu + + V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g) + * faster bin computation & slightly different binning + * merged all consolidations to one part of malloc proper + (eliminating old malloc_find_space & malloc_clean_bin) + * Scan 2 returns chunks (not just 1) + * Propagate failure in realloc if malloc returns 0 + * Add stuff to allow compilation on non-ANSI compilers + from kpv@research.att.com + + V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu) + * removed potential for odd address access in prev_chunk + * removed dependency on getpagesize.h + * misc cosmetics and a bit more internal documentation + * anticosmetics: mangled names in macros to evade debugger strangeness + * tested on sparc, hp-700, dec-mips, rs6000 + with gcc & native cc (hp, dec only) allowing + Detlefs & Zorn comparison study (in SIGPLAN Notices.) + + Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu) + * Based loosely on libg++-1.2X malloc. (It retains some of the overall + structure of old version, but most details differ.) + +*/ + +#endif /* !HAVE_MALLOC */ + +#ifdef HAVE_MALLOC +static void * SDLCALL real_malloc(size_t s) { return malloc(s); } +static void * SDLCALL real_calloc(size_t n, size_t s) { return calloc(n, s); } +static void * SDLCALL real_realloc(void *p, size_t s) { return realloc(p,s); } +static void SDLCALL real_free(void *p) { free(p); } +#else +#define real_malloc dlmalloc +#define real_calloc dlcalloc +#define real_realloc dlrealloc +#define real_free dlfree +#endif + +// mark the allocator entry points as KEEPALIVE so we can call these from JavaScript. +// otherwise they could could get so aggressively inlined that their symbols +// don't exist at all in the final binary! +#ifdef SDL_PLATFORM_EMSCRIPTEN +#include +extern SDL_DECLSPEC SDL_MALLOC EMSCRIPTEN_KEEPALIVE void * SDLCALL SDL_malloc(size_t size); +extern SDL_DECLSPEC SDL_MALLOC SDL_ALLOC_SIZE2(1, 2) EMSCRIPTEN_KEEPALIVE void * SDLCALL SDL_calloc(size_t nmemb, size_t size); +extern SDL_DECLSPEC SDL_ALLOC_SIZE(2) EMSCRIPTEN_KEEPALIVE void * SDLCALL SDL_realloc(void *mem, size_t size); +extern SDL_DECLSPEC EMSCRIPTEN_KEEPALIVE void SDLCALL SDL_free(void *mem); +#endif + +/* Memory functions used by SDL that can be replaced by the application */ +static struct +{ + SDL_malloc_func malloc_func; + SDL_calloc_func calloc_func; + SDL_realloc_func realloc_func; + SDL_free_func free_func; + SDL_AtomicInt num_allocations; +} s_mem = { + real_malloc, real_calloc, real_realloc, real_free, { 0 } +}; + +// Define this if you want to track the number of allocations active +// #define SDL_TRACK_ALLOCATION_COUNT +#ifdef SDL_TRACK_ALLOCATION_COUNT +#define INCREMENT_ALLOCATION_COUNT() (void)SDL_AtomicIncRef(&s_mem.num_allocations) +#define DECREMENT_ALLOCATION_COUNT() (void)SDL_AtomicDecRef(&s_mem.num_allocations) +#else +#define INCREMENT_ALLOCATION_COUNT() +#define DECREMENT_ALLOCATION_COUNT() +#endif + + +void SDL_GetOriginalMemoryFunctions(SDL_malloc_func *malloc_func, + SDL_calloc_func *calloc_func, + SDL_realloc_func *realloc_func, + SDL_free_func *free_func) +{ + if (malloc_func) { + *malloc_func = real_malloc; + } + if (calloc_func) { + *calloc_func = real_calloc; + } + if (realloc_func) { + *realloc_func = real_realloc; + } + if (free_func) { + *free_func = real_free; + } +} + +void SDL_GetMemoryFunctions(SDL_malloc_func *malloc_func, + SDL_calloc_func *calloc_func, + SDL_realloc_func *realloc_func, + SDL_free_func *free_func) +{ + if (malloc_func) { + *malloc_func = s_mem.malloc_func; + } + if (calloc_func) { + *calloc_func = s_mem.calloc_func; + } + if (realloc_func) { + *realloc_func = s_mem.realloc_func; + } + if (free_func) { + *free_func = s_mem.free_func; + } +} + +bool SDL_SetMemoryFunctions(SDL_malloc_func malloc_func, + SDL_calloc_func calloc_func, + SDL_realloc_func realloc_func, + SDL_free_func free_func) +{ + if (!malloc_func) { + return SDL_InvalidParamError("malloc_func"); + } + if (!calloc_func) { + return SDL_InvalidParamError("calloc_func"); + } + if (!realloc_func) { + return SDL_InvalidParamError("realloc_func"); + } + if (!free_func) { + return SDL_InvalidParamError("free_func"); + } + + s_mem.malloc_func = malloc_func; + s_mem.calloc_func = calloc_func; + s_mem.realloc_func = realloc_func; + s_mem.free_func = free_func; + return true; +} + +int SDL_GetNumAllocations(void) +{ +#ifdef SDL_TRACK_ALLOCATION_COUNT + return SDL_GetAtomicInt(&s_mem.num_allocations); +#else + return -1; +#endif +} + +void *SDL_malloc(size_t size) +{ + void *mem; + + if (!size) { + size = 1; + } + + mem = s_mem.malloc_func(size); + if (mem) { + INCREMENT_ALLOCATION_COUNT(); + } else { + SDL_OutOfMemory(); + } + + return mem; +} + +void *SDL_calloc(size_t nmemb, size_t size) +{ + void *mem; + + if (!nmemb || !size) { + nmemb = 1; + size = 1; + } + + mem = s_mem.calloc_func(nmemb, size); + if (mem) { + INCREMENT_ALLOCATION_COUNT(); + } else { + SDL_OutOfMemory(); + } + + return mem; +} + +void *SDL_realloc(void *ptr, size_t size) +{ + void *mem; + + if (!size) { + size = 1; + } + + mem = s_mem.realloc_func(ptr, size); + if (mem && !ptr) { + INCREMENT_ALLOCATION_COUNT(); + } else if (!mem) { + SDL_OutOfMemory(); + } + + return mem; +} + +void SDL_free(void *ptr) +{ + if (!ptr) { + return; + } + + s_mem.free_func(ptr); + DECREMENT_ALLOCATION_COUNT(); +} diff --git a/thirdparty/sdl/stdlib/SDL_memcpy.c b/thirdparty/sdl/stdlib/SDL_memcpy.c new file mode 100644 index 00000000000..315edf023e3 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_memcpy.c @@ -0,0 +1,101 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + + +#ifdef SDL_memcpy +#undef SDL_memcpy +#endif +#if SDL_DYNAMIC_API +#define SDL_memcpy SDL_memcpy_REAL +#endif +void *SDL_memcpy(SDL_OUT_BYTECAP(len) void *dst, SDL_IN_BYTECAP(len) const void *src, size_t len) +{ +#if defined(__GNUC__) && (defined(HAVE_LIBC) && HAVE_LIBC) + /* Presumably this is well tuned for speed. + On my machine this is twice as fast as the C code below. + */ + return __builtin_memcpy(dst, src, len); +#elif defined(HAVE_MEMCPY) + return memcpy(dst, src, len); +#elif defined(HAVE_BCOPY) + bcopy(src, dst, len); + return dst; +#else + /* GCC 4.9.0 with -O3 will generate movaps instructions with the loop + using Uint32* pointers, so we need to make sure the pointers are + aligned before we loop using them. + */ + if (((uintptr_t)src & 0x3) || ((uintptr_t)dst & 0x3)) { + // Do an unaligned byte copy + Uint8 *srcp1 = (Uint8 *)src; + Uint8 *dstp1 = (Uint8 *)dst; + + while (len--) { + *dstp1++ = *srcp1++; + } + } else { + size_t left = (len % 4); + Uint32 *srcp4, *dstp4; + Uint8 *srcp1, *dstp1; + + srcp4 = (Uint32 *)src; + dstp4 = (Uint32 *)dst; + len /= 4; + while (len--) { + *dstp4++ = *srcp4++; + } + + srcp1 = (Uint8 *)srcp4; + dstp1 = (Uint8 *)dstp4; + switch (left) { + case 3: + *dstp1++ = *srcp1++; + SDL_FALLTHROUGH; + case 2: + *dstp1++ = *srcp1++; + SDL_FALLTHROUGH; + case 1: + *dstp1++ = *srcp1++; + } + } + return dst; +#endif // HAVE_MEMCPY +} + +/* The optimizer on Visual Studio 2005 and later generates memcpy() and memset() calls. + We will provide our own implementation if we're not building with a C runtime. */ +#ifndef HAVE_LIBC +// NOLINTNEXTLINE(readability-redundant-declaration) +extern void *memcpy(void *dst, const void *src, size_t len); +#if defined(_MSC_VER) && !defined(__INTEL_LLVM_COMPILER) +#pragma intrinsic(memcpy) +#endif + +#if defined(_MSC_VER) && !defined(__clang__) +#pragma function(memcpy) +#endif +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void *memcpy(void *dst, const void *src, size_t len) +{ + return SDL_memcpy(dst, src, len); +} +#endif // !HAVE_LIBC diff --git a/thirdparty/sdl/stdlib/SDL_memmove.c b/thirdparty/sdl/stdlib/SDL_memmove.c new file mode 100644 index 00000000000..4e0d26c4bf5 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_memmove.c @@ -0,0 +1,73 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + + +#ifdef SDL_memmove +#undef SDL_memmove +#endif +#if SDL_DYNAMIC_API +#define SDL_memmove SDL_memmove_REAL +#endif +void *SDL_memmove(SDL_OUT_BYTECAP(len) void *dst, SDL_IN_BYTECAP(len) const void *src, size_t len) +{ +#if defined(__GNUC__) && (defined(HAVE_LIBC) && HAVE_LIBC) + // Presumably this is well tuned for speed. + return __builtin_memmove(dst, src, len); +#elif defined(HAVE_MEMMOVE) + return memmove(dst, src, len); +#else + char *srcp = (char *)src; + char *dstp = (char *)dst; + + if (src < dst) { + srcp += len - 1; + dstp += len - 1; + while (len--) { + *dstp-- = *srcp--; + } + } else { + while (len--) { + *dstp++ = *srcp++; + } + } + return dst; +#endif // HAVE_MEMMOVE +} + + +#ifndef HAVE_LIBC +// NOLINTNEXTLINE(readability-redundant-declaration) +extern void *memmove(void *dst, const void *src, size_t len); +#if defined(_MSC_VER) && !defined(__INTEL_LLVM_COMPILER) +#pragma intrinsic(memmove) +#endif + +#if defined(_MSC_VER) && !defined(__clang__) +#pragma function(memmove) +#endif +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void *memmove(void *dst, const void *src, size_t len) +{ + return SDL_memmove(dst, src, len); +} +#endif // !HAVE_LIBC + diff --git a/thirdparty/sdl/stdlib/SDL_memset.c b/thirdparty/sdl/stdlib/SDL_memset.c new file mode 100644 index 00000000000..324f91787d2 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_memset.c @@ -0,0 +1,139 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + + +#ifdef SDL_memset +#undef SDL_memset +#endif +#if SDL_DYNAMIC_API +#define SDL_memset SDL_memset_REAL +#endif +void *SDL_memset(SDL_OUT_BYTECAP(len) void *dst, int c, size_t len) +{ +#if defined(__GNUC__) && (defined(HAVE_LIBC) && HAVE_LIBC) + return __builtin_memset(dst, c, len); +#elif defined(HAVE_MEMSET) + return memset(dst, c, len); +#else + size_t left; + Uint32 *dstp4; + Uint8 *dstp1 = (Uint8 *)dst; + Uint8 value1; + Uint32 value4; + + // The value used in memset() is a byte, passed as an int + c &= 0xff; + + /* The destination pointer needs to be aligned on a 4-byte boundary to + * execute a 32-bit set. Set first bytes manually if needed until it is + * aligned. */ + value1 = (Uint8)c; + while ((uintptr_t)dstp1 & 0x3) { + if (len--) { + *dstp1++ = value1; + } else { + return dst; + } + } + + value4 = ((Uint32)c | ((Uint32)c << 8) | ((Uint32)c << 16) | ((Uint32)c << 24)); + dstp4 = (Uint32 *)dstp1; + left = (len % 4); + len /= 4; + while (len--) { + *dstp4++ = value4; + } + + dstp1 = (Uint8 *)dstp4; + switch (left) { + case 3: + *dstp1++ = value1; + SDL_FALLTHROUGH; + case 2: + *dstp1++ = value1; + SDL_FALLTHROUGH; + case 1: + *dstp1++ = value1; + } + + return dst; +#endif // HAVE_MEMSET +} + +// Note that memset() is a byte assignment and this is a 32-bit assignment, so they're not directly equivalent. +void *SDL_memset4(void *dst, Uint32 val, size_t dwords) +{ +#if defined(__APPLE__) && defined(HAVE_STRING_H) + memset_pattern4(dst, &val, dwords * 4); +#elif defined(__GNUC__) && defined(__i386__) + int u0, u1, u2; + __asm__ __volatile__( + "cld \n\t" + "rep ; stosl \n\t" + : "=&D"(u0), "=&a"(u1), "=&c"(u2) + : "0"(dst), "1"(val), "2"(SDL_static_cast(Uint32, dwords)) + : "memory"); +#else + size_t _n = (dwords + 3) / 4; + Uint32 *_p = SDL_static_cast(Uint32 *, dst); + Uint32 _val = (val); + if (dwords == 0) { + return dst; + } + switch (dwords % 4) { + case 0: + do { + *_p++ = _val; + SDL_FALLTHROUGH; + case 3: + *_p++ = _val; + SDL_FALLTHROUGH; + case 2: + *_p++ = _val; + SDL_FALLTHROUGH; + case 1: + *_p++ = _val; + } while (--_n); + } +#endif + return dst; +} + +/* The optimizer on Visual Studio 2005 and later generates memcpy() and memset() calls. + We will provide our own implementation if we're not building with a C runtime. */ +#ifndef HAVE_LIBC +// NOLINTNEXTLINE(readability-redundant-declaration) +extern void *memset(void *dst, int c, size_t len); +#if defined(_MSC_VER) && !defined(__INTEL_LLVM_COMPILER) +#pragma intrinsic(memset) +#endif + +#if defined(_MSC_VER) && !defined(__clang__) +#pragma function(memset) +#endif +// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) +void *memset(void *dst, int c, size_t len) +{ + return SDL_memset(dst, c, len); +} +#endif // !HAVE_LIBC + diff --git a/thirdparty/sdl/stdlib/SDL_mslibc.c b/thirdparty/sdl/stdlib/SDL_mslibc.c new file mode 100644 index 00000000000..6698403fe89 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_mslibc.c @@ -0,0 +1,746 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This file contains SDL replacements for functions in the C library + +#if !defined(HAVE_LIBC) && !defined(SDL_STATIC_LIB) + +// These are some C runtime intrinsics that need to be defined + +#ifdef _MSC_VER + +#ifndef __FLTUSED__ +#define __FLTUSED__ +__declspec(selectany) int _fltused = 1; +#endif + +#ifdef _M_IX86 + +// Float to long +void __declspec(naked) _ftol() +{ + /* *INDENT-OFF* */ + __asm { + push ebp + mov ebp,esp + sub esp,20h + and esp,0FFFFFFF0h + fld st(0) + fst dword ptr [esp+18h] + fistp qword ptr [esp+10h] + fild qword ptr [esp+10h] + mov edx,dword ptr [esp+18h] + mov eax,dword ptr [esp+10h] + test eax,eax + je integer_QnaN_or_zero +arg_is_not_integer_QnaN: + fsubp st(1),st + test edx,edx + jns positive + fstp dword ptr [esp] + mov ecx,dword ptr [esp] + xor ecx,80000000h + add ecx,7FFFFFFFh + adc eax,0 + mov edx,dword ptr [esp+14h] + adc edx,0 + jmp localexit +positive: + fstp dword ptr [esp] + mov ecx,dword ptr [esp] + add ecx,7FFFFFFFh + sbb eax,0 + mov edx,dword ptr [esp+14h] + sbb edx,0 + jmp localexit +integer_QnaN_or_zero: + mov edx,dword ptr [esp+14h] + test edx,7FFFFFFFh + jne arg_is_not_integer_QnaN + fstp dword ptr [esp+18h] + fstp dword ptr [esp+18h] +localexit: + leave + ret + } + /* *INDENT-ON* */ +} + +void _ftol2_sse() +{ + _ftol(); +} + +void _ftol2() +{ + _ftol(); +} + +// 64-bit math operators for 32-bit systems +void __declspec(naked) _allmul() +{ + /* *INDENT-OFF* */ + __asm { + mov eax, dword ptr[esp+8] + mov ecx, dword ptr[esp+10h] + or ecx, eax + mov ecx, dword ptr[esp+0Ch] + jne hard + mov eax, dword ptr[esp+4] + mul ecx + ret 10h +hard: + push ebx + mul ecx + mov ebx, eax + mov eax, dword ptr[esp+8] + mul dword ptr[esp+14h] + add ebx, eax + mov eax, dword ptr[esp+8] + mul ecx + add edx, ebx + pop ebx + ret 10h + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _alldiv() +{ + /* *INDENT-OFF* */ + __asm { + push edi + push esi + push ebx + xor edi,edi + mov eax,dword ptr [esp+14h] + or eax,eax + jge L1 + inc edi + mov edx,dword ptr [esp+10h] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+14h],eax + mov dword ptr [esp+10h],edx +L1: + mov eax,dword ptr [esp+1Ch] + or eax,eax + jge L2 + inc edi + mov edx,dword ptr [esp+18h] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+1Ch],eax + mov dword ptr [esp+18h],edx +L2: + or eax,eax + jne L3 + mov ecx,dword ptr [esp+18h] + mov eax,dword ptr [esp+14h] + xor edx,edx + div ecx + mov ebx,eax + mov eax,dword ptr [esp+10h] + div ecx + mov edx,ebx + jmp L4 +L3: + mov ebx,eax + mov ecx,dword ptr [esp+18h] + mov edx,dword ptr [esp+14h] + mov eax,dword ptr [esp+10h] +L5: + shr ebx,1 + rcr ecx,1 + shr edx,1 + rcr eax,1 + or ebx,ebx + jne L5 + div ecx + mov esi,eax + mul dword ptr [esp+1Ch] + mov ecx,eax + mov eax,dword ptr [esp+18h] + mul esi + add edx,ecx + jb L6 + cmp edx,dword ptr [esp+14h] + ja L6 + jb L7 + cmp eax,dword ptr [esp+10h] + jbe L7 +L6: + dec esi +L7: + xor edx,edx + mov eax,esi +L4: + dec edi + jne L8 + neg edx + neg eax + sbb edx,0 +L8: + pop ebx + pop esi + pop edi + ret 10h + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _aulldiv() +{ + /* *INDENT-OFF* */ + __asm { + push ebx + push esi + mov eax,dword ptr [esp+18h] + or eax,eax + jne L1 + mov ecx,dword ptr [esp+14h] + mov eax,dword ptr [esp+10h] + xor edx,edx + div ecx + mov ebx,eax + mov eax,dword ptr [esp+0Ch] + div ecx + mov edx,ebx + jmp L2 +L1: + mov ecx,eax + mov ebx,dword ptr [esp+14h] + mov edx,dword ptr [esp+10h] + mov eax,dword ptr [esp+0Ch] +L3: + shr ecx,1 + rcr ebx,1 + shr edx,1 + rcr eax,1 + or ecx,ecx + jne L3 + div ebx + mov esi,eax + mul dword ptr [esp+18h] + mov ecx,eax + mov eax,dword ptr [esp+14h] + mul esi + add edx,ecx + jb L4 + cmp edx,dword ptr [esp+10h] + ja L4 + jb L5 + cmp eax,dword ptr [esp+0Ch] + jbe L5 +L4: + dec esi +L5: + xor edx,edx + mov eax,esi +L2: + pop esi + pop ebx + ret 10h + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _allrem() +{ + /* *INDENT-OFF* */ + __asm { + push ebx + push edi + xor edi,edi + mov eax,dword ptr [esp+10h] + or eax,eax + jge L1 + inc edi + mov edx,dword ptr [esp+0Ch] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+10h],eax + mov dword ptr [esp+0Ch],edx +L1: + mov eax,dword ptr [esp+18h] + or eax,eax + jge L2 + mov edx,dword ptr [esp+14h] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+18h],eax + mov dword ptr [esp+14h],edx +L2: + or eax,eax + jne L3 + mov ecx,dword ptr [esp+14h] + mov eax,dword ptr [esp+10h] + xor edx,edx + div ecx + mov eax,dword ptr [esp+0Ch] + div ecx + mov eax,edx + xor edx,edx + dec edi + jns L4 + jmp L8 +L3: + mov ebx,eax + mov ecx,dword ptr [esp+14h] + mov edx,dword ptr [esp+10h] + mov eax,dword ptr [esp+0Ch] +L5: + shr ebx,1 + rcr ecx,1 + shr edx,1 + rcr eax,1 + or ebx,ebx + jne L5 + div ecx + mov ecx,eax + mul dword ptr [esp+18h] + xchg eax,ecx + mul dword ptr [esp+14h] + add edx,ecx + jb L6 + cmp edx,dword ptr [esp+10h] + ja L6 + jb L7 + cmp eax,dword ptr [esp+0Ch] + jbe L7 +L6: + sub eax,dword ptr [esp+14h] + sbb edx,dword ptr [esp+18h] +L7: + sub eax,dword ptr [esp+0Ch] + sbb edx,dword ptr [esp+10h] + dec edi + jns L8 +L4: + neg edx + neg eax + sbb edx,0 +L8: + pop edi + pop ebx + ret 10h + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _aullrem() +{ + /* *INDENT-OFF* */ + __asm { + push ebx + mov eax,dword ptr [esp+14h] + or eax,eax + jne L1 + mov ecx,dword ptr [esp+10h] + mov eax,dword ptr [esp+0Ch] + xor edx,edx + div ecx + mov eax,dword ptr [esp+8] + div ecx + mov eax,edx + xor edx,edx + jmp L2 +L1: + mov ecx,eax + mov ebx,dword ptr [esp+10h] + mov edx,dword ptr [esp+0Ch] + mov eax,dword ptr [esp+8] +L3: + shr ecx,1 + rcr ebx,1 + shr edx,1 + rcr eax,1 + or ecx,ecx + jne L3 + div ebx + mov ecx,eax + mul dword ptr [esp+14h] + xchg eax,ecx + mul dword ptr [esp+10h] + add edx,ecx + jb L4 + cmp edx,dword ptr [esp+0Ch] + ja L4 + jb L5 + cmp eax,dword ptr [esp+8] + jbe L5 +L4: + sub eax,dword ptr [esp+10h] + sbb edx,dword ptr [esp+14h] +L5: + sub eax,dword ptr [esp+8] + sbb edx,dword ptr [esp+0Ch] + neg edx + neg eax + sbb edx,0 +L2: + pop ebx + ret 10h + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _alldvrm() +{ + /* *INDENT-OFF* */ + __asm { + push edi + push esi + push ebp + xor edi,edi + xor ebp,ebp + mov eax,dword ptr [esp+14h] + or eax,eax + jge L1 + inc edi + inc ebp + mov edx,dword ptr [esp+10h] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+14h],eax + mov dword ptr [esp+10h],edx +L1: + mov eax,dword ptr [esp+1Ch] + or eax,eax + jge L2 + inc edi + mov edx,dword ptr [esp+18h] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+1Ch],eax + mov dword ptr [esp+18h],edx +L2: + or eax,eax + jne L3 + mov ecx,dword ptr [esp+18h] + mov eax,dword ptr [esp+14h] + xor edx,edx + div ecx + mov ebx,eax + mov eax,dword ptr [esp+10h] + div ecx + mov esi,eax + mov eax,ebx + mul dword ptr [esp+18h] + mov ecx,eax + mov eax,esi + mul dword ptr [esp+18h] + add edx,ecx + jmp L4 +L3: + mov ebx,eax + mov ecx,dword ptr [esp+18h] + mov edx,dword ptr [esp+14h] + mov eax,dword ptr [esp+10h] +L5: + shr ebx,1 + rcr ecx,1 + shr edx,1 + rcr eax,1 + or ebx,ebx + jne L5 + div ecx + mov esi,eax + mul dword ptr [esp+1Ch] + mov ecx,eax + mov eax,dword ptr [esp+18h] + mul esi + add edx,ecx + jb L6 + cmp edx,dword ptr [esp+14h] + ja L6 + jb L7 + cmp eax,dword ptr [esp+10h] + jbe L7 +L6: + dec esi + sub eax,dword ptr [esp+18h] + sbb edx,dword ptr [esp+1Ch] +L7: + xor ebx,ebx +L4: + sub eax,dword ptr [esp+10h] + sbb edx,dword ptr [esp+14h] + dec ebp + jns L9 + neg edx + neg eax + sbb edx,0 +L9: + mov ecx,edx + mov edx,ebx + mov ebx,ecx + mov ecx,eax + mov eax,esi + dec edi + jne L8 + neg edx + neg eax + sbb edx,0 +L8: + pop ebp + pop esi + pop edi + ret 10h + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _aulldvrm() +{ + /* *INDENT-OFF* */ + __asm { + push esi + mov eax,dword ptr [esp+14h] + or eax,eax + jne L1 + mov ecx,dword ptr [esp+10h] + mov eax,dword ptr [esp+0Ch] + xor edx,edx + div ecx + mov ebx,eax + mov eax,dword ptr [esp+8] + div ecx + mov esi,eax + mov eax,ebx + mul dword ptr [esp+10h] + mov ecx,eax + mov eax,esi + mul dword ptr [esp+10h] + add edx,ecx + jmp L2 +L1: + mov ecx,eax + mov ebx,dword ptr [esp+10h] + mov edx,dword ptr [esp+0Ch] + mov eax,dword ptr [esp+8] +L3: + shr ecx,1 + rcr ebx,1 + shr edx,1 + rcr eax,1 + or ecx,ecx + jne L3 + div ebx + mov esi,eax + mul dword ptr [esp+14h] + mov ecx,eax + mov eax,dword ptr [esp+10h] + mul esi + add edx,ecx + jb L4 + cmp edx,dword ptr [esp+0Ch] + ja L4 + jb L5 + cmp eax,dword ptr [esp+8] + jbe L5 +L4: + dec esi + sub eax,dword ptr [esp+10h] + sbb edx,dword ptr [esp+14h] +L5: + xor ebx,ebx +L2: + sub eax,dword ptr [esp+8] + sbb edx,dword ptr [esp+0Ch] + neg edx + neg eax + sbb edx,0 + mov ecx,edx + mov edx,ebx + mov ebx,ecx + mov ecx,eax + mov eax,esi + pop esi + ret 10h + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _allshl() +{ + /* *INDENT-OFF* */ + __asm { + cmp cl,40h + jae RETZERO + cmp cl,20h + jae MORE32 + shld edx,eax,cl + shl eax,cl + ret +MORE32: + mov edx,eax + xor eax,eax + and cl,1Fh + shl edx,cl + ret +RETZERO: + xor eax,eax + xor edx,edx + ret + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _allshr() +{ + /* *INDENT-OFF* */ + __asm { + cmp cl,3Fh + jae RETSIGN + cmp cl,20h + jae MORE32 + shrd eax,edx,cl + sar edx,cl + ret +MORE32: + mov eax,edx + sar edx,1Fh + and cl,1Fh + sar eax,cl + ret +RETSIGN: + sar edx,1Fh + mov eax,edx + ret + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _aullshr() +{ + /* *INDENT-OFF* */ + __asm { + cmp cl,40h + jae RETZERO + cmp cl,20h + jae MORE32 + shrd eax,edx,cl + shr edx,cl + ret +MORE32: + mov eax,edx + xor edx,edx + and cl,1Fh + shr eax,cl + ret +RETZERO: + xor eax,eax + xor edx,edx + ret + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _chkstk(void) +{ + __asm { + push ecx + mov ecx,esp ; lea ecx,dword ptr [esp]+4 + add ecx,4 + sub ecx,eax + sbb eax,eax + not eax + and ecx,eax + mov eax,esp + and eax,0xfffff000 +L1: + cmp ecx,eax + jb short L2 + mov eax,ecx + pop ecx + xchg esp,eax + mov eax,dword ptr [eax] + mov dword ptr [esp],eax + ret +L2: + sub eax,0x1000 + test dword ptr [eax],eax + jmp short L1 + } +} + +void __declspec(naked) _alloca_probe_8(void) +{ + /* *INDENT-OFF* */ + __asm { + push ecx + mov ecx,esp ; lea ecx,dword ptr [esp]+8 + add ecx,8 + sub ecx,eax + and ecx,0x7 + add eax,ecx + sbb ecx,ecx + or eax,ecx + pop ecx + jmp _chkstk + } + /* *INDENT-ON* */ +} + +void __declspec(naked) _alloca_probe_16(void) +{ + /* *INDENT-OFF* */ + __asm { + push ecx + mov ecx,esp ; lea ecx,dword ptr [esp]+8 + add ecx,8 + sub ecx,eax + and ecx,0xf + add eax,ecx + sbb ecx,ecx + or eax,ecx + pop ecx + jmp _chkstk + } + /* *INDENT-ON* */ +} + +#endif // _M_IX86 + +#endif // MSC_VER + +#ifdef __ICL +/* The classic Intel compiler generates calls to _intel_fast_memcpy + * and _intel_fast_memset when building an optimized SDL library */ +void *_intel_fast_memcpy(void *dst, const void *src, size_t len) +{ + return SDL_memcpy(dst, src, len); +} +void *_intel_fast_memset(void *dst, int c, size_t len) +{ + return SDL_memset(dst, c, len); +} +#endif + +#endif // !HAVE_LIBC && !SDL_STATIC_LIB diff --git a/thirdparty/sdl/stdlib/SDL_murmur3.c b/thirdparty/sdl/stdlib/SDL_murmur3.c new file mode 100644 index 00000000000..6b030bd9509 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_murmur3.c @@ -0,0 +1,87 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// Public domain murmur3 32-bit hash algorithm +// +// Adapted from: https://en.wikipedia.org/wiki/MurmurHash + +static SDL_INLINE Uint32 murmur_32_scramble(Uint32 k) +{ + k *= 0xcc9e2d51; + k = (k << 15) | (k >> 17); + k *= 0x1b873593; + return k; +} + +Uint32 SDLCALL SDL_murmur3_32(const void *data, size_t len, Uint32 seed) +{ + const Uint8 *bytes = (const Uint8 *)data; + Uint32 hash = seed; + Uint32 k; + + // Read in groups of 4. + if ((((uintptr_t)bytes) & 3) == 0) { + // We can do aligned 32-bit reads + for (size_t i = len >> 2; i--; ) { + k = *(const Uint32 *)bytes; + k = SDL_Swap32LE(k); + bytes += sizeof(Uint32); + hash ^= murmur_32_scramble(k); + hash = (hash << 13) | (hash >> 19); + hash = hash * 5 + 0xe6546b64; + } + } else { + for (size_t i = len >> 2; i--; ) { + SDL_memcpy(&k, bytes, sizeof(Uint32)); + k = SDL_Swap32LE(k); + bytes += sizeof(Uint32); + hash ^= murmur_32_scramble(k); + hash = (hash << 13) | (hash >> 19); + hash = hash * 5 + 0xe6546b64; + } + } + + // Read the rest. + size_t left = (len & 3); + if (left) { + k = 0; + for (size_t i = left; i--; ) { + k <<= 8; + k |= bytes[i]; + } + + // A swap is *not* necessary here because the preceding loop already + // places the low bytes in the low places according to whatever endianness + // we use. Swaps only apply when the memory is copied in a chunk. + hash ^= murmur_32_scramble(k); + } + + /* Finalize. */ + hash ^= len; + hash ^= hash >> 16; + hash *= 0x85ebca6b; + hash ^= hash >> 13; + hash *= 0xc2b2ae35; + hash ^= hash >> 16; + + return hash; +} diff --git a/thirdparty/sdl/stdlib/SDL_qsort.c b/thirdparty/sdl/stdlib/SDL_qsort.c new file mode 100644 index 00000000000..4ed2863e504 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_qsort.c @@ -0,0 +1,574 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// SDL3 always uses its own internal qsort implementation, below, so +// it can guarantee stable sorts across platforms and not have to +// tapdance to support the various qsort_r interfaces, or bridge from +// the C runtime's non-SDLCALL compare functions. + +#ifdef assert +#undef assert +#endif +#define assert SDL_assert +#ifdef malloc +#undef malloc +#endif +#define malloc SDL_malloc +#ifdef free +#undef free +#endif +#define free SDL_free +#ifdef memcpy +#undef memcpy +#endif +#define memcpy SDL_memcpy +#ifdef memmove +#undef memmove +#endif +#define memmove SDL_memmove + +/* +This code came from Gareth McCaughan, under the zlib license. +Specifically this: https://www.mccaughan.org.uk/software/qsort.c-1.16 + +Everything below this comment until the HAVE_QSORT #endif was from Gareth +(any minor changes will be noted inline). + +Thank you to Gareth for relicensing this code under the zlib license for our +benefit! + +Update for SDL3: we have modified this from a qsort function to qsort_r. + +--ryan. +*/ + +/* This is a drop-in replacement for the C library's |qsort()| routine. + * + * It is intended for use where you know or suspect that your + * platform's qsort is bad. If that isn't the case, then you + * should probably use the qsort your system gives you in preference + * to mine -- it will likely have been tested and tuned better. + * + * Features: + * - Median-of-three pivoting (and more) + * - Truncation and final polishing by a single insertion sort + * - Early truncation when no swaps needed in pivoting step + * - Explicit recursion, guaranteed not to overflow + * - A few little wrinkles stolen from the GNU |qsort()|. + * (For the avoidance of doubt, no code was stolen, only + * broad ideas.) + * - separate code for non-aligned / aligned / word-size objects + * + * Earlier releases of this code used an idiosyncratic licence + * I wrote myself, because I'm an idiot. The code is now released + * under the "zlib/libpng licence"; you will find the actual + * terms in the next comment. I request (but do not require) + * that if you make any changes beyond the name of the exported + * routine and reasonable tweaks to the TRUNC_* and + * PIVOT_THRESHOLD values, you modify the _ID string so as + * to make it clear that you have changed the code. + * + * If you find problems with this code, or find ways of + * making it significantly faster, please let me know! + * My e-mail address, valid as of early 2016 and for the + * foreseeable future, is + * gareth.mccaughan@pobox.com + * Thanks! + * + * Gareth McCaughan + */ + +/* Copyright (c) 1998-2021 Gareth McCaughan + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any + * damages arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; + * you must not claim that you wrote the original software. + * If you use this software in a product, an acknowledgment + * in the product documentation would be appreciated but + * is not required. + * + * 2. Altered source versions must be plainly marked as such, + * and must not be misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source + * distribution. + */ + +/* Revision history since release: + * 1998-03-19 v1.12 First release I have any records of. + * 2007-09-02 v1.13 Fix bug kindly reported by Dan Bodoh + * (premature termination of recursion). + * Add a few clarifying comments. + * Minor improvements to debug output. + * 2016-02-21 v1.14 Replace licence with 2-clause BSD, + * and clarify a couple of things in + * comments. No code changes. + * 2016-03-10 v1.15 Fix bug kindly reported by Ryan Gordon + * (pre-insertion-sort messed up). + * Disable DEBUG_QSORT by default. + * Tweak comments very slightly. + * 2021-02-20 v1.16 Fix bug kindly reported by Ray Gardner + * (error in recursion leading to possible + * stack overflow). + * When checking alignment, avoid casting + * pointer to possibly-smaller integer. + */ + +/* BEGIN SDL CHANGE ... commented this out with an #if 0 block. --ryan. */ +#if 0 +#include +#include +#include +#include + +#undef DEBUG_QSORT + +static char _ID[]=""; +#endif +/* END SDL CHANGE ... commented this out with an #if 0 block. --ryan. */ + +/* How many bytes are there per word? (Must be a power of 2, + * and must in fact equal sizeof(int).) + */ +#define WORD_BYTES sizeof(int) + +/* How big does our stack need to be? Answer: one entry per + * bit in a |size_t|. (Actually, a bit less because we don't + * recurse all the way down to size-1 subarrays.) + */ +#define STACK_SIZE (8*sizeof(size_t)) + +/* Different situations have slightly different requirements, + * and we make life epsilon easier by using different truncation + * points for the three different cases. + * So far, I have tuned TRUNC_words and guessed that the same + * value might work well for the other two cases. Of course + * what works well on my machine might work badly on yours. + */ +#define TRUNC_nonaligned 12 +#define TRUNC_aligned 12 +#define TRUNC_words 12*WORD_BYTES /* nb different meaning */ + +/* We use a simple pivoting algorithm for shortish sub-arrays + * and a more complicated one for larger ones. The threshold + * is PIVOT_THRESHOLD. + */ +#define PIVOT_THRESHOLD 40 + +typedef struct { char * first; char * last; } stack_entry; +#define pushLeft {stack[stacktop].first=ffirst;stack[stacktop++].last=last;} +#define pushRight {stack[stacktop].first=first;stack[stacktop++].last=llast;} +#define doLeft {first=ffirst;llast=last;continue;} +#define doRight {ffirst=first;last=llast;continue;} +#define pop {if (--stacktop<0) break;\ + first=ffirst=stack[stacktop].first;\ + last=llast=stack[stacktop].last;\ + continue;} + +/* Some comments on the implementation. + * 1. When we finish partitioning the array into "low" + * and "high", we forget entirely about short subarrays, + * because they'll be done later by insertion sort. + * Doing lots of little insertion sorts might be a win + * on large datasets for locality-of-reference reasons, + * but it makes the code much nastier and increases + * bookkeeping overhead. + * 2. We always save the longer and get to work on the + * shorter. This guarantees that whenever we push + * a k'th entry onto the stack we are about to get + * working on something of size <= N/2^k where N is + * the original array size; so the stack can't need + * more than log_2(max-array-size) entries. + * 3. We choose a pivot by looking at the first, last + * and middle elements. We arrange them into order + * because it's easy to do that in conjunction with + * choosing the pivot, and it makes things a little + * easier in the partitioning step. Anyway, the pivot + * is the middle of these three. It's still possible + * to construct datasets where the algorithm takes + * time of order n^2, but it simply never happens in + * practice. + * 3' Newsflash: On further investigation I find that + * it's easy to construct datasets where median-of-3 + * simply isn't good enough. So on large-ish subarrays + * we do a more sophisticated pivoting: we take three + * sets of 3 elements, find their medians, and then + * take the median of those. + * 4. We copy the pivot element to a separate place + * because that way we can always do our comparisons + * directly against a pointer to that separate place, + * and don't have to wonder "did we move the pivot + * element?". This makes the inner loop better. + * 5. It's possible to make the pivoting even more + * reliable by looking at more candidates when n + * is larger. (Taking this to its logical conclusion + * results in a variant of quicksort that doesn't + * have that n^2 worst case.) However, the overhead + * from the extra bookkeeping means that it's just + * not worth while. + * 6. This is pretty clean and portable code. Here are + * all the potential portability pitfalls and problems + * I know of: + * - In one place (the insertion sort) I construct + * a pointer that points just past the end of the + * supplied array, and assume that (a) it won't + * compare equal to any pointer within the array, + * and (b) it will compare equal to a pointer + * obtained by stepping off the end of the array. + * These might fail on some segmented architectures. + * - I assume that there are 8 bits in a |char| when + * computing the size of stack needed. This would + * fail on machines with 9-bit or 16-bit bytes. + * - I assume that if |((int)base&(sizeof(int)-1))==0| + * and |(size&(sizeof(int)-1))==0| then it's safe to + * get at array elements via |int*|s, and that if + * actually |size==sizeof(int)| as well then it's + * safe to treat the elements as |int|s. This might + * fail on systems that convert pointers to integers + * in non-standard ways. + * - I assume that |8*sizeof(size_t)<=INT_MAX|. This + * would be false on a machine with 8-bit |char|s, + * 16-bit |int|s and 4096-bit |size_t|s. :-) + */ + +/* The recursion logic is the same in each case. + * We keep chopping up until we reach subarrays of size + * strictly less than Trunc; we leave these unsorted. */ +#define Recurse(Trunc) \ + { size_t l=last-ffirst,r=llast-first; \ + if (l=Trunc) doRight \ + else pop \ + } \ + else if (l<=r) { pushRight; doLeft } \ + else if (r>=Trunc) { pushLeft; doRight }\ + else doLeft \ + } + +/* and so is the pivoting logic (note: last is inclusive): */ +#define Pivot(swapper,sz) \ + if ((size_t)(last-first)>PIVOT_THRESHOLD*sz) mid=pivot_big(first,mid,last,sz,compare,userdata);\ + else { \ + if (compare(userdata,first,mid)<0) { \ + if (compare(userdata,mid,last)>0) { \ + swapper(mid,last); \ + if (compare(userdata,first,mid)>0) swapper(first,mid);\ + } \ + } \ + else { \ + if (compare(userdata,mid,last)>0) swapper(first,last)\ + else { \ + swapper(first,mid); \ + if (compare(userdata,mid,last)>0) swapper(mid,last);\ + } \ + } \ + first+=sz; last-=sz; \ + } + +#ifdef DEBUG_QSORT +#include +#endif + +/* and so is the partitioning logic: */ +#define Partition(swapper,sz) { \ + do { \ + while (compare(userdata,first,pivot)<0) first+=sz; \ + while (compare(userdata,pivot,last)<0) last-=sz; \ + if (firstlimit ? limit : nmemb)-1)*sz;\ + while (last!=base) { \ + if (compare(userdata,first,last)>0) first=last; \ + last-=sz; } \ + if (first!=base) swapper(first,(char*)base); + +/* and so is the insertion sort, in the first two cases: */ +#define Insertion(swapper) \ + last=((char*)base)+nmemb*size; \ + for (first=((char*)base)+size;first!=last;first+=size) { \ + char *test; \ + /* Find the right place for |first|. \ + * My apologies for var reuse. */ \ + for (test=first-size;compare(userdata,test,first)>0;test-=size) ; \ + test+=size; \ + if (test!=first) { \ + /* Shift everything in [test,first) \ + * up by one, and place |first| \ + * where |test| is. */ \ + memcpy(pivot,first,size); \ + memmove(test+size,test,first-test); \ + memcpy(test,pivot,size); \ + } \ + } + +#define SWAP_nonaligned(a,b) { \ + register char *aa=(a),*bb=(b); \ + register size_t sz=size; \ + do { register char t=*aa; *aa++=*bb; *bb++=t; } while (--sz); } + +#define SWAP_aligned(a,b) { \ + register int *aa=(int*)(a),*bb=(int*)(b); \ + register size_t sz=size; \ + do { register int t=*aa;*aa++=*bb; *bb++=t; } while (sz-=WORD_BYTES); } + +#define SWAP_words(a,b) { \ + register int t=*((int*)a); *((int*)a)=*((int*)b); *((int*)b)=t; } + +/* ---------------------------------------------------------------------- */ + +static char * pivot_big(char *first, char *mid, char *last, size_t size, + int (SDLCALL *compare)(void *, const void *, const void *), void *userdata) { + size_t d=(((last-first)/size)>>3)*size; +#ifdef DEBUG_QSORT +fprintf(stderr, "pivot_big: first=%p last=%p size=%lu n=%lu\n", first, (unsigned long)last, size, (unsigned long)((last-first+1)/size)); +#endif + char *m1,*m2,*m3; + { char *a=first, *b=first+d, *c=first+2*d; +#ifdef DEBUG_QSORT +fprintf(stderr,"< %d %d %d @ %p %p %p\n",*(int*)a,*(int*)b,*(int*)c, a,b,c); +#endif + m1 = compare(userdata,a,b)<0 ? + (compare(userdata,b,c)<0 ? b : (compare(userdata,a,c)<0 ? c : a)) + : (compare(userdata,a,c)<0 ? a : (compare(userdata,b,c)<0 ? c : b)); + } + { char *a=mid-d, *b=mid, *c=mid+d; +#ifdef DEBUG_QSORT +fprintf(stderr,". %d %d %d @ %p %p %p\n",*(int*)a,*(int*)b,*(int*)c, a,b,c); +#endif + m2 = compare(userdata,a,b)<0 ? + (compare(userdata,b,c)<0 ? b : (compare(userdata,a,c)<0 ? c : a)) + : (compare(userdata,a,c)<0 ? a : (compare(userdata,b,c)<0 ? c : b)); + } + { char *a=last-2*d, *b=last-d, *c=last; +#ifdef DEBUG_QSORT +fprintf(stderr,"> %d %d %d @ %p %p %p\n",*(int*)a,*(int*)b,*(int*)c, a,b,c); +#endif + m3 = compare(userdata,a,b)<0 ? + (compare(userdata,b,c)<0 ? b : (compare(userdata,a,c)<0 ? c : a)) + : (compare(userdata,a,c)<0 ? a : (compare(userdata,b,c)<0 ? c : b)); + } +#ifdef DEBUG_QSORT +fprintf(stderr,"-> %d %d %d @ %p %p %p\n",*(int*)m1,*(int*)m2,*(int*)m3, m1,m2,m3); +#endif + return compare(userdata,m1,m2)<0 ? + (compare(userdata,m2,m3)<0 ? m2 : (compare(userdata,m1,m3)<0 ? m3 : m1)) + : (compare(userdata,m1,m3)<0 ? m1 : (compare(userdata,m2,m3)<0 ? m3 : m2)); +} + +/* ---------------------------------------------------------------------- */ + +static void qsort_r_nonaligned(void *base, size_t nmemb, size_t size, + int (SDLCALL *compare)(void *, const void *, const void *), void *userdata) { + + stack_entry stack[STACK_SIZE]; + int stacktop=0; + char *first,*last; + char *pivot=malloc(size); + size_t trunc=TRUNC_nonaligned*size; + assert(pivot != NULL); + + first=(char*)base; last=first+(nmemb-1)*size; + + if ((size_t)(last-first)>=trunc) { + char *ffirst=first, *llast=last; + while (1) { + /* Select pivot */ + { char * mid=first+size*((last-first)/size >> 1); + Pivot(SWAP_nonaligned,size); + memcpy(pivot,mid,size); + } + /* Partition. */ + Partition(SWAP_nonaligned,size); + /* Prepare to recurse/iterate. */ + Recurse(trunc) + } + } + PreInsertion(SWAP_nonaligned,TRUNC_nonaligned,size); + Insertion(SWAP_nonaligned); + free(pivot); +} + +static void qsort_r_aligned(void *base, size_t nmemb, size_t size, + int (SDLCALL *compare)(void *,const void *, const void *), void *userdata) { + + stack_entry stack[STACK_SIZE]; + int stacktop=0; + char *first,*last; + char *pivot=malloc(size); + size_t trunc=TRUNC_aligned*size; + assert(pivot != NULL); + + first=(char*)base; last=first+(nmemb-1)*size; + + if ((size_t)(last-first)>=trunc) { + char *ffirst=first,*llast=last; + while (1) { + /* Select pivot */ + { char * mid=first+size*((last-first)/size >> 1); + Pivot(SWAP_aligned,size); + memcpy(pivot,mid,size); + } + /* Partition. */ + Partition(SWAP_aligned,size); + /* Prepare to recurse/iterate. */ + Recurse(trunc) + } + } + PreInsertion(SWAP_aligned,TRUNC_aligned,size); + Insertion(SWAP_aligned); + free(pivot); +} + +static void qsort_r_words(void *base, size_t nmemb, + int (SDLCALL *compare)(void *,const void *, const void *), void *userdata) { + + stack_entry stack[STACK_SIZE]; + int stacktop=0; + char *first,*last; + char *pivot=malloc(WORD_BYTES); + assert(pivot != NULL); + + first=(char*)base; last=first+(nmemb-1)*WORD_BYTES; + + if (last-first>=TRUNC_words) { + char *ffirst=first, *llast=last; + while (1) { +#ifdef DEBUG_QSORT +fprintf(stderr,"Doing %d:%d: ", + (first-(char*)base)/WORD_BYTES, + (last-(char*)base)/WORD_BYTES); +#endif + /* Select pivot */ + { char * mid=first+WORD_BYTES*((last-first) / (2*WORD_BYTES)); + Pivot(SWAP_words,WORD_BYTES); + *(int*)pivot=*(int*)mid; +#ifdef DEBUG_QSORT +fprintf(stderr,"pivot = %p = #%lu = %d\n", mid, (unsigned long)(((int*)mid)-((int*)base)), *(int*)mid); +#endif + } + /* Partition. */ + Partition(SWAP_words,WORD_BYTES); +#ifdef DEBUG_QSORT +fprintf(stderr, "after partitioning first=#%lu last=#%lu\n", (first-(char*)base)/4lu, (last-(char*)base)/4lu); +#endif + /* Prepare to recurse/iterate. */ + Recurse(TRUNC_words) + } + } + PreInsertion(SWAP_words,TRUNC_words/WORD_BYTES,WORD_BYTES); + /* Now do insertion sort. */ + last=((char*)base)+nmemb*WORD_BYTES; + for (first=((char*)base)+WORD_BYTES;first!=last;first+=WORD_BYTES) { + /* Find the right place for |first|. My apologies for var reuse */ + int *pl=(int*)(first-WORD_BYTES),*pr=(int*)first; + *(int*)pivot=*(int*)first; + for (;compare(userdata,pl,pivot)>0;pr=pl,--pl) { + *pr=*pl; } + if (pr!=(int*)first) *pr=*(int*)pivot; + } + free(pivot); +} + +/* ---------------------------------------------------------------------- */ + +void SDL_qsort_r(void *base, size_t nmemb, size_t size, + SDL_CompareCallback_r compare, void *userdata) { + + if (nmemb<=1) return; + if (((uintptr_t)base|size)&(WORD_BYTES-1)) + qsort_r_nonaligned(base,nmemb,size,compare,userdata); + else if (size!=WORD_BYTES) + qsort_r_aligned(base,nmemb,size,compare,userdata); + else + qsort_r_words(base,nmemb,compare,userdata); +} + +static int SDLCALL qsort_non_r_bridge(void *userdata, const void *a, const void *b) +{ + int (SDLCALL *compare)(const void *, const void *) = (int (SDLCALL *)(const void *, const void *)) userdata; + return compare(a, b); +} + +void SDL_qsort(void *base, size_t nmemb, size_t size, SDL_CompareCallback compare) +{ + SDL_qsort_r(base, nmemb, size, qsort_non_r_bridge, compare); +} + +// Don't use the C runtime for such a simple function, since we want to allow SDLCALL callbacks and userdata. +// SDL's replacement: Taken from the Public Domain C Library (PDCLib): +// Permission is granted to use, modify, and / or redistribute at will. +void *SDL_bsearch_r(const void *key, const void *base, size_t nmemb, size_t size, SDL_CompareCallback_r compare, void *userdata) +{ + const void *pivot; + size_t corr; + int rc; + + while (nmemb) { + /* algorithm needs -1 correction if remaining elements are an even number. */ + corr = nmemb % 2; + nmemb /= 2; + pivot = (const char *)base + (nmemb * size); + rc = compare(userdata, key, pivot); + + if (rc > 0) { + base = (const char *)pivot + size; + /* applying correction */ + nmemb -= (1 - corr); + } else if (rc == 0) { + return (void *)pivot; + } + } + + return NULL; +} + +void *SDL_bsearch(const void *key, const void *base, size_t nmemb, size_t size, SDL_CompareCallback compare) +{ + // qsort_non_r_bridge just happens to match calling conventions, so reuse it. + return SDL_bsearch_r(key, base, nmemb, size, qsort_non_r_bridge, compare); +} + diff --git a/thirdparty/sdl/stdlib/SDL_random.c b/thirdparty/sdl/stdlib/SDL_random.c new file mode 100644 index 00000000000..a774d30c967 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_random.c @@ -0,0 +1,115 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This file contains portable random functions for SDL + +static Uint64 SDL_rand_state; +static bool SDL_rand_initialized = false; + +void SDL_srand(Uint64 seed) +{ + if (!seed) { + seed = SDL_GetPerformanceCounter(); + } + SDL_rand_state = seed; + SDL_rand_initialized = true; +} + +Sint32 SDL_rand(Sint32 n) +{ + if (!SDL_rand_initialized) { + SDL_srand(0); + } + + return SDL_rand_r(&SDL_rand_state, n); +} + +float SDL_randf(void) +{ + if (!SDL_rand_initialized) { + SDL_srand(0); + } + + return SDL_randf_r(&SDL_rand_state); +} + +Uint32 SDL_rand_bits(void) +{ + if (!SDL_rand_initialized) { + SDL_srand(0); + } + + return SDL_rand_bits_r(&SDL_rand_state); +} + +Uint32 SDL_rand_bits_r(Uint64 *state) +{ + if (!state) { + return 0; + } + + // The C and A parameters of this LCG have been chosen based on hundreds + // of core-hours of testing with PractRand and TestU01's Crush. + // Using a 32-bit A improves performance on 32-bit architectures. + // C can be any odd number, but < 256 generates smaller code on ARM32 + // These values perform as well as a full 64-bit implementation against + // Crush and PractRand. Plus, their worst-case performance is better + // than common 64-bit constants when tested against PractRand using seeds + // with only a single bit set. + + // We tested all 32-bit and 33-bit A with all C < 256 from a v2 of: + // Steele GL, Vigna S. Computationally easy, spectrally good multipliers + // for congruential pseudorandom number generators. + // Softw Pract Exper. 2022;52(2):443-458. doi: 10.1002/spe.3030 + // https://arxiv.org/abs/2001.05304v2 + + *state = *state * 0xff1cd035ul + 0x05; + + // Only return top 32 bits because they have a longer period + return (Uint32)(*state >> 32); +} + +Sint32 SDL_rand_r(Uint64 *state, Sint32 n) +{ + // Algorithm: get 32 bits from SDL_rand_bits() and treat it as a 0.32 bit + // fixed point number. Multiply by the 31.0 bit n to get a 31.32 bit + // result. Shift right by 32 to get the 31 bit integer that we want. + + if (n < 0) { + // The algorithm looks like it works for numbers < 0 but it has an + // infinitesimal chance of returning a value out of range. + // Returning -SDL_rand(abs(n)) blows up at INT_MIN instead. + // It's easier to just say no. + return 0; + } + + // On 32-bit arch, the compiler will optimize to a single 32-bit multiply + Uint64 val = (Uint64)SDL_rand_bits_r(state) * n; + return (Sint32)(val >> 32); +} + +float SDL_randf_r(Uint64 *state) +{ + // Note: its using 24 bits because float has 23 bits significand + 1 implicit bit + return (SDL_rand_bits_r(state) >> (32 - 24)) * 0x1p-24f; +} + diff --git a/thirdparty/sdl/stdlib/SDL_stdlib.c b/thirdparty/sdl/stdlib/SDL_stdlib.c new file mode 100644 index 00000000000..093b2bec479 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_stdlib.c @@ -0,0 +1,573 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This file contains portable stdlib functions for SDL + +#include "../libm/math_libm.h" + +double SDL_atan(double x) +{ +#ifdef HAVE_ATAN + return atan(x); +#else + return SDL_uclibc_atan(x); +#endif +} + +float SDL_atanf(float x) +{ +#ifdef HAVE_ATANF + return atanf(x); +#else + return (float)SDL_atan((double)x); +#endif +} + +double SDL_atan2(double y, double x) +{ +#ifdef HAVE_ATAN2 + return atan2(y, x); +#else + return SDL_uclibc_atan2(y, x); +#endif +} + +float SDL_atan2f(float y, float x) +{ +#ifdef HAVE_ATAN2F + return atan2f(y, x); +#else + return (float)SDL_atan2((double)y, (double)x); +#endif +} + +double SDL_acos(double val) +{ +#ifdef HAVE_ACOS + return acos(val); +#else + double result; + if (val == -1.0) { + result = SDL_PI_D; + } else { + result = SDL_atan(SDL_sqrt(1.0 - val * val) / val); + if (result < 0.0) { + result += SDL_PI_D; + } + } + return result; +#endif +} + +float SDL_acosf(float val) +{ +#ifdef HAVE_ACOSF + return acosf(val); +#else + return (float)SDL_acos((double)val); +#endif +} + +double SDL_asin(double val) +{ +#ifdef HAVE_ASIN + return asin(val); +#else + double result; + if (val == -1.0) { + result = -(SDL_PI_D / 2.0); + } else { + result = (SDL_PI_D / 2.0) - SDL_acos(val); + } + return result; +#endif +} + +float SDL_asinf(float val) +{ +#ifdef HAVE_ASINF + return asinf(val); +#else + return (float)SDL_asin((double)val); +#endif +} + +double SDL_ceil(double x) +{ +#ifdef HAVE_CEIL + return ceil(x); +#else + double integer = SDL_floor(x); + double fraction = x - integer; + if (fraction > 0.0) { + integer += 1.0; + } + return integer; +#endif // HAVE_CEIL +} + +float SDL_ceilf(float x) +{ +#ifdef HAVE_CEILF + return ceilf(x); +#else + return (float)SDL_ceil((double)x); +#endif +} + +double SDL_copysign(double x, double y) +{ +#ifdef HAVE_COPYSIGN + return copysign(x, y); +#elif defined(HAVE__COPYSIGN) + return _copysign(x, y); +#elif defined(__WATCOMC__) && defined(__386__) + // this is nasty as hell, but it works.. + unsigned int *xi = (unsigned int *)&x, + *yi = (unsigned int *)&y; + xi[1] = (yi[1] & 0x80000000) | (xi[1] & 0x7fffffff); + return x; +#else + return SDL_uclibc_copysign(x, y); +#endif // HAVE_COPYSIGN +} + +float SDL_copysignf(float x, float y) +{ +#ifdef HAVE_COPYSIGNF + return copysignf(x, y); +#else + return (float)SDL_copysign((double)x, (double)y); +#endif +} + +double SDL_cos(double x) +{ +#ifdef HAVE_COS + return cos(x); +#else + return SDL_uclibc_cos(x); +#endif +} + +float SDL_cosf(float x) +{ +#ifdef HAVE_COSF + return cosf(x); +#else + return (float)SDL_cos((double)x); +#endif +} + +double SDL_exp(double x) +{ +#ifdef HAVE_EXP + return exp(x); +#else + return SDL_uclibc_exp(x); +#endif +} + +float SDL_expf(float x) +{ +#ifdef HAVE_EXPF + return expf(x); +#else + return (float)SDL_exp((double)x); +#endif +} + +double SDL_fabs(double x) +{ +#ifdef HAVE_FABS + return fabs(x); +#else + return SDL_uclibc_fabs(x); +#endif +} + +float SDL_fabsf(float x) +{ +#ifdef HAVE_FABSF + return fabsf(x); +#else + return (float)SDL_fabs((double)x); +#endif +} + +double SDL_floor(double x) +{ +#ifdef HAVE_FLOOR + return floor(x); +#else + return SDL_uclibc_floor(x); +#endif +} + +float SDL_floorf(float x) +{ +#ifdef HAVE_FLOORF + return floorf(x); +#else + return (float)SDL_floor((double)x); +#endif +} + +double SDL_trunc(double x) +{ +#ifdef HAVE_TRUNC + return trunc(x); +#else + if (x >= 0.0f) { + return SDL_floor(x); + } else { + return SDL_ceil(x); + } +#endif +} + +float SDL_truncf(float x) +{ +#ifdef HAVE_TRUNCF + return truncf(x); +#else + return (float)SDL_trunc((double)x); +#endif +} + +double SDL_fmod(double x, double y) +{ +#ifdef HAVE_FMOD + return fmod(x, y); +#else + return SDL_uclibc_fmod(x, y); +#endif +} + +float SDL_fmodf(float x, float y) +{ +#ifdef HAVE_FMODF + return fmodf(x, y); +#else + return (float)SDL_fmod((double)x, (double)y); +#endif +} + +int SDL_isinf(double x) +{ +#ifdef HAVE_ISINF + return isinf(x); +#else + return SDL_uclibc_isinf(x); +#endif +} + +int SDL_isinff(float x) +{ +#ifdef HAVE_ISINF_FLOAT_MACRO + return isinf(x); +#elif defined(HAVE_ISINFF) + return isinff(x); +#else + return SDL_uclibc_isinff(x); +#endif +} + +int SDL_isnan(double x) +{ +#ifdef HAVE_ISNAN + return isnan(x); +#else + return SDL_uclibc_isnan(x); +#endif +} + +int SDL_isnanf(float x) +{ +#ifdef HAVE_ISNAN_FLOAT_MACRO + return isnan(x); +#elif defined(HAVE_ISNANF) + return isnanf(x); +#else + return SDL_uclibc_isnanf(x); +#endif +} + +double SDL_log(double x) +{ +#ifdef HAVE_LOG + return log(x); +#else + return SDL_uclibc_log(x); +#endif +} + +float SDL_logf(float x) +{ +#ifdef HAVE_LOGF + return logf(x); +#else + return (float)SDL_log((double)x); +#endif +} + +double SDL_log10(double x) +{ +#ifdef HAVE_LOG10 + return log10(x); +#else + return SDL_uclibc_log10(x); +#endif +} + +float SDL_log10f(float x) +{ +#ifdef HAVE_LOG10F + return log10f(x); +#else + return (float)SDL_log10((double)x); +#endif +} + +double SDL_modf(double x, double *y) +{ +#ifdef HAVE_MODF + return modf(x, y); +#else + return SDL_uclibc_modf(x, y); +#endif +} + +float SDL_modff(float x, float *y) +{ +#ifdef HAVE_MODFF + return modff(x, y); +#else + double double_result, double_y; + double_result = SDL_modf((double)x, &double_y); + *y = (float)double_y; + return (float)double_result; +#endif +} + +double SDL_pow(double x, double y) +{ +#ifdef HAVE_POW + return pow(x, y); +#else + return SDL_uclibc_pow(x, y); +#endif +} + +float SDL_powf(float x, float y) +{ +#ifdef HAVE_POWF + return powf(x, y); +#else + return (float)SDL_pow((double)x, (double)y); +#endif +} + +double SDL_round(double arg) +{ +#if defined HAVE_ROUND + return round(arg); +#else + if (arg >= 0.0) { + return SDL_floor(arg + 0.5); + } else { + return SDL_ceil(arg - 0.5); + } +#endif +} + +float SDL_roundf(float arg) +{ +#if defined HAVE_ROUNDF + return roundf(arg); +#else + return (float)SDL_round((double)arg); +#endif +} + +long SDL_lround(double arg) +{ +#if defined HAVE_LROUND + return lround(arg); +#else + return (long)SDL_round(arg); +#endif +} + +long SDL_lroundf(float arg) +{ +#if defined HAVE_LROUNDF + return lroundf(arg); +#else + return (long)SDL_round((double)arg); +#endif +} + +double SDL_scalbn(double x, int n) +{ +#ifdef HAVE_SCALBN + return scalbn(x, n); +#elif defined(HAVE__SCALB) + return _scalb(x, n); +#elif defined(HAVE_LIBC) && defined(HAVE_FLOAT_H) && (FLT_RADIX == 2) + /* from scalbn(3): If FLT_RADIX equals 2 (which is + * usual), then scalbn() is equivalent to ldexp(3). */ + return ldexp(x, n); +#else + return SDL_uclibc_scalbn(x, n); +#endif +} + +float SDL_scalbnf(float x, int n) +{ +#ifdef HAVE_SCALBNF + return scalbnf(x, n); +#else + return (float)SDL_scalbn((double)x, n); +#endif +} + +double SDL_sin(double x) +{ +#ifdef HAVE_SIN + return sin(x); +#else + return SDL_uclibc_sin(x); +#endif +} + +float SDL_sinf(float x) +{ +#ifdef HAVE_SINF + return sinf(x); +#else + return (float)SDL_sin((double)x); +#endif +} + +double SDL_sqrt(double x) +{ +#ifdef HAVE_SQRT + return sqrt(x); +#else + return SDL_uclibc_sqrt(x); +#endif +} + +float SDL_sqrtf(float x) +{ +#ifdef HAVE_SQRTF + return sqrtf(x); +#else + return (float)SDL_sqrt((double)x); +#endif +} + +double SDL_tan(double x) +{ +#ifdef HAVE_TAN + return tan(x); +#else + return SDL_uclibc_tan(x); +#endif +} + +float SDL_tanf(float x) +{ +#ifdef HAVE_TANF + return tanf(x); +#else + return (float)SDL_tan((double)x); +#endif +} + +int SDL_abs(int x) +{ +#ifdef HAVE_ABS + return abs(x); +#else + return (x < 0) ? -x : x; +#endif +} + +int SDL_isalpha(int x) { return (SDL_isupper(x)) || (SDL_islower(x)); } +int SDL_isalnum(int x) { return (SDL_isalpha(x)) || (SDL_isdigit(x)); } +int SDL_isdigit(int x) { return ((x) >= '0') && ((x) <= '9'); } +int SDL_isxdigit(int x) { return (((x) >= 'A') && ((x) <= 'F')) || (((x) >= 'a') && ((x) <= 'f')) || (SDL_isdigit(x)); } +int SDL_ispunct(int x) { return (SDL_isgraph(x)) && (!SDL_isalnum(x)); } +int SDL_isspace(int x) { return ((x) == ' ') || ((x) == '\t') || ((x) == '\r') || ((x) == '\n') || ((x) == '\f') || ((x) == '\v'); } +int SDL_isupper(int x) { return ((x) >= 'A') && ((x) <= 'Z'); } +int SDL_islower(int x) { return ((x) >= 'a') && ((x) <= 'z'); } +int SDL_isprint(int x) { return ((x) >= ' ') && ((x) < '\x7f'); } +int SDL_isgraph(int x) { return (SDL_isprint(x)) && ((x) != ' '); } +int SDL_iscntrl(int x) { return (((x) >= '\0') && ((x) <= '\x1f')) || ((x) == '\x7f'); } +int SDL_toupper(int x) { return ((x) >= 'a') && ((x) <= 'z') ? ('A' + ((x) - 'a')) : (x); } +int SDL_tolower(int x) { return ((x) >= 'A') && ((x) <= 'Z') ? ('a' + ((x) - 'A')) : (x); } +int SDL_isblank(int x) { return ((x) == ' ') || ((x) == '\t'); } + +void *SDL_aligned_alloc(size_t alignment, size_t size) +{ + size_t padding; + Uint8 *result = NULL; + size_t requested_size = size; + + if (alignment < sizeof(void*)) { + alignment = sizeof(void*); + } + padding = (alignment - (size % alignment)); + + if (SDL_size_add_check_overflow(size, alignment, &size) && + SDL_size_add_check_overflow(size, sizeof(void *), &size) && + SDL_size_add_check_overflow(size, padding, &size)) { + void *original = SDL_malloc(size); + if (original) { + // Make sure we have enough space to store the original pointer + result = (Uint8 *)original + sizeof(original); + + // Align the pointer we're going to return + result += alignment - (((size_t)result) % alignment); + + // Store the original pointer right before the returned value + SDL_memcpy(result - sizeof(original), &original, sizeof(original)); + + // Initialize the padding to zero + if (padding > 0) { + SDL_memset(result + requested_size, 0, padding); + } + } + } + return result; +} + +void SDL_aligned_free(void *mem) +{ + if (mem) { + void *original; + SDL_memcpy(&original, ((Uint8 *)mem - sizeof(original)), sizeof(original)); + SDL_free(original); + } +} diff --git a/thirdparty/sdl/stdlib/SDL_string.c b/thirdparty/sdl/stdlib/SDL_string.c new file mode 100644 index 00000000000..79679a1f444 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_string.c @@ -0,0 +1,2511 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// This file contains portable string manipulation functions for SDL + +#include "SDL_vacopy.h" + +#ifdef SDL_PLATFORM_VITA +#include +#endif + +#include "SDL_sysstdlib.h" + +#include "SDL_casefolding.h" + +#if defined(__SIZEOF_WCHAR_T__) +#define SDL_SIZEOF_WCHAR_T __SIZEOF_WCHAR_T__ +#elif defined(SDL_PLATFORM_WINDOWS) +#define SDL_SIZEOF_WCHAR_T 2 +#else // assume everything else is UTF-32 (add more tests if compiler-assert fails below!) +#define SDL_SIZEOF_WCHAR_T 4 +#endif +SDL_COMPILE_TIME_ASSERT(sizeof_wchar_t, sizeof(wchar_t) == SDL_SIZEOF_WCHAR_T); + + +char *SDL_UCS4ToUTF8(Uint32 codepoint, char *dst) +{ + if (!dst) { + return NULL; // I guess...? + } else if (codepoint > 0x10FFFF) { // Outside the range of Unicode codepoints (also, larger than can be encoded in 4 bytes of UTF-8!). + codepoint = SDL_INVALID_UNICODE_CODEPOINT; + } else if ((codepoint >= 0xD800) && (codepoint <= 0xDFFF)) { // UTF-16 surrogate values are illegal in UTF-8. + codepoint = SDL_INVALID_UNICODE_CODEPOINT; + } + + Uint8 *p = (Uint8 *)dst; + if (codepoint <= 0x7F) { + *p = (Uint8)codepoint; + ++dst; + } else if (codepoint <= 0x7FF) { + p[0] = 0xC0 | (Uint8)((codepoint >> 6) & 0x1F); + p[1] = 0x80 | (Uint8)(codepoint & 0x3F); + dst += 2; + } else if (codepoint <= 0xFFFF) { + p[0] = 0xE0 | (Uint8)((codepoint >> 12) & 0x0F); + p[1] = 0x80 | (Uint8)((codepoint >> 6) & 0x3F); + p[2] = 0x80 | (Uint8)(codepoint & 0x3F); + dst += 3; + } else { + SDL_assert(codepoint <= 0x10FFFF); + p[0] = 0xF0 | (Uint8)((codepoint >> 18) & 0x07); + p[1] = 0x80 | (Uint8)((codepoint >> 12) & 0x3F); + p[2] = 0x80 | (Uint8)((codepoint >> 6) & 0x3F); + p[3] = 0x80 | (Uint8)(codepoint & 0x3F); + dst += 4; + } + + return dst; +} + + +// this expects `from` and `to` to be UTF-32 encoding! +int SDL_CaseFoldUnicode(Uint32 from, Uint32 *to) +{ + // !!! FIXME: since the hashtable is static, maybe we should binary + // !!! FIXME: search it instead of walking the whole bucket. + + if (from < 128) { // low-ASCII, easy! + if ((from >= 'A') && (from <= 'Z')) { + *to = 'a' + (from - 'A'); + return 1; + } + } else if (from <= 0xFFFF) { // the Basic Multilingual Plane. + const Uint8 hash = ((from ^ (from >> 8)) & 0xFF); + const Uint16 from16 = (Uint16) from; + + // see if it maps to a single char (most common)... + { + const CaseFoldHashBucket1_16 *bucket = &case_fold_hash1_16[hash]; + const int count = (int) bucket->count; + for (int i = 0; i < count; i++) { + const CaseFoldMapping1_16 *mapping = &bucket->list[i]; + if (mapping->from == from16) { + *to = mapping->to0; + return 1; + } + } + } + + // see if it folds down to two chars... + { + const CaseFoldHashBucket2_16 *bucket = &case_fold_hash2_16[hash & 15]; + const int count = (int) bucket->count; + for (int i = 0; i < count; i++) { + const CaseFoldMapping2_16 *mapping = &bucket->list[i]; + if (mapping->from == from16) { + to[0] = mapping->to0; + to[1] = mapping->to1; + return 2; + } + } + } + + // okay, maybe it's _three_ characters! + { + const CaseFoldHashBucket3_16 *bucket = &case_fold_hash3_16[hash & 3]; + const int count = (int) bucket->count; + for (int i = 0; i < count; i++) { + const CaseFoldMapping3_16 *mapping = &bucket->list[i]; + if (mapping->from == from16) { + to[0] = mapping->to0; + to[1] = mapping->to1; + to[2] = mapping->to2; + return 3; + } + } + } + + } else { // codepoint that doesn't fit in 16 bits. + const Uint8 hash = ((from ^ (from >> 8)) & 0xFF); + const CaseFoldHashBucket1_32 *bucket = &case_fold_hash1_32[hash & 15]; + const int count = (int) bucket->count; + for (int i = 0; i < count; i++) { + const CaseFoldMapping1_32 *mapping = &bucket->list[i]; + if (mapping->from == from) { + *to = mapping->to0; + return 1; + } + } + } + + // Not found...there's no folding needed for this codepoint. + *to = from; + return 1; +} + +#define UNICODE_STRCASECMP(bits, slen1, slen2, update_slen1, update_slen2) \ + Uint32 folded1[3], folded2[3]; \ + int head1 = 0, tail1 = 0, head2 = 0, tail2 = 0; \ + while (true) { \ + Uint32 cp1, cp2; \ + if (head1 != tail1) { \ + cp1 = folded1[tail1++]; \ + } else { \ + const Uint##bits *str1start = (const Uint##bits *) str1; \ + head1 = SDL_CaseFoldUnicode(StepUTF##bits(&str1, slen1), folded1); \ + update_slen1; \ + cp1 = folded1[0]; \ + tail1 = 1; \ + } \ + if (head2 != tail2) { \ + cp2 = folded2[tail2++]; \ + } else { \ + const Uint##bits *str2start = (const Uint##bits *) str2; \ + head2 = SDL_CaseFoldUnicode(StepUTF##bits(&str2, slen2), folded2); \ + update_slen2; \ + cp2 = folded2[0]; \ + tail2 = 1; \ + } \ + if (cp1 < cp2) { \ + return -1; \ + } else if (cp1 > cp2) { \ + return 1; \ + } else if (cp1 == 0) { \ + break; /* complete match. */ \ + } \ + } \ + return 0 + + +static Uint32 StepUTF8(const char **_str, const size_t slen) +{ + /* + * From rfc3629, the UTF-8 spec: + * https://www.ietf.org/rfc/rfc3629.txt + * + * Char. number range | UTF-8 octet sequence + * (hexadecimal) | (binary) + * --------------------+--------------------------------------------- + * 0000 0000-0000 007F | 0xxxxxxx + * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx + * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx + * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + */ + + const Uint8 *str = (const Uint8 *) *_str; + const Uint32 octet = (Uint32) (slen ? *str : 0); + + if (octet == 0) { // null terminator, end of string. + return 0; // don't advance `*_str`. + } else if ((octet & 0x80) == 0) { // 0xxxxxxx: one byte codepoint. + (*_str)++; + return octet; + } else if (((octet & 0xE0) == 0xC0) && (slen >= 2)) { // 110xxxxx 10xxxxxx: two byte codepoint. + const Uint8 str1 = str[1]; + if ((str1 & 0xC0) == 0x80) { // If trailing bytes aren't 10xxxxxx, sequence is bogus. + const Uint32 result = ((octet & 0x1F) << 6) | (str1 & 0x3F); + if (result >= 0x0080) { // rfc3629 says you can't use overlong sequences for smaller values. + *_str += 2; + return result; + } + } + } else if (((octet & 0xF0) == 0xE0) && (slen >= 3)) { // 1110xxxx 10xxxxxx 10xxxxxx: three byte codepoint. + const Uint8 str1 = str[1]; + const Uint8 str2 = str[2]; + if (((str1 & 0xC0) == 0x80) && ((str2 & 0xC0) == 0x80)) { // If trailing bytes aren't 10xxxxxx, sequence is bogus. + const Uint32 octet2 = ((Uint32) (str1 & 0x3F)) << 6; + const Uint32 octet3 = ((Uint32) (str2 & 0x3F)); + const Uint32 result = ((octet & 0x0F) << 12) | octet2 | octet3; + if (result >= 0x800) { // rfc3629 says you can't use overlong sequences for smaller values. + if ((result < 0xD800) || (result > 0xDFFF)) { // UTF-16 surrogate values are illegal in UTF-8. + *_str += 3; + return result; + } + } + } + } else if (((octet & 0xF8) == 0xF0) && (slen >= 4)) { // 11110xxxx 10xxxxxx 10xxxxxx 10xxxxxx: four byte codepoint. + const Uint8 str1 = str[1]; + const Uint8 str2 = str[2]; + const Uint8 str3 = str[3]; + if (((str1 & 0xC0) == 0x80) && ((str2 & 0xC0) == 0x80) && ((str3 & 0xC0) == 0x80)) { // If trailing bytes aren't 10xxxxxx, sequence is bogus. + const Uint32 octet2 = ((Uint32) (str1 & 0x1F)) << 12; + const Uint32 octet3 = ((Uint32) (str2 & 0x3F)) << 6; + const Uint32 octet4 = ((Uint32) (str3 & 0x3F)); + const Uint32 result = ((octet & 0x07) << 18) | octet2 | octet3 | octet4; + if (result >= 0x10000) { // rfc3629 says you can't use overlong sequences for smaller values. + *_str += 4; + return result; + } + } + } + + // bogus byte, skip ahead, return a REPLACEMENT CHARACTER. + (*_str)++; + return SDL_INVALID_UNICODE_CODEPOINT; +} + +Uint32 SDL_StepUTF8(const char **pstr, size_t *pslen) +{ + if (!pslen) { + return StepUTF8(pstr, 4); // 4 == max codepoint size. + } + const char *origstr = *pstr; + const Uint32 result = StepUTF8(pstr, *pslen); + *pslen -= (size_t) (*pstr - origstr); + return result; +} + +Uint32 SDL_StepBackUTF8(const char *start, const char **pstr) +{ + if (!pstr || *pstr <= start) { + return 0; + } + + // Step back over the previous UTF-8 character + const char *str = *pstr; + do { + if (str == start) { + break; + } + --str; + } while ((*str & 0xC0) == 0x80); + + size_t length = (*pstr - str); + *pstr = str; + return StepUTF8(&str, length); +} + +#if (SDL_SIZEOF_WCHAR_T == 2) +static Uint32 StepUTF16(const Uint16 **_str, const size_t slen) +{ + const Uint16 *str = *_str; + Uint32 cp = (Uint32) *(str++); + if (cp == 0) { + return 0; // don't advance string pointer. + } else if ((cp >= 0xDC00) && (cp <= 0xDFFF)) { + cp = SDL_INVALID_UNICODE_CODEPOINT; // Orphaned second half of surrogate pair + } else if ((cp >= 0xD800) && (cp <= 0xDBFF)) { // start of surrogate pair! + const Uint32 pair = (Uint32) *str; + if ((pair == 0) || ((pair < 0xDC00) || (pair > 0xDFFF))) { + cp = SDL_INVALID_UNICODE_CODEPOINT; + } else { + str++; // eat the other surrogate. + cp = 0x10000 + (((cp - 0xD800) << 10) | (pair - 0xDC00)); + } + } + + *_str = str; + return (cp > 0x10FFFF) ? SDL_INVALID_UNICODE_CODEPOINT : cp; +} +#elif (SDL_SIZEOF_WCHAR_T == 4) +static Uint32 StepUTF32(const Uint32 **_str, const size_t slen) +{ + if (!slen) { + return 0; + } + + const Uint32 *str = *_str; + const Uint32 cp = *str; + if (cp == 0) { + return 0; // don't advance string pointer. + } + + (*_str)++; + return (cp > 0x10FFFF) ? SDL_INVALID_UNICODE_CODEPOINT : cp; +} +#endif + +#define UTF8_IsLeadByte(c) ((c) >= 0xC0 && (c) <= 0xF4) +#define UTF8_IsTrailingByte(c) ((c) >= 0x80 && (c) <= 0xBF) + +static size_t UTF8_GetTrailingBytes(unsigned char c) +{ + if (c >= 0xC0 && c <= 0xDF) { + return 1; + } else if (c >= 0xE0 && c <= 0xEF) { + return 2; + } else if (c >= 0xF0 && c <= 0xF4) { + return 3; + } + + return 0; +} + +#if !defined(HAVE_VSSCANF) || !defined(HAVE_STRTOL) || !defined(HAVE_STRTOUL) || !defined(HAVE_STRTOLL) || !defined(HAVE_STRTOULL) || !defined(HAVE_STRTOD) +/** + * Parses an unsigned long long and returns the unsigned value and sign bit. + * + * Positive values are clamped to ULLONG_MAX. + * The result `value == 0 && negative` indicates negative overflow + * and might need to be handled differently depending on whether a + * signed or unsigned integer is being parsed. + */ +static size_t SDL_ScanUnsignedLongLongInternal(const char *text, int count, int radix, unsigned long long *valuep, bool *negativep) +{ + const unsigned long long ullong_max = ~0ULL; + + const char *text_start = text; + const char *number_start = text_start; + unsigned long long value = 0; + bool negative = false; + bool overflow = false; + + if (radix == 0 || (radix >= 2 && radix <= 36)) { + while (SDL_isspace(*text)) { + ++text; + } + if (*text == '-' || *text == '+') { + negative = *text == '-'; + ++text; + } + if ((radix == 0 || radix == 16) && *text == '0' && (text[1] == 'x' || text[1] == 'X')) { + text += 2; + radix = 16; + } else if (radix == 0 && *text == '0' && (text[1] >= '0' && text[1] <= '9')) { + ++text; + radix = 8; + } else if (radix == 0) { + radix = 10; + } + number_start = text; + do { + unsigned long long digit; + if (*text >= '0' && *text <= '9') { + digit = *text - '0'; + } else if (radix > 10) { + if (*text >= 'A' && *text < 'A' + (radix - 10)) { + digit = 10 + (*text - 'A'); + } else if (*text >= 'a' && *text < 'a' + (radix - 10)) { + digit = 10 + (*text - 'a'); + } else { + break; + } + } else { + break; + } + if (value != 0 && radix > ullong_max / value) { + overflow = true; + } else { + value *= radix; + if (digit > ullong_max - value) { + overflow = true; + } else { + value += digit; + } + } + ++text; + } while (count == 0 || (text - text_start) != count); + } + if (text == number_start) { + if (radix == 16 && text > text_start && (*(text - 1) == 'x' || *(text - 1) == 'X')) { + // the string was "0x"; consume the '0' but not the 'x' + --text; + } else { + // no number was parsed, and thus no characters were consumed + text = text_start; + } + } + if (overflow) { + if (negative) { + value = 0; + } else { + value = ullong_max; + } + } else if (value == 0) { + negative = false; + } + *valuep = value; + *negativep = negative; + return text - text_start; +} +#endif + +#ifndef HAVE_WCSTOL +// SDL_ScanUnsignedLongLongInternalW assumes that wchar_t can be converted to int without truncating bits +SDL_COMPILE_TIME_ASSERT(wchar_t_int, sizeof(wchar_t) <= sizeof(int)); + +/** + * Parses an unsigned long long and returns the unsigned value and sign bit. + * + * Positive values are clamped to ULLONG_MAX. + * The result `value == 0 && negative` indicates negative overflow + * and might need to be handled differently depending on whether a + * signed or unsigned integer is being parsed. + */ +static size_t SDL_ScanUnsignedLongLongInternalW(const wchar_t *text, int count, int radix, unsigned long long *valuep, bool *negativep) +{ + const unsigned long long ullong_max = ~0ULL; + + const wchar_t *text_start = text; + const wchar_t *number_start = text_start; + unsigned long long value = 0; + bool negative = false; + bool overflow = false; + + if (radix == 0 || (radix >= 2 && radix <= 36)) { + while (SDL_isspace(*text)) { + ++text; + } + if (*text == '-' || *text == '+') { + negative = *text == '-'; + ++text; + } + if ((radix == 0 || radix == 16) && *text == '0' && (text[1] == 'x' || text[1] == 'X')) { + text += 2; + radix = 16; + } else if (radix == 0 && *text == '0' && (text[1] >= '0' && text[1] <= '9')) { + ++text; + radix = 8; + } else if (radix == 0) { + radix = 10; + } + number_start = text; + do { + unsigned long long digit; + if (*text >= '0' && *text <= '9') { + digit = *text - '0'; + } else if (radix > 10) { + if (*text >= 'A' && *text < 'A' + (radix - 10)) { + digit = 10 + (*text - 'A'); + } else if (*text >= 'a' && *text < 'a' + (radix - 10)) { + digit = 10 + (*text - 'a'); + } else { + break; + } + } else { + break; + } + if (value != 0 && radix > ullong_max / value) { + overflow = true; + } else { + value *= radix; + if (digit > ullong_max - value) { + overflow = true; + } else { + value += digit; + } + } + ++text; + } while (count == 0 || (text - text_start) != count); + } + if (text == number_start) { + if (radix == 16 && text > text_start && (*(text - 1) == 'x' || *(text - 1) == 'X')) { + // the string was "0x"; consume the '0' but not the 'x' + --text; + } else { + // no number was parsed, and thus no characters were consumed + text = text_start; + } + } + if (overflow) { + if (negative) { + value = 0; + } else { + value = ullong_max; + } + } else if (value == 0) { + negative = false; + } + *valuep = value; + *negativep = negative; + return text - text_start; +} +#endif + +#if !defined(HAVE_VSSCANF) || !defined(HAVE_STRTOL) +static size_t SDL_ScanLong(const char *text, int count, int radix, long *valuep) +{ + const unsigned long long_max = (~0UL) >> 1; + unsigned long long value; + bool negative; + size_t len = SDL_ScanUnsignedLongLongInternal(text, count, radix, &value, &negative); + if (negative) { + const unsigned long abs_long_min = long_max + 1; + if (value == 0 || value > abs_long_min) { + value = 0ULL - abs_long_min; + } else { + value = 0ULL - value; + } + } else if (value > long_max) { + value = long_max; + } + *valuep = (long)value; + return len; +} +#endif + +#ifndef HAVE_WCSTOL +static size_t SDL_ScanLongW(const wchar_t *text, int count, int radix, long *valuep) +{ + const unsigned long long_max = (~0UL) >> 1; + unsigned long long value; + bool negative; + size_t len = SDL_ScanUnsignedLongLongInternalW(text, count, radix, &value, &negative); + if (negative) { + const unsigned long abs_long_min = long_max + 1; + if (value == 0 || value > abs_long_min) { + value = 0ULL - abs_long_min; + } else { + value = 0ULL - value; + } + } else if (value > long_max) { + value = long_max; + } + *valuep = (long)value; + return len; +} +#endif + +#if !defined(HAVE_VSSCANF) || !defined(HAVE_STRTOUL) +static size_t SDL_ScanUnsignedLong(const char *text, int count, int radix, unsigned long *valuep) +{ + const unsigned long ulong_max = ~0UL; + unsigned long long value; + bool negative; + size_t len = SDL_ScanUnsignedLongLongInternal(text, count, radix, &value, &negative); + if (negative) { + if (value == 0 || value > ulong_max) { + value = ulong_max; + } else if (value == ulong_max) { + value = 1; + } else { + value = 0ULL - value; + } + } else if (value > ulong_max) { + value = ulong_max; + } + *valuep = (unsigned long)value; + return len; +} +#endif + +#ifndef HAVE_VSSCANF +static size_t SDL_ScanUintPtrT(const char *text, uintptr_t *valuep) +{ + const uintptr_t uintptr_max = ~(uintptr_t)0; + unsigned long long value; + bool negative; + size_t len = SDL_ScanUnsignedLongLongInternal(text, 0, 16, &value, &negative); + if (negative) { + if (value == 0 || value > uintptr_max) { + value = uintptr_max; + } else if (value == uintptr_max) { + value = 1; + } else { + value = 0ULL - value; + } + } else if (value > uintptr_max) { + value = uintptr_max; + } + *valuep = (uintptr_t)value; + return len; +} +#endif + +#if !defined(HAVE_VSSCANF) || !defined(HAVE_STRTOLL) +static size_t SDL_ScanLongLong(const char *text, int count, int radix, long long *valuep) +{ + const unsigned long long llong_max = (~0ULL) >> 1; + unsigned long long value; + bool negative; + size_t len = SDL_ScanUnsignedLongLongInternal(text, count, radix, &value, &negative); + if (negative) { + const unsigned long long abs_llong_min = llong_max + 1; + if (value == 0 || value > abs_llong_min) { + value = 0ULL - abs_llong_min; + } else { + value = 0ULL - value; + } + } else if (value > llong_max) { + value = llong_max; + } + *valuep = value; + return len; +} +#endif + +#if !defined(HAVE_VSSCANF) || !defined(HAVE_STRTOULL) || !defined(HAVE_STRTOD) +static size_t SDL_ScanUnsignedLongLong(const char *text, int count, int radix, unsigned long long *valuep) +{ + const unsigned long long ullong_max = ~0ULL; + bool negative; + size_t len = SDL_ScanUnsignedLongLongInternal(text, count, radix, valuep, &negative); + if (negative) { + if (*valuep == 0) { + *valuep = ullong_max; + } else { + *valuep = 0ULL - *valuep; + } + } + return len; +} +#endif + +#if !defined(HAVE_VSSCANF) || !defined(HAVE_STRTOD) +static size_t SDL_ScanFloat(const char *text, double *valuep) +{ + const char *text_start = text; + const char *number_start = text_start; + double value = 0.0; + bool negative = false; + + while (SDL_isspace(*text)) { + ++text; + } + if (*text == '-' || *text == '+') { + negative = *text == '-'; + ++text; + } + number_start = text; + if (SDL_isdigit(*text)) { + value += SDL_strtoull(text, (char **)(&text), 10); + if (*text == '.') { + double denom = 10; + ++text; + while (SDL_isdigit(*text)) { + value += (double)(*text - '0') / denom; + denom *= 10; + ++text; + } + } + } + if (text == number_start) { + // no number was parsed, and thus no characters were consumed + text = text_start; + } else if (negative) { + value = -value; + } + *valuep = value; + return text - text_start; +} +#endif + +int SDL_memcmp(const void *s1, const void *s2, size_t len) +{ +#ifdef SDL_PLATFORM_VITA + /* + Using memcmp on NULL is UB per POSIX / C99 7.21.1/2. + But, both linux and bsd allow that, with an exception: + zero length strings are always identical, so NULLs are never dereferenced. + sceClibMemcmp on PSVita doesn't allow that, so we check ourselves. + */ + if (len == 0) { + return 0; + } + return sceClibMemcmp(s1, s2, len); +#elif defined(HAVE_MEMCMP) + return memcmp(s1, s2, len); +#else + char *s1p = (char *)s1; + char *s2p = (char *)s2; + while (len--) { + if (*s1p != *s2p) { + return *s1p - *s2p; + } + ++s1p; + ++s2p; + } + return 0; +#endif // HAVE_MEMCMP +} + +size_t SDL_strlen(const char *string) +{ +#ifdef HAVE_STRLEN + return strlen(string); +#else + size_t len = 0; + while (*string++) { + ++len; + } + return len; +#endif // HAVE_STRLEN +} + +size_t SDL_strnlen(const char *string, size_t maxlen) +{ +#ifdef HAVE_STRNLEN + return strnlen(string, maxlen); +#else + size_t len = 0; + while (len < maxlen && *string++) { + ++len; + } + return len; +#endif // HAVE_STRNLEN +} + +size_t SDL_wcslen(const wchar_t *string) +{ +#ifdef HAVE_WCSLEN + return wcslen(string); +#else + size_t len = 0; + while (*string++) { + ++len; + } + return len; +#endif // HAVE_WCSLEN +} + +size_t SDL_wcsnlen(const wchar_t *string, size_t maxlen) +{ +#ifdef HAVE_WCSNLEN + return wcsnlen(string, maxlen); +#else + size_t len = 0; + while (len < maxlen && *string++) { + ++len; + } + return len; +#endif // HAVE_WCSNLEN +} + +size_t SDL_wcslcpy(SDL_OUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t maxlen) +{ +#ifdef HAVE_WCSLCPY + return wcslcpy(dst, src, maxlen); +#else + size_t srclen = SDL_wcslen(src); + if (maxlen > 0) { + size_t len = SDL_min(srclen, maxlen - 1); + SDL_memcpy(dst, src, len * sizeof(wchar_t)); + dst[len] = '\0'; + } + return srclen; +#endif // HAVE_WCSLCPY +} + +size_t SDL_wcslcat(SDL_INOUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t maxlen) +{ +#ifdef HAVE_WCSLCAT + return wcslcat(dst, src, maxlen); +#else + size_t dstlen = SDL_wcslen(dst); + size_t srclen = SDL_wcslen(src); + if (dstlen < maxlen) { + SDL_wcslcpy(dst + dstlen, src, maxlen - dstlen); + } + return dstlen + srclen; +#endif // HAVE_WCSLCAT +} + +wchar_t *SDL_wcsdup(const wchar_t *string) +{ + size_t len = ((SDL_wcslen(string) + 1) * sizeof(wchar_t)); + wchar_t *newstr = (wchar_t *)SDL_malloc(len); + if (newstr) { + SDL_memcpy(newstr, string, len); + } + return newstr; +} + +wchar_t *SDL_wcsnstr(const wchar_t *haystack, const wchar_t *needle, size_t maxlen) +{ + size_t length = SDL_wcslen(needle); + if (length == 0) { + return (wchar_t *)haystack; + } + while (maxlen >= length && *haystack) { + if (maxlen >= length && SDL_wcsncmp(haystack, needle, length) == 0) { + return (wchar_t *)haystack; + } + ++haystack; + --maxlen; + } + return NULL; +} + +wchar_t *SDL_wcsstr(const wchar_t *haystack, const wchar_t *needle) +{ +#ifdef HAVE_WCSSTR + return SDL_const_cast(wchar_t *, wcsstr(haystack, needle)); +#else + return SDL_wcsnstr(haystack, needle, SDL_wcslen(haystack)); +#endif // HAVE_WCSSTR +} + +int SDL_wcscmp(const wchar_t *str1, const wchar_t *str2) +{ +#ifdef HAVE_WCSCMP + return wcscmp(str1, str2); +#else + while (*str1 && *str2) { + if (*str1 != *str2) { + break; + } + ++str1; + ++str2; + } + return *str1 - *str2; +#endif // HAVE_WCSCMP +} + +int SDL_wcsncmp(const wchar_t *str1, const wchar_t *str2, size_t maxlen) +{ +#ifdef HAVE_WCSNCMP + return wcsncmp(str1, str2, maxlen); +#else + while (*str1 && *str2 && maxlen) { + if (*str1 != *str2) { + break; + } + ++str1; + ++str2; + --maxlen; + } + if (!maxlen) { + return 0; + } + return *str1 - *str2; + +#endif // HAVE_WCSNCMP +} + +int SDL_wcscasecmp(const wchar_t *wstr1, const wchar_t *wstr2) +{ +#if (SDL_SIZEOF_WCHAR_T == 2) + const Uint16 *str1 = (const Uint16 *) wstr1; + const Uint16 *str2 = (const Uint16 *) wstr2; + UNICODE_STRCASECMP(16, 2, 2, (void) str1start, (void) str2start); // always NULL-terminated, no need to adjust lengths. +#elif (SDL_SIZEOF_WCHAR_T == 4) + const Uint32 *str1 = (const Uint32 *) wstr1; + const Uint32 *str2 = (const Uint32 *) wstr2; + UNICODE_STRCASECMP(32, 1, 1, (void) str1start, (void) str2start); // always NULL-terminated, no need to adjust lengths. +#else + #error Unexpected wchar_t size + return -1; +#endif +} + +int SDL_wcsncasecmp(const wchar_t *wstr1, const wchar_t *wstr2, size_t maxlen) +{ + size_t slen1 = maxlen; + size_t slen2 = maxlen; + +#if (SDL_SIZEOF_WCHAR_T == 2) + const Uint16 *str1 = (const Uint16 *) wstr1; + const Uint16 *str2 = (const Uint16 *) wstr2; + UNICODE_STRCASECMP(16, slen1, slen2, slen1 -= (size_t) (str1 - str1start), slen2 -= (size_t) (str2 - str2start)); +#elif (SDL_SIZEOF_WCHAR_T == 4) + const Uint32 *str1 = (const Uint32 *) wstr1; + const Uint32 *str2 = (const Uint32 *) wstr2; + UNICODE_STRCASECMP(32, slen1, slen2, slen1 -= (size_t) (str1 - str1start), slen2 -= (size_t) (str2 - str2start)); +#else + #error Unexpected wchar_t size + return -1; +#endif +} + +long SDL_wcstol(const wchar_t *string, wchar_t **endp, int base) +{ +#ifdef HAVE_WCSTOL + return wcstol(string, endp, base); +#else + long value = 0; + size_t len = SDL_ScanLongW(string, 0, base, &value); + if (endp) { + *endp = (wchar_t *)string + len; + } + return value; +#endif // HAVE_WCSTOL +} + +size_t SDL_strlcpy(SDL_OUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen) +{ +#ifdef HAVE_STRLCPY + return strlcpy(dst, src, maxlen); +#else + size_t srclen = SDL_strlen(src); + if (maxlen > 0) { + size_t len = SDL_min(srclen, maxlen - 1); + SDL_memcpy(dst, src, len); + dst[len] = '\0'; + } + return srclen; +#endif // HAVE_STRLCPY +} + +size_t SDL_utf8strlcpy(SDL_OUT_Z_CAP(dst_bytes) char *dst, const char *src, size_t dst_bytes) +{ + size_t bytes = 0; + + if (dst_bytes > 0) { + size_t src_bytes = SDL_strlen(src); + size_t i = 0; + size_t trailing_bytes = 0; + + bytes = SDL_min(src_bytes, dst_bytes - 1); + if (bytes) { + unsigned char c = (unsigned char)src[bytes - 1]; + if (UTF8_IsLeadByte(c)) { + --bytes; + } else if (UTF8_IsTrailingByte(c)) { + for (i = bytes - 1; i != 0; --i) { + c = (unsigned char)src[i]; + trailing_bytes = UTF8_GetTrailingBytes(c); + if (trailing_bytes) { + if ((bytes - i) != (trailing_bytes + 1)) { + bytes = i; + } + + break; + } + } + } + SDL_memcpy(dst, src, bytes); + } + dst[bytes] = '\0'; + } + + return bytes; +} + +size_t SDL_utf8strlen(const char *str) +{ + size_t result = 0; + while (SDL_StepUTF8(&str, NULL)) { + result++; + } + return result; +} + +size_t SDL_utf8strnlen(const char *str, size_t bytes) +{ + size_t result = 0; + while (SDL_StepUTF8(&str, &bytes)) { + result++; + } + return result; +} + +size_t SDL_strlcat(SDL_INOUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen) +{ +#ifdef HAVE_STRLCAT + return strlcat(dst, src, maxlen); +#else + size_t dstlen = SDL_strlen(dst); + size_t srclen = SDL_strlen(src); + if (dstlen < maxlen) { + SDL_strlcpy(dst + dstlen, src, maxlen - dstlen); + } + return dstlen + srclen; +#endif // HAVE_STRLCAT +} + +char *SDL_strdup(const char *string) +{ + size_t len = SDL_strlen(string) + 1; + char *newstr = (char *)SDL_malloc(len); + if (newstr) { + SDL_memcpy(newstr, string, len); + } + return newstr; +} + +char *SDL_strndup(const char *string, size_t maxlen) +{ + size_t len = SDL_strnlen(string, maxlen); + char *newstr = (char *)SDL_malloc(len + 1); + if (newstr) { + SDL_memcpy(newstr, string, len); + newstr[len] = '\0'; + } + return newstr; +} + +char *SDL_strrev(char *string) +{ +#ifdef HAVE__STRREV + return _strrev(string); +#else + size_t len = SDL_strlen(string); + char *a = &string[0]; + char *b = &string[len - 1]; + len /= 2; + while (len--) { + const char c = *a; // NOLINT(clang-analyzer-core.uninitialized.Assign) + *a++ = *b; + *b-- = c; + } + return string; +#endif // HAVE__STRREV +} + +char *SDL_strupr(char *string) +{ + char *bufp = string; + while (*bufp) { + *bufp = (char)SDL_toupper((unsigned char)*bufp); + ++bufp; + } + return string; +} + +char *SDL_strlwr(char *string) +{ + char *bufp = string; + while (*bufp) { + *bufp = (char)SDL_tolower((unsigned char)*bufp); + ++bufp; + } + return string; +} + +char *SDL_strchr(const char *string, int c) +{ +#ifdef HAVE_STRCHR + return SDL_const_cast(char *, strchr(string, c)); +#elif defined(HAVE_INDEX) + return SDL_const_cast(char *, index(string, c)); +#else + while (*string) { + if (*string == c) { + return (char *)string; + } + ++string; + } + if (c == '\0') { + return (char *)string; + } + return NULL; +#endif // HAVE_STRCHR +} + +char *SDL_strrchr(const char *string, int c) +{ +#ifdef HAVE_STRRCHR + return SDL_const_cast(char *, strrchr(string, c)); +#elif defined(HAVE_RINDEX) + return SDL_const_cast(char *, rindex(string, c)); +#else + const char *bufp = string + SDL_strlen(string); + while (bufp >= string) { + if (*bufp == c) { + return (char *)bufp; + } + --bufp; + } + return NULL; +#endif // HAVE_STRRCHR +} + +char *SDL_strnstr(const char *haystack, const char *needle, size_t maxlen) +{ +#ifdef HAVE_STRNSTR + return SDL_const_cast(char *, strnstr(haystack, needle, maxlen)); +#else + size_t length = SDL_strlen(needle); + if (length == 0) { + return (char *)haystack; + } + while (maxlen >= length && *haystack) { + if (SDL_strncmp(haystack, needle, length) == 0) { + return (char *)haystack; + } + ++haystack; + --maxlen; + } + return NULL; +#endif // HAVE_STRSTR +} + +char *SDL_strstr(const char *haystack, const char *needle) +{ +#ifdef HAVE_STRSTR + return SDL_const_cast(char *, strstr(haystack, needle)); +#else + return SDL_strnstr(haystack, needle, SDL_strlen(haystack)); +#endif // HAVE_STRSTR +} + +char *SDL_strcasestr(const char *haystack, const char *needle) +{ + const size_t length = SDL_strlen(needle); + do { + if (SDL_strncasecmp(haystack, needle, length) == 0) { + return (char *)haystack; + } + } while (SDL_StepUTF8(&haystack, NULL)); // move ahead by a full codepoint at a time, regardless of bytes. + + return NULL; +} + +#if !defined(HAVE__LTOA) || !defined(HAVE__I64TOA) || \ + !defined(HAVE__ULTOA) || !defined(HAVE__UI64TOA) +static const char ntoa_table[] = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', + 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', + 'U', 'V', 'W', 'X', 'Y', 'Z' +}; +#endif // ntoa() conversion table + +char *SDL_itoa(int value, char *string, int radix) +{ +#ifdef HAVE_ITOA + return itoa(value, string, radix); +#else + return SDL_ltoa((long)value, string, radix); +#endif // HAVE_ITOA +} + +char *SDL_uitoa(unsigned int value, char *string, int radix) +{ +#ifdef HAVE__UITOA + return _uitoa(value, string, radix); +#else + return SDL_ultoa((unsigned long)value, string, radix); +#endif // HAVE__UITOA +} + +char *SDL_ltoa(long value, char *string, int radix) +{ +#ifdef HAVE__LTOA + return _ltoa(value, string, radix); +#else + char *bufp = string; + + if (value < 0) { + *bufp++ = '-'; + SDL_ultoa(-value, bufp, radix); + } else { + SDL_ultoa(value, bufp, radix); + } + + return string; +#endif // HAVE__LTOA +} + +char *SDL_ultoa(unsigned long value, char *string, int radix) +{ +#ifdef HAVE__ULTOA + return _ultoa(value, string, radix); +#else + char *bufp = string; + + if (value) { + while (value > 0) { + *bufp++ = ntoa_table[value % radix]; + value /= radix; + } + } else { + *bufp++ = '0'; + } + *bufp = '\0'; + + // The numbers went into the string backwards. :) + SDL_strrev(string); + + return string; +#endif // HAVE__ULTOA +} + +char *SDL_lltoa(long long value, char *string, int radix) +{ +#ifdef HAVE__I64TOA + return _i64toa(value, string, radix); +#else + char *bufp = string; + + if (value < 0) { + *bufp++ = '-'; + SDL_ulltoa(-value, bufp, radix); + } else { + SDL_ulltoa(value, bufp, radix); + } + + return string; +#endif // HAVE__I64TOA +} + +char *SDL_ulltoa(unsigned long long value, char *string, int radix) +{ +#ifdef HAVE__UI64TOA + return _ui64toa(value, string, radix); +#else + char *bufp = string; + + if (value) { + while (value > 0) { + *bufp++ = ntoa_table[value % radix]; + value /= radix; + } + } else { + *bufp++ = '0'; + } + *bufp = '\0'; + + // The numbers went into the string backwards. :) + SDL_strrev(string); + + return string; +#endif // HAVE__UI64TOA +} + +int SDL_atoi(const char *string) +{ +#ifdef HAVE_ATOI + return atoi(string); +#else + return SDL_strtol(string, NULL, 10); +#endif // HAVE_ATOI +} + +double SDL_atof(const char *string) +{ +#ifdef HAVE_ATOF + return atof(string); +#else + return SDL_strtod(string, NULL); +#endif // HAVE_ATOF +} + +long SDL_strtol(const char *string, char **endp, int base) +{ +#ifdef HAVE_STRTOL + return strtol(string, endp, base); +#else + long value = 0; + size_t len = SDL_ScanLong(string, 0, base, &value); + if (endp) { + *endp = (char *)string + len; + } + return value; +#endif // HAVE_STRTOL +} + +unsigned long SDL_strtoul(const char *string, char **endp, int base) +{ +#ifdef HAVE_STRTOUL + return strtoul(string, endp, base); +#else + unsigned long value = 0; + size_t len = SDL_ScanUnsignedLong(string, 0, base, &value); + if (endp) { + *endp = (char *)string + len; + } + return value; +#endif // HAVE_STRTOUL +} + +long long SDL_strtoll(const char *string, char **endp, int base) +{ +#ifdef HAVE_STRTOLL + return strtoll(string, endp, base); +#else + long long value = 0; + size_t len = SDL_ScanLongLong(string, 0, base, &value); + if (endp) { + *endp = (char *)string + len; + } + return value; +#endif // HAVE_STRTOLL +} + +unsigned long long SDL_strtoull(const char *string, char **endp, int base) +{ +#ifdef HAVE_STRTOULL + return strtoull(string, endp, base); +#else + unsigned long long value = 0; + size_t len = SDL_ScanUnsignedLongLong(string, 0, base, &value); + if (endp) { + *endp = (char *)string + len; + } + return value; +#endif // HAVE_STRTOULL +} + +double SDL_strtod(const char *string, char **endp) +{ +#ifdef HAVE_STRTOD + return strtod(string, endp); +#else + double value; + size_t len = SDL_ScanFloat(string, &value); + if (endp) { + *endp = (char *)string + len; + } + return value; +#endif // HAVE_STRTOD +} + +int SDL_strcmp(const char *str1, const char *str2) +{ +#ifdef HAVE_STRCMP + return strcmp(str1, str2); +#else + int result; + + while (1) { + result = ((unsigned char)*str1 - (unsigned char)*str2); + if (result != 0 || (*str1 == '\0' /* && *str2 == '\0'*/)) { + break; + } + ++str1; + ++str2; + } + return result; +#endif // HAVE_STRCMP +} + +int SDL_strncmp(const char *str1, const char *str2, size_t maxlen) +{ +#ifdef HAVE_STRNCMP + return strncmp(str1, str2, maxlen); +#else + int result = 0; + + while (maxlen) { + result = (int)(unsigned char)*str1 - (unsigned char)*str2; + if (result != 0 || *str1 == '\0' /* && *str2 == '\0'*/) { + break; + } + ++str1; + ++str2; + --maxlen; + } + return result; +#endif // HAVE_STRNCMP +} + +int SDL_strcasecmp(const char *str1, const char *str2) +{ + UNICODE_STRCASECMP(8, 4, 4, (void) str1start, (void) str2start); // always NULL-terminated, no need to adjust lengths. +} + +int SDL_strncasecmp(const char *str1, const char *str2, size_t maxlen) +{ + size_t slen1 = maxlen; + size_t slen2 = maxlen; + UNICODE_STRCASECMP(8, slen1, slen2, slen1 -= (size_t) (str1 - ((const char *) str1start)), slen2 -= (size_t) (str2 - ((const char *) str2start))); +} + +int SDL_sscanf(const char *text, SDL_SCANF_FORMAT_STRING const char *fmt, ...) +{ + int rc; + va_list ap; + va_start(ap, fmt); + rc = SDL_vsscanf(text, fmt, ap); + va_end(ap); + return rc; +} + +#ifdef HAVE_VSSCANF +int SDL_vsscanf(const char *text, const char *fmt, va_list ap) +{ + return vsscanf(text, fmt, ap); +} +#else +static bool CharacterMatchesSet(char c, const char *set, size_t set_len) +{ + bool invert = false; + bool result = false; + + if (*set == '^') { + invert = true; + ++set; + --set_len; + } + while (set_len > 0 && !result) { + if (set_len >= 3 && set[1] == '-') { + char low_char = SDL_min(set[0], set[2]); + char high_char = SDL_max(set[0], set[2]); + if (c >= low_char && c <= high_char) { + result = true; + } + set += 3; + set_len -= 3; + } else { + if (c == *set) { + result = true; + } + ++set; + --set_len; + } + } + if (invert) { + result = !result; + } + return result; +} + +// NOLINTNEXTLINE(readability-non-const-parameter) +int SDL_vsscanf(const char *text, SDL_SCANF_FORMAT_STRING const char *fmt, va_list ap) +{ + const char *start = text; + int result = 0; + + if (!text || !*text) { + return -1; + } + + while (*fmt) { + if (*fmt == ' ') { + while (SDL_isspace((unsigned char)*text)) { + ++text; + } + ++fmt; + continue; + } + if (*fmt == '%') { + bool done = false; + long count = 0; + int radix = 10; + enum + { + DO_SHORT, + DO_INT, + DO_LONG, + DO_LONGLONG, + DO_SIZE_T + } inttype = DO_INT; + size_t advance; + bool suppress = false; + + ++fmt; + if (*fmt == '%') { + if (*text == '%') { + ++text; + ++fmt; + continue; + } + break; + } + if (*fmt == '*') { + suppress = true; + ++fmt; + } + fmt += SDL_ScanLong(fmt, 0, 10, &count); + + if (*fmt == 'c') { + if (!count) { + count = 1; + } + if (suppress) { + while (count--) { + ++text; + } + } else { + char *valuep = va_arg(ap, char *); + while (count--) { + *valuep++ = *text++; + } + ++result; + } + continue; + } + + while (SDL_isspace((unsigned char)*text)) { + ++text; + } + + // FIXME: implement more of the format specifiers + while (!done) { + switch (*fmt) { + case '*': + suppress = true; + break; + case 'h': + if (inttype == DO_INT) { + inttype = DO_SHORT; + } else if (inttype > DO_SHORT) { + ++inttype; + } + break; + case 'l': + if (inttype < DO_LONGLONG) { + ++inttype; + } + break; + case 'I': + if (SDL_strncmp(fmt, "I64", 3) == 0) { + fmt += 2; + inttype = DO_LONGLONG; + } + break; + case 'z': + inttype = DO_SIZE_T; + break; + case 'i': + { + int index = 0; + if (text[index] == '-') { + ++index; + } + if (text[index] == '0') { + if (SDL_tolower((unsigned char)text[index + 1]) == 'x') { + radix = 16; + } else { + radix = 8; + } + } + } + SDL_FALLTHROUGH; + case 'd': + if (inttype == DO_LONGLONG) { + long long value = 0; + advance = SDL_ScanLongLong(text, count, radix, &value); + text += advance; + if (advance && !suppress) { + Sint64 *valuep = va_arg(ap, Sint64 *); + *valuep = value; + ++result; + } + } else if (inttype == DO_SIZE_T) { + long long value = 0; + advance = SDL_ScanLongLong(text, count, radix, &value); + text += advance; + if (advance && !suppress) { + size_t *valuep = va_arg(ap, size_t *); + *valuep = (size_t)value; + ++result; + } + } else { + long value = 0; + advance = SDL_ScanLong(text, count, radix, &value); + text += advance; + if (advance && !suppress) { + switch (inttype) { + case DO_SHORT: + { + short *valuep = va_arg(ap, short *); + *valuep = (short)value; + } break; + case DO_INT: + { + int *valuep = va_arg(ap, int *); + *valuep = (int)value; + } break; + case DO_LONG: + { + long *valuep = va_arg(ap, long *); + *valuep = value; + } break; + case DO_LONGLONG: + case DO_SIZE_T: + // Handled above + break; + } + ++result; + } + } + done = true; + break; + case 'o': + if (radix == 10) { + radix = 8; + } + SDL_FALLTHROUGH; + case 'x': + case 'X': + if (radix == 10) { + radix = 16; + } + SDL_FALLTHROUGH; + case 'u': + if (inttype == DO_LONGLONG) { + unsigned long long value = 0; + advance = SDL_ScanUnsignedLongLong(text, count, radix, &value); + text += advance; + if (advance && !suppress) { + Uint64 *valuep = va_arg(ap, Uint64 *); + *valuep = value; + ++result; + } + } else if (inttype == DO_SIZE_T) { + unsigned long long value = 0; + advance = SDL_ScanUnsignedLongLong(text, count, radix, &value); + text += advance; + if (advance && !suppress) { + size_t *valuep = va_arg(ap, size_t *); + *valuep = (size_t)value; + ++result; + } + } else { + unsigned long value = 0; + advance = SDL_ScanUnsignedLong(text, count, radix, &value); + text += advance; + if (advance && !suppress) { + switch (inttype) { + case DO_SHORT: + { + short *valuep = va_arg(ap, short *); + *valuep = (short)value; + } break; + case DO_INT: + { + int *valuep = va_arg(ap, int *); + *valuep = (int)value; + } break; + case DO_LONG: + { + long *valuep = va_arg(ap, long *); + *valuep = value; + } break; + case DO_LONGLONG: + case DO_SIZE_T: + // Handled above + break; + } + ++result; + } + } + done = true; + break; + case 'p': + { + uintptr_t value = 0; + advance = SDL_ScanUintPtrT(text, &value); + text += advance; + if (advance && !suppress) { + void **valuep = va_arg(ap, void **); + *valuep = (void *)value; + ++result; + } + } + done = true; + break; + case 'f': + { + double value = 0.0; + advance = SDL_ScanFloat(text, &value); + text += advance; + if (advance && !suppress) { + float *valuep = va_arg(ap, float *); + *valuep = (float)value; + ++result; + } + } + done = true; + break; + case 's': + if (suppress) { + while (!SDL_isspace((unsigned char)*text)) { + ++text; + if (count) { + if (--count == 0) { + break; + } + } + } + } else { + char *valuep = va_arg(ap, char *); + while (!SDL_isspace((unsigned char)*text)) { + *valuep++ = *text++; + if (count) { + if (--count == 0) { + break; + } + } + } + *valuep = '\0'; + ++result; + } + done = true; + break; + case 'n': + switch (inttype) { + case DO_SHORT: + { + short *valuep = va_arg(ap, short *); + *valuep = (short)(text - start); + } break; + case DO_INT: + { + int *valuep = va_arg(ap, int *); + *valuep = (int)(text - start); + } break; + case DO_LONG: + { + long *valuep = va_arg(ap, long *); + *valuep = (long)(text - start); + } break; + case DO_LONGLONG: + { + long long *valuep = va_arg(ap, long long *); + *valuep = (long long)(text - start); + } break; + case DO_SIZE_T: + { + size_t *valuep = va_arg(ap, size_t *); + *valuep = (size_t)(text - start); + } break; + } + done = true; + break; + case '[': + { + const char *set = fmt + 1; + while (*fmt && *fmt != ']') { + ++fmt; + } + if (*fmt) { + size_t set_len = (fmt - set); + if (suppress) { + while (CharacterMatchesSet(*text, set, set_len)) { + ++text; + if (count) { + if (--count == 0) { + break; + } + } + } + } else { + bool had_match = false; + char *valuep = va_arg(ap, char *); + while (CharacterMatchesSet(*text, set, set_len)) { + had_match = true; + *valuep++ = *text++; + if (count) { + if (--count == 0) { + break; + } + } + } + *valuep = '\0'; + if (had_match) { + ++result; + } + } + } + } + done = true; + break; + default: + done = true; + break; + } + ++fmt; + } + continue; + } + if (*text == *fmt) { + ++text; + ++fmt; + continue; + } + // Text didn't match format specifier + break; + } + + return result; +} +#endif // HAVE_VSSCANF + +int SDL_snprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + int result; + + va_start(ap, fmt); + result = SDL_vsnprintf(text, maxlen, fmt, ap); + va_end(ap); + + return result; +} + +int SDL_swprintf(SDL_OUT_Z_CAP(maxlen) wchar_t *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const wchar_t *fmt, ...) +{ + va_list ap; + int result; + + va_start(ap, fmt); + result = SDL_vswprintf(text, maxlen, fmt, ap); + va_end(ap); + + return result; +} + +#if defined(HAVE_LIBC) && defined(__WATCOMC__) +// _vsnprintf() doesn't ensure nul termination +int SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt, va_list ap) +{ + int result; + if (!fmt) { + fmt = ""; + } + result = _vsnprintf(text, maxlen, fmt, ap); + if (maxlen > 0) { + text[maxlen - 1] = '\0'; + } + if (result < 0) { + result = (int)maxlen; + } + return result; +} +#elif defined(HAVE_VSNPRINTF) +int SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt, va_list ap) +{ + if (!fmt) { + fmt = ""; + } + return vsnprintf(text, maxlen, fmt, ap); +} +#else +#define TEXT_AND_LEN_ARGS (length < maxlen) ? &text[length] : NULL, (length < maxlen) ? (maxlen - length) : 0 + +// FIXME: implement more of the format specifiers +typedef enum +{ + SDL_CASE_NOCHANGE, + SDL_CASE_LOWER, + SDL_CASE_UPPER +} SDL_letter_case; + +typedef struct +{ + bool left_justify; + bool force_sign; + bool force_type; // for now: used only by float printer, ignored otherwise. + bool pad_zeroes; + SDL_letter_case force_case; + int width; + int radix; + int precision; +} SDL_FormatInfo; + +static size_t SDL_PrintString(char *text, size_t maxlen, SDL_FormatInfo *info, const char *string) +{ + const char fill = (info && info->pad_zeroes) ? '0' : ' '; + size_t width = 0; + size_t filllen = 0; + size_t length = 0; + size_t slen, sz; + + if (!string) { + string = "(null)"; + } + + sz = SDL_strlen(string); + if (info && info->width > 0 && (size_t)info->width > sz) { + width = info->width - sz; + if (info->precision >= 0 && (size_t)info->precision < sz) { + width += sz - (size_t)info->precision; + } + + filllen = SDL_min(width, maxlen); + if (!info->left_justify) { + SDL_memset(text, fill, filllen); + text += filllen; + maxlen -= filllen; + length += width; + filllen = 0; + } + } + + SDL_strlcpy(text, string, maxlen); + length += sz; + + if (filllen > 0) { + SDL_memset(text + sz, fill, filllen); + length += width; + } + + if (info) { + if (info->precision >= 0 && (size_t)info->precision < sz) { + slen = (size_t)info->precision; + if (slen < maxlen) { + text[slen] = '\0'; + } + length -= (sz - slen); + } + if (maxlen > 1) { + if (info->force_case == SDL_CASE_LOWER) { + SDL_strlwr(text); + } else if (info->force_case == SDL_CASE_UPPER) { + SDL_strupr(text); + } + } + } + return length; +} + +static size_t SDL_PrintStringW(char *text, size_t maxlen, SDL_FormatInfo *info, const wchar_t *wide_string) +{ + size_t length = 0; + if (wide_string) { + char *string = SDL_iconv_string("UTF-8", "WCHAR_T", (char *)(wide_string), (SDL_wcslen(wide_string) + 1) * sizeof(*wide_string)); + length = SDL_PrintString(TEXT_AND_LEN_ARGS, info, string); + SDL_free(string); + } else { + length = SDL_PrintString(TEXT_AND_LEN_ARGS, info, NULL); + } + return length; +} + +static void SDL_IntPrecisionAdjust(char *num, size_t maxlen, SDL_FormatInfo *info) +{ // left-pad num with zeroes. + size_t sz, pad, have_sign; + + if (!info) { + return; + } + + have_sign = 0; + if (*num == '-' || *num == '+') { + have_sign = 1; + ++num; + --maxlen; + } + sz = SDL_strlen(num); + if (info->precision > 0 && sz < (size_t)info->precision) { + pad = (size_t)info->precision - sz; + if (pad + sz + 1 <= maxlen) { // otherwise ignore the precision + SDL_memmove(num + pad, num, sz + 1); + SDL_memset(num, '0', pad); + } + } + info->precision = -1; // so that SDL_PrintString() doesn't make a mess. + + if (info->pad_zeroes && info->width > 0 && (size_t)info->width > sz + have_sign) { + /* handle here: spaces are added before the sign + but zeroes must be placed _after_ the sign. */ + // sz hasn't changed: we ignore pad_zeroes if a precision is given. + pad = (size_t)info->width - sz - have_sign; + if (pad + sz + 1 <= maxlen) { + SDL_memmove(num + pad, num, sz + 1); + SDL_memset(num, '0', pad); + } + info->width = 0; // so that SDL_PrintString() doesn't make a mess. + } +} + +static size_t SDL_PrintLong(char *text, size_t maxlen, SDL_FormatInfo *info, long value) +{ + char num[130], *p = num; + + if (info->force_sign && value >= 0L) { + *p++ = '+'; + } + + SDL_ltoa(value, p, info ? info->radix : 10); + SDL_IntPrecisionAdjust(num, sizeof(num), info); + return SDL_PrintString(text, maxlen, info, num); +} + +static size_t SDL_PrintUnsignedLong(char *text, size_t maxlen, SDL_FormatInfo *info, unsigned long value) +{ + char num[130]; + + SDL_ultoa(value, num, info ? info->radix : 10); + SDL_IntPrecisionAdjust(num, sizeof(num), info); + return SDL_PrintString(text, maxlen, info, num); +} + +static size_t SDL_PrintLongLong(char *text, size_t maxlen, SDL_FormatInfo *info, long long value) +{ + char num[130], *p = num; + + if (info->force_sign && value >= (Sint64)0) { + *p++ = '+'; + } + + SDL_lltoa(value, p, info ? info->radix : 10); + SDL_IntPrecisionAdjust(num, sizeof(num), info); + return SDL_PrintString(text, maxlen, info, num); +} + +static size_t SDL_PrintUnsignedLongLong(char *text, size_t maxlen, SDL_FormatInfo *info, unsigned long long value) +{ + char num[130]; + + SDL_ulltoa(value, num, info ? info->radix : 10); + SDL_IntPrecisionAdjust(num, sizeof(num), info); + return SDL_PrintString(text, maxlen, info, num); +} + +static size_t SDL_PrintFloat(char *text, size_t maxlen, SDL_FormatInfo *info, double arg, bool g) +{ + char num[327]; + size_t length = 0; + size_t integer_length; + int precision = info->precision; + + // This isn't especially accurate, but hey, it's easy. :) + unsigned long long value; + + if (arg < 0.0 || (arg == 0.0 && 1.0 / arg < 0.0)) { // additional check for signed zero + num[length++] = '-'; + arg = -arg; + } else if (info->force_sign) { + num[length++] = '+'; + } + value = (unsigned long long)arg; + integer_length = SDL_PrintUnsignedLongLong(&num[length], sizeof(num) - length, NULL, value); + length += integer_length; + arg -= value; + if (precision < 0) { + precision = 6; + } + if (g) { + // The precision includes the integer portion + precision -= SDL_min((int)integer_length, precision); + } + if (info->force_type || precision > 0) { + const char decimal_separator = '.'; + double integer_value; + + SDL_assert(length < sizeof(num)); + num[length++] = decimal_separator; + while (precision > 1) { + arg *= 10.0; + arg = SDL_modf(arg, &integer_value); + SDL_assert(length < sizeof(num)); + num[length++] = '0' + (char)integer_value; + --precision; + } + if (precision == 1) { + arg *= 10.0; + integer_value = SDL_round(arg); + if (integer_value == 10.0) { + // Carry the one... + size_t i; + + for (i = length; i--; ) { + if (num[i] == decimal_separator) { + continue; + } + if (num[i] == '9') { + num[i] = '0'; + if (i == 0 || num[i - 1] == '-' || num[i - 1] == '+') { + SDL_memmove(&num[i+1], &num[i], length - i); + num[i] = '1'; + ++length; + break; + } + } else { + ++num[i]; + break; + } + } + SDL_assert(length < sizeof(num)); + num[length++] = '0'; + } else { + SDL_assert(length < sizeof(num)); + num[length++] = '0' + (char)integer_value; + } + } + + if (g) { + // Trim trailing zeroes and decimal separator + size_t i; + + for (i = length - 1; num[i] != decimal_separator; --i) { + if (num[i] == '0') { + --length; + } else { + break; + } + } + if (num[i] == decimal_separator) { + --length; + } + } + } + num[length] = '\0'; + + info->precision = -1; + length = SDL_PrintString(text, maxlen, info, num); + + if (info->width > 0 && (size_t)info->width > length) { + const char fill = info->pad_zeroes ? '0' : ' '; + size_t width = info->width - length; + size_t filllen, movelen; + + filllen = SDL_min(width, maxlen); + movelen = SDL_min(length, (maxlen - filllen)); + SDL_memmove(&text[filllen], text, movelen); + SDL_memset(text, fill, filllen); + length += width; + } + return length; +} + +static size_t SDL_PrintPointer(char *text, size_t maxlen, SDL_FormatInfo *info, const void *value) +{ + char num[130]; + size_t length; + + if (!value) { + return SDL_PrintString(text, maxlen, info, NULL); + } + + SDL_ulltoa((unsigned long long)(uintptr_t)value, num, 16); + length = SDL_PrintString(text, maxlen, info, "0x"); + return length + SDL_PrintString(TEXT_AND_LEN_ARGS, info, num); +} + +// NOLINTNEXTLINE(readability-non-const-parameter) +int SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) +{ + size_t length = 0; + + if (!text) { + maxlen = 0; + } + if (!fmt) { + fmt = ""; + } + while (*fmt) { + if (*fmt == '%') { + bool done = false; + bool check_flag; + SDL_FormatInfo info; + enum + { + DO_INT, + DO_LONG, + DO_LONGLONG, + DO_SIZE_T + } inttype = DO_INT; + + SDL_zero(info); + info.radix = 10; + info.precision = -1; + + check_flag = true; + while (check_flag) { + ++fmt; + switch (*fmt) { + case '-': + info.left_justify = true; + break; + case '+': + info.force_sign = true; + break; + case '#': + info.force_type = true; + break; + case '0': + info.pad_zeroes = true; + break; + default: + check_flag = false; + break; + } + } + + if (*fmt >= '0' && *fmt <= '9') { + info.width = SDL_strtol(fmt, (char **)&fmt, 0); + } else if (*fmt == '*') { + ++fmt; + info.width = va_arg(ap, int); + } + + if (*fmt == '.') { + ++fmt; + if (*fmt >= '0' && *fmt <= '9') { + info.precision = SDL_strtol(fmt, (char **)&fmt, 0); + } else if (*fmt == '*') { + ++fmt; + info.precision = va_arg(ap, int); + } else { + info.precision = 0; + } + if (info.precision < 0) { + info.precision = 0; + } + } + + while (!done) { + switch (*fmt) { + case '%': + if (length < maxlen) { + text[length] = '%'; + } + ++length; + done = true; + break; + case 'c': + // char is promoted to int when passed through (...) + if (length < maxlen) { + text[length] = (char)va_arg(ap, int); + } + ++length; + done = true; + break; + case 'h': + // short is promoted to int when passed through (...) + break; + case 'l': + if (inttype < DO_LONGLONG) { + ++inttype; + } + break; + case 'I': + if (SDL_strncmp(fmt, "I64", 3) == 0) { + fmt += 2; + inttype = DO_LONGLONG; + } + break; + case 'z': + inttype = DO_SIZE_T; + break; + case 'i': + case 'd': + if (info.precision >= 0) { + info.pad_zeroes = false; + } + switch (inttype) { + case DO_INT: + length += SDL_PrintLong(TEXT_AND_LEN_ARGS, &info, + (long)va_arg(ap, int)); + break; + case DO_LONG: + length += SDL_PrintLong(TEXT_AND_LEN_ARGS, &info, + va_arg(ap, long)); + break; + case DO_LONGLONG: + length += SDL_PrintLongLong(TEXT_AND_LEN_ARGS, &info, + va_arg(ap, long long)); + break; + case DO_SIZE_T: + length += SDL_PrintLongLong(TEXT_AND_LEN_ARGS, &info, + va_arg(ap, size_t)); + break; + } + done = true; + break; + case 'p': + info.force_case = SDL_CASE_LOWER; + length += SDL_PrintPointer(TEXT_AND_LEN_ARGS, &info, va_arg(ap, void *)); + done = true; + break; + case 'x': + info.force_case = SDL_CASE_LOWER; + SDL_FALLTHROUGH; + case 'X': + if (info.force_case == SDL_CASE_NOCHANGE) { + info.force_case = SDL_CASE_UPPER; + } + if (info.radix == 10) { + info.radix = 16; + } + SDL_FALLTHROUGH; + case 'o': + if (info.radix == 10) { + info.radix = 8; + } + SDL_FALLTHROUGH; + case 'u': + info.force_sign = false; + if (info.precision >= 0) { + info.pad_zeroes = false; + } + switch (inttype) { + case DO_INT: + length += SDL_PrintUnsignedLong(TEXT_AND_LEN_ARGS, &info, + va_arg(ap, unsigned int)); + break; + case DO_LONG: + length += SDL_PrintUnsignedLong(TEXT_AND_LEN_ARGS, &info, + va_arg(ap, unsigned long)); + break; + case DO_LONGLONG: + length += SDL_PrintUnsignedLongLong(TEXT_AND_LEN_ARGS, &info, + va_arg(ap, unsigned long long)); + break; + case DO_SIZE_T: + length += SDL_PrintUnsignedLongLong(TEXT_AND_LEN_ARGS, &info, + va_arg(ap, size_t)); + break; + } + done = true; + break; + case 'f': + length += SDL_PrintFloat(TEXT_AND_LEN_ARGS, &info, va_arg(ap, double), false); + done = true; + break; + case 'g': + length += SDL_PrintFloat(TEXT_AND_LEN_ARGS, &info, va_arg(ap, double), true); + done = true; + break; + case 'S': + info.pad_zeroes = false; + length += SDL_PrintStringW(TEXT_AND_LEN_ARGS, &info, va_arg(ap, wchar_t *)); + done = true; + break; + case 's': + info.pad_zeroes = false; + if (inttype > DO_INT) { + length += SDL_PrintStringW(TEXT_AND_LEN_ARGS, &info, va_arg(ap, wchar_t *)); + } else { + length += SDL_PrintString(TEXT_AND_LEN_ARGS, &info, va_arg(ap, char *)); + } + done = true; + break; + default: + done = true; + break; + } + ++fmt; + } + } else { + if (length < maxlen) { + text[length] = *fmt; + } + ++fmt; + ++length; + } + } + if (length < maxlen) { + text[length] = '\0'; + } else if (maxlen > 0) { + text[maxlen - 1] = '\0'; + } + return (int)length; +} + +#undef TEXT_AND_LEN_ARGS +#endif // HAVE_VSNPRINTF + +int SDL_vswprintf(SDL_OUT_Z_CAP(maxlen) wchar_t *text, size_t maxlen, const wchar_t *fmt, va_list ap) +{ + char *fmt_utf8 = NULL; + if (fmt) { + fmt_utf8 = SDL_iconv_string("UTF-8", "WCHAR_T", (const char *)fmt, (SDL_wcslen(fmt) + 1) * sizeof(wchar_t)); + if (!fmt_utf8) { + return -1; + } + } + + char tinybuf[64]; // for really small strings, calculate it once. + + // generate the text to find the final text length + va_list aq; + va_copy(aq, ap); + const int utf8len = SDL_vsnprintf(tinybuf, sizeof (tinybuf), fmt_utf8, aq); + va_end(aq); + + if (utf8len < 0) { + SDL_free(fmt_utf8); + return -1; + } + + bool isstack = false; + char *smallbuf = NULL; + char *utf8buf; + int result; + + if (utf8len < sizeof (tinybuf)) { // whole thing fit in the stack buffer, just use that copy. + utf8buf = tinybuf; + } else { // didn't fit in the stack buffer, allocate the needed space and run it again. + utf8buf = smallbuf = SDL_small_alloc(char, utf8len + 1, &isstack); + if (!smallbuf) { + SDL_free(fmt_utf8); + return -1; // oh well. + } + const int utf8len2 = SDL_vsnprintf(smallbuf, utf8len + 1, fmt_utf8, ap); + if (utf8len2 > utf8len) { + SDL_free(fmt_utf8); + return SDL_SetError("Formatted output changed between two runs"); // race condition on the parameters, and we no longer have room...yikes. + } + } + + SDL_free(fmt_utf8); + + wchar_t *wbuf = (wchar_t *)SDL_iconv_string("WCHAR_T", "UTF-8", utf8buf, utf8len + 1); + if (wbuf) { + if (text) { + SDL_wcslcpy(text, wbuf, maxlen); + } + result = (int)SDL_wcslen(wbuf); + SDL_free(wbuf); + } else { + result = -1; + } + + if (smallbuf != NULL) { + SDL_small_free(smallbuf, isstack); + } + + return result; +} + +int SDL_asprintf(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + int result; + + va_start(ap, fmt); + result = SDL_vasprintf(strp, fmt, ap); + va_end(ap); + + return result; +} + +int SDL_vasprintf(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) +{ + int result; + int size = 100; // Guess we need no more than 100 bytes + char *p, *np; + va_list aq; + + *strp = NULL; + + p = (char *)SDL_malloc(size); + if (!p) { + return -1; + } + + while (1) { + // Try to print in the allocated space + va_copy(aq, ap); + result = SDL_vsnprintf(p, size, fmt, aq); + va_end(aq); + + // Check error code + if (result < 0) { + SDL_free(p); + return result; + } + + // If that worked, return the string + if (result < size) { + *strp = p; + return result; + } + + // Else try again with more space + size = result + 1; // Precisely what is needed + + np = (char *)SDL_realloc(p, size); + if (!np) { + SDL_free(p); + return -1; + } else { + p = np; + } + } +} + +char * SDL_strpbrk(const char *str, const char *breakset) +{ +#ifdef HAVE_STRPBRK + return strpbrk(str, breakset); +#else + + for (; *str; str++) { + const char *b; + + for (b = breakset; *b; b++) { + if (*str == *b) { + return (char *) str; + } + } + } + return NULL; +#endif +} diff --git a/thirdparty/sdl/stdlib/SDL_strtokr.c b/thirdparty/sdl/stdlib/SDL_strtokr.c new file mode 100644 index 00000000000..e60080895d3 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_strtokr.c @@ -0,0 +1,95 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + + +char *SDL_strtok_r(char *s1, const char *s2, char **ptr) +{ +#ifdef HAVE_STRTOK_R + return strtok_r(s1, s2, ptr); + +#else /* SDL implementation */ +/* + * Adapted from _PDCLIB_strtok() of PDClib library at + * https://github.com/DevSolar/pdclib.git + * + * The code was under CC0 license: + * https://creativecommons.org/publicdomain/zero/1.0/legalcode : + * + * No Copyright + * + * The person who associated a work with this deed has dedicated the + * work to the public domain by waiving all of his or her rights to + * the work worldwide under copyright law, including all related and + * neighboring rights, to the extent allowed by law. + * + * You can copy, modify, distribute and perform the work, even for + * commercial purposes, all without asking permission. See Other + * Information below. + */ + const char *p = s2; + + if (!s2 || !ptr || (!s1 && !*ptr)) return NULL; + + if (s1 != NULL) { /* new string */ + *ptr = s1; + } else { /* old string continued */ + if (*ptr == NULL) { + /* No old string, no new string, nothing to do */ + return NULL; + } + s1 = *ptr; + } + + /* skip leading s2 characters */ + while (*p && *s1) { + if (*s1 == *p) { + /* found separator; skip and start over */ + ++s1; + p = s2; + continue; + } + ++p; + } + + if (! *s1) { /* no more to parse */ + *ptr = s1; + return NULL; + } + + /* skipping non-s2 characters */ + *ptr = s1; + while (**ptr) { + p = s2; + while (*p) { + if (**ptr == *p++) { + /* found separator; overwrite with '\0', position *ptr, return */ + *((*ptr)++) = '\0'; + return s1; + } + } + ++(*ptr); + } + + /* parsed to end of string */ + return s1; +#endif +} diff --git a/thirdparty/sdl/stdlib/SDL_sysstdlib.h b/thirdparty/sdl/stdlib/SDL_sysstdlib.h new file mode 100644 index 00000000000..7d43ab0d425 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_sysstdlib.h @@ -0,0 +1,32 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_sysstdlib_h_ +#define SDL_sysstdlib_h_ + +// most things you might need internally in here are public APIs, this is +// just a few special pieces right now. + +// this expects `from` to be a Unicode codepoint, and `to` to point to AT LEAST THREE Uint32s. +int SDL_CaseFoldUnicode(Uint32 from, Uint32 *to); + +#endif + diff --git a/thirdparty/sdl/stdlib/SDL_vacopy.h b/thirdparty/sdl/stdlib/SDL_vacopy.h new file mode 100644 index 00000000000..fee560e4684 --- /dev/null +++ b/thirdparty/sdl/stdlib/SDL_vacopy.h @@ -0,0 +1,30 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +// Do our best to make sure va_copy is working +#if defined(_MSC_VER) && _MSC_VER <= 1800 +// Visual Studio 2013 tries to link with _vacopy in the C runtime. Newer versions do an inline assignment +#undef va_copy +#define va_copy(dst, src) dst = src + +#elif defined(__GNUC__) && (__GNUC__ < 3) +#define va_copy(dst, src) __va_copy(dst, src) +#endif diff --git a/thirdparty/sdl/thread/SDL_systhread.h b/thirdparty/sdl/thread/SDL_systhread.h new file mode 100644 index 00000000000..596b248b650 --- /dev/null +++ b/thirdparty/sdl/thread/SDL_systhread.h @@ -0,0 +1,77 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// These are functions that need to be implemented by a port of SDL + +#ifndef SDL_systhread_h_ +#define SDL_systhread_h_ + +#include "SDL_thread_c.h" + +// Set up for C function definitions, even when using C++ +#ifdef __cplusplus +extern "C" { +#endif + +/* This function creates a thread, passing args to SDL_RunThread(), + saves a system-dependent thread id in thread->id, and returns 0 + on success. +*/ +extern bool SDL_SYS_CreateThread(SDL_Thread *thread, + SDL_FunctionPointer pfnBeginThread, + SDL_FunctionPointer pfnEndThread); + +// This function does any necessary setup in the child thread +extern void SDL_SYS_SetupThread(const char *name); + +// This function sets the current thread priority +extern bool SDL_SYS_SetThreadPriority(SDL_ThreadPriority priority); + +/* This function waits for the thread to finish and frees any data + allocated by SDL_SYS_CreateThread() + */ +extern void SDL_SYS_WaitThread(SDL_Thread *thread); + +// Mark thread as cleaned up as soon as it exits, without joining. +extern void SDL_SYS_DetachThread(SDL_Thread *thread); + +// Initialize the global TLS data +extern void SDL_SYS_InitTLSData(void); + +// Get the thread local storage for this thread +extern SDL_TLSData *SDL_SYS_GetTLSData(void); + +// Set the thread local storage for this thread +extern bool SDL_SYS_SetTLSData(SDL_TLSData *data); + +// Quit the global TLS data +extern void SDL_SYS_QuitTLSData(void); + +// A helper function for setting up a thread with a stack size. +extern SDL_Thread *SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, size_t stacksize, void *data); + +// Ends C function definitions when using C++ +#ifdef __cplusplus +} +#endif + +#endif // SDL_systhread_h_ diff --git a/thirdparty/sdl/thread/SDL_thread.c b/thirdparty/sdl/thread/SDL_thread.c new file mode 100644 index 00000000000..99cb9dd7f15 --- /dev/null +++ b/thirdparty/sdl/thread/SDL_thread.c @@ -0,0 +1,584 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// System independent thread management routines for SDL + +#include "SDL_thread_c.h" +#include "SDL_systhread.h" +#include "../SDL_error_c.h" + +// The storage is local to the thread, but the IDs are global for the process + +static SDL_AtomicInt SDL_tls_allocated; +static SDL_AtomicInt SDL_tls_id; + +void SDL_InitTLSData(void) +{ + SDL_SYS_InitTLSData(); +} + +void *SDL_GetTLS(SDL_TLSID *id) +{ + SDL_TLSData *storage; + int storage_index; + + if (id == NULL) { + SDL_InvalidParamError("id"); + return NULL; + } + + storage_index = SDL_GetAtomicInt(id) - 1; + storage = SDL_SYS_GetTLSData(); + if (!storage || storage_index < 0 || storage_index >= storage->limit) { + return NULL; + } + return storage->array[storage_index].data; +} + +bool SDL_SetTLS(SDL_TLSID *id, const void *value, SDL_TLSDestructorCallback destructor) +{ + SDL_TLSData *storage; + int storage_index; + + if (id == NULL) { + return SDL_InvalidParamError("id"); + } + + /* Make sure TLS is initialized. + * There's a race condition here if you are calling this from non-SDL threads + * and haven't called SDL_Init() on your main thread, but such is life. + */ + SDL_InitTLSData(); + + // Get the storage index associated with the ID in a thread-safe way + storage_index = SDL_GetAtomicInt(id) - 1; + if (storage_index < 0) { + int new_id = (SDL_AtomicIncRef(&SDL_tls_id) + 1); + + SDL_CompareAndSwapAtomicInt(id, 0, new_id); + + /* If there was a race condition we'll have wasted an ID, but every thread + * will have the same storage index for this id. + */ + storage_index = SDL_GetAtomicInt(id) - 1; + } + + // Get the storage for the current thread + storage = SDL_SYS_GetTLSData(); + if (!storage || storage_index >= storage->limit) { + unsigned int i, oldlimit, newlimit; + SDL_TLSData *new_storage; + + oldlimit = storage ? storage->limit : 0; + newlimit = (storage_index + TLS_ALLOC_CHUNKSIZE); + new_storage = (SDL_TLSData *)SDL_realloc(storage, sizeof(*storage) + (newlimit - 1) * sizeof(storage->array[0])); + if (!new_storage) { + return false; + } + storage = new_storage; + storage->limit = newlimit; + for (i = oldlimit; i < newlimit; ++i) { + storage->array[i].data = NULL; + storage->array[i].destructor = NULL; + } + if (!SDL_SYS_SetTLSData(storage)) { + SDL_free(storage); + return false; + } + SDL_AtomicIncRef(&SDL_tls_allocated); + } + + storage->array[storage_index].data = SDL_const_cast(void *, value); + storage->array[storage_index].destructor = destructor; + return true; +} + +void SDL_CleanupTLS(void) +{ + SDL_TLSData *storage; + + // Cleanup the storage for the current thread + storage = SDL_SYS_GetTLSData(); + if (storage) { + int i; + for (i = 0; i < storage->limit; ++i) { + if (storage->array[i].destructor) { + storage->array[i].destructor(storage->array[i].data); + } + } + SDL_SYS_SetTLSData(NULL); + SDL_free(storage); + (void)SDL_AtomicDecRef(&SDL_tls_allocated); + } +} + +void SDL_QuitTLSData(void) +{ + SDL_CleanupTLS(); + + if (SDL_GetAtomicInt(&SDL_tls_allocated) == 0) { + SDL_SYS_QuitTLSData(); + } else { + // Some thread hasn't called SDL_CleanupTLS() + } +} + +/* This is a generic implementation of thread-local storage which doesn't + require additional OS support. + + It is not especially efficient and doesn't clean up thread-local storage + as threads exit. If there is a real OS that doesn't support thread-local + storage this implementation should be improved to be production quality. +*/ + +typedef struct SDL_TLSEntry +{ + SDL_ThreadID thread; + SDL_TLSData *storage; + struct SDL_TLSEntry *next; +} SDL_TLSEntry; + +static SDL_Mutex *SDL_generic_TLS_mutex; +static SDL_TLSEntry *SDL_generic_TLS; + +void SDL_Generic_InitTLSData(void) +{ + if (!SDL_generic_TLS_mutex) { + SDL_generic_TLS_mutex = SDL_CreateMutex(); + } +} + +SDL_TLSData *SDL_Generic_GetTLSData(void) +{ + SDL_ThreadID thread = SDL_GetCurrentThreadID(); + SDL_TLSEntry *entry; + SDL_TLSData *storage = NULL; + + SDL_LockMutex(SDL_generic_TLS_mutex); + for (entry = SDL_generic_TLS; entry; entry = entry->next) { + if (entry->thread == thread) { + storage = entry->storage; + break; + } + } + SDL_UnlockMutex(SDL_generic_TLS_mutex); + + return storage; +} + +bool SDL_Generic_SetTLSData(SDL_TLSData *data) +{ + SDL_ThreadID thread = SDL_GetCurrentThreadID(); + SDL_TLSEntry *prev, *entry; + bool result = true; + + SDL_LockMutex(SDL_generic_TLS_mutex); + prev = NULL; + for (entry = SDL_generic_TLS; entry; entry = entry->next) { + if (entry->thread == thread) { + if (data) { + entry->storage = data; + } else { + if (prev) { + prev->next = entry->next; + } else { + SDL_generic_TLS = entry->next; + } + SDL_free(entry); + } + break; + } + prev = entry; + } + if (!entry && data) { + entry = (SDL_TLSEntry *)SDL_malloc(sizeof(*entry)); + if (entry) { + entry->thread = thread; + entry->storage = data; + entry->next = SDL_generic_TLS; + SDL_generic_TLS = entry; + } else { + result = false; + } + } + SDL_UnlockMutex(SDL_generic_TLS_mutex); + + return result; +} + +void SDL_Generic_QuitTLSData(void) +{ + SDL_TLSEntry *entry; + + // This should have been cleaned up by the time we get here + SDL_assert(!SDL_generic_TLS); + if (SDL_generic_TLS) { + SDL_LockMutex(SDL_generic_TLS_mutex); + for (entry = SDL_generic_TLS; entry; ) { + SDL_TLSEntry *next = entry->next; + SDL_free(entry->storage); + SDL_free(entry); + entry = next; + } + SDL_generic_TLS = NULL; + SDL_UnlockMutex(SDL_generic_TLS_mutex); + } + + if (SDL_generic_TLS_mutex) { + SDL_DestroyMutex(SDL_generic_TLS_mutex); + SDL_generic_TLS_mutex = NULL; + } +} + +// Non-thread-safe global error variable +static SDL_error *SDL_GetStaticErrBuf(void) +{ + static SDL_error SDL_global_error; + static char SDL_global_error_str[128]; + SDL_global_error.str = SDL_global_error_str; + SDL_global_error.len = sizeof(SDL_global_error_str); + return &SDL_global_error; +} + +#ifndef SDL_THREADS_DISABLED +static void SDLCALL SDL_FreeErrBuf(void *data) +{ + SDL_error *errbuf = (SDL_error *)data; + + if (errbuf->str) { + errbuf->free_func(errbuf->str); + } + errbuf->free_func(errbuf); +} +#endif + +// Routine to get the thread-specific error variable +SDL_error *SDL_GetErrBuf(bool create) +{ +#ifdef SDL_THREADS_DISABLED + return SDL_GetStaticErrBuf(); +#else + static SDL_TLSID tls_errbuf; + SDL_error *errbuf; + + errbuf = (SDL_error *)SDL_GetTLS(&tls_errbuf); + if (!errbuf) { + if (!create) { + return NULL; + } + + /* Get the original memory functions for this allocation because the lifetime + * of the error buffer may span calls to SDL_SetMemoryFunctions() by the app + */ + SDL_realloc_func realloc_func; + SDL_free_func free_func; + SDL_GetOriginalMemoryFunctions(NULL, NULL, &realloc_func, &free_func); + + errbuf = (SDL_error *)realloc_func(NULL, sizeof(*errbuf)); + if (!errbuf) { + return SDL_GetStaticErrBuf(); + } + SDL_zerop(errbuf); + errbuf->realloc_func = realloc_func; + errbuf->free_func = free_func; + SDL_SetTLS(&tls_errbuf, errbuf, SDL_FreeErrBuf); + } + return errbuf; +#endif // SDL_THREADS_DISABLED +} + +static bool ThreadValid(SDL_Thread *thread) +{ + return SDL_ObjectValid(thread, SDL_OBJECT_TYPE_THREAD); +} + +void SDL_RunThread(SDL_Thread *thread) +{ + void *userdata = thread->userdata; + int(SDLCALL *userfunc)(void *) = thread->userfunc; + + int *statusloc = &thread->status; + + // Perform any system-dependent setup - this function may not fail + SDL_SYS_SetupThread(thread->name); + + // Get the thread id + thread->threadid = SDL_GetCurrentThreadID(); + + // Run the function + *statusloc = userfunc(userdata); + + // Clean up thread-local storage + SDL_CleanupTLS(); + + // Mark us as ready to be joined (or detached) + if (!SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_COMPLETE)) { + // Clean up if something already detached us. + if (SDL_GetThreadState(thread) == SDL_THREAD_DETACHED) { + SDL_free(thread->name); // Can't free later, we've already cleaned up TLS + SDL_free(thread); + } + } +} + +SDL_Thread *SDL_CreateThreadWithPropertiesRuntime(SDL_PropertiesID props, + SDL_FunctionPointer pfnBeginThread, + SDL_FunctionPointer pfnEndThread) +{ + // rather than check this in every backend, just make sure it's correct upfront. Only allow non-NULL if Windows, or Microsoft GDK. + #if !defined(SDL_PLATFORM_WINDOWS) + if (pfnBeginThread || pfnEndThread) { + SDL_SetError("_beginthreadex/_endthreadex not supported on this platform"); + return NULL; + } + #endif + + SDL_ThreadFunction fn = (SDL_ThreadFunction) SDL_GetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, NULL); + const char *name = SDL_GetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, NULL); + const size_t stacksize = (size_t) SDL_GetNumberProperty(props, SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER, 0); + void *userdata = SDL_GetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, NULL); + + if (!fn) { + SDL_SetError("Thread entry function is NULL"); + return NULL; + } + + SDL_InitMainThread(); + + SDL_Thread *thread = (SDL_Thread *)SDL_calloc(1, sizeof(*thread)); + if (!thread) { + return NULL; + } + thread->status = -1; + SDL_SetAtomicInt(&thread->state, SDL_THREAD_ALIVE); + + // Set up the arguments for the thread + if (name) { + thread->name = SDL_strdup(name); + if (!thread->name) { + SDL_free(thread); + return NULL; + } + } + + thread->userfunc = fn; + thread->userdata = userdata; + thread->stacksize = stacksize; + + SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, true); + + // Create the thread and go! + if (!SDL_SYS_CreateThread(thread, pfnBeginThread, pfnEndThread)) { + // Oops, failed. Gotta free everything + SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false); + SDL_free(thread->name); + SDL_free(thread); + thread = NULL; + } + + // Everything is running now + return thread; +} + +SDL_Thread *SDL_CreateThreadRuntime(SDL_ThreadFunction fn, + const char *name, void *userdata, + SDL_FunctionPointer pfnBeginThread, + SDL_FunctionPointer pfnEndThread) +{ + const SDL_PropertiesID props = SDL_CreateProperties(); + SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, (void *) fn); + SDL_SetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, name); + SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, userdata); + SDL_Thread *thread = SDL_CreateThreadWithPropertiesRuntime(props, pfnBeginThread, pfnEndThread); + SDL_DestroyProperties(props); + return thread; +} + +// internal helper function, not in the public API. +SDL_Thread *SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, size_t stacksize, void *userdata) +{ + const SDL_PropertiesID props = SDL_CreateProperties(); + SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, (void *) fn); + SDL_SetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, name); + SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, userdata); + SDL_SetNumberProperty(props, SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER, (Sint64) stacksize); + SDL_Thread *thread = SDL_CreateThreadWithProperties(props); + SDL_DestroyProperties(props); + return thread; +} + +SDL_ThreadID SDL_GetThreadID(SDL_Thread *thread) +{ + SDL_ThreadID id = 0; + + if (thread) { + if (ThreadValid(thread)) { + id = thread->threadid; + } + } else { + id = SDL_GetCurrentThreadID(); + } + return id; +} + +const char *SDL_GetThreadName(SDL_Thread *thread) +{ + if (ThreadValid(thread)) { + return SDL_GetPersistentString(thread->name); + } else { + return NULL; + } +} + +bool SDL_SetCurrentThreadPriority(SDL_ThreadPriority priority) +{ + return SDL_SYS_SetThreadPriority(priority); +} + +void SDL_WaitThread(SDL_Thread *thread, int *status) +{ + if (!ThreadValid(thread)) { + if (status) { + *status = -1; + } + return; + } + + SDL_SYS_WaitThread(thread); + if (status) { + *status = thread->status; + } + SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false); + SDL_free(thread->name); + SDL_free(thread); +} + +SDL_ThreadState SDL_GetThreadState(SDL_Thread *thread) +{ + if (!ThreadValid(thread)) { + return SDL_THREAD_UNKNOWN; + } + + return (SDL_ThreadState)SDL_GetAtomicInt(&thread->state); +} + +void SDL_DetachThread(SDL_Thread *thread) +{ + if (!ThreadValid(thread)) { + return; + } + + // The thread may vanish at any time, it's no longer valid + SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false); + + // Grab dibs if the state is alive+joinable. + if (SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_DETACHED)) { + SDL_SYS_DetachThread(thread); + } else { + // all other states are pretty final, see where we landed. + SDL_ThreadState thread_state = SDL_GetThreadState(thread); + if (thread_state == SDL_THREAD_DETACHED) { + return; // already detached (you shouldn't call this twice!) + } else if (thread_state == SDL_THREAD_COMPLETE) { + SDL_WaitThread(thread, NULL); // already done, clean it up. + } + } +} + +void SDL_WaitSemaphore(SDL_Semaphore *sem) +{ + SDL_WaitSemaphoreTimeoutNS(sem, -1); +} + +bool SDL_TryWaitSemaphore(SDL_Semaphore *sem) +{ + return SDL_WaitSemaphoreTimeoutNS(sem, 0); +} + +bool SDL_WaitSemaphoreTimeout(SDL_Semaphore *sem, Sint32 timeoutMS) +{ + Sint64 timeoutNS; + + if (timeoutMS >= 0) { + timeoutNS = SDL_MS_TO_NS(timeoutMS); + } else { + timeoutNS = -1; + } + return SDL_WaitSemaphoreTimeoutNS(sem, timeoutNS); +} + +void SDL_WaitCondition(SDL_Condition *cond, SDL_Mutex *mutex) +{ + SDL_WaitConditionTimeoutNS(cond, mutex, -1); +} + +bool SDL_WaitConditionTimeout(SDL_Condition *cond, SDL_Mutex *mutex, Sint32 timeoutMS) +{ + Sint64 timeoutNS; + + if (timeoutMS >= 0) { + timeoutNS = SDL_MS_TO_NS(timeoutMS); + } else { + timeoutNS = -1; + } + return SDL_WaitConditionTimeoutNS(cond, mutex, timeoutNS); +} + +bool SDL_ShouldInit(SDL_InitState *state) +{ + while (SDL_GetAtomicInt(&state->status) != SDL_INIT_STATUS_INITIALIZED) { + if (SDL_CompareAndSwapAtomicInt(&state->status, SDL_INIT_STATUS_UNINITIALIZED, SDL_INIT_STATUS_INITIALIZING)) { + state->thread = SDL_GetCurrentThreadID(); + return true; + } + + // Wait for the other thread to complete transition + SDL_Delay(1); + } + return false; +} + +bool SDL_ShouldQuit(SDL_InitState *state) +{ + while (SDL_GetAtomicInt(&state->status) != SDL_INIT_STATUS_UNINITIALIZED) { + if (SDL_CompareAndSwapAtomicInt(&state->status, SDL_INIT_STATUS_INITIALIZED, SDL_INIT_STATUS_UNINITIALIZING)) { + state->thread = SDL_GetCurrentThreadID(); + return true; + } + + // Wait for the other thread to complete transition + SDL_Delay(1); + } + return false; +} + +void SDL_SetInitialized(SDL_InitState *state, bool initialized) +{ + SDL_assert(state->thread == SDL_GetCurrentThreadID()); + + if (initialized) { + SDL_SetAtomicInt(&state->status, SDL_INIT_STATUS_INITIALIZED); + } else { + SDL_SetAtomicInt(&state->status, SDL_INIT_STATUS_UNINITIALIZED); + } +} + diff --git a/thirdparty/sdl/thread/SDL_thread_c.h b/thirdparty/sdl/thread/SDL_thread_c.h new file mode 100644 index 00000000000..3368016a6c9 --- /dev/null +++ b/thirdparty/sdl/thread/SDL_thread_c.h @@ -0,0 +1,92 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_thread_c_h_ +#define SDL_thread_c_h_ + +// Need the definitions of SYS_ThreadHandle +#ifdef SDL_THREADS_DISABLED +#include "generic/SDL_systhread_c.h" +#elif defined(SDL_THREAD_PTHREAD) +#include "pthread/SDL_systhread_c.h" +#elif defined(SDL_THREAD_WINDOWS) +#include "windows/SDL_systhread_c.h" +#elif defined(SDL_THREAD_PS2) +#include "ps2/SDL_systhread_c.h" +#elif defined(SDL_THREAD_PSP) +#include "psp/SDL_systhread_c.h" +#elif defined(SDL_THREAD_VITA) +#include "vita/SDL_systhread_c.h" +#elif defined(SDL_THREAD_N3DS) +#include "n3ds/SDL_systhread_c.h" +#else +#error Need thread implementation for this platform +#include "generic/SDL_systhread_c.h" +#endif +#include "../SDL_error_c.h" + +// This is the system-independent thread info structure +struct SDL_Thread +{ + SDL_ThreadID threadid; + SYS_ThreadHandle handle; + int status; + SDL_AtomicInt state; /* SDL_ThreadState */ + SDL_error errbuf; + char *name; + size_t stacksize; // 0 for default, >0 for user-specified stack size. + int(SDLCALL *userfunc)(void *); + void *userdata; + void *data; + SDL_FunctionPointer endfunc; // only used on some platforms. +}; + +// This is the function called to run a thread +extern void SDL_RunThread(SDL_Thread *thread); + +// This is the system-independent thread local storage structure +typedef struct +{ + int limit; + struct + { + void *data; + void(SDLCALL *destructor)(void *); + } array[1]; +} SDL_TLSData; + +// This is how many TLS entries we allocate at once +#define TLS_ALLOC_CHUNKSIZE 4 + +extern void SDL_InitTLSData(void); +extern void SDL_QuitTLSData(void); + +/* Generic TLS support. + This is only intended as a fallback if getting real thread-local + storage fails or isn't supported on this platform. + */ +extern void SDL_Generic_InitTLSData(void); +extern SDL_TLSData *SDL_Generic_GetTLSData(void); +extern bool SDL_Generic_SetTLSData(SDL_TLSData *data); +extern void SDL_Generic_QuitTLSData(void); + +#endif // SDL_thread_c_h_ diff --git a/thirdparty/sdl/thread/generic/SDL_syscond.c b/thirdparty/sdl/thread/generic/SDL_syscond.c new file mode 100644 index 00000000000..5fdfe842e39 --- /dev/null +++ b/thirdparty/sdl/thread/generic/SDL_syscond.c @@ -0,0 +1,216 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// An implementation of condition variables using semaphores and mutexes +/* + This implementation borrows heavily from the BeOS condition variable + implementation, written by Christopher Tate and Owen Smith. Thanks! + */ + +#include "../generic/SDL_syscond_c.h" + +/* If two implementations are to be compiled into SDL (the active one + * will be chosen at runtime), the function names need to be + * suffixed + */ +#ifndef SDL_THREAD_GENERIC_COND_SUFFIX +#define SDL_CreateCondition_generic SDL_CreateCondition +#define SDL_DestroyCondition_generic SDL_DestroyCondition +#define SDL_SignalCondition_generic SDL_SignalCondition +#define SDL_BroadcastCondition_generic SDL_BroadcastCondition +#endif + +typedef struct SDL_cond_generic +{ + SDL_Semaphore *sem; + SDL_Semaphore *handshake_sem; + SDL_Semaphore *signal_sem; + int num_waiting; + int num_signals; +} SDL_cond_generic; + +// Create a condition variable +SDL_Condition *SDL_CreateCondition_generic(void) +{ + SDL_cond_generic *cond = (SDL_cond_generic *)SDL_calloc(1, sizeof(*cond)); + +#ifndef SDL_THREADS_DISABLED + if (cond) { + cond->sem = SDL_CreateSemaphore(0); + cond->handshake_sem = SDL_CreateSemaphore(0); + cond->signal_sem = SDL_CreateSemaphore(1); + if (!cond->sem || !cond->handshake_sem || !cond->signal_sem) { + SDL_DestroyCondition_generic((SDL_Condition *)cond); + cond = NULL; + } + } +#endif + + return (SDL_Condition *)cond; +} + +// Destroy a condition variable +void SDL_DestroyCondition_generic(SDL_Condition *_cond) +{ + SDL_cond_generic *cond = (SDL_cond_generic *)_cond; + if (cond) { + if (cond->sem) { + SDL_DestroySemaphore(cond->sem); + } + if (cond->handshake_sem) { + SDL_DestroySemaphore(cond->handshake_sem); + } + if (cond->signal_sem) { + SDL_DestroySemaphore(cond->signal_sem); + } + SDL_free(cond); + } +} + +// Restart one of the threads that are waiting on the condition variable +void SDL_SignalCondition_generic(SDL_Condition *_cond) +{ + SDL_cond_generic *cond = (SDL_cond_generic *)_cond; + if (!cond) { + return; + } + +#ifndef SDL_THREADS_DISABLED + /* If there are waiting threads not already signalled, then + signal the condition and wait for the thread to respond. + */ + SDL_WaitSemaphore(cond->signal_sem); + if (cond->num_waiting > cond->num_signals) { + cond->num_signals++; + SDL_SignalSemaphore(cond->sem); + SDL_SignalSemaphore(cond->signal_sem); + SDL_WaitSemaphore(cond->handshake_sem); + } else { + SDL_SignalSemaphore(cond->signal_sem); + } +#endif +} + +// Restart all threads that are waiting on the condition variable +void SDL_BroadcastCondition_generic(SDL_Condition *_cond) +{ + SDL_cond_generic *cond = (SDL_cond_generic *)_cond; + if (!cond) { + return; + } + +#ifndef SDL_THREADS_DISABLED + /* If there are waiting threads not already signalled, then + signal the condition and wait for the thread to respond. + */ + SDL_WaitSemaphore(cond->signal_sem); + if (cond->num_waiting > cond->num_signals) { + const int num_waiting = (cond->num_waiting - cond->num_signals); + cond->num_signals = cond->num_waiting; + for (int i = 0; i < num_waiting; i++) { + SDL_SignalSemaphore(cond->sem); + } + /* Now all released threads are blocked here, waiting for us. + Collect them all (and win fabulous prizes!) :-) + */ + SDL_SignalSemaphore(cond->signal_sem); + for (int i = 0; i < num_waiting; i++) { + SDL_WaitSemaphore(cond->handshake_sem); + } + } else { + SDL_SignalSemaphore(cond->signal_sem); + } +#endif +} + +/* Wait on the condition variable for at most 'timeoutNS' nanoseconds. + The mutex must be locked before entering this function! + The mutex is unlocked during the wait, and locked again after the wait. + +Typical use: + +Thread A: + SDL_LockMutex(lock); + while ( ! condition ) { + SDL_WaitCondition(cond, lock); + } + SDL_UnlockMutex(lock); + +Thread B: + SDL_LockMutex(lock); + ... + condition = true; + ... + SDL_SignalCondition(cond); + SDL_UnlockMutex(lock); + */ +bool SDL_WaitConditionTimeoutNS_generic(SDL_Condition *_cond, SDL_Mutex *mutex, Sint64 timeoutNS) +{ + SDL_cond_generic *cond = (SDL_cond_generic *)_cond; + bool result = true; + + if (!cond || !mutex) { + return true; + } + +#ifndef SDL_THREADS_DISABLED + /* Obtain the protection mutex, and increment the number of waiters. + This allows the signal mechanism to only perform a signal if there + are waiting threads. + */ + SDL_WaitSemaphore(cond->signal_sem); + cond->num_waiting++; + SDL_SignalSemaphore(cond->signal_sem); + + // Unlock the mutex, as is required by condition variable semantics + SDL_UnlockMutex(mutex); + + // Wait for a signal + result = SDL_WaitSemaphoreTimeoutNS(cond->sem, timeoutNS); + + /* Let the signaler know we have completed the wait, otherwise + the signaler can race ahead and get the condition semaphore + if we are stopped between the mutex unlock and semaphore wait, + giving a deadlock. See the following URL for details: + http://web.archive.org/web/20010914175514/http://www-classic.be.com/aboutbe/benewsletter/volume_III/Issue40.html#Workshop + */ + SDL_WaitSemaphore(cond->signal_sem); + if (cond->num_signals > 0) { + SDL_SignalSemaphore(cond->handshake_sem); + cond->num_signals--; + } + cond->num_waiting--; + SDL_SignalSemaphore(cond->signal_sem); + + // Lock the mutex, as is required by condition variable semantics + SDL_LockMutex(mutex); +#endif + + return result; +} + +#ifndef SDL_THREAD_GENERIC_COND_SUFFIX +bool SDL_WaitConditionTimeoutNS(SDL_Condition *cond, SDL_Mutex *mutex, Sint64 timeoutNS) +{ + return SDL_WaitConditionTimeoutNS_generic(cond, mutex, timeoutNS); +} +#endif diff --git a/thirdparty/sdl/thread/generic/SDL_syscond_c.h b/thirdparty/sdl/thread/generic/SDL_syscond_c.h new file mode 100644 index 00000000000..253c3945bf2 --- /dev/null +++ b/thirdparty/sdl/thread/generic/SDL_syscond_c.h @@ -0,0 +1,36 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_syscond_generic_h_ +#define SDL_syscond_generic_h_ + +#ifdef SDL_THREAD_GENERIC_COND_SUFFIX + +SDL_Condition *SDL_CreateCondition_generic(void); +void SDL_DestroyCondition_generic(SDL_Condition *cond); +void SDL_SignalCondition_generic(SDL_Condition *cond); +void SDL_BroadcastCondition_generic(SDL_Condition *cond); +bool SDL_WaitConditionTimeoutNS_generic(SDL_Condition *cond, SDL_Mutex *mutex, Sint64 timeoutNS); + +#endif // SDL_THREAD_GENERIC_COND_SUFFIX + +#endif // SDL_syscond_generic_h_ diff --git a/thirdparty/sdl/thread/generic/SDL_sysrwlock.c b/thirdparty/sdl/thread/generic/SDL_sysrwlock.c new file mode 100644 index 00000000000..24caf51b2f6 --- /dev/null +++ b/thirdparty/sdl/thread/generic/SDL_sysrwlock.c @@ -0,0 +1,194 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// An implementation of rwlocks using mutexes, condition variables, and atomics. + +#include "SDL_systhread_c.h" + +#include "../generic/SDL_sysrwlock_c.h" + +/* If two implementations are to be compiled into SDL (the active one + * will be chosen at runtime), the function names need to be + * suffixed + */ +// !!! FIXME: this is quite a tapdance with macros and the build system, maybe we can simplify how we do this. --ryan. +#ifndef SDL_THREAD_GENERIC_RWLOCK_SUFFIX +#define SDL_CreateRWLock_generic SDL_CreateRWLock +#define SDL_DestroyRWLock_generic SDL_DestroyRWLock +#define SDL_LockRWLockForReading_generic SDL_LockRWLockForReading +#define SDL_LockRWLockForWriting_generic SDL_LockRWLockForWriting +#define SDL_UnlockRWLock_generic SDL_UnlockRWLock +#endif + +struct SDL_RWLock +{ +#ifdef SDL_THREADS_DISABLED + int unused; +#else + SDL_Mutex *lock; + SDL_Condition *condition; + SDL_ThreadID writer_thread; + SDL_AtomicInt reader_count; + SDL_AtomicInt writer_count; +#endif +}; + +SDL_RWLock *SDL_CreateRWLock_generic(void) +{ + SDL_RWLock *rwlock = (SDL_RWLock *) SDL_calloc(1, sizeof (*rwlock)); + + if (!rwlock) { + return NULL; + } + +#ifndef SDL_THREADS_DISABLED + rwlock->lock = SDL_CreateMutex(); + if (!rwlock->lock) { + SDL_free(rwlock); + return NULL; + } + + rwlock->condition = SDL_CreateCondition(); + if (!rwlock->condition) { + SDL_DestroyMutex(rwlock->lock); + SDL_free(rwlock); + return NULL; + } + + SDL_SetAtomicInt(&rwlock->reader_count, 0); + SDL_SetAtomicInt(&rwlock->writer_count, 0); +#endif + + return rwlock; +} + +void SDL_DestroyRWLock_generic(SDL_RWLock *rwlock) +{ + if (rwlock) { +#ifndef SDL_THREADS_DISABLED + SDL_DestroyMutex(rwlock->lock); + SDL_DestroyCondition(rwlock->condition); +#endif + SDL_free(rwlock); + } +} + +void SDL_LockRWLockForReading_generic(SDL_RWLock *rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ +#ifndef SDL_THREADS_DISABLED + if (rwlock) { + // !!! FIXME: these don't have to be atomic, we always gate them behind a mutex. + SDL_LockMutex(rwlock->lock); + SDL_assert(SDL_GetAtomicInt(&rwlock->writer_count) == 0); // shouldn't be able to grab lock if there's a writer! + SDL_AddAtomicInt(&rwlock->reader_count, 1); + SDL_UnlockMutex(rwlock->lock); // other readers can attempt to share the lock. + } +#endif +} + +void SDL_LockRWLockForWriting_generic(SDL_RWLock *rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ +#ifndef SDL_THREADS_DISABLED + if (rwlock) { + SDL_LockMutex(rwlock->lock); + while (SDL_GetAtomicInt(&rwlock->reader_count) > 0) { // while something is holding the shared lock, keep waiting. + SDL_WaitCondition(rwlock->condition, rwlock->lock); // release the lock and wait for readers holding the shared lock to release it, regrab the lock. + } + + // we hold the lock! + SDL_AddAtomicInt(&rwlock->writer_count, 1); // we let these be recursive, but the API doesn't require this. It _does_ trust you unlock correctly! + } +#endif +} + +bool SDL_TryLockRWLockForReading_generic(SDL_RWLock *rwlock) +{ +#ifndef SDL_THREADS_DISABLED + if (rwlock) { + if (!SDL_TryLockMutex(rwlock->lock)) { + // !!! FIXME: there is a small window where a reader has to lock the mutex, and if we hit that, we will return SDL_RWLOCK_TIMEDOUT even though we could have shared the lock. + return false; + } + + SDL_assert(SDL_GetAtomicInt(&rwlock->writer_count) == 0); // shouldn't be able to grab lock if there's a writer! + SDL_AddAtomicInt(&rwlock->reader_count, 1); + SDL_UnlockMutex(rwlock->lock); // other readers can attempt to share the lock. + } +#endif + + return true; +} + +#ifndef SDL_THREAD_GENERIC_RWLOCK_SUFFIX +bool SDL_TryLockRWLockForReading(SDL_RWLock *rwlock) +{ + return SDL_TryLockRWLockForReading_generic(rwlock); +} +#endif + +bool SDL_TryLockRWLockForWriting_generic(SDL_RWLock *rwlock) +{ +#ifndef SDL_THREADS_DISABLED + if (rwlock) { + if (!SDL_TryLockMutex(rwlock->lock)) { + return false; + } + + if (SDL_GetAtomicInt(&rwlock->reader_count) > 0) { // a reader is using the shared lock, treat it as unavailable. + SDL_UnlockMutex(rwlock->lock); + return false; + } + + // we hold the lock! + SDL_AddAtomicInt(&rwlock->writer_count, 1); // we let these be recursive, but the API doesn't require this. It _does_ trust you unlock correctly! + } +#endif + + return true; +} + +#ifndef SDL_THREAD_GENERIC_RWLOCK_SUFFIX +bool SDL_TryLockRWLockForWriting(SDL_RWLock *rwlock) +{ + return SDL_TryLockRWLockForWriting_generic(rwlock); +} +#endif + +void SDL_UnlockRWLock_generic(SDL_RWLock *rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ +#ifndef SDL_THREADS_DISABLED + if (rwlock) { + SDL_LockMutex(rwlock->lock); // recursive lock for writers, readers grab lock to make sure things are sane. + + if (SDL_GetAtomicInt(&rwlock->reader_count) > 0) { // we're a reader + SDL_AddAtomicInt(&rwlock->reader_count, -1); + SDL_BroadcastCondition(rwlock->condition); // alert any pending writers to attempt to try to grab the lock again. + } else if (SDL_GetAtomicInt(&rwlock->writer_count) > 0) { // we're a writer + SDL_AddAtomicInt(&rwlock->writer_count, -1); + SDL_UnlockMutex(rwlock->lock); // recursive unlock. + } + + SDL_UnlockMutex(rwlock->lock); + } +#endif +} + diff --git a/thirdparty/sdl/thread/generic/SDL_sysrwlock_c.h b/thirdparty/sdl/thread/generic/SDL_sysrwlock_c.h new file mode 100644 index 00000000000..9589d253127 --- /dev/null +++ b/thirdparty/sdl/thread/generic/SDL_sysrwlock_c.h @@ -0,0 +1,38 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_sysrwlock_c_h_ +#define SDL_sysrwlock_c_h_ + +#ifdef SDL_THREAD_GENERIC_RWLOCK_SUFFIX + +SDL_RWLock *SDL_CreateRWLock_generic(void); +void SDL_DestroyRWLock_generic(SDL_RWLock *rwlock); +void SDL_LockRWLockForReading_generic(SDL_RWLock *rwlock); +void SDL_LockRWLockForWriting_generic(SDL_RWLock *rwlock); +bool SDL_TryLockRWLockForReading_generic(SDL_RWLock *rwlock); +bool SDL_TryLockRWLockForWriting_generic(SDL_RWLock *rwlock); +void SDL_UnlockRWLock_generic(SDL_RWLock *rwlock); + +#endif // SDL_THREAD_GENERIC_RWLOCK_SUFFIX + +#endif // SDL_sysrwlock_c_h_ diff --git a/thirdparty/sdl/thread/generic/SDL_syssem.c b/thirdparty/sdl/thread/generic/SDL_syssem.c new file mode 100644 index 00000000000..dcd6fcc64fe --- /dev/null +++ b/thirdparty/sdl/thread/generic/SDL_syssem.c @@ -0,0 +1,183 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// An implementation of semaphores using mutexes and condition variables + +#include "SDL_systhread_c.h" + +#ifdef SDL_THREADS_DISABLED + +SDL_Semaphore *SDL_CreateSemaphore(Uint32 initial_value) +{ + SDL_SetError("SDL not built with thread support"); + return NULL; +} + +void SDL_DestroySemaphore(SDL_Semaphore *sem) +{ +} + +bool SDL_WaitSemaphoreTimeoutNS(SDL_Semaphore *sem, Sint64 timeoutNS) +{ + return true; +} + +Uint32 SDL_GetSemaphoreValue(SDL_Semaphore *sem) +{ + return 0; +} + +void SDL_SignalSemaphore(SDL_Semaphore *sem) +{ + return; +} + +#else + +struct SDL_Semaphore +{ + Uint32 count; + Uint32 waiters_count; + SDL_Mutex *count_lock; + SDL_Condition *count_nonzero; +}; + +SDL_Semaphore *SDL_CreateSemaphore(Uint32 initial_value) +{ + SDL_Semaphore *sem; + + sem = (SDL_Semaphore *)SDL_malloc(sizeof(*sem)); + if (!sem) { + return NULL; + } + sem->count = initial_value; + sem->waiters_count = 0; + + sem->count_lock = SDL_CreateMutex(); + sem->count_nonzero = SDL_CreateCondition(); + if (!sem->count_lock || !sem->count_nonzero) { + SDL_DestroySemaphore(sem); + return NULL; + } + + return sem; +} + +/* WARNING: + You cannot call this function when another thread is using the semaphore. +*/ +void SDL_DestroySemaphore(SDL_Semaphore *sem) +{ + if (sem) { + sem->count = 0xFFFFFFFF; + while (sem->waiters_count > 0) { + SDL_SignalCondition(sem->count_nonzero); + SDL_Delay(10); + } + SDL_DestroyCondition(sem->count_nonzero); + if (sem->count_lock) { + SDL_LockMutex(sem->count_lock); + SDL_UnlockMutex(sem->count_lock); + SDL_DestroyMutex(sem->count_lock); + } + SDL_free(sem); + } +} + +bool SDL_WaitSemaphoreTimeoutNS(SDL_Semaphore *sem, Sint64 timeoutNS) +{ + bool result = false; + + if (!sem) { + return true; + } + + if (timeoutNS == 0) { + SDL_LockMutex(sem->count_lock); + if (sem->count > 0) { + --sem->count; + result = true; + } + SDL_UnlockMutex(sem->count_lock); + } else if (timeoutNS < 0) { + SDL_LockMutex(sem->count_lock); + ++sem->waiters_count; + while (sem->count == 0) { + SDL_WaitConditionTimeoutNS(sem->count_nonzero, sem->count_lock, -1); + } + --sem->waiters_count; + --sem->count; + result = true; + SDL_UnlockMutex(sem->count_lock); + } else { + Uint64 stop_time = SDL_GetTicksNS() + timeoutNS; + + SDL_LockMutex(sem->count_lock); + ++sem->waiters_count; + while (sem->count == 0) { + Sint64 waitNS = (Sint64)(stop_time - SDL_GetTicksNS()); + if (waitNS > 0) { + SDL_WaitConditionTimeoutNS(sem->count_nonzero, sem->count_lock, waitNS); + } else { + break; + } + } + --sem->waiters_count; + + if (sem->count > 0) { + --sem->count; + result = true; + } + SDL_UnlockMutex(sem->count_lock); + } + + return result; +} + +Uint32 SDL_GetSemaphoreValue(SDL_Semaphore *sem) +{ + Uint32 value; + + value = 0; + if (sem) { + SDL_LockMutex(sem->count_lock); + value = sem->count; + SDL_UnlockMutex(sem->count_lock); + } + return value; +} + +void SDL_SignalSemaphore(SDL_Semaphore *sem) +{ + if (!sem) { + return; + } + + SDL_LockMutex(sem->count_lock); + if (sem->waiters_count > 0) { + SDL_SignalCondition(sem->count_nonzero); + } + ++sem->count; + SDL_UnlockMutex(sem->count_lock); +} + +#endif // SDL_THREADS_DISABLED diff --git a/thirdparty/sdl/thread/generic/SDL_systhread.c b/thirdparty/sdl/thread/generic/SDL_systhread.c new file mode 100644 index 00000000000..ecfa4e13ef3 --- /dev/null +++ b/thirdparty/sdl/thread/generic/SDL_systhread.c @@ -0,0 +1,57 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// Thread management routines for SDL + +#include "../SDL_systhread.h" + +bool SDL_SYS_CreateThread(SDL_Thread *thread, + SDL_FunctionPointer pfnBeginThread, + SDL_FunctionPointer pfnEndThread) +{ + return SDL_SetError("Threads are not supported on this platform"); +} + +void SDL_SYS_SetupThread(const char *name) +{ + return; +} + +SDL_ThreadID SDL_GetCurrentThreadID(void) +{ + return 0; +} + +bool SDL_SYS_SetThreadPriority(SDL_ThreadPriority priority) +{ + return true; +} + +void SDL_SYS_WaitThread(SDL_Thread *thread) +{ + return; +} + +void SDL_SYS_DetachThread(SDL_Thread *thread) +{ + return; +} diff --git a/thirdparty/sdl/thread/generic/SDL_systhread_c.h b/thirdparty/sdl/thread/generic/SDL_systhread_c.h new file mode 100644 index 00000000000..9ba55fd87a9 --- /dev/null +++ b/thirdparty/sdl/thread/generic/SDL_systhread_c.h @@ -0,0 +1,24 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +// Stub until we implement threads on this platform +typedef int SYS_ThreadHandle; diff --git a/thirdparty/sdl/thread/pthread/SDL_syscond.c b/thirdparty/sdl/thread/pthread/SDL_syscond.c new file mode 100644 index 00000000000..c3e4098f907 --- /dev/null +++ b/thirdparty/sdl/thread/pthread/SDL_syscond.c @@ -0,0 +1,128 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include +#include +#include +#include +#include + +#include "SDL_sysmutex_c.h" + +struct SDL_Condition +{ + pthread_cond_t cond; +}; + +// Create a condition variable +SDL_Condition *SDL_CreateCondition(void) +{ + SDL_Condition *cond; + + cond = (SDL_Condition *)SDL_malloc(sizeof(SDL_Condition)); + if (cond) { + if (pthread_cond_init(&cond->cond, NULL) != 0) { + SDL_SetError("pthread_cond_init() failed"); + SDL_free(cond); + cond = NULL; + } + } + return cond; +} + +// Destroy a condition variable +void SDL_DestroyCondition(SDL_Condition *cond) +{ + if (cond) { + pthread_cond_destroy(&cond->cond); + SDL_free(cond); + } +} + +// Restart one of the threads that are waiting on the condition variable +void SDL_SignalCondition(SDL_Condition *cond) +{ + if (!cond) { + return; + } + + pthread_cond_signal(&cond->cond); +} + +// Restart all threads that are waiting on the condition variable +void SDL_BroadcastCondition(SDL_Condition *cond) +{ + if (!cond) { + return; + } + + pthread_cond_broadcast(&cond->cond); +} + +bool SDL_WaitConditionTimeoutNS(SDL_Condition *cond, SDL_Mutex *mutex, Sint64 timeoutNS) +{ +#ifndef HAVE_CLOCK_GETTIME + struct timeval delta; +#endif + struct timespec abstime; + + if (!cond || !mutex) { + return true; + } + + if (timeoutNS < 0) { + return (pthread_cond_wait(&cond->cond, &mutex->id) == 0); + } + +#ifdef HAVE_CLOCK_GETTIME + clock_gettime(CLOCK_REALTIME, &abstime); + + abstime.tv_sec += (timeoutNS / SDL_NS_PER_SECOND); + abstime.tv_nsec += (timeoutNS % SDL_NS_PER_SECOND); +#else + gettimeofday(&delta, NULL); + + abstime.tv_sec = delta.tv_sec + (timeoutNS / SDL_NS_PER_SECOND); + abstime.tv_nsec = SDL_US_TO_NS(delta.tv_usec) + (timeoutNS % SDL_NS_PER_SECOND); +#endif + while (abstime.tv_nsec >= 1000000000) { + abstime.tv_sec += 1; + abstime.tv_nsec -= 1000000000; + } + + bool result; + int rc; +tryagain: + rc = pthread_cond_timedwait(&cond->cond, &mutex->id, &abstime); + switch (rc) { + case EINTR: + goto tryagain; + // break; -Wunreachable-code-break + case ETIMEDOUT: + result = false; + break; + default: + result = true; + break; + } + return result; +} diff --git a/thirdparty/sdl/thread/pthread/SDL_sysmutex.c b/thirdparty/sdl/thread/pthread/SDL_sysmutex.c new file mode 100644 index 00000000000..7bba286e1ad --- /dev/null +++ b/thirdparty/sdl/thread/pthread/SDL_sysmutex.c @@ -0,0 +1,154 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include +#include + +#include "SDL_sysmutex_c.h" + +SDL_Mutex *SDL_CreateMutex(void) +{ + SDL_Mutex *mutex; + pthread_mutexattr_t attr; + + // Allocate the structure + mutex = (SDL_Mutex *)SDL_calloc(1, sizeof(*mutex)); + if (mutex) { + pthread_mutexattr_init(&attr); +#ifdef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); +#elif defined(SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP) + pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP); +#else + // No extra attributes necessary +#endif + if (pthread_mutex_init(&mutex->id, &attr) != 0) { + SDL_SetError("pthread_mutex_init() failed"); + SDL_free(mutex); + mutex = NULL; + } + } + return mutex; +} + +void SDL_DestroyMutex(SDL_Mutex *mutex) +{ + if (mutex) { + pthread_mutex_destroy(&mutex->id); + SDL_free(mutex); + } +} + +void SDL_LockMutex(SDL_Mutex *mutex) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + if (mutex) { +#ifdef FAKE_RECURSIVE_MUTEX + pthread_t this_thread = pthread_self(); + if (mutex->owner == this_thread) { + ++mutex->recursive; + } else { + /* The order of operations is important. + We set the locking thread id after we obtain the lock + so unlocks from other threads will fail. + */ + const int rc = pthread_mutex_lock(&mutex->id); + SDL_assert(rc == 0); // assume we're in a lot of trouble if this assert fails. + mutex->owner = this_thread; + mutex->recursive = 0; + } +#else + const int rc = pthread_mutex_lock(&mutex->id); + SDL_assert(rc == 0); // assume we're in a lot of trouble if this assert fails. +#endif + } +} + +bool SDL_TryLockMutex(SDL_Mutex *mutex) +{ + bool result = true; + + if (mutex) { +#ifdef FAKE_RECURSIVE_MUTEX + pthread_t this_thread = pthread_self(); + if (mutex->owner == this_thread) { + ++mutex->recursive; + } else { + /* The order of operations is important. + We set the locking thread id after we obtain the lock + so unlocks from other threads will fail. + */ + const int rc = pthread_mutex_trylock(&mutex->id); + if (rc == 0) { + mutex->owner = this_thread; + mutex->recursive = 0; + } else if (rc == EBUSY) { + result = false; + } else { + SDL_assert(!"Error trying to lock mutex"); // assume we're in a lot of trouble if this assert fails. + result = false; + } + } +#else + const int rc = pthread_mutex_trylock(&mutex->id); + if (rc != 0) { + if (rc == EBUSY) { + result = false; + } else { + SDL_assert(!"Error trying to lock mutex"); // assume we're in a lot of trouble if this assert fails. + result = false; + } + } +#endif + } + + return result; +} + +void SDL_UnlockMutex(SDL_Mutex *mutex) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + if (mutex) { +#ifdef FAKE_RECURSIVE_MUTEX + // We can only unlock the mutex if we own it + if (pthread_self() == mutex->owner) { + if (mutex->recursive) { + --mutex->recursive; + } else { + /* The order of operations is important. + First reset the owner so another thread doesn't lock + the mutex and set the ownership before we reset it, + then release the lock semaphore. + */ + mutex->owner = 0; + pthread_mutex_unlock(&mutex->id); + } + } else { + SDL_SetError("mutex not owned by this thread"); + return; + } + +#else + const int rc = pthread_mutex_unlock(&mutex->id); + SDL_assert(rc == 0); // assume we're in a lot of trouble if this assert fails. +#endif // FAKE_RECURSIVE_MUTEX + } +} + diff --git a/thirdparty/sdl/thread/pthread/SDL_sysmutex_c.h b/thirdparty/sdl/thread/pthread/SDL_sysmutex_c.h new file mode 100644 index 00000000000..f69e7b319dd --- /dev/null +++ b/thirdparty/sdl/thread/pthread/SDL_sysmutex_c.h @@ -0,0 +1,40 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_mutex_c_h_ +#define SDL_mutex_c_h_ + +#if !(defined(SDL_THREAD_PTHREAD_RECURSIVE_MUTEX) || \ + defined(SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP)) +#define FAKE_RECURSIVE_MUTEX +#endif + +struct SDL_Mutex +{ + pthread_mutex_t id; +#ifdef FAKE_RECURSIVE_MUTEX + int recursive; + pthread_t owner; +#endif +}; + +#endif // SDL_mutex_c_h_ diff --git a/thirdparty/sdl/thread/pthread/SDL_sysrwlock.c b/thirdparty/sdl/thread/pthread/SDL_sysrwlock.c new file mode 100644 index 00000000000..3cf02e5d133 --- /dev/null +++ b/thirdparty/sdl/thread/pthread/SDL_sysrwlock.c @@ -0,0 +1,113 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include +#include + +struct SDL_RWLock +{ + pthread_rwlock_t id; +}; + + +SDL_RWLock *SDL_CreateRWLock(void) +{ + SDL_RWLock *rwlock; + + // Allocate the structure + rwlock = (SDL_RWLock *)SDL_calloc(1, sizeof(*rwlock)); + if (rwlock) { + if (pthread_rwlock_init(&rwlock->id, NULL) != 0) { + SDL_SetError("pthread_rwlock_init() failed"); + SDL_free(rwlock); + rwlock = NULL; + } + } + return rwlock; +} + +void SDL_DestroyRWLock(SDL_RWLock *rwlock) +{ + if (rwlock) { + pthread_rwlock_destroy(&rwlock->id); + SDL_free(rwlock); + } +} + +void SDL_LockRWLockForReading(SDL_RWLock *rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + if (rwlock) { + const int rc = pthread_rwlock_rdlock(&rwlock->id); + SDL_assert(rc == 0); // assume we're in a lot of trouble if this assert fails. + } +} + +void SDL_LockRWLockForWriting(SDL_RWLock *rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + if (rwlock) { + const int rc = pthread_rwlock_wrlock(&rwlock->id); + SDL_assert(rc == 0); // assume we're in a lot of trouble if this assert fails. + } +} + +bool SDL_TryLockRWLockForReading(SDL_RWLock *rwlock) +{ + bool result = true; + + if (rwlock) { + const int rc = pthread_rwlock_tryrdlock(&rwlock->id); + if (rc != 0) { + result = false; + if (rc != EBUSY) { + SDL_assert(!"Error trying to lock rwlock for reading"); // assume we're in a lot of trouble if this assert fails. + } + } + } + + return result; +} + +bool SDL_TryLockRWLockForWriting(SDL_RWLock *rwlock) +{ + bool result = true; + + if (rwlock) { + const int rc = pthread_rwlock_trywrlock(&rwlock->id); + if (rc != 0) { + result = false; + if (rc != EBUSY) { + SDL_assert(!"Error trying to lock rwlock for writing"); // assume we're in a lot of trouble if this assert fails. + } + } + } + + return result; +} + +void SDL_UnlockRWLock(SDL_RWLock *rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + if (rwlock) { + const int rc = pthread_rwlock_unlock(&rwlock->id); + SDL_assert(rc == 0); // assume we're in a lot of trouble if this assert fails. + } +} + diff --git a/thirdparty/sdl/thread/pthread/SDL_syssem.c b/thirdparty/sdl/thread/pthread/SDL_syssem.c new file mode 100644 index 00000000000..d5d32982c66 --- /dev/null +++ b/thirdparty/sdl/thread/pthread/SDL_syssem.c @@ -0,0 +1,160 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include +#include +#include +#include +#include + +// Wrapper around POSIX 1003.1b semaphores + +#if defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS) +// macOS doesn't support sem_getvalue() as of version 10.4 +#include "../generic/SDL_syssem.c" +#else + +struct SDL_Semaphore +{ + sem_t sem; +}; + +// Create a semaphore, initialized with value +SDL_Semaphore *SDL_CreateSemaphore(Uint32 initial_value) +{ + SDL_Semaphore *sem = (SDL_Semaphore *)SDL_malloc(sizeof(SDL_Semaphore)); + if (sem) { + if (sem_init(&sem->sem, 0, initial_value) < 0) { + SDL_SetError("sem_init() failed"); + SDL_free(sem); + sem = NULL; + } + } + return sem; +} + +void SDL_DestroySemaphore(SDL_Semaphore *sem) +{ + if (sem) { + sem_destroy(&sem->sem); + SDL_free(sem); + } +} + +bool SDL_WaitSemaphoreTimeoutNS(SDL_Semaphore *sem, Sint64 timeoutNS) +{ +#ifdef HAVE_SEM_TIMEDWAIT +#ifndef HAVE_CLOCK_GETTIME + struct timeval now; +#endif + struct timespec ts_timeout; +#else + Uint64 stop_time; +#endif + + if (!sem) { + return true; + } + + // Try the easy cases first + if (timeoutNS == 0) { + return (sem_trywait(&sem->sem) == 0); + } + + if (timeoutNS < 0) { + int rc; + do { + rc = sem_wait(&sem->sem); + } while (rc < 0 && errno == EINTR); + + return (rc == 0); + } + +#ifdef HAVE_SEM_TIMEDWAIT + /* Setup the timeout. sem_timedwait doesn't wait for + * a lapse of time, but until we reach a certain time. + * This time is now plus the timeout. + */ +#ifdef HAVE_CLOCK_GETTIME + clock_gettime(CLOCK_REALTIME, &ts_timeout); + + // Add our timeout to current time + ts_timeout.tv_sec += (timeoutNS / SDL_NS_PER_SECOND); + ts_timeout.tv_nsec += (timeoutNS % SDL_NS_PER_SECOND); +#else + gettimeofday(&now, NULL); + + // Add our timeout to current time + ts_timeout.tv_sec = now.tv_sec + (timeoutNS / SDL_NS_PER_SECOND); + ts_timeout.tv_nsec = SDL_US_TO_NS(now.tv_usec) + (timeoutNS % SDL_NS_PER_SECOND); +#endif + + // Wrap the second if needed + while (ts_timeout.tv_nsec >= 1000000000) { + ts_timeout.tv_sec += 1; + ts_timeout.tv_nsec -= 1000000000; + } + + // Wait. + int rc; + do { + rc = sem_timedwait(&sem->sem, &ts_timeout); + } while (rc < 0 && errno == EINTR); + + return (rc == 0); +#else + stop_time = SDL_GetTicksNS() + timeoutNS; + while (sem_trywait(&sem->sem) != 0) { + if (SDL_GetTicksNS() >= stop_time) { + return false; + } + SDL_DelayNS(100); + } + return true; +#endif // HAVE_SEM_TIMEDWAIT +} + +Uint32 SDL_GetSemaphoreValue(SDL_Semaphore *sem) +{ + int ret = 0; + + if (!sem) { + return 0; + } + + sem_getvalue(&sem->sem, &ret); + if (ret < 0) { + ret = 0; + } + return (Uint32)ret; +} + +void SDL_SignalSemaphore(SDL_Semaphore *sem) +{ + if (!sem) { + return; + } + + sem_post(&sem->sem); +} + +#endif // SDL_PLATFORM_MACOS diff --git a/thirdparty/sdl/thread/pthread/SDL_systhread.c b/thirdparty/sdl/thread/pthread/SDL_systhread.c new file mode 100644 index 00000000000..ae4a94c2e27 --- /dev/null +++ b/thirdparty/sdl/thread/pthread/SDL_systhread.c @@ -0,0 +1,293 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include + +#ifdef HAVE_PTHREAD_NP_H +#include +#endif + +#ifdef HAVE_SIGNAL_H +#include +#endif +#include + +#ifdef SDL_PLATFORM_LINUX +#include +#include +#include +#include + +#include "../../core/linux/SDL_dbus.h" +#endif // SDL_PLATFORM_LINUX + +#if (defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_ANDROID) || defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS)) && defined(HAVE_DLOPEN) +#include +#ifndef RTLD_DEFAULT +#define RTLD_DEFAULT NULL +#endif +#endif + +#include "../SDL_thread_c.h" +#include "../SDL_systhread.h" +#ifdef SDL_PLATFORM_ANDROID +#include "../../core/android/SDL_android.h" +#endif + +#ifdef SDL_PLATFORM_HAIKU +#include +#endif + +#ifdef HAVE_SIGNAL_H +// List of signals to mask in the subthreads +static const int sig_list[] = { + SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH, + SIGVTALRM, SIGPROF, 0 +}; +#endif + +static void *RunThread(void *data) +{ +#ifdef SDL_PLATFORM_ANDROID + Android_JNI_SetupThread(); +#endif + SDL_RunThread((SDL_Thread *)data); + return NULL; +} + +#if (defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS)) && defined(HAVE_DLOPEN) +static bool checked_setname = false; +static int (*ppthread_setname_np)(const char *) = NULL; +#elif (defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_ANDROID)) && defined(HAVE_DLOPEN) +static bool checked_setname = false; +static int (*ppthread_setname_np)(pthread_t, const char *) = NULL; +#endif +bool SDL_SYS_CreateThread(SDL_Thread *thread, + SDL_FunctionPointer pfnBeginThread, + SDL_FunctionPointer pfnEndThread) +{ + pthread_attr_t type; + +// do this here before any threads exist, so there's no race condition. +#if (defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS) || defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_ANDROID)) && defined(HAVE_DLOPEN) + if (!checked_setname) { + void *fn = dlsym(RTLD_DEFAULT, "pthread_setname_np"); +#if defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS) + ppthread_setname_np = (int (*)(const char *))fn; +#elif defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_ANDROID) + ppthread_setname_np = (int (*)(pthread_t, const char *))fn; +#endif + checked_setname = true; + } + #endif + + // Set the thread attributes + if (pthread_attr_init(&type) != 0) { + return SDL_SetError("Couldn't initialize pthread attributes"); + } + pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE); + + // Set caller-requested stack size. Otherwise: use the system default. + if (thread->stacksize) { + pthread_attr_setstacksize(&type, thread->stacksize); + } + + // Create the thread and go! + if (pthread_create(&thread->handle, &type, RunThread, thread) != 0) { + return SDL_SetError("Not enough resources to create thread"); + } + + return true; +} + +void SDL_SYS_SetupThread(const char *name) +{ +#ifdef HAVE_SIGNAL_H + int i; + sigset_t mask; +#endif + + if (name) { +#if (defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS) || defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_ANDROID)) && defined(HAVE_DLOPEN) + SDL_assert(checked_setname); + if (ppthread_setname_np) { +#if defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS) + ppthread_setname_np(name); +#elif defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_ANDROID) + if (ppthread_setname_np(pthread_self(), name) == ERANGE) { + char namebuf[16]; // Limited to 16 char + SDL_strlcpy(namebuf, name, sizeof(namebuf)); + ppthread_setname_np(pthread_self(), namebuf); + } +#endif + } +#elif defined(HAVE_PTHREAD_SETNAME_NP) +#ifdef SDL_PLATFORM_NETBSD + pthread_setname_np(pthread_self(), "%s", name); +#else + if (pthread_setname_np(pthread_self(), name) == ERANGE) { + char namebuf[16]; // Limited to 16 char + SDL_strlcpy(namebuf, name, sizeof(namebuf)); + pthread_setname_np(pthread_self(), namebuf); + } +#endif +#elif defined(HAVE_PTHREAD_SET_NAME_NP) + pthread_set_name_np(pthread_self(), name); +#elif defined(SDL_PLATFORM_HAIKU) + // The docs say the thread name can't be longer than B_OS_NAME_LENGTH. + char namebuf[B_OS_NAME_LENGTH]; + SDL_strlcpy(namebuf, name, sizeof(namebuf)); + rename_thread(find_thread(NULL), namebuf); +#endif + } + +#ifdef HAVE_SIGNAL_H + // Mask asynchronous signals for this thread + sigemptyset(&mask); + for (i = 0; sig_list[i]; ++i) { + sigaddset(&mask, sig_list[i]); + } + pthread_sigmask(SIG_BLOCK, &mask, 0); +#endif + +#ifdef PTHREAD_CANCEL_ASYNCHRONOUS + // Allow ourselves to be asynchronously cancelled + { + int oldstate; + pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate); + } +#endif +} + +SDL_ThreadID SDL_GetCurrentThreadID(void) +{ + return (SDL_ThreadID)pthread_self(); +} + +bool SDL_SYS_SetThreadPriority(SDL_ThreadPriority priority) +{ +#ifdef SDL_PLATFORM_RISCOS + // FIXME: Setting thread priority does not seem to be supported + return true; +#else + struct sched_param sched; + int policy; + int pri_policy; + pthread_t thread = pthread_self(); + const char *policyhint = SDL_GetHint(SDL_HINT_THREAD_PRIORITY_POLICY); + const bool timecritical_realtime_hint = SDL_GetHintBoolean(SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL, false); + + if (pthread_getschedparam(thread, &policy, &sched) != 0) { + return SDL_SetError("pthread_getschedparam() failed"); + } + + /* Higher priority levels may require changing the pthread scheduler policy + * for the thread. SDL will make such changes by default but there is + * also a hint allowing that behavior to be overridden. */ + switch (priority) { + case SDL_THREAD_PRIORITY_LOW: + case SDL_THREAD_PRIORITY_NORMAL: + pri_policy = SCHED_OTHER; + break; + case SDL_THREAD_PRIORITY_HIGH: + case SDL_THREAD_PRIORITY_TIME_CRITICAL: +#if defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS) || defined(SDL_PLATFORM_TVOS) + // Apple requires SCHED_RR for high priority threads + pri_policy = SCHED_RR; + break; +#else + pri_policy = SCHED_OTHER; + break; +#endif + default: + pri_policy = policy; + break; + } + + if (timecritical_realtime_hint && priority == SDL_THREAD_PRIORITY_TIME_CRITICAL) { + pri_policy = SCHED_RR; + } + + if (policyhint) { + if (SDL_strcmp(policyhint, "current") == 0) { + // Leave current thread scheduler policy unchanged + } else if (SDL_strcmp(policyhint, "other") == 0) { + policy = SCHED_OTHER; + } else if (SDL_strcmp(policyhint, "rr") == 0) { + policy = SCHED_RR; + } else if (SDL_strcmp(policyhint, "fifo") == 0) { + policy = SCHED_FIFO; + } else { + policy = pri_policy; + } + } else { + policy = pri_policy; + } + +#ifdef SDL_PLATFORM_LINUX + { + pid_t linuxTid = syscall(SYS_gettid); + return SDL_SetLinuxThreadPriorityAndPolicy(linuxTid, priority, policy); + } +#else + if (priority == SDL_THREAD_PRIORITY_LOW) { + sched.sched_priority = sched_get_priority_min(policy); + } else if (priority == SDL_THREAD_PRIORITY_TIME_CRITICAL) { + sched.sched_priority = sched_get_priority_max(policy); + } else { + int min_priority = sched_get_priority_min(policy); + int max_priority = sched_get_priority_max(policy); + +#if defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_IOS) || defined(SDL_PLATFORM_TVOS) + if (min_priority == 15 && max_priority == 47) { + // Apple has a specific set of thread priorities + if (priority == SDL_THREAD_PRIORITY_HIGH) { + sched.sched_priority = 45; + } else { + sched.sched_priority = 37; + } + } else +#endif // SDL_PLATFORM_MACOS || SDL_PLATFORM_IOS || SDL_PLATFORM_TVOS + { + sched.sched_priority = (min_priority + (max_priority - min_priority) / 2); + if (priority == SDL_THREAD_PRIORITY_HIGH) { + sched.sched_priority += ((max_priority - min_priority) / 4); + } + } + } + if (pthread_setschedparam(thread, policy, &sched) != 0) { + return SDL_SetError("pthread_setschedparam() failed"); + } + return true; +#endif // linux +#endif // #if SDL_PLATFORM_RISCOS +} + +void SDL_SYS_WaitThread(SDL_Thread *thread) +{ + pthread_join(thread->handle, 0); +} + +void SDL_SYS_DetachThread(SDL_Thread *thread) +{ + pthread_detach(thread->handle); +} diff --git a/thirdparty/sdl/thread/pthread/SDL_systhread_c.h b/thirdparty/sdl/thread/pthread/SDL_systhread_c.h new file mode 100644 index 00000000000..bdfcd68c21a --- /dev/null +++ b/thirdparty/sdl/thread/pthread/SDL_systhread_c.h @@ -0,0 +1,25 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include + +typedef pthread_t SYS_ThreadHandle; diff --git a/thirdparty/sdl/thread/pthread/SDL_systls.c b/thirdparty/sdl/thread/pthread/SDL_systls.c new file mode 100644 index 00000000000..18e9a01edf5 --- /dev/null +++ b/thirdparty/sdl/thread/pthread/SDL_systls.c @@ -0,0 +1,78 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" +#include "../SDL_systhread.h" +#include "../SDL_thread_c.h" + +#include + +#define INVALID_PTHREAD_KEY ((pthread_key_t)-1) + +static pthread_key_t thread_local_storage = INVALID_PTHREAD_KEY; +static bool generic_local_storage = false; + +void SDL_SYS_InitTLSData(void) +{ + if (thread_local_storage == INVALID_PTHREAD_KEY && !generic_local_storage) { + if (pthread_key_create(&thread_local_storage, NULL) != 0) { + thread_local_storage = INVALID_PTHREAD_KEY; + SDL_Generic_InitTLSData(); + generic_local_storage = true; + } + } +} + +SDL_TLSData *SDL_SYS_GetTLSData(void) +{ + if (generic_local_storage) { + return SDL_Generic_GetTLSData(); + } + + if (thread_local_storage != INVALID_PTHREAD_KEY) { + return (SDL_TLSData *)pthread_getspecific(thread_local_storage); + } + return NULL; +} + +bool SDL_SYS_SetTLSData(SDL_TLSData *data) +{ + if (generic_local_storage) { + return SDL_Generic_SetTLSData(data); + } + + if (pthread_setspecific(thread_local_storage, data) != 0) { + return SDL_SetError("pthread_setspecific() failed"); + } + return true; +} + +void SDL_SYS_QuitTLSData(void) +{ + if (generic_local_storage) { + SDL_Generic_QuitTLSData(); + generic_local_storage = false; + } else { + if (thread_local_storage != INVALID_PTHREAD_KEY) { + pthread_key_delete(thread_local_storage); + thread_local_storage = INVALID_PTHREAD_KEY; + } + } +} diff --git a/thirdparty/sdl/thread/windows/SDL_syscond_cv.c b/thirdparty/sdl/thread/windows/SDL_syscond_cv.c new file mode 100644 index 00000000000..b29ef634e0b --- /dev/null +++ b/thirdparty/sdl/thread/windows/SDL_syscond_cv.c @@ -0,0 +1,226 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "../generic/SDL_syscond_c.h" +#include "SDL_sysmutex_c.h" + +typedef SDL_Condition *(*pfnSDL_CreateCondition)(void); +typedef void (*pfnSDL_DestroyCondition)(SDL_Condition *); +typedef void (*pfnSDL_SignalCondition)(SDL_Condition *); +typedef void (*pfnSDL_BroadcastCondition)(SDL_Condition *); +typedef bool (*pfnSDL_WaitConditionTimeoutNS)(SDL_Condition *, SDL_Mutex *, Sint64); + +typedef struct SDL_cond_impl_t +{ + pfnSDL_CreateCondition Create; + pfnSDL_DestroyCondition Destroy; + pfnSDL_SignalCondition Signal; + pfnSDL_BroadcastCondition Broadcast; + pfnSDL_WaitConditionTimeoutNS WaitTimeoutNS; +} SDL_cond_impl_t; + +// Implementation will be chosen at runtime based on available Kernel features +static SDL_cond_impl_t SDL_cond_impl_active = { 0 }; + +/** + * Native Windows Condition Variable (SRW Locks) + */ + +#ifndef CONDITION_VARIABLE_INIT +#define CONDITION_VARIABLE_INIT \ + { \ + 0 \ + } +typedef struct CONDITION_VARIABLE +{ + PVOID Ptr; +} CONDITION_VARIABLE, *PCONDITION_VARIABLE; +#endif + +typedef VOID(WINAPI *pfnWakeConditionVariable)(PCONDITION_VARIABLE); +typedef VOID(WINAPI *pfnWakeAllConditionVariable)(PCONDITION_VARIABLE); +typedef BOOL(WINAPI *pfnSleepConditionVariableSRW)(PCONDITION_VARIABLE, PSRWLOCK, DWORD, ULONG); +typedef BOOL(WINAPI *pfnSleepConditionVariableCS)(PCONDITION_VARIABLE, PCRITICAL_SECTION, DWORD); + +static pfnWakeConditionVariable pWakeConditionVariable = NULL; +static pfnWakeAllConditionVariable pWakeAllConditionVariable = NULL; +static pfnSleepConditionVariableSRW pSleepConditionVariableSRW = NULL; +static pfnSleepConditionVariableCS pSleepConditionVariableCS = NULL; + +typedef struct SDL_cond_cv +{ + CONDITION_VARIABLE cond; +} SDL_cond_cv; + +static SDL_Condition *SDL_CreateCondition_cv(void) +{ + // Relies on CONDITION_VARIABLE_INIT == 0. + return (SDL_Condition *)SDL_calloc(1, sizeof(SDL_cond_cv)); +} + +static void SDL_DestroyCondition_cv(SDL_Condition *cond) +{ + // There are no kernel allocated resources + SDL_free(cond); +} + +static void SDL_SignalCondition_cv(SDL_Condition *_cond) +{ + SDL_cond_cv *cond = (SDL_cond_cv *)_cond; + pWakeConditionVariable(&cond->cond); +} + +static void SDL_BroadcastCondition_cv(SDL_Condition *_cond) +{ + SDL_cond_cv *cond = (SDL_cond_cv *)_cond; + pWakeAllConditionVariable(&cond->cond); +} + +static bool SDL_WaitConditionTimeoutNS_cv(SDL_Condition *_cond, SDL_Mutex *_mutex, Sint64 timeoutNS) +{ + SDL_cond_cv *cond = (SDL_cond_cv *)_cond; + DWORD timeout; + bool result; + + if (timeoutNS < 0) { + timeout = INFINITE; + } else { + timeout = (DWORD)SDL_NS_TO_MS(timeoutNS); + } + + if (SDL_mutex_impl_active.Type == SDL_MUTEX_SRW) { + SDL_mutex_srw *mutex = (SDL_mutex_srw *)_mutex; + + if (mutex->count != 1 || mutex->owner != GetCurrentThreadId()) { + // Passed mutex is not locked or locked recursively" + return false; + } + + // The mutex must be updated to the released state + mutex->count = 0; + mutex->owner = 0; + + result = (pSleepConditionVariableSRW(&cond->cond, &mutex->srw, timeout, 0) == TRUE); + + // The mutex is owned by us again, regardless of status of the wait + SDL_assert(mutex->count == 0 && mutex->owner == 0); + mutex->count = 1; + mutex->owner = GetCurrentThreadId(); + } else { + SDL_mutex_cs *mutex = (SDL_mutex_cs *)_mutex; + + SDL_assert(SDL_mutex_impl_active.Type == SDL_MUTEX_CS); + + result = (pSleepConditionVariableCS(&cond->cond, &mutex->cs, timeout) == TRUE); + } + + return result; +} + +static const SDL_cond_impl_t SDL_cond_impl_cv = { + &SDL_CreateCondition_cv, + &SDL_DestroyCondition_cv, + &SDL_SignalCondition_cv, + &SDL_BroadcastCondition_cv, + &SDL_WaitConditionTimeoutNS_cv, +}; + + +// Generic Condition Variable implementation using SDL_Mutex and SDL_Semaphore +static const SDL_cond_impl_t SDL_cond_impl_generic = { + &SDL_CreateCondition_generic, + &SDL_DestroyCondition_generic, + &SDL_SignalCondition_generic, + &SDL_BroadcastCondition_generic, + &SDL_WaitConditionTimeoutNS_generic, +}; + +SDL_Condition *SDL_CreateCondition(void) +{ + if (!SDL_cond_impl_active.Create) { + const SDL_cond_impl_t *impl = NULL; + + if (SDL_mutex_impl_active.Type == SDL_MUTEX_INVALID) { + // The mutex implementation isn't decided yet, trigger it + SDL_Mutex *mutex = SDL_CreateMutex(); + if (!mutex) { + return NULL; + } + SDL_DestroyMutex(mutex); + + SDL_assert(SDL_mutex_impl_active.Type != SDL_MUTEX_INVALID); + } + + // Default to generic implementation, works with all mutex implementations + impl = &SDL_cond_impl_generic; + { + HMODULE kernel32 = GetModuleHandle(TEXT("kernel32.dll")); + if (kernel32) { + pWakeConditionVariable = (pfnWakeConditionVariable)GetProcAddress(kernel32, "WakeConditionVariable"); + pWakeAllConditionVariable = (pfnWakeAllConditionVariable)GetProcAddress(kernel32, "WakeAllConditionVariable"); + pSleepConditionVariableSRW = (pfnSleepConditionVariableSRW)GetProcAddress(kernel32, "SleepConditionVariableSRW"); + pSleepConditionVariableCS = (pfnSleepConditionVariableCS)GetProcAddress(kernel32, "SleepConditionVariableCS"); + if (pWakeConditionVariable && pWakeAllConditionVariable && pSleepConditionVariableSRW && pSleepConditionVariableCS) { + // Use the Windows provided API + impl = &SDL_cond_impl_cv; + } + } + } + + SDL_copyp(&SDL_cond_impl_active, impl); + } + return SDL_cond_impl_active.Create(); +} + +void SDL_DestroyCondition(SDL_Condition *cond) +{ + if (cond) { + SDL_cond_impl_active.Destroy(cond); + } +} + +void SDL_SignalCondition(SDL_Condition *cond) +{ + if (!cond) { + return; + } + + SDL_cond_impl_active.Signal(cond); +} + +void SDL_BroadcastCondition(SDL_Condition *cond) +{ + if (!cond) { + return; + } + + SDL_cond_impl_active.Broadcast(cond); +} + +bool SDL_WaitConditionTimeoutNS(SDL_Condition *cond, SDL_Mutex *mutex, Sint64 timeoutNS) +{ + if (!cond || !mutex) { + return true; + } + + return SDL_cond_impl_active.WaitTimeoutNS(cond, mutex, timeoutNS); +} diff --git a/thirdparty/sdl/thread/windows/SDL_sysmutex.c b/thirdparty/sdl/thread/windows/SDL_sysmutex.c new file mode 100644 index 00000000000..88ec0047c47 --- /dev/null +++ b/thirdparty/sdl/thread/windows/SDL_sysmutex.c @@ -0,0 +1,238 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_THREAD_WINDOWS + +/** + * Mutex functions using the Win32 API + * There are two implementations available based on: + * - Critical Sections. Available on all OS versions since Windows XP. + * - Slim Reader/Writer Locks. Requires Windows 7 or newer. + * which are chosen at runtime. + */ + +#include "SDL_sysmutex_c.h" + +// Implementation will be chosen at runtime based on available Kernel features +SDL_mutex_impl_t SDL_mutex_impl_active = { 0 }; + +/** + * Implementation based on Slim Reader/Writer (SRW) Locks for Win 7 and newer. + */ + +typedef VOID(WINAPI *pfnInitializeSRWLock)(PSRWLOCK); +typedef VOID(WINAPI *pfnReleaseSRWLockExclusive)(PSRWLOCK); +typedef VOID(WINAPI *pfnAcquireSRWLockExclusive)(PSRWLOCK); +typedef BOOLEAN(WINAPI *pfnTryAcquireSRWLockExclusive)(PSRWLOCK); +static pfnInitializeSRWLock pInitializeSRWLock = NULL; +static pfnReleaseSRWLockExclusive pReleaseSRWLockExclusive = NULL; +static pfnAcquireSRWLockExclusive pAcquireSRWLockExclusive = NULL; +static pfnTryAcquireSRWLockExclusive pTryAcquireSRWLockExclusive = NULL; + +static SDL_Mutex *SDL_CreateMutex_srw(void) +{ + SDL_mutex_srw *mutex = (SDL_mutex_srw *)SDL_calloc(1, sizeof(*mutex)); + if (mutex) { + pInitializeSRWLock(&mutex->srw); + } + return (SDL_Mutex *)mutex; +} + +static void SDL_DestroyMutex_srw(SDL_Mutex *mutex) +{ + // There are no kernel allocated resources + SDL_free(mutex); +} + +static void SDL_LockMutex_srw(SDL_Mutex *_mutex) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + SDL_mutex_srw *mutex = (SDL_mutex_srw *)_mutex; + const DWORD this_thread = GetCurrentThreadId(); + + if (mutex->owner == this_thread) { + ++mutex->count; + } else { + /* The order of operations is important. + We set the locking thread id after we obtain the lock + so unlocks from other threads will fail. + */ + pAcquireSRWLockExclusive(&mutex->srw); + SDL_assert(mutex->count == 0 && mutex->owner == 0); + mutex->owner = this_thread; + mutex->count = 1; + } +} + +static bool SDL_TryLockMutex_srw(SDL_Mutex *_mutex) +{ + SDL_mutex_srw *mutex = (SDL_mutex_srw *)_mutex; + const DWORD this_thread = GetCurrentThreadId(); + bool retval = true; + + if (mutex->owner == this_thread) { + ++mutex->count; + } else { + if (pTryAcquireSRWLockExclusive(&mutex->srw) != 0) { + SDL_assert(mutex->count == 0 && mutex->owner == 0); + mutex->owner = this_thread; + mutex->count = 1; + } else { + retval = false; + } + } + return retval; +} + +static void SDL_UnlockMutex_srw(SDL_Mutex *_mutex) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + SDL_mutex_srw *mutex = (SDL_mutex_srw *)_mutex; + + if (mutex->owner == GetCurrentThreadId()) { + if (--mutex->count == 0) { + mutex->owner = 0; + pReleaseSRWLockExclusive(&mutex->srw); + } + } else { + SDL_assert(!"mutex not owned by this thread"); // undefined behavior...! + } +} + +static const SDL_mutex_impl_t SDL_mutex_impl_srw = { + &SDL_CreateMutex_srw, + &SDL_DestroyMutex_srw, + &SDL_LockMutex_srw, + &SDL_TryLockMutex_srw, + &SDL_UnlockMutex_srw, + SDL_MUTEX_SRW, +}; + +/** + * Fallback Mutex implementation using Critical Sections (before Win 7) + */ + +static SDL_Mutex *SDL_CreateMutex_cs(void) +{ + SDL_mutex_cs *mutex = (SDL_mutex_cs *)SDL_malloc(sizeof(*mutex)); + if (mutex) { + // Initialize + // On SMP systems, a non-zero spin count generally helps performance + // This function always succeeds + (void)InitializeCriticalSectionAndSpinCount(&mutex->cs, 2000); + } + return (SDL_Mutex *)mutex; +} + +static void SDL_DestroyMutex_cs(SDL_Mutex *mutex_) +{ + SDL_mutex_cs *mutex = (SDL_mutex_cs *)mutex_; + DeleteCriticalSection(&mutex->cs); + SDL_free(mutex); +} + +static void SDL_LockMutex_cs(SDL_Mutex *mutex_) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + SDL_mutex_cs *mutex = (SDL_mutex_cs *)mutex_; + EnterCriticalSection(&mutex->cs); +} + +static bool SDL_TryLockMutex_cs(SDL_Mutex *mutex_) +{ + SDL_mutex_cs *mutex = (SDL_mutex_cs *)mutex_; + return (TryEnterCriticalSection(&mutex->cs) == TRUE); +} + +static void SDL_UnlockMutex_cs(SDL_Mutex *mutex_) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + SDL_mutex_cs *mutex = (SDL_mutex_cs *)mutex_; + LeaveCriticalSection(&mutex->cs); +} + +static const SDL_mutex_impl_t SDL_mutex_impl_cs = { + &SDL_CreateMutex_cs, + &SDL_DestroyMutex_cs, + &SDL_LockMutex_cs, + &SDL_TryLockMutex_cs, + &SDL_UnlockMutex_cs, + SDL_MUTEX_CS, +}; + +/** + * Runtime selection and redirection + */ + +SDL_Mutex *SDL_CreateMutex(void) +{ + if (!SDL_mutex_impl_active.Create) { + const SDL_mutex_impl_t *impl = &SDL_mutex_impl_cs; + + // Try faster implementation for Windows 7 and newer + HMODULE kernel32 = GetModuleHandle(TEXT("kernel32.dll")); + if (kernel32) { + // Requires Vista: + pInitializeSRWLock = (pfnInitializeSRWLock)GetProcAddress(kernel32, "InitializeSRWLock"); + pReleaseSRWLockExclusive = (pfnReleaseSRWLockExclusive)GetProcAddress(kernel32, "ReleaseSRWLockExclusive"); + pAcquireSRWLockExclusive = (pfnAcquireSRWLockExclusive)GetProcAddress(kernel32, "AcquireSRWLockExclusive"); + // Requires 7: + pTryAcquireSRWLockExclusive = (pfnTryAcquireSRWLockExclusive)GetProcAddress(kernel32, "TryAcquireSRWLockExclusive"); + if (pInitializeSRWLock && pReleaseSRWLockExclusive && pAcquireSRWLockExclusive && pTryAcquireSRWLockExclusive) { + impl = &SDL_mutex_impl_srw; + } + } + + // Copy instead of using pointer to save one level of indirection + SDL_copyp(&SDL_mutex_impl_active, impl); + } + return SDL_mutex_impl_active.Create(); +} + +void SDL_DestroyMutex(SDL_Mutex *mutex) +{ + if (mutex) { + SDL_mutex_impl_active.Destroy(mutex); + } +} + +void SDL_LockMutex(SDL_Mutex *mutex) +{ + if (mutex) { + SDL_mutex_impl_active.Lock(mutex); + } +} + +bool SDL_TryLockMutex(SDL_Mutex *mutex) +{ + bool result = true; + + if (mutex) { + result = SDL_mutex_impl_active.TryLock(mutex); + } + return result; +} + +void SDL_UnlockMutex(SDL_Mutex *mutex) +{ + if (mutex) { + SDL_mutex_impl_active.Unlock(mutex); + } +} + +#endif // SDL_THREAD_WINDOWS diff --git a/thirdparty/sdl/thread/windows/SDL_sysmutex_c.h b/thirdparty/sdl/thread/windows/SDL_sysmutex_c.h new file mode 100644 index 00000000000..762dc7c98cd --- /dev/null +++ b/thirdparty/sdl/thread/windows/SDL_sysmutex_c.h @@ -0,0 +1,73 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "../../core/windows/SDL_windows.h" + +typedef SDL_Mutex *(*pfnSDL_CreateMutex)(void); +typedef void (*pfnSDL_LockMutex)(SDL_Mutex *); +typedef bool (*pfnSDL_TryLockMutex)(SDL_Mutex *); +typedef void (*pfnSDL_UnlockMutex)(SDL_Mutex *); +typedef void (*pfnSDL_DestroyMutex)(SDL_Mutex *); + +typedef enum +{ + SDL_MUTEX_INVALID = 0, + SDL_MUTEX_SRW, + SDL_MUTEX_CS, +} SDL_MutexType; + +typedef struct SDL_mutex_impl_t +{ + pfnSDL_CreateMutex Create; + pfnSDL_DestroyMutex Destroy; + pfnSDL_LockMutex Lock; + pfnSDL_TryLockMutex TryLock; + pfnSDL_UnlockMutex Unlock; + // Needed by SDL_Condition: + SDL_MutexType Type; +} SDL_mutex_impl_t; + +extern SDL_mutex_impl_t SDL_mutex_impl_active; + +#ifndef SRWLOCK_INIT +#define SRWLOCK_INIT \ + { \ + 0 \ + } +typedef struct _SRWLOCK +{ + PVOID Ptr; +} SRWLOCK, *PSRWLOCK; +#endif + +typedef struct SDL_mutex_srw +{ + SRWLOCK srw; + // SRW Locks are not recursive, that has to be handled by SDL: + DWORD count; + DWORD owner; +} SDL_mutex_srw; + +typedef struct SDL_mutex_cs +{ + CRITICAL_SECTION cs; +} SDL_mutex_cs; diff --git a/thirdparty/sdl/thread/windows/SDL_sysrwlock_srw.c b/thirdparty/sdl/thread/windows/SDL_sysrwlock_srw.c new file mode 100644 index 00000000000..ca1a48eb843 --- /dev/null +++ b/thirdparty/sdl/thread/windows/SDL_sysrwlock_srw.c @@ -0,0 +1,231 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +/** + * Implementation based on Slim Reader/Writer (SRW) Locks for Win 7 and newer. + */ + +// This header makes sure SRWLOCK is actually declared, even on ancient WinSDKs. +#include "SDL_sysmutex_c.h" + +typedef VOID(WINAPI *pfnInitializeSRWLock)(PSRWLOCK); +typedef VOID(WINAPI *pfnReleaseSRWLockShared)(PSRWLOCK); +typedef VOID(WINAPI *pfnAcquireSRWLockShared)(PSRWLOCK); +typedef BOOLEAN(WINAPI *pfnTryAcquireSRWLockShared)(PSRWLOCK); +typedef VOID(WINAPI *pfnReleaseSRWLockExclusive)(PSRWLOCK); +typedef VOID(WINAPI *pfnAcquireSRWLockExclusive)(PSRWLOCK); +typedef BOOLEAN(WINAPI *pfnTryAcquireSRWLockExclusive)(PSRWLOCK); + +static pfnInitializeSRWLock pInitializeSRWLock = NULL; +static pfnReleaseSRWLockShared pReleaseSRWLockShared = NULL; +static pfnAcquireSRWLockShared pAcquireSRWLockShared = NULL; +static pfnTryAcquireSRWLockShared pTryAcquireSRWLockShared = NULL; +static pfnReleaseSRWLockExclusive pReleaseSRWLockExclusive = NULL; +static pfnAcquireSRWLockExclusive pAcquireSRWLockExclusive = NULL; +static pfnTryAcquireSRWLockExclusive pTryAcquireSRWLockExclusive = NULL; + +typedef SDL_RWLock *(*pfnSDL_CreateRWLock)(void); +typedef void (*pfnSDL_DestroyRWLock)(SDL_RWLock *); +typedef void (*pfnSDL_LockRWLockForReading)(SDL_RWLock *); +typedef void (*pfnSDL_LockRWLockForWriting)(SDL_RWLock *); +typedef bool (*pfnSDL_TryLockRWLockForReading)(SDL_RWLock *); +typedef bool (*pfnSDL_TryLockRWLockForWriting)(SDL_RWLock *); +typedef void (*pfnSDL_UnlockRWLock)(SDL_RWLock *); + +typedef struct SDL_rwlock_impl_t +{ + pfnSDL_CreateRWLock Create; + pfnSDL_DestroyRWLock Destroy; + pfnSDL_LockRWLockForReading LockForReading; + pfnSDL_LockRWLockForWriting LockForWriting; + pfnSDL_TryLockRWLockForReading TryLockForReading; + pfnSDL_TryLockRWLockForWriting TryLockForWriting; + pfnSDL_UnlockRWLock Unlock; +} SDL_rwlock_impl_t; + +// Implementation will be chosen at runtime based on available Kernel features +static SDL_rwlock_impl_t SDL_rwlock_impl_active = { 0 }; + +// rwlock implementation using Win7+ slim read/write locks (SRWLOCK) + +typedef struct SDL_rwlock_srw +{ + SRWLOCK srw; + SDL_ThreadID write_owner; +} SDL_rwlock_srw; + +static SDL_RWLock *SDL_CreateRWLock_srw(void) +{ + SDL_rwlock_srw *rwlock = (SDL_rwlock_srw *)SDL_calloc(1, sizeof(*rwlock)); + if (rwlock) { + pInitializeSRWLock(&rwlock->srw); + } + return (SDL_RWLock *)rwlock; +} + +static void SDL_DestroyRWLock_srw(SDL_RWLock *_rwlock) +{ + SDL_rwlock_srw *rwlock = (SDL_rwlock_srw *) _rwlock; + // There are no kernel allocated resources + SDL_free(rwlock); +} + +static void SDL_LockRWLockForReading_srw(SDL_RWLock *_rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + SDL_rwlock_srw *rwlock = (SDL_rwlock_srw *) _rwlock; + pAcquireSRWLockShared(&rwlock->srw); +} + +static void SDL_LockRWLockForWriting_srw(SDL_RWLock *_rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + SDL_rwlock_srw *rwlock = (SDL_rwlock_srw *) _rwlock; + pAcquireSRWLockExclusive(&rwlock->srw); + rwlock->write_owner = SDL_GetCurrentThreadID(); +} + +static bool SDL_TryLockRWLockForReading_srw(SDL_RWLock *_rwlock) +{ + SDL_rwlock_srw *rwlock = (SDL_rwlock_srw *) _rwlock; + return pTryAcquireSRWLockShared(&rwlock->srw); +} + +static bool SDL_TryLockRWLockForWriting_srw(SDL_RWLock *_rwlock) +{ + SDL_rwlock_srw *rwlock = (SDL_rwlock_srw *) _rwlock; + if (pTryAcquireSRWLockExclusive(&rwlock->srw)) { + rwlock->write_owner = SDL_GetCurrentThreadID(); + return true; + } else { + return false; + } +} + +static void SDL_UnlockRWLock_srw(SDL_RWLock *_rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + SDL_rwlock_srw *rwlock = (SDL_rwlock_srw *) _rwlock; + if (rwlock->write_owner == SDL_GetCurrentThreadID()) { + rwlock->write_owner = 0; + pReleaseSRWLockExclusive(&rwlock->srw); + } else { + pReleaseSRWLockShared(&rwlock->srw); + } +} + +static const SDL_rwlock_impl_t SDL_rwlock_impl_srw = { + &SDL_CreateRWLock_srw, + &SDL_DestroyRWLock_srw, + &SDL_LockRWLockForReading_srw, + &SDL_LockRWLockForWriting_srw, + &SDL_TryLockRWLockForReading_srw, + &SDL_TryLockRWLockForWriting_srw, + &SDL_UnlockRWLock_srw +}; + + +#include "../generic/SDL_sysrwlock_c.h" + +// Generic rwlock implementation using SDL_Mutex, SDL_Condition, and SDL_AtomicInt +static const SDL_rwlock_impl_t SDL_rwlock_impl_generic = { + &SDL_CreateRWLock_generic, + &SDL_DestroyRWLock_generic, + &SDL_LockRWLockForReading_generic, + &SDL_LockRWLockForWriting_generic, + &SDL_TryLockRWLockForReading_generic, + &SDL_TryLockRWLockForWriting_generic, + &SDL_UnlockRWLock_generic +}; + +SDL_RWLock *SDL_CreateRWLock(void) +{ + if (!SDL_rwlock_impl_active.Create) { + // Default to generic implementation, works with all mutex implementations + const SDL_rwlock_impl_t *impl = &SDL_rwlock_impl_generic; + { + HMODULE kernel32 = GetModuleHandle(TEXT("kernel32.dll")); + if (kernel32) { + bool okay = true; + #define LOOKUP_SRW_SYM(sym) if (okay) { if ((p##sym = (pfn##sym)GetProcAddress(kernel32, #sym)) == NULL) { okay = false; } } + LOOKUP_SRW_SYM(InitializeSRWLock); + LOOKUP_SRW_SYM(ReleaseSRWLockShared); + LOOKUP_SRW_SYM(AcquireSRWLockShared); + LOOKUP_SRW_SYM(TryAcquireSRWLockShared); + LOOKUP_SRW_SYM(ReleaseSRWLockExclusive); + LOOKUP_SRW_SYM(AcquireSRWLockExclusive); + LOOKUP_SRW_SYM(TryAcquireSRWLockExclusive); + #undef LOOKUP_SRW_SYM + if (okay) { + impl = &SDL_rwlock_impl_srw; // Use the Windows provided API instead of generic fallback + } + } + } + + SDL_copyp(&SDL_rwlock_impl_active, impl); + } + return SDL_rwlock_impl_active.Create(); +} + +void SDL_DestroyRWLock(SDL_RWLock *rwlock) +{ + if (rwlock) { + SDL_rwlock_impl_active.Destroy(rwlock); + } +} + +void SDL_LockRWLockForReading(SDL_RWLock *rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + if (rwlock) { + SDL_rwlock_impl_active.LockForReading(rwlock); + } +} + +void SDL_LockRWLockForWriting(SDL_RWLock *rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + if (rwlock) { + SDL_rwlock_impl_active.LockForWriting(rwlock); + } +} + +bool SDL_TryLockRWLockForReading(SDL_RWLock *rwlock) +{ + bool result = true; + if (rwlock) { + result = SDL_rwlock_impl_active.TryLockForReading(rwlock); + } + return result; +} + +bool SDL_TryLockRWLockForWriting(SDL_RWLock *rwlock) +{ + bool result = true; + if (rwlock) { + result = SDL_rwlock_impl_active.TryLockForWriting(rwlock); + } + return result; +} + +void SDL_UnlockRWLock(SDL_RWLock *rwlock) SDL_NO_THREAD_SAFETY_ANALYSIS // clang doesn't know about NULL mutexes +{ + if (rwlock) { + SDL_rwlock_impl_active.Unlock(rwlock); + } +} + diff --git a/thirdparty/sdl/thread/windows/SDL_syssem.c b/thirdparty/sdl/thread/windows/SDL_syssem.c new file mode 100644 index 00000000000..ba35add7d84 --- /dev/null +++ b/thirdparty/sdl/thread/windows/SDL_syssem.c @@ -0,0 +1,351 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_THREAD_WINDOWS + +/** + * Semaphore functions using the Win32 API + * There are two implementations available based on: + * - Kernel Semaphores. Available on all OS versions. (kern) + * Heavy-weight inter-process kernel objects. + * - Atomics and WaitOnAddress API. (atom) + * Faster due to significantly less context switches. + * Requires Windows 8 or newer. + * which are chosen at runtime. + */ + +#include "../../core/windows/SDL_windows.h" + +typedef SDL_Semaphore *(*pfnSDL_CreateSemaphore)(Uint32); +typedef void (*pfnSDL_DestroySemaphore)(SDL_Semaphore *); +typedef bool (*pfnSDL_WaitSemaphoreTimeoutNS)(SDL_Semaphore *, Sint64); +typedef Uint32 (*pfnSDL_GetSemaphoreValue)(SDL_Semaphore *); +typedef void (*pfnSDL_SignalSemaphore)(SDL_Semaphore *); + +typedef struct SDL_semaphore_impl_t +{ + pfnSDL_CreateSemaphore Create; + pfnSDL_DestroySemaphore Destroy; + pfnSDL_WaitSemaphoreTimeoutNS WaitTimeoutNS; + pfnSDL_GetSemaphoreValue Value; + pfnSDL_SignalSemaphore Signal; +} SDL_sem_impl_t; + +// Implementation will be chosen at runtime based on available Kernel features +static SDL_sem_impl_t SDL_sem_impl_active = { 0 }; + +/** + * Atomic + WaitOnAddress implementation + */ + +// APIs not available on WinPhone 8.1 +// https://www.microsoft.com/en-us/download/details.aspx?id=47328 + +typedef BOOL(WINAPI *pfnWaitOnAddress)(volatile VOID *, PVOID, SIZE_T, DWORD); +typedef VOID(WINAPI *pfnWakeByAddressSingle)(PVOID); + +static pfnWaitOnAddress pWaitOnAddress = NULL; +static pfnWakeByAddressSingle pWakeByAddressSingle = NULL; + +typedef struct SDL_semaphore_atom +{ + LONG count; +} SDL_sem_atom; + +static SDL_Semaphore *SDL_CreateSemaphore_atom(Uint32 initial_value) +{ + SDL_sem_atom *sem; + + sem = (SDL_sem_atom *)SDL_malloc(sizeof(*sem)); + if (sem) { + sem->count = initial_value; + } + return (SDL_Semaphore *)sem; +} + +static void SDL_DestroySemaphore_atom(SDL_Semaphore *sem) +{ + SDL_free(sem); +} + +static bool SDL_WaitSemaphoreTimeoutNS_atom(SDL_Semaphore *_sem, Sint64 timeoutNS) +{ + SDL_sem_atom *sem = (SDL_sem_atom *)_sem; + LONG count; + Uint64 now; + Uint64 deadline; + DWORD timeout_eff; + + if (!sem) { + return true; + } + + if (timeoutNS == 0) { + count = sem->count; + if (count == 0) { + return false; + } + + if (InterlockedCompareExchange(&sem->count, count - 1, count) == count) { + return true; + } + + return false; + } + + if (timeoutNS < 0) { + for (;;) { + count = sem->count; + while (count == 0) { + if (!pWaitOnAddress(&sem->count, &count, sizeof(sem->count), INFINITE)) { + return false; + } + count = sem->count; + } + + if (InterlockedCompareExchange(&sem->count, count - 1, count) == count) { + return true; + } + } + } + + /** + * WaitOnAddress is subject to spurious and stolen wakeups so we + * need to recalculate the effective timeout before every wait + */ + now = SDL_GetTicksNS(); + deadline = now + timeoutNS; + + for (;;) { + count = sem->count; + // If no semaphore is available we need to wait + while (count == 0) { + now = SDL_GetTicksNS(); + if (deadline > now) { + timeout_eff = (DWORD)SDL_NS_TO_MS(deadline - now); + } else { + return false; + } + if (!pWaitOnAddress(&sem->count, &count, sizeof(count), timeout_eff)) { + return false; + } + count = sem->count; + } + + // Actually the semaphore is only consumed if this succeeds + // If it doesn't we need to do everything again + if (InterlockedCompareExchange(&sem->count, count - 1, count) == count) { + return true; + } + } +} + +static Uint32 SDL_GetSemaphoreValue_atom(SDL_Semaphore *_sem) +{ + SDL_sem_atom *sem = (SDL_sem_atom *)_sem; + + if (!sem) { + return 0; + } + + return (Uint32)sem->count; +} + +static void SDL_SignalSemaphore_atom(SDL_Semaphore *_sem) +{ + SDL_sem_atom *sem = (SDL_sem_atom *)_sem; + + if (!sem) { + return; + } + + InterlockedIncrement(&sem->count); + pWakeByAddressSingle(&sem->count); +} + +static const SDL_sem_impl_t SDL_sem_impl_atom = { + &SDL_CreateSemaphore_atom, + &SDL_DestroySemaphore_atom, + &SDL_WaitSemaphoreTimeoutNS_atom, + &SDL_GetSemaphoreValue_atom, + &SDL_SignalSemaphore_atom, +}; + +/** + * Fallback Semaphore implementation using Kernel Semaphores + */ + +typedef struct SDL_semaphore_kern +{ + HANDLE id; + LONG count; +} SDL_sem_kern; + +// Create a semaphore +static SDL_Semaphore *SDL_CreateSemaphore_kern(Uint32 initial_value) +{ + SDL_sem_kern *sem; + + // Allocate sem memory + sem = (SDL_sem_kern *)SDL_malloc(sizeof(*sem)); + if (sem) { + // Create the semaphore, with max value 32K + sem->id = CreateSemaphore(NULL, initial_value, 32 * 1024, NULL); + sem->count = initial_value; + if (!sem->id) { + SDL_SetError("Couldn't create semaphore"); + SDL_free(sem); + sem = NULL; + } + } + return (SDL_Semaphore *)sem; +} + +// Free the semaphore +static void SDL_DestroySemaphore_kern(SDL_Semaphore *_sem) +{ + SDL_sem_kern *sem = (SDL_sem_kern *)_sem; + if (sem) { + if (sem->id) { + CloseHandle(sem->id); + sem->id = 0; + } + SDL_free(sem); + } +} + +static bool SDL_WaitSemaphoreTimeoutNS_kern(SDL_Semaphore *_sem, Sint64 timeoutNS) +{ + SDL_sem_kern *sem = (SDL_sem_kern *)_sem; + DWORD dwMilliseconds; + + if (!sem) { + return true; + } + + if (timeoutNS < 0) { + dwMilliseconds = INFINITE; + } else { + dwMilliseconds = (DWORD)SDL_NS_TO_MS(timeoutNS); + } + switch (WaitForSingleObjectEx(sem->id, dwMilliseconds, FALSE)) { + case WAIT_OBJECT_0: + InterlockedDecrement(&sem->count); + return true; + default: + return false; + } +} + +// Returns the current count of the semaphore +static Uint32 SDL_GetSemaphoreValue_kern(SDL_Semaphore *_sem) +{ + SDL_sem_kern *sem = (SDL_sem_kern *)_sem; + if (!sem) { + return 0; + } + return (Uint32)sem->count; +} + +static void SDL_SignalSemaphore_kern(SDL_Semaphore *_sem) +{ + SDL_sem_kern *sem = (SDL_sem_kern *)_sem; + + if (!sem) { + return; + } + + /* Increase the counter in the first place, because + * after a successful release the semaphore may + * immediately get destroyed by another thread which + * is waiting for this semaphore. + */ + InterlockedIncrement(&sem->count); + if (ReleaseSemaphore(sem->id, 1, NULL) == FALSE) { + InterlockedDecrement(&sem->count); // restore + } +} + +static const SDL_sem_impl_t SDL_sem_impl_kern = { + &SDL_CreateSemaphore_kern, + &SDL_DestroySemaphore_kern, + &SDL_WaitSemaphoreTimeoutNS_kern, + &SDL_GetSemaphoreValue_kern, + &SDL_SignalSemaphore_kern, +}; + +/** + * Runtime selection and redirection + */ + +SDL_Semaphore *SDL_CreateSemaphore(Uint32 initial_value) +{ + if (!SDL_sem_impl_active.Create) { + // Default to fallback implementation + const SDL_sem_impl_t *impl = &SDL_sem_impl_kern; + + if (!SDL_GetHintBoolean(SDL_HINT_WINDOWS_FORCE_SEMAPHORE_KERNEL, false)) { + /* We already statically link to features from this Api + * Set (e.g. WaitForSingleObject). Dynamically loading + * API Sets is not explicitly documented but according to + * Microsoft our specific use case is legal and correct: + * https://github.com/microsoft/STL/pull/593#issuecomment-655799859 + */ + HMODULE synch120 = GetModuleHandle(TEXT("api-ms-win-core-synch-l1-2-0.dll")); + if (synch120) { + // Try to load required functions provided by Win 8 or newer + pWaitOnAddress = (pfnWaitOnAddress)GetProcAddress(synch120, "WaitOnAddress"); + pWakeByAddressSingle = (pfnWakeByAddressSingle)GetProcAddress(synch120, "WakeByAddressSingle"); + + if (pWaitOnAddress && pWakeByAddressSingle) { + impl = &SDL_sem_impl_atom; + } + } + } + + // Copy instead of using pointer to save one level of indirection + SDL_copyp(&SDL_sem_impl_active, impl); + } + return SDL_sem_impl_active.Create(initial_value); +} + +void SDL_DestroySemaphore(SDL_Semaphore *sem) +{ + SDL_sem_impl_active.Destroy(sem); +} + +bool SDL_WaitSemaphoreTimeoutNS(SDL_Semaphore *sem, Sint64 timeoutNS) +{ + return SDL_sem_impl_active.WaitTimeoutNS(sem, timeoutNS); +} + +Uint32 SDL_GetSemaphoreValue(SDL_Semaphore *sem) +{ + return SDL_sem_impl_active.Value(sem); +} + +void SDL_SignalSemaphore(SDL_Semaphore *sem) +{ + SDL_sem_impl_active.Signal(sem); +} + +#endif // SDL_THREAD_WINDOWS diff --git a/thirdparty/sdl/thread/windows/SDL_systhread.c b/thirdparty/sdl/thread/windows/SDL_systhread.c new file mode 100644 index 00000000000..c5bee81f230 --- /dev/null +++ b/thirdparty/sdl/thread/windows/SDL_systhread.c @@ -0,0 +1,197 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_THREAD_WINDOWS + +// Win32 thread management routines for SDL + +#include "../SDL_thread_c.h" +#include "../SDL_systhread.h" +#include "SDL_systhread_c.h" + +#ifndef STACK_SIZE_PARAM_IS_A_RESERVATION +#define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000 +#endif + +#define SDL_DEBUGGER_NAME_EXCEPTION_CODE 0x406D1388 + +typedef void (__cdecl * SDL_EndThreadExCallback) (unsigned retval); +typedef uintptr_t (__cdecl * SDL_BeginThreadExCallback) + (void *security, unsigned stacksize, unsigned (__stdcall *startaddr)(void *), + void * arglist, unsigned initflag, unsigned *threadaddr); + +static DWORD RunThread(void *data) +{ + SDL_Thread *thread = (SDL_Thread *)data; + SDL_EndThreadExCallback pfnEndThread = (SDL_EndThreadExCallback)thread->endfunc; + SDL_RunThread(thread); + if (pfnEndThread) { + pfnEndThread(0); + } + return 0; +} + +static DWORD WINAPI MINGW32_FORCEALIGN RunThreadViaCreateThread(LPVOID data) +{ + return RunThread(data); +} + +static unsigned __stdcall MINGW32_FORCEALIGN RunThreadViaBeginThreadEx(void *data) +{ + return (unsigned)RunThread(data); +} + +bool SDL_SYS_CreateThread(SDL_Thread *thread, + SDL_FunctionPointer vpfnBeginThread, + SDL_FunctionPointer vpfnEndThread) +{ + SDL_BeginThreadExCallback pfnBeginThread = (SDL_BeginThreadExCallback) vpfnBeginThread; + + const DWORD flags = thread->stacksize ? STACK_SIZE_PARAM_IS_A_RESERVATION : 0; + + // Save the function which we will have to call to clear the RTL of calling app! + thread->endfunc = vpfnEndThread; + + // thread->stacksize == 0 means "system default", same as win32 expects + if (pfnBeginThread) { + unsigned threadid = 0; + thread->handle = (SYS_ThreadHandle)((size_t)pfnBeginThread(NULL, (unsigned int)thread->stacksize, + RunThreadViaBeginThreadEx, + thread, flags, &threadid)); + } else { + DWORD threadid = 0; + thread->handle = CreateThread(NULL, thread->stacksize, + RunThreadViaCreateThread, + thread, flags, &threadid); + } + if (!thread->handle) { + return SDL_SetError("Not enough resources to create thread"); + } + return true; +} + +#pragma pack(push, 8) +typedef struct tagTHREADNAME_INFO +{ + DWORD dwType; // must be 0x1000 + LPCSTR szName; // pointer to name (in user addr space) + DWORD dwThreadID; // thread ID (-1=caller thread) + DWORD dwFlags; // reserved for future use, must be zero +} THREADNAME_INFO; +#pragma pack(pop) + +static LONG NTAPI EmptyVectoredExceptionHandler(EXCEPTION_POINTERS *info) +{ + if (info != NULL && info->ExceptionRecord != NULL && info->ExceptionRecord->ExceptionCode == SDL_DEBUGGER_NAME_EXCEPTION_CODE) { + return EXCEPTION_CONTINUE_EXECUTION; + } else { + return EXCEPTION_CONTINUE_SEARCH; + } +} + +typedef HRESULT(WINAPI *pfnSetThreadDescription)(HANDLE, PCWSTR); + +void SDL_SYS_SetupThread(const char *name) +{ + if (name) { + PVOID exceptionHandlerHandle; + static pfnSetThreadDescription pSetThreadDescription = NULL; + static HMODULE kernel32 = NULL; + + if (!kernel32) { + kernel32 = GetModuleHandle(TEXT("kernel32.dll")); + if (kernel32) { + pSetThreadDescription = (pfnSetThreadDescription)GetProcAddress(kernel32, "SetThreadDescription"); + } + if (!kernel32 || !pSetThreadDescription) { + HMODULE kernelBase = GetModuleHandle(TEXT("KernelBase.dll")); + if (kernelBase) { + pSetThreadDescription = (pfnSetThreadDescription)GetProcAddress(kernelBase, "SetThreadDescription"); + } + } + } + + if (pSetThreadDescription) { + WCHAR *strw = WIN_UTF8ToStringW(name); + if (strw) { + pSetThreadDescription(GetCurrentThread(), strw); + SDL_free(strw); + } + } + + /* Presumably some version of Visual Studio will understand SetThreadDescription(), + but we still need to deal with older OSes and debuggers. Set it with the arcane + exception magic, too. */ + + exceptionHandlerHandle = AddVectoredExceptionHandler(1, EmptyVectoredExceptionHandler); + if (exceptionHandlerHandle) { + THREADNAME_INFO inf; + // This magic tells the debugger to name a thread if it's listening. + SDL_zero(inf); + inf.dwType = 0x1000; + inf.szName = name; + inf.dwThreadID = (DWORD)-1; + inf.dwFlags = 0; + + // The debugger catches this, renames the thread, continues on. + RaiseException(SDL_DEBUGGER_NAME_EXCEPTION_CODE, 0, sizeof(inf) / sizeof(ULONG_PTR), (const ULONG_PTR *)&inf); + RemoveVectoredExceptionHandler(exceptionHandlerHandle); + } + } +} + +SDL_ThreadID SDL_GetCurrentThreadID(void) +{ + return (SDL_ThreadID)GetCurrentThreadId(); +} + +bool SDL_SYS_SetThreadPriority(SDL_ThreadPriority priority) +{ + int value; + + if (priority == SDL_THREAD_PRIORITY_LOW) { + value = THREAD_PRIORITY_LOWEST; + } else if (priority == SDL_THREAD_PRIORITY_HIGH) { + value = THREAD_PRIORITY_HIGHEST; + } else if (priority == SDL_THREAD_PRIORITY_TIME_CRITICAL) { + value = THREAD_PRIORITY_TIME_CRITICAL; + } else { + value = THREAD_PRIORITY_NORMAL; + } + if (!SetThreadPriority(GetCurrentThread(), value)) { + return WIN_SetError("SetThreadPriority()"); + } + return true; +} + +void SDL_SYS_WaitThread(SDL_Thread *thread) +{ + WaitForSingleObjectEx(thread->handle, INFINITE, FALSE); + CloseHandle(thread->handle); +} + +void SDL_SYS_DetachThread(SDL_Thread *thread) +{ + CloseHandle(thread->handle); +} + +#endif // SDL_THREAD_WINDOWS diff --git a/thirdparty/sdl/thread/windows/SDL_systhread_c.h b/thirdparty/sdl/thread/windows/SDL_systhread_c.h new file mode 100644 index 00000000000..5787abb8d6a --- /dev/null +++ b/thirdparty/sdl/thread/windows/SDL_systhread_c.h @@ -0,0 +1,30 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_systhread_c_h_ +#define SDL_systhread_c_h_ + +#include "../../core/windows/SDL_windows.h" + +typedef HANDLE SYS_ThreadHandle; + +#endif // SDL_systhread_c_h_ diff --git a/thirdparty/sdl/thread/windows/SDL_systls.c b/thirdparty/sdl/thread/windows/SDL_systls.c new file mode 100644 index 00000000000..354016a7eb4 --- /dev/null +++ b/thirdparty/sdl/thread/windows/SDL_systls.c @@ -0,0 +1,81 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifdef SDL_THREAD_WINDOWS + +#include "../../core/windows/SDL_windows.h" + +#include "../SDL_thread_c.h" + +static DWORD thread_local_storage = TLS_OUT_OF_INDEXES; +static bool generic_local_storage = false; + +void SDL_SYS_InitTLSData(void) +{ + if (thread_local_storage == TLS_OUT_OF_INDEXES && !generic_local_storage) { + thread_local_storage = TlsAlloc(); + if (thread_local_storage == TLS_OUT_OF_INDEXES) { + SDL_Generic_InitTLSData(); + generic_local_storage = true; + } + } +} + +SDL_TLSData *SDL_SYS_GetTLSData(void) +{ + if (generic_local_storage) { + return SDL_Generic_GetTLSData(); + } + + if (thread_local_storage != TLS_OUT_OF_INDEXES) { + return (SDL_TLSData *)TlsGetValue(thread_local_storage); + } + return NULL; +} + +bool SDL_SYS_SetTLSData(SDL_TLSData *data) +{ + if (generic_local_storage) { + return SDL_Generic_SetTLSData(data); + } + + if (!TlsSetValue(thread_local_storage, data)) { + return WIN_SetError("TlsSetValue()"); + } + return true; +} + +void SDL_SYS_QuitTLSData(void) +{ + if (generic_local_storage) { + SDL_Generic_QuitTLSData(); + generic_local_storage = false; + } else { + if (thread_local_storage != TLS_OUT_OF_INDEXES) { + TlsFree(thread_local_storage); + thread_local_storage = TLS_OUT_OF_INDEXES; + } + } +} + +#endif // SDL_THREAD_WINDOWS diff --git a/thirdparty/sdl/timer/SDL_timer.c b/thirdparty/sdl/timer/SDL_timer.c new file mode 100644 index 00000000000..2fa65530377 --- /dev/null +++ b/thirdparty/sdl/timer/SDL_timer.c @@ -0,0 +1,734 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_timer_c.h" +#include "../thread/SDL_systhread.h" + +// #define DEBUG_TIMERS + +#if !defined(SDL_PLATFORM_EMSCRIPTEN) || !defined(SDL_THREADS_DISABLED) + +typedef struct SDL_Timer +{ + SDL_TimerID timerID; + SDL_TimerCallback callback_ms; + SDL_NSTimerCallback callback_ns; + void *userdata; + Uint64 interval; + Uint64 scheduled; + SDL_AtomicInt canceled; + struct SDL_Timer *next; +} SDL_Timer; + +typedef struct SDL_TimerMap +{ + SDL_TimerID timerID; + SDL_Timer *timer; + struct SDL_TimerMap *next; +} SDL_TimerMap; + +// The timers are kept in a sorted list +typedef struct +{ + // Data used by the main thread + SDL_InitState init; + SDL_Thread *thread; + SDL_TimerMap *timermap; + SDL_Mutex *timermap_lock; + + // Padding to separate cache lines between threads + char cache_pad[SDL_CACHELINE_SIZE]; + + // Data used to communicate with the timer thread + SDL_SpinLock lock; + SDL_Semaphore *sem; + SDL_Timer *pending; + SDL_Timer *freelist; + SDL_AtomicInt active; + + // List of timers - this is only touched by the timer thread + SDL_Timer *timers; +} SDL_TimerData; + +static SDL_TimerData SDL_timer_data; + +/* The idea here is that any thread might add a timer, but a single + * thread manages the active timer queue, sorted by scheduling time. + * + * Timers are removed by simply setting a canceled flag + */ + +static void SDL_AddTimerInternal(SDL_TimerData *data, SDL_Timer *timer) +{ + SDL_Timer *prev, *curr; + + prev = NULL; + for (curr = data->timers; curr; prev = curr, curr = curr->next) { + if (curr->scheduled > timer->scheduled) { + break; + } + } + + // Insert the timer here! + if (prev) { + prev->next = timer; + } else { + data->timers = timer; + } + timer->next = curr; +} + +static int SDLCALL SDL_TimerThread(void *_data) +{ + SDL_TimerData *data = (SDL_TimerData *)_data; + SDL_Timer *pending; + SDL_Timer *current; + SDL_Timer *freelist_head = NULL; + SDL_Timer *freelist_tail = NULL; + Uint64 tick, now, interval, delay; + + /* Threaded timer loop: + * 1. Queue timers added by other threads + * 2. Handle any timers that should dispatch this cycle + * 3. Wait until next dispatch time or new timer arrives + */ + for (;;) { + // Pending and freelist maintenance + SDL_LockSpinlock(&data->lock); + { + // Get any timers ready to be queued + pending = data->pending; + data->pending = NULL; + + // Make any unused timer structures available + if (freelist_head) { + freelist_tail->next = data->freelist; + data->freelist = freelist_head; + } + } + SDL_UnlockSpinlock(&data->lock); + + // Sort the pending timers into our list + while (pending) { + current = pending; + pending = pending->next; + SDL_AddTimerInternal(data, current); + } + freelist_head = NULL; + freelist_tail = NULL; + + // Check to see if we're still running, after maintenance + if (!SDL_GetAtomicInt(&data->active)) { + break; + } + + // Initial delay if there are no timers + delay = (Uint64)-1; + + tick = SDL_GetTicksNS(); + + // Process all the pending timers for this tick + while (data->timers) { + current = data->timers; + + if (tick < current->scheduled) { + // Scheduled for the future, wait a bit + delay = (current->scheduled - tick); + break; + } + + // We're going to do something with this timer + data->timers = current->next; + + if (SDL_GetAtomicInt(¤t->canceled)) { + interval = 0; + } else { + if (current->callback_ms) { + interval = SDL_MS_TO_NS(current->callback_ms(current->userdata, current->timerID, (Uint32)SDL_NS_TO_MS(current->interval))); + } else { + interval = current->callback_ns(current->userdata, current->timerID, current->interval); + } + } + + if (interval > 0) { + // Reschedule this timer + current->interval = interval; + current->scheduled = tick + interval; + SDL_AddTimerInternal(data, current); + } else { + if (!freelist_head) { + freelist_head = current; + } + if (freelist_tail) { + freelist_tail->next = current; + } + freelist_tail = current; + + SDL_SetAtomicInt(¤t->canceled, 1); + } + } + + // Adjust the delay based on processing time + now = SDL_GetTicksNS(); + interval = (now - tick); + if (interval > delay) { + delay = 0; + } else { + delay -= interval; + } + + /* Note that each time a timer is added, this will return + immediately, but we process the timers added all at once. + That's okay, it just means we run through the loop a few + extra times. + */ + SDL_WaitSemaphoreTimeoutNS(data->sem, delay); + } + return 0; +} + +bool SDL_InitTimers(void) +{ + SDL_TimerData *data = &SDL_timer_data; + + if (!SDL_ShouldInit(&data->init)) { + return true; + } + + data->timermap_lock = SDL_CreateMutex(); + if (!data->timermap_lock) { + goto error; + } + + data->sem = SDL_CreateSemaphore(0); + if (!data->sem) { + goto error; + } + + SDL_SetAtomicInt(&data->active, true); + + // Timer threads use a callback into the app, so we can't set a limited stack size here. + data->thread = SDL_CreateThread(SDL_TimerThread, "SDLTimer", data); + if (!data->thread) { + goto error; + } + + SDL_SetInitialized(&data->init, true); + return true; + +error: + SDL_SetInitialized(&data->init, true); + SDL_QuitTimers(); + return false; +} + +void SDL_QuitTimers(void) +{ + SDL_TimerData *data = &SDL_timer_data; + SDL_Timer *timer; + SDL_TimerMap *entry; + + if (!SDL_ShouldQuit(&data->init)) { + return; + } + + SDL_SetAtomicInt(&data->active, false); + + // Shutdown the timer thread + if (data->thread) { + SDL_SignalSemaphore(data->sem); + SDL_WaitThread(data->thread, NULL); + data->thread = NULL; + } + + if (data->sem) { + SDL_DestroySemaphore(data->sem); + data->sem = NULL; + } + + // Clean up the timer entries + while (data->timers) { + timer = data->timers; + data->timers = timer->next; + SDL_free(timer); + } + while (data->freelist) { + timer = data->freelist; + data->freelist = timer->next; + SDL_free(timer); + } + while (data->timermap) { + entry = data->timermap; + data->timermap = entry->next; + SDL_free(entry); + } + + if (data->timermap_lock) { + SDL_DestroyMutex(data->timermap_lock); + data->timermap_lock = NULL; + } + + SDL_SetInitialized(&data->init, false); +} + +static bool SDL_CheckInitTimers(void) +{ + return SDL_InitTimers(); +} + +static SDL_TimerID SDL_CreateTimer(Uint64 interval, SDL_TimerCallback callback_ms, SDL_NSTimerCallback callback_ns, void *userdata) +{ + SDL_TimerData *data = &SDL_timer_data; + SDL_Timer *timer; + SDL_TimerMap *entry; + + if (!callback_ms && !callback_ns) { + SDL_InvalidParamError("callback"); + return 0; + } + + if (!SDL_CheckInitTimers()) { + return 0; + } + + SDL_LockSpinlock(&data->lock); + timer = data->freelist; + if (timer) { + data->freelist = timer->next; + } + SDL_UnlockSpinlock(&data->lock); + + if (timer) { + SDL_RemoveTimer(timer->timerID); + } else { + timer = (SDL_Timer *)SDL_malloc(sizeof(*timer)); + if (!timer) { + return 0; + } + } + timer->timerID = SDL_GetNextObjectID(); + timer->callback_ms = callback_ms; + timer->callback_ns = callback_ns; + timer->userdata = userdata; + timer->interval = interval; + timer->scheduled = SDL_GetTicksNS() + timer->interval; + SDL_SetAtomicInt(&timer->canceled, 0); + + entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry)); + if (!entry) { + SDL_free(timer); + return 0; + } + entry->timer = timer; + entry->timerID = timer->timerID; + + SDL_LockMutex(data->timermap_lock); + entry->next = data->timermap; + data->timermap = entry; + SDL_UnlockMutex(data->timermap_lock); + + // Add the timer to the pending list for the timer thread + SDL_LockSpinlock(&data->lock); + timer->next = data->pending; + data->pending = timer; + SDL_UnlockSpinlock(&data->lock); + + // Wake up the timer thread if necessary + SDL_SignalSemaphore(data->sem); + + return entry->timerID; +} + +SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *userdata) +{ + return SDL_CreateTimer(SDL_MS_TO_NS(interval), callback, NULL, userdata); +} + +SDL_TimerID SDL_AddTimerNS(Uint64 interval, SDL_NSTimerCallback callback, void *userdata) +{ + return SDL_CreateTimer(interval, NULL, callback, userdata); +} + +bool SDL_RemoveTimer(SDL_TimerID id) +{ + SDL_TimerData *data = &SDL_timer_data; + SDL_TimerMap *prev, *entry; + bool canceled = false; + + if (!id) { + return SDL_InvalidParamError("id"); + } + + // Find the timer + SDL_LockMutex(data->timermap_lock); + prev = NULL; + for (entry = data->timermap; entry; prev = entry, entry = entry->next) { + if (entry->timerID == id) { + if (prev) { + prev->next = entry->next; + } else { + data->timermap = entry->next; + } + break; + } + } + SDL_UnlockMutex(data->timermap_lock); + + if (entry) { + if (!SDL_GetAtomicInt(&entry->timer->canceled)) { + SDL_SetAtomicInt(&entry->timer->canceled, 1); + canceled = true; + } + SDL_free(entry); + } + if (canceled) { + return true; + } else { + return SDL_SetError("Timer not found"); + } +} + +#else + +#include +#include + +typedef struct SDL_TimerMap +{ + SDL_TimerID timerID; + int timeoutID; + Uint64 interval; + SDL_TimerCallback callback_ms; + SDL_NSTimerCallback callback_ns; + void *userdata; + struct SDL_TimerMap *next; +} SDL_TimerMap; + +typedef struct +{ + SDL_TimerMap *timermap; +} SDL_TimerData; + +static SDL_TimerData SDL_timer_data; + +static void SDL_Emscripten_TimerHelper(void *userdata) +{ + SDL_TimerMap *entry = (SDL_TimerMap *)userdata; + if (entry->callback_ms) { + entry->interval = SDL_MS_TO_NS(entry->callback_ms(entry->userdata, entry->timerID, (Uint32)SDL_NS_TO_MS(entry->interval))); + } else { + entry->interval = entry->callback_ns(entry->userdata, entry->timerID, entry->interval); + } + if (entry->interval > 0) { + entry->timeoutID = emscripten_set_timeout(&SDL_Emscripten_TimerHelper, + SDL_NS_TO_MS(entry->interval), + entry); + } +} + +bool SDL_InitTimers(void) +{ + return true; +} + +void SDL_QuitTimers(void) +{ + SDL_TimerData *data = &SDL_timer_data; + SDL_TimerMap *entry; + + while (data->timermap) { + entry = data->timermap; + data->timermap = entry->next; + SDL_free(entry); + } +} + +static SDL_TimerID SDL_CreateTimer(Uint64 interval, SDL_TimerCallback callback_ms, SDL_NSTimerCallback callback_ns, void *userdata) +{ + SDL_TimerData *data = &SDL_timer_data; + SDL_TimerMap *entry; + + if (!callback_ms && !callback_ns) { + SDL_InvalidParamError("callback"); + return 0; + } + + entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry)); + if (!entry) { + return 0; + } + entry->timerID = SDL_GetNextObjectID(); + entry->callback_ms = callback_ms; + entry->callback_ns = callback_ns; + entry->userdata = userdata; + entry->interval = interval; + + entry->timeoutID = emscripten_set_timeout(&SDL_Emscripten_TimerHelper, + SDL_NS_TO_MS(entry->interval), + entry); + + entry->next = data->timermap; + data->timermap = entry; + + return entry->timerID; +} + +SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *userdata) +{ + return SDL_CreateTimer(SDL_MS_TO_NS(interval), callback, NULL, userdata); +} + +SDL_TimerID SDL_AddTimerNS(Uint64 interval, SDL_NSTimerCallback callback, void *userdata) +{ + return SDL_CreateTimer(interval, NULL, callback, userdata); +} + +bool SDL_RemoveTimer(SDL_TimerID id) +{ + SDL_TimerData *data = &SDL_timer_data; + SDL_TimerMap *prev, *entry; + + if (!id) { + return SDL_InvalidParamError("id"); + } + + // Find the timer + prev = NULL; + for (entry = data->timermap; entry; prev = entry, entry = entry->next) { + if (entry->timerID == id) { + if (prev) { + prev->next = entry->next; + } else { + data->timermap = entry->next; + } + break; + } + } + + if (entry) { + emscripten_clear_timeout(entry->timeoutID); + SDL_free(entry); + return true; + } else { + return SDL_SetError("Timer not found"); + } +} + +#endif // !SDL_PLATFORM_EMSCRIPTEN || !SDL_THREADS_DISABLED + +static Uint64 tick_start; +static Uint32 tick_numerator_ns; +static Uint32 tick_denominator_ns; +static Uint32 tick_numerator_ms; +static Uint32 tick_denominator_ms; + +#if defined(SDL_TIMER_WINDOWS) && !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) +#include +#define HAVE_TIME_BEGIN_PERIOD +#endif + +static void SDL_SetSystemTimerResolutionMS(int period) +{ +#ifdef HAVE_TIME_BEGIN_PERIOD + static int timer_period = 0; + + if (period != timer_period) { + if (timer_period) { + timeEndPeriod((UINT)timer_period); + } + + timer_period = period; + + if (timer_period) { + timeBeginPeriod((UINT)timer_period); + } + } +#endif // HAVE_TIME_BEGIN_PERIOD +} + +static void SDLCALL SDL_TimerResolutionChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +{ + int period; + + // Unless the hint says otherwise, let's have good sleep precision + if (hint && *hint) { + period = SDL_atoi(hint); + } else { + period = 1; + } + if (period || oldValue != hint) { + SDL_SetSystemTimerResolutionMS(period); + } +} + +void SDL_InitTicks(void) +{ + Uint64 tick_freq; + Uint32 gcd; + + if (tick_start) { + return; + } + + /* If we didn't set a precision, set it high. This affects lots of things + on Windows besides the SDL timers, like audio callbacks, etc. */ + SDL_AddHintCallback(SDL_HINT_TIMER_RESOLUTION, + SDL_TimerResolutionChanged, NULL); + + tick_freq = SDL_GetPerformanceFrequency(); + SDL_assert(tick_freq > 0 && tick_freq <= (Uint64)SDL_MAX_UINT32); + + gcd = SDL_CalculateGCD(SDL_NS_PER_SECOND, (Uint32)tick_freq); + tick_numerator_ns = (SDL_NS_PER_SECOND / gcd); + tick_denominator_ns = (Uint32)(tick_freq / gcd); + + gcd = SDL_CalculateGCD(SDL_MS_PER_SECOND, (Uint32)tick_freq); + tick_numerator_ms = (SDL_MS_PER_SECOND / gcd); + tick_denominator_ms = (Uint32)(tick_freq / gcd); + + tick_start = SDL_GetPerformanceCounter(); + if (!tick_start) { + --tick_start; + } +} + +void SDL_QuitTicks(void) +{ + SDL_RemoveHintCallback(SDL_HINT_TIMER_RESOLUTION, + SDL_TimerResolutionChanged, NULL); + + SDL_SetSystemTimerResolutionMS(0); // always release our timer resolution request. + + tick_start = 0; +} + +Uint64 SDL_GetTicksNS(void) +{ + Uint64 starting_value, value; + + if (!tick_start) { + SDL_InitTicks(); + } + + starting_value = (SDL_GetPerformanceCounter() - tick_start); + value = (starting_value * tick_numerator_ns); + SDL_assert(value >= starting_value); + value /= tick_denominator_ns; + return value; +} + +Uint64 SDL_GetTicks(void) +{ + Uint64 starting_value, value; + + if (!tick_start) { + SDL_InitTicks(); + } + + starting_value = (SDL_GetPerformanceCounter() - tick_start); + value = (starting_value * tick_numerator_ms); + SDL_assert(value >= starting_value); + value /= tick_denominator_ms; + return value; +} + +void SDL_Delay(Uint32 ms) +{ + SDL_SYS_DelayNS(SDL_MS_TO_NS(ms)); +} + +void SDL_DelayNS(Uint64 ns) +{ + SDL_SYS_DelayNS(ns); +} + +void SDL_DelayPrecise(Uint64 ns) +{ + Uint64 current_value = SDL_GetTicksNS(); + const Uint64 target_value = current_value + ns; + + // Sleep for a short number of cycles when real sleeps are desired. + // We'll use 1 ms, it's the minimum guaranteed to produce real sleeps across + // all platforms. + const Uint64 SHORT_SLEEP_NS = 1 * SDL_NS_PER_MS; + + // Try to sleep short of target_value. If for some crazy reason + // a particular platform sleeps for less than 1 ms when 1 ms was requested, + // that's fine, the code below can cope with that, but in practice no + // platforms behave that way. + Uint64 max_sleep_ns = SHORT_SLEEP_NS; + while (current_value + max_sleep_ns < target_value) { + // Sleep for a short time + SDL_SYS_DelayNS(SHORT_SLEEP_NS); + + const Uint64 now = SDL_GetTicksNS(); + const Uint64 next_sleep_ns = (now - current_value); + if (next_sleep_ns > max_sleep_ns) { + max_sleep_ns = next_sleep_ns; + } + current_value = now; + } + + // Do a shorter sleep of the remaining time here, less the max overshoot in + // the first loop. Due to maintaining max_sleep_ns as + // greater-than-or-equal-to-1 ms, we can always subtract off 1 ms to get + // the duration overshot beyond a 1 ms sleep request; if the system never + // overshot, great, it's zero duration. By choosing the max overshoot + // amount, we're likely to not overshoot here. If the sleep here ends up + // functioning like SDL_DelayNS(0) internally, that's fine, we just don't + // get to do a more-precise-than-1 ms-resolution sleep to undershoot by a + // small amount on the current system, but SDL_DelayNS(0) does at least + // introduce a small, yielding delay on many platforms, better than an + // unyielding busyloop. + // + // Note that we'll always do at least one sleep in this function, so the + // minimum resolution will be that of SDL_SYS_DelayNS() + if (current_value < target_value && (target_value - current_value) > (max_sleep_ns - SHORT_SLEEP_NS)) { + const Uint64 delay_ns = (target_value - current_value) - (max_sleep_ns - SHORT_SLEEP_NS); + SDL_SYS_DelayNS(delay_ns); + current_value = SDL_GetTicksNS(); + } + + // We've likely undershot target_value at this point by a pretty small + // amount, but maybe not. The footgun case if not handled here is where + // we've undershot by a large amount, like several ms, but still smaller + // than the amount max_sleep_ns overshot by; in such a situation, the above + // shorter-sleep block didn't do any delay, the if-block wasn't entered. + // Also, maybe the shorter-sleep undershot by several ms, so we still don't + // want to spin a lot then. In such a case, we accept the possibility of + // overshooting to not spin much, or if overshot here, not at all, keeping + // CPU/power usage down in any case. Due to scheduler sloppiness, it's + // entirely possible to end up undershooting/overshooting here by much less + // than 1 ms even if the current system's sleep function is only 1 + // ms-resolution, as SDL_GetTicksNS() generally is better resolution than 1 + // ms on the systems SDL supports. + while (current_value + SHORT_SLEEP_NS < target_value) { + SDL_SYS_DelayNS(SHORT_SLEEP_NS); + current_value = SDL_GetTicksNS(); + } + + // Spin for any remaining time + while (current_value < target_value) { + SDL_CPUPauseInstruction(); + current_value = SDL_GetTicksNS(); + } +} diff --git a/thirdparty/sdl/timer/SDL_timer_c.h b/thirdparty/sdl/timer/SDL_timer_c.h new file mode 100644 index 00000000000..18d817167ad --- /dev/null +++ b/thirdparty/sdl/timer/SDL_timer_c.h @@ -0,0 +1,39 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_timer_c_h_ +#define SDL_timer_c_h_ + +#include "SDL_internal.h" + +// Useful functions and variables from SDL_timer.c + +#define ROUND_RESOLUTION(X) \ + (((X + TIMER_RESOLUTION - 1) / TIMER_RESOLUTION) * TIMER_RESOLUTION) + +extern void SDL_InitTicks(void); +extern void SDL_QuitTicks(void); +extern bool SDL_InitTimers(void); +extern void SDL_QuitTimers(void); + +extern void SDL_SYS_DelayNS(Uint64 ns); + +#endif // SDL_timer_c_h_ diff --git a/thirdparty/sdl/timer/unix/SDL_systimer.c b/thirdparty/sdl/timer/unix/SDL_systimer.c new file mode 100644 index 00000000000..0f96319af79 --- /dev/null +++ b/thirdparty/sdl/timer/unix/SDL_systimer.c @@ -0,0 +1,188 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_TIMER_UNIX + +#include +#include +#include +#include + +#include "../SDL_timer_c.h" + +#ifdef SDL_PLATFORM_EMSCRIPTEN +#include +#endif + +/* The clock_gettime provides monotonous time, so we should use it if + it's available. The clock_gettime function is behind ifdef + for __USE_POSIX199309 + Tommi Kyntola (tommi.kyntola@ray.fi) 27/09/2005 +*/ +/* Reworked monotonic clock to not assume the current system has one + as not all linux kernels provide a monotonic clock (yeah recent ones + probably do) + Also added macOS Monotonic clock support + Based on work in https://github.com/ThomasHabets/monotonic_clock + */ +#if defined(HAVE_NANOSLEEP) || defined(HAVE_CLOCK_GETTIME) +#include +#endif +#ifdef SDL_PLATFORM_APPLE +#include +#endif + +// Use CLOCK_MONOTONIC_RAW, if available, which is not subject to adjustment by NTP +#ifdef HAVE_CLOCK_GETTIME +#ifdef CLOCK_MONOTONIC_RAW +#define SDL_MONOTONIC_CLOCK CLOCK_MONOTONIC_RAW +#else +#define SDL_MONOTONIC_CLOCK CLOCK_MONOTONIC +#endif +#endif + +// The first ticks value of the application +#if !defined(HAVE_CLOCK_GETTIME) && defined(SDL_PLATFORM_APPLE) +mach_timebase_info_data_t mach_base_info; +#endif +static bool checked_monotonic_time = false; +static bool has_monotonic_time = false; + +static void CheckMonotonicTime(void) +{ +#ifdef HAVE_CLOCK_GETTIME + struct timespec value; + if (clock_gettime(SDL_MONOTONIC_CLOCK, &value) == 0) { + has_monotonic_time = true; + } +#elif defined(SDL_PLATFORM_APPLE) + if (mach_timebase_info(&mach_base_info) == 0) { + has_monotonic_time = true; + } +#endif + checked_monotonic_time = true; +} + +Uint64 SDL_GetPerformanceCounter(void) +{ + Uint64 ticks; + + if (!checked_monotonic_time) { + CheckMonotonicTime(); + } + + if (has_monotonic_time) { +#ifdef HAVE_CLOCK_GETTIME + struct timespec now; + + clock_gettime(SDL_MONOTONIC_CLOCK, &now); + ticks = now.tv_sec; + ticks *= SDL_NS_PER_SECOND; + ticks += now.tv_nsec; +#elif defined(SDL_PLATFORM_APPLE) + ticks = mach_absolute_time(); +#else + SDL_assert(false); + ticks = 0; +#endif + } else { + struct timeval now; + + gettimeofday(&now, NULL); + ticks = now.tv_sec; + ticks *= SDL_US_PER_SECOND; + ticks += now.tv_usec; + } + return ticks; +} + +Uint64 SDL_GetPerformanceFrequency(void) +{ + if (!checked_monotonic_time) { + CheckMonotonicTime(); + } + + if (has_monotonic_time) { +#ifdef HAVE_CLOCK_GETTIME + return SDL_NS_PER_SECOND; +#elif defined(SDL_PLATFORM_APPLE) + Uint64 freq = mach_base_info.denom; + freq *= SDL_NS_PER_SECOND; + freq /= mach_base_info.numer; + return freq; +#endif + } + + return SDL_US_PER_SECOND; +} + +void SDL_SYS_DelayNS(Uint64 ns) +{ + int was_error; + +#ifdef HAVE_NANOSLEEP + struct timespec tv, remaining; +#else + struct timeval tv; + Uint64 then, now, elapsed; +#endif + +#ifdef SDL_PLATFORM_EMSCRIPTEN + if (emscripten_has_asyncify() && SDL_GetHintBoolean(SDL_HINT_EMSCRIPTEN_ASYNCIFY, true)) { + // pseudo-synchronous pause, used directly or through e.g. SDL_WaitEvent + emscripten_sleep(ns / SDL_NS_PER_MS); + return; + } +#endif + + // Set the timeout interval +#ifdef HAVE_NANOSLEEP + remaining.tv_sec = (time_t)(ns / SDL_NS_PER_SECOND); + remaining.tv_nsec = (long)(ns % SDL_NS_PER_SECOND); +#else + then = SDL_GetTicksNS(); +#endif + do { + errno = 0; + +#ifdef HAVE_NANOSLEEP + tv.tv_sec = remaining.tv_sec; + tv.tv_nsec = remaining.tv_nsec; + was_error = nanosleep(&tv, &remaining); +#else + // Calculate the time interval left (in case of interrupt) + now = SDL_GetTicksNS(); + elapsed = (now - then); + then = now; + if (elapsed >= ns) { + break; + } + ns -= elapsed; + tv.tv_sec = (ns / SDL_NS_PER_SECOND); + tv.tv_usec = SDL_NS_TO_US(ns % SDL_NS_PER_SECOND); + + was_error = select(0, NULL, NULL, NULL, &tv); +#endif // HAVE_NANOSLEEP + } while (was_error && (errno == EINTR)); +} + +#endif // SDL_TIMER_UNIX diff --git a/thirdparty/sdl/timer/windows/SDL_systimer.c b/thirdparty/sdl/timer/windows/SDL_systimer.c new file mode 100644 index 00000000000..f6f4b15c72b --- /dev/null +++ b/thirdparty/sdl/timer/windows/SDL_systimer.c @@ -0,0 +1,133 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_TIMER_WINDOWS + +#include "../../core/windows/SDL_windows.h" + +/* CREATE_WAITABLE_TIMER_HIGH_RESOLUTION flag was added in Windows 10 version 1803. */ +#ifndef CREATE_WAITABLE_TIMER_HIGH_RESOLUTION +#define CREATE_WAITABLE_TIMER_HIGH_RESOLUTION 0x2 +#endif + +typedef HANDLE (WINAPI *CreateWaitableTimerExW_t)(LPSECURITY_ATTRIBUTES lpTimerAttributes, LPCWSTR lpTimerName, DWORD dwFlags, DWORD dwDesiredAccess); +static CreateWaitableTimerExW_t pCreateWaitableTimerExW; + +typedef BOOL (WINAPI *SetWaitableTimerEx_t)(HANDLE hTimer, const LARGE_INTEGER *lpDueTime, LONG lPeriod, PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, PREASON_CONTEXT WakeContext, ULONG TolerableDelay); +static SetWaitableTimerEx_t pSetWaitableTimerEx; + +static void SDL_CleanupWaitableHandle(void *handle) +{ + CloseHandle(handle); +} + +static HANDLE SDL_GetWaitableTimer(void) +{ + static SDL_TLSID TLS_timer_handle; + HANDLE timer; + + if (!pCreateWaitableTimerExW || !pSetWaitableTimerEx) { + static bool initialized; + + if (!initialized) { + HMODULE module = GetModuleHandle(TEXT("kernel32.dll")); + if (module) { + pCreateWaitableTimerExW = (CreateWaitableTimerExW_t)GetProcAddress(module, "CreateWaitableTimerExW"); + pSetWaitableTimerEx = (SetWaitableTimerEx_t)GetProcAddress(module, "SetWaitableTimerEx"); + } + initialized = true; + } + + if (!pCreateWaitableTimerExW || !pSetWaitableTimerEx) { + return NULL; + } + } + + timer = SDL_GetTLS(&TLS_timer_handle); + if (!timer) { + timer = pCreateWaitableTimerExW(NULL, NULL, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); + if (timer) { + SDL_SetTLS(&TLS_timer_handle, timer, SDL_CleanupWaitableHandle); + } + } + return timer; +} + +static HANDLE SDL_GetWaitableEvent(void) +{ + static SDL_TLSID TLS_event_handle; + HANDLE event; + + event = SDL_GetTLS(&TLS_event_handle); + if (!event) { + event = CreateEvent(NULL, FALSE, FALSE, NULL); + if (event) { + SDL_SetTLS(&TLS_event_handle, event, SDL_CleanupWaitableHandle); + } + } + return event; +} + +Uint64 SDL_GetPerformanceCounter(void) +{ + LARGE_INTEGER counter; + const BOOL rc = QueryPerformanceCounter(&counter); + SDL_assert(rc != 0); // this should _never_ fail if you're on XP or later. + return (Uint64)counter.QuadPart; +} + +Uint64 SDL_GetPerformanceFrequency(void) +{ + LARGE_INTEGER frequency; + const BOOL rc = QueryPerformanceFrequency(&frequency); + SDL_assert(rc != 0); // this should _never_ fail if you're on XP or later. + return (Uint64)frequency.QuadPart; +} + +void SDL_SYS_DelayNS(Uint64 ns) +{ + HANDLE timer = SDL_GetWaitableTimer(); + if (timer) { + LARGE_INTEGER due_time; + due_time.QuadPart = -((LONGLONG)ns / 100); + if (pSetWaitableTimerEx(timer, &due_time, 0, NULL, NULL, NULL, 0)) { + WaitForSingleObject(timer, INFINITE); + } + return; + } + + const Uint64 max_delay = 0xffffffffLL * SDL_NS_PER_MS; + if (ns > max_delay) { + ns = max_delay; + } + const DWORD delay = (DWORD)SDL_NS_TO_MS(ns); + + HANDLE event = SDL_GetWaitableEvent(); + if (event) { + WaitForSingleObjectEx(event, delay, FALSE); + return; + } + + Sleep(delay); +} + +#endif // SDL_TIMER_WINDOWS diff --git a/thirdparty/sdl/update-sdl.sh b/thirdparty/sdl/update-sdl.sh new file mode 100755 index 00000000000..77ad3b2149b --- /dev/null +++ b/thirdparty/sdl/update-sdl.sh @@ -0,0 +1,87 @@ +#!/bin/bash -e + +VERSION=3.2.16 + +target=$(dirname "$(realpath $0)") +pushd $target + +rm -rf atomic core events haptic hidapi include io joystick libm loadso \ + sensor stdlib thread timer *.c *.h CREDITS.md LICENSE.txt +rm -rf *.tar.gz tmp + +mkdir tmp && pushd tmp + +echo "Updating SDL3 to version:" $VERSION +curl -L -O https://github.com/libsdl-org/SDL/archive/release-$VERSION.tar.gz + +tar --strip-components=1 -xvf release-$VERSION.tar.gz +rm release-$VERSION.tar.gz + +# We aim to copy only the minimum amount of files needed, so we don't need to +# vendor and compile more source code than necessary. + +cp -v CREDITS.md LICENSE.txt $target + +# Includes. +# For build config, we use a single private one in the driver. +# We might reconsider as we make more platforms use SDL. +cp -rv include $target +rm -f $target/include/build_config/{*.cmake,SDL_build_config_*.h} $target +rm -f $target/include/SDL3/SDL_{egl,gpu,oldnames,opengl*,test*,vulkan}.h $target + +pushd src + +# Shared dependencies + +cp -rv *.{c,h} atomic libm stdlib $target +rm -f $target/stdlib/*.masm + +# Only some files needed + +mkdir $target/events +cp -v events/SDL_{event*.{c,h},mouse_c.h} $target/events + +mkdir $target/io +cp -v io/SDL_iostream*.{c,h} $target/io + +# Platform specific + +mkdir $target/core +cp -rv core/{linux,unix,windows} $target/core +rm -f $target/core/windows/version.rc + +mkdir $target/haptic +cp -rv haptic/{*.{c,h},darwin,linux,windows} $target/haptic + +mkdir $target/joystick +cp -rv joystick/{*.{c,h},apple,darwin,hidapi,linux,windows} $target/joystick + +mkdir $target/loadso +cp -rv loadso/dlopen $target/loadso + +mkdir $target/sensor +cp -rv sensor/{*.{c,h},dummy} $target/sensor + +mkdir $target/thread +cp -rv thread/{*.{c,h},generic,pthread,windows} $target/thread +rm -f $target/thread/generic/SDL_{sysmutex*.{c,h},systls.c} + +mkdir $target/timer +cp -rv timer/{*.{c,h},unix,windows} $target/timer + +# HIDAPI + +mkdir -p $target/hidapi +cp -v hidapi/{*.{c,h},AUTHORS.txt,LICENSE.txt,LICENSE-bsd.txt,VERSION} $target/hidapi +for dir in hidapi linux mac windows; do + mkdir $target/hidapi/$dir + cp -v hidapi/$dir/*.{c,h} $target/hidapi/$dir +done + +popd +popd +rm -rf tmp +popd + +echo "SDL3 source code copied successfully. Review 'git status' for potential new files to compile or remove." +echo "Make sure to re-apply patches from the 'patches' folder if any are provided."