From c68f494160c8e79c76bfa109b2e99571a5c11358 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 07:39:13 -0500 Subject: [PATCH] RT-INPUT-SCRIPT-NO-SDL3: serve LEONIDA_INPUT_SCRIPT without SDL3 A build without SDL3 answered GameInputCreate with no devices and E_NOTIMPL for every other slot, so the title waited at its first "press A" prompt forever: no CI artifact or offline build could get past it. With LEONIDA_INPUT_SCRIPT set, gameinput_no_sdl.cpp now serves one scripted pad (an Xbox One gamepad) driven by the script alone: device enumeration through RegisterDeviceCallback (blocking, async, dispatcher), FindDeviceFromId, and GetCurrentReading/GetNextReading/GetPreviousReading whose gamepad and UI navigation state follow the script. Readings are taken when the title asks, so no thread polls. Without the variable it behaves as before. The parser, the 300 ms timeline, the button names, the press log lines and the UI navigation mapping move from gameinput.cpp into gameinput_script.h, which both shims use; nothing in it needs SDL. gameinput.cpp checks the shared SDL button numbers against SDL_GamepadButton at compile time. gameinput_no_sdl_test --input-script (CTest gameinput_no_sdl_script) checks the scripted pad on a fake clock. Docs: runtime/README.md, docs/gameinput.md, docs/linux_proton.md, docs/README.md. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- docs/gameinput.md | 50 +- docs/linux_proton.md | 9 +- runtime/CMakeLists.txt | 5 +- runtime/README.md | 8 +- runtime/shims/gameinput.cpp | 171 ++----- runtime/shims/gameinput_no_sdl.cpp | 644 ++++++++++++++++++++++++- runtime/shims/gameinput_no_sdl.h | 12 + runtime/shims/gameinput_script.h | 180 +++++++ runtime/test/gameinput_no_sdl_test.cpp | 242 +++++++++- 10 files changed, 1174 insertions(+), 149 deletions(-) create mode 100644 runtime/shims/gameinput_no_sdl.h create mode 100644 runtime/shims/gameinput_script.h diff --git a/docs/README.md b/docs/README.md index 6856349124..0e090c476e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -88,7 +88,7 @@ method, scope and caveats. No game data is included. | [directstorage.md](directstorage.md) | Console DirectStorage: the DLL and ABI the title is expected to use (`DStorageGetFactory`, `dstorage_xs`, `XCRDAPI`), how sure that is and the evidence for it, and what `runtime/shims/dstorage.cpp` serves on the PC. The executable's own imports are unmeasured. | | [cpu_features.md](cpu_features.md) | CPU instructions in the executable a desktop CPU may lack (`tools/cpu_feature_scan.py`): 19 SSE4a, 10 CLZERO and 4 MONITORX/MWAITX sites (AMD only) and 8 CLWB sites (Intel since Ice Lake), all real code; `#UD` on hosts without them. | | [xcl_compare.md](xcl_compare.md) | XCL's synthetic test title under `gta6rt --run` and under XCL (`tools/xcl_compare.py`): 5 of 50 checks pass here, both hangs are the documented manual-queue terminate deadlock, and each other difference mapped to an open item or a lead. | -| [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend; by hand on an Xbox Series X pad (Bluetooth) and a DualSense (USB). 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | +| [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; without SDL3, one scripted pad for `LEONIDA_INPUT_SCRIPT`; 261 checks on virtual joysticks and a fake haptic backend; by hand on an Xbox Series X pad (Bluetooth) and a DualSense (USB). 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | | [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). | | [pipeline_check.md](pipeline_check.md) | Driver-level corpus check: the full corpus, 26,503 of 26,503 modules and pipelines, 0 failures (RTX 4060 Ti); an earlier 10/12-shard run, 22,092 modules and 2,217 compute pipelines, also had 0 failures. Driver-level corpus check: 10/12 shards, 22,092 modules, 2,217 compute pipelines, 0 failures. | | [multi_gpu_validation.md](multi_gpu_validation.md) | Running disjoint shards on eight identical RDNA1/RADV GPUs: PCI-BDF pinning, base controls, per-card logs, the V540 farm's aggregate results and its known driver limitations. | diff --git a/docs/gameinput.md b/docs/gameinput.md index feed391533..06c2013a5d 100644 --- a/docs/gameinput.md +++ b/docs/gameinput.md @@ -37,10 +37,42 @@ SDL3 is available in one of these ways: - **A local copy of that tarball**: extract it and pass `-DFETCHCONTENT_SOURCE_DIR_SDL3=`; it is built the same way, without a download. -Without any of these, or with `-DLEONIDA_SDL3=OFF`, configure prints a message and `gta6rt` is built without the shim: -it has no `GameInputCreate`, as before, so the loader binds it to the host's `GameInput.dll` or the unimplemented -thunk. `gameinput_test` and `gameinput_probe` are not built, and CTest lists `gameinput` as not run (disabled) rather -than failing. +Without any of these, or with `-DLEONIDA_SDL3=OFF`, configure prints a message and `gta6rt` is built without the SDL3 +shim. It links `runtime/shims/gameinput_no_sdl.cpp` instead, which still serves `GameInputCreate` (by name and as +`gameinput.dll!#1`): with no devices, or with `LEONIDA_INPUT_SCRIPT` set with one scripted pad (see +[Scripted input without SDL3](#scripted-input-without-sdl3)). `gameinput_test` and `gameinput_probe` are not built, +and CTest lists `gameinput` and `gameinput_script` as not run (disabled) rather than failing; `gameinput_no_sdl` and +`gameinput_no_sdl_script` run instead. + +### Scripted input without SDL3 + +The Windows artifacts of CI and offline builds have no SDL3. Without a device, the title waits at its first "press A" +prompt forever, so no headless or CI run could get past it. With `LEONIDA_INPUT_SCRIPT` set, such a build serves one +scripted pad, driven by the script alone: + +- **The device:** an Xbox One gamepad named `Scripted pad (Leonida)`, connected from the first `GameInputCreate`. It + is reported by `RegisterDeviceCallback` enumeration (blocking on the caller's thread, async from a thread of the + shim, or through `IGameInputDispatcher::Dispatch` once the title made a dispatcher) and found by `FindDeviceFromId`. + It is already connected, so a callback registered without enumeration hears nothing. +- **The readings:** `GetCurrentReading`, `GetNextReading` and `GetPreviousReading`, with gamepad, UI navigation, + controller axis and controller button state. A reading is taken when the title asks for one and the script's state + has changed since the last, so no thread polls; the history keeps the last 64 readings. +- **The timeline:** the same as with SDL3 (`runtime/shims/gameinput_script.h` holds the parser, the timeline and the + log lines for both): seconds from the first `GameInputCreate`, each press held 300 ms, then released. +- **Not served:** reading callbacks, aggregate devices, rumble and every other device. Those slots answer `E_NOTIMPL` + and log the slot once. Controllers and the [keyboard pad](#keyboard-pad) still need SDL3. + +The start of the run logs one line with the counts, and each press logs the same lines as with SDL3: + +```text +[rt] gameinput: served without SDL3: one scripted pad for LEONIDA_INPUT_SCRIPT (3 scripted press(es), 0 rejected); controllers and the keyboard pad need SDL3 +[rt] gameinput: scripted press of button 0 at 40.0 s +[rt] gameinput: press a@40.0 (Scripted pad (Leonida)) +``` + +A press is logged when the title reads it, so a press the title never reads is not logged. `LEONIDA_INPUT_LOG=0` +turns the `press` lines off. Without `LEONIDA_INPUT_SCRIPT`, the shim serves no devices and answers `E_NOTIMPL` for +every slot past `Release`, as before. `scripts/build_runtime.ps1` (what `make_game.py` runs) builds the shim only on its CMake path, when Visual Studio's C++ CMake tools are installed. Its direct-`cl.exe` fallback compiles a fixed file list without the shim and warns @@ -302,7 +334,7 @@ line is logged when it takes effect); tracking goes on underneath, so clearing i | `LEONIDA_PROMPTS_SWITCH_MS` | `300` | shortest time between two changes of the active input family, 0..2000 ms | | `LEONIDA_GAMEINPUT_THREAD` | `1` | `0` stops the background poll thread; only `rt::gameinput::poll()` then reads the pads (tests) | | `LEONIDA_KEYBOARD_PAD` | `off` | `1` adds the [keyboard pad](#keyboard-pad), read while this process has focus; `always` reads keys whatever has focus | -| `LEONIDA_INPUT_SCRIPT` | unset | With the keyboard pad enabled, set comma-separated `button@seconds` entries, e.g. `a@2,a@4,start@6`. The first pad update reads the script once at startup and starts the clock. `reload_config()` does not reread it. Each press lasts 300 ms. Buttons are `a b x y start back lb rb up down left right`. Spaces around entries are allowed. Empty entries, unknown buttons and invalid times (including negative or non-finite values) are counted and ignored. | +| `LEONIDA_INPUT_SCRIPT` | unset | Comma-separated `button@seconds` entries, e.g. `a@2,a@4,start@6`. With SDL3 they drive the keyboard pad, which has to be enabled; without SDL3 they drive [one scripted pad](#scripted-input-without-sdl3), the only device. The first pad update (without SDL3, the first `GameInputCreate`) reads the script once at startup and starts the clock. `reload_config()` does not reread it. Each press lasts 300 ms. Buttons are `a b x y start back lb rb up down left right`. Spaces around entries are allowed. Empty entries, unknown buttons and invalid times (including negative or non-finite values) are counted and ignored. | | `LEONIDA_MOUSE_SENSITIVITY` | `1` | scales how far the mouse moves the keyboard pad's right stick, 0.1..10 | SDL's own hints (`SDL_JOYSTICK_*`, see SDL's `SDL_hints.h`) also apply, for example `SDL_JOYSTICK_HIDAPI_PS5=0` to @@ -457,6 +489,14 @@ rests on a transcription rather than on a side-by-side compile. button, the touchpad, a trigger or a stick, stick drift and a one-count mouse jitter ignored, a real mouse movement counted, the 300 ms window on the real clock, and `LEONIDA_PROMPTS` forcing, changing, ignoring an unknown value and clearing. +- `gameinput_no_sdl_test` (CTest, only in a build without SDL3, no controller): `gameinput_no_sdl` checks the + identity-only object (both names served, `AddRef`/`Release`, `E_NOTIMPL` without touching the out-parameter). + `gameinput_no_sdl_script` sets `LEONIDA_INPUT_SCRIPT` with overlapping presses, a mixed-case name, `rsup` and three + rejected entries, puts the shim on a fake clock and checks the scripted pad: blocking, async and dispatcher + enumeration (and none without enumeration, for another status or another kind), the device info, `FindDeviceFromId`, + the buttons, UI navigation and right stick read at chosen times (held for 0.3 s, a later press of the same button + not cut short, nothing after the script), no new reading without a change, `GetPreviousReading` and + `GetNextReading`, no motion, and reading callbacks answering `E_NOTIMPL`. - `gameinput_test` (CTest, no controller): turns SDL's real backends off and drives the shim through `rt::shims::find` with SDL virtual joysticks, an Xbox-style pad with trigger motors, a DualSense (Sony `054c:0ce6`) and a pad without trigger motors. It checks enumeration and device callbacks, the button, stick, diff --git a/docs/linux_proton.md b/docs/linux_proton.md index f98aacf149..03f663eca8 100644 --- a/docs/linux_proton.md +++ b/docs/linux_proton.md @@ -53,12 +53,15 @@ the layout the comments at their top describe (`/opt/leonida` for traces, overla `__GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1`. - **Input:** a pad through GameInput/SDL3, or the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), or a script: `LEONIDA_INPUT_SCRIPT=a@210,a@240` presses A at those seconds (any length since this branch; it was cut at 63 - characters before). + characters before). The script also works in a build without SDL3, where it drives one scripted pad + ([docs/gameinput.md](gameinput.md#scripted-input-without-sdl3)); pads and the keyboard pad need SDL3. - **Window:** frames are presented in the title's own window; `LEONIDA_PRESENT_WINDOW=own|hidden` chooses otherwise. Three setup mistakes each give a blank or empty picture without an error: the executable's embedded shaders missing -from the library (`exe/index.json`), a build without SDL3 (no pad), and a BCPack predictor file that was never -generated (`tools/build_dstorage_history.py`; without it the loading art and most BC7 textures stay empty). +from the library (`exe/index.json`), a build without SDL3 and without `LEONIDA_INPUT_SCRIPT` (no pad, so nothing +gets past the first prompt; set a script, or build with SDL3 for a pad or the keyboard pad), and a BCPack predictor +file that was never generated (`tools/build_dstorage_history.py`; without it the loading art and most BC7 textures +stay empty). ## What a healthy boot looks like (Linux machine) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e9cb8d4345..57ccce76a8 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -690,7 +690,8 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) endif() if(NOT (LEONIDA_SDL3 AND TARGET SDL3::SDL3-static)) # Nothing served gameinput.dll in a build without SDL3, so the loader fell through to the host's gameinput.dll and - # that one answers GameInputCreate with a null interface the title dereferences. Keep the object identity honest. + # that one answers GameInputCreate with a null interface the title dereferences. Keep the object identity honest, + # and with LEONIDA_INPUT_SCRIPT serve one pad driven by the script (shims/gameinput_script.h, shared with SDL3's). target_sources(gta6rt PRIVATE shims/gameinput_no_sdl.cpp) add_executable(gameinput_no_sdl_test test/gameinput_no_sdl_test.cpp @@ -1657,6 +1658,8 @@ if(BUILD_TESTING) add_test(NAME active_input COMMAND active_input_test) if(WIN32 AND TARGET gameinput_no_sdl_test) add_test(NAME gameinput_no_sdl COMMAND gameinput_no_sdl_test) + # LEONIDA_INPUT_SCRIPT without SDL3: the scripted pad, its device callbacks and its readings on a fake clock. + add_test(NAME gameinput_no_sdl_script COMMAND gameinput_no_sdl_test --input-script) endif() if(WIN32 AND TARGET gameinput_test) add_test(NAME gameinput COMMAND gameinput_test) diff --git a/runtime/README.md b/runtime/README.md index 1573b8883c..070fa28add 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -288,7 +288,9 @@ Current limits, by design: lightbar. Optional and CMake-only: built when an installed SDL3 is found, or with `-DLEONIDA_SDL3_FETCH=ON` to download the pinned release; nothing is downloaded otherwise, and the `scripts/build_runtime.ps1` cl.exe fallback never builds it. See [docs/gameinput.md](../docs/gameinput.md) for the mapping, the `LEONIDA_DS_*` settings and what is - unverified. + unverified. A build without SDL3 links `shims/gameinput_no_sdl.cpp` instead: no devices, or with + `LEONIDA_INPUT_SCRIPT` set one scripted pad driven by the script alone, so a headless or CI build can get past the + title's first prompt ([docs/gameinput.md](../docs/gameinput.md#scripted-input-without-sdl3)). ### What `xgameruntime.dll` reports: environment overrides @@ -340,6 +342,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_VOLUME_MIPS` | on | The XG layout of a 3D texture with mips or a block format is computed (`shims/xg_xs_layout.h`). `0` refuses it. | | `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`), and only in the build the watchdog was measured in. | | `LEONIDA_PEEK_SECONDS` | `10` | *Diagnostic.* The period of the `LEONIDA_PEEK` thread (`src/main.cpp`), which prints 8-byte values of the title's image. | +| `LEONIDA_INPUT_SCRIPT` | unset | Timed pad presses, `button@seconds` separated by commas (`a@70,a@85,start@120`), each held 300 ms; the clock starts with the shim. Works with and without SDL3: with SDL3 it drives the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), without SDL3 one scripted pad that is the only device. Controllers and the keyboard pad still need SDL3. Format and buttons in [docs/gameinput.md](../docs/gameinput.md#environment-variables). | | `LEONIDA_INPUT_LOG` | on | The GameInput shim logs every press in `LEONIDA_INPUT_SCRIPT`'s form (`name@seconds`), so a session played by hand can be replayed. `0` turns the lines off. | | `LEONIDA_LOG_ALLOCINFO` | unset | *Diagnostic.* `1` logs every device slot 25 call (`GetResourceAllocationInfo`) with its thread, description and sizes (`shims/d3d12_xs_device.cpp`). | | `LEONIDA_LOG_EXE_PIPELINES` | unset | *Diagnostic.* When set, one line per distinct graphics pipeline that uses a program translated from the executable's inline containers. | @@ -454,6 +457,9 @@ SDK, or `-DLEONIDA_VULKAN_HEADERS_FETCH=ON` to download the pinned Khronos Vulka `gameinput_test` (only with SDL3; otherwise CTest lists `gameinput` as not run) drives the GameInput shim on SDL virtual joysticks (no controller needed): enumeration, readings and the button/axis mapping, rumble and trigger rumble, DualSense effect bytes, a dispatcher, and hot-plug. +`gameinput_no_sdl_test` (only without SDL3) checks the shim a build without SDL3 links: `gameinput_no_sdl` the +identity-only object, `gameinput_no_sdl_script` the scripted pad of `LEONIDA_INPUT_SCRIPT` on a fake clock (device +callbacks, readings at chosen times, the reading history). `gameinput_probe [--seconds N] [--rumble] [--force-feedback]` is the manual check on a real pad: it prints live readings, plays each motor and trigger, and holds a constant force on a pad that reports a force-feedback motor. diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index db685e71f5..47e9aa9412 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp @@ -52,6 +52,7 @@ #include "gameinput.h" #include "gameinput_abi.h" +#include "gameinput_script.h" #include "shims.h" using namespace gi; @@ -132,18 +133,30 @@ const rt::gameinput::HapticApi& haptics() { return *g_haptic_api.load(); } // ---- configuration ---------------------------------------------------------------------------------------------- -std::string env(const char* name) { - // Any length: an input script (LEONIDA_INPUT_SCRIPT) is easily longer than a fixed buffer, and a value that did - // not fit used to read as unset. - const DWORD need = GetEnvironmentVariableA(name, nullptr, 0); // with the terminator - if (need == 0) return {}; - std::string s(need, '\0'); - const DWORD n = GetEnvironmentVariableA(name, s.data(), need); - if (n == 0 || n >= need) return {}; - s.resize(n); - for (auto& c : s) c = static_cast(std::tolower(static_cast(c))); - return s; +std::string env(const char* name) { return rt::gameinput::script::env_lower(name); } + +// The script's button numbers are SDL's (gameinput_script.h shares them with the shim built without SDL3). +constexpr bool script_buttons_match_sdl() { + const struct { + uint32_t bit; + SDL_GamepadButton sdl; + } expected[] = {{GameInputGamepadA, SDL_GAMEPAD_BUTTON_SOUTH}, {GameInputGamepadB, SDL_GAMEPAD_BUTTON_EAST}, + {GameInputGamepadX, SDL_GAMEPAD_BUTTON_WEST}, {GameInputGamepadY, SDL_GAMEPAD_BUTTON_NORTH}, + {GameInputGamepadMenu, SDL_GAMEPAD_BUTTON_START}, {GameInputGamepadView, SDL_GAMEPAD_BUTTON_BACK}, + {GameInputGamepadLeftShoulder, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER}, + {GameInputGamepadRightShoulder, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER}, + {GameInputGamepadDPadUp, SDL_GAMEPAD_BUTTON_DPAD_UP}, {GameInputGamepadDPadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN}, + {GameInputGamepadDPadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT}, + {GameInputGamepadDPadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT}}; + if (std::size(expected) != std::size(rt::gameinput::script::kButtons)) return false; + for (const auto& e : expected) { + bool found = false; + for (const auto& b : rt::gameinput::script::kButtons) found |= b.bit == e.bit && b.sdl == e.sdl; + if (!found) return false; + } + return true; } +static_assert(script_buttons_match_sdl(), "gameinput_script.h's SDL button numbers drifted from SDL_GamepadButton"); rt::gameinput::Config read_config() { rt::gameinput::Config c; @@ -1103,30 +1116,7 @@ Snapshot read_pad(Device* d) { } } - // UI navigation derived from the gamepad (VERIFY against the console's own mapping). - const uint32_t b = s.gamepad.buttons; - const float t = 0.5f; - uint32_t& u = s.ui; - if (b & GameInputGamepadMenu) u |= GameInputUiNavigationMenu; - if (b & GameInputGamepadView) u |= GameInputUiNavigationView; - if (b & GameInputGamepadA) u |= GameInputUiNavigationAccept; - if (b & GameInputGamepadB) u |= GameInputUiNavigationCancel; - if (b & GameInputGamepadX) u |= GameInputUiNavigationContext1; - if (b & GameInputGamepadY) u |= GameInputUiNavigationContext2; - if (b & GameInputGamepadLeftThumbstick) u |= GameInputUiNavigationContext3; - if (b & GameInputGamepadRightThumbstick) u |= GameInputUiNavigationContext4; - if ((b & GameInputGamepadDPadUp) || s.gamepad.leftThumbstickY > t) u |= GameInputUiNavigationUp; - if ((b & GameInputGamepadDPadDown) || s.gamepad.leftThumbstickY < -t) u |= GameInputUiNavigationDown; - if ((b & GameInputGamepadDPadLeft) || s.gamepad.leftThumbstickX < -t) u |= GameInputUiNavigationLeft; - if ((b & GameInputGamepadDPadRight) || s.gamepad.leftThumbstickX > t) u |= GameInputUiNavigationRight; - if (b & GameInputGamepadLeftShoulder) u |= GameInputUiNavigationPageLeft; - if (b & GameInputGamepadRightShoulder) u |= GameInputUiNavigationPageRight; - if (s.gamepad.leftTrigger > t) u |= GameInputUiNavigationPageUp; - if (s.gamepad.rightTrigger > t) u |= GameInputUiNavigationPageDown; - if (s.gamepad.rightThumbstickY > t) u |= GameInputUiNavigationScrollUp; - if (s.gamepad.rightThumbstickY < -t) u |= GameInputUiNavigationScrollDown; - if (s.gamepad.rightThumbstickX < -t) u |= GameInputUiNavigationScrollLeft; - if (s.gamepad.rightThumbstickX > t) u |= GameInputUiNavigationScrollRight; + s.ui = rt::gameinput::script::ui_navigation(s.gamepad); return s; } @@ -1897,80 +1887,29 @@ void update_keyboard_pad() { for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard // pad, in seconds since the pad's first update, each held 300 ms. For unattended boots: the title's first prompt - // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). Buttons: a b x y start back lb rb - // up down left right. The rsup and rsdown entries replay the right-stick throws logged below. + // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). The parser, the timeline and the + // button names are gameinput_script.h's, shared with the scripted pad of a build without SDL3. + namespace script = rt::gameinput::script; int right_y = g_keyboard.right_y; - struct ScriptedPress { - SDL_GamepadButton button; - double at; - int right_y = 0; - }; - static const std::vector script = [] { - std::vector out; - static const std::pair names[] = { - {"a", SDL_GAMEPAD_BUTTON_SOUTH}, {"b", SDL_GAMEPAD_BUTTON_EAST}, - {"x", SDL_GAMEPAD_BUTTON_WEST}, {"y", SDL_GAMEPAD_BUTTON_NORTH}, - {"start", SDL_GAMEPAD_BUTTON_START}, {"back", SDL_GAMEPAD_BUTTON_BACK}, - {"lb", SDL_GAMEPAD_BUTTON_LEFT_SHOULDER}, {"rb", SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER}, - {"up", SDL_GAMEPAD_BUTTON_DPAD_UP}, {"down", SDL_GAMEPAD_BUTTON_DPAD_DOWN}, - {"left", SDL_GAMEPAD_BUTTON_DPAD_LEFT}, {"right", SDL_GAMEPAD_BUTTON_DPAD_RIGHT}}; - const std::string text = env("LEONIDA_INPUT_SCRIPT"); - if (text.empty()) return out; - constexpr char whitespace[] = " \t\r\n\f\v"; - size_t items = 0; - for (size_t at = 0, end; at <= text.size(); at = end + 1) { - ++items; - end = std::min(text.find(',', at), text.size()); - const std::string item = text.substr(at, end - at); - const size_t first = item.find_first_not_of(whitespace); - const size_t sep = item.find('@'); - if (sep == std::string::npos || first >= sep) continue; - const char* time = item.c_str() + sep + 1; - char* tail; - const double seconds = std::strtod(time, &tail); - if (tail == time || !std::isfinite(seconds) || seconds < 0 || - item.find_first_not_of(whitespace, tail - item.c_str()) != std::string::npos) continue; - if (item.compare(first, sep - first, "rsup") == 0 || item.compare(first, sep - first, "rsdown") == 0) { - const bool up = item.compare(first, sep - first, "rsup") == 0; - out.push_back({SDL_GAMEPAD_BUTTON_INVALID, seconds, up ? -kStickFull : kStickFull}); - continue; - } - for (const auto& [name, button] : names) { - if (item.compare(first, sep - first, name) == 0) { - out.push_back({button, seconds}); - break; - } - } - } - std::fprintf(stderr, "[rt] gameinput: LEONIDA_INPUT_SCRIPT: %zu scripted press(es), %zu rejected\n", - out.size(), items - out.size()); - return out; + static const script::Script scripted = [] { + script::Script s = script::parse(env("LEONIDA_INPUT_SCRIPT")); + if (!s.empty() || s.rejected) + std::fprintf(stderr, "[rt] gameinput: LEONIDA_INPUT_SCRIPT: %zu scripted press(es), %zu rejected\n", + s.presses.size(), s.rejected); + return s; }(); - if (!script.empty()) { + if (!scripted.empty()) { static const ULONGLONG origin = GetTickCount64(); const double now = (GetTickCount64() - origin) / 1000.0; - // One decision per button: a later entry for the same button must not release what an earlier entry holds - // (it did: with several entries only the last one ever reached the title). - bool scripted[SDL_GAMEPAD_BUTTON_COUNT] = {}; - bool named[SDL_GAMEPAD_BUTTON_COUNT] = {}; - for (const auto& press : script) { - const bool held = now >= press.at && now < press.at + 0.3; - if (press.right_y) { - if (held) right_y = press.right_y; - } else { - named[press.button] = true; - scripted[press.button] |= held; - } - } - for (int button = 0; button < SDL_GAMEPAD_BUTTON_COUNT; ++button) { - if (!named[button]) continue; - SDL_SetJoystickVirtualButton(g_keyboard.js, static_cast(button), - scripted[button] || down[button]); - static bool was[SDL_GAMEPAD_BUTTON_COUNT] = {}; - if (scripted[button] && !was[button]) - std::fprintf(stderr, "[rt] gameinput: scripted press of button %d at %.1f s\n", button, now); - was[button] = scripted[button]; + const script::Held held = script::held_at(scripted, now); + if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down + for (const script::Button& b : script::kButtons) { + if (!(scripted.named & b.bit)) continue; + const auto button = static_cast(b.sdl); + SDL_SetJoystickVirtualButton(g_keyboard.js, button, (held.buttons & b.bit) || down[button]); } + static uint32_t was = 0; + script::log_scripted(held.buttons, &was, now); } const int reach = lx && ly ? kStickDiagonal : kStickFull; SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast(lx * reach)); @@ -2053,26 +1992,10 @@ void poll_once() { { static const bool log_presses = env("LEONIDA_INPUT_LOG") != "0"; static const ULONGLONG log_origin = GetTickCount64(); - if (log_presses) { - static const std::pair kNames[] = { - {GameInputGamepadA, "a"}, {GameInputGamepadB, "b"}, - {GameInputGamepadX, "x"}, {GameInputGamepadY, "y"}, - {GameInputGamepadMenu, "start"}, {GameInputGamepadView, "back"}, - {GameInputGamepadLeftShoulder, "lb"}, {GameInputGamepadRightShoulder, "rb"}, - {GameInputGamepadDPadUp, "up"}, {GameInputGamepadDPadDown, "down"}, - {GameInputGamepadDPadLeft, "left"}, {GameInputGamepadDPadRight, "right"}}; - const double at = (GetTickCount64() - log_origin) / 1000.0; - const uint32_t pressed = snap.gamepad.buttons & ~d->last_snap.gamepad.buttons; - for (const auto& n : kNames) - if (pressed & n.first) - std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", n.second, at, d->name.c_str()); - const auto throw_of = [](float y) { return y > 0.6f ? 1 : y < -0.6f ? -1 : 0; }; - const int was = throw_of(d->last_snap.gamepad.rightThumbstickY); - const int is = throw_of(snap.gamepad.rightThumbstickY); - if (is != was && is != 0) - std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", is > 0 ? "rsup" : "rsdown", at, - d->name.c_str()); - } + if (log_presses) + rt::gameinput::script::log_presses(snap.gamepad.buttons & ~d->last_snap.gamepad.buttons, + d->last_snap.gamepad.rightThumbstickY, snap.gamepad.rightThumbstickY, + (GetTickCount64() - log_origin) / 1000.0, d->name.c_str()); } d->last_snap = snap; // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button diff --git a/runtime/shims/gameinput_no_sdl.cpp b/runtime/shims/gameinput_no_sdl.cpp index ab190d2505..77b7ebccf0 100644 --- a/runtime/shims/gameinput_no_sdl.cpp +++ b/runtime/shims/gameinput_no_sdl.cpp @@ -5,21 +5,47 @@ // one), and that host answers GameInputCreate with a null interface while the title ignores the HRESULT: the title's // lazy singleton stores the null and calls AddRef/Release through it, which is a page fault at address 0. // -// This file keeps the object identity honest without any input backend: one static object, slot 0/1/2 as -// QueryInterface/AddRef/Release, E_NOTIMPL for every other slot, so a caller that only holds and releases the -// interface survives and one that asks for devices gets a clean refusal instead of a null dereference. +// This file serves one of two objects, chosen on the first GameInputCreate: +// +// - LEONIDA_INPUT_SCRIPT unset: an object that keeps the identity honest without any input backend. One static +// object, slot 0/1/2 as QueryInterface/AddRef/Release, E_NOTIMPL for every other slot, so a caller that only +// holds and releases the interface survives and one that asks for devices gets a clean refusal instead of a null +// dereference. +// - LEONIDA_INPUT_SCRIPT set: one scripted pad, driven only by the script (gameinput_script.h, the same parser and +// timeline the SDL3 shim's keyboard pad uses). Without it a build without SDL3 has no device at all and the +// title waits at its first "press A" prompt forever. The pad is an Xbox One gamepad that is connected from the +// first GameInputCreate on: device enumeration through RegisterDeviceCallback (blocking, async, and through a +// dispatcher), GetCurrentReading, GetNextReading and GetPreviousReading, and readings whose GetGamepadState and +// GetUiNavigationState follow the script. A reading is taken when the title asks for one, so no thread runs; +// reading callbacks, aggregate devices, rumble and every other device still need SDL3. Controllers and the +// keyboard pad need SDL3 too. #include +#include #include #include #include #include +#include +#include +#include +#include +#include #include +#include +#include "gameinput_abi.h" +#include "gameinput_no_sdl.h" +#include "gameinput_script.h" #include "shims.h" +using namespace gi; +namespace script = rt::gameinput::script; + namespace { +// ---- no script: the identity-only object ------------------------------------------------------------------------ + constexpr size_t kSlots = 64; // comfortably covers the public v0 IGameInput vtable struct GameInputStub { @@ -66,8 +92,616 @@ ULONG __stdcall stub_add_ref(GameInputStub*) { return g_refs.fetch_add(1) + 1; } ULONG __stdcall stub_release(GameInputStub*) { return g_refs.fetch_sub(1) - 1; } +// ---- LEONIDA_INPUT_SCRIPT: the scripted pad --------------------------------------------------------------------- + +constexpr uint32_t kKinds = + GameInputKindControllerAxis | GameInputKindControllerButton | GameInputKindGamepad | GameInputKindUiNavigation; +constexpr uint32_t kConnectedStatus = GameInputDeviceConnected | GameInputDeviceInputEnabled | GameInputDeviceOutputEnabled; +constexpr uint32_t kAxisCount = 6; // LX, LY, RX, RY, LT, RT, as the SDL3 shim reports them +constexpr uint32_t kButtonCount = 15; // SDL's standard gamepad buttons, numbered as the script's Button::sdl +constexpr size_t kHistoryCap = 64; // readings kept for GetNextReading/GetPreviousReading; one per change +constexpr char kPadName[] = "Scripted pad (Leonida)"; + +uint64_t qpc_now_us() { + static const LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }(); + LARGE_INTEGER c; + QueryPerformanceCounter(&c); + return static_cast(c.QuadPart / freq.QuadPart * 1'000'000 + c.QuadPart % freq.QuadPart * 1'000'000 / freq.QuadPart); +} +std::atomic g_clock{&qpc_now_us}; +uint64_t now_us() { return g_clock.load()(); } + +bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; } + +ULONG release_floor(std::atomic& refs) { // objects kept for the process: never freed + ULONG r = refs.load(); + while (r > 1 && !refs.compare_exchange_weak(r, r - 1)) {} + return r > 1 ? r - 1 : 1; +} + +template +void not_served(const char* what) { + static std::atomic warned{false}; + if (!warned.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] gameinput: slot %zu (%s) is not served without SDL3; E_NOTIMPL (logged once)\n", + Slot, what); +} + +class Pad; +Pad& pad(); + +class Reading final : public IGameInputReading { +public: + Reading(const GameInputGamepadState& state, uint64_t seq, uint64_t ts) : state_(state), seq_(seq), ts_(ts) {} + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputReading)) { + AddRef(); + *out = static_cast(this); + return S_OK; + } + *out = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { + const ULONG r = --refs_; + if (r == 0) delete this; + return r; + } + + uint32_t STDMETHODCALLTYPE GetInputKind() override { return kKinds; } + uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; } + uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; } + void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; + bool STDMETHODCALLTYPE GetRawReport(void** report) override { + if (report) *report = nullptr; + return false; + } + uint32_t STDMETHODCALLTYPE GetControllerAxisCount() override { return kAxisCount; } + uint32_t STDMETHODCALLTYPE GetControllerAxisState(uint32_t count, float* out) override { + if (!out) return 0; + // 0..1 with 0.5 at rest for the sticks, as the SDL3 shim reports them. + const float axes[kAxisCount] = {(state_.leftThumbstickX + 1) * 0.5f, (state_.leftThumbstickY + 1) * 0.5f, + (state_.rightThumbstickX + 1) * 0.5f, (state_.rightThumbstickY + 1) * 0.5f, + state_.leftTrigger, state_.rightTrigger}; + const uint32_t n = std::min(count, kAxisCount); + std::memcpy(out, axes, n * sizeof(float)); + return n; + } + uint32_t STDMETHODCALLTYPE GetControllerButtonCount() override { return kButtonCount; } + uint32_t STDMETHODCALLTYPE GetControllerButtonState(uint32_t count, bool* out) override { + if (!out) return 0; + bool buttons[kButtonCount] = {}; + for (const script::Button& b : script::kButtons) buttons[b.sdl] = (state_.buttons & b.bit) != 0; + const uint32_t n = std::min(count, kButtonCount); + std::memcpy(out, buttons, n * sizeof(bool)); + return n; + } + uint32_t STDMETHODCALLTYPE GetControllerSwitchCount() override { return 0; } + uint32_t STDMETHODCALLTYPE GetControllerSwitchState(uint32_t, GameInputSwitchPosition*) override { return 0; } + uint32_t STDMETHODCALLTYPE GetKeyCount() override { return 0; } + uint32_t STDMETHODCALLTYPE GetKeyState(uint32_t, void*) override { return 0; } + bool STDMETHODCALLTYPE GetMouseState(void*) override { return false; } + uint32_t STDMETHODCALLTYPE GetTouchCount() override { return 0; } + uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t, void*) override { return 0; } + bool STDMETHODCALLTYPE GetMotionState(void*) override { return false; } + bool STDMETHODCALLTYPE GetArcadeStickState(void*) override { return false; } + bool STDMETHODCALLTYPE GetFlightStickState(void*) override { return false; } + bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override { + if (!state) return false; + *state = state_; + return true; + } + bool STDMETHODCALLTYPE GetRacingWheelState(void*) override { return false; } + bool STDMETHODCALLTYPE GetUiNavigationState(GameInputUiNavigationState* state) override { + if (!state) return false; + state->buttons = script::ui_navigation(state_); + return true; + } + + const GameInputGamepadState& state() const { return state_; } + uint64_t seq() const { return seq_; } + +private: + std::atomic refs_{1}; + GameInputGamepadState state_; + uint64_t seq_, ts_; +}; + +// The one device. It lives for the process and is connected from the first GameInputCreate on. +class Pad final : public IGameInputDevice { +public: + Pad() { + GameInputDeviceInfo& i = info_; + i.infoSize = sizeof(GameInputDeviceInfo); + i.usage = {0x01, 0x05}; // HID generic desktop / game pad + std::memcpy(i.deviceId.value, "LEONIDA_SCRIPTED_PAD_DEVICE_ID\0\0", sizeof i.deviceId.value); + i.deviceRootId = i.deviceId; + i.deviceFamily = GameInputFamilyXboxOne; // every pad is an Xbox One pad to the title, as in the SDL3 shim + i.supportedInput = kKinds; + i.controllerAxisCount = kAxisCount; + i.controllerButtonCount = kButtonCount; + for (uint32_t a = 0; a < kAxisCount; ++a) { + axis_info_[a].mappedInputKinds = GameInputKindGamepad; + axis_info_[a].isContinuous = true; + axis_info_[a].hasRestValue = true; + axis_info_[a].restValue = a < 4 ? 0.5f : 0.0f; + axis_info_[a].resolution = 65536; + axis_info_[a].legacyHidIndex = axis_info_[a].legacyDInputIndex = static_cast(a); + } + axis_info_[4].label = GameInputLabelXboxLeftTrigger; + axis_info_[5].label = GameInputLabelXboxRightTrigger; + const GameInputLabel labels[kButtonCount] = { + GameInputLabelXboxA, GameInputLabelXboxB, GameInputLabelXboxX, + GameInputLabelXboxY, GameInputLabelXboxView, GameInputLabelXboxGuide, + GameInputLabelXboxMenu, GameInputLabelXboxLeftStickButton, GameInputLabelXboxRightStickButton, + GameInputLabelXboxLeftShoulder, GameInputLabelXboxRightShoulder, GameInputLabelXboxDPadUp, + GameInputLabelXboxDPadDown, GameInputLabelXboxDPadLeft, GameInputLabelXboxDPadRight}; + for (uint32_t b = 0; b < kButtonCount; ++b) { + button_info_[b].mappedInputKinds = GameInputKindGamepad; + button_info_[b].label = labels[b]; + button_info_[b].legacyHidIndex = button_info_[b].legacyDInputIndex = static_cast(b); + } + gamepad_info_ = {GameInputLabelXboxMenu, GameInputLabelXboxView, GameInputLabelXboxA, + GameInputLabelXboxB, GameInputLabelXboxX, GameInputLabelXboxY, + GameInputLabelXboxDPadUp, GameInputLabelXboxDPadDown, GameInputLabelXboxDPadLeft, + GameInputLabelXboxDPadRight, GameInputLabelXboxLeftShoulder, GameInputLabelXboxRightShoulder, + GameInputLabelXboxLeftStickButton, GameInputLabelXboxRightStickButton}; + const GameInputLabel none = GameInputLabelNone; + ui_info_ = {GameInputLabelXboxMenu, GameInputLabelXboxView, GameInputLabelXboxA, + GameInputLabelXboxB, GameInputLabelXboxDPadUp, GameInputLabelXboxDPadDown, + GameInputLabelXboxDPadLeft, GameInputLabelXboxDPadRight, GameInputLabelXboxX, + GameInputLabelXboxY, GameInputLabelXboxLeftStickButton, GameInputLabelXboxRightStickButton, + GameInputLabelXboxLeftTrigger, GameInputLabelXboxRightTrigger, GameInputLabelXboxLeftShoulder, + GameInputLabelXboxRightShoulder, none, none, none, none, GameInputLabelXboxGuide}; + i.controllerAxisInfo = axis_info_; + i.controllerButtonInfo = button_info_; + i.gamepadInfo = &gamepad_info_; + i.uiNavigationInfo = &ui_info_; + constexpr uint32_t name_size = sizeof kPadName - 1; + display_name_ = {name_size, name_size, kPadName}; + i.displayName = &display_name_; + } + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputDevice)) { + AddRef(); + *out = static_cast(this); + return S_OK; + } + *out = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { return release_floor(refs_); } + + const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info_; } + uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return kConnectedStatus; } + void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override { + if (state) *state = {0, 0, 0, 0, GameInputBatteryUnknown}; + } + // No motors: the pad reports none, so every motor index is out of range. + HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t, const void*, void** effect) override { + if (effect) *effect = nullptr; + return E_INVALIDARG; + } + bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t) override { return false; } + void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t, float) override {} + HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t, const void*) override { return E_INVALIDARG; } + void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams*) override {} + void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {} + void STDMETHODCALLTYPE SendInputSynchronizationHint() override {} + void STDMETHODCALLTYPE PowerOff() override {} + HRESULT STDMETHODCALLTYPE CreateRawDeviceReport(uint32_t, int32_t, void** report) override { return no_raw(report); } + HRESULT STDMETHODCALLTYPE GetRawDeviceFeature(uint32_t, void** report) override { return no_raw(report); } + HRESULT STDMETHODCALLTYPE SetRawDeviceFeature(void*) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE SendRawDeviceOutput(void*) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE SendRawDeviceOutputWithResponse(void*, void** response) override { return no_raw(response); } + HRESULT STDMETHODCALLTYPE ExecuteRawDeviceIoControl(uint32_t, size_t, const void*, size_t, void*, size_t* size) override { + if (size) *size = 0; + return E_NOTIMPL; + } + bool STDMETHODCALLTYPE AcquireExclusiveRawDeviceAccess(uint64_t) override { return false; } + void STDMETHODCALLTYPE ReleaseExclusiveRawDeviceAccess() override {} + +private: + static HRESULT no_raw(void** out) { + if (out) *out = nullptr; + return E_NOTIMPL; + } + std::atomic refs_{1}; + GameInputDeviceInfo info_{}; + GameInputControllerAxisInfo axis_info_[kAxisCount]{}; + GameInputControllerButtonInfo button_info_[kButtonCount]{}; + GameInputGamepadInfo gamepad_info_{}; + GameInputUiNavigationInfo ui_info_{}; + GameInputString display_name_{}; +}; + +Pad& pad() { + static Pad* p = new Pad; + return *p; +} + +void Reading::GetDevice(IGameInputDevice** device) { + if (!device) return; + pad().AddRef(); + *device = &pad(); +} + +enum class CbType { Device, Guide, KeyboardLayout }; + +struct Callback { + GameInputCallbackToken token; + CbType type; + void* context; + void* fn; + bool active; +}; + +// A device callback's enumeration report that is delivered later (async enumeration), by a one-shot thread or, when +// the title made a dispatcher, by IGameInputDispatcher::Dispatch on the title's thread. +struct Pending { + GameInputCallbackToken token; + uint64_t timestamp; +}; + +struct State { + std::recursive_mutex mu; // everything below + std::recursive_mutex deliver_mu; // held while callbacks run; UnregisterCallback waits on it + std::atomic delivering_thread{0}; + script::Script script; + uint64_t origin_us = 0; // the script's clock starts at the first GameInputCreate + bool log_presses = true; // LEONIDA_INPUT_LOG + uint32_t logged_held = 0; // what log_scripted saw last + std::deque history; // one reference each, oldest first; the newest is the current reading + uint64_t evicted_seq = 0; // sequence number of the newest reading dropped from history + uint64_t seq = 0; + std::vector callbacks; + std::vector pending; + GameInputCallbackToken next_token = 1; + int dispatchers = 0; + HANDLE wait_event = nullptr; // auto-reset, signalled when a dispatcher has work +}; + +State& g() { + static State* s = new State; // never destroyed: a title thread may still read during exit + return *s; +} + +// Takes a reading when the script's state at `now` differs from the current one. Under g().mu. +void update(uint64_t now) { + State& s = g(); + const double seconds = now > s.origin_us ? (now - s.origin_us) / 1e6 : 0.0; + const script::Held held = script::held_at(s.script, seconds); + GameInputGamepadState state{}; + state.buttons = held.buttons; + state.rightThumbstickY = static_cast(held.stick); + const Reading* last = s.history.empty() ? nullptr : s.history.back(); + if (last && last->state().buttons == state.buttons && last->state().rightThumbstickY == state.rightThumbstickY) + return; + script::log_scripted(held.buttons, &s.logged_held, seconds); + if (s.log_presses && last) + script::log_presses(state.buttons & ~last->state().buttons, last->state().rightThumbstickY, + state.rightThumbstickY, seconds, kPadName); + s.history.push_back(new Reading(state, ++s.seq, now)); + while (s.history.size() > kHistoryCap) { + s.evicted_seq = s.history.front()->seq(); + s.history.front()->Release(); + s.history.pop_front(); + } +} + +void call_device(const Callback& c, uint64_t timestamp) { + reinterpret_cast(c.fn)(c.token, c.context, &pad(), timestamp, kConnectedStatus, + GameInputDeviceNoStatus); +} + +// Runs the pending enumeration reports on the calling thread, without holding the state lock. +void deliver() { + State& s = g(); + std::lock_guard dl(s.deliver_mu); + std::vector batch; + { + std::lock_guard lock(s.mu); + batch.swap(s.pending); + } + s.delivering_thread = GetCurrentThreadId(); + for (const Pending& p : batch) { + Callback target{}; + { + std::lock_guard lock(s.mu); + for (const Callback& c : s.callbacks) + if (c.token == p.token && c.active) target = c; + } + if (target.fn) call_device(target, p.timestamp); + } + s.delivering_thread = 0; +} + +// Async enumeration: the report arrives after RegisterDeviceCallback returns, as GameInput delivers it from a thread +// of its own; with a dispatcher, the title's Dispatch delivers it instead. +void schedule_delivery() { + State& s = g(); + { + std::lock_guard lock(s.mu); + if (s.dispatchers > 0) { + SetEvent(s.wait_event); + return; + } + } + std::thread([] { + { + std::lock_guard lock(g().mu); + if (g().dispatchers > 0) { // a dispatcher appeared meanwhile: it owns the delivery + SetEvent(g().wait_event); + return; + } + } + deliver(); + }).detach(); +} + +class Dispatcher final : public IGameInputDispatcher { +public: + Dispatcher() { + std::lock_guard lock(g().mu); + ++g().dispatchers; + if (!g().pending.empty()) SetEvent(g().wait_event); + } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputDispatcher)) { + AddRef(); + *out = static_cast(this); + return S_OK; + } + *out = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { + const ULONG r = --refs_; + if (r == 0) { + { + std::lock_guard lock(g().mu); + --g().dispatchers; + } + delete this; + } + return r; + } + // The pending reports are few (one per async enumeration), so all of them run whatever the quota. + bool STDMETHODCALLTYPE Dispatch(uint64_t) override { + deliver(); + std::lock_guard lock(g().mu); + return !g().pending.empty(); + } + HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override { + if (!handle) return E_POINTER; + *handle = nullptr; + if (!DuplicateHandle(GetCurrentProcess(), g().wait_event, GetCurrentProcess(), handle, 0, FALSE, + DUPLICATE_SAME_ACCESS)) + return HRESULT_FROM_WIN32(GetLastError()); + return S_OK; + } + +private: + std::atomic refs_{1}; +}; + +// GetNextReading (forward) and GetPreviousReading: the reading right after or right before the reference. A step +// across a reading dropped from the history is REFERENCE_READING_TOO_OLD, as in the SDL3 shim. +HRESULT find_reading(IGameInputReading* ref, uint32_t kind, IGameInputReading** out, bool forward) { + if (!out) return E_POINTER; + *out = nullptr; + if (!ref) return E_INVALIDARG; + if (kind != GameInputKindUnknown && !(kind & kKinds)) return GAMEINPUT_E_READING_NOT_FOUND; + State& s = g(); + std::lock_guard lock(s.mu); + update(now_us()); + const uint64_t r = static_cast(ref)->seq(); + if (forward ? s.evicted_seq > r : s.evicted_seq >= r) return GAMEINPUT_E_REFERENCE_READING_TOO_OLD; + Reading* best = nullptr; + for (Reading* c : s.history) { + if (forward && c->seq() > r) { + best = c; + break; + } + if (!forward && c->seq() < r) best = c; + } + if (!best) return GAMEINPUT_E_READING_NOT_FOUND; + best->AddRef(); + *out = best; + return S_OK; +} + +bool is_pad(IGameInputDevice* device) { return device == static_cast(&pad()); } + +class ScriptedInput final : public IGameInput { +public: + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInput)) { + AddRef(); + *out = static_cast(this); + return S_OK; + } + *out = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { return release_floor(refs_); } // a process-wide singleton + + uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); } + + HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (kind != GameInputKindUnknown && !(kind & kKinds)) return GAMEINPUT_E_READING_NOT_FOUND; + if (device && !is_pad(device)) return GAMEINPUT_E_DEVICE_NOT_FOUND; + State& s = g(); + std::lock_guard lock(s.mu); + update(now_us()); + Reading* r = s.history.back(); + r->AddRef(); + *out = r; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, + IGameInputReading** out) override { + if (device && !is_pad(device)) return out ? (*out = nullptr, GAMEINPUT_E_DEVICE_NOT_FOUND) : E_POINTER; + return find_reading(ref, kind, out, true); + } + HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, + IGameInputReading** out) override { + if (device && !is_pad(device)) return out ? (*out = nullptr, GAMEINPUT_E_DEVICE_NOT_FOUND) : E_POINTER; + return find_reading(ref, kind, out, false); + } + // GameInput v0's own answer (see the SDL3 shim). + HRESULT STDMETHODCALLTYPE GetTemporalReading(uint64_t, IGameInputDevice*, IGameInputReading** out) override { + if (!out) return E_POINTER; + *out = nullptr; + return E_NOTIMPL; + } + // Readings are taken when the title asks for one, so there is nothing to call back with. + HRESULT STDMETHODCALLTYPE RegisterReadingCallback(IGameInputDevice*, uint32_t, float, void*, GameInputReadingCallback, + GameInputCallbackToken* token) override { + if (token) *token = kInvalidCallbackToken; + not_served<8>("RegisterReadingCallback"); + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE RegisterDeviceCallback(IGameInputDevice* device, uint32_t kind, uint32_t status_filter, + GameInputEnumerationKind enumeration, void* context, + GameInputDeviceCallback fn, GameInputCallbackToken* token) override { + if (token) *token = kInvalidCallbackToken; + if (!fn) return E_INVALIDARG; + State& s = g(); + Callback c{0, CbType::Device, context, reinterpret_cast(fn), true}; + // The pad is connected already, so only an enumeration reports it: there is no later connection event. + const bool report = enumeration != GameInputNoEnumeration && (!device || is_pad(device)) && + (kind == GameInputKindUnknown || (kind & kKinds)) && (kConnectedStatus & status_filter); + bool later = false; + { + std::lock_guard lock(s.mu); + c.token = s.next_token++; + s.callbacks.push_back(c); + if (report && enumeration != GameInputBlockingEnumeration) { + s.pending.push_back({c.token, now_us()}); + later = true; + } + } + if (token) *token = c.token; + // Blocking enumeration: the pad is reported before this returns, on the caller's thread. + if (report && enumeration == GameInputBlockingEnumeration) call_device(c, now_us()); + if (later) schedule_delivery(); + return S_OK; + } + // The script has no guide button and the pad no keyboard layout: these are accepted and never run. + HRESULT STDMETHODCALLTYPE RegisterGuideButtonCallback(IGameInputDevice*, void* context, GameInputGuideButtonCallback fn, + GameInputCallbackToken* token) override { + return add(CbType::Guide, context, reinterpret_cast(fn), token); + } + HRESULT STDMETHODCALLTYPE RegisterKeyboardLayoutCallback(IGameInputDevice*, void* context, + GameInputKeyboardLayoutCallback fn, + GameInputCallbackToken* token) override { + return add(CbType::KeyboardLayout, context, reinterpret_cast(fn), token); + } + void STDMETHODCALLTYPE StopCallback(GameInputCallbackToken token) override { + std::lock_guard lock(g().mu); + for (Callback& c : g().callbacks) + if (c.token == token) c.active = false; + } + // Removes the callback and, unless called from inside a callback, waits for one that is running to return. + bool STDMETHODCALLTYPE UnregisterCallback(GameInputCallbackToken token, uint64_t) override { + State& s = g(); + bool found = false; + { + std::lock_guard lock(s.mu); + auto it = std::find_if(s.callbacks.begin(), s.callbacks.end(), + [token](const Callback& c) { return c.token == token; }); + if (it != s.callbacks.end()) { + s.callbacks.erase(it); + found = true; + } + } + if (found && s.delivering_thread != GetCurrentThreadId()) std::lock_guard wait(s.deliver_mu); + return found; + } + HRESULT STDMETHODCALLTYPE CreateDispatcher(IGameInputDispatcher** out) override { + if (!out) return E_POINTER; + *out = new Dispatcher; + return S_OK; + } + HRESULT STDMETHODCALLTYPE CreateAggregateDevice(uint32_t, IGameInputDevice** out) override { + if (out) *out = nullptr; + not_served<15>("CreateAggregateDevice"); + return E_NOTIMPL; + } + HRESULT STDMETHODCALLTYPE FindDeviceFromId(const AppLocalDeviceId* id, IGameInputDevice** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (!id) return E_INVALIDARG; + if (std::memcmp(id, &pad().GetDeviceInfo()->deviceId, sizeof *id) != 0) return GAMEINPUT_E_DEVICE_NOT_FOUND; + pad().AddRef(); + *out = &pad(); + return S_OK; + } + HRESULT STDMETHODCALLTYPE FindDeviceFromObject(IUnknown*, IGameInputDevice** out) override { return not_found(out); } + HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformHandle(HANDLE, IGameInputDevice** out) override { return not_found(out); } + HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformString(LPCWSTR, IGameInputDevice** out) override { return not_found(out); } + HRESULT STDMETHODCALLTYPE EnableOemDeviceSupport(uint16_t, uint16_t, uint8_t, uint8_t) override { return S_OK; } + void STDMETHODCALLTYPE SetFocusPolicy(uint32_t) override {} + +private: + static HRESULT not_found(IGameInputDevice** out) { + if (out) *out = nullptr; + return GAMEINPUT_E_DEVICE_NOT_FOUND; + } + static HRESULT add(CbType type, void* context, void* fn, GameInputCallbackToken* token) { + if (token) *token = kInvalidCallbackToken; + if (!fn) return E_INVALIDARG; + std::lock_guard lock(g().mu); + const GameInputCallbackToken t = g().next_token++; + g().callbacks.push_back({t, type, context, fn, true}); + if (token) *token = t; + return S_OK; + } + std::atomic refs_{1}; +}; + +// The scripted object when LEONIDA_INPUT_SCRIPT is set, read once on the first call; null otherwise. +ScriptedInput* scripted() { + static ScriptedInput* const input = []() -> ScriptedInput* { + const std::string text = script::env_lower("LEONIDA_INPUT_SCRIPT"); + if (text.empty()) return nullptr; + State& s = g(); + std::lock_guard lock(s.mu); + s.script = script::parse(text); + s.log_presses = script::env_lower("LEONIDA_INPUT_LOG") != "0"; + s.wait_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + s.origin_us = now_us(); + update(s.origin_us); // the first reading: nothing held unless the script presses at 0 s + std::fprintf(stderr, + "[rt] gameinput: served without SDL3: one scripted pad for LEONIDA_INPUT_SCRIPT (%zu scripted " + "press(es), %zu rejected); controllers and the keyboard pad need SDL3\n", + s.script.presses.size(), s.script.rejected); + return new ScriptedInput; + }(); + return input; +} + HRESULT WINAPI GameInputCreate(void** out) { if (!out) return E_POINTER; + if (ScriptedInput* input = scripted()) { + input->AddRef(); + *out = static_cast(input); + return S_OK; + } g_refs.fetch_add(1); *out = &g_gameinput; static std::atomic warned{false}; @@ -78,6 +712,10 @@ HRESULT WINAPI GameInputCreate(void** out) { } // namespace +namespace rt::gameinput_no_sdl { +void set_clock(ClockFn now) { g_clock.store(now ? now : &qpc_now_us); } +} // namespace rt::gameinput_no_sdl + SHIM_TABLE(gameinput_no_sdl, {"gameinput.dll", "GameInputCreate", reinterpret_cast(&GameInputCreate)}, // The retail executable imports this one by ordinal, so the registry key is "#1"; without the alias the loader diff --git a/runtime/shims/gameinput_no_sdl.h b/runtime/shims/gameinput_no_sdl.h new file mode 100644 index 0000000000..02eef85c66 --- /dev/null +++ b/runtime/shims/gameinput_no_sdl.h @@ -0,0 +1,12 @@ +// gameinput.dll without SDL3 (gameinput_no_sdl.cpp): the test seam of its scripted pad. +#pragma once +#include + +namespace rt::gameinput_no_sdl { + +// The clock the scripted pad reads, in microseconds (GetCurrentTimestamp's scale). Set it before the first +// GameInputCreate, which starts the script's clock; nullptr restores the performance counter. +using ClockFn = uint64_t (*)(); +void set_clock(ClockFn now_us); + +} // namespace rt::gameinput_no_sdl diff --git a/runtime/shims/gameinput_script.h b/runtime/shims/gameinput_script.h new file mode 100644 index 0000000000..7595067500 --- /dev/null +++ b/runtime/shims/gameinput_script.h @@ -0,0 +1,180 @@ +// LEONIDA_INPUT_SCRIPT, shared by both GameInput shims: the SDL3 one (gameinput.cpp, where the script drives the +// keyboard pad) and the one built without SDL3 (gameinput_no_sdl.cpp, where it drives a scripted pad of its own). +// The parser, the press timeline, the button names and the press log lines live here, once; nothing in this file +// needs SDL. docs/gameinput.md, "Scripted input", has the format. +// +// LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" +// +// Each entry is button@seconds, the seconds counted from the shim's first update. A press is held for kHoldSeconds, +// then released. Buttons: a b x y start back lb rb up down left right; rsup and rsdown throw the right stick fully up +// or down for the same time (they replay the stick throws the press log writes). Spaces around an entry are allowed; +// empty entries, unknown buttons and invalid times (negative, non-finite, trailing text) are counted as rejected. +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gameinput_abi.h" + +namespace rt::gameinput::script { + +constexpr double kHoldSeconds = 0.3; + +// One scriptable button: its name in the script and the press log, its GameInput gamepad bit, and its SDL3 +// SDL_GamepadButton number, which the "scripted press of button " line has always carried (tools/stage_timeline.py +// reads it). gameinput.cpp checks the numbers against SDL's enum. +struct Button { + const char* name; + uint32_t bit; + int sdl; +}; +inline constexpr Button kButtons[] = { + {"a", gi::GameInputGamepadA, 0}, {"b", gi::GameInputGamepadB, 1}, + {"x", gi::GameInputGamepadX, 2}, {"y", gi::GameInputGamepadY, 3}, + {"start", gi::GameInputGamepadMenu, 6}, {"back", gi::GameInputGamepadView, 4}, + {"lb", gi::GameInputGamepadLeftShoulder, 9}, {"rb", gi::GameInputGamepadRightShoulder, 10}, + {"up", gi::GameInputGamepadDPadUp, 11}, {"down", gi::GameInputGamepadDPadDown, 12}, + {"left", gi::GameInputGamepadDPadLeft, 13}, {"right", gi::GameInputGamepadDPadRight, 14}, +}; + +struct Press { + uint32_t button = 0; // a GameInput gamepad bit, or 0 for a stick throw + int stick = 0; // +1 rsup, -1 rsdown (GameInput's +Y is up) + double at = 0; // seconds +}; + +struct Script { + std::vector presses; + size_t rejected = 0; + uint32_t named = 0; // every button the script presses at least once + bool empty() const { return presses.empty(); } +}; + +// The script in `text`, matched without regard to case. +inline Script parse(std::string text) { + for (auto& c : text) c = static_cast(std::tolower(static_cast(c))); + Script out; + if (text.empty()) return out; + constexpr char whitespace[] = " \t\r\n\f\v"; + size_t items = 0; + for (size_t at = 0, end; at <= text.size(); at = end + 1) { + ++items; + end = std::min(text.find(',', at), text.size()); + const std::string item = text.substr(at, end - at); + const size_t first = item.find_first_not_of(whitespace); + const size_t sep = item.find('@'); + if (sep == std::string::npos || first >= sep) continue; + const char* time = item.c_str() + sep + 1; + char* tail; + const double seconds = std::strtod(time, &tail); + if (tail == time || !std::isfinite(seconds) || seconds < 0 || + item.find_first_not_of(whitespace, static_cast(tail - item.c_str())) != std::string::npos) + continue; + const auto is = [&](const char* name) { return item.compare(first, sep - first, name) == 0; }; + if (is("rsup") || is("rsdown")) { + out.presses.push_back({0, is("rsup") ? 1 : -1, seconds}); + continue; + } + for (const Button& b : kButtons) { + if (is(b.name)) { + out.presses.push_back({b.bit, 0, seconds}); + out.named |= b.bit; + break; + } + } + } + out.rejected = items - out.presses.size(); + return out; +} + +// What the script holds `seconds` after its clock started: the buttons (GameInput bits) and the right stick throw. +// One decision per button: a later entry for the same button must not release what an earlier entry holds (it did: +// with several entries only the last one ever reached the title). +struct Held { + uint32_t buttons = 0; + int stick = 0; // +1 up, -1 down, 0 at rest +}; +inline Held held_at(const Script& script, double seconds) { + Held h; + for (const Press& p : script.presses) { + if (seconds < p.at || seconds >= p.at + kHoldSeconds) continue; + if (p.stick) h.stick = p.stick; + else h.buttons |= p.button; + } + return h; +} + +inline const Button* button_of(uint32_t bit) { + for (const Button& b : kButtons) + if (b.bit == bit) return &b; + return nullptr; +} + +// "[rt] gameinput: scripted press of button at s" for every button the script starts holding: `was` is the +// previous call's held set and is updated. +inline void log_scripted(uint32_t held, uint32_t* was, double seconds) { + for (const Button& b : kButtons) + if ((held & b.bit) && !(*was & b.bit)) + std::fprintf(stderr, "[rt] gameinput: scripted press of button %d at %.1f s\n", b.sdl, seconds); + *was = held; +} + +// The press log (LEONIDA_INPUT_LOG, on unless 0): every newly pressed button and every new right-stick throw in the +// script's own form, name@seconds, so a session played by hand can be replayed by joining the items with commas. +inline int stick_throw(float y) { return y > 0.6f ? 1 : y < -0.6f ? -1 : 0; } +inline void log_presses(uint32_t pressed, float right_y_was, float right_y, double seconds, const char* device) { + for (const Button& b : kButtons) + if (pressed & b.bit) std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", b.name, seconds, device); + const int was = stick_throw(right_y_was), is = stick_throw(right_y); + if (is != was && is != 0) + std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", is > 0 ? "rsup" : "rsdown", seconds, device); +} + +// UI navigation derived from a gamepad state, the same for every pad (VERIFY against the console's own mapping). +inline uint32_t ui_navigation(const gi::GameInputGamepadState& g) { + using namespace gi; + const uint32_t b = g.buttons; + const float t = 0.5f; + uint32_t u = 0; + if (b & GameInputGamepadMenu) u |= GameInputUiNavigationMenu; + if (b & GameInputGamepadView) u |= GameInputUiNavigationView; + if (b & GameInputGamepadA) u |= GameInputUiNavigationAccept; + if (b & GameInputGamepadB) u |= GameInputUiNavigationCancel; + if (b & GameInputGamepadX) u |= GameInputUiNavigationContext1; + if (b & GameInputGamepadY) u |= GameInputUiNavigationContext2; + if (b & GameInputGamepadLeftThumbstick) u |= GameInputUiNavigationContext3; + if (b & GameInputGamepadRightThumbstick) u |= GameInputUiNavigationContext4; + if ((b & GameInputGamepadDPadUp) || g.leftThumbstickY > t) u |= GameInputUiNavigationUp; + if ((b & GameInputGamepadDPadDown) || g.leftThumbstickY < -t) u |= GameInputUiNavigationDown; + if ((b & GameInputGamepadDPadLeft) || g.leftThumbstickX < -t) u |= GameInputUiNavigationLeft; + if ((b & GameInputGamepadDPadRight) || g.leftThumbstickX > t) u |= GameInputUiNavigationRight; + if (b & GameInputGamepadLeftShoulder) u |= GameInputUiNavigationPageLeft; + if (b & GameInputGamepadRightShoulder) u |= GameInputUiNavigationPageRight; + if (g.leftTrigger > t) u |= GameInputUiNavigationPageUp; + if (g.rightTrigger > t) u |= GameInputUiNavigationPageDown; + if (g.rightThumbstickY > t) u |= GameInputUiNavigationScrollUp; + if (g.rightThumbstickY < -t) u |= GameInputUiNavigationScrollDown; + if (g.rightThumbstickX < -t) u |= GameInputUiNavigationScrollLeft; + if (g.rightThumbstickX > t) u |= GameInputUiNavigationScrollRight; + return u; +} + +// An environment variable in lower case, of any length (a script is easily longer than a fixed buffer, and a value +// that did not fit used to read as unset). Empty when unset. +inline std::string env_lower(const char* name) { + const DWORD need = GetEnvironmentVariableA(name, nullptr, 0); // with the terminator + if (need == 0) return {}; + std::string s(need, '\0'); + const DWORD n = GetEnvironmentVariableA(name, s.data(), need); + if (n == 0 || n >= need) return {}; + s.resize(n); + for (auto& c : s) c = static_cast(std::tolower(static_cast(c))); + return s; +} + +} // namespace rt::gameinput::script diff --git a/runtime/test/gameinput_no_sdl_test.cpp b/runtime/test/gameinput_no_sdl_test.cpp index c8443f3b36..a131dc7c99 100644 --- a/runtime/test/gameinput_no_sdl_test.cpp +++ b/runtime/test/gameinput_no_sdl_test.cpp @@ -1,28 +1,34 @@ -// gameinput.dll!#1 without SDL3: the retail executable imports GameInputCreate by ordinal, and a build without SDL3 -// still has to hand back an interface instead of letting the loader fall through to the host's gameinput.dll, which -// answers with a null pointer that the title dereferences. +// gameinput.dll without SDL3 (shims/gameinput_no_sdl.cpp). No controller, no game data. +// +// gameinput_no_sdl_test LEONIDA_INPUT_SCRIPT unset: the identity-only object. The retail executable +// imports GameInputCreate by ordinal, and a build without SDL3 still has to +// hand back an interface instead of letting the loader fall through to the +// host's gameinput.dll, which answers with a null pointer the title +// dereferences. +// gameinput_no_sdl_test --input-script LEONIDA_INPUT_SCRIPT set: the scripted pad, found through device callbacks +// and read at chosen times of a fake clock. #include #include #include +#include +#include "gameinput_abi.h" +#include "gameinput_no_sdl.h" #include "shims.h" +using namespace gi; + namespace { int g_failed = 0; void check(bool ok, const char* what) { std::printf("%s %s\n", ok ? "ok " : "FAIL ", what); if (!ok) ++g_failed; } -} // namespace -int main() { - auto create = reinterpret_cast(rt::shims::find("gameinput.dll", "#1")); - auto named = reinterpret_cast(rt::shims::find("gameinput.dll", "GameInputCreate")); - check(create != nullptr, "the ordinal import gameinput.dll!#1 is served"); - check(named != nullptr, "the name GameInputCreate is served"); - if (!create) return 1; +using CreateFn = HRESULT(WINAPI*)(void**); +int identity_only(CreateFn create) { void* object = nullptr; check(create(&object) == S_OK, "GameInputCreate returns S_OK"); check(object != nullptr, "GameInputCreate hands back a non-null interface"); @@ -41,6 +47,220 @@ int main() { check(devices == reinterpret_cast(0x1), "an unserved slot writes nothing to its out-parameter"); check(create(nullptr) == E_POINTER, "a null out parameter is E_POINTER"); + return 0; +} + +// ---- the scripted pad ---- + +uint64_t g_now_us = 7'000'000; // the fake clock; the script's clock starts at GameInputCreate +uint64_t fake_clock() { return g_now_us; } +void at(double seconds) { g_now_us = 7'000'000 + static_cast(seconds * 1e6 + 0.5); } + +struct Seen { + int calls = 0; + IGameInputDevice* device = nullptr; + uint32_t current = 0, previous = 0xFFFFFFFF; + DWORD thread = 0; + HANDLE done = nullptr; +}; +void CALLBACK on_device(GameInputCallbackToken, void* context, IGameInputDevice* device, uint64_t, uint32_t current, + uint32_t previous) { + auto* seen = static_cast(context); + ++seen->calls; + seen->device = device; + seen->current = current; + seen->previous = previous; + seen->thread = GetCurrentThreadId(); + if (seen->done) SetEvent(seen->done); +} + +struct Pad { + uint32_t buttons = 0xFFFFFFFF; + float right_y = -2; + uint32_t ui = 0xFFFFFFFF; + uint64_t seq = 0; + bool a_button = false; +}; +Pad read_at(IGameInput* input, IGameInputDevice* device, double seconds) { + at(seconds); + Pad p; + IGameInputReading* r = nullptr; + if (input->GetCurrentReading(GameInputKindGamepad, device, &r) != S_OK || !r) return p; + GameInputGamepadState s{}; + if (r->GetGamepadState(&s)) p.buttons = s.buttons, p.right_y = s.rightThumbstickY; + GameInputUiNavigationState u{}; + if (r->GetUiNavigationState(&u)) p.ui = u.buttons; + p.seq = r->GetSequenceNumber(GameInputKindGamepad); + bool buttons[15] = {}; + if (r->GetControllerButtonState(15, buttons) == 15) p.a_button = buttons[0]; + r->Release(); + return p; +} + +int scripted_pad(CreateFn create) { + // Four presses (two overlapping A presses, Menu, a right-stick throw) and three rejected entries. + SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT", "a@1, START@2.5 ,a@1.2,rsup@4,bogus@1,a@-1,"); + rt::gameinput_no_sdl::set_clock(fake_clock); + at(0); + + IGameInput* input = nullptr; + check(create(reinterpret_cast(&input)) == S_OK && input, "script: GameInputCreate returns an instance"); + if (!input) return 1; + IUnknown* unk = nullptr; + check(input->QueryInterface(IID_IGameInput, reinterpret_cast(&unk)) == S_OK && unk == input, + "script: QueryInterface(IID_IGameInput) is the same object"); + if (unk) unk->Release(); + check(input->GetCurrentTimestamp() == g_now_us, "script: GetCurrentTimestamp reads the shim's clock"); + + // Device callbacks: a blocking enumeration reports the pad before it returns, on this thread. + Seen blocking; + GameInputCallbackToken token = 0; + check(input->RegisterDeviceCallback(nullptr, GameInputKindGamepad, GameInputDeviceConnected, + GameInputBlockingEnumeration, &blocking, on_device, &token) == S_OK && + token != kInvalidCallbackToken, + "script: RegisterDeviceCallback (blocking) is served"); + check(blocking.calls == 1 && blocking.device && blocking.thread == GetCurrentThreadId(), + "script: blocking enumeration reports one device on the caller's thread"); + check((blocking.current & GameInputDeviceConnected) && blocking.previous == GameInputDeviceNoStatus, + "script: the device is reported connected, from no status"); + IGameInputDevice* device = blocking.device; + if (!device) return 1; + const GameInputDeviceInfo* info = device->GetDeviceInfo(); + check(info && info->deviceFamily == GameInputFamilyXboxOne && (info->supportedInput & GameInputKindGamepad), + "script: the device is an Xbox One gamepad"); + check(info && info->gamepadInfo && info->gamepadInfo->aButtonLabel == GameInputLabelXboxA, + "script: the A button carries the Xbox A label"); + check(info && info->displayName && info->displayName->sizeInBytes > 0, "script: the device has a display name"); + check(device->GetDeviceStatus() & GameInputDeviceConnected, "script: GetDeviceStatus says connected"); + IGameInputDevice* found = nullptr; + check(info && input->FindDeviceFromId(&info->deviceId, &found) == S_OK && found == device, + "script: FindDeviceFromId finds the pad"); + if (found) found->Release(); + check(input->UnregisterCallback(token, 0), "script: the blocking callback unregisters"); + + // No enumeration, or a status filter the pad does not match: nothing is reported. + Seen quiet; + check(input->RegisterDeviceCallback(nullptr, GameInputKindGamepad, GameInputDeviceConnected, GameInputNoEnumeration, + &quiet, on_device, &token) == S_OK, + "script: RegisterDeviceCallback without enumeration is served"); + input->UnregisterCallback(token, 0); + check(input->RegisterDeviceCallback(nullptr, GameInputKindGamepad, GameInputDeviceWireless, + GameInputBlockingEnumeration, &quiet, on_device, &token) == S_OK, + "script: RegisterDeviceCallback with another status filter is served"); + input->UnregisterCallback(token, 0); + check(input->RegisterDeviceCallback(nullptr, GameInputKindKeyboard, GameInputDeviceAnyStatus, + GameInputBlockingEnumeration, &quiet, on_device, &token) == S_OK, + "script: RegisterDeviceCallback for keyboards is served"); + input->UnregisterCallback(token, 0); + check(quiet.calls == 0, "script: no report without enumeration, for another status or another kind"); + + // Async enumeration: reported after the call, from another thread. + Seen async; + async.done = CreateEventW(nullptr, TRUE, FALSE, nullptr); + check(input->RegisterDeviceCallback(nullptr, GameInputKindUnknown, GameInputDeviceAnyStatus, + GameInputAsyncEnumeration, &async, on_device, &token) == S_OK, + "script: RegisterDeviceCallback (async) is served"); + check(WaitForSingleObject(async.done, 5000) == WAIT_OBJECT_0 && async.calls == 1 && async.device == device, + "script: async enumeration reports the pad"); + check(async.thread != GetCurrentThreadId(), "script: async enumeration reports it from another thread"); + input->UnregisterCallback(token, 0); + + // With a dispatcher, the title's Dispatch delivers the report on its own thread. + IGameInputDispatcher* dispatcher = nullptr; + check(input->CreateDispatcher(&dispatcher) == S_OK && dispatcher, "script: CreateDispatcher is served"); + if (dispatcher) { + HANDLE wait = nullptr; + check(dispatcher->OpenWaitHandle(&wait) == S_OK && wait, "script: the dispatcher has a wait handle"); + Seen dispatched; + check(input->RegisterDeviceCallback(nullptr, GameInputKindGamepad, GameInputDeviceConnected, + GameInputAsyncEnumeration, &dispatched, on_device, &token) == S_OK, + "script: RegisterDeviceCallback (async, with a dispatcher) is served"); + check(wait && WaitForSingleObject(wait, 5000) == WAIT_OBJECT_0, "script: the wait handle is signalled"); + check(dispatched.calls == 0, "script: nothing is delivered before Dispatch"); + check(!dispatcher->Dispatch(0) && dispatched.calls == 1 && dispatched.thread == GetCurrentThreadId(), + "script: Dispatch delivers the report on the caller's thread"); + input->UnregisterCallback(token, 0); + if (wait) CloseHandle(wait); + dispatcher->Release(); + } + + // Readings follow the script's timeline: each press is held for 0.3 s, then released. + const Pad start = read_at(input, nullptr, 0.0); + check(start.buttons == 0 && start.right_y == 0, "script: nothing is held at 0 s"); + const Pad idle = read_at(input, device, 0.9); + check(idle.buttons == 0 && idle.seq == start.seq, "script: no new reading while nothing changes"); + const Pad a = read_at(input, device, 1.0); + check(a.buttons == GameInputGamepadA && a.a_button && a.seq > idle.seq, "script: A is held at 1.0 s"); + check(a.ui == GameInputUiNavigationAccept, "script: A reads as UI Accept"); + check(read_at(input, device, 1.25).buttons == GameInputGamepadA, "script: overlapping A presses hold A at 1.25 s"); + check(read_at(input, device, 1.45).buttons == GameInputGamepadA, + "script: a later press of the same button is not cut by the earlier one's release"); + const Pad released = read_at(input, device, 1.55); + check(released.buttons == 0 && !released.a_button, "script: A is released after its last 0.3 s hold"); + const Pad menu = read_at(input, device, 2.6); + check(menu.buttons == GameInputGamepadMenu && menu.ui == GameInputUiNavigationMenu, + "script: START (any case) holds Menu at 2.6 s"); + check(read_at(input, device, 2.85).buttons == 0, "script: Menu is released at 2.85 s"); + const Pad up = read_at(input, device, 4.1); + check(up.buttons == 0 && up.right_y == 1.0f && up.ui == GameInputUiNavigationScrollUp, + "script: rsup throws the right stick up at 4.1 s"); + check(read_at(input, device, 4.5).right_y == 0, "script: the stick is back at rest at 4.5 s"); + check(read_at(input, device, 60).buttons == 0, "script: nothing is held after the script ends"); + + // The history: the reading before the current one is the stick throw, and the one after that throw is the rest. + IGameInputReading* now = nullptr; + IGameInputReading* before = nullptr; + IGameInputReading* after = nullptr; + check(input->GetCurrentReading(GameInputKindUnknown, nullptr, &now) == S_OK && now, "script: a current reading"); + if (now) { + GameInputGamepadState s{}; + check(input->GetPreviousReading(now, GameInputKindGamepad, device, &before) == S_OK && before && + before->GetGamepadState(&s) && s.rightThumbstickY == 1.0f, + "script: GetPreviousReading steps back to the stick throw"); + if (before) { + check(input->GetNextReading(before, GameInputKindGamepad, nullptr, &after) == S_OK && after == now, + "script: GetNextReading steps forward to the current reading"); + before->Release(); + } + if (after) after->Release(); + IGameInputReading* none = nullptr; + check(input->GetNextReading(now, GameInputKindUnknown, nullptr, &none) == GAMEINPUT_E_READING_NOT_FOUND && + !none, + "script: nothing after the current reading"); + IGameInputDevice* of = nullptr; + now->GetDevice(&of); + check(of == device, "script: a reading belongs to the pad"); + if (of) of->Release(); + now->Release(); + } + + IGameInputReading* motion = nullptr; + check(input->GetCurrentReading(GameInputKindMotion, nullptr, &motion) == GAMEINPUT_E_READING_NOT_FOUND && !motion, + "script: the pad has no motion readings"); + GameInputCallbackToken reading_token = 1; + check(input->RegisterReadingCallback(nullptr, GameInputKindGamepad, 0, nullptr, nullptr, &reading_token) == + E_NOTIMPL && + reading_token == kInvalidCallbackToken, + "script: reading callbacks still need SDL3"); + void* second = nullptr; + check(create(&second) == S_OK && second == input, "script: a second GameInputCreate returns the same instance"); + if (second) static_cast(second)->Release(); + input->Release(); + return 0; +} +} // namespace + +int main(int argc, char** argv) { + auto create = reinterpret_cast(rt::shims::find("gameinput.dll", "#1")); + auto named = reinterpret_cast(rt::shims::find("gameinput.dll", "GameInputCreate")); + check(create != nullptr, "the ordinal import gameinput.dll!#1 is served"); + check(named != nullptr, "the name GameInputCreate is served"); + if (!create) return 1; + + const bool with_script = argc == 2 && std::strcmp(argv[1], "--input-script") == 0; + SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT", nullptr); + SetEnvironmentVariableA("LEONIDA_INPUT_LOG", nullptr); + const int early = with_script ? scripted_pad(create) : identity_only(create); std::printf("%d failure(s)\n", g_failed); - return g_failed ? 1 : 0; + return early || g_failed ? 1 : 0; }