upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts/windows-boot
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 20:26:00 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 20:26:00 -0500
commit154e4ec034902deffa4b89b2cbca9a949f38baec (patch)
tree1b2ef5656de42c172291bc6009efa4c510650815 /scripts/windows-boot
parenteb6a08cd359d98b5777e70d54d0ae8a75879495a (diff)
parent8a242efebf823aeb23c72d17c3d666daf0bbd3e2 (diff)
Merge the #984 result (main + RT-PROTON-STORY-LOAD) into #939
The base is 8a242efeb, the merge of main and #984. 68 files conflicted; they were resolved in seven groups by one rule: the same change in two forms keeps the base's form, everything only #939 has is kept, and where the two solve one problem in two ways the base's is the frame and #939's plugs into it. A, the Xbox proxy (d3d12_xs_device.cpp/.h, d3d12_xs.cpp, d3d12_xs_pso_stream.cpp/.h, d3d12_xs_alloc_size.h, d3d12_xs_desc_clean.h, device_proxy_test.cpp, queue_proxy_test.cpp): the base's files with #939's additions ported in. Device slot 57 asks #939's NativeGraphicsFactory first and falls back to the base's proxy_create_graphics_pipeline_from_native_code on E_NOTIMPL. Kept from #939: the providers (texture lease, raw texture view, resource by address, constant view, descriptor mapping, depth-stencil UAV, texture pages), the title-backed descriptor mirror, slot 13's feature answers, GPU labels on list slots 71/72. Dropped: #939's duplicates of the boot ladder routes, its fallback window, its slot 133 stand-in. A2 (xs_proxy_mock_test.cpp): the base's test with #939's slot 70 raw-buffer case; presentation cases follow #939's rule that a device which ever had a handler has no queue fallback. B1, the Vulkan device (d3d12_vulkan_device.cpp, d3d12_com.cpp/.h, shader_library.h, queue_families.h, pipeline_cache_file.h, startup_trace.h): one lazy-pipeline mechanism, the base's; #939's pending_base_compile and first_use_backend_pipelines dropped, prepare_on_bind and cold_graphics_compile kept. create_texture keeps the base's signature; #939's deferred backing is folded into the base's placed-memory binder. #939's quad lists as triangle indices. B2, the D3D12 tests (d3d12_existing_heap, a8_dimensions, pipeline_cache_seed, title_va, rect_list, shader_library, loader_tls_index0, draw, compute, xmem_placed, shader_library_corpus): the base's tests where both carry the same case, #939's cases added (rebound tables, linear texture map, large vertex batch, executable shaders, default A8 views). C, the backend (vulkan_replay.h, vulkan_backend.h, vulkan_bindless.h, vulkan_scratch.h, vulkan_present.h, rect_list_geometry.h, vk_test_device.h, vk_pipeline_check.cpp, vk_store_test.cpp, bindless_sizing_test.cpp, replay_texture_barrier_test.cpp): the base's prepare_draw and lazy compute, its #1055 release rule and its rectangle generator; #939's rectangle variants, GPU quad index expansion, 1D/3D and depth-stencil UAVs, the label fence on the base's submit. D, memory, services, presentation (xmem.cpp/.h, xg_xs.cpp, xg_xs_test.cpp, title_va_alias.h and its test, main.cpp, frame_pacer.h, xbox_present.cpp/.h; xgameruntime_offline.cpp for one comment): the base's xmem with #939's label hooks, file-backed sections and pin_mapped_data; both texture computers in xg_xs.cpp, the base's answering first; --first-run-ui kept without host speech in its profile. E, build, tools, docs (runtime/CMakeLists.txt, make_game.py, tools/rdna2spirv.py, tools/shader_disasm.py, scripts, tests, docs; docs/README.md and tests/test_exe_shaders_stage.py beyond the conflicts): the base's v_dot4 decode, #281's disassembler form and tests/semantic/test_fspx_dot4_op_sel_disasm.py dropped; the base's executable-shader step with #939's cache fix; 366 registered tests. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'scripts/windows-boot')
-rw-r--r--scripts/windows-boot/README.md93
-rw-r--r--scripts/windows-boot/boot.ps1456
2 files changed, 549 insertions, 0 deletions
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md
new file mode 100644
index 000000000..3a875af4b
--- /dev/null
+++ b/scripts/windows-boot/README.md
@@ -0,0 +1,93 @@
1# Native Windows boot harness
2
3`boot.ps1` boots the retail executable under `gta6rt` on native Windows the way the Linux harness
4([`scripts/linux-boot/`](../linux-boot/)) does under Proton: same switches, one game process at a time, a trace of
5every boot and a short digest at the end. Windows PowerShell 5.1 is enough. New here? the repository README
6covers the setup that comes before this.
7
8## Run it
9
10```powershell
11# What would run, with every path checked; launches nothing.
12powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
13
14# A 200 s boot with the default unattended presses (a@45,a@60,a@75,a@90).
15powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
16
17# Extra or changed switches: trailing KEY=VALUE arguments (KEY= removes one), as run-boot.sh takes them.
18powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x98f828c,0x78b2818"
19
20# Every parameter.
21Get-Help -Full .\scripts\windows-boot\boot.ps1
22```
23
24Set `LEONIDA_GAME_DIR`, `LEONIDA_SHADERS` (and `GTA6RT`, `LEONIDA_RUNS` if you use other places) once in your
25profile and the parameters can be left out. Defaults: `gta6rt` from `runtime\build\RelWithDebInfo\` of this
26checkout, the executable from the game folder (`-Exe` or `LEONIDA_EXE` when it lives elsewhere), outputs in `$HOME\leonida-runs`.
27The script refuses an output folder inside the repository.
28
29## What it sets
30
31Only when your shell has not set them already (`-DryRun` prints the final list):
32
33| Variable | Default | Why |
34|---|---|---|
35| `LEONIDA_D3D12` | `vulkan` | the runtime's D3D12-on-Vulkan backend |
36| `LEONIDA_DEVICE_TYPE` | `6` | Series S identity; the runtime answers the title's `ConsoleMode` registry read with it (1920x1080) |
37| `LEONIDA_ARENA_MB` | `2048` | as on Linux |
38| `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit |
39| `LEONIDA_STARTUP_CACHE_CHECKPOINTS` | `1` | save the pipeline cache during startup |
40| `LEONIDA_PIPELINE_CACHE_DIR` | `<out>\pipeline-cache` | one warmed cache shared by every build you boot |
41| `LEONIDA_PEEK` / `_SECONDS` | `0x7446510,0x98f828c` / `5` | game state and session state (low dword), the two numbers every RESULT reports |
42| `LEONIDA_DEVICE_FAULT` | `1` | on device loss: `VK_EXT_device_fault` info, checkpoints, last replay steps |
43| `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive |
44| `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 |
45| `DISABLE_RTSS_LAYER`, `DISABLE_VULKAN_OBS_CAPTURE` | `1` | keep third-party Vulkan overlay layers out of the process |
46
47Per run, from the parameters: `LEONIDA_SHADERS` (`-Shaders`), `LEONIDA_CAPTURE` (`<out>\cap_<name>`, `-NoCapture`
48turns it off), `LEONIDA_INPUT_SCRIPT` (`-InputScript`, `-NoInput` for none), `LEONIDA_STACKS` (`-Stacks 30,60`: every
49thread's call chain at those seconds, unwound in-process, which works natively where `tools/re/mdmp_unwind.py`
50cannot walk Windows' own DLLs). Other `LEONIDA_*` variables in your shell pass through and are listed.
51
52The command is `gta6rt --run <exe> --game-dir <game> --overlay <out>\overlay --trace <name>.jsonl --trace-d3d12`.
53The overlay takes everything the title writes, so the package folder can stay read-only.
54
55## What you get
56
57In the output folder: `<name>.log` (stderr: `[rt]` lines and the D3D12 trace), `<name>.stdout.log`,
58`<name>.jsonl` (startup trace), `<name>.summary.txt` (`tools/boot_trace.py`), `<name>.digest.txt` and
59`cap_<name>\` (PPM frames plus `index.txt` with the mean RGB of each). The digest:
60
61```
62== boot first: ran its full time limit (200 s), stopped
63shaders: [rt] d3d12: 26586 translated shaders (21 fspx, 0 fspx_compute, 0 fspx_gfx, 52 bvh, 10 exe) from ...
64states: t=0s game=0 session=0 | t=15s game=2 session=0 | t=30s game=3 session=3 | t=60s game=3 session=d
65presents: PresentX ok 1581, failed 0
66input: 13 presses logged
67faults: none
68frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 0.00 0.00
69```
70
71`-DigestOnly -Name <name>` writes the summary and digest again for an earlier run. The digest holds counts and
72states only, which is what goes into a RESULT on the board; the logs, traces, captures and dumps can quote the game
73and stay on your machine ([AGENTS.md](../../AGENTS.md), "No game data").
74
75How to read the states: game state `0x7446510` goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing
76screen waiting for A), `d` after A. `docs/linux_proton.md` (the same stages apply natively)
77section 2 has the healthy sequence with times and section 3 "which blank do you have".
78
79## One game at a time
80
81The script holds the named mutex `Local\LeonidaGameBoot` for the whole boot and also waits while any `gta6rt.exe`
82runs (another agent's boot, or one started by hand), up to `-LockWaitSeconds` (default an hour, then exit 3). Two
83game processes on one GPU make both runs meaningless and can take the driver down.
84
85## Helper tools (`tools/re/windows/`)
86
87| Tool | What for |
88|---|---|
89| `sym.py IMAGE RVA...` | `gta6rt.exe+0x...` frames to function and line through dbghelp and the build's PDB (the Windows SDK's or Visual Studio's `dbghelp.dll`; `LEONIDA_DBGHELP` names another) |
90| `ripsample.ps1 [-Seconds 20]` | sampling profiler of a running `gta6rt`: per thread, where it spends its time, as module+RVA (`TITLE+0x...` for the title) |
91| `minidump.py PID OUT.dmp` | a minidump through dbghelp's `MiniDumpWriteDump`. Do not use `rundll32 comsvcs.dll MiniDump`: Defender flags it. A dump holds game memory: local only |
92
93Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell).
diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1
new file mode 100644
index 000000000..d052a79da
--- /dev/null
+++ b/scripts/windows-boot/boot.ps1
@@ -0,0 +1,456 @@
1<#
2.SYNOPSIS
3 Boot the retail executable under gta6rt on native Windows, one game process at a time, and print a digest.
4
5.DESCRIPTION
6 The native counterpart of scripts/linux-boot/: sets the switches both machines boot with (see
7 docs/re/howto-blank-to-story-load.md, section 1), runs `gta6rt --run` with --trace and --trace-d3d12 for
8 -Seconds, stops it, runs tools/boot_trace.py and prints a short digest: exit, game/session state over time,
9 PresentX count, device-fault lines, capture means. Paste numbers from the digest into a RESULT on the
10 coordination board, never the logs: they can quote the game (AGENTS.md, "No game data").
11
12 Only one game process runs at a time: the script holds a named mutex and also waits while any gta6rt.exe is
13 running (another agent's boot, or one started by hand).
14
15 Every default switch is used only when the variable is not already set in this shell; other LEONIDA_*
16 variables of the shell pass through; -SetEnv overrides all of them. -DryRun lists the result. Outputs go to -OutDir (never inside the repository):
17 <OutDir>\<Name>.log stderr of gta6rt: [rt] diagnostics and [d3d12-trace] lines
18 <OutDir>\<Name>.stdout.log stdout of gta6rt
19 <OutDir>\<Name>.jsonl startup trace (--trace)
20 <OutDir>\<Name>.summary.txt tools/boot_trace.py report
21 <OutDir>\<Name>.digest.txt the digest printed at the end
22 <OutDir>\cap_<Name>\ swapchain captures (PPM) and index.txt with mean RGB per frame
23
24.PARAMETER Name
25 Run name; output files are named after it. Default: boot-<yyyyMMdd-HHmmss>.
26
27.PARAMETER Seconds
28 How long the game runs before it is stopped. Default 180.
29
30.PARAMETER GameDir
31 Your package folder (MicrosoftGame.Config and the .rpf archives as plain files). Default: $env:LEONIDA_GAME_DIR,
32 else game_path.txt beside gta6rt.exe (written by make_game.py's runtime stage).
33
34.PARAMETER Exe
35 game_scarlett_master.exe. Default: $env:LEONIDA_EXE, else <GameDir>\game_scarlett_master.exe.
36
37.PARAMETER Runtime
38 gta6rt.exe (gta6rt_tls_host.dll must sit beside it). Default: $env:GTA6RT, else
39 <repo>\runtime\build\RelWithDebInfo\gta6rt.exe.
40
41.PARAMETER Shaders
42 The translated library, <work>\shaders\spirv. Default: $env:LEONIDA_SHADERS; when neither is given the
43 runtime reads shader_path.txt beside gta6rt.exe.
44
45.PARAMETER OutDir
46 Folder for logs, traces and captures. Default: $env:LEONIDA_RUNS, else $HOME\leonida-runs.
47
48.PARAMETER Overlay
49 Writable folder for everything the title writes (saves, caches). Default <OutDir>\overlay.
50
51.PARAMETER InputScript
52 LEONIDA_INPUT_SCRIPT: timed pad presses, seconds since the pad's first poll (button@seconds, comma-separated;
53 buttons a b x y start back lb rb up down left right). Sets LEONIDA_KEYBOARD_PAD=always. Builds older than
54 main @ 8146ef690 ignore a script longer than 63 characters. Default 'a@45,a@60,a@75,a@90'.
55
56.PARAMETER NoInput
57 No input script (LEONIDA_KEYBOARD_PAD then stays as this shell has it: LEONIDA_KEYBOARD_PAD=1 to play by
58 hand with the window focused).
59
60.PARAMETER Stacks
61 LEONIDA_STACKS: whole seconds at which every thread's call chain is printed to the log, e.g. '30,60'.
62
63.PARAMETER SetEnv
64 Extra or overriding environment variables as a hashtable, when called from a PowerShell prompt:
65 & .\scripts\windows-boot\boot.ps1 -SetEnv @{ LEONIDA_PEEK_SECONDS = '2' }. A value of '' removes the variable.
66
67.PARAMETER EnvPairs
68 Any further arguments, each KEY=VALUE, as scripts/linux-boot/run-boot.sh takes them. These work with
69 powershell -File too: ... -Name x LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x75e8eb0".
70 Applied after -SetEnv. KEY= removes the variable for this boot.
71
72.PARAMETER NoCapture
73 Do not set LEONIDA_CAPTURE.
74
75.PARAMETER ExtraArgs
76 More gta6rt arguments, appended after the standard ones.
77
78.PARAMETER Python
79 Python 3.12+ used for tools/boot_trace.py. Default: python, else py -3.
80
81.PARAMETER SummaryLines
82 How many lines of the boot_trace.py report to print. Default 40; 0 prints none.
83
84.PARAMETER LockWaitSeconds
85 How long to wait for another boot to finish. Default 3600.
86
87.PARAMETER DryRun
88 Print the environment and the command line, check the paths, launch nothing.
89
90.PARAMETER DigestOnly
91 Launch nothing; write the summary and digest again from an earlier run's files (-Name, -OutDir).
92
93.EXAMPLE
94 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
95
96.EXAMPLE
97 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
98
99.EXAMPLE
100 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=0x7446510,0x75e8eb0,0x75e8ea0,0x9844898"
101
102.EXAMPLE
103 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DigestOnly -Name first
104#>
105[CmdletBinding(PositionalBinding = $false)]
106param(
107 [string]$Name = "",
108 [int]$Seconds = 180,
109 [string]$GameDir = "",
110 [string]$Exe = "",
111 [string]$Runtime = "",
112 [string]$Shaders = "",
113 [string]$OutDir = "",
114 [string]$Overlay = "",
115 [string]$InputScript = "a@45,a@60,a@75,a@90",
116 [string]$Stacks = "",
117 [hashtable]$SetEnv = @{},
118 [switch]$NoCapture,
119 [switch]$NoInput,
120 [string[]]$ExtraArgs = @(),
121 [string]$Python = "",
122 [int]$SummaryLines = 40,
123 [int]$LockWaitSeconds = 3600,
124 [switch]$DryRun,
125 [switch]$DigestOnly,
126 [Parameter(ValueFromRemainingArguments = $true)]
127 [string[]]$EnvPairs = @()
128)
129
130Set-StrictMode -Version 2.0
131$ErrorActionPreference = "Stop"
132
133$RepoRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\.."))
134$ExeName = "game_scarlett_master.exe"
135
136function Get-FirstValue {
137 param([object[]]$Candidates)
138 foreach ($c in $Candidates) { if ($c -and ([string]$c).Trim()) { return ([string]$c).Trim() } }
139 return ""
140}
141
142function Read-SideFile {
143 # One line from a text file make_game.py writes beside gta6rt.exe (game_path.txt, shader_path.txt).
144 param([string]$Path)
145 if (Test-Path -LiteralPath $Path -PathType Leaf) {
146 $line = Get-Content -LiteralPath $Path -TotalCount 1
147 if ($line) { return ([string]$line).Trim() }
148 }
149 return ""
150}
151
152function ConvertTo-ProcessArgument {
153 # Quote one argument the way the MSVC CRT splits a command line (backslashes before a quote are doubled).
154 param([string]$Value)
155 if ($Value -ne "" -and $Value -notmatch '[\s"]') { return $Value }
156 $sb = New-Object System.Text.StringBuilder
157 [void]$sb.Append('"')
158 $slashes = 0
159 foreach ($ch in $Value.ToCharArray()) {
160 if ($ch -eq '\') { $slashes++; continue }
161 if ($ch -eq '"') { [void]$sb.Append('\', 2 * $slashes + 1) } elseif ($slashes) { [void]$sb.Append('\', $slashes) }
162 $slashes = 0
163 [void]$sb.Append($ch)
164 }
165 if ($slashes) { [void]$sb.Append('\', 2 * $slashes) }
166 [void]$sb.Append('"')
167 return $sb.ToString()
168}
169
170function Test-InsideFolder {
171 param([string]$Path, [string]$Folder)
172 $p = [System.IO.Path]::GetFullPath($Path).TrimEnd('\') + '\'
173 $f = [System.IO.Path]::GetFullPath($Folder).TrimEnd('\') + '\'
174 return $p.StartsWith($f, [System.StringComparison]::OrdinalIgnoreCase)
175}
176
177function Resolve-Python {
178 param([string]$Requested)
179 if ($Requested) { return @($Requested) }
180 if (Get-Command python -ErrorAction SilentlyContinue) { return @("python") }
181 if (Get-Command py -ErrorAction SilentlyContinue) { return @("py", "-3") }
182 return @()
183}
184
185# ------------------------------------------------------------------------------------------------ paths
186
187if (-not $Name) { $Name = "boot-" + (Get-Date -Format "yyyyMMdd-HHmmss") }
188if ($NoInput) { $InputScript = "" }
189if ($Name -notmatch '^[A-Za-z0-9._-]+$') { throw "-Name may hold letters, digits, '.', '_' and '-' only: $Name" }
190
191$Runtime = Get-FirstValue @($Runtime, $env:GTA6RT, (Join-Path $RepoRoot "runtime\build\RelWithDebInfo\gta6rt.exe"))
192$RuntimeDir = Split-Path -Parent $Runtime
193$GameDir = Get-FirstValue @($GameDir, $env:LEONIDA_GAME_DIR, (Read-SideFile (Join-Path $RuntimeDir "game_path.txt")))
194$Exe = Get-FirstValue @($Exe, $env:LEONIDA_EXE, $(if ($GameDir) { Join-Path $GameDir $ExeName } else { "" }))
195$Shaders = Get-FirstValue @($Shaders, $env:LEONIDA_SHADERS)
196$OutDir = Get-FirstValue @($OutDir, $env:LEONIDA_RUNS, (Join-Path $HOME "leonida-runs"))
197$OutDir = [System.IO.Path]::GetFullPath($OutDir)
198$Overlay = Get-FirstValue @($Overlay, (Join-Path $OutDir "overlay"))
199$Capture = Join-Path $OutDir ("cap_" + $Name)
200$LogFile = Join-Path $OutDir ($Name + ".log")
201$StdoutFile = Join-Path $OutDir ($Name + ".stdout.log")
202$TraceFile = Join-Path $OutDir ($Name + ".jsonl")
203$SummaryFile = Join-Path $OutDir ($Name + ".summary.txt")
204$DigestFile = Join-Path $OutDir ($Name + ".digest.txt")
205
206$problems = New-Object System.Collections.Generic.List[string]
207if (Test-InsideFolder $OutDir $RepoRoot) { $problems.Add("-OutDir $OutDir is inside the repository; logs and captures must stay outside it") }
208if (-not (Test-Path -LiteralPath $Runtime -PathType Leaf)) { $problems.Add("no gta6rt.exe at $Runtime (build it, or pass -Runtime / set GTA6RT)") }
209elseif (-not (Test-Path -LiteralPath (Join-Path $RuntimeDir "gta6rt_tls_host.dll") -PathType Leaf)) {
210 $problems.Add("gta6rt_tls_host.dll is missing beside $Runtime (build the gta6rt target; without it the title exits at once)")
211}
212if (-not $GameDir) { $problems.Add("no game folder: pass -GameDir or set LEONIDA_GAME_DIR") }
213elseif (-not (Test-Path -LiteralPath (Join-Path $GameDir "MicrosoftGame.Config") -PathType Leaf)) {
214 $problems.Add("$GameDir has no MicrosoftGame.Config: -GameDir is the folder with it and the .rpf archives")
215}
216if (-not $Exe -or -not (Test-Path -LiteralPath $Exe -PathType Leaf)) { $problems.Add("no $ExeName at '$Exe' (pass -Exe)") }
217if ($Shaders) {
218 if (-not (Test-Path -LiteralPath (Join-Path $Shaders "index.json") -PathType Leaf)) {
219 $problems.Add("$Shaders has no index.json: -Shaders is <work>\shaders\spirv after make_game.py --stages check,shaders")
220 } elseif (-not (Test-Path -LiteralPath (Join-Path $Shaders "exe\index.json") -PathType Leaf)) {
221 Write-Warning "$Shaders has no exe\index.json: the title's 10 embedded shaders are missing and frames cannot draw (JOIN.md, 'The executable trap')"
222 }
223} elseif (-not (Read-SideFile (Join-Path $RuntimeDir "shader_path.txt"))) {
224 $problems.Add("no shader library: pass -Shaders <work>\shaders\spirv or set LEONIDA_SHADERS")
225}
226
227# ------------------------------------------------------------------------------------------ environment
228
229# Defaults: used only when this shell has not set the variable. They match the Linux harness (scripts/linux-boot/).
230$defaults = [ordered]@{
231 LEONIDA_D3D12 = "vulkan"
232 LEONIDA_DEVICE_TYPE = "6" # Series S identity; the runtime answers the ConsoleMode registry read with it
233 LEONIDA_ARENA_MB = "2048"
234 LEONIDA_PIPELINE_CACHE_BYTES = "4294967296"
235 LEONIDA_STARTUP_CACHE_CHECKPOINTS = "1"
236 LEONIDA_PIPELINE_CACHE_DIR = (Join-Path $OutDir "pipeline-cache")
237 LEONIDA_PEEK = "0x7446510,0x98f828c" # game state, session state (low dword)
238 LEONIDA_PEEK_SECONDS = "5"
239 LEONIDA_DEVICE_FAULT = "1" # device-loss report (VK_EXT_device_fault, checkpoints)
240 LEONIDA_CAPTURE_EVERY = "60"
241 LEONIDA_CAPTURE_LIMIT = "40"
242 DISABLE_RTSS_LAYER = "1" # third-party Vulkan overlay layers off
243 DISABLE_VULKAN_OBS_CAPTURE = "1"
244}
245if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" }
246# Per-run values: always this script's (from its parameters), whatever the shell has.
247$perRun = [ordered]@{
248 LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture })
249 LEONIDA_INPUT_SCRIPT = $InputScript
250}
251if ($Shaders) { $perRun["LEONIDA_SHADERS"] = $Shaders }
252if ($Stacks) { $perRun["LEONIDA_STACKS"] = $Stacks }
253
254$bootEnv = [ordered]@{}
255foreach ($k in $defaults.Keys) {
256 $cur = [Environment]::GetEnvironmentVariable($k)
257 if ($cur) { $bootEnv[$k] = $cur } else { $bootEnv[$k] = $defaults[$k] }
258}
259foreach ($k in $perRun.Keys) { $bootEnv[$k] = $perRun[$k] }
260# Other LEONIDA_* switches already set in this shell are passed through as they are; they are listed below.
261foreach ($item in (Get-ChildItem Env: | Where-Object { $_.Name -like "LEONIDA_*" })) {
262 if (-not $bootEnv.Contains($item.Name)) { $bootEnv[$item.Name] = $item.Value }
263}
264foreach ($k in $SetEnv.Keys) { $bootEnv[[string]$k] = [string]$SetEnv[$k] }
265foreach ($pair in $EnvPairs) {
266 if ($pair -notmatch '^([A-Za-z_][A-Za-z0-9_]*)=(.*)$') { throw "not a parameter and not KEY=VALUE: '$pair' (Get-Help $PSCommandPath -Full)" }
267 $bootEnv[$Matches[1]] = $Matches[2]
268}
269if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] }
270
271$gameArgs = @("--run", $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs
272$argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " "
273
274if (-not $DigestOnly) {
275 Write-Output "[boot] $Name ${Seconds}s repo $RepoRoot"
276 Write-Output "[boot] gta6rt $Runtime"
277 Write-Output "[boot] out $OutDir"
278 foreach ($k in $bootEnv.Keys) { if ($bootEnv[$k] -ne "") { Write-Output ("[boot] env {0}={1}" -f $k, $bootEnv[$k]) } }
279 Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine"
280}
281
282if ($DigestOnly) {
283 if (-not (Test-Path -LiteralPath $LogFile)) { Write-Output "[boot] no $LogFile to digest"; exit 2 }
284 $problems.Clear()
285}
286if ($problems.Count) {
287 foreach ($p in $problems) { Write-Output "[boot] problem: $p" }
288 if (-not $DryRun) { exit 2 }
289}
290if ($DryRun) { Write-Output "[boot] dry run: nothing launched"; exit $(if ($problems.Count) { 2 } else { 0 }) }
291
292$verdict = "digest of an earlier run (-DigestOnly)"
293$exitCode = 0
294if (-not $DigestOnly) {
295
296 # --------------------------------------------------------------------------------------------- the lock
297
298 $mutex = New-Object System.Threading.Mutex($false, "Local\LeonidaGameBoot")
299 $owned = $false
300 $saved = @{}
301 $exitCode = 0
302 try {
303 $deadline = (Get-Date).AddSeconds($LockWaitSeconds)
304 $said = $false
305 while (-not $owned) {
306 try { $owned = $mutex.WaitOne(5000) } catch [System.Threading.AbandonedMutexException] { $owned = $true }
307 if ($owned -and (Get-Process -Name gta6rt -ErrorAction SilentlyContinue)) {
308 # A game started by hand or by another script that does not take this lock: wait for it too.
309 $mutex.ReleaseMutex(); $owned = $false; Start-Sleep -Seconds 5
310 }
311 if (-not $owned) {
312 if (-not $said) { Write-Output "[boot] waiting: another game process is running (one at a time)"; $said = $true }
313 if ((Get-Date) -gt $deadline) { Write-Output "[boot] gave up waiting after $LockWaitSeconds s"; exit 3 }
314 }
315 }
316
317 foreach ($d in @($OutDir, $Overlay)) { New-Item -ItemType Directory -Force -Path $d | Out-Null }
318 if ($bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]) {
319 New-Item -ItemType Directory -Force -Path $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"] | Out-Null
320 }
321 if ($bootEnv["LEONIDA_CAPTURE"]) {
322 # A capture folder reused by the same -Name: drop the earlier run's frames and index, nothing else.
323 New-Item -ItemType Directory -Force -Path $Capture | Out-Null
324 Get-ChildItem -LiteralPath $Capture -File | Where-Object { $_.Name -like "frame_*.ppm" -or $_.Name -like "*index.txt" } |
325 Remove-Item -Force -Confirm:$false
326 }
327 foreach ($f in @($LogFile, $StdoutFile, $TraceFile, $SummaryFile, $DigestFile)) {
328 if (Test-Path -LiteralPath $f) { Remove-Item -LiteralPath $f -Force -Confirm:$false }
329 }
330
331 foreach ($k in $bootEnv.Keys) {
332 $saved[$k] = [Environment]::GetEnvironmentVariable($k)
333 $v = $bootEnv[$k]; if ($v -eq "") { $v = $null }
334 [Environment]::SetEnvironmentVariable($k, $v)
335 }
336
337 # ------------------------------------------------------------------------------------------- the boot
338 $started = Get-Date
339 $proc = Start-Process -FilePath $Runtime -ArgumentList $argLine -WorkingDirectory $RepoRoot -NoNewWindow -PassThru `
340 -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile
341 $handle = $proc.Handle # keeps the exit code readable after the process ends
342 $stopped = $false
343 if (-not $proc.WaitForExit($Seconds * 1000)) {
344 $stopped = $true
345 try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { }
346 [void]$proc.WaitForExit(20000)
347 }
348 $ran = [int]((Get-Date) - $started).TotalSeconds
349 $rc = $null
350 try { $rc = $proc.ExitCode } catch { }
351 if ($stopped) { $verdict = "ran its full time limit ($ran s), stopped"; $exitCode = 0 }
352 elseif ($rc -eq $null) { $verdict = "exited by itself after $ran s, exit code unknown"; $exitCode = 1 }
353 else { $verdict = ("exited by itself after {0} s, exit code {1} (0x{2:x8})" -f $ran, $rc, ([int64]$rc -band 0xffffffffL)); $exitCode = [int]$rc }
354 } finally {
355 foreach ($k in $saved.Keys) { [Environment]::SetEnvironmentVariable($k, $saved[$k]) }
356 if ($owned) { $mutex.ReleaseMutex() }
357 $mutex.Dispose()
358 }
359}
360
361# -------------------------------------------------------------------------------------------- the digest
362
363$py = @(Resolve-Python $Python)
364if ($py.Count) {
365 $pyArgs = @()
366 if ($py.Count -gt 1) { $pyArgs += $py[1..($py.Count - 1)] }
367 $pyArgs += @("-I", (Join-Path $RepoRoot "tools\boot_trace.py"), $TraceFile, "--d3d12", $LogFile)
368 # Windows PowerShell 5.1 turns a native program's stderr into error records; with "Stop" that would end the script.
369 $ErrorActionPreference = "Continue"
370 & $py[0] @pyArgs 2>&1 | ForEach-Object { "$_" } | Out-File -FilePath $SummaryFile -Encoding utf8
371 $ErrorActionPreference = "Stop"
372} else {
373 "no python found for tools/boot_trace.py" | Out-File -FilePath $SummaryFile -Encoding utf8
374}
375
376$peekRx = [regex]'\[rt\] peek t=(\d+)s:(.*)$'
377$valRx = [regex]'0x([0-9a-f]+)=([0-9a-f?]+)'
378$states = New-Object System.Collections.Generic.List[string]
379$lastPeek = ""; $prevPair = ""
380$presentOk = 0; $presentFailed = 0; $presses = 0
381$shaderLine = ""; $faults = New-Object System.Collections.Generic.List[string]
382$wrapped = 0
383if (Test-Path -LiteralPath $LogFile) {
384 foreach ($line in [System.IO.File]::ReadLines($LogFile)) {
385 if ($line.Contains("XboxPresentation::PresentX")) {
386 if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ }
387 continue
388 }
389 if ($line.Contains("[rt] peek t=")) {
390 $m = $peekRx.Match($line)
391 if ($m.Success) {
392 $lastPeek = $line.Substring($line.IndexOf("[rt] peek"))
393 $game = "?"; $session = "?"
394 foreach ($v in $valRx.Matches($m.Groups[2].Value)) {
395 $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value
396 if ($rva -eq "7446510") { $game = $val }
397 elseif ($rva -eq "98f828c" -and $val -ne "?") {
398 $low = $val.PadLeft(16, '0').Substring(8).TrimStart('0') # the session state is the low dword
399 $session = $(if ($low) { $low } else { "0" })
400 }
401 }
402 $pair = "game=$game session=$session"
403 if ($pair -ne $prevPair) { $states.Add("t=$($m.Groups[1].Value)s $pair"); $prevPair = $pair }
404 }
405 continue
406 }
407 if ($line.Contains("[rt] gameinput: press ")) {
408 # Buttons only: with the keyboard pad, mouse movement is logged as right-stick presses (rsup, rsdown...).
409 if ($line -notmatch 'gameinput: press [lr]s') { $presses++ }
410 continue
411 }
412 if ($line.Contains("[rt] device-fault:") -and -not $line.Contains("device-fault: enabled")) { if ($faults.Count -lt 8) { $faults.Add($line.Trim()) }; continue }
413 if ($line.Contains("VK_ERROR_DEVICE_LOST") -and $faults.Count -lt 8) { $faults.Add($line.Trim()); continue }
414 if (-not $shaderLine -and $line.Contains(" translated shaders (")) { $shaderLine = $line.Substring([Math]::Max(0, $line.IndexOf("[rt]"))).Trim() }
415 if ($line.Contains("wrapped V#")) { $wrapped++ }
416 }
417}
418
419$capText = "no captures"
420$capIndex = Join-Path $Capture "index.txt"
421if (Test-Path -LiteralPath $capIndex) {
422 $frames = 0; $nonBlack = 0; $last = ""; $maxSum = -1.0; $maxText = ""
423 $meanRx = [regex]'mean rgb ([0-9.]+) ([0-9.]+) ([0-9.]+)'
424 foreach ($line in [System.IO.File]::ReadLines($capIndex)) {
425 $m = $meanRx.Match($line)
426 if (-not $m.Success) { continue }
427 $frames++
428 $r = [double]::Parse($m.Groups[1].Value, [Globalization.CultureInfo]::InvariantCulture)
429 $g = [double]::Parse($m.Groups[2].Value, [Globalization.CultureInfo]::InvariantCulture)
430 $b = [double]::Parse($m.Groups[3].Value, [Globalization.CultureInfo]::InvariantCulture)
431 $sum = $r + $g + $b
432 if ($sum -gt 0) { $nonBlack++ }
433 $last = "$($m.Groups[1].Value) $($m.Groups[2].Value) $($m.Groups[3].Value)"
434 if ($sum -gt $maxSum) { $maxSum = $sum; $maxText = $last }
435 }
436 $capText = "$frames captured, $nonBlack non-black; last mean rgb $last; brightest $maxText"
437}
438
439$digest = New-Object System.Collections.Generic.List[string]
440$digest.Add("== boot ${Name}: $verdict")
441$digest.Add("shaders: $(if ($shaderLine) { $shaderLine } else { 'no translated-shaders line (Vulkan device not reached?)' })")
442$digest.Add("states: $(if ($states.Count) { $states -join ' | ' } else { 'no peek lines' })")
443$digest.Add("presents: PresentX ok $presentOk, failed $presentFailed")
444$digest.Add("input: $presses presses logged")
445$digest.Add("faults: $(if ($faults.Count) { $faults.Count.ToString() + ' device-fault lines' } else { 'none' })")
446foreach ($f in $faults) { $digest.Add(" $f") }
447if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") }
448$digest.Add("frames: $capText")
449$digest.Add("files: $LogFile, $TraceFile, $SummaryFile")
450$digest | Out-File -FilePath $DigestFile -Encoding utf8
451$digest
452if ($SummaryLines -gt 0 -and (Test-Path -LiteralPath $SummaryFile)) {
453 Write-Output "-- boot_trace.py (first $SummaryLines lines of $SummaryFile)"
454 Get-Content -LiteralPath $SummaryFile -TotalCount $SummaryLines
455}
456exit $exitCode