diff --git a/.github/workflows/build-and-publish.yml b/.github/workflows/build-and-publish.yml index 68da432..8f55f05 100644 --- a/.github/workflows/build-and-publish.yml +++ b/.github/workflows/build-and-publish.yml @@ -81,7 +81,7 @@ jobs: if: matrix.platform == 'linux' run: | sudo apt-get update - sudo apt-get install -y libx11-dev + sudo apt-get install -y libx11-dev libudev-dev - name: Build native library run: | diff --git a/CMakeLists.txt b/CMakeLists.txt index 0792eae..dbb34a4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.15) +cmake_minimum_required(VERSION 3.16) project(VpeNativeInput VERSION 1.0.0 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 17) @@ -18,14 +18,16 @@ set(SOURCES # Platform-specific sources if(WIN32) list(APPEND SOURCES src/NativeInput_Windows.cpp) - set(PLATFORM_LIBS winmm hid setupapi cfgmgr32) + set(PLATFORM_LIBS winmm hid setupapi cfgmgr32 user32) elseif(APPLE) - list(APPEND SOURCES src/NativeInput_Mac.mm) + list(APPEND SOURCES src/NativeInput_Mac.mm src/OpenPinballInput.cpp src/OpenPinballMac.cpp) find_library(APPKIT_FRAMEWORK AppKit REQUIRED) find_library(APPLICATION_SERVICES_FRAMEWORK ApplicationServices REQUIRED) - set(PLATFORM_LIBS ${APPKIT_FRAMEWORK} ${APPLICATION_SERVICES_FRAMEWORK}) -elseif(UNIX) - list(APPEND SOURCES src/NativeInput_Linux.cpp) + find_library(CORE_FOUNDATION_FRAMEWORK CoreFoundation REQUIRED) + find_library(IOKIT_FRAMEWORK IOKit REQUIRED) + set(PLATFORM_LIBS ${APPKIT_FRAMEWORK} ${APPLICATION_SERVICES_FRAMEWORK} ${CORE_FOUNDATION_FRAMEWORK} ${IOKIT_FRAMEWORK}) +elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") + list(APPEND SOURCES src/NativeInput_Linux.cpp src/OpenPinballInput.cpp src/OpenPinballLinux.cpp) find_package(Threads REQUIRED) find_package(X11 REQUIRED) set(PLATFORM_LIBS Threads::Threads ${X11_LIBRARIES}) @@ -33,6 +35,35 @@ else() list(APPEND SOURCES src/NativeInput_Stub.cpp) set(PLATFORM_LIBS) endif() + +if(WIN32 OR APPLE OR CMAKE_SYSTEM_NAME STREQUAL "Linux") + include(FetchContent) + set(SDL_SHARED OFF CACHE BOOL "" FORCE) + set(SDL_STATIC ON CACHE BOOL "" FORCE) + set(SDL_INSTALL OFF CACHE BOOL "" FORCE) + set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE) + set(SDL_HIDAPI_LIBUSB OFF CACHE BOOL "" FORCE) + set(SDL_UNIX_CONSOLE_BUILD ON CACHE BOOL "" FORCE) + foreach(subsystem AUDIO VIDEO HAPTIC POWER SENSOR DIALOG TRAY) + set(SDL_${subsystem} OFF CACHE BOOL "" FORCE) + endforeach() + if(APPLE) + # SDL's macOS HIDAPI driver runs its own report thread. The IOKit and + # GameController joystick drivers can be sampled by our polling thread. + set(SDL_HIDAPI_JOYSTICK OFF CACHE BOOL "" FORCE) + endif() + if(POLICY CMP0135) + cmake_policy(SET CMP0135 NEW) + endif() + FetchContent_Declare(SDL3 + URL https://github.com/libsdl-org/SDL/releases/download/release-3.4.20/SDL3-3.4.20.tar.gz + URL_HASH SHA256=f3bb06f55bed9557227a700af2ea62e49497ebdf58037732a731a5fb3ef8581f) + FetchContent_MakeAvailable(SDL3) + set_target_properties(SDL3-static PROPERTIES POSITION_INDEPENDENT_CODE ON C_VISIBILITY_PRESET hidden) + target_compile_definitions(SDL3-static PRIVATE SDL_DECLSPEC=) + list(APPEND SOURCES src/ControllerInput.cpp src/NativeButtons.cpp) + list(APPEND PLATFORM_LIBS SDL3::SDL3-static) +endif() # Create shared library add_library(VpeNativeInput SHARED ${SOURCES}) @@ -44,7 +75,7 @@ endif() # Link platform libraries target_link_libraries(VpeNativeInput PRIVATE ${PLATFORM_LIBS}) -if(UNIX AND NOT APPLE) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") target_include_directories(VpeNativeInput PRIVATE ${X11_INCLUDE_DIR}) endif() @@ -92,6 +123,9 @@ message(STATUS "NativeInput output directory: ${OUTPUT_DIR}") # Set output directory set_target_properties(VpeNativeInput PROPERTIES OUTPUT_NAME "VisualPinball.NativeInput" + CXX_VISIBILITY_PRESET hidden + OBJCXX_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON LIBRARY_OUTPUT_DIRECTORY ${OUTPUT_DIR} RUNTIME_OUTPUT_DIRECTORY ${OUTPUT_DIR} ARCHIVE_OUTPUT_DIRECTORY ${OUTPUT_DIR} @@ -105,3 +139,17 @@ install(TARGETS VpeNativeInput LIBRARY DESTINATION ${OUTPUT_DIR} RUNTIME DESTINATION ${OUTPUT_DIR} ) + +option(NATIVEINPUT_BUILD_TESTS "Build native input report tests" OFF) +if(NATIVEINPUT_BUILD_TESTS) + enable_testing() + add_executable(OpenPinballDeviceTests tests/OpenPinballDeviceTests.cpp src/OpenPinballInput.cpp src/NativeButtons.cpp) + target_include_directories(OpenPinballDeviceTests PRIVATE src) + add_test(NAME OpenPinballDeviceTests COMMAND OpenPinballDeviceTests) + if(TARGET SDL3::SDL3-static) + add_executable(ControllerInputTests tests/ControllerInputTests.cpp src/ControllerInput.cpp src/NativeButtons.cpp) + target_include_directories(ControllerInputTests PRIVATE src) + target_link_libraries(ControllerInputTests PRIVATE SDL3::SDL3-static) + add_test(NAME ControllerInputTests COMMAND ControllerInputTests) + endif() +endif() diff --git a/README.md b/README.md index d3b08e2..117ddd6 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ cmake .. -DCMAKE_BUILD_TYPE=Release make ``` -Requires: `libx11-dev` +Requires `libx11-dev` and `libudev-dev`. The app user needs read access to the controller's input devices. ### macOS @@ -77,7 +77,7 @@ cmake .. -DCMAKE_BUILD_TYPE=Release make ``` -Requires: AppKit and ApplicationServices frameworks (provided by macOS) +Requires CMake 3.24 or newer and the macOS SDK. ### CI / NuGet @@ -131,14 +131,37 @@ NativeInputApi.VpeInputStopPolling(); NativeInputApi.VpeInputShutdown(); ``` +## Open Pinball Device + +NativeInput recognizes Open Pinball Device 1.x HID collections by their report signature on Windows, Linux, and macOS. The native input thread reads the reports and exposes named X/Y acceleration and velocity axes and the reported plunger fields. Preassigned OPD buttons that match existing VPE actions work alongside keyboard bindings, including physical tilt and digital nudges. An action stays pressed while any connected source holds it. + +Pinscape Pico can expose both OPD and a joystick. VPE's cabinet setup prefers OPD and lets a player explicitly choose either collection. On Linux and macOS, OPD mapping identities include the physical USB port so identical boards can be mapped independently. Pico acceleration and velocity ranges depend on its firmware configuration. + +On Linux, run VPE with an X11 display. The local user needs read access to the Pico's hidraw node for input and read/write access to its USB device node for the signature request. On a systemd-based desktop, these udev rules grant the active local user access to a Pico using the default IDs. Save them as `/etc/udev/rules.d/70-pinscape-pico.rules`, reload the rules, and reconnect the board. Use the configured VID and PID if the firmware overrides them. + +```udev +SUBSYSTEM=="hidraw", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="eaeb", TAG+="uaccess" +SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTR{idVendor}=="1209", ATTR{idProduct}=="eaeb", TAG+="uaccess" +``` + +Build the report replay tests with `-DNATIVEINPUT_BUILD_TESTS=ON`, then run `ctest --test-dir build -C Release --output-on-failure` from this repository. + ## Platform Status | Platform | Status | API Used | |----------|--------|----------| -| Windows | ✅ Implemented | GetAsyncKeyState, QueryPerformanceCounter | -| Linux | ✅ Implemented | X11 keyboard state polling | -| macOS | ✅ Implemented | CoreGraphics keyboard state polling | +| Windows | Keyboard, joystick and gamepad axes, Open Pinball Device | GetAsyncKeyState, Windows HID, SDL | +| Linux | Keyboard, joystick and gamepad axes, Open Pinball Device | X11, SDL, hidraw, usbfs | +| macOS | Keyboard, joystick and gamepad axes, Open Pinball Device | CoreGraphics, SDL, IOKit | + +SDL is linked into the plugin and only its joystick and gamepad subsystem is started. The native polling thread samples all controller axes. Recognized gamepads expose named stick and trigger axes, and generic joysticks expose raw axes for manual nudge mapping. Windows keeps the existing HID axes and their saved IDs. If a Windows gamepad also exposes HID joystick axes, its standardized axes appear under the separate `(Gamepad)` entry. + +Some Nintendo controllers change their report format when SDL opens them. On Windows, use the standardized entry if a saved raw HID mapping for one of those controllers stops receiving samples. + +Controller mappings use serial numbers and physical paths where available. When the platform exposes identical devices without a physical identity, the mappings use slots for that model. Recheck those slots after changing the connection order of identical controllers. +The Player's Nudge settings can bind joystick, gamepad, and generic OPD controls to left, right, and forward nudge, Tilt, and Slam Tilt. POV directions are exposed as buttons. Analog axes can activate an action above or below a threshold. Each action accepts alternatives, including combos whose controls must be held together. The native polling thread evaluates bindings and records presses for capture. Bindings follow stable device IDs across polling sessions and supplement keyboard and predefined OPD buttons. Tilt uses the table's physical Tilt Bob routing. + ## Performance - **Latency**: <0.1ms from physical input to event callback @@ -148,13 +171,13 @@ NativeInputApi.VpeInputShutdown(); ## Future Enhancements -1. **Gamepad support**: XInput (Windows), SDL/libinput (Linux), GCController (macOS) -2. **Analog inputs**: Plunger, steering, analog triggers -3. **Force feedback**: Haptics for nudge, tilt, button feedback -4. **Hot-plugging**: Detect device connect/disconnect -5. **Configuration**: JSON-based key mapping files -6. **Profiles**: Per-table input profiles +1. **Controller buttons**: Configurable bindings for other gameplay actions +2. **Force feedback**: Haptics for nudge, tilt, button feedback +3. **Configuration**: JSON-based key mapping files +4. **Profiles**: Per-table input profiles ## License GPLv3+ (same as VPE) + +SDL is distributed under the [zlib license](native/nuget/SDL-LICENSE.txt). diff --git a/native/nuget/SDL-LICENSE.txt b/native/nuget/SDL-LICENSE.txt new file mode 100644 index 0000000..acaf5b2 --- /dev/null +++ b/native/nuget/SDL-LICENSE.txt @@ -0,0 +1,17 @@ +Copyright (C) 1997-2026 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/native/nuget/VisualPinball.NativeInput.nuspec b/native/nuget/VisualPinball.NativeInput.nuspec index d3800a9..a9cc3d1 100644 --- a/native/nuget/VisualPinball.NativeInput.nuspec +++ b/native/nuget/VisualPinball.NativeInput.nuspec @@ -10,13 +10,14 @@ GPL-3.0-or-later icon.png README.md - Cross-platform native keyboard polling library for Visual Pinball Engine. - Native keyboard polling for Visual Pinball Engine. - visualpinball unity native input keyboard + Cross-platform native keyboard, joystick, gamepad and cabinet input polling for Visual Pinball Engine. + Native input polling for Visual Pinball Engine. + visualpinball unity native input keyboard joystick gamepad + diff --git a/src/ControllerInput.cpp b/src/ControllerInput.cpp new file mode 100644 index 0000000..cfb7442 --- /dev/null +++ b/src/ControllerInput.cpp @@ -0,0 +1,362 @@ +// license:GPLv3+ +#include "ControllerInput.h" +#include "NativeButtons.h" + +#if defined(VPE_PLATFORM_WINDOWS) +#define NOMINMAX +#define WIN32_LEAN_AND_MEAN +#endif + +#define SDL_MAIN_HANDLED +#include +#include + +#include +#include +#include +#include +#include + +#if defined(VPE_PLATFORM_WINDOWS) +#include +#elif defined(VPE_PLATFORM_LINUX) +#include +#include +#endif + +namespace { + constexpr int64_t ScanIntervalUsec = 250000; + constexpr int RawGamepadButtonBase = 0x10000; + constexpr int HatButtonBase = 0x20000; + constexpr std::array HatDirections = {SDL_HAT_UP, SDL_HAT_RIGHT, SDL_HAT_DOWN, SDL_HAT_LEFT}; + constexpr std::array GamepadAxisNames = { + "Left Stick X", "Left Stick Y", "Right Stick X", "Right Stick Y", "Left Trigger", "Right Trigger" + }; + + const char* ValueOrEmpty(const char* value) { return value == nullptr ? "" : value; } + + std::vector DescribeButtons(SDL_Joystick* joystick, SDL_Gamepad* gamepad) { + std::vector buttons; + const int rawCount = std::max(SDL_GetNumJoystickButtons(joystick), 0); + std::vector mapped(rawCount); + std::vector mappedHatDirections(std::max(SDL_GetNumJoystickHats(joystick), 0)); + if (gamepad != nullptr) { + int count = 0; + std::unique_ptr bindings(SDL_GetGamepadBindings(gamepad, &count), SDL_free); + for (int i = 0; bindings && i < count; ++i) { + const auto& binding = *bindings.get()[i]; + if (binding.input_type == SDL_GAMEPAD_BINDTYPE_BUTTON && binding.input.button >= 0 + && binding.input.button < rawCount) mapped[binding.input.button] = true; + if (binding.output_type == SDL_GAMEPAD_BINDTYPE_BUTTON && binding.input_type == SDL_GAMEPAD_BINDTYPE_HAT + && binding.input.hat.hat >= 0 && static_cast(binding.input.hat.hat) < mappedHatDirections.size()) { + mappedHatDirections[binding.input.hat.hat] |= static_cast(binding.input.hat.hat_mask); + } + } + for (int i = 0; i < SDL_GAMEPAD_BUTTON_COUNT; ++i) { + const auto id = static_cast(i); + if (!SDL_GamepadHasButton(gamepad, id)) continue; + VpeInputButtonInfo button{}; + button.buttonId = i; + const auto* name = SDL_GetGamepadStringForButton(id); + std::snprintf(button.name, sizeof(button.name), "%s", ValueOrEmpty(name)); + buttons.push_back(button); + } + } + for (int i = 0; i < rawCount; ++i) { + if (mapped[i]) continue; + VpeInputButtonInfo button{}; + button.buttonId = gamepad == nullptr ? i : RawGamepadButtonBase + i; + std::snprintf(button.name, sizeof(button.name), "Button %d", i + 1); + buttons.push_back(button); + } + constexpr const char* directions[] = {"Up", "Right", "Down", "Left"}; + for (size_t hat = 0; hat < mappedHatDirections.size(); ++hat) { + for (size_t direction = 0; direction < HatDirections.size(); ++direction) { + if (mappedHatDirections[hat] & HatDirections[direction]) continue; + VpeInputButtonInfo button{}; + button.buttonId = HatButtonBase + static_cast(hat * HatDirections.size() + direction); + std::snprintf(button.name, sizeof(button.name), "Hat %zu %s", hat + 1, directions[direction]); + buttons.push_back(button); + } + } + return buttons; + } + + bool UsesPinscapeLayout(const char* name) { + return SDL_strncasecmp(name, "mjrnet Pinscape Controller", sizeof("mjrnet Pinscape Controller") - 1) == 0 + || SDL_strcasecmp(name, "Pinscape Controller") == 0 + || SDL_strcasecmp(name, "PinscapePico") == 0 + || SDL_strcasecmp(name, "Pinscape Pico") == 0 + || SDL_strcasecmp(name, "mjrnet PinscapePico") == 0 + || SDL_strcasecmp(name, "mjrgh PinscapePico") == 0; + } + + bool IsWindowsHidPath(const char* path) { +#if defined(VPE_PLATFORM_WINDOWS) + // The Windows HID backend retains these raw axes and their saved + // mapping IDs. Standard gamepad axes use a separate SDL device. + return SDL_strncasecmp(path, R"(\\?\hid#)", 8) == 0; +#else + (void)path; + return false; +#endif + } + + std::string StableLocation(std::string_view path) { +#if defined(VPE_PLATFORM_LINUX) + // Kernel node numbers change on reconnect. The input or HID physical + // path (USB port and interface, or Bluetooth address) survives it. + if (path.rfind("/dev/input/", 0) == 0) { + const auto node = std::filesystem::path(path).filename(); + std::ifstream file(std::filesystem::path("/sys/class/input") / node / "device/phys"); + std::string phys; + if (std::getline(file, phys)) return phys; + } else if (path.rfind("/dev/hidraw", 0) == 0) { + const auto node = std::filesystem::path(path).filename(); + std::ifstream file(std::filesystem::path("/sys/class/hidraw") / node / "device/uevent"); + for (std::string line; std::getline(file, line);) { + if (line.rfind("HID_PHYS=", 0) == 0) return line.substr(9); + } + } + return {}; +#else + return std::string(path); +#endif + } + + std::string IdBase(SDL_Joystick* joystick, const char* path, bool gamepad) { + char guid[33]{}; + SDL_GUIDToString(SDL_GetJoystickGUID(joystick), guid, sizeof(guid)); + const auto identity = StableLocation(path) + '\n' + ValueOrEmpty(SDL_GetJoystickSerial(joystick)); + uint64_t hash = 14695981039346656037ULL; + for (unsigned char byte : identity) hash = (hash ^ byte) * 1099511628211ULL; + char id[80]; + std::snprintf(id, sizeof(id), "sdl-%s:%s:%016llx:", gamepad ? "gamepad" : "joystick", + guid, static_cast(hash)); + return id; + } + + void PumpDeviceNotifications() { +#if defined(VPE_PLATFORM_WINDOWS) + // SDL's joystick notification window lives on this thread. Service it + // without initializing SDL video or pumping the host application's UI. + MSG message; + for (int i = 0; i < 32 && PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE); ++i) { + DispatchMessageW(&message); + } +#endif + } +} + +struct ControllerInput::Device { + SDL_JoystickID id; + SDL_Joystick* joystick = nullptr; + SDL_Gamepad* gamepad = nullptr; + VpeInputDeviceInfo info{}; + std::vector axes; + + explicit Device(SDL_JoystickID id) : id(id) {} + ~Device() { + if (gamepad != nullptr) SDL_CloseGamepad(gamepad); + else if (joystick != nullptr) SDL_CloseJoystick(joystick); + } +}; + +ControllerInput::ControllerInput() = default; +ControllerInput::~ControllerInput() = default; + +void ControllerInput::Start() { + // Only the joystick/gamepad subsystem is initialized here. IOKit attaches + // its run loop and Win32 creates its notification window on this thread. + SDL_SetMainReady(); + SDL_SetHintWithPriority(SDL_HINT_NO_SIGNAL_HANDLERS, "1", SDL_HINT_OVERRIDE); + SDL_SetHintWithPriority(SDL_HINT_JOYSTICK_THREAD, "0", SDL_HINT_OVERRIDE); + SDL_SetHintWithPriority(SDL_HINT_JOYSTICK_RAWINPUT, "0", SDL_HINT_OVERRIDE); + SDL_SetHintWithPriority(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1", SDL_HINT_OVERRIDE); + m_started = SDL_InitSubSystem(SDL_INIT_GAMEPAD); + if (m_started) { + SDL_SetJoystickEventsEnabled(false); + SDL_SetGamepadEventsEnabled(false); + SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_UPDATE_COMPLETE, false); + } else { + SDL_LogError(SDL_LOG_CATEGORY_INPUT, "VPE controller input initialization failed: %s", SDL_GetError()); + } + m_wasPublishing = false; + m_nextScan = 0; + m_nextIndex = FirstDeviceIndex; +} + +void ControllerInput::Stop() { + { + std::lock_guard lock(m_snapshotMutex); + for (const auto& device : m_devices) NativeButtons::GetState().Disconnect(device->info.deviceIndex); + m_devices.clear(); + } + if (m_started) SDL_QuitSubSystem(SDL_INIT_GAMEPAD); + m_started = false; +} + +void ControllerInput::SetGameplayEnabled(bool enabled) { + if (enabled) m_refreshOnResume.store(true); + m_gameplayEnabled.store(enabled); +} + +bool ControllerInput::Reconcile(int64_t timestamp) { + bool changed = false; + const auto removed = std::remove_if(m_devices.begin(), m_devices.end(), [](const auto& device) { + if (SDL_JoystickConnected(device->joystick)) return false; + NativeButtons::GetState().Disconnect(device->info.deviceIndex); + return true; + }); + if (removed != m_devices.end()) { + m_devices.erase(removed, m_devices.end()); + changed = true; + } + if (timestamp < m_nextScan) return changed; + m_nextScan = timestamp + ScanIntervalUsec; + + int count = 0; + std::unique_ptr ids(SDL_GetJoysticks(&count), SDL_free); + if (!ids) return changed; + for (int i = 0; i < count; ++i) { + const auto id = ids.get()[i]; + if (std::any_of(m_devices.begin(), m_devices.end(), [id](const auto& device) { return device->id == id; })) continue; + + const auto* path = ValueOrEmpty(SDL_GetJoystickPathForID(id)); + const auto* name = ValueOrEmpty(SDL_GetJoystickNameForID(id)); + const bool pinscape = UsesPinscapeLayout(name); + const bool standardized = SDL_IsGamepad(id) && !pinscape; + if (!standardized && IsWindowsHidPath(path)) continue; + + auto device = std::make_unique(id); + if (standardized) { + device->gamepad = SDL_OpenGamepad(id); + if (device->gamepad == nullptr) continue; + device->joystick = SDL_GetGamepadJoystick(device->gamepad); + } else { + device->joystick = SDL_OpenJoystick(id); + } + if (device->joystick == nullptr) continue; + + const auto base = IdBase(device->joystick, path, standardized); + int slot = 0; + std::string stableId; + do { + stableId = base + std::to_string(slot++); + } while (std::any_of(m_devices.begin(), m_devices.end(), [&](const auto& existing) { + return stableId == existing->info.stableId; + })); + + device->info.deviceIndex = m_nextIndex++; + device->info.isConnected = 1; + std::snprintf(device->info.stableId, sizeof(device->info.stableId), "%s", stableId.c_str()); + const auto* label = standardized ? ValueOrEmpty(SDL_GetGamepadName(device->gamepad)) : name; + std::snprintf(device->info.displayName, sizeof(device->info.displayName), "%.*s%s", + static_cast(sizeof(device->info.displayName) - sizeof(" (Gamepad)")), + *label != '\0' ? label : "Controller", standardized ? " (Gamepad)" : ""); + + const int axisCount = standardized ? static_cast(SDL_GAMEPAD_AXIS_COUNT) : SDL_GetNumJoystickAxes(device->joystick); + constexpr const char* PinscapeAxisNames[] = { "X", "Y", "Z", "RX", "RY", "RZ" }; + for (int axis = 0; axis < axisCount; ++axis) { + VpeInputAxisInfo info{}; + info.axisId = axis; + info.kind = VPE_AXIS_KIND_POSITION; + if (standardized) { + if (!SDL_GamepadHasAxis(device->gamepad, static_cast(axis))) continue; + info.usagePage = VPE_GAMEPAD_AXIS_USAGE_PAGE; + info.usage = axis; + std::snprintf(info.name, sizeof(info.name), "%s", GamepadAxisNames[axis]); + } else if (pinscape && axisCount >= 6 && axis < 6) { + // The known six-axis Pinscape joystick layout, as exposed by + // SDL, matches the usage-based preset used by Windows HID. + info.usagePage = 0x01; + info.usage = 0x30 + axis; + std::snprintf(info.name, sizeof(info.name), "%s", PinscapeAxisNames[axis]); + } else { + std::snprintf(info.name, sizeof(info.name), "Axis %d", axis + 1); + } + device->axes.push_back(info); + } + auto buttons = DescribeButtons(device->joystick, device->gamepad); + if (device->axes.empty() && buttons.empty()) continue; + std::vector axisIds; + for (const auto& axis : device->axes) axisIds.push_back(axis.axisId); + NativeButtons::GetState().Connect(device->info.deviceIndex, stableId, std::move(buttons), axisIds); + device->info.axisCount = static_cast(device->axes.size()); + m_devices.push_back(std::move(device)); + changed = true; + } + return changed; +} + +void ControllerInput::Poll(int64_t timestamp, bool foreground, VpeInputEventCallback callback, void* userData) { + if (!m_started) return; + PumpDeviceNotifications(); + SDL_UpdateJoysticks(); + // MFi notifications can change SDL's device list on the OS thread. + SDL_LockJoysticks(); + const bool publish = foreground && m_gameplayEnabled.load(); + const bool refresh = publish && (m_refreshOnResume.exchange(false) || !m_wasPublishing); + m_axisEvents.clear(); + bool changed; + { + std::lock_guard lock(m_snapshotMutex); + changed = Reconcile(timestamp); + for (auto& device : m_devices) { + for (auto& axis : device->axes) { + const auto value = device->gamepad != nullptr + ? SDL_GetGamepadAxis(device->gamepad, static_cast(axis.axisId)) + : SDL_GetJoystickAxis(device->joystick, axis.axisId); + const float normalized = static_cast(value) / 32768.0f; + if (publish && (refresh || axis.timestampUsec == 0 || normalized != axis.rawValue)) { + m_axisEvents.push_back({timestamp, VPE_INPUT_EVENT_AXIS, 0, device->info.deviceIndex, axis.axisId, normalized, 0}); + } + axis.rawValue = normalized; + axis.timestampUsec = timestamp; + } + auto axis = device->axes.begin(); + NativeButtons::GetState().Update(device->info.deviceIndex, [&](const auto& button) { + if (button.buttonId >= HatButtonBase) { + const auto offset = static_cast(button.buttonId - HatButtonBase); + const auto hat = SDL_GetJoystickHat(device->joystick, static_cast(offset / HatDirections.size())); + return (hat & HatDirections[offset % HatDirections.size()]) != 0; + } + if (device->gamepad == nullptr) return SDL_GetJoystickButton(device->joystick, button.buttonId); + if (button.buttonId >= RawGamepadButtonBase) { + return SDL_GetJoystickButton(device->joystick, button.buttonId - RawGamepadButtonBase); + } + return SDL_GetGamepadButton(device->gamepad, static_cast(button.buttonId)); + }, [&](int, float) { return (axis++)->rawValue; }); + } + } + SDL_UnlockJoysticks(); + m_wasPublishing = publish; + if (callback == nullptr) return; + if (changed) { + const VpeInputEvent event{timestamp, VPE_INPUT_EVENT_DEVICES_CHANGED, 0, 0, 0, 0, 0}; + callback(&event, userData); + } + for (const auto& event : m_axisEvents) callback(&event, userData); +} + +int ControllerInput::AppendDevices(VpeInputDeviceInfo* devices, int maxDevices, int existingCount) { + std::lock_guard lock(m_snapshotMutex); + const int count = static_cast(m_devices.size()); + if (devices != nullptr && maxDevices > existingCount) { + for (int i = 0; i < std::min(count, maxDevices - existingCount); ++i) { + devices[existingCount + i] = m_devices[i]->info; + } + } + return existingCount + count; +} + +int ControllerInput::ListAxes(int deviceIndex, VpeInputAxisInfo* axes, int maxAxes) { + std::lock_guard lock(m_snapshotMutex); + for (const auto& device : m_devices) { + if (device->info.deviceIndex != deviceIndex) continue; + const int count = device->info.axisCount; + if (axes != nullptr && maxAxes > 0) std::copy_n(device->axes.begin(), std::min(count, maxAxes), axes); + return count; + } + return 0; +} diff --git a/src/ControllerInput.h b/src/ControllerInput.h new file mode 100644 index 0000000..a812d69 --- /dev/null +++ b/src/ControllerInput.h @@ -0,0 +1,39 @@ +// license:GPLv3+ +#pragma once + +#include "NativeInput.h" + +#include +#include +#include +#include + +// A private SDL joystick subsystem. The platform input thread owns the SDL +// lifecycle and calls Poll. Other threads can only read the published snapshot. +class ControllerInput { +public: + static constexpr int FirstDeviceIndex = 0x40000000; + + ControllerInput(); + ~ControllerInput(); + void Start(); + void Stop(); + void SetGameplayEnabled(bool enabled); + void Poll(int64_t timestamp, bool foreground, VpeInputEventCallback callback, void* userData); + int AppendDevices(VpeInputDeviceInfo* devices, int maxDevices, int existingCount); + int ListAxes(int deviceIndex, VpeInputAxisInfo* axes, int maxAxes); + +private: + struct Device; + bool Reconcile(int64_t timestamp); + + std::mutex m_snapshotMutex; + std::vector> m_devices; + std::vector m_axisEvents; + std::atomic m_gameplayEnabled{true}; + std::atomic m_refreshOnResume{true}; + bool m_started = false; + bool m_wasPublishing = false; + int m_nextIndex = FirstDeviceIndex; + int64_t m_nextScan = 0; +}; diff --git a/src/NativeButtons.cpp b/src/NativeButtons.cpp new file mode 100644 index 0000000..dafe47d --- /dev/null +++ b/src/NativeButtons.cpp @@ -0,0 +1,250 @@ +// license:GPLv3+ +#include "NativeButtons.h" + +#include +#include +#include +#include +#include + +static_assert(sizeof(VpeInputControlBinding) == 280); + +namespace NativeButtons { + namespace { + bool IsNudgeOrTilt(int action) { + return action == VPE_INPUT_LEFT_NUDGE || action == VPE_INPUT_RIGHT_NUDGE + || action == VPE_INPUT_CENTER_NUDGE || action == VPE_INPUT_TILT || action == VPE_INPUT_SLAM_TILT; + } + + bool SameControl(const VpeInputControlBinding& a, const VpeInputControlBinding& b) { + return a.kind == b.kind && a.controlId == b.controlId && a.threshold == b.threshold + && std::strcmp(a.deviceId, b.deviceId) == 0; + } + } + + State& GetState() { + static State state; + return state; + } + + void State::Connect(int deviceIndex, const std::string& stableId, std::vector buttons, + const std::vector& axisIds) { + if (buttons.empty() && axisIds.empty()) return; + Device device{deviceIndex, stableId.substr(0, VPE_INPUT_DEVICE_ID_SIZE - 1), std::move(buttons), {}}; + for (int id : axisIds) device.axes.push_back({id}); + std::lock_guard lock(m_mutex); + m_devices.push_back(std::move(device)); + } + + void State::Disconnect(int deviceIndex) { + std::lock_guard lock(m_mutex); + const auto removed = std::remove_if(m_devices.begin(), m_devices.end(), [&](const Device& device) { + if (device.index != deviceIndex) return false; + if (m_captureMode && std::any_of(m_capture.begin(), m_capture.end(), [&](const auto& control) { + return device.id == control.deviceId; + })) { + m_capture.clear(); + m_captureReleased = false; + } + return true; + }); + m_devices.erase(removed, m_devices.end()); + } + + void State::Configure(const VpeInputButtonBinding* bindings, int count) { + std::vector controls; + for (int i = 0; bindings != nullptr && i < count; ++i) { + const auto& binding = bindings[i]; + VpeInputControlBinding control{binding.action, i, VPE_CONTROL_BUTTON, binding.buttonId, 0.0f, {}}; + std::copy_n(binding.deviceId, VPE_INPUT_DEVICE_ID_SIZE, control.deviceId); + controls.push_back(control); + } + ConfigureControls(controls.data(), static_cast(controls.size())); + } + + void State::ConfigureControls(const VpeInputControlBinding* controls, int count) { + std::vector groups; + bool hasAxisBindings = false; + for (int i = 0; controls != nullptr && i < count; ++i) { + const auto& control = controls[i]; + if (!IsNudgeOrTilt(control.action) || control.group < 0) continue; + auto group = std::find_if(groups.begin(), groups.end(), [&](const Binding& binding) { + return binding.action == control.action && binding.group == control.group; + }); + if (group == groups.end()) { + groups.push_back({control.action, control.group, {}}); + group = std::prev(groups.end()); + } + group->controls.push_back({control}); + } + groups.erase(std::remove_if(groups.begin(), groups.end(), [&](const Binding& group) { + // Reject the entire group if any member is malformed. + return std::any_of(group.controls.begin(), group.controls.end(), [](const auto& member) { + const auto& control = member.control; + const bool validThreshold = control.kind == VPE_CONTROL_BUTTON + || (control.kind == VPE_CONTROL_AXIS_ABOVE && control.threshold > 0.0f) + || (control.kind == VPE_CONTROL_AXIS_BELOW && control.threshold < 0.0f); + return !validThreshold || control.controlId < 0 || !std::isfinite(control.threshold) + || std::fabs(control.threshold) > 1.0f || control.deviceId[0] == '\0' + || std::find(std::begin(control.deviceId), std::end(control.deviceId), '\0') == std::end(control.deviceId); + }); + }), groups.end()); + for (auto& group : groups) { + auto& members = group.controls; + for (auto& member : members) { + if (member.control.kind == VPE_CONTROL_BUTTON) member.control.threshold = 0.0f; + else hasAxisBindings = true; + } + for (auto member = members.begin(); member != members.end(); ++member) { + members.erase(std::remove_if(std::next(member), members.end(), [&](const auto& other) { + return SameControl(member->control, other.control); + }), members.end()); + } + } + std::lock_guard lock(m_mutex); + m_bindings.swap(groups); + m_hasAxisBindings = hasAxisBindings; + } + + void State::StartCapture(int mode) { + std::lock_guard lock(m_mutex); + m_captureMode = mode == 1 || mode == 2 ? mode : 0; + m_captureReleased = false; + m_capture.clear(); + m_captureCandidates.clear(); + } + + int State::ReadCapture(VpeInputControlBinding* controls, int maxControls) { + std::lock_guard lock(m_mutex); + if (m_captureMode != 0) return 0; + const int count = static_cast(m_capture.size()); + if (controls != nullptr && maxControls > 0) std::copy_n(m_capture.begin(), std::min(count, maxControls), controls); + return count; + } + + void State::CaptureCandidate(const std::string& id, int kind, int controlId, float threshold) { + if (m_captureReleased || m_captureCandidates.size() >= 8) return; + VpeInputControlBinding control{0, 0, kind, controlId, threshold, {}}; + std::snprintf(control.deviceId, sizeof(control.deviceId), "%s", id.c_str()); + m_captureCandidates.push_back(control); + } + + void State::AdvanceCapture() { + const auto held = [this](const auto& control) { return ControlPressed(control, true); }; + if (!m_capture.empty() && !std::all_of(m_capture.begin(), m_capture.end(), held)) m_captureReleased = true; + if (!m_captureReleased) { + for (const auto& candidate : m_captureCandidates) { + if (m_capture.size() >= (m_captureMode == 1 ? 1 : 8)) break; + if (std::none_of(m_capture.begin(), m_capture.end(), [&](const auto& member) { + return SameControl(member, candidate); + })) m_capture.push_back(candidate); + } + } else if (std::none_of(m_capture.begin(), m_capture.end(), held)) { + if (m_captureMode == 2 && m_capture.size() < 2) { + m_capture.clear(); + m_captureReleased = false; + } else { + m_captureMode = 0; + } + } + m_captureCandidates.clear(); + } + + int State::List(int deviceIndex, VpeInputButtonInfo* buttons, int maxButtons) { + std::lock_guard lock(m_mutex); + for (const auto& device : m_devices) { + if (device.index != deviceIndex) continue; + const int count = static_cast(device.buttons.size()); + if (buttons != nullptr && maxButtons > 0) std::copy_n(device.buttons.begin(), std::min(count, maxButtons), buttons); + return count; + } + return 0; + } + + uint64_t State::PressedActions() { + std::lock_guard lock(m_mutex); + for (auto& binding : m_bindings) { + binding.pressed = true; + for (auto& member : binding.controls) { + member.pressed = ControlPressed(member.control, member.pressed); + binding.pressed &= member.pressed; + } + if (!binding.pressed) binding.suppressed = false; + } + // When a combo and a shorter subset complete together, publish only + // the combo. The shorter binding must release before it can fire again. + for (const auto& combo : m_bindings) { + if (!combo.pressed || combo.wasPressed || combo.controls.size() < 2) continue; + for (auto& shorter : m_bindings) { + if (!shorter.pressed || shorter.wasPressed || shorter.controls.size() >= combo.controls.size()) continue; + if (std::all_of(shorter.controls.begin(), shorter.controls.end(), [&](const auto& control) { + return std::any_of(combo.controls.begin(), combo.controls.end(), [&](const auto& member) { + return SameControl(control.control, member.control); + }); + })) shorter.suppressed = true; + } + } + uint64_t actions = 0; + for (auto& binding : m_bindings) { + if (binding.pressed && !binding.suppressed) actions |= uint64_t{1} << binding.action; + binding.wasPressed = binding.pressed; + } + return actions; + } + + bool State::ControlPressed(const VpeInputControlBinding& control, bool wasPressed) const { + constexpr float releaseMargin = 0.1f; + for (const auto& device : m_devices) { + if (device.id != control.deviceId) continue; + if (control.kind == VPE_CONTROL_BUTTON) { + for (const auto& button : device.buttons) { + if (button.buttonId == control.controlId && button.isPressed) return true; + } + } else { + for (const auto& axis : device.axes) { + if (axis.id != control.controlId || !std::isfinite(axis.value)) continue; + if (control.kind == VPE_CONTROL_AXIS_ABOVE) { + if (wasPressed ? axis.value > std::max(0.0f, control.threshold - releaseMargin) : axis.value >= control.threshold) + return true; + } else { + if (wasPressed ? axis.value < std::min(0.0f, control.threshold + releaseMargin) : axis.value <= control.threshold) + return true; + } + } + } + } + return false; + } + + std::vector OpdGenericButtons() { + std::vector buttons(32); + for (int i = 0; i < 32; ++i) { + buttons[i].buttonId = i; + std::snprintf(buttons[i].name, sizeof(buttons[i].name), "Generic Button %d", i + 1); + } + return buttons; + } + +} + +extern "C" { + VPE_API void VpeInputSetButtonBindings(const VpeInputButtonBinding* bindings, int count) { + NativeButtons::GetState().Configure(bindings, count); + } + + VPE_API int VpeInputListDeviceButtons(int deviceIndex, VpeInputButtonInfo* buttons, int maxButtons) { + return NativeButtons::GetState().List(deviceIndex, buttons, maxButtons); + } + + VPE_API void VpeInputSetControlBindings(const VpeInputControlBinding* controls, int count) { + NativeButtons::GetState().ConfigureControls(controls, count); + } + + VPE_API void VpeInputStartControlCapture(int mode) { + NativeButtons::GetState().StartCapture(mode); + } + + VPE_API int VpeInputReadControlCapture(VpeInputControlBinding* controls, int maxControls) { + return NativeButtons::GetState().ReadCapture(controls, maxControls); + } +} diff --git a/src/NativeButtons.h b/src/NativeButtons.h new file mode 100644 index 0000000..c94d2a1 --- /dev/null +++ b/src/NativeButtons.h @@ -0,0 +1,108 @@ +// license:GPLv3+ +#pragma once + +#include "NativeInput.h" + +#include +#include +#include +#include +#include + +namespace NativeButtons { + class State { + public: + void Connect(int deviceIndex, const std::string& stableId, std::vector buttons, + const std::vector& axisIds = {}); + void Disconnect(int deviceIndex); + void Configure(const VpeInputButtonBinding* bindings, int count); + void ConfigureControls(const VpeInputControlBinding* controls, int count); + void StartCapture(int mode); + int ReadCapture(VpeInputControlBinding* controls, int maxControls); + int List(int deviceIndex, VpeInputButtonInfo* buttons, int maxButtons); + uint64_t PressedActions(); + + template + bool Update(int deviceIndex, Sample sample) { + return Update(deviceIndex, sample, [](int, float previous) { return previous; }); + } + + template + bool Update(int deviceIndex, SampleButton sampleButton, SampleAxis sampleAxis) { + std::lock_guard lock(m_mutex); + for (auto& device : m_devices) { + if (device.index != deviceIndex) continue; + bool changed = false; + for (auto& button : device.buttons) { + const bool pressed = sampleButton(button); + const bool wasPressed = button.isPressed != 0; + changed |= pressed != wasPressed; + if (m_captureMode && device.buttonsSampled && pressed && !wasPressed) + CaptureCandidate(device.id, VPE_CONTROL_BUTTON, button.buttonId, 0.0f); + button.isPressed = pressed; + } + device.buttonsSampled = true; + for (auto& axis : device.axes) { + const float value = sampleAxis(axis.id, axis.value); + changed |= m_hasAxisBindings && value != axis.value + && (std::isfinite(value) || std::isfinite(axis.value)); + if (m_captureMode && std::isfinite(axis.value)) { + if (value >= CaptureThreshold && axis.value < CaptureThreshold) + CaptureCandidate(device.id, VPE_CONTROL_AXIS_ABOVE, axis.id, CaptureThreshold); + if (value <= -CaptureThreshold && axis.value > -CaptureThreshold) + CaptureCandidate(device.id, VPE_CONTROL_AXIS_BELOW, axis.id, -CaptureThreshold); + } + axis.value = value; + } + if (m_captureMode) AdvanceCapture(); + return changed; + } + return false; + } + + private: + static constexpr float CaptureThreshold = 0.65f; + + struct Axis { + int id; + float value = std::numeric_limits::quiet_NaN(); + }; + + struct Device { + int index; + std::string id; + std::vector buttons; + std::vector axes; + bool buttonsSampled = false; + }; + + struct Binding { + int action; + int group; + struct Member { + VpeInputControlBinding control; + bool pressed = false; + }; + std::vector controls; + bool wasPressed = false; + bool pressed = false; + bool suppressed = false; + }; + + bool ControlPressed(const VpeInputControlBinding& control, bool wasPressed) const; + void CaptureCandidate(const std::string& id, int kind, int controlId, float threshold); + void AdvanceCapture(); + + std::mutex m_mutex; + std::vector m_devices; + std::vector m_bindings; + bool m_hasAxisBindings = false; + int m_captureMode = 0; + bool m_captureReleased = false; + std::vector m_capture; + std::vector m_captureCandidates; + }; + + State& GetState(); + std::vector OpdGenericButtons(); +} diff --git a/src/NativeInput.h b/src/NativeInput.h index 08d76c2..f14257d 100644 --- a/src/NativeInput.h +++ b/src/NativeInput.h @@ -150,6 +150,10 @@ typedef enum { #define VPE_INPUT_DEVICE_ID_SIZE 260 #define VPE_INPUT_DEVICE_NAME_SIZE 128 #define VPE_INPUT_AXIS_NAME_SIZE 32 +#define VPE_INPUT_BUTTON_NAME_SIZE 32 + +// Vendor-defined metadata page for SDL's standardized gamepad axes. +#define VPE_GAMEPAD_AXIS_USAGE_PAGE 0xff00 // Input device descriptor (matches C# struct layout) typedef struct { @@ -192,6 +196,34 @@ typedef struct { int32_t _padding; } VpeInputBinding; +typedef struct { + int32_t buttonId; + int32_t isPressed; + char name[VPE_INPUT_BUTTON_NAME_SIZE]; +} VpeInputButtonInfo; + +typedef struct { + int32_t action; + int32_t buttonId; + char deviceId[VPE_INPUT_DEVICE_ID_SIZE]; // UTF-8 stable ID from VpeInputListDevices +} VpeInputButtonBinding; + +typedef enum { + VPE_CONTROL_BUTTON = 0, + VPE_CONTROL_AXIS_ABOVE = 1, + VPE_CONTROL_AXIS_BELOW = 2 +} VpeInputControlKind; + +// Rows sharing an action and group form a combo. Groups are alternatives. +typedef struct { + int32_t action; + int32_t group; + int32_t kind; + int32_t controlId; + float threshold; + char deviceId[VPE_INPUT_DEVICE_ID_SIZE]; +} VpeInputControlBinding; + // Callback for input events typedef void (*VpeInputEventCallback)(const VpeInputEvent* event, void* userData); @@ -212,6 +244,12 @@ VPE_API void VpeInputShutdown(void); // count: Number of bindings VPE_API void VpeInputSetBindings(const VpeInputBinding* bindings, int count); +#if defined(VPE_PLATFORM_WINDOWS) || defined(VPE_PLATFORM_LINUX) || defined(VPE_PLATFORM_MACOS) +// Optional desktop entry point. Suppressed actions retain their published state and +// reconcile releases on resume. New presses during suppression are ignored. +VPE_API void VpeInputSetGameplayInputEnabled(int enabled); +#endif + // Start polling thread // callback: Function called for each input event // userData: User data passed to callback @@ -221,7 +259,7 @@ VPE_API int VpeInputStartPolling(VpeInputEventCallback callback, void* userData, // Stop polling thread VPE_API void VpeInputStopPolling(void); -// List HID joystick/gamepad-style devices with analog axes. +// List HID joystick/gamepad-style devices and Open Pinball Device collections. // Returns the total available device count. Copies up to maxDevices entries when devices is non-null. VPE_API int VpeInputListDevices(VpeInputDeviceInfo* devices, int maxDevices); @@ -229,6 +267,16 @@ VPE_API int VpeInputListDevices(VpeInputDeviceInfo* devices, int maxDevices); // Returns the total available axis count. Copies up to maxAxes entries when axes is non-null. VPE_API int VpeInputListDeviceAxes(int deviceIndex, VpeInputAxisInfo* axes, int maxAxes); +// Optional desktop extension. These mappings supplement keyboard and +// predefined OPD mappings. Replace them atomically, even while polling. +VPE_API void VpeInputSetButtonBindings(const VpeInputButtonBinding* bindings, int count); +VPE_API int VpeInputListDeviceButtons(int deviceIndex, VpeInputButtonInfo* buttons, int maxButtons); +VPE_API void VpeInputSetControlBindings(const VpeInputControlBinding* controls, int count); +// 0 cancels, 1 captures a single control, 2 captures controls held together. +VPE_API void VpeInputStartControlCapture(int mode); +// Returns the completed combo's size once all its controls have been released. +VPE_API int VpeInputReadControlCapture(VpeInputControlBinding* controls, int maxControls); + // Get high-resolution timestamp in microseconds VPE_API int64_t VpeGetTimestampUsec(void); diff --git a/src/NativeInput_Linux.cpp b/src/NativeInput_Linux.cpp index 16c2b6c..b8fd5c0 100644 --- a/src/NativeInput_Linux.cpp +++ b/src/NativeInput_Linux.cpp @@ -3,7 +3,8 @@ #ifdef __linux__ -#include "NativeInput.h" +#include "ControllerInput.h" +#include "OpenPinballInput.h" #include #include @@ -26,7 +27,6 @@ namespace { struct KeyBindingState { VpeInputAction action; KeyCode nativeKeyCode; - float previousValue; }; std::thread g_pollingThread; @@ -34,15 +34,15 @@ namespace { std::atomic g_protocolVersionChecked(false); std::condition_variable g_waitCondition; std::mutex g_waitMutex; - VpeInputEventCallback g_callback = nullptr; - void* g_userData = nullptr; + OpenPinballDevice::Input g_input; + ControllerInput g_controllers; + std::mutex g_bindingsMutex; int g_pollIntervalUs = 500; Clock::time_point g_startTime; Display* g_display = nullptr; Atom g_activeWindowAtom = None; Atom g_wmPidAtom = None; std::vector g_bindings; - bool g_wasForeground = false; int64_t GetTimestampUsecInternal() { return std::chrono::duration_cast(Clock::now() - g_startTime).count(); @@ -249,74 +249,35 @@ namespace { return (keyBits[index] & (1u << bit)) != 0; } - void EmitReleaseForPressedKeys(int64_t timestampUsec) { - if (g_callback == nullptr) { - for (auto& binding : g_bindings) { - binding.previousValue = 0.0f; - } - return; - } - - for (auto& binding : g_bindings) { - if (binding.previousValue <= 0.0f) { - continue; - } - - binding.previousValue = 0.0f; - - VpeInputEvent event{}; - event.timestampUsec = timestampUsec; - event.eventType = VPE_INPUT_EVENT_ACTION; - event.action = static_cast(binding.action); - event.value = 0.0f; - g_callback(&event, g_userData); - } - } - - void PollingThreadFunc() { + void PollingThreadFunc(VpeInputEventCallback callback, void* userData) { VpeSetThreadPriority(); - + OpenPinballDevice::Transport transport(g_input); + g_controllers.Start(); while (g_running.load(std::memory_order_acquire)) { - const int64_t timestampUsec = GetTimestampUsecInternal(); - const bool isForeground = IsCurrentProcessForeground(); - - if (!isForeground) { - if (g_wasForeground) { - EmitReleaseForPressedKeys(timestampUsec); - } - g_wasForeground = false; - } else { - g_wasForeground = true; - char keymap[32] = {}; - XQueryKeymap(g_display, keymap); - const auto* keyBits = reinterpret_cast(keymap); - - for (auto& binding : g_bindings) { - const float currentValue = IsPressed(keyBits, binding.nativeKeyCode) ? 1.0f : 0.0f; - if (currentValue == binding.previousValue) { - continue; - } - - binding.previousValue = currentValue; - if (g_callback == nullptr) { - continue; + const int64_t timestamp = GetTimestampUsecInternal(); + OpenPinballDevice::Keys keys{}; + bool foreground; + { + std::lock_guard lock(g_bindingsMutex); + foreground = IsCurrentProcessForeground(); + if (foreground) { + char keymap[32] = {}; + XQueryKeymap(g_display, keymap); + const auto* keyBits = reinterpret_cast(keymap); + for (const auto& binding : g_bindings) { + keys[binding.action] |= IsPressed(keyBits, binding.nativeKeyCode); } - - VpeInputEvent event{}; - event.timestampUsec = timestampUsec; - event.eventType = VPE_INPUT_EVENT_ACTION; - event.action = static_cast(binding.action); - event.value = currentValue; - g_callback(&event, g_userData); } } + g_controllers.Poll(timestamp, foreground, callback, userData); + g_input.BeginPoll(timestamp, foreground, keys); + transport.Poll(timestamp); std::unique_lock lock(g_waitMutex); - g_waitCondition.wait_for( - lock, - std::chrono::microseconds(g_pollIntervalUs > 0 ? g_pollIntervalUs : 500), + g_waitCondition.wait_for(lock, std::chrono::microseconds(g_pollIntervalUs), [] { return !g_running.load(std::memory_order_acquire); }); } + g_controllers.Stop(); } } @@ -324,6 +285,8 @@ extern "C" { VPE_API int VpeInputInit(void) { g_protocolVersionChecked.store(false, std::memory_order_release); + g_input.ResetGameplayGate(); + g_controllers.SetGameplayEnabled(true); g_startTime = Clock::now(); g_display = XOpenDisplay(nullptr); if (g_display == nullptr) { @@ -332,7 +295,6 @@ VPE_API int VpeInputInit(void) { g_activeWindowAtom = XInternAtom(g_display, "_NET_ACTIVE_WINDOW", True); g_wmPidAtom = XInternAtom(g_display, "_NET_WM_PID", True); - g_wasForeground = false; return 1; } @@ -343,9 +305,9 @@ VPE_API int VpeInputGetProtocolVersion(void) { VPE_API void VpeInputShutdown(void) { VpeInputStopPolling(); + VpeInputSetButtonBindings(nullptr, 0); g_protocolVersionChecked.store(false, std::memory_order_release); g_bindings.clear(); - g_wasForeground = false; if (g_display != nullptr) { XCloseDisplay(g_display); @@ -354,15 +316,16 @@ VPE_API void VpeInputShutdown(void) { } VPE_API void VpeInputSetBindings(const VpeInputBinding* bindings, int count) { + std::lock_guard lock(g_bindingsMutex); g_bindings.clear(); - g_wasForeground = false; if (g_display == nullptr || bindings == nullptr || count <= 0) { return; } for (int i = 0; i < count; ++i) { - if (bindings[i].bindingType != VPE_BINDING_KEYBOARD) { + if (bindings[i].bindingType != VPE_BINDING_KEYBOARD + || bindings[i].action < 0 || bindings[i].action >= VPE_INPUT_MAX) { continue; } @@ -379,11 +342,15 @@ VPE_API void VpeInputSetBindings(const VpeInputBinding* bindings, int count) { g_bindings.push_back({ static_cast(bindings[i].action), nativeKeyCode, - 0.0f, }); } } +VPE_API void VpeInputSetGameplayInputEnabled(int enabled) { + g_input.SetGameplayEnabled(enabled); + g_controllers.SetGameplayEnabled(enabled != 0); +} + VPE_API int VpeInputStartPolling(VpeInputEventCallback callback, void* userData, int pollIntervalUs) { if (!g_protocolVersionChecked.load(std::memory_order_acquire) || g_display == nullptr || @@ -391,14 +358,12 @@ VPE_API int VpeInputStartPolling(VpeInputEventCallback callback, void* userData, return 0; } - g_callback = callback; - g_userData = userData; + g_input.Start(callback, userData); g_pollIntervalUs = pollIntervalUs > 0 ? pollIntervalUs : 500; - g_wasForeground = false; g_running.store(true, std::memory_order_release); try { - g_pollingThread = std::thread(PollingThreadFunc); + g_pollingThread = std::thread(PollingThreadFunc, callback, userData); return 1; } catch (...) { g_running.store(false, std::memory_order_release); @@ -407,6 +372,7 @@ VPE_API int VpeInputStartPolling(VpeInputEventCallback callback, void* userData, } VPE_API void VpeInputStopPolling(void) { + VpeInputStartControlCapture(0); if (!g_running.load(std::memory_order_acquire)) { return; } @@ -416,19 +382,18 @@ VPE_API void VpeInputStopPolling(void) { if (g_pollingThread.joinable()) { g_pollingThread.join(); } + g_input.Stop(); } VPE_API int VpeInputListDevices(VpeInputDeviceInfo* devices, int maxDevices) { - (void)devices; - (void)maxDevices; - return 0; + const int count = g_input.ListDevices(devices, maxDevices); + return g_controllers.AppendDevices(devices, maxDevices, count); } VPE_API int VpeInputListDeviceAxes(int deviceIndex, VpeInputAxisInfo* axes, int maxAxes) { - (void)deviceIndex; - (void)axes; - (void)maxAxes; - return 0; + return deviceIndex >= ControllerInput::FirstDeviceIndex + ? g_controllers.ListAxes(deviceIndex, axes, maxAxes) + : g_input.ListAxes(deviceIndex, axes, maxAxes); } VPE_API int64_t VpeGetTimestampUsec(void) { diff --git a/src/NativeInput_Mac.mm b/src/NativeInput_Mac.mm index f8b1262..2bd715a 100644 --- a/src/NativeInput_Mac.mm +++ b/src/NativeInput_Mac.mm @@ -3,7 +3,8 @@ #ifdef __APPLE__ -#include "NativeInput.h" +#include "ControllerInput.h" +#include "OpenPinballInput.h" #import #import @@ -23,7 +24,6 @@ struct KeyBindingState { VpeInputAction action; CGKeyCode nativeKeyCode; - float previousValue; }; std::thread g_pollingThread; @@ -31,12 +31,12 @@ std::atomic g_protocolVersionChecked(false); std::condition_variable g_waitCondition; std::mutex g_waitMutex; - VpeInputEventCallback g_callback = nullptr; - void* g_userData = nullptr; + OpenPinballDevice::Input g_input; + ControllerInput g_controllers; + std::mutex g_bindingsMutex; int g_pollIntervalUs = 500; Clock::time_point g_startTime; std::vector g_bindings; - bool g_wasForeground = false; int64_t GetTimestampUsecInternal() { return std::chrono::duration_cast(Clock::now() - g_startTime).count(); @@ -215,72 +215,33 @@ bool IsPressed(CGKeyCode nativeKeyCode) { return CGEventSourceKeyState(kCGEventSourceStateCombinedSessionState, nativeKeyCode); } - void EmitReleaseForPressedKeys(int64_t timestampUsec) { - if (g_callback == nullptr) { - for (auto& binding : g_bindings) { - binding.previousValue = 0.0f; - } - return; - } - - for (auto& binding : g_bindings) { - if (binding.previousValue <= 0.0f) { - continue; - } - - binding.previousValue = 0.0f; - - VpeInputEvent event{}; - event.timestampUsec = timestampUsec; - event.eventType = VPE_INPUT_EVENT_ACTION; - event.action = static_cast(binding.action); - event.value = 0.0f; - g_callback(&event, g_userData); - } - } - - void PollingThreadFunc() { + void PollingThreadFunc(VpeInputEventCallback callback, void* userData) { @autoreleasepool { VpeSetThreadPriority(); - + OpenPinballDevice::Transport transport(g_input); + g_controllers.Start(); while (g_running.load(std::memory_order_acquire)) { - const int64_t timestampUsec = GetTimestampUsecInternal(); - const bool isForeground = IsCurrentProcessForeground(); - - if (!isForeground) { - if (g_wasForeground) { - EmitReleaseForPressedKeys(timestampUsec); - } - g_wasForeground = false; - } else { - g_wasForeground = true; - - for (auto& binding : g_bindings) { - const float currentValue = IsPressed(binding.nativeKeyCode) ? 1.0f : 0.0f; - if (currentValue == binding.previousValue) { - continue; - } - - binding.previousValue = currentValue; - if (g_callback == nullptr) { - continue; + const int64_t timestamp = GetTimestampUsecInternal(); + OpenPinballDevice::Keys keys{}; + bool foreground; + { + std::lock_guard lock(g_bindingsMutex); + foreground = IsCurrentProcessForeground(); + if (foreground) { + for (const auto& binding : g_bindings) { + keys[binding.action] |= IsPressed(binding.nativeKeyCode); } - - VpeInputEvent event{}; - event.timestampUsec = timestampUsec; - event.eventType = VPE_INPUT_EVENT_ACTION; - event.action = static_cast(binding.action); - event.value = currentValue; - g_callback(&event, g_userData); } } + g_controllers.Poll(timestamp, foreground, callback, userData); + g_input.BeginPoll(timestamp, foreground, keys); + transport.Poll(timestamp); std::unique_lock lock(g_waitMutex); - g_waitCondition.wait_for( - lock, - std::chrono::microseconds(g_pollIntervalUs > 0 ? g_pollIntervalUs : 500), + g_waitCondition.wait_for(lock, std::chrono::microseconds(g_pollIntervalUs), [] { return !g_running.load(std::memory_order_acquire); }); } + g_controllers.Stop(); } } } @@ -289,8 +250,9 @@ void PollingThreadFunc() { VPE_API int VpeInputInit(void) { g_protocolVersionChecked.store(false, std::memory_order_release); + g_input.ResetGameplayGate(); + g_controllers.SetGameplayEnabled(true); g_startTime = Clock::now(); - g_wasForeground = false; return 1; } @@ -301,21 +263,22 @@ VPE_API int VpeInputGetProtocolVersion(void) { VPE_API void VpeInputShutdown(void) { VpeInputStopPolling(); + VpeInputSetButtonBindings(nullptr, 0); g_protocolVersionChecked.store(false, std::memory_order_release); g_bindings.clear(); - g_wasForeground = false; } VPE_API void VpeInputSetBindings(const VpeInputBinding* bindings, int count) { + std::lock_guard lock(g_bindingsMutex); g_bindings.clear(); - g_wasForeground = false; if (bindings == nullptr || count <= 0) { return; } for (int i = 0; i < count; ++i) { - if (bindings[i].bindingType != VPE_BINDING_KEYBOARD) { + if (bindings[i].bindingType != VPE_BINDING_KEYBOARD + || bindings[i].action < 0 || bindings[i].action >= VPE_INPUT_MAX) { continue; } @@ -327,25 +290,27 @@ VPE_API void VpeInputSetBindings(const VpeInputBinding* bindings, int count) { g_bindings.push_back({ static_cast(bindings[i].action), nativeKeyCode, - 0.0f, }); } } +VPE_API void VpeInputSetGameplayInputEnabled(int enabled) { + g_input.SetGameplayEnabled(enabled); + g_controllers.SetGameplayEnabled(enabled != 0); +} + VPE_API int VpeInputStartPolling(VpeInputEventCallback callback, void* userData, int pollIntervalUs) { if (!g_protocolVersionChecked.load(std::memory_order_acquire) || g_running.load(std::memory_order_acquire)) { return 0; } - g_callback = callback; - g_userData = userData; + g_input.Start(callback, userData); g_pollIntervalUs = pollIntervalUs > 0 ? pollIntervalUs : 500; - g_wasForeground = false; g_running.store(true, std::memory_order_release); try { - g_pollingThread = std::thread(PollingThreadFunc); + g_pollingThread = std::thread(PollingThreadFunc, callback, userData); return 1; } catch (...) { g_running.store(false, std::memory_order_release); @@ -354,6 +319,7 @@ VPE_API int VpeInputStartPolling(VpeInputEventCallback callback, void* userData, } VPE_API void VpeInputStopPolling(void) { + VpeInputStartControlCapture(0); if (!g_running.load(std::memory_order_acquire)) { return; } @@ -363,19 +329,18 @@ VPE_API void VpeInputStopPolling(void) { if (g_pollingThread.joinable()) { g_pollingThread.join(); } + g_input.Stop(); } VPE_API int VpeInputListDevices(VpeInputDeviceInfo* devices, int maxDevices) { - (void)devices; - (void)maxDevices; - return 0; + const int count = g_input.ListDevices(devices, maxDevices); + return g_controllers.AppendDevices(devices, maxDevices, count); } VPE_API int VpeInputListDeviceAxes(int deviceIndex, VpeInputAxisInfo* axes, int maxAxes) { - (void)deviceIndex; - (void)axes; - (void)maxAxes; - return 0; + return deviceIndex >= ControllerInput::FirstDeviceIndex + ? g_controllers.ListAxes(deviceIndex, axes, maxAxes) + : g_input.ListAxes(deviceIndex, axes, maxAxes); } VPE_API int64_t VpeGetTimestampUsec(void) { diff --git a/src/NativeInput_Windows.cpp b/src/NativeInput_Windows.cpp index a252db5..76fb4b5 100644 --- a/src/NativeInput_Windows.cpp +++ b/src/NativeInput_Windows.cpp @@ -3,7 +3,10 @@ #ifdef _WIN32 +#include "ControllerInput.h" +#include "NativeButtons.h" #include "NativeInput.h" +#include "OpenPinballDevice.h" #ifndef NOMINMAX #define NOMINMAX @@ -20,6 +23,8 @@ #include #include #include +#include +#include #include #include #include @@ -33,11 +38,15 @@ namespace { constexpr USAGE UsageMultiAxisController = 0x08; constexpr USAGE UsageAxisMin = 0x30; constexpr USAGE UsageAxisMax = 0x38; + constexpr USAGE UsageHat = 0x39; + constexpr int HatButtonBase = 0x20000; - struct KeyBindingState { - int keyCode; + struct ActionBindingState { VpeInputAction action; - float previousValue; + std::vector keys; + uint32_t opdMask = 0; + bool keyPressed = false; + OpenPinballDevice::ActionLatch latch; }; struct AxisDescriptor { @@ -48,6 +57,14 @@ namespace { float previousValue; float rawValue; int64_t timestampUsec; + const OpenPinballDevice::Axis* opdAxis = nullptr; + bool samplePending = false; + float bindingValue = std::numeric_limits::quiet_NaN(); + }; + + struct HatDescriptor { + HIDP_VALUE_CAPS caps; + uint8_t directions = 0; }; struct HidDevice { @@ -59,20 +76,38 @@ namespace { PHIDP_PREPARSED_DATA preparsedData = nullptr; HIDP_CAPS caps = {}; std::vector axes; + std::vector hats; + std::vector buttons; + std::vector buttonReportIds; + std::vector buttonData; + std::vector pressedDataIndices; + bool controlsRegistered = false; std::vector inputReport; OVERLAPPED readOverlap = {}; HANDLE readEvent = NULL; bool readPending = false; bool isConnected = true; + bool isOpd = false; + uint8_t opdReportId = 0; + uint32_t opdButtons = 0; + OpenPinballDevice::Clock opdClock; }; struct PendingAxisEvent { + int64_t timestampUsec; int deviceIndex; int axisId; float value; }; + struct PendingButtons { + int64_t timestampUsec; + uint32_t mask; + uint64_t configurable; + }; + std::thread g_pollingThread; + ControllerInput g_controllers; std::atomic g_running(false); std::atomic g_protocolVersionChecked(false); VpeInputEventCallback g_callback = nullptr; @@ -81,10 +116,13 @@ namespace { HANDLE g_timer = NULL; HANDLE g_stopEvent = NULL; - std::mutex g_bindingsMutex; // guards g_bindings and g_wasForeground between API calls and the polling thread - std::vector g_bindings; + std::mutex g_bindingsMutex; + std::vector g_bindings; + bool g_gameplayInputEnabled = true; + bool g_gameplayGateConfigured = false; std::mutex g_hidDevicesMutex; // guards the live polling device snapshot and axis telemetry - std::vector g_hidDevices; + // ReadFile retains each OVERLAPPED address until completion or cancellation. + std::deque g_hidDevices; // Hotplug handling (polling thread only, except the atomic request flag): // a cheap present-interface probe runs every couple of seconds, and a full @@ -95,7 +133,6 @@ namespace { LARGE_INTEGER g_frequency; LARGE_INTEGER g_startTime; - bool g_wasForeground = false; int64_t GetTimestampUsecInternal() { if (g_frequency.QuadPart == 0) { @@ -205,14 +242,28 @@ namespace { g_callback(&event, g_userData); } - void EmitReleaseForPressedKeys(int64_t timestampUsec) { + ActionBindingState& GetBinding(VpeInputAction action) { for (auto& binding : g_bindings) { - if (binding.previousValue <= 0.0f) { - continue; - } + if (binding.action == action) return binding; + } + g_bindings.push_back({action}); + return g_bindings.back(); + } - binding.previousValue = 0.0f; - EmitActionEvent(timestampUsec, binding.action, 0.0f); + void AddOpdBindings() { + for (size_t bit = 0; bit < std::size(OpenPinballDevice::ButtonActions); ++bit) { + GetBinding(OpenPinballDevice::ButtonActions[bit]).opdMask |= uint32_t{1} << bit; + } + } + + void PublishActions(int64_t timestampUsec, bool enabled, uint32_t opdButtons, uint64_t configurable) { + for (auto& binding : g_bindings) { + const bool pressed = binding.keyPressed || (binding.opdMask & opdButtons) != 0 + || (configurable & (uint64_t{1} << binding.action)) != 0; + bool value; + if (binding.latch.Update(pressed, enabled, value)) { + EmitActionEvent(timestampUsec, binding.action, value ? 1.0f : 0.0f); + } } } @@ -220,6 +271,10 @@ namespace { if (valueCaps.UsagePage != UsagePageGenericDesktop) { return; } + const bool hasHat = valueCaps.IsRange + ? valueCaps.Range.UsageMin <= UsageHat && UsageHat <= valueCaps.Range.UsageMax + : valueCaps.NotRange.Usage == UsageHat; + if (hasHat && !valueCaps.IsAlias) device.hats.push_back({valueCaps}); if (valueCaps.IsRange) { for (USAGE usage = valueCaps.Range.UsageMin; usage <= valueCaps.Range.UsageMax; usage++) { @@ -280,6 +335,10 @@ namespace { } void CloseHidDevice(HidDevice& device) { + if (device.controlsRegistered) { + NativeButtons::GetState().Disconnect(device.deviceIndex); + device.controlsRegistered = false; + } if (device.handle != INVALID_HANDLE_VALUE) { if (device.readPending) { CancelIoEx(device.handle, &device.readOverlap); @@ -303,7 +362,7 @@ namespace { } } - void CloseHidDevices(std::vector& devices) { + void CloseHidDevices(std::deque& devices) { for (auto& device : devices) { CloseHidDevice(device); } @@ -359,6 +418,78 @@ namespace { return paths; } + bool OpenOpdCollection(HidDevice& device) { + const auto& caps = device.caps; + if (caps.UsagePage != OpenPinballDevice::UsagePage || caps.Usage != OpenPinballDevice::Usage + || caps.NumberInputButtonCaps != 1 || caps.NumberInputValueCaps != 0 + || caps.InputReportByteLength < OpenPinballDevice::ReportIdSize + 16) { + return false; + } + + // Windows exposes OPD's opaque HID array as a button capability. The + // indexed usage string is the protocol signature, independent of VID/PID. + HIDP_BUTTON_CAPS field{}; + USHORT count = 1; + if (HidP_GetButtonCaps(HidP_Input, &field, &count, device.preparsedData) != HIDP_STATUS_SUCCESS + || count != 1 || field.UsagePage != caps.UsagePage) { + return false; + } + const auto usage = field.IsRange ? field.Range.UsageMin : field.NotRange.Usage; + const auto stringIndex = field.IsRange ? field.Range.StringMin : field.NotRange.StringIndex; + if (usage != 0 || (field.IsRange && field.Range.UsageMax != 0) || field.IsStringRange || stringIndex == 0) return false; + + wchar_t signature[128] = {}; + if (!HidD_GetIndexedString(device.handle, stringIndex, signature, sizeof(signature)) + || !OpenPinballDevice::SupportsVersion(std::wstring_view(signature, std::find(std::begin(signature), std::end(signature), L'\0') - signature))) { + return false; + } + + device.isOpd = true; + device.opdReportId = field.ReportID; + device.displayName += " (OPD)"; + for (const auto& axis : OpenPinballDevice::Axes) { + if (axis.offset + 2 + OpenPinballDevice::ReportIdSize <= caps.InputReportByteLength) { + device.axes.push_back({axis.id, caps.UsagePage, caps.Usage, {}, + std::numeric_limits::quiet_NaN(), 0.0f, 0, &axis}); + } + } + return true; + } + + void DescribeHidButtons(HidDevice& device) { + USHORT count = device.caps.NumberInputButtonCaps; + if (count == 0) return; + std::vector caps(count); + if (HidP_GetButtonCaps(HidP_Input, caps.data(), &count, device.preparsedData) != HIDP_STATUS_SUCCESS) return; + device.buttonReportIds.assign(device.caps.NumberInputDataIndices, -1); + for (USHORT i = 0; i < count; ++i) { + const auto& cap = caps[i]; + if (cap.UsagePage != 0x09) continue; + const unsigned firstIndex = cap.IsRange ? cap.Range.DataIndexMin : cap.NotRange.DataIndex; + const unsigned lastIndex = cap.IsRange ? cap.Range.DataIndexMax : cap.NotRange.DataIndex; + const unsigned firstUsage = cap.IsRange ? cap.Range.UsageMin : cap.NotRange.Usage; + for (unsigned index = firstIndex; index <= lastIndex && index < device.buttonReportIds.size(); ++index) { + if (device.buttonReportIds[index] != -1) continue; + device.buttonReportIds[index] = cap.ReportID; + VpeInputButtonInfo button{}; + button.buttonId = static_cast(index); + std::snprintf(button.name, sizeof(button.name), "Button %u", firstUsage + index - firstIndex); + device.buttons.push_back(button); + } + } + if (device.buttons.empty()) return; + device.buttonData.resize(HidP_MaxDataListLength(HidP_Input, device.preparsedData)); + device.pressedDataIndices.resize(device.buttonReportIds.size()); + } + + void RegisterHidControls(HidDevice& device) { + if (device.buttons.empty() && device.axes.empty()) return; + std::vector axisIds; + for (const auto& axis : device.axes) axisIds.push_back(axis.axisId); + NativeButtons::GetState().Connect(device.deviceIndex, device.stableId, std::move(device.buttons), axisIds); + device.controlsRegistered = true; + } + bool OpenHidDevice(const std::wstring& path, bool overlapped, HidDevice& device) { const DWORD flags = FILE_ATTRIBUTE_NORMAL | (overlapped ? FILE_FLAG_OVERLAPPED : 0); // Listing only needs to query HID metadata, which works with zero access @@ -414,17 +545,33 @@ namespace { } } - if (!DeviceLooksLikeJoystick(device.caps)) { + if (!DeviceLooksLikeJoystick(device.caps) && !OpenOpdCollection(device)) { CloseHidDevice(device); return false; } - if (device.axes.empty() || device.caps.InputReportByteLength == 0) { + if (device.isOpd) device.buttons = NativeButtons::OpdGenericButtons(); + else { + DescribeHidButtons(device); + constexpr const char* directions[] = {"Up", "Right", "Down", "Left"}; + for (size_t hat = 0; hat < device.hats.size(); ++hat) { + for (int direction = 0; direction < 4; ++direction) { + VpeInputButtonInfo button{}; + button.buttonId = HatButtonBase + static_cast(hat * 4) + direction; + std::snprintf(button.name, sizeof(button.name), "Hat %zu %s", hat + 1, directions[direction]); + device.buttons.push_back(button); + } + } + } + if ((!device.isOpd && device.axes.empty() && device.buttons.empty()) || device.caps.InputReportByteLength == 0) { CloseHidDevice(device); return false; } device.inputReport.resize(device.caps.InputReportByteLength); if (overlapped) { + // Motion reports contain current levels. Keep the driver queue short + // so a scheduling stall doesn't turn into a burst of old nudges. + if (device.isOpd) HidD_SetNumInputBuffers(device.handle, 4); device.readEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (device.readEvent == NULL) { CloseHidDevice(device); @@ -435,7 +582,7 @@ namespace { return true; } - void EnumerateHidDevices(std::vector& devices, bool openForPolling) { + void EnumerateHidDevices(std::deque& devices, bool openForPolling) { CloseHidDevices(devices); GUID hidGuid; @@ -471,6 +618,7 @@ namespace { } device.deviceIndex = static_cast(devices.size()); devices.push_back(std::move(device)); + if (openForPolling) RegisterHidControls(devices.back()); } SetupDiDestroyDeviceInfoList(deviceInfoSet); @@ -486,6 +634,7 @@ namespace { } fresh.deviceIndex = device.deviceIndex; device = std::move(fresh); + RegisterHidControls(device); return true; } @@ -535,10 +684,11 @@ namespace { } HidDevice device{}; if (!OpenHidDevice(presentPaths[i], true, device)) { - continue; // not a joystick-style device (or open failed) + continue; } device.deviceIndex = static_cast(g_hidDevices.size()); g_hidDevices.push_back(std::move(device)); + RegisterHidControls(g_hidDevices.back()); changed = true; } @@ -559,19 +709,102 @@ namespace { destination.axisId = source.axisId; destination.usagePage = source.usagePage; destination.usage = source.usage; - destination.kind = VPE_AXIS_KIND_POSITION; + destination.kind = source.opdAxis ? source.opdAxis->kind : VPE_AXIS_KIND_POSITION; destination.rawValue = source.rawValue; destination.timestampUsec = source.timestampUsec; - CopyString(destination.name, VPE_INPUT_AXIS_NAME_SIZE, AxisName(source.usage)); + CopyString(destination.name, VPE_INPUT_AXIS_NAME_SIZE, source.opdAxis ? source.opdAxis->name : AxisName(source.usage)); } - void ParseInputReport(HidDevice& device, int64_t timestampUsec, std::vector& pendingEvents) { - if (device.preparsedData == nullptr || device.inputReport.empty()) { + // Called with the HID snapshot locked. Aggregate by protocol bit so a + // second controller holding the same button keeps the action pressed. + void CaptureButtons(int64_t timestampUsec, std::vector& changes) { + uint32_t buttons = 0; + for (const auto& device : g_hidDevices) { + if (device.isOpd && device.isConnected) buttons |= device.opdButtons; + } + const uint64_t configurable = NativeButtons::GetState().PressedActions(); + if (changes.empty() || changes.back().mask != buttons || changes.back().configurable != configurable) { + changes.push_back({timestampUsec, buttons, configurable}); + } + } + + bool ReadHidButtonData(HidDevice& device, char* report, ULONG reportLength) { + if (device.buttonData.empty()) return false; + ULONG count = static_cast(device.buttonData.size()); + if (HidP_GetData(HidP_Input, device.buttonData.data(), &count, device.preparsedData, report, reportLength) + != HIDP_STATUS_SUCCESS) return false; + std::fill(device.pressedDataIndices.begin(), device.pressedDataIndices.end(), 0); + for (ULONG i = 0; i < count; ++i) { + const auto index = device.buttonData[i].DataIndex; + if (index < device.pressedDataIndices.size()) device.pressedDataIndices[index] = 1; + } + return true; + } + + void ReadHidHats(HidDevice& device, char* report, ULONG reportLength) { + constexpr uint8_t directions[] = {1, 3, 2, 6, 4, 12, 8, 9}; // clockwise from up + for (auto& hat : device.hats) { + ULONG value = 0; + if (HidP_GetUsageValue(HidP_Input, UsagePageGenericDesktop, hat.caps.LinkCollection, UsageHat, + &value, device.preparsedData, report, reportLength) != HIDP_STATUS_SUCCESS) continue; + const auto offset = static_cast(value) - hat.caps.LogicalMin; + const auto range = static_cast(hat.caps.LogicalMax) - hat.caps.LogicalMin + 1; + hat.directions = 0; + if (offset >= 0 && offset < range && (range == 4 || range == 8)) + hat.directions = directions[offset * (8 / range)]; + } + } + + void PublishHidAxis(AxisDescriptor& axis, int deviceIndex, int64_t timestampUsec, + std::vector& pendingEvents) { + axis.samplePending = false; + if (std::isnan(axis.previousValue) || std::fabs(axis.rawValue - axis.previousValue) > 0.0001f) { + axis.previousValue = axis.rawValue; + pendingEvents.push_back({timestampUsec, deviceIndex, axis.axisId, axis.rawValue}); + } + } + + void ParseInputReport(HidDevice& device, DWORD bytesRead, int64_t timestampUsec, bool publishAxes, + std::vector& pendingEvents, std::vector& buttons) { + if (device.preparsedData == nullptr || bytesRead != device.inputReport.size()) { + return; + } + if (device.isOpd) { + OpenPinballDevice::Report report{}; + if (!OpenPinballDevice::Report::Read(device.inputReport.data(), bytesRead, device.opdReportId, report)) { + return; + } + // Button levels are authoritative even if a firmware repeats its clock. + const auto buttonMask = report.PinballButtons(); + const auto genericMask = report.GenericButtons(); + auto bindingAxis = device.axes.begin(); + const bool controlsChanged = NativeButtons::GetState().Update(device.deviceIndex, [&](const auto& button) { + return (genericMask & (uint32_t{1} << button.buttonId)) != 0; + }, [&](int, float previous) { + float value; + return report.TryReadAxis(*(bindingAxis++)->opdAxis, value) ? value : previous; + }); + if (device.opdButtons != buttonMask || controlsChanged) { + device.opdButtons = buttonMask; + CaptureButtons(timestampUsec, buttons); + } + int64_t sampleUsec; + if (!device.opdClock.Translate(report.Timestamp(), timestampUsec, sampleUsec)) return; + for (auto& axis : device.axes) { + float value; + if (report.TryReadAxis(*axis.opdAxis, value)) { + axis.rawValue = value; + axis.timestampUsec = sampleUsec; + if (publishAxes) pendingEvents.push_back({sampleUsec, device.deviceIndex, axis.axisId, value}); + } + } return; } auto* report = reinterpret_cast(device.inputReport.data()); const ULONG reportLength = static_cast(device.inputReport.size()); + const bool buttonsRead = ReadHidButtonData(device, report, reportLength); + ReadHidHats(device, report, reportLength); for (auto& axis : device.axes) { ULONG value = 0; const NTSTATUS status = HidP_GetUsageValue( @@ -588,19 +821,30 @@ namespace { } const float normalized = NormalizeAxisValue(value, axis.valueCaps); + axis.bindingValue = normalized; if (std::isnan(normalized)) { continue; } axis.rawValue = normalized; axis.timestampUsec = timestampUsec; - if (std::isnan(axis.previousValue) || std::fabs(normalized - axis.previousValue) > 0.0001f) { - axis.previousValue = normalized; - pendingEvents.push_back({ device.deviceIndex, axis.axisId, normalized }); + if (publishAxes) PublishHidAxis(axis, device.deviceIndex, timestampUsec, pendingEvents); + else axis.samplePending = true; + } + auto bindingAxis = device.axes.begin(); + const bool controlsChanged = NativeButtons::GetState().Update(device.deviceIndex, [&](const auto& button) { + if (button.buttonId >= HatButtonBase) { + const int offset = button.buttonId - HatButtonBase; + return (device.hats[offset / 4].directions & (1 << (offset % 4))) != 0; } - } + // Reports for other IDs leave these button levels untouched. + return buttonsRead && device.buttonReportIds[button.buttonId] == device.inputReport[0] + ? device.pressedDataIndices[button.buttonId] != 0 : button.isPressed != 0; + }, [&](int, float) { return (bindingAxis++)->bindingValue; }); + if (controlsChanged) CaptureButtons(timestampUsec, buttons); } - void StartHidRead(HidDevice& device, int64_t timestampUsec, std::vector& pendingEvents) { + void StartHidRead(HidDevice& device, int64_t timestampUsec, bool publishAxes, + std::vector& pendingEvents, std::vector& buttons) { if (device.handle == INVALID_HANDLE_VALUE || device.readPending || device.inputReport.empty()) { return; } @@ -614,7 +858,7 @@ namespace { &bytesRead, &device.readOverlap); if (ok) { - ParseInputReport(device, timestampUsec, pendingEvents); + ParseInputReport(device, bytesRead, timestampUsec, publishAxes, pendingEvents, buttons); return; } @@ -629,7 +873,8 @@ namespace { } } - void CompleteHidRead(HidDevice& device, int64_t timestampUsec, std::vector& pendingEvents) { + void CompleteHidRead(HidDevice& device, int64_t timestampUsec, bool publishAxes, + std::vector& pendingEvents, std::vector& buttons) { if (!device.readPending || device.readEvent == NULL) { return; } @@ -641,7 +886,7 @@ namespace { const BOOL ok = GetOverlappedResult(device.handle, &device.readOverlap, &bytesRead, FALSE); device.readPending = false; if (ok && bytesRead > 0) { - ParseInputReport(device, timestampUsec, pendingEvents); + ParseInputReport(device, bytesRead, timestampUsec, publishAxes, pendingEvents, buttons); } else if (!ok) { // Read completed with failure — typically device removal mid-read. DisconnectHidDevice(device); @@ -649,19 +894,37 @@ namespace { } } - void PollHidDevices(int64_t timestampUsec, std::vector& pendingEvents) { + bool PollHidDevices(int64_t timestampUsec, bool foreground, bool publishAxes, bool refreshRawAxes, + std::vector& pendingEvents, std::vector& buttons) { pendingEvents.clear(); + buttons.clear(); + bool disconnected = false; { std::lock_guard lock(g_hidDevicesMutex); + CaptureButtons(timestampUsec, buttons); for (auto& device : g_hidDevices) { - CompleteHidRead(device, timestampUsec, pendingEvents); - StartHidRead(device, timestampUsec, pendingEvents); + // Keep draining button reports in the background so buffered + // edges aren't replayed on returning to the game. + if (!foreground && !device.controlsRegistered) continue; + const bool wasConnected = device.isConnected; + const size_t firstEvent = pendingEvents.size(); + CompleteHidRead(device, timestampUsec, publishAxes, pendingEvents, buttons); + StartHidRead(device, timestampUsec, publishAxes, pendingEvents, buttons); + if (wasConnected && !device.isConnected) { + disconnected = true; + pendingEvents.resize(firstEvent); + CaptureButtons(timestampUsec, buttons); + } else if (refreshRawAxes && device.isConnected && !device.isOpd) { + // Reports drained while gameplay is disabled may be the only + // samples from a device that reports axis changes on demand. + for (auto& axis : device.axes) { + if (axis.samplePending) PublishHidAxis(axis, device.deviceIndex, timestampUsec, pendingEvents); + } + } } } - for (const auto& event : pendingEvents) { - EmitAxisEvent(timestampUsec, event.deviceIndex, event.axisId, event.value); - } + return disconnected; } // Runs on the polling thread: cheap present-interface probe on a fixed @@ -709,36 +972,46 @@ namespace { const HANDLE handles[2] = { g_timer, g_stopEvent }; std::vector pendingAxisEvents; + std::vector pendingButtons; int64_t nextHotplugCheckUsec = 0; bool hotplugReconcilePending = false; + bool wasPublishingAxes = false; + g_controllers.Start(); while (g_running.load(std::memory_order_acquire)) { const int64_t timestampUsec = GetTimestampUsecInternal(); CheckHotplug(timestampUsec, nextHotplugCheckUsec, hotplugReconcilePending); const bool isForeground = IsCurrentProcessForeground(); - if (!isForeground) { + g_controllers.Poll(timestampUsec, isForeground, g_callback, g_userData); + bool publishAxes; + { + std::lock_guard lock(g_bindingsMutex); + publishAxes = isForeground && g_gameplayInputEnabled; + } + const bool refreshRawAxes = publishAxes && !wasPublishingAxes; + const bool disconnected = PollHidDevices(timestampUsec, isForeground, publishAxes, + refreshRawAxes, pendingAxisEvents, pendingButtons); + wasPublishingAxes = publishAxes; + { std::lock_guard lock(g_bindingsMutex); - if (g_wasForeground) { - EmitReleaseForPressedKeys(timestampUsec); + for (auto& binding : g_bindings) { + binding.keyPressed = isForeground && std::any_of(binding.keys.begin(), binding.keys.end(), [](int key) { + return (GetAsyncKeyState(key) & 0x8000) != 0; + }); } - g_wasForeground = false; - } else { - { - std::lock_guard lock(g_bindingsMutex); - g_wasForeground = true; - - for (auto& binding : g_bindings) { - SHORT keyState = GetAsyncKeyState(binding.keyCode); - bool isPressed = (keyState & 0x8000) != 0; - float currentValue = isPressed ? 1.0f : 0.0f; - - if (currentValue != binding.previousValue) { - binding.previousValue = currentValue; - EmitActionEvent(timestampUsec, binding.action, currentValue); - } + if (!isForeground && !g_gameplayGateConfigured) { + // Preserve focus-loss releases for clients predating the optional gate. + PublishActions(timestampUsec, true, 0, 0); + } else { + for (const auto& state : pendingButtons) { + PublishActions(state.timestampUsec, isForeground && g_gameplayInputEnabled, state.mask, state.configurable); } } - - PollHidDevices(timestampUsec, pendingAxisEvents); + } + if (disconnected) EmitDevicesChangedEvent(timestampUsec); + if (publishAxes) { + for (const auto& event : pendingAxisEvents) { + EmitAxisEvent(event.timestampUsec, event.deviceIndex, event.axisId, event.value); + } } if (g_pollIntervalUs > 0 && g_timer != NULL) { @@ -756,6 +1029,7 @@ namespace { } } } + g_controllers.Stop(); } } @@ -763,6 +1037,7 @@ extern "C" { VPE_API int VpeInputInit(void) { g_protocolVersionChecked.store(false, std::memory_order_release); + g_controllers.SetGameplayEnabled(true); // Only establish the timestamp epoch once; a re-init while a consumer is // live must not make timestamps jump backwards. @@ -788,10 +1063,13 @@ VPE_API int VpeInputGetProtocolVersion(void) { VPE_API void VpeInputShutdown(void) { VpeInputStopPolling(); + VpeInputSetButtonBindings(nullptr, 0); g_protocolVersionChecked.store(false, std::memory_order_release); { std::lock_guard lock(g_bindingsMutex); g_bindings.clear(); + g_gameplayInputEnabled = true; + g_gameplayGateConfigured = false; } { std::lock_guard lock(g_hidDevicesMutex); @@ -809,18 +1087,24 @@ VPE_API void VpeInputShutdown(void) { VPE_API void VpeInputSetBindings(const VpeInputBinding* bindings, int count) { std::lock_guard lock(g_bindingsMutex); - g_bindings.clear(); - g_wasForeground = false; - - for (int i = 0; i < count; i++) { - if (bindings[i].bindingType == VPE_BINDING_KEYBOARD) { - g_bindings.push_back({ - bindings[i].keyCode, - static_cast(bindings[i].action), - 0.0f, - }); + // A live remap only replaces keyboard sources. Keep action latches so + // previously published presses can still release after remapping or pause. + for (auto& binding : g_bindings) binding.keys.clear(); + + for (int i = 0; bindings != nullptr && i < count; i++) { + if (bindings[i].bindingType == VPE_BINDING_KEYBOARD + && bindings[i].action >= 0 && bindings[i].action < VPE_INPUT_MAX) { + GetBinding(static_cast(bindings[i].action)).keys.push_back(bindings[i].keyCode); } } + AddOpdBindings(); +} + +VPE_API void VpeInputSetGameplayInputEnabled(int enabled) { + std::lock_guard lock(g_bindingsMutex); + g_gameplayGateConfigured = true; + g_gameplayInputEnabled = enabled != 0; + g_controllers.SetGameplayEnabled(enabled != 0); } VPE_API int VpeInputStartPolling(VpeInputEventCallback callback, void* userData, int pollIntervalUs) { @@ -831,7 +1115,13 @@ VPE_API int VpeInputStartPolling(VpeInputEventCallback callback, void* userData, g_callback = callback; g_userData = userData; g_pollIntervalUs = pollIntervalUs; - g_wasForeground = false; + { + std::lock_guard lock(g_bindingsMutex); + AddOpdBindings(); + for (auto& binding : g_bindings) { + binding.latch = {}; + } + } if (g_stopEvent != NULL) { ResetEvent(g_stopEvent); } @@ -839,8 +1129,8 @@ VPE_API int VpeInputStartPolling(VpeInputEventCallback callback, void* userData, std::lock_guard lock(g_hidDevicesMutex); EnumerateHidDevices(g_hidDevices, true); } - // Baseline for the hotplug probe; the polling thread reconciles against this. - g_lastHidInterfaceList = GetHidInterfaceList(); + // Reconcile on the first poll too, in case a device appeared during enumeration. + g_lastHidInterfaceList.clear(); g_hotplugCheckRequested.store(false, std::memory_order_release); g_running.store(true, std::memory_order_release); @@ -858,6 +1148,7 @@ VPE_API int VpeInputStartPolling(VpeInputEventCallback callback, void* userData, } VPE_API void VpeInputStopPolling(void) { + VpeInputStartControlCapture(0); if (g_running.load(std::memory_order_acquire)) { g_running.store(false, std::memory_order_release); if (g_stopEvent != NULL) { @@ -886,10 +1177,10 @@ VPE_API int VpeInputListDevices(VpeInputDeviceInfo* devices, int maxDevices) { CopyDeviceInfo(g_hidDevices[i], devices[i]); } } - return count; + return g_controllers.AppendDevices(devices, maxDevices, count); } - std::vector enumeratedDevices; + std::deque enumeratedDevices; EnumerateHidDevices(enumeratedDevices, false); const int count = static_cast(enumeratedDevices.size()); if (devices != nullptr && maxDevices > 0) { @@ -903,6 +1194,9 @@ VPE_API int VpeInputListDevices(VpeInputDeviceInfo* devices, int maxDevices) { } VPE_API int VpeInputListDeviceAxes(int deviceIndex, VpeInputAxisInfo* axes, int maxAxes) { + if (deviceIndex >= ControllerInput::FirstDeviceIndex) { + return g_controllers.ListAxes(deviceIndex, axes, maxAxes); + } if (g_running.load(std::memory_order_acquire)) { std::lock_guard lock(g_hidDevicesMutex); if (deviceIndex < 0 || deviceIndex >= static_cast(g_hidDevices.size())) { @@ -919,7 +1213,7 @@ VPE_API int VpeInputListDeviceAxes(int deviceIndex, VpeInputAxisInfo* axes, int return count; } - std::vector enumeratedDevices; + std::deque enumeratedDevices; EnumerateHidDevices(enumeratedDevices, false); if (deviceIndex < 0 || deviceIndex >= static_cast(enumeratedDevices.size())) { CloseHidDevices(enumeratedDevices); diff --git a/src/OpenPinballDescriptor.h b/src/OpenPinballDescriptor.h new file mode 100644 index 0000000..e905095 --- /dev/null +++ b/src/OpenPinballDescriptor.h @@ -0,0 +1,142 @@ +// license:GPLv3+ +#pragma once + +#include "OpenPinballDevice.h" + +#include +#include +#include + +namespace OpenPinballDevice { + constexpr size_t MaxDescriptorSize = 4096; + constexpr size_t MaxReportSize = 4096; + enum class ProbeResult { Found, NotOpd, Retry }; + + constexpr int64_t NextProbe(ProbeResult result, int64_t timestamp) { + // Recheck access failures in case the OS is still setting permissions. + return result == ProbeResult::NotOpd ? std::numeric_limits::max() : timestamp + 5000000; + } + + struct Descriptor { + uint8_t reportId = 0; + uint8_t stringIndex = 0; + size_t payloadSize = 0; + }; + + // OPD puts its whole payload in one opaque byte-array Input item. Walk the + // surrounding HID items to locate it even on a composite HID interface. + inline Descriptor FindDescriptor(const unsigned char* bytes, size_t size) { + struct Globals { + uint32_t usagePage = 0; + uint32_t reportSize = 0; + uint32_t reportCount = 0; + uint8_t reportId = 0; + } globals; + struct Locals { + uint32_t usage = 0; + uint32_t stringIndex = 0; + bool hasUsage = false; + bool complex = false; + } locals; + std::vector stack; + std::array inputBits{}; + Descriptor match; + size_t depth = 0; + bool isPinball = false; + + for (size_t offset = 0; offset < size;) { + const auto item = bytes[offset++]; + if (item == 0xfe) { + if (size - offset < 2 || bytes[offset] > size - offset - 2) return {}; + offset += 2 + bytes[offset]; + continue; + } + const size_t code = item & 3; + const size_t length = code == 3 ? 4 : code; + if (length > size - offset) return {}; + const auto value = static_cast(ReadUnsigned(bytes + offset, length)); + offset += length; + + switch (item & 0xfc) { + case 0x04: globals.usagePage = value; break; + case 0x74: globals.reportSize = value; break; + case 0x84: + if (value == 0 || value > 255) return {}; + globals.reportId = static_cast(value); + break; + case 0x94: globals.reportCount = value; break; + case 0xa4: stack.push_back(globals); break; + case 0xb4: + if (stack.empty()) return {}; + globals = stack.back(); + stack.pop_back(); + break; + case 0x08: + locals.complex |= locals.hasUsage; + locals.hasUsage = true; + locals.usage = length == 4 ? value : (globals.usagePage << 16) | value; + break; + case 0x78: + locals.complex |= locals.stringIndex != 0; + locals.stringIndex = value; + break; + case 0x18: case 0x28: // Usage Minimum/Maximum + case 0x88: case 0x98: // String Minimum/Maximum + case 0xa8: // Delimiter + locals.complex = true; + break; + case 0xa0: + if (depth++ == 0) { + isPinball = value == 1 && !locals.complex && locals.hasUsage + && locals.usage == ((uint32_t{UsagePage} << 16) | Usage); + } + break; + case 0xc0: + if (depth == 0) return {}; + if (--depth == 0) isPinball = false; + break; + case 0x80: { + if (globals.reportSize > MaxReportSize * 8 || globals.reportCount > MaxReportSize * 8) return {}; + inputBits[globals.reportId] += uint64_t{globals.reportSize} * globals.reportCount; + if (isPinball && (value & 0x03) == 0 && globals.reportSize == 8 + && globals.reportCount >= 16 && globals.reportCount <= MaxReportSize - (globals.reportId != 0) + && !locals.complex && locals.hasUsage && locals.usage == (uint32_t{UsagePage} << 16) + && locals.stringIndex > 0 && locals.stringIndex <= 255) { + if (match.stringIndex != 0) return {}; + match = {globals.reportId, static_cast(locals.stringIndex), globals.reportCount}; + } + break; + } + } + if ((item & 0x0c) == 0) locals = {}; + } + + if (depth != 0 || !stack.empty() || inputBits[match.reportId] != match.payloadSize * 8) return {}; + return match; + } + + // Read the USB language table first. The OPD signature itself is ASCII + // encoded as a USB UTF-16LE string descriptor. + template + ProbeResult VerifySignature(uint8_t index, ReadString readString) { + std::array bytes{}; + const auto length = [&](int size) { + return size >= 2 && bytes[1] == 3 && bytes[0] <= size && bytes[0] >= 2 + && bytes[0] % 2 == 0 ? bytes[0] : 0; + }; + const int languages = readString(0, 0, bytes); + if (languages < 0) return ProbeResult::Retry; + if (length(languages) < 4) return ProbeResult::NotOpd; + const auto language = static_cast(ReadUnsigned(bytes.data() + 2, 2)); + const int received = readString(index, language, bytes); + if (received < 0) return ProbeResult::Retry; + const int size = length(received); + std::array signature{}; + for (int i = 2; i < size; i += 2) { + if (bytes[i + 1] != 0) return ProbeResult::NotOpd; + signature[(i - 2) / 2] = bytes[i]; + } + return size > 2 && SupportsVersion(std::wstring_view(signature.data(), (size - 2) / 2)) + ? ProbeResult::Found : ProbeResult::NotOpd; + } +} diff --git a/src/OpenPinballDevice.h b/src/OpenPinballDevice.h new file mode 100644 index 0000000..1dedaae --- /dev/null +++ b/src/OpenPinballDevice.h @@ -0,0 +1,143 @@ +// license:GPLv3+ +#pragma once + +#include "NativeInput.h" +#include +#include +#include + +namespace OpenPinballDevice { + constexpr uint16_t UsagePage = 0x05; + constexpr uint16_t Usage = 0x02; + constexpr size_t ReportIdSize = 1; + + struct Axis { + int id; + const char* name; + VpeAxisKind kind; + size_t offset; + }; + + // Offsets in the OPD 1.x payload, excluding the HID report ID. + constexpr Axis Axes[] = { + {0, "Nudge X Acceleration", VPE_AXIS_KIND_ACCELERATION, 16}, + {1, "Nudge Y Acceleration", VPE_AXIS_KIND_ACCELERATION, 18}, + {2, "Nudge X Velocity", VPE_AXIS_KIND_VELOCITY, 20}, + {3, "Nudge Y Velocity", VPE_AXIS_KIND_VELOCITY, 22}, + {4, "Plunger Position", VPE_AXIS_KIND_POSITION, 24}, + {5, "Plunger Velocity", VPE_AXIS_KIND_VELOCITY, 26}, + }; + + constexpr bool SupportsVersion(std::wstring_view signature) { + constexpr std::wstring_view prefix = L"OpenPinballDeviceStruct/1."; + if (signature.substr(0, prefix.size()) != prefix || signature.size() == prefix.size()) { + return false; + } + for (const auto c : signature.substr(prefix.size())) { + if (c < L'0' || c > L'9') return false; + } + return true; + } + + inline uint64_t ReadUnsigned(const unsigned char* bytes, size_t size) { + uint64_t value = 0; + for (size_t i = 0; i < size; ++i) { + value |= static_cast(bytes[i]) << (8 * i); + } + return value; + } + + struct Report { + const unsigned char* payload; + size_t size; + + static bool Read(const unsigned char* bytes, size_t size, uint8_t reportId, Report& result) { + // All 1.x reports begin with a timestamp and two button masks. Fields + // after that header can be absent in shorter descriptors. + if (size < ReportIdSize || bytes[0] != reportId) return false; + return ReadPayload(bytes + ReportIdSize, size - ReportIdSize, result); + } + + static bool ReadPayload(const unsigned char* bytes, size_t size, Report& result) { + if (size < 16) return false; + result = {bytes, size}; + return true; + } + + uint64_t Timestamp() const { return ReadUnsigned(payload, 8); } + uint32_t PinballButtons() const { return static_cast(ReadUnsigned(payload + 12, 4)); } + uint32_t GenericButtons() const { return static_cast(ReadUnsigned(payload + 8, 4)); } + + bool TryReadAxis(const Axis& axis, float& value) const { + if (axis.offset + 2 > size) return false; + const int bits = static_cast(ReadUnsigned(payload + axis.offset, 2)); + value = static_cast(bits < 32768 ? bits : bits - 65536) / 32768.0f; + return true; + } + }; + + // Each device boots with its own clock origin. Keep its intervals in VPE's + // host clock domain without feeding future or backward times to physics. + class Clock { + public: + bool Translate(uint64_t deviceUsec, int64_t hostUsec, int64_t& sampleUsec) { + if (m_hasSample && deviceUsec == m_deviceUsec) return false; + // Reanchor after a stall or accumulated device/host clock drift. + constexpr int64_t MaxClockLagUsec = 20000; + if (!m_hasSample || deviceUsec < m_deviceUsec || hostUsec - m_sampleUsec > MaxClockLagUsec) { + m_sampleUsec = hostUsec; + } else { + const uint64_t remaining = static_cast(std::max(hostUsec - m_sampleUsec, 0)); + m_sampleUsec += static_cast(std::min(deviceUsec - m_deviceUsec, remaining)); + } + m_hasSample = true; + m_deviceUsec = deviceUsec; + sampleUsec = m_sampleUsec; + return true; + } + + private: + bool m_hasSample = false; + uint64_t m_deviceUsec = 0; + int64_t m_sampleUsec = 0; + }; + + // Keep the last delivered level while gameplay is paused. A release that + // happened during the pause is reconciled on resume, while a new press + // during the pause must be released before it can drive gameplay. + class ActionLatch { + public: + bool Update(bool pressed, bool enabled, bool& value) { + const bool newPress = pressed && !m_wasPressed; + m_wasPressed = pressed; + if (!pressed) m_ignoreUntilReleased = false; + if (!enabled) { + if (newPress) m_ignoreUntilReleased = true; + return false; + } + value = pressed && !m_ignoreUntilReleased; + if (value == m_published) return false; + m_published = value; + return true; + } + + private: + bool m_published = false; + bool m_ignoreUntilReleased = false; + bool m_wasPressed = false; + }; + + // OPD preassigned button bits 0 through 24. Bits 25 and 26 are volume + // controls, for which NativeInput has no action. + constexpr VpeInputAction ButtonActions[] = { + VPE_INPUT_START, VPE_INPUT_EXIT_GAME, VPE_INPUT_EXTRA_BALL, + VPE_INPUT_COIN_INSERT_1, VPE_INPUT_COIN_INSERT_2, VPE_INPUT_COIN_INSERT_3, VPE_INPUT_COIN_INSERT_4, + VPE_INPUT_PLUNGE, VPE_INPUT_LOCKBAR, + VPE_INPUT_LEFT_FLIPPER, VPE_INPUT_RIGHT_FLIPPER, + VPE_INPUT_LEFT_STAGED_FLIPPER, VPE_INPUT_RIGHT_STAGED_FLIPPER, + VPE_INPUT_LEFT_MAGNASAVE, VPE_INPUT_RIGHT_MAGNASAVE, + VPE_INPUT_TILT, VPE_INPUT_SLAM_TILT, VPE_INPUT_COIN_DOOR, + VPE_INPUT_SERVICE_1, VPE_INPUT_SERVICE_2, VPE_INPUT_SERVICE_3, VPE_INPUT_SERVICE_4, + VPE_INPUT_LEFT_NUDGE, VPE_INPUT_CENTER_NUDGE, VPE_INPUT_RIGHT_NUDGE, + }; +} diff --git a/src/OpenPinballInput.cpp b/src/OpenPinballInput.cpp new file mode 100644 index 0000000..ea155ae --- /dev/null +++ b/src/OpenPinballInput.cpp @@ -0,0 +1,190 @@ +// license:GPLv3+ +#include "OpenPinballInput.h" +#include "NativeButtons.h" + +#include + +namespace OpenPinballDevice { + void Input::Start(VpeInputEventCallback callback, void* userData) { + m_callback = callback; + m_userData = userData; + m_actions = {}; + m_nextDeviceIndex = 0; + } + + void Input::Stop() { + std::lock_guard lock(m_snapshotMutex); + for (const auto& device : m_devices) NativeButtons::GetState().Disconnect(device.info.deviceIndex); + m_devices.clear(); + } + + void Input::SetGameplayEnabled(int enabled) { + std::lock_guard lock(m_gameplayMutex); + m_gate = enabled ? Gate::Enabled : Gate::Disabled; + } + + void Input::ResetGameplayGate() { + std::lock_guard lock(m_gameplayMutex); + m_gate = Gate::Unconfigured; + } + + void Input::BeginPoll(int64_t timestamp, bool foreground, const Keys& keys) { + m_foreground = foreground; + m_keys = keys; + PublishActions(timestamp); + } + + int Input::Connect(const std::string& stableId, const std::string& product, Descriptor descriptor, int64_t timestamp) { + Device device{}; + device.descriptor = descriptor; + device.info.deviceIndex = m_nextDeviceIndex++; + device.info.isConnected = 1; + std::snprintf(device.info.stableId, sizeof(device.info.stableId), "%s", stableId.c_str()); + std::snprintf(device.info.displayName, sizeof(device.info.displayName), "%.*s (OPD)", + static_cast(sizeof(device.info.displayName) - sizeof(" (OPD)")), product.c_str()); + + std::vector axisIds; + for (const auto& axis : Axes) { + if (axis.offset + 2 > descriptor.payloadSize) break; + auto& info = device.axes[device.info.axisCount++]; + axisIds.push_back(axis.id); + info.axisId = axis.id; + info.usagePage = UsagePage; + info.usage = Usage; + info.kind = axis.kind; + std::snprintf(info.name, sizeof(info.name), "%s", axis.name); + } + + { + std::lock_guard lock(m_snapshotMutex); + NativeButtons::GetState().Connect(device.info.deviceIndex, stableId, NativeButtons::OpdGenericButtons(), axisIds); + m_devices.push_back(device); + } + Emit({timestamp, VPE_INPUT_EVENT_DEVICES_CHANGED}); + return device.info.deviceIndex; + } + + void Input::Disconnect(int deviceIndex, int64_t timestamp) { + { + std::lock_guard lock(m_snapshotMutex); + const auto device = std::find_if(m_devices.begin(), m_devices.end(), [deviceIndex](const Device& item) { + return item.info.deviceIndex == deviceIndex; + }); + if (device == m_devices.end()) return; + NativeButtons::GetState().Disconnect(deviceIndex); + m_devices.erase(device); + } + PublishActions(timestamp); + Emit({timestamp, VPE_INPUT_EVENT_DEVICES_CHANGED}); + } + + void Input::Receive(int deviceIndex, const unsigned char* bytes, size_t size, int64_t timestamp) { + std::array events; + int eventCount = 0; + bool buttonsChanged; + { + std::lock_guard lock(m_snapshotMutex); + const auto device = std::find_if(m_devices.begin(), m_devices.end(), [deviceIndex](const Device& item) { + return item.info.deviceIndex == deviceIndex; + }); + if (device == m_devices.end()) return; + + const auto& descriptor = device->descriptor; + if (size != descriptor.payloadSize + (descriptor.reportId != 0)) return; + Report report{}; + const bool valid = descriptor.reportId != 0 + ? Report::Read(bytes, size, descriptor.reportId, report) + : Report::ReadPayload(bytes, size, report); + if (!valid) return; + + const auto genericMask = report.GenericButtons(); + const bool controlsChanged = NativeButtons::GetState().Update(deviceIndex, [&](const auto& button) { + return (genericMask & (uint32_t{1} << button.buttonId)) != 0; + }, [&](int axisId, float previous) { + float value; + return report.TryReadAxis(Axes[axisId], value) ? value : previous; + }); + buttonsChanged = controlsChanged || device->buttons != report.PinballButtons(); + device->buttons = report.PinballButtons(); + int64_t sample; + if (device->clock.Translate(report.Timestamp(), timestamp, sample)) { + for (int i = 0; i < device->info.axisCount; ++i) { + auto& axis = device->axes[i]; + report.TryReadAxis(Axes[i], axis.rawValue); + axis.timestampUsec = sample; + events[eventCount++] = {sample, VPE_INPUT_EVENT_AXIS, 0, deviceIndex, axis.axisId, axis.rawValue}; + } + } + } + // Controls use every report, including repeated motion timestamps. + if (buttonsChanged) PublishActions(timestamp); + if (eventCount > 0) { + std::lock_guard lock(m_gameplayMutex); + if (!m_foreground || m_gate == Gate::Disabled) return; + for (int i = 0; i < eventCount; ++i) Emit(events[i]); + } + } + + int Input::ListDevices(VpeInputDeviceInfo* devices, int maxDevices) { + std::lock_guard lock(m_snapshotMutex); + const int count = static_cast(m_devices.size()); + if (devices != nullptr) { + for (int i = 0; i < std::min(count, maxDevices); ++i) devices[i] = m_devices[i].info; + } + return count; + } + + int Input::ListAxes(int deviceIndex, VpeInputAxisInfo* axes, int maxAxes) { + std::lock_guard lock(m_snapshotMutex); + for (const auto& device : m_devices) { + if (device.info.deviceIndex != deviceIndex) continue; + const int count = device.info.axisCount; + if (axes != nullptr && maxAxes > 0) std::copy_n(device.axes.begin(), std::min(count, maxAxes), axes); + return count; + } + return 0; + } + + void Input::PublishActions(int64_t timestamp) { + // Finish in-flight callbacks before returning from a gate change. + // Managed input starts dropping events after it disables this gate. + std::lock_guard lock(m_gameplayMutex); + const bool enabled = m_gate == Gate::Unconfigured || (m_foreground && m_gate == Gate::Enabled); + uint64_t configurable = 0; + Keys pressed{}; + if (m_foreground || m_gate != Gate::Unconfigured) { + configurable = NativeButtons::GetState().PressedActions(); + pressed = m_keys; + uint32_t buttons = 0; + // Device state only changes on this thread. Snapshot readers never + // access the button mask. + for (const auto& device : m_devices) buttons |= device.buttons; + for (size_t bit = 0; bit < std::size(ButtonActions); ++bit) { + if ((buttons & (uint32_t{1} << bit)) != 0) pressed[ButtonActions[bit]] = true; + } + } + for (int action = 0; action < VPE_INPUT_MAX; ++action) { + bool value; + const bool down = pressed[action] || (configurable & (uint64_t{1} << action)) != 0; + if (m_actions[action].Update(down, enabled, value)) { + Emit({timestamp, VPE_INPUT_EVENT_ACTION, action, 0, 0, value ? 1.0f : 0.0f}); + } + } + } + + void Input::Emit(VpeInputEvent event) const { + if (m_callback != nullptr) m_callback(&event, m_userData); + } + + std::string StableId(const char* platform, const std::string& location, + const std::string& serial, uint16_t vendor, uint16_t product, uint8_t reportId) { + // Bound the serial portion to the ABI's fixed-size ID buffer. + uint64_t serialHash = 14695981039346656037ULL; + for (unsigned char c : serial) serialHash = (serialHash ^ c) * 1099511628211ULL; + char id[64]; + std::snprintf(id, sizeof(id), "opd:%s:%04x:%04x:%016llx:%02x:", + platform, static_cast(vendor), static_cast(product), + static_cast(serialHash), static_cast(reportId)); + return id + location; + } +} diff --git a/src/OpenPinballInput.h b/src/OpenPinballInput.h new file mode 100644 index 0000000..a6c849f --- /dev/null +++ b/src/OpenPinballInput.h @@ -0,0 +1,72 @@ +// license:GPLv3+ +#pragma once + +#include "OpenPinballDescriptor.h" + +#include +#include +#include +#include + +namespace OpenPinballDevice { + using Keys = std::array; + + // Shared Linux/macOS polling state. Only the polling thread mutates device + // state and delivers callbacks. Snapshot queries can run on either thread. + class Input { + public: + void Start(VpeInputEventCallback callback, void* userData); + void Stop(); + void SetGameplayEnabled(int enabled); + void ResetGameplayGate(); + void BeginPoll(int64_t timestamp, bool foreground, const Keys& keys); + + int Connect(const std::string& stableId, const std::string& product, Descriptor descriptor, int64_t timestamp); + void Disconnect(int deviceIndex, int64_t timestamp); + void Receive(int deviceIndex, const unsigned char* bytes, size_t size, int64_t timestamp); + int ListDevices(VpeInputDeviceInfo* devices, int maxDevices); + int ListAxes(int deviceIndex, VpeInputAxisInfo* axes, int maxAxes); + + private: + struct Device { + VpeInputDeviceInfo info{}; + Descriptor descriptor; + std::array axes{}; + Clock clock; + uint32_t buttons = 0; + }; + + void PublishActions(int64_t timestamp); + void Emit(VpeInputEvent event) const; + + std::vector m_devices; + std::mutex m_snapshotMutex; + int m_nextDeviceIndex = 0; + VpeInputEventCallback m_callback = nullptr; + void* m_userData = nullptr; + Keys m_keys{}; + std::array m_actions{}; + bool m_foreground = false; + enum class Gate { Unconfigured, Enabled, Disabled }; + std::mutex m_gameplayMutex; + Gate m_gate = Gate::Unconfigured; + }; + + // IDs keep the USB port as part of the identity so two identical devices + // with missing or duplicated serial numbers can be mapped independently. + std::string StableId(const char* platform, const std::string& location, + const std::string& serial, uint16_t vendor, uint16_t product, uint8_t reportId); + + // The platform transport is created and destroyed on the native polling + // thread, including the run loop and report callbacks on macOS. + class Transport { + public: + explicit Transport(Input& input); + ~Transport(); + void Poll(int64_t timestamp); + + private: + struct Impl; + std::unique_ptr m_impl; + }; +} diff --git a/src/OpenPinballLinux.cpp b/src/OpenPinballLinux.cpp new file mode 100644 index 0000000..cfd8ef3 --- /dev/null +++ b/src/OpenPinballLinux.cpp @@ -0,0 +1,186 @@ +// license:GPLv3+ +#include "OpenPinballInput.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace OpenPinballDevice { + namespace { + namespace fs = std::filesystem; + + struct File { + int fd; + + explicit File(const fs::path& path, int flags) : fd(open(path.c_str(), flags | O_CLOEXEC)) {} + File(File&& other) noexcept : fd(std::exchange(other.fd, -1)) {} + ~File() { if (fd >= 0) close(fd); } + }; + + ProbeResult ReadSignature(const fs::path& usbDevice, uint8_t index) { + int busNumber, deviceNumber; + if (!(std::ifstream(usbDevice / "busnum") >> busNumber) + || !(std::ifstream(usbDevice / "devnum") >> deviceNumber)) return ProbeResult::Retry; + char usbPath[32]; + std::snprintf(usbPath, sizeof(usbPath), "/dev/bus/usb/%03d/%03d", busNumber, deviceNumber); + File usb(usbPath, O_RDWR); + if (usb.fd < 0) return ProbeResult::Retry; + // A device-recipient control transfer does not claim the HID + // interface. The kernel HID driver stays attached for report reads. + return VerifySignature(index, [&](uint8_t stringIndex, uint16_t language, auto& bytes) { + usbdevfs_ctrltransfer request{}; + request.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE; + request.bRequest = USB_REQ_GET_DESCRIPTOR; + request.wValue = (USB_DT_STRING << 8) | stringIndex; + request.wIndex = language; + request.wLength = static_cast(bytes.size()); + request.timeout = 100; + request.data = bytes.data(); + return ioctl(usb.fd, USBDEVFS_CONTROL, &request); + }); + } + } + + struct Transport::Impl { + struct Device { + File hid; + int index; + }; + struct PendingProbe { + fs::path entry; + fs::path hidDevice; + File hid; + Descriptor descriptor; + std::string id; + std::string name; + std::future result; + }; + + Input& input; + std::map devices; + std::map retryAfter; + std::unique_ptr pending; + int64_t nextScan = 0; + + explicit Impl(Input& input) : input(input) {} + + ProbeResult BeginProbe(const fs::path& entry, const fs::path& hidDevice) { + std::array descriptorBytes; + std::ifstream descriptorFile(hidDevice / "report_descriptor", std::ios::binary); + descriptorFile.read(reinterpret_cast(descriptorBytes.data()), descriptorBytes.size()); + const auto size = static_cast(descriptorFile.gcount()); + if (size == 0) return ProbeResult::Retry; + if (size > MaxDescriptorSize) return ProbeResult::NotOpd; + const auto descriptor = FindDescriptor(descriptorBytes.data(), size); + if (descriptor.stringIndex == 0) return ProbeResult::NotOpd; + + const auto usbInterface = hidDevice.parent_path(); + const auto usbDevice = usbInterface.parent_path(); + File hid(fs::path("/dev") / entry.filename(), O_RDONLY | O_NONBLOCK); + hidraw_devinfo rawInfo{}; + std::error_code pathError; + if (hid.fd < 0 || ioctl(hid.fd, HIDIOCGRAWINFO, &rawInfo) < 0 + || fs::canonical(entry / "device", pathError) != hidDevice) return ProbeResult::Retry; + if (rawInfo.bustype != BUS_USB) return ProbeResult::NotOpd; + char name[VPE_INPUT_DEVICE_NAME_SIZE]{}; + if (ioctl(hid.fd, HIDIOCGRAWNAME(sizeof(name) - 1), name) <= 0) { + std::snprintf(name, sizeof(name), "Open Pinball Device"); + } + std::string serial; + std::ifstream serialFile(usbDevice / "serial"); + std::getline(serialFile, serial); + const auto id = StableId("linux", usbInterface.filename().string(), serial, + static_cast(rawInfo.vendor), static_cast(rawInfo.product), descriptor.reportId); + try { + // The USB control transfer may time out. Keep the open hidraw + // handle here and perform only the signature request off-thread. + pending = std::make_unique(PendingProbe{entry, hidDevice, std::move(hid), descriptor, id, name, + std::async(std::launch::async, [usbDevice, descriptor] { + return ReadSignature(usbDevice, descriptor.stringIndex); + })}); + } catch (const std::system_error&) { + return ProbeResult::Retry; + } + return ProbeResult::Found; + } + + void FinishProbe(int64_t timestamp) { + if (!pending || pending->result.wait_for(std::chrono::seconds(0)) != std::future_status::ready) return; + auto probe = std::move(pending); + const auto result = probe->result.get(); + std::error_code error; + if (fs::canonical(probe->entry / "device", error) != probe->hidDevice || error) return; + if (result != ProbeResult::Found) { + retryAfter[probe->hidDevice] = NextProbe(result, timestamp); + return; + } + retryAfter.erase(probe->hidDevice); + const int index = input.Connect(probe->id, probe->name, probe->descriptor, timestamp); + devices.emplace(probe->hidDevice, Device{std::move(probe->hid), index}); + } + + void Scan(int64_t timestamp) { + std::error_code error; + const fs::path hidraw("/sys/class/hidraw"); + for (fs::directory_iterator it(hidraw, error), end; !error && it != end; it.increment(error)) { + const auto& entry = it->path(); + std::error_code pathError; + const auto hidDevice = fs::canonical(entry / "device", pathError); + if (pathError || devices.find(hidDevice) != devices.end()) continue; + + const auto retry = retryAfter.find(hidDevice); + if (retry != retryAfter.end() && timestamp < retry->second) continue; + const auto result = BeginProbe(entry, hidDevice); + if (result == ProbeResult::Found) break; + retryAfter[hidDevice] = NextProbe(result, timestamp); + } + for (auto it = retryAfter.begin(); it != retryAfter.end();) { + std::error_code pathError; + if (!fs::exists(it->first, pathError) && !pathError) it = retryAfter.erase(it); + else ++it; + } + } + + void Poll(int64_t timestamp) { + std::array bytes; + for (auto it = devices.begin(); it != devices.end();) { + const auto& device = it->second; + bool disconnected = false; + for (int i = 0; i < 32; ++i) { + const auto size = read(device.hid.fd, bytes.data(), bytes.size()); + if (size <= 0) { + disconnected = size == 0 || (errno != EAGAIN && errno != EINTR); + break; + } + input.Receive(device.index, bytes.data(), static_cast(size), timestamp); + } + if (disconnected) { + input.Disconnect(device.index, timestamp); + it = devices.erase(it); + } else { + ++it; + } + } + FinishProbe(timestamp); + if (!pending && timestamp >= nextScan) { + nextScan = timestamp + 1000000; + Scan(timestamp); + } + } + }; + + Transport::Transport(Input& input) : m_impl(std::make_unique(input)) {} + Transport::~Transport() = default; + void Transport::Poll(int64_t timestamp) { m_impl->Poll(timestamp); } +} diff --git a/src/OpenPinballMac.cpp b/src/OpenPinballMac.cpp new file mode 100644 index 0000000..6af59f1 --- /dev/null +++ b/src/OpenPinballMac.cpp @@ -0,0 +1,255 @@ +// license:GPLv3+ +#include "OpenPinballInput.h" + +#include +#include +#include + +#include +#include +#include + +namespace OpenPinballDevice { + namespace { + CFStringRef PollMode() { return CFSTR("VpeOpenPinballInput"); } + + struct Service { + io_service_t value; + explicit Service(io_service_t value) : value(value) {} + Service(Service&& other) noexcept : value(std::exchange(other.value, IO_OBJECT_NULL)) {} + ~Service() { if (value != IO_OBJECT_NULL) IOObjectRelease(value); } + }; + + int64_t ReadNumber(io_service_t service, CFStringRef key, int64_t fallback = 0) { + const auto property = IORegistryEntryCreateCFProperty(service, key, kCFAllocatorDefault, 0); + if (property == nullptr) return fallback; + int64_t value = fallback; + if (CFGetTypeID(property) == CFNumberGetTypeID()) { + CFNumberGetValue(static_cast(property), kCFNumberSInt64Type, &value); + } + CFRelease(property); + return value; + } + + std::string ReadString(IOHIDDeviceRef device, CFStringRef key) { + const auto property = IOHIDDeviceGetProperty(device, key); + char bytes[512]; + if (property == nullptr || CFGetTypeID(property) != CFStringGetTypeID() + || !CFStringGetCString(static_cast(property), bytes, sizeof(bytes), kCFStringEncodingUTF8)) return {}; + return bytes; + } + + io_service_t FindUsbDevice(io_service_t hid, int& interfaceNumber) { + IOObjectRetain(hid); + auto entry = hid; + while (entry != IO_OBJECT_NULL) { + if (IOObjectConformsTo(entry, "IOUSBHostDevice") || IOObjectConformsTo(entry, "IOUSBDevice")) return entry; + if (IOObjectConformsTo(entry, "IOUSBHostInterface") || IOObjectConformsTo(entry, "IOUSBInterface")) { + interfaceNumber = static_cast(ReadNumber(entry, CFSTR("bInterfaceNumber"), -1)); + } + io_registry_entry_t parent = IO_OBJECT_NULL; + IORegistryEntryGetParentEntry(entry, kIOServicePlane, &parent); + IOObjectRelease(entry); + entry = parent; + } + return IO_OBJECT_NULL; + } + + ProbeResult ReadSignature(io_service_t service, uint8_t index) { + IOCFPlugInInterface** plugin = nullptr; + SInt32 score; + if (IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID, + kIOCFPlugInInterfaceID, &plugin, &score) != kIOReturnSuccess) return ProbeResult::Retry; + IOUSBDeviceInterface245** usb = nullptr; + const auto query = (*plugin)->QueryInterface(plugin, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID245), + reinterpret_cast(&usb)); + IODestroyPlugInInterface(plugin); + if (query != 0 || usb == nullptr) return ProbeResult::Retry; + + // Use a temporary non-seizing device open, with no interface claim. + // The descriptor request may also succeed if the device is busy. + const bool opened = (*usb)->USBDeviceOpen(usb) == kIOReturnSuccess; + const auto signature = VerifySignature(index, [&](uint8_t stringIndex, uint16_t language, auto& bytes) { + IOUSBDevRequestTO request{}; + request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice); + request.bRequest = kUSBRqGetDescriptor; + request.wValue = (kUSBStringDesc << 8) | stringIndex; + request.wIndex = language; + request.wLength = static_cast(bytes.size()); + request.pData = bytes.data(); + request.noDataTimeout = 20; + request.completionTimeout = 100; + return (*usb)->DeviceRequestTO(usb, &request) == kIOReturnSuccess + ? static_cast(request.wLenDone) : -1; + }); + if (opened) (*usb)->USBDeviceClose(usb); + (*usb)->Release(usb); + return signature; + } + } + + struct Transport::Impl { + struct Device { + Impl& owner; + IOHIDDeviceRef hid; + bool opened = false; + bool removed = false; + int index = -1; + std::array bytes; + + Device(Impl& owner, IOHIDDeviceRef hid) : owner(owner), hid(hid) {} + ~Device() { + if (index >= 0) IOHIDDeviceUnscheduleFromRunLoop(hid, CFRunLoopGetCurrent(), PollMode()); + if (opened) IOHIDDeviceClose(hid, kIOHIDOptionsTypeNone); + CFRelease(hid); + } + + static void OnRemoval(void* context, IOReturn, void*) { + static_cast(context)->removed = true; + } + + static void OnReport(void* context, IOReturn result, void*, IOHIDReportType type, + uint32_t, uint8_t* report, CFIndex size) { + auto& device = *static_cast(context); + if (!device.removed && result == kIOReturnSuccess && type == kIOHIDReportTypeInput && size > 0) { + // IOKit supplies the HID report ID byte for numbered reports. + device.owner.input.Receive(device.index, report, static_cast(size), device.owner.timestamp); + } + } + }; + struct PendingProbe { + uint64_t registryId; + std::unique_ptr device; + Descriptor descriptor; + std::string id; + std::string name; + std::future result; + }; + + Input& input; + std::map> devices; + std::map retryAfter; + std::unique_ptr pending; + int64_t timestamp = 0; + int64_t nextScan = 0; + + explicit Impl(Input& input) : input(input) {} + + ProbeResult BeginProbe(io_service_t service, uint64_t registryId) { + const auto property = IORegistryEntryCreateCFProperty(service, CFSTR(kIOHIDReportDescriptorKey), kCFAllocatorDefault, 0); + if (property == nullptr) return ProbeResult::Retry; + Descriptor descriptor; + if (CFGetTypeID(property) == CFDataGetTypeID()) { + const auto data = static_cast(property); + const auto size = CFDataGetLength(data); + if (size > 0 && size <= MaxDescriptorSize) descriptor = FindDescriptor(CFDataGetBytePtr(data), size); + } + CFRelease(property); + if (descriptor.stringIndex == 0) return ProbeResult::NotOpd; + + int interfaceNumber = -1; + Service usb(FindUsbDevice(service, interfaceNumber)); + if (usb.value == IO_OBJECT_NULL) return ProbeResult::NotOpd; + const auto location = static_cast(ReadNumber(usb.value, CFSTR("locationID"))); + const auto vendor = static_cast(ReadNumber(usb.value, CFSTR("idVendor"))); + const auto product = static_cast(ReadNumber(usb.value, CFSTR("idProduct"))); + + const auto hid = IOHIDDeviceCreate(kCFAllocatorDefault, service); + if (hid == nullptr) return ProbeResult::Retry; + auto device = std::make_unique(*this, hid); + device->opened = IOHIDDeviceOpen(hid, kIOHIDOptionsTypeNone) == kIOReturnSuccess; + if (!device->opened || location == 0) return ProbeResult::Retry; + const auto serial = ReadString(hid, CFSTR(kIOHIDSerialNumberKey)); + const auto name = ReadString(hid, CFSTR(kIOHIDProductKey)); + const auto id = StableId("mac", std::to_string(location) + ":" + std::to_string(interfaceNumber), + serial, vendor, product, descriptor.reportId); + try { + // Keep IOHID report registration on the polling run loop. Only + // the temporary USB device's signature request runs elsewhere. + pending = std::make_unique(PendingProbe{registryId, std::move(device), descriptor, id, name, + std::async(std::launch::async, [usb = std::move(usb), descriptor] { + return ReadSignature(usb.value, descriptor.stringIndex); + })}); + } catch (const std::system_error&) { + return ProbeResult::Retry; + } + return ProbeResult::Found; + } + + void FinishProbe() { + if (!pending || pending->result.wait_for(std::chrono::seconds(0)) != std::future_status::ready) return; + auto probe = std::move(pending); + const auto result = probe->result.get(); + if (result != ProbeResult::Found) { + retryAfter[probe->registryId] = NextProbe(result, timestamp); + return; + } + Service present(IOServiceGetMatchingService(MACH_PORT_NULL, IORegistryEntryIDMatching(probe->registryId))); + if (present.value == IO_OBJECT_NULL) return; + retryAfter.erase(probe->registryId); + auto& device = probe->device; + device->index = input.Connect(probe->id, probe->name.empty() ? "Open Pinball Device" : probe->name, + probe->descriptor, timestamp); + IOHIDDeviceRegisterRemovalCallback(device->hid, Device::OnRemoval, device.get()); + IOHIDDeviceRegisterInputReportCallback(device->hid, device->bytes.data(), device->bytes.size(), Device::OnReport, device.get()); + IOHIDDeviceScheduleWithRunLoop(device->hid, CFRunLoopGetCurrent(), PollMode()); + devices.emplace(probe->registryId, std::move(device)); + } + + void RemoveDisconnected(const std::map* present = nullptr) { + for (auto it = devices.begin(); it != devices.end();) { + if (it->second->removed || (present != nullptr && present->count(it->first) == 0)) { + input.Disconnect(it->second->index, timestamp); + it = devices.erase(it); + } else { + ++it; + } + } + } + + void Poll(int64_t now) { + timestamp = now; + for (int i = 0; i < 32; ++i) { + if (CFRunLoopRunInMode(PollMode(), 0, true) != kCFRunLoopRunHandledSource) break; + } + RemoveDisconnected(); + FinishProbe(); + if (timestamp < nextScan) return; + nextScan = timestamp + 1000000; + io_iterator_t iterator; + if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching(kIOHIDDeviceKey), &iterator) != kIOReturnSuccess) return; + std::map present; + while (const auto service = IOIteratorNext(iterator)) { + uint64_t registryId; + if (IORegistryEntryGetRegistryEntryID(service, ®istryId) != kIOReturnSuccess + || !present.emplace(registryId, service).second) { + IOObjectRelease(service); + } + } + // A device can disappear between opening it and registering the + // removal callback. Retire those handles before connecting replacements. + if (IOIteratorIsValid(iterator)) { + RemoveDisconnected(&present); + for (const auto& [id, service] : present) { + if (pending) break; + if (devices.find(id) != devices.end()) continue; + const auto retry = retryAfter.find(id); + if (retry != retryAfter.end() && timestamp < retry->second) continue; + const auto result = BeginProbe(service, id); + if (result == ProbeResult::Found) break; + retryAfter[id] = NextProbe(result, timestamp); + } + for (auto it = retryAfter.begin(); it != retryAfter.end();) { + if (present.count(it->first) == 0) it = retryAfter.erase(it); + else ++it; + } + } + IOObjectRelease(iterator); + for (const auto& item : present) IOObjectRelease(item.second); + } + }; + + Transport::Transport(Input& input) : m_impl(std::make_unique(input)) {} + Transport::~Transport() = default; + void Transport::Poll(int64_t timestamp) { m_impl->Poll(timestamp); } +} diff --git a/tests/ControllerInputTests.cpp b/tests/ControllerInputTests.cpp new file mode 100644 index 0000000..e26e2b7 --- /dev/null +++ b/tests/ControllerInputTests.cpp @@ -0,0 +1,208 @@ +// license:GPLv3+ +#include "ControllerInput.h" +#include "NativeButtons.h" + +#include + +#include +#include +#include +#include +#include +#include + +static void Check(bool condition, const char* message) { + if (!condition) { + std::fprintf(stderr, "%s (SDL: %s)\n", message, SDL_GetError()); + std::exit(1); + } +} + +struct Observed { + ControllerInput& input; + std::vector events; + std::vector devices; + + void Snapshot() { + const int count = input.AppendDevices(nullptr, 0, 1); + devices.resize(count); + devices[0].deviceIndex = 77; + Check(input.AppendDevices(devices.data(), count, 1) == count, "Append controller snapshot"); + Check(devices[0].deviceIndex == 77, "Keep the preexisting device snapshot"); + } + + VpeInputDeviceInfo Find(const char* name) const { + for (const auto& device : devices) { + if (std::strcmp(device.displayName, name) == 0) return device; + } + return {}; + } + + bool SawAxis(int device, int axis, float value) const { + return std::any_of(events.begin(), events.end(), [&](const VpeInputEvent& event) { + return event.eventType == VPE_INPUT_EVENT_AXIS && event.deviceIndex == device + && event.axisId == axis && event.value == value; + }); + } +}; + +static SDL_JoystickID Attach(const char* name, SDL_JoystickType type, Uint16 axes, Uint16 hats = 0) { + SDL_VirtualJoystickDesc desc; + SDL_INIT_INTERFACE(&desc); + desc.name = name; + desc.type = type; + desc.naxes = axes; + desc.nhats = hats; + desc.nbuttons = 1; + const auto id = SDL_AttachVirtualJoystick(&desc); + Check(id != 0, "Attach a virtual controller"); + return id; +} + +int main() { + ControllerInput input; + input.Start(); + Observed observed{input}; + const auto callback = [](const VpeInputEvent* event, void* data) { + auto& state = *static_cast(data); + state.events.push_back(*event); + if (event->eventType == VPE_INPUT_EVENT_DEVICES_CHANGED) state.Snapshot(); + }; + + const auto rawId = Attach("PinscapePico", SDL_JOYSTICK_TYPE_UNKNOWN, 6, 1); + const auto padId = Attach("VPE Test Pad", SDL_JOYSTICK_TYPE_GAMEPAD, SDL_GAMEPAD_AXIS_COUNT); + SDL_Joystick* raw = SDL_OpenJoystick(rawId); + SDL_Joystick* pad = SDL_OpenJoystick(padId); + Check(raw != nullptr && pad != nullptr, "Open the virtual devices for sample injection"); + input.Poll(1000, true, callback, &observed); + const auto pinscape = observed.Find("PinscapePico"); + const auto gamepad = observed.Find("VPE Test Pad (Gamepad)"); + Check(pinscape.deviceIndex >= ControllerInput::FirstDeviceIndex && pinscape.axisCount == 6, + "Publish all raw joystick axes after discovery"); + Check(gamepad.deviceIndex >= ControllerInput::FirstDeviceIndex && gamepad.axisCount == 6, + "Publish standardized gamepad axes"); + Check(observed.events.front().eventType == VPE_INPUT_EVENT_DEVICES_CHANGED, "Publish identity before axis events"); + std::array axes{}; + input.ListAxes(pinscape.deviceIndex, axes.data(), static_cast(axes.size())); + Check(axes[0].usagePage == 1 && axes[3].usage == 0x33, "Expose Pinscape X/RX usages for existing presets"); + input.ListAxes(gamepad.deviceIndex, axes.data(), static_cast(axes.size())); + Check(axes[0].usagePage == VPE_GAMEPAD_AXIS_USAGE_PAGE && std::strcmp(axes[0].name, "Left Stick X") == 0, + "Expose standardized axis metadata"); + std::array rawButtons{}; + VpeInputButtonInfo padButton{}; + Check(VpeInputListDeviceButtons(pinscape.deviceIndex, rawButtons.data(), 5) == 5 && rawButtons[0].buttonId == 0 + && std::strcmp(rawButtons[1].name, "Hat 1 Up") == 0 && std::strcmp(rawButtons[2].name, "Hat 1 Right") == 0, + "Expose raw joystick buttons and POV directions"); + const auto rawButton = rawButtons[0]; + Check(VpeInputListDeviceButtons(gamepad.deviceIndex, &padButton, 1) == 1 + && padButton.buttonId == SDL_GAMEPAD_BUTTON_SOUTH, "Expose standardized gamepad buttons"); + VpeInputButtonBinding bindings[] = {{VPE_INPUT_LEFT_NUDGE, rawButton.buttonId}, {VPE_INPUT_LEFT_NUDGE, padButton.buttonId}}; + std::snprintf(bindings[0].deviceId, sizeof(bindings[0].deviceId), "%s", pinscape.stableId); + std::snprintf(bindings[1].deviceId, sizeof(bindings[1].deviceId), "%s", gamepad.stableId); + VpeInputSetButtonBindings(bindings, 2); + Check(SDL_SetJoystickVirtualButton(raw, 0, true) && SDL_SetJoystickVirtualButton(pad, 0, true), + "Inject joystick and gamepad presses"); + input.Poll(1100, true, callback, &observed); + const uint64_t nudge = uint64_t{1} << VPE_INPUT_LEFT_NUDGE; + Check(NativeButtons::GetState().PressedActions() == nudge, "Combine configured joystick and gamepad presses"); + Check(SDL_SetJoystickVirtualButton(pad, 0, false), "Release the gamepad button"); + input.Poll(1200, true, callback, &observed); + Check(NativeButtons::GetState().PressedActions() == nudge, "A joystick can keep the action held"); + + observed.events.clear(); + Check(SDL_SetJoystickVirtualAxis(raw, 0, -32768), "Inject a raw sample"); + Check(SDL_SetJoystickVirtualAxis(pad, SDL_GAMEPAD_AXIS_LEFTX, 16384), "Inject a left-stick sample"); + input.Poll(2000, true, callback, &observed); + Check(observed.SawAxis(pinscape.deviceIndex, 0, -1.f), "Deliver a signed raw sample"); + Check(observed.SawAxis(gamepad.deviceIndex, 0, .5f), "Deliver a signed standardized sample"); + + observed.events.clear(); + input.SetGameplayEnabled(false); + Check(SDL_SetJoystickVirtualAxis(pad, SDL_GAMEPAD_AXIS_LEFTX, -16384), "Inject a sample during pause"); + input.Poll(3000, true, callback, &observed); + Check(observed.events.empty(), "Suppress axis events during pause"); + input.ListAxes(gamepad.deviceIndex, axes.data(), static_cast(axes.size())); + Check(axes[0].rawValue == -.5f && axes[0].timestampUsec == 3000, "Keep the calibration snapshot live during pause"); + input.SetGameplayEnabled(true); + input.Poll(4000, true, callback, &observed); + Check(observed.SawAxis(gamepad.deviceIndex, 0, -.5f), "Refresh held axes on resume"); + + const auto makeBinding = [](int action, int group, int kind, int id, float threshold, const char* device) { + VpeInputControlBinding binding{action, group, kind, id, threshold, {}}; + std::snprintf(binding.deviceId, sizeof(binding.deviceId), "%s", device); + return binding; + }; + const auto hatUp = makeBinding(VPE_INPUT_LEFT_NUDGE, 0, VPE_CONTROL_BUTTON, rawButtons[1].buttonId, 0, pinscape.stableId); + const VpeInputControlBinding controls[] = { + hatUp, + makeBinding(VPE_INPUT_LEFT_NUDGE, 1, VPE_CONTROL_AXIS_BELOW, 0, -.75f, gamepad.stableId), + makeBinding(VPE_INPUT_SLAM_TILT, 0, VPE_CONTROL_BUTTON, rawButtons[1].buttonId, 0, pinscape.stableId), + makeBinding(VPE_INPUT_SLAM_TILT, 0, VPE_CONTROL_AXIS_ABOVE, 0, .5f, gamepad.stableId), + }; + VpeInputSetControlBindings(controls, 4); + Check(SDL_SetJoystickVirtualAxis(pad, 0, 24576) && SDL_SetJoystickVirtualHat(raw, 0, SDL_HAT_RIGHTUP), + "Inject a stick and diagonal POV combination"); + input.Poll(4100, true, callback, &observed); + const uint64_t slam = uint64_t{1} << VPE_INPUT_SLAM_TILT; + Check(NativeButtons::GetState().PressedActions() == slam, "The complete combo suppresses its newly pressed subset"); + VpeInputListDeviceButtons(pinscape.deviceIndex, rawButtons.data(), 5); + Check(rawButtons[1].isPressed && rawButtons[2].isPressed, "A diagonal holds both cardinal directions"); + Check(SDL_SetJoystickVirtualAxis(pad, 0, 14746), "Dither just below the positive press threshold"); + input.Poll(4150, true, callback, &observed); + Check(NativeButtons::GetState().PressedActions() == slam, "Threshold hysteresis keeps the combo pressed during jitter"); + Check(SDL_SetJoystickVirtualAxis(pad, 0, -24576), "Move the axis to the alternative threshold"); + input.Poll(4200, true, callback, &observed); + Check(NativeButtons::GetState().PressedActions() == nudge, "The negative axis threshold is an independent alternative"); + Check(SDL_SetJoystickVirtualAxis(pad, 0, 0), "Release the axis"); + input.Poll(4300, true, callback, &observed); + Check(NativeButtons::GetState().PressedActions() == 0, "Releasing the combo does not replay its held subset"); + + input.SetGameplayEnabled(false); + VpeInputStartControlCapture(2); + Check(SDL_SetJoystickVirtualButton(pad, 0, true), "Press a fresh button for capture"); + input.Poll(4400, true, callback, &observed); + Check(SDL_SetJoystickVirtualAxis(pad, 0, 24576), "Move a stick while the button is held"); + input.Poll(4500, true, callback, &observed); + Check(SDL_SetJoystickVirtualButton(pad, 0, false) && SDL_SetJoystickVirtualAxis(pad, 0, 19661), + "Release the button while the stick still sits inside the capture hysteresis"); + input.Poll(4600, true, callback, &observed); + VpeInputControlBinding captured[8]{}; + Check(VpeInputReadControlCapture(captured, 8) == 0, "Wait for the captured axis to release through its deadband"); + Check(SDL_SetJoystickVirtualAxis(pad, 0, 0), "Release the stick"); + input.Poll(4700, true, callback, &observed); + Check(VpeInputReadControlCapture(captured, 8) == 2 && captured[0].controlId == padButton.buttonId + && captured[0].kind == VPE_CONTROL_BUTTON && captured[1].kind == VPE_CONTROL_AXIS_ABOVE + && std::strcmp(captured[0].deviceId, gamepad.stableId) == 0, + "Capture the overlapping inputs during pause and ignore the hat held before capture"); + VpeInputStartControlCapture(0); + input.SetGameplayEnabled(true); + VpeInputSetButtonBindings(bindings, 2); + + const std::string rawStableId = pinscape.stableId; + Check(SDL_DetachVirtualJoystick(rawId), "Unplug the raw joystick"); + SDL_CloseJoystick(raw); + input.Poll(5000, true, callback, &observed); + Check(observed.Find("PinscapePico").isConnected == 0, "Remove disconnected devices before the next scan"); + Check(input.ListAxes(pinscape.deviceIndex, nullptr, 0) == 0, "Remove the disconnected axis snapshot"); + Check(VpeInputListDeviceButtons(pinscape.deviceIndex, nullptr, 0) == 0 + && NativeButtons::GetState().PressedActions() == 0, "Drop the held button when the joystick disconnects"); + const auto newRawId = Attach("PinscapePico", SDL_JOYSTICK_TYPE_UNKNOWN, 6, 1); + input.Poll(260000, true, callback, &observed); + const auto replacement = observed.Find("PinscapePico"); + Check(replacement.isConnected && replacement.deviceIndex != pinscape.deviceIndex + && rawStableId == replacement.stableId, "Reconnect with a stable mapping and fresh event index"); + + Check(SDL_DetachVirtualJoystick(newRawId), "Detach the replacement fixture"); + Check(SDL_DetachVirtualJoystick(padId), "Detach the gamepad fixture"); + SDL_CloseJoystick(pad); + input.Stop(); + Check(input.AppendDevices(nullptr, 0, 0) == 0, "Clear the controller snapshot on stop"); + input.Start(); + const auto restartedId = Attach("VPE Restart", SDL_JOYSTICK_TYPE_UNKNOWN, 0); + input.Poll(270000, true, callback, &observed); + Check(observed.Find("VPE Restart").isConnected && observed.Find("VPE Restart").axisCount == 0, + "Detect button-only devices after restarting"); + Check(SDL_DetachVirtualJoystick(restartedId), "Detach the restart fixture"); + input.Stop(); + VpeInputSetButtonBindings(nullptr, 0); +} diff --git a/tests/OpenPinballDeviceTests.cpp b/tests/OpenPinballDeviceTests.cpp new file mode 100644 index 0000000..00d9af6 --- /dev/null +++ b/tests/OpenPinballDeviceTests.cpp @@ -0,0 +1,266 @@ +// license:GPLv3+ +#include "OpenPinballInput.h" + +#include +#include +#include + +using namespace OpenPinballDevice; + +static void Check(bool condition, const char* message) { + if (!condition) { + std::fprintf(stderr, "%s\n", message); + std::exit(1); + } +} + +static void CheckDescriptor() { + // A joystick collection followed by the Pico's OPD collection on the + // same HID interface. The signature index comes from the Input item. + unsigned char bytes[] = { + 0x05, 0x01, 0x09, 0x04, 0xa1, 0x01, 0x85, 0x04, + 0x09, 0x30, 0x75, 0x08, 0x95, 0x01, 0x81, 0x02, 0xc0, + 0x05, 0x05, 0x09, 0x02, 0xa1, 0x01, 0x85, 0x05, + 0x79, 71, 0x09, 0x00, 0x15, 0x00, 0x26, 0xff, 0x00, + 0x75, 0x08, 0x95, 28, 0x81, 0x00, 0xc0, + }; + const auto descriptor = FindDescriptor(bytes, sizeof(bytes)); + Check(descriptor.reportId == 5 && descriptor.stringIndex == 71 && descriptor.payloadSize == 28, + "Find the OPD report in a composite HID descriptor"); + Check(FindDescriptor(bytes, sizeof(bytes) - 2).stringIndex == 0, "Reject a truncated descriptor"); + bytes[24] = 4; + Check(FindDescriptor(bytes, sizeof(bytes)).stringIndex == 0, "Reject another input field sharing the OPD report ID"); + bytes[24] = 5; + bytes[20] = 3; + Check(FindDescriptor(bytes, sizeof(bytes)).stringIndex == 0, "Reject a different application usage"); + bytes[20] = 2; + bytes[sizeof(bytes) - 2] = 0x04; + Check(FindDescriptor(bytes, sizeof(bytes)).stringIndex == 71, "Allow other data-array flags"); + bytes[sizeof(bytes) - 2] = 0x02; + Check(FindDescriptor(bytes, sizeof(bytes)).stringIndex == 0, "Reject a variable input field"); + + const unsigned char unnumbered[] = { + 0x05, 0x05, 0x09, 0x02, 0xa1, 0x01, 0x79, 71, 0x09, 0x00, + 0x75, 0x08, 0x95, 20, 0x81, 0x00, 0xc0, + }; + const auto shortReport = FindDescriptor(unnumbered, sizeof(unnumbered)); + Check(shortReport.reportId == 0 && shortReport.stringIndex == 71 && shortReport.payloadSize == 20, + "Accept an unnumbered acceleration-only report"); +} + +static bool CheckUsbString(const char* signature, bool truncate = false) { + return VerifySignature(71, [&](uint8_t index, uint16_t language, auto& bytes) { + if (index == 0 && language == 0) { + bytes[0] = 4; + bytes[1] = 3; + bytes[2] = 9; + bytes[3] = 4; + return 4; + } + if (index != 71 || language != 0x0409) return -1; + bytes.fill(0); + const int size = static_cast(2 + std::strlen(signature) * 2); + bytes[0] = static_cast(size); + bytes[1] = 3; + for (int i = 2; i < size; i += 2) bytes[i] = signature[(i - 2) / 2]; + return truncate ? size - 2 : size; + }) == ProbeResult::Found; +} + +static void CheckPollingState() { + Input input; + std::vector events; + input.Start([](const VpeInputEvent* event, void* data) { + static_cast*>(data)->push_back(*event); + }, &events); + const int first = input.Connect("first", "Pinscape Pico", {5, 71, 28}, 0); + const int second = input.Connect("second", "Other OPD", {0, 71, 20}, 0); + VpeInputDeviceInfo devices[2]{}; + Check(input.ListDevices(devices, 2) == 2 && std::strcmp(devices[0].displayName, "Pinscape Pico (OPD)") == 0 + && devices[0].axisCount == 6 && devices[1].axisCount == 2, "Expose separate devices and only complete axes"); + + Keys keys{}; + input.BeginPoll(10, true, keys); + unsigned char report[29]{}; + report[0] = 5; + report[14] = 2; // Left flipper, bit 9. + report[18] = 0x80; // Acceleration X = -32768. + events.clear(); + input.Receive(first, report, sizeof(report) - 1, 10); + Check(events.empty(), "Ignore a truncated report"); + input.Receive(first, report, sizeof(report), 10); + Check(events.size() == 7 && events[0].action == VPE_INPUT_LEFT_FLIPPER && events[0].value == 1 + && events[1].value == -1 && events[1].deviceIndex == first, "Publish a button and all six signed axes"); + VpeInputAxisInfo axes[6]{}; + Check(input.ListAxes(first, axes, 6) == 6 && axes[0].rawValue == -1 && axes[0].timestampUsec == 10 + && axes[0].kind == VPE_AXIS_KIND_ACCELERATION && axes[2].kind == VPE_AXIS_KIND_VELOCITY, + "Expose the live axis snapshot"); + + keys[VPE_INPUT_LEFT_FLIPPER] = true; + input.BeginPoll(20, true, keys); + input.Receive(second, report + 1, 20, 20); + events.clear(); + report[14] = 0; + input.Receive(first, report, sizeof(report), 20); + Check(events.empty(), "A repeated timestamp suppresses motion and other sources preserve a held button"); + keys[VPE_INPUT_LEFT_FLIPPER] = false; + input.BeginPoll(30, true, keys); + Check(events.empty(), "An unnumbered controller still holds the shared button"); + input.SetGameplayEnabled(0); + report[1] = 20; + report[18] = 0x40; + input.Receive(first, report, sizeof(report), 30); + Check(events.empty(), "Do not send OPD axis callbacks during gameplay pause"); + Check(input.ListAxes(first, axes, 6) == 6 && axes[0].rawValue == .5f && axes[0].timestampUsec == 30, + "Keep OPD calibration telemetry current during gameplay pause"); + input.Disconnect(second, 30); + Check(events.size() == 1 && events[0].eventType == VPE_INPUT_EVENT_DEVICES_CHANGED + && input.ListAxes(second, nullptr, 0) == 0, "Hot unplug updates the snapshot during pause"); + input.SetGameplayEnabled(1); + input.BeginPoll(40, true, keys); + Check(events.size() == 2 && events[1].eventType == VPE_INPUT_EVENT_ACTION && events[1].value == 0, + "Release the shared action on resume"); + report[1] = 40; + input.Receive(first, report, sizeof(report), 50); + Check(events.size() == 8 && events[2].eventType == VPE_INPUT_EVENT_AXIS && events[2].value == .5f, + "Resume OPD axis callbacks when gameplay resumes"); + input.Stop(); + Check(input.ListDevices(nullptr, 0) == 0, "Clear snapshots when polling stops"); +} + +static void CheckGenericButtons() { + Input input; + std::vector actions; + input.Start([](const VpeInputEvent* event, void* data) { + if (event->eventType == VPE_INPUT_EVENT_ACTION) { + static_cast*>(data)->push_back(*event); + } + }, &actions); + const int first = input.Connect("mapped", "OPD", {5, 71, 28}, 0); + const int other = input.Connect("other", "OPD", {5, 71, 28}, 0); + VpeInputButtonInfo buttons[32]{}; + Check(VpeInputListDeviceButtons(first, buttons, 32) == 32 && buttons[31].buttonId == 31 + && std::strcmp(buttons[31].name, "Generic Button 32") == 0, "Expose one-based OPD button labels"); + + const VpeInputButtonBinding binding{VPE_INPUT_TILT, 31, "mapped"}; + VpeInputSetButtonBindings(&binding, 1); + Keys keys{}; + input.BeginPoll(10, true, keys); + unsigned char report[29]{}; + report[0] = 5; + report[12] = 0x80; // Generic button 32, separate from predefined buttons. + input.Receive(other, report, sizeof(report), 20); + Check(actions.empty(), "Do not use the same button number on another device"); + input.Receive(first, report, sizeof(report), 20); + Check(actions.size() == 1 && actions.back().action == VPE_INPUT_TILT && actions.back().value == 1, + "Route the selected generic OPD button"); + Check(VpeInputListDeviceButtons(first, buttons, 32) == 32 && buttons[31].isPressed, + "Expose the generic button level"); + + keys[VPE_INPUT_TILT] = true; + input.BeginPoll(30, true, keys); + report[12] = 0; + report[14] = 0x80; // Predefined physical tilt replaces the held generic button. + input.Receive(first, report, sizeof(report), 30); + keys[VPE_INPUT_TILT] = false; + input.BeginPoll(40, true, keys); + Check(actions.size() == 1, "Combine generic, predefined and keyboard tilt without a spurious release"); + report[14] = 0; + input.Receive(first, report, sizeof(report), 40); + Check(actions.size() == 2 && actions.back().value == 0, "Release only when all tilt sources release"); + + input.SetGameplayEnabled(0); + report[12] = 0x80; + input.Receive(first, report, sizeof(report), 50); + input.SetGameplayEnabled(1); + input.BeginPoll(60, true, keys); + Check(actions.size() == 2, "Ignore a generic button pressed during pause"); + report[12] = 0; + input.Receive(first, report, sizeof(report), 60); + report[12] = 0x80; + input.Receive(first, report, sizeof(report), 60); + Check(actions.size() == 3 && actions.back().value == 1, "Re-arm after the button releases"); + input.Disconnect(first, 70); + Check(actions.size() == 4 && actions.back().value == 0 && VpeInputListDeviceButtons(first, nullptr, 0) == 0, + "Release the action and clear button metadata on unplug"); + const VpeInputControlBinding combo[] = { + {VPE_INPUT_SLAM_TILT, 0, VPE_CONTROL_AXIS_ABOVE, 0, .5f, "other"}, + {VPE_INPUT_SLAM_TILT, 0, VPE_CONTROL_BUTTON, 31, 0.f, "other"}, + }; + VpeInputSetControlBindings(combo, 2); + input.BeginPoll(80, true, keys); + Check(actions.size() == 4, "A held OPD button is only part of the combo"); + report[18] = 0x60; + input.Receive(other, report, sizeof(report), 80); + Check(actions.size() == 5 && actions.back().action == VPE_INPUT_SLAM_TILT && actions.back().value == 1, + "Thresholds see OPD axis values even when a report repeats the motion timestamp"); + report[12] = 0; + input.Receive(other, report, sizeof(report), 90); + Check(actions.size() == 6 && actions.back().value == 0, "Releasing an OPD combo member releases the action"); + VpeInputSetButtonBindings(nullptr, 0); + input.Stop(); +} + +int main() { + CheckDescriptor(); + Check(CheckUsbString("OpenPinballDeviceStruct/1.0"), "Read the signature in the advertised USB language"); + Check(!CheckUsbString("OpenPinballDeviceStruct/1.0", true), "Reject a truncated USB string"); + Check(!CheckUsbString("OpenPinballDeviceStruct/2.0"), "Reject an incompatible USB signature"); + CheckPollingState(); + CheckGenericButtons(); + + Check(SupportsVersion(L"OpenPinballDeviceStruct/1.0"), "Recognize the Pico signature"); + Check(SupportsVersion(L"OpenPinballDeviceStruct/1.12"), "Accept a future minor version"); + Check(!SupportsVersion(L"OpenPinballDeviceStruct/2.0"), "Reject a different major version"); + Check(!SupportsVersion(L"OpenPinballDeviceStruct/1."), "Reject a missing minor version"); + Check(!SupportsVersion(L"OpenPinballDeviceStruct/1.0junk"), "Reject malformed versions"); + + const unsigned char bytes[] = { + 0x06, // report ID + 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, // timestamp + 0xff, 0xff, 0xff, 0xff, // generic buttons + 0, 0x80, 0x40, 0, // physical tilt and left nudge + 0x00, 0x80, 0xff, 0x7f, // acceleration (-32768, 32767) + 0x00, 0x40, 0x00, 0xc0, // velocity (+16384, -16384) + 0x00, 0x20, 0x00, 0xe0, // plunger (+8192, -8192) + }; + Report report{}; + Check(!Report::Read(bytes, sizeof(bytes), 7, report), "Reject a different report ID"); + Check(!Report::Read(bytes, 16, 6, report), "Reject a truncated header"); + Check(Report::Read(bytes, sizeof(bytes), 6, report), "Decode a Pico report"); + Check(report.Timestamp() == UINT64_C(0x0123456789abcdef), "Read little-endian device timestamp"); + Check(report.PinballButtons() == ((1u << 15) | (1u << 22)), "Read only the predefined button mask"); + Check(ButtonActions[15] == VPE_INPUT_TILT && ButtonActions[22] == VPE_INPUT_LEFT_NUDGE, "Route tilt and nudge bits"); + const float expected[] = {-1.f, 32767.f / 32768.f, .5f, -.5f, .25f, -.25f}; + for (const auto& axis : Axes) { + float value; + Check(report.TryReadAxis(axis, value) && value == expected[axis.id], "Decode signed, named OPD axes"); + } + Check(Report::Read(bytes, 21, 6, report), "Read an acceleration-only report"); + float value; + Check(report.TryReadAxis(Axes[1], value), "Keep complete acceleration fields"); + Check(!report.TryReadAxis(Axes[2], value), "An absent velocity field is distinct from zero"); + Check(Report::Read(bytes, 22, 6, report) && !report.TryReadAxis(Axes[2], value), "Reject a partial axis field"); + + Clock clock; + int64_t sample; + Check(clock.Translate(500000, 2000, sample) && sample == 2000, "Anchor device time in the host domain"); + Check(!clock.Translate(500000, 2500, sample), "Ignore repeated timestamps for motion samples"); + Check(clock.Translate(500750, 3000, sample) && sample == 2750, "Preserve a fresh report's interval"); + Check(clock.Translate(501250, 3100, sample) && sample == 3100, "Clamp timestamps to receipt time"); + Check(clock.Translate(100, 4000, sample) && sample == 4000, "Reanchor after a controller reset"); + Check(clock.Translate(200, 30000, sample) && sample == 30000, "Reanchor stale timestamps after a stall"); + + ActionLatch latch; + bool pressed; + Check(latch.Update(true, true, pressed) && pressed, "Publish a button press"); + Check(!latch.Update(false, false, pressed), "Suppress a release during pause"); + Check(latch.Update(false, true, pressed) && !pressed, "Reconcile that release on resume"); + Check(!latch.Update(true, false, pressed), "Suppress a press during pause"); + Check(!latch.Update(true, true, pressed), "Don't replay a menu press still held on resume"); + Check(!latch.Update(false, true, pressed), "Re-arm after the ignored press is released"); + Check(latch.Update(true, true, pressed) && pressed, "Publish the next gameplay press"); + Check(!latch.Update(false, false, pressed), "Keep a published hold during pause"); + Check(!latch.Update(true, false, pressed), "Suppress another press after releasing that hold"); + Check(latch.Update(true, true, pressed) && !pressed, "Release the old hold without replaying the new press"); +}