diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md index 3a875af4bb..5e113b6e9b 100644 --- a/scripts/windows-boot/README.md +++ b/scripts/windows-boot/README.md @@ -14,6 +14,9 @@ powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GT # A 200 s boot with the default unattended presses (a@45,a@60,a@75,a@90). powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv +# State-relative presses: A 5 s after session=3 and after session=d, instead of fixed seconds. +powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name state -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv -InputScript "a@session=3+5,a@session=d+5" + # Extra or changed switches: trailing KEY=VALUE arguments (KEY= removes one), as run-boot.sh takes them. powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x98f828c,0x78b2818" @@ -40,7 +43,7 @@ Only when your shell has not set them already (`-DryRun` prints the final list): | `LEONIDA_PIPELINE_CACHE_DIR` | `\pipeline-cache` | one warmed cache shared by every build you boot | | `LEONIDA_PEEK` / `_SECONDS` | `0x7446510,0x98f828c` / `5` | game state and session state (low dword), the two numbers every RESULT reports | | `LEONIDA_DEVICE_FAULT` | `1` | on device loss: `VK_EXT_device_fault` info, checkpoints, last replay steps | -| `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive | +| `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's and the harness's state-relative presses arrive | | `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 | | `DISABLE_RTSS_LAYER`, `DISABLE_VULKAN_OBS_CAPTURE` | `1` | keep third-party Vulkan overlay layers out of the process | @@ -49,6 +52,12 @@ turns it off), `LEONIDA_INPUT_SCRIPT` (`-InputScript`, `-NoInput` for none), `LE thread's call chain at those seconds, unwound in-process, which works natively where `tools/re/mdmp_unwind.py` cannot walk Windows' own DLLs). Other `LEONIDA_*` variables in your shell pass through and are listed. +`-InputScript` entries are `button@seconds` (the runtime's timed presses) or `button@game=+` / +`button@session=+` (state-relative). The state-relative ones are matched by this harness against the +`LEONIDA_PEEK` values (`0x7446510` game, low dword of `0x98f828c` session) and injected as keys through the keyboard +pad (`SendInput`; no window focus needed), once the state has been seen for the delay. They make an A/B boot press in +the same game state when startup timing shifts; the absolute form is unchanged. + The command is `gta6rt --run --game-dir --overlay \overlay --trace .jsonl --trace-d3d12`. The overlay takes everything the title writes, so the package folder can stay read-only. diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1 index d052a79da9..f0f4c252ac 100644 --- a/scripts/windows-boot/boot.ps1 +++ b/scripts/windows-boot/boot.ps1 @@ -49,8 +49,10 @@ Writable folder for everything the title writes (saves, caches). Default \overlay. .PARAMETER InputScript - LEONIDA_INPUT_SCRIPT: timed pad presses, seconds since the pad's first poll (button@seconds, comma-separated; - buttons a b x y start back lb rb up down left right). Sets LEONIDA_KEYBOARD_PAD=always. Builds older than + LEONIDA_INPUT_SCRIPT: pad presses, comma-separated. `button@seconds` (e.g. a@45) is timed from the pad's first + poll and goes to the runtime. `button@game=3+5` / `button@session=d+5` are state-relative: this harness watches + LEONIDA_PEEK (every LEONIDA_PEEK_SECONDS) and injects the key once that state has been seen for the delay + (buttons a b x y start back lb rb up down left right). Sets LEONIDA_KEYBOARD_PAD=always. Builds older than main @ 8146ef690 ignore a script longer than 63 characters. Default 'a@45,a@60,a@75,a@90'. .PARAMETER NoInput @@ -224,6 +226,35 @@ if ($Shaders) { $problems.Add("no shader library: pass -Shaders \shaders\spirv or set LEONIDA_SHADERS") } +# ---------------------------------------------------------------------------------------------- input +# Absolute entries (a@45) go to the runtime as before; state-relative ones (a@session=d+5, a@game=3+5) +# are matched here against the LEONIDA_PEEK values and injected as keys once the state has been seen +# for the delay. The parser/state matcher is tools/boot_input_script.py (unit-tested separately). +$absoluteScript = $InputScript +$statePlan = @() +$InputPlanFile = Join-Path ([System.IO.Path]::GetTempPath()) ("leonida-input-plan-" + $Name + ".json") +if ($InputScript) { + $inputPy = @(Resolve-Python $Python) + $stateLike = $InputScript -match '@(game|session)=' + if (-not $inputPy.Count -and $stateLike) { + throw "state-relative LEONIDA_INPUT_SCRIPT needs Python (python or py -3 on PATH, or -Python): $InputScript" + } + if ($inputPy.Count) { + $parseArgs = @() + if ($inputPy.Count -gt 1) { $parseArgs += $inputPy[1..($inputPy.Count - 1)] } + $parseArgs += @("-I", (Join-Path $RepoRoot "tools\boot_input_script.py"), "parse", $InputScript, "--out", $InputPlanFile) + $ErrorActionPreference = "Continue" + $planOut = & $inputPy[0] @parseArgs 2>&1 | ForEach-Object { "$_" } + $parseExit = $LASTEXITCODE + $ErrorActionPreference = "Stop" + if ($parseExit -ne 0) { throw "tools/boot_input_script.py parse failed: $($planOut -join ' ')" } + $plan = ($planOut -join "`n") | ConvertFrom-Json + $absoluteScript = [string]$plan.absolute + $statePlan = @($plan.state) + if (@($plan.rejected).Count) { Write-Warning ("ignored input entries: " + (@($plan.rejected) -join ", ")) } + } +} + # ------------------------------------------------------------------------------------------ environment # Defaults: used only when this shell has not set the variable. They match the Linux harness (scripts/linux-boot/). @@ -246,7 +277,7 @@ if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" } # Per-run values: always this script's (from its parameters), whatever the shell has. $perRun = [ordered]@{ LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture }) - LEONIDA_INPUT_SCRIPT = $InputScript + LEONIDA_INPUT_SCRIPT = $absoluteScript } if ($Shaders) { $perRun["LEONIDA_SHADERS"] = $Shaders } if ($Stacks) { $perRun["LEONIDA_STACKS"] = $Stacks } @@ -276,6 +307,7 @@ if (-not $DigestOnly) { Write-Output "[boot] gta6rt $Runtime" Write-Output "[boot] out $OutDir" foreach ($k in $bootEnv.Keys) { if ($bootEnv[$k] -ne "") { Write-Output ("[boot] env {0}={1}" -f $k, $bootEnv[$k]) } } + if ($InputScript) { Write-Output ("[boot] input absolute='{0}' state={1}" -f $absoluteScript, @($statePlan).Count) } Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine" } @@ -291,6 +323,7 @@ if ($DryRun) { Write-Output "[boot] dry run: nothing launched"; exit $(if ($prob $verdict = "digest of an earlier run (-DigestOnly)" $exitCode = 0 +$proc = $null if (-not $DigestOnly) { # --------------------------------------------------------------------------------------------- the lock @@ -340,10 +373,101 @@ if (-not $DigestOnly) { -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile $handle = $proc.Handle # keeps the exit code readable after the process ends $stopped = $false - if (-not $proc.WaitForExit($Seconds * 1000)) { - $stopped = $true - try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { } - [void]$proc.WaitForExit(20000) + if (-not $statePlan.Count) { + if (-not $proc.WaitForExit($Seconds * 1000)) { + $stopped = $true + try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { } + [void]$proc.WaitForExit(20000) + } + } else { + # State-relative input: watch the LEONIDA_PEEK values and inject a key once a state has been seen + # for its delay. The key path is the keyboard pad (GetAsyncKeyState), so LEONIDA_KEYBOARD_PAD=always + # is set above; no window focus is needed. + $watchStart = Get-Date + $deadline = $watchStart.AddSeconds($Seconds) + $seen = @{ game = $null; session = $null } + $fired = @{} + $watchPeekRx = [regex]'\[rt\] peek t=(\d+)s:(.*)$' + $watchValRx = [regex]'0x([0-9a-f]+)=([0-9a-f?]+)' + $keyMap = @{ a = 0x0D; b = 0x08; x = 0x58; y = 0x59; start = 0x1B; back = 0x09 + lb = 0x51; rb = 0x45; up = 0x26; down = 0x28; left = 0x25; right = 0x27 } + if (-not ("LeonidaKeys" -as [type])) { + Add-Type -TypeDefinition @" +using System; +using System.Runtime.InteropServices; +[StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } +[StructLayout(LayoutKind.Explicit, Size = 40)] public struct INPUT { [FieldOffset(0)] public uint type; [FieldOffset(8)] public KEYBDINPUT ki; } +public static class LeonidaKeys { + [DllImport("user32.dll", SetLastError = true)] public static extern uint SendInput(uint n, INPUT[] inputs, int cb); + public static void Key(ushort vk, bool down) { + INPUT[] input = new INPUT[1]; + input[0].type = 1; // INPUT_KEYBOARD + input[0].ki.wVk = vk; + input[0].ki.dwFlags = down ? 0u : 2u; // KEYEVENTF_KEYUP + SendInput(1, input, Marshal.SizeOf(typeof(INPUT))); + } +} +"@ + } + $dueArgs = @() + if ($inputPy.Count -gt 1) { $dueArgs += $inputPy[1..($inputPy.Count - 1)] } + $dueArgs += @("-I", (Join-Path $RepoRoot "tools\boot_input_script.py"), "due", "--plan", $InputPlanFile) + $fs = $null; $reader = $null + try { + $fs = [System.IO.File]::Open($LogFile, [System.IO.FileMode]::OpenOrCreate, + [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite) + $reader = New-Object System.IO.StreamReader($fs) + while (-not $proc.HasExited -and (Get-Date) -lt $deadline) { + $line = $reader.ReadLine() + if ($null -eq $line) { Start-Sleep -Milliseconds 100; continue } + if (-not $line.Contains("[rt] peek t=")) { continue } + $m = $watchPeekRx.Match($line) + if (-not $m.Success) { continue } + $game = $null; $session = $null + foreach ($v in $watchValRx.Matches($m.Groups[2].Value)) { + $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value + if ($rva -eq "7446510") { $game = $val } + elseif ($rva -eq "98f828c" -and $val -ne "?") { + $low = $val.PadLeft(16, '0').Substring(8).TrimStart('0') + $session = $(if ($low) { $low } else { "0" }) + } + } + if ($null -eq $game -and $null -eq $session) { continue } + $now = ((Get-Date) - $watchStart).TotalSeconds + if ($null -ne $game -and $null -eq $seen.game) { $seen.game = $now } + if ($null -ne $session -and $null -eq $seen.session) { $seen.session = $now } + $call = $dueArgs + @("--now", [string]$now) + if ($null -ne $game) { $call += @("--game", [string]$game) } + if ($null -ne $session) { $call += @("--session", [string]$session) } + if ($null -ne $seen.game) { $call += @("--seen-game", [string]$seen.game) } + if ($null -ne $seen.session) { $call += @("--seen-session", [string]$seen.session) } + if ($fired.Keys.Count) { $call += @("--fired", (($fired.Keys | ForEach-Object { [string]$_ }) -join ",")) } + $ErrorActionPreference = "Continue" + $out = & $inputPy[0] @call 2>&1 | ForEach-Object { "$_" } + $ErrorActionPreference = "Stop" + if ($LASTEXITCODE -ne 0) { Write-Warning "boot_input_script.py due failed: $($out -join ' ')"; continue } + $dueList = ($out -join "`n") | ConvertFrom-Json + if ($null -eq $dueList) { continue } + foreach ($d in @($dueList)) { + $button = [string]$d.button + if (-not $keyMap.ContainsKey($button)) { continue } + $vk = [uint16]$keyMap[$button] + [LeonidaKeys]::Key($vk, $true) + Start-Sleep -Milliseconds 300 + [LeonidaKeys]::Key($vk, $false) + $fired[[int]$d.index] = $true + Write-Output ("[boot] input {0} at game={1} session={2} ({3:n1}s)" -f $button, $game, $session, $now) + } + } + } finally { + if ($reader) { $reader.Dispose() } + if ($fs) { $fs.Dispose() } + } + if (-not $proc.HasExited) { + $stopped = $true + try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { } + [void]$proc.WaitForExit(20000) + } } $ran = [int]((Get-Date) - $started).TotalSeconds $rc = $null @@ -358,6 +482,8 @@ if (-not $DigestOnly) { } } +if ($proc) { try { $proc.Dispose() } catch { } } # close the redirect handles before the digest reads the log + # -------------------------------------------------------------------------------------------- the digest $py = @(Resolve-Python $Python) @@ -381,7 +507,7 @@ $presentOk = 0; $presentFailed = 0; $presses = 0 $shaderLine = ""; $faults = New-Object System.Collections.Generic.List[string] $wrapped = 0 if (Test-Path -LiteralPath $LogFile) { - foreach ($line in [System.IO.File]::ReadLines($LogFile)) { + foreach ($line in Get-Content -LiteralPath $LogFile) { if ($line.Contains("XboxPresentation::PresentX")) { if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ } continue diff --git a/tests/test_boot_input_script.py b/tests/test_boot_input_script.py new file mode 100644 index 0000000000..ff858f6373 --- /dev/null +++ b/tests/test_boot_input_script.py @@ -0,0 +1,91 @@ +"""Unit tests for tools/boot_input_script.py on synthetic scripts (no game data, no GPU).""" + +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import boot_input_script as bis + + +class ParseTest(unittest.TestCase): + def test_absolute_only(self): + plan = bis.parse("a@45,a@60,start@120") + self.assertEqual(plan["absolute"], "a@45,a@60,start@120") + self.assertEqual(plan["state"], []) + self.assertEqual(plan["rejected"], []) + + def test_state_only(self): + plan = bis.parse("a@session=d+5,b@game=3") + self.assertEqual(plan["absolute"], "") + self.assertEqual( + plan["state"], + [ + {"button": "a", "field": "session", "value": "d", "delay": 5.0}, + {"button": "b", "field": "game", "value": "3", "delay": 0.0}, + ], + ) + + def test_mixed_spaces_and_case(self): + plan = bis.parse(" A@45 , a@Session=D+5.5 , b@Game=0x3+0 ") + self.assertEqual(plan["absolute"], "a@45") + self.assertEqual( + plan["state"], + [ + {"button": "a", "field": "session", "value": "d", "delay": 5.5}, + {"button": "b", "field": "game", "value": "3", "delay": 0.0}, + ], + ) + + def test_rejects_bad_entries(self): + plan = bis.parse("rsup@session=d+5,a@session=zz,a@-1,a@nan,nope@3,a@,a@game=+5") + self.assertEqual(plan["absolute"], "") + self.assertEqual(plan["state"], []) + self.assertEqual(len(plan["rejected"]), 7) + + def test_empty(self): + plan = bis.parse("") + self.assertEqual(plan["absolute"], "") + self.assertEqual(plan["state"], []) + self.assertEqual(plan["rejected"], []) + + +class DueTest(unittest.TestCase): + def plan(self): + return bis.parse("a@session=d+5,b@game=3+1") + + def test_delay_not_reached(self): + self.assertEqual(bis.due(self.plan(), now=14.9, session="d", seen={"session": 10}), []) + + def test_fires_after_delay(self): + self.assertEqual( + bis.due(self.plan(), now=15.0, session="d", seen={"session": 10}), + [{"index": 0, "button": "a"}], + ) + + def test_leading_zero_and_case(self): + plan = bis.parse("a@session=0D+0") + self.assertEqual(bis.due(plan, now=0, session="d", seen={"session": 0}), [{"index": 0, "button": "a"}]) + + def test_other_field_ignored(self): + plan = bis.parse("a@session=d+5") + self.assertEqual(bis.due(plan, now=100, game="3", session=None, seen={"game": 0}), []) + + def test_already_fired(self): + self.assertEqual(bis.due(self.plan(), now=100, session="d", seen={"session": 0}, fired=[0]), []) + + def test_no_state_seen(self): + self.assertEqual(bis.due(self.plan(), now=100, session="d", seen={}), []) + + def test_games_entry(self): + self.assertEqual( + bis.due(self.plan(), now=1.0, game="3", seen={"game": 0}), + [{"index": 1, "button": "b"}], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/boot_input_script.py b/tools/boot_input_script.py new file mode 100644 index 0000000000..fd46fd5e2c --- /dev/null +++ b/tools/boot_input_script.py @@ -0,0 +1,156 @@ +"""Parse LEONIDA_INPUT_SCRIPT for scripts/windows-boot/boot.ps1. + +Absolute entries (``button@seconds``) go to the runtime as before. State-relative entries +(``button@game=3+5`` / ``button@session=d+5``) are returned to the harness, which watches the +``LEONIDA_PEEK`` values and injects the key once the state has been seen for the delay. + +No game files, no Windows, no GPU: this module only parses and matches the script text. +""" + +import argparse +import json +import math +import sys + +BUTTONS = { + "a", "b", "x", "y", "start", "back", "lb", "rb", "up", "down", "left", "right", "rsup", "rsdown", +} +# The keyboard pad maps keys to these buttons (docs/gameinput.md, "Keyboard pad"); rsup/rsdown are +# stick throws with no key, so the harness cannot inject them. +KEY_BUTTONS = {"a", "b", "x", "y", "start", "back", "lb", "rb", "up", "down", "left", "right"} +STATE_FIELDS = {"game", "session"} + + +def _number(text): + try: + value = float(text) + except (TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + + +def _hex(text): + text = text.strip().lower() + if text.startswith("0x"): + text = text[2:] + try: + int(text, 16) + except (TypeError, ValueError): + return None + return text or None + + +def parse(text): + """Return {"absolute": str, "state": [...], "rejected": [...]} for one script.""" + absolute = [] + state = [] + rejected = [] + for raw in (text or "").split(","): + entry = raw.strip() + if not entry: + continue + if "@" not in entry: + rejected.append(entry) + continue + button, spec = entry.split("@", 1) + button = button.strip().lower() + spec = spec.strip() + if button not in BUTTONS: + rejected.append(entry) + continue + if spec.lower().startswith(("game=", "session=")): + field, rest = spec.split("=", 1) + field = field.strip().lower() + if field not in STATE_FIELDS or button not in KEY_BUTTONS: + rejected.append(entry) + continue + if "+" in rest: + value_text, delay_text = rest.split("+", 1) + else: + value_text, delay_text = rest, "0" + value = _hex(value_text) + delay = _number(delay_text) + if value is None or delay is None: + rejected.append(entry) + continue + state.append({"button": button, "field": field, "value": value, "delay": delay}) + else: + seconds = _number(spec) + if seconds is None: + rejected.append(entry) + continue + absolute.append("%s@%s" % (button, spec)) + return {"absolute": ",".join(absolute), "state": state, "rejected": rejected} + + +def due(plan, now, game=None, session=None, seen=None, fired=None): + """Entries in ``plan`` whose state has been seen for its delay and that have not fired.""" + seen = seen or {} + fired = set(fired or ()) + out = [] + for index, entry in enumerate(plan.get("state", [])): + if index in fired: + continue + state = game if entry["field"] == "game" else session + if state is None: + continue + state_value = _hex(str(state)) + if state_value is None or int(state_value, 16) != int(entry["value"], 16): + continue + since = seen.get(entry["field"]) + if since is None or now < since + entry["delay"]: + continue + out.append({"index": index, "button": entry["button"]}) + return out + + +def _load_plan(args): + if args.plan: + with open(args.plan, "r", encoding="utf-8") as handle: + return json.load(handle) + if args.plan_json: + return json.loads(args.plan_json) + raise SystemExit("due needs --plan or --plan-json") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + parse_cmd = sub.add_parser("parse", help="split a script into absolute and state-relative entries") + parse_cmd.add_argument("script") + parse_cmd.add_argument("--out", help="write the plan here as JSON") + + due_cmd = sub.add_parser("due", help="the entries whose state has been seen for their delay") + due_cmd.add_argument("--plan") + due_cmd.add_argument("--plan-json") + due_cmd.add_argument("--now", type=float, required=True) + due_cmd.add_argument("--game") + due_cmd.add_argument("--session") + due_cmd.add_argument("--seen-game", type=float) + due_cmd.add_argument("--seen-session", type=float) + due_cmd.add_argument("--fired", default="") + + args = parser.parse_args(argv) + if args.command == "parse": + plan = parse(args.script) + text = json.dumps(plan, indent=2) + if args.out: + with open(args.out, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text + "\n") + print(text) + return 0 + + plan = _load_plan(args) + seen = {} + if args.seen_game is not None: + seen["game"] = args.seen_game + if args.seen_session is not None: + seen["session"] = args.seen_session + fired = [int(part) for part in args.fired.split(",") if part.strip().isdigit()] + print(json.dumps(due(plan, args.now, args.game, args.session, seen, fired))) + return 0 + + +if __name__ == "__main__": + sys.exit(main())