Skip to content
Closed
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
11 changes: 10 additions & 1 deletion scripts/windows-boot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -40,7 +43,7 @@ Only when your shell has not set them already (`-DryRun` prints the final list):
| `LEONIDA_PIPELINE_CACHE_DIR` | `<out>\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 |

Expand All @@ -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=<hex>+<delay>` /
`button@session=<hex>+<delay>` (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 <exe> --game-dir <game> --overlay <out>\overlay --trace <name>.jsonl --trace-d3d12`.
The overlay takes everything the title writes, so the package folder can stay read-only.

Expand Down
142 changes: 134 additions & 8 deletions scripts/windows-boot/boot.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@
Writable folder for everything the title writes (saves, caches). Default <OutDir>\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
Expand Down Expand Up @@ -224,6 +226,35 @@ if ($Shaders) {
$problems.Add("no shader library: pass -Shaders <work>\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")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep the input plan local to the run

This path is keyed only by -Name and is written before the -DryRun exit and before the run lock. Two dry runs using different output directories and the same name created and then replaced the same temporary plan. The second run can also replace a live run's plan, since the watcher opens it on each poll. Keep the plan in memory or use a unique per-run file written after validation and dry-run handling.

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/).
Expand All @@ -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 }
Expand Down Expand Up @@ -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"
}

Expand All @@ -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
Expand Down Expand Up @@ -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)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep unattended input out of the system keyboard stream

SendInput enters the system keyboard stream. LEONIDA_KEYBOARD_PAD=always lets the game observe it in the background, and the foreground app can still receive the synthesized Enter, Backspace or Escape. This makes unattended runs affect other apps. Route scripted presses through the runtime's virtual pad. Win32 SendInput docs.

}
}
"@
}
$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 }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Start the delay when the observed value changes

The timer is set on the first report for the field and is never reset if its value changes. With a synthetic first report of session 0 at t=0 and the first d at t=10, the watcher code supplies seen-session=0 and button@session=d+5 is due immediately. It should first be eligible at t=15. Track the current value and its entry time for both fields, and add a transition case to the tests.

$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
Expand All @@ -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)
Expand All @@ -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
Expand Down
91 changes: 91 additions & 0 deletions tests/test_boot_input_script.py
Original file line number Diff line number Diff line change
@@ -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()
Loading