# Controller input: the GameInput shim on SDL3 The Xbox build reads controllers through Microsoft's GameInput API. `runtime/shims/gameinput.cpp` answers `GameInputCreate` with its own implementation of that API, backed by [SDL3](https://libsdl.org) gamepads, so every controller SDL supports works the way an Xbox pad would: DualSense, DualShock 4, Switch Pro, Xbox pads, and the rest of SDL's controller database. On a DualSense the impulse-trigger rumble becomes adaptive-trigger effects, and the lightbar colour can be set. Without the shim the loader would bind `GameInputCreate` to the host's `GameInput.dll` if there is one ([#279](https://github.com/ItsNotRexed/Leonida/pull/279)). That works for Xbox pads only, and gives no DualSense features. That path is tested without the game: `gameinput_host_test` (ctest `gameinput_host`) maps a synthetic DLL built against the SDK's `gameinput.lib` and checks that its `GameInput.dll` import binds to the host's copy, that `GameInputCreate` and `GetCurrentTimestamp` work from mapped code, and that `GetCurrentReading` answers; with a pad attached, `GetGamepadState` must succeed on the reading. It passes on Windows 11 build 26300 (GameInput 0.2309) without a pad attached. The test skips only where Windows cannot load `GameInput.dll`; with the DLL present, an import that binds to nothing fails it. The game executable is not available yet, so whether it imports GameInput this way, and under which module, is unverified (see [VERIFY](#verify)). ### Diagnosing a native host failure If `gameinput_host` binds to the host DLL but `GameInputCreate` fails, call `GameInputCreate` directly from the absolute `%WINDIR%\System32\GameInput.dll` path, outside the mapped path. A matching failure shows that the call can fail without Leonida's loader, but does not identify the underlying cause or rule out every concurrent loader issue. A failed call alone is not evidence that the GameInput service is absent or stopped. Once Windows loads the DLL, keep the host test failure visible; do not skip it. ## Building The shim is optional, and the build downloads nothing unless asked. SDL3 is zlib-licensed. CMake builds the shim when SDL3 is available in one of these ways: - **Installed SDL3**, 3.2 or newer, found by `find_package(SDL3)`: set `SDL3_DIR` or `CMAKE_PREFIX_PATH`, for example `-DSDL3_DIR=C:/SDL3/cmake`. No flag is needed. - **`-DLEONIDA_SDL3_FETCH=ON`**: downloads the pinned release `SDL3-3.4.20.tar.gz` from SDL's GitHub releases once at configure time, checks its SHA-256, and builds it static with only the gamepad parts (no audio, video, GPU or render). That takes about a minute on the first build. `scripts/build_runtime.ps1 -FetchSdl3` passes it. - **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 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, so no thread polls, but it first adds one reading for every change the script made since the last, stamped with the script's own time: a press that starts and ends between two reads of the title is still in the history, where `GetNextReading` finds it, and the readings are the same however often the title reads. 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 (or its own `:hold`, see `LEONIDA_INPUT_SCRIPT` below), 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 at the next reading the title asks for, with the script's time of the press, so a press is logged once the title reads its pad again. `LEONIDA_INPUT_LOG=0` turns the `press` lines off. `LEONIDA_INPUT_TRACE=1` (diagnostic, this shim only) logs what the title asks for: the first 128 `GetCurrentReading`, `GetNextReading` and `GetPreviousReading` calls, then every one that returns a pressed button and every 1000th, the device callbacks and `RegisterDeviceCallback` calls, and the first few calls of each reading method. Without `LEONIDA_INPUT_SCRIPT`, the shim serves no devices and answers `E_NOTIMPL` for every slot past `Release`, as before. `LEONIDA_INPUT_FILE=` drives a run whose display takes no keyboard input (a headless session): every line appended to that file names one button of the script's table (`a`, `down`, ...) and becomes a press at once, held like a scripted one. The file is read again at most every 250 ms. It is for local runs only. `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 about it. ## Mapping GameInput's buttons are positional, as on an Xbox pad, and SDL's are too, so the face buttons go by position, not by label: | GameInput | SDL3 | DualSense | Switch Pro | |---|---|---|---| | `A` | south | Cross | B | | `B` | east | Circle | A | | `X` | west | Square | Y | | `Y` | north | Triangle | X | | `View` | back | Create | Minus | | `Menu` | start | Options | Plus | | shoulders, stick clicks, d-pad | same | L1/R1, L3/R3, d-pad | L/R, stick clicks, d-pad | | guide button callback | guide | PS | Home | The DualSense touchpad click, mute button and paddles are not in GameInput's gamepad state; they are in the controller-button array (`GetControllerButtonState`, indexed in SDL's `SDL_GamepadButton` order). - Sticks: -1..1 with +Y up (SDL reports +Y down; the shim flips it). Triggers: 0..1. No deadzone is applied, as on console: the title applies its own. - `GetUiNavigationState` is derived from the pad: A accept, B cancel, X/Y context 1/2, stick clicks context 3/4, d-pad or left stick past half for up/down/left/right, shoulders for page left/right, triggers past half for page up/down, right stick past half for scrolling, Menu and View as themselves. - Controller axes (`GetControllerAxisState`): LX, LY, RX, RY, LT, RT in 0..1, sticks at rest at 0.5. - Every pad is reported as family `GameInputFamilyXboxOne` with its real USB vendor and product id. - Player LEDs (and SDL's default lightbar colour) follow connection order: the first pad is player 1, and a pad plugged in later takes the lowest free slot. ## Keyboard pad The title reads gamepads only, so keyboard input has to arrive as a gamepad. With `LEONIDA_KEYBOARD_PAD` set, the shim attaches one SDL virtual gamepad named `Keyboard pad (Leonida)` and presses its buttons from the keyboard on every poll. It then goes through the same path as a real pad: a device object, the next free player slot, readings, reading and device callbacks, and UI navigation derived from its buttons. It reports no rumble motors. It is off by default. If SDL fails to attach or open the keyboard pad, the shim retries after one second while the pad is enabled. Only the first failure in a continuous series is logged; turning the pad off and back on retries immediately. | key | button | |---|---| | arrow keys | d-pad | | Enter | `A` | | Backspace | `B` | | X | `X` | | Y | `Y` | | Q / E | left / right shoulder | | Esc | `Menu` | | Tab | `View` | | W / A / S / D | left stick up / left / down / right | | mouse movement | right stick | | right mouse button | left trigger (aim) | | left mouse button | right trigger (fire) | Letters are Windows virtual-key codes, so `Y` is the key labelled Y on the active layout (it sits where Z does on a QWERTY keyboard with a German layout). Mouse buttons are the physical ones: `GetAsyncKeyState` ignores the swapped-buttons setting. WASD pushes the left stick to full deflection. Opposite keys cancel (W+S is centered on Y), and a diagonal sits on the round gate as a real stick reports it: about 0.707 on each axis, not 1. The right stick follows the mouse's movement, not the cursor's position. Each poll (2 ms with the background thread) the stick keeps 7/8 of its value and adds 1024 axis units (of 32767, times `LEONIDA_MOUSE_SENSITIVITY`) per count the mouse moved since the last poll, clamped to full. Steady movement of 4 counts a poll (2000 a second) is full deflection; when the mouse stops, the stick falls back from full to exactly 0 in 67 polls (134 ms). Moving the mouse down pushes the stick down. The movement comes from raw input (`WM_INPUT`): what the mouse itself reports, so it does not stop at the edge of the screen and Windows' pointer acceleration does not change it. When the keyboard pad attaches, the shim starts one thread with a message-only window (never shown) registered for raw mouse input (`RIDEV_INPUTSINK`), which adds each relative movement to a running total; the poll takes the difference of that total between polls. Absolute reports (remote desktop, some virtual machines, pen tablets) are ignored. If the window or the registration fails, the shim logs it and falls back to `GetCursorPos` deltas, which stop at the screen edge. A count is one step of the mouse's sensor, about a pixel at Windows' default pointer speed without acceleration, so the feel depends on the mouse's DPI. With raw input on and a window of this process in the foreground, the cursor is kept inside that window's client area (`ClipCursor`, re-applied every 100 ms) so that a click cannot land on another window; it is released when focus moves away or the keyboard pad is turned off. It is also released while the window is moved or sized, while a menu loop runs, and while a mouse press that began outside the client area (on the title bar or a border) is held, so the window can still be dragged; it comes back once the button is released. The cursor stays visible: hiding it has to happen on the thread that owns the game's window, which is the title's, not the shim's. Keys are read with `GetAsyncKeyState`, which needs no window or message loop (SDL's keyboard is part of its video subsystem, which this build leaves out) and works under Wine. With `LEONIDA_KEYBOARD_PAD=1` keys count only while a window of this process is in the foreground. Losing focus releases keyboard and mouse input. The cursor is read afresh on return so the right stick does not jump. Scripted presses run with or without focus for unattended runs. `LEONIDA_KEYBOARD_PAD=always` reads physical input whatever has focus; a console tool such as `gameinput_probe` needs it, because its console window belongs to the terminal, not to the tool. - Force feedback and haptics run through a fake haptic backend (`rt::gameinput::set_haptic_source`), because SDL's virtual joysticks report no haptics: the motor count, axes and effect flags a wheel reports, and a pad without SDL haptics reporting no motor at all; `CreateForceFeedbackEffect` and its `E_INVALIDARG` cases; a constant effect becoming `SDL_HAPTIC_CONSTANT` at the right level, not re-sent while unchanged, updated once when the parameters change; the effect's gain and the motor's device gain; a 50 Hz sine's period, phase, length and play count; a spring's coefficients, saturations, dead zone and centre; a finished effect reporting stopped; `Paused` stopping it; `LEONIDA_RUMBLE=0` silencing it and the mute lifting; the SDL effect destroyed when the title releases it; and, on a pad with trigger motors, the two haptic motors, `SetHapticMotorState`'s intensity, deadline, `playCount` 0 and null, and the trigger rumble sharing the one message. To try it by hand: `set LEONIDA_KEYBOARD_PAD=always`, then `gameinput_probe --seconds 20` and press keys. ## The keyboard-and-mouse pad of the D3D12 runtime The D3D12 runtime (`d3d12/`) has its own GameInput module (`d3d12/crates/leonida-hle/src/modules/gameinput.rs`) with a stand-in pad made from the keyboard and mouse, present while no host pad is connected (or beside one, with `LEONIDA_ONE_PAD`, the default). Keys and mouse buttons count only while a window of the runtime has focus. ### Grand Theft Auto V's layout: one table on foot, one in a vehicle The title reads a pad only, and on a pad one button is two actions: the right trigger shoots on foot and accelerates in a vehicle, the left trigger aims and brakes. One table of keys cannot be a PC layout then, so there are two (`gameinput/kbm.rs`), and the stand-in pad uses the one of what the player is in. The keys are Grand Theft Auto V's PC defaults (its key bindings as listed in BisectHosting's "GTA V controls guide" and on StrategyWiki's controls page). The pad button of each action is the title's default pad layout as far as it is known: the table below is the one that came with the PC prompt glyphs (a contributor's notes on the Xbox layout), not measured here. | pad | on foot | in a vehicle | |---|---|---| | left stick, click | move, run | steer (lean on a bike), horn | | right stick, click | camera, look behind (zoom while aiming) | camera, look behind | | A / B / X / Y | jump and climb / crouch / melee and reload / interact, enter a vehicle | handbrake / duck, headlights / not known / leave the vehicle | | LB / RB | loadout wheel, holster / cover | loadout wheel / shoot from the vehicle | | LT / RT | aim / shoot | brake and reverse / accelerate | | d-pad up, down, left, right | phone, HUD and objective, radio menu, partner menu | the same | | Menu / View | pause / map | the same | | key | on foot | in a vehicle | |---|---|---| | W, S | left stick up, down: move | RT, LT (fully): accelerate, brake and reverse | | A, D | left stick left, right: move | the same: steer | | mouse | right stick: camera (mouse look, below) | the same | | left mouse button | RT: shoot | RB: shoot from the vehicle | | right mouse button | LT: aim | nothing (the button that aims from a vehicle is not known) | | Space | A: jump, climb | A: handbrake | | Left Shift | left stick click: run | left stick up: lean forward on a bike, nose down in an aircraft | | Left Ctrl | B: crouch (GTA V's stealth) | left stick down: lean back, nose up | | Num 8, Num 5, Num 4, Num 6 | nothing | left stick up, down, left, right (GTA V's aircraft keys) | | Q | RB: cover | d-pad left: radio menu (GTA V's radio wheel) | | E | Y: interact (GTA V's context action) | left stick click: horn | | F | Y: enter a vehicle | Y: leave it | | R | X: reload, melee | X (the same button; GTA V's cinematic camera has none known) | | X, H | nothing | B: duck, headlights | | Tab | LB: loadout wheel (hold), holster | LB | | C | right stick click: look behind | the same | | M | View: map | the same | | Esc, P | Menu: pause | the same | | arrows | d-pad: phone (up) and its menus | the same | | Enter, Backspace | A, B: accept and back in the phone and menus | the same | | Z | d-pad down: HUD and objective (GTA V's radar zoom, the same press on its pad) | the same | | Y; I J K L | Y; right stick (kept from the layout before; GTA V has nothing on them on foot) | the same | GTA V keys left without a binding, because the title's pad button for the action is not known: V (camera view), G (grenade; landing gear), O (heavy melee), the number keys (weapon slots), `[` `]` `,` `.` `=` `-` (zoom, radio), T, B, N, the F keys (character switch), Insert, Page Up and Page Down, the middle mouse button, and Caps Lock (GTA V's special ability), which is the switch described below. Left Alt (GTA V's character switch) would be the partner menu, d-pad right, and is left out because every Alt+Tab would press it; the right arrow is that button. For the same reason Tab, Enter, Space and Esc give nothing while an Alt key is down. The mouse wheel (GTA V's next and previous weapon, and zoom while aiming) is not bound either: the pad has no button known for the next weapon, and the host source polls key states (`GetAsyncKeyState`), which a wheel does not have; it would have to be counted from `WM_MOUSEWHEEL` in the window procedure of `lifecycle.rs`. The layout before had Z and V as the triggers, X as X, H as a second right stick click and Left Ctrl as a second left stick click; those went where GTA V has another meaning for the key. `LEONIDA_KBM=classic` brings the table of before back whole (`FALLBACK_BUTTONS`: W A S D and I J K L the sticks, Space or Enter A, R or Backspace B, X, F or Y, Q and E the shoulders, Left Shift or Left Ctrl and C or H the stick clicks, Z or the right mouse button LT, V or the left mouse button RT, Esc Menu, Tab View). In an aircraft A and D are the left stick (roll), not GTA V's rudder: only "in a vehicle" is known, not which kind. ### Which table counts `gameinput::set_player_context(OnFoot | InVehicle | Unknown)` tells the stand-in pad, lock-free from any thread; a context that is not set again for 500 ms is unknown (and the pad only lets go of a known one after 100 ms of unknown). Unknown is the on-foot table, and then **Caps Lock** switches to the driving table and back by hand, with a line in the log at every change of table; driving by hand also ends when F (leave the vehicle) is pressed, so that W cannot stay the right trigger on foot. While a context is measured Caps Lock does nothing: it is GTA V's special ability key, and a press out of habit on foot must not make W a shot. `gameinput::driving_controls()` says which table is in use (for whoever draws key prompts). **The hand-over** when the table changes: a key that is another pad input in the other table (W, S, the mouse buttons, Left Shift, Left Ctrl, Q, E, X, H) and is down at that moment gives nothing until it has been let go and pressed again, and no such key gives anything for 400 ms after the change (`LEONIDA_KBM_SETTLE_MS`, 0 to 3000). So the left mouse button held on foot never becomes the accelerator and W held in a car never becomes a shot; the price is that W held while getting in has to be pressed again to drive off. Keys that are the same pad input in both tables (A, D, Space, F, ...) carry over as a real pad's button would. Unit-tested over every set of held keys in both directions (`cargo test -p leonida-hle gameinput`). **Who tells.** `d3d12/apps/leonida/src/player_context.rs` reads the title every 16 ms from a thread of its own (`ReadProcessMemory` on the own process: nothing is written and no title code is called, so it does not need `LEONIDA_GAME_ACTIONS=1`; without the game actions it looks the two globals up itself at start, two more passes over the image's code, about 0.15 s together on the retail executable's 99.9 MB of code). It tells `Unknown` while there is no player ped, and a change counts after three equal reads. What says "in a vehicle" is, in this order: 1. `LEONIDA_PED_VEHICLE_AT=0x`: a field of the player's ped that points at its vehicle and is null on foot. None is known (see below why there may be none), so this is unset by default. 2. The title's own global of the player's vehicle (`Site::PlayerVehicle` in `leonida-loader/src/game_actions.rs`, found by a pattern that is in the 1.0.2.1 executable once; `LEONIDA_PLAYER_VEHICLE_AT=0x` names another, `=off` turns it off). **Read from the code, not yet seen in the running title:** - The title keeps what belongs to a ped apart from the ped's entity, in tables looked up by the entity's id (`+9Ch`; a ped's id has `60000h` under the mask `3E0000h`, its index is the low 17 bits, and a 16-bit slot of `FFFFh` means "none"). Its "the vehicle this ped is in" (the function at `4DD7510h`) takes column `47h` of those tables and gives the pointer at `+898h` of it when bit `20h` of the byte at `+10h` is set, else null: the shape of GTA V's `GetVehiclePedInside`, a "my vehicle" pointer that outlives the ride plus a flag. That is why a pointer in the ped that is null on foot may not exist at all. - The global at `AB760C8h` is written by one function (`CA4DE0h`), which has three callers: one passes a vehicle (in a function of 129Fh bytes, taken to be where a ped is put in a vehicle), one passes null after testing that the ped's id is the player's (taken to be where a ped is taken out), and the function that sets the player's ped passes what `4DD7510h` gives for the new ped. The first two are methods of that same column `47h` record: the first begins by reading its `+10h` and `+898h` and testing bit `20h`, the second tests other bits beside it (`+12h`). 167 places in the code read the global; the vehicle cheats read a type byte at `+FAh` of what it points at. - Not known until it has run: that it is null in every on-foot state (after a crash through the windscreen, a vehicle that blows up, a cutscene), and when during getting in and out it changes compared with the title's own switch of its controls. The reader logs every change with its time, and warns when the ped moves at 12 m/s for a second while it says "on foot", or the vehicle is 60 m from the ped while it says "in a vehicle". 3. `LEONIDA_KBM_SPEED=1`: the speed rule. From the ped's position (taken every 0.2 s): 12 m/s (43 km/h; a sprint is about 7) or more for a second without a break is "in a vehicle", until 3 s have passed below that speed; a fall (more down than along) and a jump of the position (a teleport, a respawn) do not count. Its limits are why it is off unless asked for: it never says "on foot" (a car at a red light and a ped standing are the same to it), it cannot see a drive begin, so it never switches from a standstill and the first metres of every drive are on the on-foot keys, and so the meaning of W and of the mouse buttons would change in the middle of a drive, at every stop. It always runs as the check named above. With none of the three the context stays unknown: the on-foot table, and Caps Lock. | switch | effect | |---|---| | `LEONIDA_KBM=classic` | the single table of before; nothing reads the title | | `LEONIDA_KBM_DRIVE=on` / `off` / `auto` | forces the driving table on or off (a test; nothing reads the title and Caps Lock does nothing then); `auto` is the default | | `LEONIDA_KBM_SETTLE_MS=` | the pause after a change of table, 400 | | `LEONIDA_PED_VEHICLE_AT`, `LEONIDA_PLAYER_VEHICLE_AT`, `LEONIDA_KBM_SPEED` | what says "in a vehicle", above | | `LEONIDA_PED_DUMP=` | for measuring: F8 in the game's window, or a file named `dump` in that folder (its text is the label), writes the first 4000h bytes of the player's ped to `ped--