Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions docs/gameinput.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ like a scripted one. The file is read again at most every 250 ms. It is for loca

`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.
about it. `make_game.py`'s runtime stage on Windows runs it with `-FetchSdl3`, so a build made the usual way has
controller, keyboard and mouse input; `--no-sdl3` leaves the download out (an installed SDL3 is still used).

## Mapping

Expand Down Expand Up @@ -119,11 +120,13 @@ controller-button array (`GetControllerButtonState`, indexed in SDL's `SDL_Gamep

## 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
The title reads gamepads only, so keyboard input has to arrive as a gamepad. 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 on by default in the
focused mode, so a player without a pad can still play; `LEONIDA_KEYBOARD_PAD=off` removes it.

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 |
Expand Down Expand Up @@ -167,9 +170,10 @@ moves away or the keyboard pad is turned off. The cursor stays visible: hiding i
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.
subsystem, which this build leaves out) and works under Wine. By default (or 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
Expand Down Expand Up @@ -344,8 +348,8 @@ line is logged when it takes effect); tracking goes on underneath, so clearing i
| `LEONIDA_PROMPTS` | `auto` | forces the [active input](#active-input) family: `xbox`, `playstation` (or `ps5`), `ps4`, `ps3`, `nintendo` or `keyboard`; `auto` follows the devices |
| `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 | 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, or `hold` seconds when the entry is `button@seconds:hold` (more than 0, at most 600). With SDL3 a press then stays down until the title has read the pads six times since it began, but never past 5 s from its start (or its hold, if longer). A title reads its pad once a frame, so at a few seconds a frame a 300 ms press can fall between two reads and never arrive: on the retail title's "Couldn't autosave" prompt, three 300 ms `b` presses did nothing, while 120 presses 0.5 s apart got through; one `b@1100:3` replaces them. Buttons are `a b x y start back lb rb up down left right`. Spaces around entries are allowed. Empty entries, unknown buttons, invalid times (including negative or non-finite values) and invalid holds (0 or less, more than 600, not a number) are counted and ignored. |
| `LEONIDA_KEYBOARD_PAD` | `1` | the [keyboard pad](#keyboard-pad), read while this process has focus; `always` reads keys whatever has focus; `off` removes it |
| `LEONIDA_INPUT_SCRIPT` | unset | Comma-separated `button@seconds` entries, e.g. `a@2,a@4,start@6`. With SDL3 they drive the keyboard pad (on unless `LEONIDA_KEYBOARD_PAD=off`); 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, or `hold` seconds when the entry is `button@seconds:hold` (more than 0, at most 600). With SDL3 a press then stays down until the title has read the pads six times since it began, but never past 5 s from its start (or its hold, if longer). A title reads its pad once a frame, so at a few seconds a frame a 300 ms press can fall between two reads and never arrive: on the retail title's "Couldn't autosave" prompt, three 300 ms `b` presses did nothing, while 120 presses 0.5 s apart got through; one `b@1100:3` replaces them. Buttons are `a b x y start back lb rb up down left right`. Spaces around entries are allowed. Empty entries, unknown buttons, invalid times (including negative or non-finite values) and invalid holds (0 or less, more than 600, not a number) 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
Expand Down
23 changes: 15 additions & 8 deletions make_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
/run/media/<user> where Linux desktops mount drives), two folder levels down. A share path
(\\server\share\...) can't be listed, so give it to --game. This script never decrypts or works around anything:
it reads plain files and writes
everything it makes under --out. The only thing it downloads is the third_party/rpf9-explorer submodule, when
it is missing. Never share what it makes.
everything it makes under --out. The only things it downloads are the third_party/rpf9-explorer submodule, when
it is missing, and, for the Windows runtime stage, the pinned SDL3 release CMake checks by SHA-256 (controller,
keyboard and mouse input; --no-sdl3 skips it). Never share what it makes.

Stages (each skips work that is already done, so a stopped build continues where it left off):
check always first: file names and sizes against game/<version>.json (add --full-check for SHA-256, slow)
Expand Down Expand Up @@ -2616,7 +2617,7 @@ def build_pipeline_check(jobs: int) -> None:


def runtime(game: str, out: str, v: dict, runtime_build: str | None = None, jobs: int = 1,
*, work: str | None = None) -> None:
*, work: str | None = None, sdl3: bool = True) -> None:
destinations = [*RUNTIME_FILES, "game_path.txt"]
if work is not None:
destinations.append("shader_path.txt")
Expand All @@ -2636,8 +2637,11 @@ def runtime(game: str, out: str, v: dict, runtime_build: str | None = None, jobs
build = cross_build_runtime(jobs)
else:
log("runtime: building")
# -FetchSdl3 builds the GameInput shim (docs/gameinput.md): without it and without an installed SDL3, no
# controller, keyboard or mouse reaches the title. CMake downloads the pinned, hash-checked SDL3 release
# once; --no-sdl3 leaves it out.
run([windows_powershell(), "-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
os.path.join(ROOT, "scripts", "build_runtime.ps1"), "-Jobs", str(jobs)])
os.path.join(ROOT, "scripts", "build_runtime.ps1"), "-Jobs", str(jobs), *(["-FetchSdl3"] if sdl3 else [])])
build = os.path.join(ROOT, "runtime", "build")
artifacts = [os.path.join(build, name) for name in RUNTIME_FILES]
for built in artifacts:
Expand Down Expand Up @@ -2989,7 +2993,7 @@ def _invoke_stage(name: str, fn) -> None:

def run_build_stages(stages: list, *, game: str, work: str, out: str, v: dict, wav: bool, jobs: int,
runtime_build: str | None, emulate: bool, keep_emulated: bool,
fallbacks: tuple[str, ...], overlap: bool = True) -> None:
fallbacks: tuple[str, ...], overlap: bool = True, sdl3: bool = True) -> None:
"""Run build stages after check. With overlap=True (default), shaders/assets/runtime share the machine and
pipelines starts once shaders (and a selected runtime rebuild) are ready. With overlap=False, stages run in order."""
cpu_heavy = [s for s in ("shaders", "assets") if s in stages]
Expand All @@ -3005,7 +3009,7 @@ def fn_assets():
assets(game, work, wav, jobs, dump_jobs=dump_jobs)

def fn_runtime():
runtime(game, out, v, runtime_build, jobs, work=work)
runtime(game, out, v, runtime_build, jobs, work=work, sdl3=sdl3)

def fn_pipelines():
pipelines(work, out, jobs, runtime_build=runtime_build)
Expand Down Expand Up @@ -3124,6 +3128,9 @@ def main() -> int:
help="also decode the Ogg Opus audio to 16-bit PCM WAV (much larger; needs ffmpeg)")
ap.add_argument("--jobs", type=positive_int, default=max(1, (os.cpu_count() or 2) // 2))
ap.add_argument("--find", action="store_true", help="only list the game copies found on this PC")
ap.add_argument("--no-sdl3", action="store_true",
help="on Windows, build the runtime without downloading SDL3: no GameInput shim, so no controller, "
"keyboard or mouse input unless SDL3 is installed (docs/gameinput.md)")
ap.add_argument("--runtime-build", metavar="DIR", type=nonempty_path,
help="a Windows build of runtime/ (gta6rt.exe and gta6rt_tls_host.dll) for the runtime stage "
"instead of building it (off Windows: instead of the clang-cl + xwin cross-build); "
Expand Down Expand Up @@ -3296,12 +3303,12 @@ def main() -> int:
tui_board.set_summary(f"build 0% · {', '.join(build_stages)}")
run_build_stages(stages, game=game, work=work, out=out, v=v, wav=a.wav, jobs=a.jobs,
runtime_build=runtime_build, emulate=emulate, keep_emulated=keep_emulated,
fallbacks=fallbacks, overlap=overlap)
fallbacks=fallbacks, overlap=overlap, sdl3=not a.no_sdl3)
tui_board.set_summary(f"finished in {(time.time() - t0) / 60:.0f} min")
else:
run_build_stages(stages, game=game, work=work, out=out, v=v, wav=a.wav, jobs=a.jobs,
runtime_build=runtime_build, emulate=emulate, keep_emulated=keep_emulated,
fallbacks=fallbacks, overlap=overlap)
fallbacks=fallbacks, overlap=overlap, sdl3=not a.no_sdl3)
log(f"finished in {(time.time() - t0) / 60:.0f} min")
return 0

Expand Down
11 changes: 7 additions & 4 deletions runtime/shims/gameinput.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -187,12 +187,15 @@ rt::gameinput::Config read_config() {
}
if (env("LEONIDA_RUMBLE") == "0") c.rumble = false;
if (env("LEONIDA_GAMEINPUT_THREAD") == "0") c.background_thread = false;
// On by default in the focused mode: the title reads gamepads only, so without it a player with no pad has no
// input at all. Keys and the mouse count only while this process's window has focus (docs/gameinput.md).
const std::string k = env("LEONIDA_KEYBOARD_PAD");
if (k == "1" || k == "on" || k == "focus") c.keyboard_pad = rt::gameinput::KeyboardPadMode::Focused;
if (k.empty() || k == "1" || k == "on" || k == "focus") c.keyboard_pad = rt::gameinput::KeyboardPadMode::Focused;
else if (k == "always") c.keyboard_pad = rt::gameinput::KeyboardPadMode::Always;
else if (!k.empty() && k != "0" && k != "off")
std::fprintf(stderr, "[rt] gameinput: LEONIDA_KEYBOARD_PAD=%s unknown (1, always or off), keyboard pad off\n",
k.c_str());
else if (k == "0" || k == "off") c.keyboard_pad = rt::gameinput::KeyboardPadMode::Off;
else
std::fprintf(stderr, "[rt] gameinput: LEONIDA_KEYBOARD_PAD=%s unknown (1, focus, always or off), keyboard pad "
"off\n", k.c_str());
using leonida::InputFamily;
const std::string p = env("LEONIDA_PROMPTS");
if (p == "xbox") c.prompts = InputFamily::Xbox;
Expand Down
2 changes: 1 addition & 1 deletion runtime/shims/gameinput.h
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ struct Config {
uint8_t lightbar[3] = {0, 0, 0}; // player colour
bool rumble = true; // LEONIDA_RUMBLE=0 turns all rumble off
bool background_thread = true; // LEONIDA_GAMEINPUT_THREAD=0: poll only from poll()
KeyboardPadMode keyboard_pad = KeyboardPadMode::Off; // LEONIDA_KEYBOARD_PAD=1|focus|always|off
KeyboardPadMode keyboard_pad = KeyboardPadMode::Off; // config(): Focused unless LEONIDA_KEYBOARD_PAD=off|0|always
};

// The configuration in use. Read from the environment on the first GameInputCreate.
Expand Down
14 changes: 10 additions & 4 deletions runtime/test/gameinput_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -812,10 +812,15 @@ void test_keyboard_pad(IGameInput* input) {
rt::gameinput::set_keyboard_source(fake_key_down, fake_focus);
rt::gameinput::set_cursor_source(fake_cursor);

// On by default (focused): a player without a pad still has the keyboard and mouse.
set_env("LEONIDA_KEYBOARD_PAD", nullptr);
rt::gameinput::reload_config();
check(rt::gameinput::config().keyboard_pad == rt::gameinput::KeyboardPadMode::Focused,
"keyboard pad: the focused mode by default");
set_env("LEONIDA_KEYBOARD_PAD", "off");
rt::gameinput::reload_config();
rt::gameinput::poll();
check(rt::gameinput::connected_count() == 0, "keyboard pad: off by default");
check(rt::gameinput::connected_count() == 0, "keyboard pad: off with LEONIDA_KEYBOARD_PAD=off");

set_env("LEONIDA_KEYBOARD_PAD", "1");
rt::gameinput::reload_config();
Expand Down Expand Up @@ -916,7 +921,7 @@ void test_keyboard_pad(IGameInput* input) {
(kb->GetDeviceStatus() & GameInputDeviceConnected),
"keyboard pad: on again is the same device object");

set_env("LEONIDA_KEYBOARD_PAD", nullptr);
set_env("LEONIDA_KEYBOARD_PAD", "off");
rt::gameinput::reload_config();
rt::gameinput::poll();
check(rt::gameinput::connected_count() == 0, "keyboard pad: removed at the end");
Expand Down Expand Up @@ -1063,7 +1068,7 @@ void test_active_input() {
// Clean up: everything off and unplugged.
set_env("LEONIDA_PROMPTS", nullptr);
set_env("LEONIDA_PROMPTS_SWITCH_MS", nullptr);
set_env("LEONIDA_KEYBOARD_PAD", nullptr);
set_env("LEONIDA_KEYBOARD_PAD", "off");
rt::gameinput::reload_config();
detach(ds);
detach(ds4);
Expand Down Expand Up @@ -1699,7 +1704,8 @@ int main(int argc, char** argv) {
SDL_HINT_JOYSTICK_GAMEINPUT, SDL_HINT_XINPUT_ENABLED, SDL_HINT_JOYSTICK_DIRECTINPUT})
SDL_SetHintWithPriority(hint, "0", SDL_HINT_OVERRIDE);
set_env("LEONIDA_GAMEINPUT_THREAD", "0");
set_env("LEONIDA_KEYBOARD_PAD", nullptr);
// The keyboard pad is on by default; the other tests count only their own virtual pads.
set_env("LEONIDA_KEYBOARD_PAD", "off");
set_env("LEONIDA_INPUT_SCRIPT", nullptr);
set_env("LEONIDA_DS_TRIGGERS", nullptr);
set_env("LEONIDA_DS_LIGHTBAR", nullptr);
Expand Down
2 changes: 1 addition & 1 deletion tests/test_make_game_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def test_independent_stages_all_run_when_listed_out_of_order(self):
self.assertIsNotNone(manager.assets.call_args.kwargs["dump_jobs"])
manager.runtime.assert_called_once_with(
os.path.abspath(self.game_dir), os.path.abspath(self.out_dir), unittest.mock.ANY, None,
unittest.mock.ANY, work=os.path.abspath(self.work_dir))
unittest.mock.ANY, work=os.path.abspath(self.work_dir), sdl3=True)
manager.pipelines.assert_called_once_with(
os.path.abspath(self.work_dir), os.path.abspath(self.out_dir), unittest.mock.ANY,
runtime_build=None)
Expand Down
20 changes: 17 additions & 3 deletions tests/test_make_game_platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,9 +457,23 @@ def test_windows_native_build_receives_the_requested_jobs(self):
mock.patch.object(make_game, "ROOT", root), \
mock.patch.object(make_game, "run") as run, mock.patch.object(make_game, "log"):
make_game.runtime(root, os.path.join(root, "out"), {"expected_exe": "game.exe"}, jobs=1)
command = run.call_args.args[0]
self.assertEqual(command[command.index("-File") + 1:],
[os.path.join(root, "scripts", "build_runtime.ps1"), "-Jobs", "1"])
default = run.call_args.args[0]
make_game.runtime(root, os.path.join(root, "out"), {"expected_exe": "game.exe"}, jobs=1, sdl3=False)
without = run.call_args.args[0]
# INPUT-OUT-OF-THE-BOX: without -FetchSdl3 (and no installed SDL3) the GameInput shim is not built, and
# no controller, keyboard or mouse reaches the title.
script = os.path.join(root, "scripts", "build_runtime.ps1")
self.assertEqual(default[default.index("-File") + 1:], [script, "-Jobs", "1", "-FetchSdl3"])
self.assertEqual(without[without.index("-File") + 1:], [script, "-Jobs", "1"])

def test_no_sdl3_reaches_the_runtime_stage(self):
seen = {}
with mock.patch.object(make_game, "runtime", lambda *a, **k: seen.update(k)), \
mock.patch.object(make_game, "StageBoard"):
make_game.run_build_stages(["runtime"], game="g", work="w", out="o", v={}, wav=False, jobs=1,
runtime_build=None, emulate=False, keep_emulated=False, fallbacks=(),
overlap=False, sdl3=False)
self.assertIs(seen.get("sdl3"), False)

def test_off_windows_copies_the_build_and_writes_a_wine_launcher(self):
with tempfile.TemporaryDirectory() as root:
Expand Down
Loading