upleb.uk

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

summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authorxel1uz <hampus.robertsson@gmail.com>2026-11-25 05:27:31 +0100
committerGitHub <noreply@github.com>2026-11-25 05:27:31 +0100
commit89b4e9edf28ff76e0ed57dae8e2adbc4a00f381d (patch)
treef4eb49f4343bb38abda353a727741800b636e1d6 /scripts
parent1548519aee782ec75868625d58b54f04152220bb (diff)
parentc7e82e26eadeac237da66949b64e7a52b718361e (diff)
Merge branch 'ubiquitarianism:main' into fix/glb-inspect-morph-weight-count
Diffstat (limited to 'scripts')
-rw-r--r--scripts/build_runtime.ps16
-rw-r--r--scripts/check_no_game_data.py1
-rwxr-xr-xscripts/linux-boot/boot-digest.sh75
-rwxr-xr-xscripts/linux-boot/boot-inner.sh45
-rwxr-xr-xscripts/linux-boot/boot.sh42
-rwxr-xr-xscripts/linux-boot/configure-worktree.sh9
-rwxr-xr-xscripts/linux-boot/run-boot.sh56
-rw-r--r--scripts/merge_check.py6
-rw-r--r--scripts/run_gpu_tests.py36
-rw-r--r--scripts/translate_pipeline_compute.py174
-rw-r--r--scripts/windows-boot/README.md93
-rw-r--r--scripts/windows-boot/boot.ps1456
12 files changed, 979 insertions, 20 deletions
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index f24cc073f..733d2c041 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -86,14 +86,16 @@ $build || exit /b 1
86 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it." 86 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it."
87 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" 87 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue"
88 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } 88 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" }
89 $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } 89 $files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_pso_stream.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" }
90 $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" 90 $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`""
91 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } 91 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" }
92 $body = @" 92 $body = @"
93cd /d "$out" || exit /b 1 93cd /d "$out" || exit /b 1
94rem BUILD-1457: a game thread with the default stack size gets this program's reserve, and drivers compile on it. The same number as in CMakeLists.txt. 94rem BUILD-1457: a game thread with the default stack size gets this program's reserve, and drivers compile on it. The same number as in CMakeLists.txt.
95rem Keep the host base in step with runtime\CMakeLists.txt GTA6RT_HOST_BASE. 95rem Keep the host base in step with runtime\CMakeLists.txt GTA6RT_HOST_BASE.
96cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF /BASE:0x10000000000 /STACK:8388608 psapi.lib ole32.lib || exit /b 1 96python -I "$root\tools\gen_bcpack_runtime_tables.py" "bcpack_tables.inc" || exit /b 1
97cl /nologo /std:c++20 /EHsc /O2 /I "." "$root\tools\bcpack_history_train.cpp" /Fe:bcpack_history_train.exe || exit /b 1
98cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE /I "." $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF /BASE:0x10000000000 /STACK:8388608 psapi.lib ole32.lib || exit /b 1
97cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /MT /DWIN32_LEAN_AND_MEAN /DNOMINMAX "$src\src\tls_host.cpp" /LD /Fe:gta6rt_tls_host.dll || exit /b 1 99cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /MT /DWIN32_LEAN_AND_MEAN /DNOMINMAX "$src\src\tls_host.cpp" /LD /Fe:gta6rt_tls_host.dll || exit /b 1
98cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1 100cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1
99cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1 101cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py
index bccee5e68..ae3d06e77 100644
--- a/scripts/check_no_game_data.py
+++ b/scripts/check_no_game_data.py
@@ -42,6 +42,7 @@ MAGICS = (
42 ("RPF9 archive", 0, b"9FPR"), 42 ("RPF9 archive", 0, b"9FPR"),
43 ("RPF9 archive", 0, b"RPF9"), 43 ("RPF9 archive", 0, b"RPF9"),
44 ("TTPF texture pool", 0, b"TTPF"), 44 ("TTPF texture pool", 0, b"TTPF"),
45 ("local BCPack predictor profile", 0, b"BCPHIST1"),
45 ("RAGE resource", 0, b"RSC7"), 46 ("RAGE resource", 0, b"RSC7"),
46 ("RAGE resource", 0, b"RSC8"), 47 ("RAGE resource", 0, b"RSC8"),
47 ("RAGE resource", 0, b"RSCC"), 48 ("RAGE resource", 0, b"RSCC"),
diff --git a/scripts/linux-boot/boot-digest.sh b/scripts/linux-boot/boot-digest.sh
new file mode 100755
index 000000000..dd2289e30
--- /dev/null
+++ b/scripts/linux-boot/boot-digest.sh
@@ -0,0 +1,75 @@
1#!/bin/bash
2# ExecStopPost of a leonida-boot-* unit: runs after the boot ends however it ended (exit, crash, oomd kill, timeout).
3# Writes /opt/leonida/work/<agent>/boot-<n>.digest.txt and appends a line to /opt/leonida/work/boots.tsv.
4# Local only: digests quote trace lines, so they never go into commits or PRs.
5set -u
6AGENT=$1; N=$2; WORK=/opt/leonida/work/$AGENT; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv
7META=$WORK/boot-$N.meta; OUT=$WORK/boot-$N.digest.txt; LEDGER=/opt/leonida/work/boots.tsv
8START=$(sed -n 's/^start_epoch=//p' "$META" 2>/dev/null); BOOT=$(sed -n 's/^boot_epoch=//p' "$META" 2>/dev/null)
9START=${START:-$(date +%s)}; BOOT=${BOOT:-$START}; END=$(date +%s)
10RESULT=${SERVICE_RESULT:-?}; ECODE=${EXIT_CODE:-?}; ESTAT=${EXIT_STATUS:-?}
11D3D=$(grep -o 'd3d12=[^ ]*' "$LOG" 2>/dev/null | tail -1 | cut -d= -f2)
12STDOUT=${D3D/d3d12-run-/stdout-run-}
13CAP=/opt/leonida/capture/$AGENT-$N
14
15verdict=OK
16# systemd-oomd can kill the unit's processes without the unit ending in "oom-kill" (boot.sh then exits on its own).
17if journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -q 'systemd-oomd killed'; then RESULT=oom-kill; fi
18case "$RESULT" in
19 oom-kill) verdict="KILLED BY OOM (systemd-oomd or kernel): memory, not a crash" ;;
20 timeout) verdict="TIMEOUT" ;;
21 exit-code) verdict="EXITED WITH ERROR (code $ECODE status $ESTAT)" ;;
22 signal|core-dump) verdict="KILLED BY SIGNAL ($ESTAT)" ;;
23 success) verdict="OK (ran to its time limit or exited cleanly)" ;;
24esac
25grep -q 'time limit reached' "$LOG" 2>/dev/null && [ "$RESULT" = success ] && verdict="OK (ran its full time limit)"
26
27cnt() { local c=0; [ -f "$D3D" ] && c=$(grep -a -c -E "$@" "$D3D"); echo "${c:-0}"; }
28{
29 echo "== leonida boot $AGENT-$N: $verdict"
30 echo "unit result=$RESULT exit_code=$ECODE exit_status=$ESTAT"
31 echo "queued $((BOOT-START)) s, ran $((END-BOOT)) s; trace $D3D"
32 sed -n '/^LEONIDA_\|^WINEDEBUG\|^unit=/p' "$META" 2>/dev/null | tr '\n' ' '; echo
33 echo
34 echo "-- counts"
35 echo "PresentX ok $(cnt 'XboxPresentation::PresentX ok') refused $(cnt 'XboxPresentation::PresentX failed')"
36 echo "CreatePipelineState failed $(cnt 'CreatePipelineState failed') FSPX compute misses $(cnt 'no translated compute shader for FSPX') slot-67 failed $(cnt 'slot 67 call .* failed')"
37 echo "E_NOTIMPL $(cnt 'E_NOTIMPL') wine err: lines $(cnt '^[0-9a-f]{4}:err:|:err:') exceptions $(cnt -i 'exception|unhandled|page fault|access violation')"
38 grep -a -m1 -E 'translated shaders \(' "$D3D" 2>/dev/null
39 grep -a 'present-probe: source frame .* via' "$D3D" 2>/dev/null | tail -1 | sed 's/.*via/source via/' | cut -c1-120
40 echo
41 echo "-- frames (swapchain; then the title's own backbuffer when LEONIDA_CAPTURE_SOURCE=1)"
42 [ -f "$CAP/index.txt" ] && { echo "$(wc -l < "$CAP/index.txt") captured; last: $(tail -1 "$CAP/index.txt" | cut -c1-110)"; awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print n+0 " of " NR " frames non-black"}' "$CAP/index.txt"; } || echo "no capture index"
43 grep -a 'present-probe: source frame .* mean' "$D3D" 2>/dev/null | tail -2 | sed 's/.*source frame/source frame/' | cut -c1-140
44 echo
45 echo "-- resources (2 s samples)"
46 [ -s "$RES" ] && awk -F'\t' 'NR>1{ if(min==""||$2<min)min=$2; if($3>sw)sw=$3; if($4>um)um=$4; if($5>us)us=$5; if($6+0>gm)gm=$6 } END{printf "min RAM available %s MB, max swap used %s MB, game peak %s MB RAM + %s MB swap, VRAM peak %s MB\n",min,sw,um,us,gm}' "$RES" || echo "no samples"
47 journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -E 'Consumed|oom|Failed' | sed 's/^.*\]: //' | sort -u | cut -c1-200
48 # Compare with other boots instead of guessing: on the console (Series S) path the title itself grows to ~20 GB of
49 # RAM+swap by ~130 s (fsdraw-6: 9.9 GB + 11.2 GB), mostly zero pages that zram compresses well.
50 [ -s "$RES" ] && awk -F'\t' 'NR>1{t=$4+$5; if(t>m)m=t} END{printf "game peak RAM+swap %.1f GB (console-path baseline ~20 GB at 130 s; oomd kills when zram swap passes 98%%)\n", m/1024}' "$RES"
51 echo
52 echo "-- system events during the boot (OOM, GPU Xid, segfaults)"
53 { journalctl --since "@$BOOT" -q --no-pager 2>/dev/null | grep -i -E 'systemd-oomd.*(Marked|killed)|oom-kill|out of memory|NVRM: Xid|segfault|gta6rt|wineserver.*crash' ; } | cut -c1-200 | tail -15
54 echo
55 echo "-- distinct error lines (normalised, with counts; top 60)"
56 for f in "$D3D" "$STDOUT"; do [ -f "$f" ] && cat "$f"; done 2>/dev/null \
57 | grep -a -i -E 'error|fail|E_NOTIMPL|E_INVALIDARG|E_FAIL|0x8[0-9a-f]{7}|exception|assert|abort|unhandled|page fault|refused|not implemented|no translated|no emulation|crash|:err:|fatal|cannot|could not|unsupported|invalid' \
58 | grep -a -v -E ' ok$| called$' \
59 | sed -E 's/#[0-9]+/#N/g; s/0x[0-9a-fA-F]{6,}/0xADDR/g; s/\b[0-9a-f]{64}\b/SHA/g; s/[0-9]{4,}/NUM/g; s/^[0-9a-f]{4}:/TID:/' \
60 | cut -c1-220 | sort | uniq -c | sort -rn | head -60
61 echo
62 echo "-- where the trace ended"
63 [ -f "$D3D" ] && tail -n 8 "$D3D" | cut -c1-200
64} > "$OUT" 2>&1
65
66frames=$( [ -f "$CAP/index.txt" ] && awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print (n+0) "/" NR}' "$CAP/index.txt" || echo "-")
67peak=$( [ -s "$RES" ] && awk -F'\t' 'NR>1{if($4>u)u=$4} END{print u+0}' "$RES" || echo "-")
68exec 7>>"$LEDGER"; flock 7
69# Both the unit's ExecStopPost and the outer wrapper call this; the first one to finish records the boot.
70grep -q -P "^[^\t]*\t$AGENT\t$N\t" "$LEDGER" 2>/dev/null && exit 0
71[ -s "$LEDGER" ] || printf 'end\tagent\tn\tresult\tran_s\tpresentx_ok\tpso_failed\tfspx_miss\tnonblack_frames\tpeak_mb\tgta6rt\n' >&7
72printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%F %T')" "$AGENT" "$N" "$RESULT" "$((END-BOOT))" \
73 "$(cnt 'XboxPresentation::PresentX ok')" "$(cnt 'CreatePipelineState failed')" "$(cnt 'no translated compute shader for FSPX')" \
74 "$frames" "$peak" "$(sed -n 's/^unit=.*gta6rt=\([^ ]*\).*/\1/p' "$META")" >&7
75exit 0
diff --git a/scripts/linux-boot/boot-inner.sh b/scripts/linux-boot/boot-inner.sh
new file mode 100755
index 000000000..e52d3daef
--- /dev/null
+++ b/scripts/linux-boot/boot-inner.sh
@@ -0,0 +1,45 @@
1#!/bin/bash
2# Runs inside the leonida-boot-* unit (see run-boot.sh). Waits for memory, takes the locks, samples resources, boots.
3set -u
4WORK=/opt/leonida/work/$BOOT_AGENT; N=$BOOT_N; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv
5META=$WORK/boot-$N.meta
6: > "$LOG"
7echo "start_epoch=$(date +%s)" > "$META"
8echo "unit=leonida-boot-$BOOT_AGENT-$N gta6rt=$GTA6RT secs=$BOOT_SECS" >> "$META"
9env | grep -E '^(LEONIDA_|WINEDEBUG=)' | sort >> "$META"
10
11mem_free_mb() { # RAM available plus a third of free zram swap (zram pages cost RAM, roughly 3:1)
12 awk '/^MemAvailable:/{a=$2} /^SwapFree:/{s=$2} END{printf "%d", (a + s/3)/1024}' /proc/meminfo
13}
14NEED=${LEONIDA_BOOT_MIN_FREE_MB:-6500}
15swap_pct() { awk '/^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{printf "%d", t ? (t-f)*100/t : 0}' /proc/meminfo; }
16
17exec 8>/opt/leonida/.gpu.lock; flock 8 # one boot at a time
18echo "[run-boot] $(date +%T) got the GPU lock" >> "$LOG"
19for i in $(seq 1 40); do # up to 10 min for memory headroom
20 f=$(mem_free_mb); sp=$(swap_pct); [ "$f" -ge "$NEED" ] && [ "$sp" -lt 70 ] && break
21 echo "[run-boot] $(date +%T) waiting for memory: ${f} MB free (need ${NEED}), swap ${sp}% (need < 70%)" >> "$LOG"; sleep 15
22done
23echo "[run-boot] $(date +%T) memory before boot: $(mem_free_mb) MB free, swap $(swap_pct)%" >> "$LOG"
24exec 9>/opt/leonida/.build.lock; flock 9 # no compiles while the game runs
25echo "[run-boot] $(date +%T) got the build lock; booting" >> "$LOG"
26echo "boot_epoch=$(date +%s)" >> "$META"
27
28CG=/sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)
29( printf 'time\tmem_avail_mb\tswap_used_mb\tunit_mem_mb\tunit_swap_mb\tgpu_mem_mb\tgpu_util\n'
30 while :; do
31 read -r ma su < <(awk '/^MemAvailable:/{a=$2} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{print int(a/1024), int((t-f)/1024)}' /proc/meminfo)
32 um=$(( $(cat "$CG/memory.current" 2>/dev/null || echo 0) / 1048576 )); us=$(( $(cat "$CG/memory.swap.current" 2>/dev/null || echo 0) / 1048576 ))
33 g=$(nvidia-smi --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | tr -d ' ' | tr ',' '\t')
34 printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%T)" "$ma" "$su" "$um" "$us" "${g:-? ?}"
35 sleep 2
36 done ) > "$RES" 2>/dev/null &
37SAMPLER=$!
38
39/opt/leonida/boot.sh run "$BOOT_SECS" >> "$LOG" 2>&1
40rc=$?
41kill $SAMPLER 2>/dev/null
42echo "[run-boot] $(date +%T) boot.sh exit $rc" >> "$LOG"
43# boot.sh stops the title with timeout(1) at the time limit: 124 means it ran the whole time, which is success here.
44[ "$rc" = 124 ] && { echo "[run-boot] time limit reached" >> "$LOG"; rc=0; }
45exit $rc
diff --git a/scripts/linux-boot/boot.sh b/scripts/linux-boot/boot.sh
new file mode 100755
index 000000000..55f84f019
--- /dev/null
+++ b/scripts/linux-boot/boot.sh
@@ -0,0 +1,42 @@
1#!/bin/bash
2# Boot the packaged port under Wine with the network off (unshare -rn: user + network namespace, no root).
3# usage: boot.sh dry-run|init|run [seconds] (run defaults to 150 s, then the title is stopped)
4# Traces stay local in /opt/leonida/traces: they can quote game data, never post them.
5set -u
6MODE=${1:?dry-run|init|run}; SECS=${2:-150}
7OUT=/opt/leonida
8REPO=${LEONIDA_REPO:-$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)} # the checkout this script is in
9STAMP=$(date +%H%M%S)
10T=$OUT/traces; mkdir -p "$T" "$OUT/overlay" "$OUT/cache/nv"
11
12WINE=${WINE:-wine} # e.g. WINE=".../Proton - Experimental/files/bin/wine" WINEPREFIX=~/.local/share/leonida-proton/pfx
13export WINEPREFIX=${WINEPREFIX:-$HOME/.local/share/leonida-wine} WINEDEBUG=${WINEDEBUG:--all} WINEDLLOVERRIDES="mscoree,mshtml="
14export LEONIDA_D3D12=vulkan
15export LEONIDA_SHADERS=$OUT/work/shaders/spirv
16export LEONIDA_ARENA_MB=${LEONIDA_ARENA_MB:-2048}
17export LEONIDA_PIPELINE_CACHE_BYTES=${LEONIDA_PIPELINE_CACHE_BYTES:-4294967296}
18export LEONIDA_STARTUP_CACHE_CHECKPOINTS=1
19export __GL_SHADER_DISK_CACHE=1 __GL_SHADER_DISK_CACHE_PATH=$OUT/cache/nv __GL_SHADER_DISK_CACHE_SIZE=21474836480
20export __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1
21[ -n "${SKIP_INT3:-}" ] && export LEONIDA_SKIP_INT3=1
22
23GAME_WIN='Z:\opt\gta6\GTA6.Xbox.v1.0.2.1'
24EXE=/opt/gta6/GTA6.Xbox.v1.0.2.1/game_scarlett_master.exe
25TRACE_WIN="Z:\\opt\\leonida\\traces\\boot-$MODE-$STAMP.jsonl"
26D3D=$T/d3d12-$MODE-$STAMP.log
27GTA6RT=${GTA6RT:-$OUT/gta6rt.exe}; [ -f "$GTA6RT" ] || GTA6RT=$REPO/runtime/build/boot/gta6rt.exe # GTA6RT=<your build>/gta6rt.exe boots a private build without installing it
28
29args=(--"$MODE" "$EXE" --game-dir "$GAME_WIN" --overlay 'Z:\opt\leonida\overlay' --trace "$TRACE_WIN")
30[ "$MODE" = run ] && args+=(--trace-d3d12)
31echo "[boot] $MODE gta6rt=$GTA6RT trace=$T/boot-$MODE-$STAMP.jsonl d3d12=$D3D"
32# unshare: new user + network namespace, so the title has no network at all
33if [ "$MODE" = run ]; then
34 timeout --signal=INT --kill-after=20 "$SECS" unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D"
35else
36 unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D"
37fi
38rc=$?; echo "[boot] exit=$rc"
39sleep 0
40python3 -I "$REPO/tools/boot_trace.py" "$T/boot-$MODE-$STAMP.jsonl" --d3d12 "$D3D" > "$T/summary-$MODE-$STAMP.txt" 2>&1
41echo "[boot] summary: $T/summary-$MODE-$STAMP.txt"
42exit $rc
diff --git a/scripts/linux-boot/configure-worktree.sh b/scripts/linux-boot/configure-worktree.sh
new file mode 100755
index 000000000..c983b3357
--- /dev/null
+++ b/scripts/linux-boot/configure-worktree.sh
@@ -0,0 +1,9 @@
1#!/bin/bash
2# usage: configure-worktree.sh <worktree>
3# Configures a Windows build of the runtime on Linux with clang-cl and an xwin SDK (XWIN_DIR, default
4# ~/.local/share/xwin-sdk). SDL3_SRC=<an SDL3 source tree> makes the configure work offline.
5set -eu; W=$(realpath "$1")
6cmake -S "$W/runtime" -B "$W/runtime/build/boot" -G Ninja -DCMAKE_BUILD_TYPE=Release \
7 -DCMAKE_TOOLCHAIN_FILE="$W/runtime/cmake/clang-cl-xwin.cmake" -DXWIN_DIR="${XWIN_DIR:-$HOME/.local/share/xwin-sdk}" \
8 -DLEONIDA_BUILD_WINDOWS_RUNTIME=ON -DLEONIDA_SDL3=ON \
9 ${SDL3_SRC:+-DFETCHCONTENT_SOURCE_DIR_SDL3="$SDL3_SRC"}
diff --git a/scripts/linux-boot/run-boot.sh b/scripts/linux-boot/run-boot.sh
new file mode 100755
index 000000000..523d17795
--- /dev/null
+++ b/scripts/linux-boot/run-boot.sh
@@ -0,0 +1,56 @@
1#!/bin/bash
2# Boot gta6rt as its own systemd --user unit, protected from the swarm and logged in full.
3#
4# usage: run-boot.sh <agent> <n> <gta6rt.exe> [seconds=150] [KEY=VALUE ...]
5# e.g. run-boot.sh fsdraw 3 /path/wt-fsdraw/runtime/build/boot/gta6rt.exe 150 LEONIDA_FOO=1
6#
7# What it does for you:
8# - runs the boot outside your agent's process tree (survives agent/session restarts);
9# - waits for memory headroom before starting, then holds the GPU lock AND the build lock for the whole boot,
10# so no compile competes with the game for RAM;
11# - Series S profile, late-frame capture, source capture and Wine's error channel on by default (override with KEY=VALUE);
12# - samples RAM / swap / the game's memory / VRAM every 2 s;
13# - after the boot, even when systemd-oomd or a crash kills it, writes a digest with the unit result, OOM and GPU
14# kernel events and every distinct error line, and appends one line to the shared ledger /opt/leonida/work/boots.tsv.
15#
16# Outputs (in /opt/leonida/work/<agent>/): boot-<n>.log boot-<n>.resources.tsv boot-<n>.digest.txt
17set -u
18AGENT=${1:?agent}; N=${2:?n}; EXE=${3:?gta6rt.exe}; SECS=${4:-150}; shift $(( $# >= 4 ? 4 : $# ))
19[ -f "$EXE" ] || { echo "run-boot: no such gta6rt: $EXE" >&2; exit 2; }
20# gta6rt loads gta6rt_tls_host.dll from its own folder; without it the title gets no module TLS index and exits at once.
21[ -f "$(dirname "$EXE")/gta6rt_tls_host.dll" ] || { echo "run-boot: $(dirname "$EXE")/gta6rt_tls_host.dll is missing: copy it next to the exe (build it with the gta6rt target) or boot the exe from its build folder" >&2; exit 2; }
22WORK=/opt/leonida/work/$AGENT; mkdir -p "$WORK"
23UNIT=leonida-boot-$AGENT-$N
24if systemctl --user is-active --quiet "$UNIT"; then echo "run-boot: $UNIT is already running" >&2; exit 2; fi
25
26declare -A ENV=(
27 [WINE]="$HOME/.local/share/Steam/steamapps/common/Proton - Experimental/files/bin/wine"
28 [WINEPREFIX]="$HOME/.local/share/leonida-proton/pfx"
29 [WINEDEBUG]="-all,err+all"
30 [GTA6RT]="$EXE"
31 [LEONIDA_CAPTURE]="Z:\\opt\\leonida\\capture\\$AGENT-$N"
32 [LEONIDA_CAPTURE_EVERY]=4800 [LEONIDA_CAPTURE_LIMIT]=24 [LEONIDA_CAPTURE_SOURCE]=1
33 [LEONIDA_DEVICE_TYPE]=6
34 [LEONIDA_PIPELINE_CACHE_DIR]="Z:\\opt\\leonida\\cache\\pipelines"
35)
36for kv in "$@"; do ENV[${kv%%=*}]="${kv#*=}"; done
37args=()
38for k in "${!ENV[@]}"; do args+=(--setenv="$k=${ENV[$k]}"); done
39
40echo "run-boot: $UNIT starting (queues for memory headroom, the GPU lock and the build lock)"
41rm -f "$WORK/boot-$N.digest.txt"
42systemd-run --user --collect --quiet --unit="$UNIT" -p WorkingDirectory=/opt/leonida \
43 --setenv=BOOT_AGENT="$AGENT" --setenv=BOOT_N="$N" --setenv=BOOT_SECS="$SECS" "${args[@]}" \
44 /opt/leonida/boot-inner.sh || { echo "run-boot: could not start $UNIT" >&2; exit 2; }
45# The digest is written by a separate, tiny watcher unit: it survives systemd-oomd killing the boot's cgroup and the
46# caller's shell going away. It waits for the boot unit to end, reads its result from the journal and writes the digest.
47systemd-run --user --collect --quiet --unit="leonida-digest-$AGENT-$N" -p MemoryMax=256M \
48 /bin/bash -c 'while systemctl --user is-active --quiet "$0" || systemctl --user is-activating --quiet "$0"; do sleep 3; done
49 START=$(sed -n "s/^start_epoch=//p" "/opt/leonida/work/$1/boot-$2.meta" 2>/dev/null)
50 RES=$(journalctl --user -u "$0" ${START:+--since "@$START"} -q --no-pager 2>/dev/null | grep -o "Failed with result .[a-z-]*." | tail -1 | tr -d "\x27" | sed "s/Failed with result //")
51 SERVICE_RESULT=${RES:-success} exec /opt/leonida/boot-digest.sh "$1" "$2"' "$UNIT" "$AGENT" "$N"
52# Block until the digest exists (so a caller that waits on this script gets the result), then print it.
53while [ ! -s "$WORK/boot-$N.digest.txt" ] || systemctl --user is-active --quiet "leonida-digest-$AGENT-$N"; do sleep 5; done
54echo "run-boot: $UNIT finished. Digest:"
55cat "$WORK/boot-$N.digest.txt"
56head -1 "$WORK/boot-$N.digest.txt" | grep -q ': OK' && exit 0 || exit 1
diff --git a/scripts/merge_check.py b/scripts/merge_check.py
index 81bb3368a..e270cbe00 100644
--- a/scripts/merge_check.py
+++ b/scripts/merge_check.py
@@ -65,7 +65,7 @@ def _merged_pr_number(subject):
65 65
66 66
67def prior_merges(repo, main, numbers, depth): 67def prior_merges(repo, main, numbers, depth):
68 out = git(repo, "log", main, "--first-parent", f"-n{depth}", "--format=%H%x09%s").stdout 68 out = git(repo, "log", "--first-parent", f"-n{depth}", "--format=%H%x09%s", main, "--").stdout
69 hits = {number: [] for number in numbers} 69 hits = {number: [] for number in numbers}
70 for line in out.split("\n"): 70 for line in out.split("\n"):
71 sha, _, subject = line.partition("\t") 71 sha, _, subject = line.partition("\t")
@@ -113,7 +113,7 @@ def duplicates(repo, main, tree, min_length, block=3):
113 patch = git(repo, "-c", "core.quotePath=true", "diff", "--unified=0", "--no-color", "--no-renames", 113 patch = git(repo, "-c", "core.quotePath=true", "diff", "--unified=0", "--no-color", "--no-renames",
114 "--inter-hunk-context=0", "--src-prefix=a/", "--dst-prefix=b/", "--no-relative", 114 "--inter-hunk-context=0", "--src-prefix=a/", "--dst-prefix=b/", "--no-relative",
115 "--no-ext-diff", "--no-textconv", "--ignore-submodules=all", 115 "--no-ext-diff", "--no-textconv", "--ignore-submodules=all",
116 main, tree).stdout 116 main, tree, "--").stdout
117 for line in patch.split("\n"): 117 for line in patch.split("\n"):
118 if line.startswith("diff --git "): 118 if line.startswith("diff --git "):
119 path, added = None, None 119 path, added = None, None
@@ -132,7 +132,7 @@ def duplicates(repo, main, tree, min_length, block=3):
132 132
133 def windows(rev, path): 133 def windows(rev, path):
134 # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file. 134 # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file.
135 r = git(repo, "show", f"{rev}:{path}") 135 r = git(repo, "show", f"{rev}:{path}", "--")
136 lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())] 136 lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())]
137 content = [text for _, text in lines] 137 content = [text for _, text in lines]
138 return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1)) 138 return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1))
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index fef03e9c9..8ba62104d 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -25,16 +25,17 @@ sys.path.insert(0, os.path.join(ROOT, "tools"))
25import mc_command # noqa: E402 25import mc_command # noqa: E402
26sys.path.insert(0, SHADER_DIR) 26sys.path.insert(0, SHADER_DIR)
27from build import CLIP_CASES, clip_container, shader_source 27from build import CLIP_CASES, clip_container, shader_source
28from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_narrow_test, fmt_sint32_test, 28from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_narrow_test,
29 fmt_xy_xyz_test, tbuffer_store_test) 29 fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported)
30from check import compute_unsupported # vk_compute_test's exit 77 over a feature the module needs
31from compute_fixture import compute_header 30from compute_fixture import compute_header
32from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) 31from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test)
33from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, 32from check import (CS_SMEM_VCC, CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES,
34 TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, TEXTURE_CONSTANTS, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message, 33 TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, TEXTURE_CONSTANTS, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message,
35 pick_build_dir, start_failure, table_fetch_test, texture_gradient_a16_test, texture_mip_test) 34 pick_build_dir, start_failure, table_fetch_test, texture_gradient_a16_test, texture_mip_test)
36from check import SIGNED_MIP_TEST, UINT_MIP_TEST 35from check import SIGNED_MIP_TEST, UINT_MIP_TEST
37from check import cbv_modulate_test 36from check import cbv_modulate_test
37from check import IMAGE_STORE_CASES, texture_uav_test
38from check import salu_ext_test # 38 scalar ALU ops on operands seeded through VKC_SGPRS
38from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT 39from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT
39from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations 40from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations
40from check import cmp_f64_test # the 32 binary64 vector compares on memory-fed operands 41from check import cmp_f64_test # the 32 binary64 vector compares on memory-fed operands
@@ -685,7 +686,8 @@ OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_transl
685 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test", 686 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test",
686 "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test", 687 "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test",
687 "ps_live_width": "w64_graphics.py", 688 "ps_live_width": "w64_graphics.py",
688 "ps_heap_index": "d3d12_heap_index_test"} 689 "ps_heap_index": "d3d12_heap_index_test",
690 "ps_quad_flat": "d3d12_quad_index_test", "vs_quad_inst": "d3d12_quad_index_test"}
689 691
690 692
691# Shaders a selected test draws with, built even when the filter leaves them out (#192). 693# Shaders a selected test draws with, built even when the filter leaves them out (#192).
@@ -1126,6 +1128,10 @@ def run_suite(a, work: str) -> int:
1126 vals = words[:len(USER_SGPRS_WORDS)] if words else [] 1128 vals = words[:len(USER_SGPRS_WORDS)] if words else []
1127 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == USER_SGPRS_WORDS, 1129 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == USER_SGPRS_WORDS,
1128 " ".join(hex(x) for x in vals) if vals else msg)) 1130 " ".join(hex(x) for x in vals) if vals else msg))
1131 elif name == "cs_w32_salu_ext":
1132 detail = salu_ext_test(a.build, spirv_dir, cs_env)
1133 results.append((name, None if isinstance(detail, Skip) else not detail,
1134 detail or "80 words exact (73 results of 38 scalar ops and the untouched fill)"))
1129 elif name == "cs_f64_add": 1135 elif name == "cs_f64_add":
1130 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) 1136 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env)
1131 if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names 1137 if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names
@@ -1195,7 +1201,7 @@ def run_suite(a, work: str) -> int:
1195 # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none. 1201 # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none.
1196 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. 1202 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size.
1197 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) 1203 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated()))
1198 elif name in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", 1204 elif name in ("cs_smem_vcc_base", "cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half",
1199 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", 1205 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi",
1200 "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_w64", 1206 "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_w64",
1201 "cs_w64_mask_detect", 1207 "cs_w64_mask_detect",
@@ -1204,11 +1210,12 @@ def run_suite(a, work: str) -> int:
1204 "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", 1210 "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load",
1205 "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", 1211 "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent",
1206 "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", 1212 "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end",
1207 "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", 1213 "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec",
1208 "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): 1214 "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"):
1209 cs_dump_wants = { 1215 cs_dump_wants = {
1210 "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], 1216 "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000],
1211 # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone 1217 # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone
1218 "cs_smem_vcc_base": CS_SMEM_VCC,
1212 "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030, 1219 "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030,
1213 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C], 1220 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C],
1214 # SHADER-52: wave32 lane select & 31 (40 → 8) 1221 # SHADER-52: wave32 lane select & 31 (40 → 8)
@@ -1303,6 +1310,7 @@ def run_suite(a, work: str) -> int:
1303 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32], 1310 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32],
1304 "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header) 1311 "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header)
1305 "cs_w64x_saveexec_b64": [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171], # .asm header 1312 "cs_w64x_saveexec_b64": [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171], # .asm header
1313 "cs_w64x_cmp_sdst": [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5], # .asm header
1306 "cs_bpermute32": [0, 50, 162, 99, 36, 218, 183, 15], # wave32: needs 32 lanes 1314 "cs_bpermute32": [0, 50, 162, 99, 36, 218, 183, 15], # wave32: needs 32 lanes
1307 # SHADER-91: s_barrier sites in different wave-uniform branches meet (cs_barrier_divergent.asm) 1315 # SHADER-91: s_barrier sites in different wave-uniform branches meet (cs_barrier_divergent.asm)
1308 "cs_barrier_divergent": [127, 126, 125, 124, 123, 122, 121, 120], 1316 "cs_barrier_divergent": [127, 126, 125, 124, 123, 122, 121, 120],
@@ -1363,15 +1371,13 @@ def run_suite(a, work: str) -> int:
1363 unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) 1371 unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None)
1364 detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" 1372 detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)"
1365 results.append((name, ok, detail)) 1373 results.append((name, ok, detail))
1366 elif name == "cs_imgstore": 1374 elif name in IMAGE_STORE_CASES:
1367 rc, msg = run_cmd([vk_store, spv]) 1375 rc, msg = run_cmd([vk_store, spv, *IMAGE_STORE_CASES[name]])
1368 results.append((name, *helper_result(rc, msg)))
1369 elif name == "cs_imgstore_cube": # GPU-CUBE-STORE: six-layer 2D-array views at bindings 11/12/13
1370 rc, msg = run_cmd([vk_store, spv, "cube"])
1371 results.append((name, *helper_result(rc, msg)))
1372 elif name in ("cs_imgload", "cs_imgload_tfe", "cs_imgload_d16", "cs_imgload_d16_tfe", "cs_sample_lz_int_d16"):
1373 rc, msg = run_cmd([vk_store, spv, "load" if name in ("cs_imgload", "cs_imgload_tfe") else "load-d16"])
1374 results.append((name, *helper_result(rc, msg))) 1376 results.append((name, *helper_result(rc, msg)))
1377 elif name == "cs_texture_uav":
1378 problem = texture_uav_test(a.build, spv)
1379 results.append((name, None if isinstance(problem, Skip) else not problem,
1380 problem or "D3D12/Vulkan storage-image readback matched"))
1375 elif name in MIP_TEST_PASSES: 1381 elif name in MIP_TEST_PASSES:
1376 problem = texture_mip_test(a.build, spirv_dir, name) 1382 problem = texture_mip_test(a.build, spirv_dir, name)
1377 ok = None if isinstance(problem, Skip) else not problem 1383 ok = None if isinstance(problem, Skip) else not problem
diff --git a/scripts/translate_pipeline_compute.py b/scripts/translate_pipeline_compute.py
new file mode 100644
index 000000000..4e691110b
--- /dev/null
+++ b/scripts/translate_pipeline_compute.py
@@ -0,0 +1,174 @@
1"""Build an interrupted or new pipeline compute pack from shader_library.py output (Linux).
2
3Two translation processes, including the parent, each run at most one SPIRV-Tools process.
4Validated modules and their receipts survive interruption. The runtime index is published last.
5"""
6import argparse
7import fcntl
8import hashlib
9import json
10import os
11import resource
12import shutil
13import sys
14import tempfile
15from pathlib import Path
16
17ROOT = Path(__file__).resolve().parents[1]
18sys.path[:0] = [str(ROOT / "tools"), str(ROOT)]
19from make_game import file_sha256 as digest, translation_sources_digest
20import rdna2spirv as translator
21
22
23def build_one(src, out, name, settings, compact=False):
24 listing = src / "disasm" / (name + ".s")
25 side = src / "fspx" / name
26 code, state = (Path(str(side) + suffix) for suffix in (".code", ".state"))
27 code_key, state_key = digest(code), digest(state)
28 container = src / (name + ".dxbc")
29 inputs = [settings, name, code_key, state_key, digest(listing), digest(Path(str(side) + ".json")),
30 digest(container) if container.is_file() else None]
31 key = hashlib.sha256(json.dumps(inputs).encode()).hexdigest()
32 receipt = out / ".compute-cache" / (key + ".json")
33 if receipt.exists():
34 try:
35 row = json.loads(receipt.read_text(encoding="utf-8"))
36 if (row["meta"]["fspx_code_sha256"], row["meta"]["fspx_state_sha256"]) == (code_key, state_key):
37 module_hash = row["module"]
38 if len(module_hash) == 64 and all(c in "0123456789abcdef" for c in module_hash):
39 if digest(out / (name + "_" + module_hash + ".spv")) == module_hash:
40 return row
41 except (OSError, ValueError, KeyError, TypeError):
42 pass
43
44 asm = translator.translate(str(listing))
45 with tempfile.TemporaryDirectory(dir=out / ".compute-cache") as tmp:
46 sa, sv = Path(tmp) / "module.spvasm", Path(tmp) / "module.spv"
47 sa.write_text(asm, encoding="utf-8", newline="\n")
48 result = translator.assemble_spirv(str(sa), str(sv), asm_text=asm, compact=compact)
49 if result.returncode:
50 raise translator.Unsupported((result.stderr.splitlines() or ["SPIR-V tool failed"])[0])
51 meta = translator.shader_meta(translator.translate.last_gen, asm, src_path=str(listing))
52 if (meta.get("stage"), meta.get("fspx_code_sha256"), meta.get("fspx_state_sha256")) != (
53 "cs", code_key, state_key):
54 raise ValueError("compute stage or FSPX identity mismatch")
55 module_hash = digest(sv)
56 sv.replace(out / (name + "_" + module_hash + ".spv"))
57 row = {"meta": meta, "module": module_hash}
58 translator.write_index(str(receipt), row)
59 return row
60
61
62def build_part(src, out, names, settings, report, compact=False):
63 rows, failures = {}, {}
64 for number, name in enumerate(names, 1):
65 try:
66 rows[name] = build_one(src, out, name, settings, compact)
67 except (translator.Unsupported, MemoryError) as e:
68 failures[name] = str(e) or type(e).__name__
69 if number % 100 == 0 or number == len(names):
70 print(f"worker {os.getpid()}: {number}/{len(names)}, {len(failures)} failed", flush=True)
71 translator.write_index(str(report), {"rows": rows, "failures": failures})
72
73
74def build(src, out, names, settings, jobs, compact=False):
75 cache = out / ".compute-cache"
76 cache.mkdir(exist_ok=True)
77 with (cache / "lock").open("ab") as lock, tempfile.TemporaryDirectory(dir=cache) as tmp:
78 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
79 reports = [Path(tmp) / str(i) for i in range(jobs)]
80 pid = os.fork() if jobs == 2 else None
81 if pid == 0:
82 try:
83 build_part(src, out, names[1::2], settings, reports[1], compact)
84 except BaseException:
85 import traceback
86 traceback.print_exc()
87 os._exit(1)
88 os._exit(0)
89 try:
90 build_part(src, out, names[::jobs], settings, reports[0], compact)
91 finally:
92 if pid and os.waitpid(pid, 0)[1]:
93 raise RuntimeError("second translation worker failed")
94
95 index, failures, pairs = {}, {}, {}
96 for report in reports:
97 part = json.loads(report.read_text(encoding="utf-8"))
98 failures.update(part["failures"])
99 for name, row in part["rows"].items():
100 module, meta = row["module"], row["meta"]
101 pair = meta["fspx_code_sha256"], meta["fspx_state_sha256"]
102 if pairs.setdefault(pair, module) != module:
103 raise ValueError("conflicting compute modules for one code/state pair")
104 # The same binary can implement different code/state keys. Each needs a runtime entry.
105 entry = name + "_" + module
106 index[entry] = meta
107 by_hash = {}
108 for name, reason in failures.items():
109 code = digest(src / "fspx" / (name + ".code"))
110 state = digest(src / "fspx" / (name + ".state"))
111 by_hash.setdefault(code, {})[state] = reason
112 translator.write_index(str(out / "failures.json"), by_hash)
113 translator.write_index(str(out / "index.json"), index)
114 print(f"{len(index)}/{len(names)} valid, {len(failures)} failed")
115 return int(bool(failures))
116
117
118def main():
119 ap = argparse.ArgumentParser(description=__doc__)
120 ap.add_argument("inputs", type=Path, help="unpacked library with index.json, disasm/ and fspx/")
121 ap.add_argument("--out", type=Path, required=True, help="dedicated runtime library subdirectory")
122 ap.add_argument("--jobs", type=int, choices=(1, 2), default=2)
123 ap.add_argument("--memory-mib", type=int, default=768, help="virtual memory per process (default 768 MiB)")
124 ap.add_argument("--descriptor-hash", choices=translator.DESCRIPTOR_HASHES, default="fnv1a",
125 help="bindless descriptor table hash shared with the runtime")
126 ap.add_argument("--loop-limit", type=translator.spirv_loop_guard.parse_limit,
127 default=translator.spirv_loop_guard.DEFAULT_LIMIT, help="maximum loop visits (0 disables)")
128 ap.add_argument("--compact-spirv", action="store_true", help="compact modules with spirv-opt before validation")
129 ap.add_argument("--wave64-emulate", action="store_true")
130 args = ap.parse_args()
131 if args.memory_mib < 1:
132 ap.error("--memory-mib must be positive")
133 src, out = args.inputs.resolve(), args.out.resolve()
134 if out == src or src in out.parents or out in src.parents:
135 ap.error("input and output directories must be separate")
136 os.setpriority(os.PRIO_PROCESS, 0, 19)
137 soft, hard = resource.getrlimit(resource.RLIMIT_AS)
138 bound = min(n for n in (args.memory_mib << 20, soft, hard) if n != resource.RLIM_INFINITY)
139 resource.setrlimit(resource.RLIMIT_AS, (bound, hard))
140 versions = []
141 required_tools = ["spirv-as", "spirv-val"]
142 if args.compact_spirv:
143 required_tools.append("spirv-opt")
144 for tool in required_tools:
145 binary = shutil.which(tool)
146 if not binary:
147 ap.error(tool + " is required")
148 versions.append(digest(Path(binary)))
149 settings = [translation_sources_digest(), digest(Path(__file__)), versions, args.wave64_emulate,
150 args.loop_limit, args.descriptor_hash]
151 rows = json.loads((src / "index.json").read_text(encoding="utf-8"))
152 names = []
153 for row in rows:
154 if row["stage"] != "cs":
155 continue
156 filename = row["file"]
157 if Path(filename).name != filename or not filename.endswith(".dxbc") or "\\" in filename:
158 ap.error("invalid compute filename in input index")
159 names.append(filename[:-5])
160 if not names or len(set(names)) != len(names):
161 ap.error("expected unique compute filenames in the input index")
162 out.mkdir(parents=True, exist_ok=True)
163 translator.DESCRIPTOR_HASH = args.descriptor_hash
164 translator.LOOP_LIMIT = args.loop_limit
165 translator.WAVE64_EMULATE = args.wave64_emulate
166 return build(src, out, sorted(names), settings, args.jobs, args.compact_spirv)
167
168
169if __name__ == "__main__":
170 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
171 sys.stdout.reconfigure(errors="replace")
172 except AttributeError:
173 pass
174 sys.exit(main())
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