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:
authorItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 22:41:03 -0500
committerItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 22:41:03 -0500
commit2d3369a4c82e6f36c5190c4c534d3df600e135ec (patch)
tree645518e91fee1ab6299170a3251c035495000c75 /scripts
parentdb51b7d3f999ab57898cf039f8289d807b63523c (diff)
parent7b7d73f890f9fbbf5967bbb694390bbc99e33ba6 (diff)
Merge remote-tracking branch 'origin/main'
Diffstat (limited to 'scripts')
-rw-r--r--scripts/bench_wave64.py13
-rw-r--r--scripts/build_llvm_mc.ps111
-rw-r--r--scripts/build_runtime.ps16
-rw-r--r--scripts/carve_all.ps123
-rw-r--r--scripts/check_no_game_data.py36
-rw-r--r--scripts/first_look.ps14
-rw-r--r--scripts/meta_to_xml.ps16
-rw-r--r--scripts/run_gpu_tests.py80
-rw-r--r--scripts/run_wine_tests.py55
-rw-r--r--scripts/vs_input_survey.py82
10 files changed, 234 insertions, 82 deletions
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py
index 3d77bc2bc..433eea00f 100644
--- a/scripts/bench_wave64.py
+++ b/scripts/bench_wave64.py
@@ -36,13 +36,14 @@ def build(work, name, emulate, llvm_mc):
36 return os.path.join(out, "spirv", name + ".spv") 36 return os.path.join(out, "spirv", name + ".spv")
37 37
38 38
39def segments(spv): 39def segments(spv: str) -> tuple[int, int] | None:
40 """(segments, continuation segments) of an emulated module: the cases of the scheduler's OpSwitch.""" 40 """Count scheduler cases and continuations, including inner switches in a partitioned dispatch."""
41 text = open(spv[:-4] + ".spvasm", encoding="utf-8").read() 41 with open(spv[:-4] + ".spvasm", encoding="utf-8") as source:
42 m = re.search(r"OpSwitch %pcv %sw_default ([^\n]+)", text) 42 text = source.read()
43 if not m: 43 tables = re.findall(r"^[ \t]*OpSwitch %pcv %(?:sw_default|swm\d+) ([^\n]+)", text, re.MULTILINE)
44 if not tables:
44 return None 45 return None
45 cases = [int(x) for x in re.findall(r"(\d+) %blk\d+", m.group(1))] 46 cases = sorted(int(case) for table in tables for case in re.findall(r"(\d+) %blk\d+", table))
46 blocks = next((i for i, c in enumerate(cases) if c != i), len(cases)) # blocks 0..n-1, then "done" = n, then segments 47 blocks = next((i for i, c in enumerate(cases) if c != i), len(cases)) # blocks 0..n-1, then "done" = n, then segments
47 return len(cases), len(cases) - blocks 48 return len(cases), len(cases) - blocks
48 49
diff --git a/scripts/build_llvm_mc.ps1 b/scripts/build_llvm_mc.ps1
index 0e016463e..e028fd9de 100644
--- a/scripts/build_llvm_mc.ps1
+++ b/scripts/build_llvm_mc.ps1
@@ -56,9 +56,15 @@ if (-not (Test-Path (Join-Path $src "llvm\CMakeLists.txt"))) {
56 # sparse checkout fails with "Filename too long" (Windows' 260-character limit). Set in the clone's config only. 56 # sparse checkout fails with "Filename too long" (Windows' 260-character limit). Set in the clone's config only.
57 & git clone --quiet --depth 1 --branch "llvmorg-$Version" --filter=blob:none --sparse --config core.longpaths=true https://github.com/llvm/llvm-project $src 57 & git clone --quiet --depth 1 --branch "llvmorg-$Version" --filter=blob:none --sparse --config core.longpaths=true https://github.com/llvm/llvm-project $src
58 if ($LASTEXITCODE -ne 0) { throw "git clone of llvmorg-$Version failed." } 58 if ($LASTEXITCODE -ne 0) { throw "git clone of llvmorg-$Version failed." }
59 & git -C $src sparse-checkout set llvm cmake third-party 59 # libc: LLVM 23 configures only with its shared headers (llvm/CMakeLists.txt, "LLVM libc is not found").
60 & git -C $src sparse-checkout set llvm cmake third-party libc
60 if ($LASTEXITCODE -ne 0) { throw "git sparse-checkout failed." } 61 if ($LASTEXITCODE -ne 0) { throw "git sparse-checkout failed." }
61} 62}
63# A source kept by a failed LLVM 23 build of an older version of this script has no libc yet.
64if ((Test-Path (Join-Path $src ".git\info\sparse-checkout")) -and -not (Test-Path (Join-Path $src "libc"))) {
65 & git -C $src sparse-checkout add libc
66 if ($LASTEXITCODE -ne 0) { throw "git sparse-checkout add libc failed." }
67}
62 68
63# -Keep (or an interrupted build) can leave sources from another -Version. 69# -Keep (or an interrupted build) can leave sources from another -Version.
64# Refuse that checkout rather than silently rebuilding the wrong release or resetting user files. 70# Refuse that checkout rather than silently rebuilding the wrong release or resetting user files.
@@ -99,7 +105,8 @@ $batchText = @(
99) -join "`r`n" 105) -join "`r`n"
100[System.IO.File]::WriteAllText($bat, $batchText, [System.Text.UTF8Encoding]::new($false)) 106[System.IO.File]::WriteAllText($bat, $batchText, [System.Text.UTF8Encoding]::new($false))
101 107
102$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru 108# /s with a second pair of quotes: cmd.exe strips only the outer pair, so a path holding & or ^ stays quoted.
109$p = Start-Process cmd.exe -ArgumentList "/s", "/c", "`"`"$bat`"`"" -NoNewWindow -PassThru
103$null = $p.Handle # keeps the exit code readable after WaitForExit 110$null = $p.Handle # keeps the exit code readable after WaitForExit
104try { $p.PriorityClass = "BelowNormal" } catch {} 111try { $p.PriorityClass = "BelowNormal" } catch {}
105$p.WaitForExit() 112$p.WaitForExit()
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index 46dc10291..193bd447e 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -38,7 +38,7 @@ if ((Test-Path $cmake) -and (Test-Path $ninja)) {
38 Write-Warning "VS C++ CMake tools not found: building with cl.exe directly, without the GameInput shim (SDL3). Install the CMake tools component to get it." 38 Write-Warning "VS C++ CMake tools not found: building with cl.exe directly, without the GameInput shim (SDL3). Install the CMake tools component to get it."
39 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" 39 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue"
40 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } 40 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" }
41 $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" } 41 $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" }
42 $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" 42 $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`""
43 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } 43 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" }
44 $body = @" 44 $body = @"
@@ -51,6 +51,7 @@ cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /D
51cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\command_list_test.cpp" /Fe:command_list_test.exe /link /OPT:NOREF || exit /b 1 51cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\command_list_test.cpp" /Fe:command_list_test.exe /link /OPT:NOREF || exit /b 1
52if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" "$src\test\vk_pipeline_check.cpp" /Fe:vk_pipeline_check.exe || exit /b 1 52if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" "$src\test\vk_pipeline_check.cpp" /Fe:vk_pipeline_check.exe || exit /b 1
53if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_texture_test.cpp" /Fe:vk_texture_test.exe || exit /b 1 53if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_texture_test.cpp" /Fe:vk_texture_test.exe || exit /b 1
54if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_sampler_test.cpp" /Fe:vk_sampler_test.exe || exit /b 1
54if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\gfx10_descriptors_test.cpp" /Fe:gfx10_descriptors_test.exe || exit /b 1 55if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\gfx10_descriptors_test.cpp" /Fe:gfx10_descriptors_test.exe || exit /b 1
55if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_bindless_test.cpp" /Fe:vk_bindless_test.exe || exit /b 1 56if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_bindless_test.cpp" /Fe:vk_bindless_test.exe || exit /b 1
56if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_descriptor_bench.cpp" /Fe:vk_descriptor_bench.exe || exit /b 1 57if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_descriptor_bench.cpp" /Fe:vk_descriptor_bench.exe || exit /b 1
@@ -70,7 +71,8 @@ $bat = Join-Path $out "_build.cmd"
70$batchText = "@echo off`r`nchcp 65001 >nul`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body`r`n" 71$batchText = "@echo off`r`nchcp 65001 >nul`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body`r`n"
71[System.IO.File]::WriteAllText($bat, $batchText, [System.Text.UTF8Encoding]::new($false)) 72[System.IO.File]::WriteAllText($bat, $batchText, [System.Text.UTF8Encoding]::new($false))
72 73
73$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru 74# /s with a second pair of quotes: cmd.exe strips only the outer pair, so a path holding & or ^ stays quoted.
75$p = Start-Process cmd.exe -ArgumentList "/s", "/c", "`"`"$bat`"`"" -NoNewWindow -PassThru
74$null = $p.Handle # keeps the exit code readable after WaitForExit 76$null = $p.Handle # keeps the exit code readable after WaitForExit
75try { $p.PriorityClass = "BelowNormal" } catch {} 77try { $p.PriorityClass = "BelowNormal" } catch {}
76$p.WaitForExit() 78$p.WaitForExit()
diff --git a/scripts/carve_all.ps1 b/scripts/carve_all.ps1
index 6819e4376..f66d20945 100644
--- a/scripts/carve_all.ps1
+++ b/scripts/carve_all.ps1
@@ -26,15 +26,30 @@ foreach ($archive in $archives) {
26 $f = $archive.file 26 $f = $archive.file
27 $rel = $archive.relative 27 $rel = $archive.relative
28 $dest = $archive.destination 28 $dest = $archive.destination
29 if (-not (Test-Path -LiteralPath (Join-Path $dest "index.json"))) { 29 $index = Join-Path $dest "index.json"
30 if (-not (Test-Path -LiteralPath $index)) {
30 Write-Host ("{0:HH:mm:ss} carving {1} ({2:N1} GiB)" -f (Get-Date), $rel, ($f.Length / 1GB)) 31 Write-Host ("{0:HH:mm:ss} carving {1} ({2:N1} GiB)" -f (Get-Date), $rel, ($f.Length / 1GB))
31 python -I $tool $f.FullName $dest | Select-Object -Last 1 32 python -I $tool $f.FullName $dest | Select-Object -Last 1
32 if ($LASTEXITCODE -ne 0) { throw "Carving $rel failed (exit $LASTEXITCODE)" } 33 if ($LASTEXITCODE -ne 0) { throw "Carving $rel failed (exit $LASTEXITCODE)" }
33 } 34 }
34 $s = (Get-Content -LiteralPath (Join-Path $dest "index.json") -Raw | ConvertFrom-Json).summary 35 try {
36 $s = (Get-Content -LiteralPath $index -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop).summary
37 foreach ($field in 'files', 'bink2_files', 'span', 'compressed_bytes', 'unread_bytes', 'inflated_bytes') {
38 $value = $s.$field
39 if ((($value -isnot [int]) -and ($value -isnot [long])) -or $value -lt 0) {
40 throw "summary.$field must be a non-negative integer."
41 }
42 }
43 if ($s.span -eq 0 -and ($s.compressed_bytes -ne 0 -or $s.unread_bytes -ne 0)) {
44 throw 'A zero summary.span requires zero compressed and unread bytes.'
45 }
46 } catch {
47 throw "Invalid carve index '$index': $($_.Exception.Message)"
48 }
49 $denominator = [math]::Max(1L, $s.span)
35 $rows += [pscustomobject]@{ archive = $rel; files = $s.files; bink2 = $s.bink2_files; span = $s.span 50 $rows += [pscustomobject]@{ archive = $rel; files = $s.files; bink2 = $s.bink2_files; span = $s.span
36 readable = [math]::Round(($s.compressed_bytes) / $s.span, 4) 51 readable = [math]::Round($s.compressed_bytes / $denominator, 4)
37 unread = [math]::Round($s.unread_bytes / $s.span, 4); inflated = $s.inflated_bytes } 52 unread = [math]::Round($s.unread_bytes / $denominator, 4); inflated = $s.inflated_bytes }
38} 53}
39$rows | ConvertTo-Json | Set-Content -Encoding utf8 -LiteralPath (Join-Path $Out "coverage.json") 54$rows | ConvertTo-Json | Set-Content -Encoding utf8 -LiteralPath (Join-Path $Out "coverage.json")
40$rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200 55$rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py
index 0cf71cee9..09bc1d22b 100644
--- a/scripts/check_no_game_data.py
+++ b/scripts/check_no_game_data.py
@@ -44,35 +44,30 @@ MAGICS = (
44) 44)
45 45
46 46
47def is_pe(head): 47def classify(head, pe_signature=None):
48 """MZ header whose e_lfanew points at a PE signature inside the bytes read.""" 48 """The format a file starts like, or None. `head` is its first bytes; `pe_signature` the 4 bytes at e_lfanew."""
49 if not head.startswith(b"MZ") or len(head) < 0x40:
50 return False
51 offset = int.from_bytes(head[0x3C:0x40], "little")
52 return head[offset:offset + 4] == b"PE\0\0"
53
54
55def classify(head):
56 """The format `head` (the first bytes of a file) starts like, or None."""
57 for name, offset, magic in MAGICS: 49 for name, offset, magic in MAGICS:
58 if head[offset:offset + len(magic)] == magic: 50 if head[offset:offset + len(magic)] == magic:
59 return name 51 return name
60 if head.startswith(b"RIFF") and head[8:12] == b"WAVE": 52 if head.startswith(b"RIFF") and head[8:12] == b"WAVE":
61 return "RIFF WAVE audio" 53 return "RIFF WAVE audio"
62 if is_pe(head): 54 if head.startswith(b"MZ") and pe_signature == b"PE\0\0":
63 return "PE executable" 55 return "PE executable"
64 return None 56 return None
65 57
66 58
67def read_head(path): 59def read_head(path):
60 """(first bytes, the 4 bytes at e_lfanew or None). The PE signature is read where e_lfanew points, even past
61 the first bytes or straddling their end; a file too short for it gives fewer than 4 bytes and no match."""
68 with open(path, "rb") as f: 62 with open(path, "rb") as f:
69 head = f.read(HEAD) 63 head = f.read(HEAD)
70 if head.startswith(b"MZ") and len(head) >= 0x40: 64 if not head.startswith(b"MZ") or len(head) < 0x40:
71 offset = int.from_bytes(head[0x3C:0x40], "little") 65 return head, None
72 if HEAD <= offset < 1 << 20: # the PE signature sits past the first bytes read 66 offset = int.from_bytes(head[0x3C:0x40], "little")
73 f.seek(offset) 67 if offset + 4 <= len(head):
74 head += b"\0" * (offset - len(head)) + f.read(4) 68 return head, head[offset:offset + 4]
75 return head 69 f.seek(offset)
70 return head, f.read(4)
76 71
77 72
78def tracked_files(root): 73def tracked_files(root):
@@ -86,7 +81,7 @@ def check(paths):
86 for path in paths: 81 for path in paths:
87 if os.path.islink(path) or not os.path.isfile(path): 82 if os.path.islink(path) or not os.path.isfile(path):
88 continue # submodules, symlinks, files deleted in the working tree 83 continue # submodules, symlinks, files deleted in the working tree
89 name = classify(read_head(path)) 84 name = classify(*read_head(path))
90 if name: 85 if name:
91 found.append((path, name)) 86 found.append((path, name))
92 return found 87 return found
@@ -94,9 +89,10 @@ def check(paths):
94 89
95def display(path): 90def display(path):
96 try: 91 try:
97 return os.path.relpath(path) 92 path = os.path.relpath(path)
98 except ValueError: # Windows: another drive than the working directory 93 except ValueError: # Windows: another drive than the working directory
99 return path 94 pass
95 return path.replace("\n", "\\n").replace("\r", "\\r") # one line per file, even for a name with a newline
100 96
101 97
102def main(argv): 98def main(argv):
diff --git a/scripts/first_look.ps1 b/scripts/first_look.ps1
index 4f7992ced..cf530fd64 100644
--- a/scripts/first_look.ps1
+++ b/scripts/first_look.ps1
@@ -24,6 +24,10 @@ Write-Host "`n== PE inspection"
24python -I (Join-Path $root "tools\pe_inspect.py") $Exe --game-dir $GameDir --out $out 24python -I (Join-Path $root "tools\pe_inspect.py") $Exe --game-dir $GameDir --out $out
25if ($LASTEXITCODE -ne 0) { throw "pe_inspect failed" } 25if ($LASTEXITCODE -ne 0) { throw "pe_inspect failed" }
26 26
27Write-Host "`n== GDK runtime classes and slots called through xgameruntime.lib (read from the file)"
28python -I (Join-Path $root "tools\gdk_runtime_calls.py") $Exe --out $out
29if ($LASTEXITCODE -ne 0) { Write-Warning "gdk_runtime_calls could not read all of $Exe; its report may be incomplete" }
30
27$rt = Join-Path $root "runtime\build\gta6rt.exe" 31$rt = Join-Path $root "runtime\build\gta6rt.exe"
28# A gta6rt.exe older than the runtime sources (a pull since the last build) would report the old shim table, so it 32# A gta6rt.exe older than the runtime sources (a pull since the last build) would report the old shim table, so it
29# is rebuilt then too, not only when missing. 33# is rebuilt then too, not only when missing.
diff --git a/scripts/meta_to_xml.ps1 b/scripts/meta_to_xml.ps1
index 065ad4145..28c6575f6 100644
--- a/scripts/meta_to_xml.ps1
+++ b/scripts/meta_to_xml.ps1
@@ -1,7 +1,7 @@
1# Converts carved PSO ('PSIN') and RBF ('RBF0') metadata blobs to XML with CodeWalker.Core's parsers. 1# Converts carved PSO ('PSIN') and RBF ('RBF0') metadata blobs to XML with CodeWalker.Core's parsers.
2# Run in Windows PowerShell 5.1. 2# Run in Windows PowerShell 5.1.
3# .\meta_to_xml.ps1 -Carve <work>\carve -Out <work>\meta [-Limit N] 3# .\meta_to_xml.ps1 -Carve <work>\carve -Out <work>\meta [-Limit N]
4# Each blob becomes <Out>\<archive>\<offset>.xml. Failures go to <Out>\failures.txt with the error message. 4# Each blob becomes <Out>\<archive>\<offset>.xml. Failures go to <Out>\failures.txt (UTF-8 with BOM) with the error message.
5param( 5param(
6 [string]$Carve = "<work>\carve", 6 [string]$Carve = "<work>\carve",
7 [string]$Out = "<work>\meta", 7 [string]$Out = "<work>\meta",
@@ -14,7 +14,7 @@ Add-Type -Path "$CodeWalker\SharpDX.dll"; Add-Type -Path "$CodeWalker\SharpDX.Ma
14[void][Reflection.Assembly]::LoadFrom("$CodeWalker\CodeWalker.Core.dll") 14[void][Reflection.Assembly]::LoadFrom("$CodeWalker\CodeWalker.Core.dll")
15New-Item -ItemType Directory -Force $Out | Out-Null 15New-Item -ItemType Directory -Force $Out | Out-Null
16$fail = Join-Path $Out "failures.txt" 16$fail = Join-Path $Out "failures.txt"
17"" | Set-Content -LiteralPath $fail 17"" | Set-Content -LiteralPath $fail -Encoding utf8
18$ok = @{ pso = 0; rbf = 0 }; $bad = @{ pso = 0; rbf = 0 }; $n = 0 18$ok = @{ pso = 0; rbf = 0 }; $bad = @{ pso = 0; rbf = 0 }; $n = 0
19 19
20foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) { 20foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) {
@@ -44,7 +44,7 @@ foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) {
44 } catch { 44 } catch {
45 $bad[$kind]++ 45 $bad[$kind]++
46 $msg = $_.Exception.InnerException; if (-not $msg) { $msg = $_.Exception } 46 $msg = $_.Exception.InnerException; if (-not $msg) { $msg = $_.Exception }
47 "$($dir.Name)\$name $kind : $($msg.Message)" | Add-Content -LiteralPath $fail 47 "$($dir.Name)\$name $kind : $($msg.Message)" | Add-Content -LiteralPath $fail -Encoding utf8
48 } 48 }
49 } 49 }
50 if ($Limit -and $n -ge $Limit) { break } 50 if ($Limit -and $n -ge $Limit) { break }
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index 94de20f26..66400b57a 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -38,6 +38,7 @@ from check import judged_words, words_match # dump words not judged on some de
38from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py 38from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py
39from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 39from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8
40from check import gpu_test_timeout, timed_out # per-program time limit (LEONIDA_GPU_TEST_TIMEOUT) 40from check import gpu_test_timeout, timed_out # per-program time limit (LEONIDA_GPU_TEST_TIMEOUT)
41from check import run_readback
41from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS 42from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS
42from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip, 43from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip,
43 unpinned_subgroup_skip, vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py 44 unpinned_subgroup_skip, vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py
@@ -566,7 +567,7 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool,
566# checker runs them: the test program that owns them judges them. 567# checker runs them: the test program that owns them judges them.
567OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_translated_draw_test", 568OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_translated_draw_test",
568 "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test", 569 "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test",
569 "ps_m2_array": "d3d12_m2_formats_test", 570 "ps_m2_literal": "d3d12_m2_textured_test", "ps_m2_array": "d3d12_m2_formats_test",
570 "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", 571 "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test",
571 "ps_m3_post": "d3d12_m3_frame_test", "ps_m3_query": "d3d12_m3_frame_test", 572 "ps_m3_post": "d3d12_m3_frame_test", "ps_m3_query": "d3d12_m3_frame_test",
572 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test", 573 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test",
@@ -576,6 +577,7 @@ OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_transl
576# Shaders a selected test draws with, built even when the filter leaves them out (#192). 577# Shaders a selected test draws with, built even when the filter leaves them out (#192).
577DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm", 578DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm",
578 "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", 579 "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm",
580 "ps_sample_c": "vs_ids.asm", "ps_sample_c_b": "vs_ids.asm",
579 **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", "ps_imgatomic": "vs_ids.asm", 581 **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", "ps_imgatomic": "vs_ids.asm",
580 **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm", 582 **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm",
581 "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", 583 "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm",
@@ -616,6 +618,31 @@ def find_test_programs(build: str, ext: str) -> str | None:
616 return None 618 return None
617 619
618 620
621def native_folder(path: str, ansi: str = "mbcs") -> str | None:
622 """`path` spelled so that the native programs this runner starts can open files under it, or None.
623
624 On Windows the test programs and the Vulkan SDK tools (spirv-val, spirv-as) read their command line in the ANSI
625 code page, so a character outside it, as in a Cyrillic or CJK user name under %TEMP%, reaches them as '?'. Such a
626 folder is replaced by its 8.3 short name, which is plain ASCII, when the volume keeps one. Elsewhere, and for a
627 path the code page holds, `path` comes back as it is. `ansi` is the codec of that code page (a parameter so a
628 test can pick a narrow one).
629 """
630 def fits(p: str) -> bool:
631 try:
632 p.encode(ansi)
633 return True
634 except UnicodeEncodeError:
635 return False
636
637 if os.name != "nt" or fits(path):
638 return path
639 import ctypes
640 buf = ctypes.create_unicode_buffer(32768)
641 n = ctypes.windll.kernel32.GetShortPathNameW(path, buf, len(buf))
642 short = buf.value if 0 < n < len(buf) else ""
643 return short if short and fits(short) else None
644
645
619def main() -> int: 646def main() -> int:
620 ap = argparse.ArgumentParser() 647 ap = argparse.ArgumentParser()
621 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), 648 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"),
@@ -659,7 +686,14 @@ def main() -> int:
659 686
660 work = a.work or tempfile.mkdtemp(prefix="leonida_gpu_tests_") 687 work = a.work or tempfile.mkdtemp(prefix="leonida_gpu_tests_")
661 try: 688 try:
662 return run_suite(a, work) 689 os.makedirs(work, exist_ok=True)
690 native = native_folder(work)
691 if native is None:
692 print(f"error: the work folder {ascii(work)} has characters outside this PC's ANSI code page and no 8.3 "
693 "short name, so the test programs and the Vulkan SDK tools can't open files in it. Pass --work "
694 "with a folder whose path they can, such as C:\\leonida_gpu_work.", file=sys.stderr)
695 return 2
696 return run_suite(a, native)
663 finally: 697 finally:
664 if a.work is None: 698 if a.work is None:
665 shutil.rmtree(work, ignore_errors=True) 699 shutil.rmtree(work, ignore_errors=True)
@@ -747,7 +781,7 @@ def run_suite(a, work: str) -> int:
747 cmd.append("--mesh-compute") 781 cmd.append("--mesh-compute")
748 if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1 782 if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1
749 cmd.append("--pc-tail-ubo") 783 cmd.append("--pc-tail-ubo")
750 if os.environ.get("LEONIDA_FMA") in ("glsl", "khr"): # fused multiply-add: GLSL Fma or OpFmaKHR (docs/design.md) 784 if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md)
751 cmd += ["--fma", os.environ["LEONIDA_FMA"]] 785 cmd += ["--fma", os.environ["LEONIDA_FMA"]]
752 rc, out = run_cmd(cmd, gpu=False) 786 rc, out = run_cmd(cmd, gpu=False)
753 print("=== rdna2spirv.py ===") 787 print("=== rdna2spirv.py ===")
@@ -834,7 +868,7 @@ def run_suite(a, work: str) -> int:
834 ok = None if isinstance(problem, Skip) else not problem 868 ok = None if isinstance(problem, Skip) else not problem
835 results.append((name, ok, problem or f"4096 pixels in each of {len(GET_LOD_TESTS[name])} draw(s): the " 869 results.append((name, ok, problem or f"4096 pixels in each of {len(GET_LOD_TESTS[name])} draw(s): the "
836 "clamped and the calculated LOD within 1/16")) 870 "clamped and the calculated LOD within 1/16"))
837 elif name in ("cs_bounds", "cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_buf_tail", "cs_oob_select", "cs_oob_tail", 871 elif name in ("cs_bounds", "cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_smem_sconst_off", "cs_buf_tail", "cs_oob_select", "cs_oob_tail",
838 "cs_buf_swizzle", "cs_cmpx_class_f32", "cs_cvt_pk_u8", "cs_buf_load_sub", "cs_buf_fmt8"): 872 "cs_buf_swizzle", "cs_cmpx_class_f32", "cs_cvt_pk_u8", "cs_buf_load_sub", "cs_buf_fmt8"):
839 # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds 873 # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds
840 # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. 874 # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement.
@@ -849,6 +883,8 @@ def run_suite(a, work: str) -> int:
849 # never run with a translator that zero-extends the s_load immediate (reads 4 GiB past the heap) 883 # never run with a translator that zero-extends the s_load immediate (reads 4 GiB past the heap)
850 "cs_smem_sload_neg": [0x5EED0004, 0x5EED0000, 0x5EED0004, 0x5EED0004, 0x5EED0008, 0x5EED000C, 884 "cs_smem_sload_neg": [0x5EED0004, 0x5EED0000, 0x5EED0004, 0x5EED0004, 0x5EED0008, 0x5EED000C,
851 0xEEEEEEEE, 0xEEEEEEEE], 885 0xEEEEEEEE, 0xEEEEEEEE],
886 # SHADER-328: a constant SGPR offset gives what the run-time one gives (no 32-bit wrap)
887 "cs_smem_sconst_off": [0, 0x5EED0018, 0x5EED0018, 0x5EED0014],
852 "cs_buf_tail": [0, 0x5EED000C, 0x5EED0008, 0x5EED000C, 0, 0, 0x5EED0010, 0], 888 "cs_buf_tail": [0, 0x5EED000C, 0x5EED0008, 0x5EED000C, 0, 0, 0x5EED0010, 0],
853 "cs_oob_select": [0x5EED000C, 0, 0x5EED0014, 0, 0x5EED0018, 0xEEEEEEEE, 0, 0], 889 "cs_oob_select": [0x5EED000C, 0, 0x5EED0014, 0, 0x5EED0018, 0xEEEEEEEE, 0, 0],
854 "cs_oob_tail": [0, 0, 0x5EED0010, 0, 0xBEEF0000, 0xEEEEEEEE, 0, 0x5EED0010], 890 "cs_oob_tail": [0, 0, 0x5EED0010, 0, 0xBEEF0000, 0xEEEEEEEE, 0, 0x5EED0010],
@@ -1099,22 +1135,22 @@ def run_suite(a, work: str) -> int:
1099 ok = None if isinstance(problem, Skip) else not problem 1135 ok = None if isinstance(problem, Skip) else not problem
1100 results.append((name, ok, problem or "4096 RGBA pixels matched")) 1136 results.append((name, ok, problem or "4096 RGBA pixels matched"))
1101 elif name in ("ps_texture_sample", "ps_cube_sample", "ps_texture_sample_d16", "ps_sample_c_lz", 1137 elif name in ("ps_texture_sample", "ps_cube_sample", "ps_texture_sample_d16", "ps_sample_c_lz",
1102 "ps_sample_c_lz_a16"): 1138 "ps_sample_c_lz_a16", "ps_sample_c", "ps_sample_c_b"):
1103 # Bindless texture tests: vk_texture_test finds vs_ids.spv and the shader in its working directory. 1139 # Bindless texture tests: vk_texture_test finds vs_ids.spv and the shader in its working directory.
1104 tool = os.path.join(a.build, "vk_texture_test" + ext) 1140 tool = os.path.join(a.build, "vk_texture_test" + ext)
1105 raw = os.path.join(raw_dir, f"{name}.raw") 1141 raw = os.path.join(raw_dir, f"{name}.raw")
1106 if name == "ps_texture_sample_d16": 1142 if name == "ps_texture_sample_d16":
1107 Path(raw).unlink(missing_ok=True)
1108 cmd = [tool, os.path.join(spirv_dir, "vs_ids.spv"), spv, raw, "0", "0", "0", "0", "0"] 1143 cmd = [tool, os.path.join(spirv_dir, "vs_ids.spv"), spv, raw, "0", "0", "0", "0", "0"]
1109 else: 1144 else:
1110 mode = {"ps_cube_sample": ["cube"], "ps_sample_c_lz": ["dref"], 1145 mode = {"ps_cube_sample": ["cube"], "ps_sample_c_lz": ["dref"],
1111 "ps_sample_c_lz_a16": ["dref_a16"]}.get(name, []) 1146 "ps_sample_c_lz_a16": ["dref_a16"], "ps_sample_c": ["dref_c"],
1147 "ps_sample_c_b": ["dref_c_b"]}.get(name, [])
1112 cmd = [tool, *mode, raw] 1148 cmd = [tool, *mode, raw]
1113 rc, msg = run_cmd(cmd, cwd=spirv_dir) 1149 rc, msg = run_readback(raw, run_cmd, cmd, cwd=spirv_dir)
1114 if rc == UNSUPPORTED: # e.g. fewer push constant bytes than the texture tests need 1150 if rc == UNSUPPORTED: # e.g. fewer push constant bytes than the texture tests need
1115 results.append((name, None, unsupported_skip(msg))) 1151 results.append((name, None, unsupported_skip(msg)))
1116 elif name == "ps_texture_sample_d16" and rc == 0: 1152 elif name == "ps_texture_sample_d16" and rc == 0:
1117 ok, detail = check_d16_texture(raw) if os.path.isfile(raw) else (False, "missing RGBA32F readback") 1153 ok, detail = check_d16_texture(raw)
1118 results.append((name, ok, detail)) 1154 results.append((name, ok, detail))
1119 else: 1155 else:
1120 results.append((name, rc == 0 and "PASSED" in msg, msg.splitlines()[-1] if msg else "")) 1156 results.append((name, rc == 0 and "PASSED" in msg, msg.splitlines()[-1] if msg else ""))
@@ -1122,8 +1158,8 @@ def run_suite(a, work: str) -> int:
1122 expected = TEXTURE_CONSTANTS[name] 1158 expected = TEXTURE_CONSTANTS[name]
1123 tool = os.path.join(a.build, "vk_texture_test" + ext) 1159 tool = os.path.join(a.build, "vk_texture_test" + ext)
1124 raw = os.path.join(raw_dir, f"{name}.raw") 1160 raw = os.path.join(raw_dir, f"{name}.raw")
1125 rc, msg = run_cmd([tool, os.path.join(spirv_dir, "vs_ids.spv"), spv, raw, "0", "92", "c00000", 1161 rc, msg = run_readback(raw, run_cmd, [tool, os.path.join(spirv_dir, "vs_ids.spv"), spv, raw, "0", "92",
1126 "14500000", "0"], cwd=spirv_dir) 1162 "c00000", "14500000", "0"], cwd=spirv_dir)
1127 bad = 4096 1163 bad = 4096
1128 if rc == 0 and os.path.isfile(raw): 1164 if rc == 0 and os.path.isfile(raw):
1129 data = Path(raw).read_bytes() 1165 data = Path(raw).read_bytes()
@@ -1154,8 +1190,8 @@ def run_suite(a, work: str) -> int:
1154 # Texel offsets: needs vk_texture_test's texture, sampler and descriptor table (vk_harness binds none), 1190 # Texel offsets: needs vk_texture_test's texture, sampler and descriptor table (vk_harness binds none),
1155 # and VK_KHR_maintenance8 for the non-constant Offset; the tool exits 77 without it. 1191 # and VK_KHR_maintenance8 for the non-constant Offset; the tool exits 77 without it.
1156 raw = os.path.join(raw_dir, f"{name}.raw") 1192 raw = os.path.join(raw_dir, f"{name}.raw")
1157 rc, msg = run_cmd([os.path.join(a.build, "vk_texture_test" + ext), vs_tri, spv, raw, *TEXOFF_ARGS], 1193 rc, msg = run_readback(raw, run_cmd, [os.path.join(a.build, "vk_texture_test" + ext), vs_tri, spv, raw,
1158 env=texoff_env()) 1194 *TEXOFF_ARGS], env=texoff_env())
1159 if rc == UNSUPPORTED: 1195 if rc == UNSUPPORTED:
1160 results.append((name, None, unsupported_skip(msg))) 1196 results.append((name, None, unsupported_skip(msg)))
1161 elif rc != 0: 1197 elif rc != 0:
@@ -1180,7 +1216,7 @@ def run_suite(a, work: str) -> int:
1180 bary_gs = os.path.join(spirv_dir, f"{name}.bary_gs.spv") 1216 bary_gs = os.path.join(spirv_dir, f"{name}.bary_gs.spv")
1181 if bary_fallback() and os.path.isfile(bary_gs): # --bary-fallback PS: barycentrics from this GS 1217 if bary_fallback() and os.path.isfile(bary_gs): # --bary-fallback PS: barycentrics from this GS
1182 env = dict(env or os.environ, VKH_GS=bary_gs, VKH_GS_HELPER="1") 1218 env = dict(env or os.environ, VKH_GS=bary_gs, VKH_GS_HELPER="1")
1183 rc, msg = run_cmd([vk_harness, vs, spv, raw], env=env) 1219 rc, msg = run_readback(raw, run_cmd, [vk_harness, vs, spv, raw], env=env)
1184 if rc == 77: # vk_harness: the device lacks a feature this shader needs (e.g. barycentrics) 1220 if rc == 77: # vk_harness: the device lacks a feature this shader needs (e.g. barycentrics)
1185 results.append((name, None, unsupported_skip(msg))) 1221 results.append((name, None, unsupported_skip(msg)))
1186 continue 1222 continue
@@ -1231,6 +1267,7 @@ def run_suite(a, work: str) -> int:
1231 "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000), 1267 "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000),
1232 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) 1268 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers)
1233 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000), 1269 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000),
1270 "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000B), # far branches (.asm header)
1234 "ps_vcmp_f16": (0x48A12080, 0x4CE9B1A2, 0x4BA72C98, 0x4FEFBDBA), # 16-bit float v_cmp e32 (.asm header) 1271 "ps_vcmp_f16": (0x48A12080, 0x4CE9B1A2, 0x4BA72C98, 0x4FEFBDBA), # 16-bit float v_cmp e32 (.asm header)
1235 "ps_vcmp_f16_e64": (0x44C11100, 0x4CF171C1, 0x47C71D18, 0x4FF77DD9), # same, e64 with swapped operands 1272 "ps_vcmp_f16_e64": (0x44C11100, 0x4CF171C1, 0x47C71D18, 0x4FF77DD9), # same, e64 with swapped operands
1236 "ps_vcmpx_f16": (0x68A12080, 0x6CE9B1A2, 0x6BA72C98, 0x6FEFBDBA), # 16-bit float v_cmpx e32 (.asm header) 1273 "ps_vcmpx_f16": (0x68A12080, 0x6CE9B1A2, 0x6BA72C98, 0x6FEFBDBA), # 16-bit float v_cmpx e32 (.asm header)
@@ -1278,9 +1315,8 @@ def run_suite(a, work: str) -> int:
1278 problem = ij_computed_problem(list(struct.iter_unpack("<4I", source.read()))) 1315 problem = ij_computed_problem(list(struct.iter_unpack("<4I", source.read())))
1279 ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" 1316 ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6"
1280 elif name == "ps_mandelbrot": 1317 elif name == "ps_mandelbrot":
1281 with open(raw, "rb") as source: 1318 px = read_raw_u32(raw) if os.path.isfile(raw) else []
1282 px = list(struct.iter_unpack("<4I", source.read())) 1319 problem = frame_problem(px) or mandelbrot_problem(px)
1283 problem = mandelbrot_problem(px)
1284 ok, detail = not problem, problem or f"{len(px)}/{len(px)} iteration counts match the float32 model" 1320 ok, detail = not problem, problem or f"{len(px)}/{len(px)} iteration counts match the float32 model"
1285 else: 1321 else:
1286 ok, detail = False, "no checker defined" 1322 ok, detail = False, "no checker defined"
@@ -1288,7 +1324,7 @@ def run_suite(a, work: str) -> int:
1288 elif name == "gs_tri": 1324 elif name == "gs_tri":
1289 raw = os.path.join(raw_dir, f"{name}.raw") 1325 raw = os.path.join(raw_dir, f"{name}.raw")
1290 env = dict(gfx_env or os.environ, VKH_GS=spv) 1326 env = dict(gfx_env or os.environ, VKH_GS=spv)
1291 rc, msg = run_cmd([vk_harness, vs_tri, fs_loc1, raw], env=env) 1327 rc, msg = run_readback(raw, run_cmd, [vk_harness, vs_tri, fs_loc1, raw], env=env)
1292 if rc == UNSUPPORTED: 1328 if rc == UNSUPPORTED:
1293 results.append((name, None, unsupported_skip(msg))) 1329 results.append((name, None, unsupported_skip(msg)))
1294 elif rc != 0: 1330 elif rc != 0:
@@ -1307,7 +1343,7 @@ def run_suite(a, work: str) -> int:
1307 elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3"): 1343 elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3"):
1308 raw = os.path.join(raw_dir, f"{name}.raw") 1344 raw = os.path.join(raw_dir, f"{name}.raw")
1309 env = mesh_env(spirv_dir, name, gfx_env) 1345 env = mesh_env(spirv_dir, name, gfx_env)
1310 rc, msg = run_cmd([vk_harness, spv, fs_passthru, raw], env=env) 1346 rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env)
1311 # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as 1347 # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as
1312 # the wave64 compute dumps are. 1348 # the wave64 compute dumps are.
1313 no64 = (name == "ms_w64x_ballot" and not w64_emulated() and 1349 no64 = (name == "ms_w64x_ballot" and not w64_emulated() and
@@ -1328,7 +1364,7 @@ def run_suite(a, work: str) -> int:
1328 if bary_fallback() and not f16_interp_fallback(): 1364 if bary_fallback() and not f16_interp_fallback():
1329 results.append((name, None, "SKIP (per-vertex f16 interpolants need barycentrics)")) 1365 results.append((name, None, "SKIP (per-vertex f16 interpolants need barycentrics)"))
1330 continue 1366 continue
1331 rc, msg = run_cmd([vk_harness, spv, fs, raw], env=env) 1367 rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs, raw], env=env)
1332 if rc == UNSUPPORTED: 1368 if rc == UNSUPPORTED:
1333 results.append((name, None, unsupported_skip(msg))) 1369 results.append((name, None, unsupported_skip(msg)))
1334 elif rc != 0: 1370 elif rc != 0:
@@ -1340,7 +1376,7 @@ def run_suite(a, work: str) -> int:
1340 elif name == "ms_clip": 1376 elif name == "ms_clip":
1341 raw = os.path.join(raw_dir, f"{name}.raw") 1377 raw = os.path.join(raw_dir, f"{name}.raw")
1342 env = mesh_env(spirv_dir, name, gfx_env) 1378 env = mesh_env(spirv_dir, name, gfx_env)
1343 rc, msg = run_cmd([vk_harness, spv, fs_passthru, raw], env=env) 1379 rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env)
1344 if rc == UNSUPPORTED: 1380 if rc == UNSUPPORTED:
1345 results.append((name, None, unsupported_skip(msg))) 1381 results.append((name, None, unsupported_skip(msg)))
1346 elif rc != 0: 1382 elif rc != 0:
@@ -1353,7 +1389,7 @@ def run_suite(a, work: str) -> int:
1353 # ps_flat must still see vertex 0 of instance 0 (0x101), as check.py checks. 1389 # ps_flat must still see vertex 0 of instance 0 (0x101), as check.py checks.
1354 raw = os.path.join(raw_dir, f"{name}.raw") 1390 raw = os.path.join(raw_dir, f"{name}.raw")
1355 env = dict(gfx_env or os.environ, VKH_DRAW="16,7") 1391 env = dict(gfx_env or os.environ, VKH_DRAW="16,7")
1356 rc, msg = run_cmd([vk_harness, spv, os.path.join(spirv_dir, "ps_flat.spv"), raw], env=env) 1392 rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, os.path.join(spirv_dir, "ps_flat.spv"), raw], env=env)
1357 if rc == UNSUPPORTED: 1393 if rc == UNSUPPORTED:
1358 results.append((name, None, unsupported_skip(msg))) 1394 results.append((name, None, unsupported_skip(msg)))
1359 elif rc != 0: 1395 elif rc != 0:
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py
index 3e90e9ab4..c9d2e5edf 100644
--- a/scripts/run_wine_tests.py
+++ b/scripts/run_wine_tests.py
@@ -12,11 +12,12 @@ Some tests open files through absolute paths compiled into them (the GLSL test s
12runtime/build/generated). For those, the drive of --windows-root is pointed at --root in the Wine prefix for the run 12runtime/build/generated). For those, the drive of --windows-root is pointed at --root in the Wine prefix for the run
13($WINEPREFIX, else ~/.wine), unless that drive is already in use there. 13($WINEPREFIX, else ~/.wine), unless that drive is already in use there.
14 14
15Every test is run and reported. The exit code is 1 if a test named by --require fails or is missing, else 0: the 15Every test is reported. The exit code is 1 if a test named by --require fails or is missing, else 0: the
16others show what does and doesn't work under Wine yet without failing the job. 16others show what does and doesn't work under Wine yet without failing the job.
17--timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test. 17--timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test.
18""" 18"""
19import argparse 19import argparse
20from graphlib import CycleError, TopologicalSorter
20import json 21import json
21import math 22import math
22import ntpath 23import ntpath
@@ -108,6 +109,24 @@ def properties(test: dict) -> dict:
108 return {p["name"]: p["value"] for p in test.get("properties", [])} 109 return {p["name"]: p["value"] for p in test.get("properties", [])}
109 110
110 111
112def fixture_dependencies(tests: list[dict]) -> dict[int, tuple[int, ...]]:
113 """Find the listed setup tests that must finish before each fixture consumer."""
114 metadata = [properties(test) for test in tests]
115 setups: dict[str, list[int]] = {}
116 for index, props in enumerate(metadata):
117 for fixture in props.get("FIXTURES_SETUP", []):
118 setups.setdefault(fixture, []).append(index)
119 return {
120 index: tuple(dict.fromkeys(
121 setup
122 for fixture in props.get("FIXTURES_REQUIRED", [])
123 for setup in setups.get(fixture, ())
124 if setup != index
125 ))
126 for index, props in enumerate(metadata)
127 }
128
129
111def truthy(value) -> bool: 130def truthy(value) -> bool:
112 """A ctest boolean property. The JSON carries it as a string, so "0" must stay false.""" 131 """A ctest boolean property. The JSON carries it as a string, so "0" must stay false."""
113 return str(value).strip().lower() in ("1", "on", "true", "yes") 132 return str(value).strip().lower() in ("1", "on", "true", "yes")
@@ -118,7 +137,7 @@ def regex_list(value: str | list[str]) -> list[str]:
118 return [value] if isinstance(value, str) else value 137 return [value] if isinstance(value, str) else value
119 138
120 139
121def run_test(test: dict, args, wine: list[str]) -> tuple[str, str]: 140def run_test(test: dict, args, wine: list[str], *, failed_setups: tuple[str, ...] = ()) -> tuple[str, str]:
122 """Returns (status, detail): status is pass, fail or skip.""" 141 """Returns (status, detail): status is pass, fail or skip."""
123 props = properties(test) 142 props = properties(test)
124 if truthy(props.get("DISABLED")): 143 if truthy(props.get("DISABLED")):
@@ -132,6 +151,8 @@ def run_test(test: dict, args, wine: list[str]) -> tuple[str, str]:
132 return "skip", f"runs {command[0]}, not a program from the build" 151 return "skip", f"runs {command[0]}, not a program from the build"
133 if not os.path.isfile(exe): 152 if not os.path.isfile(exe):
134 return "fail", f"executable not in the artifact: {command[0]}" 153 return "fail", f"executable not in the artifact: {command[0]}"
154 if failed_setups:
155 return "fail", "failed fixture setup: " + ", ".join(failed_setups)
135 argv = list(wine) + [exe] 156 argv = list(wine) + [exe]
136 for a in command[1:]: 157 for a in command[1:]:
137 mapped = map_path(a, args.windows_root, args.root) 158 mapped = map_path(a, args.windows_root, args.root)
@@ -222,6 +243,20 @@ def wine_command(text: str) -> list[str]:
222 return parts 243 return parts
223 244
224 245
246def valid_test_row(test) -> bool:
247 if not isinstance(test, dict) or not isinstance(test.get("name"), str):
248 return False
249 # CTest can omit the command for a target that was not built.
250 command = test.get("command", [])
251 if not isinstance(command, list) or not all(isinstance(arg, str) and "\0" not in arg for arg in command):
252 return False
253 entries = test.get("properties", [])
254 return isinstance(entries, list) and all(
255 isinstance(entry, dict) and isinstance(entry.get("name"), str) and "value" in entry
256 for entry in entries
257 )
258
259
225def read_tests(path: str) -> list[dict] | None: 260def read_tests(path: str) -> list[dict] | None:
226 """The tests in a `ctest --show-only=json-v1` file, or None when it is not one.""" 261 """The tests in a `ctest --show-only=json-v1` file, or None when it is not one."""
227 try: 262 try:
@@ -231,7 +266,7 @@ def read_tests(path: str) -> list[dict] | None:
231 print(f"ERROR: cannot read {path}: {e}", file=sys.stderr) 266 print(f"ERROR: cannot read {path}: {e}", file=sys.stderr)
232 return None 267 return None
233 tests = doc.get("tests") if isinstance(doc, dict) else None 268 tests = doc.get("tests") if isinstance(doc, dict) else None
234 if not isinstance(tests, list) or not all(isinstance(t, dict) for t in tests): 269 if not isinstance(tests, list) or not all(valid_test_row(t) for t in tests):
235 print(f"ERROR: {path} is not the output of ctest --show-only=json-v1", file=sys.stderr) 270 print(f"ERROR: {path} is not the output of ctest --show-only=json-v1", file=sys.stderr)
236 return None 271 return None
237 return tests 272 return tests
@@ -254,14 +289,22 @@ def main() -> int:
254 tests = read_tests(args.tests) 289 tests = read_tests(args.tests)
255 if tests is None: 290 if tests is None:
256 return 2 291 return 2
292 dependencies = fixture_dependencies(tests)
293 try:
294 order = list(TopologicalSorter(dependencies).static_order())
295 except CycleError:
296 print("ERROR: CTest fixture setup dependencies form a cycle", file=sys.stderr)
297 return 2
257 wine = args.wine 298 wine = args.wine
258 results = {} 299 results = {}
259 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") 300 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine")
301 names = [test.get("name", "?") for test in tests]
260 with DriveMap(args.windows_root, args.root, prefix) as drive: 302 with DriveMap(args.windows_root, args.root, prefix) as drive:
261 print(drive.note, flush=True) 303 print(drive.note, flush=True)
262 for test in tests: 304 for index in order:
263 name = test.get("name", "?") 305 name = names[index]
264 status, detail = run_test(test, args, wine) 306 failed_setups = tuple(names[setup] for setup in dependencies[index] if results[names[setup]] == "fail")
307 status, detail = run_test(tests[index], args, wine, failed_setups=failed_setups)
265 results[name] = status 308 results[name] = status
266 print(f"[{status.upper()}] {name}", flush=True) 309 print(f"[{status.upper()}] {name}", flush=True)
267 if status != "pass": 310 if status != "pass":
diff --git a/scripts/vs_input_survey.py b/scripts/vs_input_survey.py
index 89e648364..fa6701c15 100644
--- a/scripts/vs_input_survey.py
+++ b/scripts/vs_input_survey.py
@@ -26,10 +26,13 @@ from collections import Counter
26ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 26ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27sys.path.insert(0, os.path.join(ROOT, "tools")) 27sys.path.insert(0, os.path.join(ROOT, "tools"))
28import shader_ir # noqa: E402 28import shader_ir # noqa: E402
29from shader_meta import SGPR_RMW # noqa: E402
29 30
30NO_DEST_OPS = ("s_cmp", "s_bitcmp", "v_cmpx", "s_set", "s_rfe", "s_branch", "s_cbranch", "s_waitcnt", "s_barrier", 31NO_DEST_OPS = ("s_cmp", "s_bitcmp", "v_cmpx", "s_set", "s_rfe", "s_branch", "s_cbranch", "s_waitcnt", "s_barrier",
31 "s_nop", "s_endpgm", "s_sendmsg", "s_sleep", "exp", "buffer_store", "global_store", "flat_store", 32 "s_nop", "s_endpgm", "s_sendmsg", "s_sleep", "exp", "buffer_store", "tbuffer_store", "global_store",
32 "scratch_store", "image_store", "ds_write") 33 "flat_store", "scratch_store", "s_store", "s_buffer_store", "image_store", "ds_write")
34DUAL_DST_VALU = ("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")
35DS_RETURNING = ("ds_read", "ds_bpermute", "ds_permute", "ds_swizzle", "ds_consume", "ds_append", "ds_ordered_count")
33PRIM_EXPORT = re.compile(r"^\s*exp\s+prim\b", re.M) 36PRIM_EXPORT = re.compile(r"^\s*exp\s+prim\b", re.M)
34POS0_EXPORT = re.compile(r"^\s*exp\s+pos0\b", re.M) 37POS0_EXPORT = re.compile(r"^\s*exp\s+pos0\b", re.M)
35PARAM_EXPORT = re.compile(r"^\s*exp\s+param\d+\b", re.M) 38PARAM_EXPORT = re.compile(r"^\s*exp\s+param\d+\b", re.M)
@@ -45,6 +48,20 @@ def base_op(op):
45 return op 48 return op
46 49
47 50
51def _expand_regs(a):
52 """Return ('s' | 'v', iterable of register indices) for an operand, or (None, ())."""
53 k = a["k"]
54 if k == "sgpr":
55 return "s", range(a["r"], a["r"] + a.get("n", 1))
56 if k == "vgpr":
57 return "v", range(a["r"], a["r"] + a.get("n", 1))
58 if k == "slist":
59 return "s", (r for r in a["r"] if isinstance(r, int))
60 if k == "vlist":
61 return "v", (r for r in a["r"] if isinstance(r, int))
62 return None, ()
63
64
48def read_before_write(insns): 65def read_before_write(insns):
49 """(SGPRs, VGPRs) read before any write, straight-line from the first instruction.""" 66 """(SGPRs, VGPRs) read before any write, straight-line from the first instruction."""
50 written_s, written_v, read_s, read_v = set(), set(), set(), set() 67 written_s, written_v, read_s, read_v = set(), set(), set(), set()
@@ -52,32 +69,51 @@ def read_before_write(insns):
52 op, args = base_op(ins["op"]), ins["args"] 69 op, args = base_op(ins["op"]), ins["args"]
53 if not args: 70 if not args:
54 continue 71 continue
55 no_dest = op.startswith(NO_DEST_OPS) 72 mods = ins.get("mods", ())
56 dst_read = "fmac" in op or "mac_" in op or op in ("v_writelane_b32", "v_swap_b32") or "_atomic_" in op 73 is_gf_atomic = op.startswith(("global_atomic_", "flat_atomic_"))
57 if not no_dest and op.startswith("v_") and "_co_" in op and "_ci_" not in op and len(args) >= 2: 74 is_bi_atomic = op.startswith(("buffer_atomic_", "image_atomic_"))
58 dsts, srcs = args[:2], args[2:] # v_add_co_u32 writes a VGPR and a carry 75 is_ds_no_dest = op.startswith("ds_") and not op.startswith(DS_RETURNING) and "_rtn" not in op
59 elif no_dest: 76 no_dest = (
77 op.startswith(NO_DEST_OPS)
78 or ((is_gf_atomic or is_bi_atomic) and "glc" not in mods)
79 or is_ds_no_dest
80 or (op.startswith("v_cmp_") and len(args) <= 2)
81 )
82 if no_dest:
60 dsts, srcs = [], args 83 dsts, srcs = [], args
84 elif op == "v_swap_b32" and len(args) >= 2:
85 dsts, srcs = args[:2], args[:2]
86 elif (op.startswith("v_") and ("_co_" in op or op in DUAL_DST_VALU)
87 and len(args) >= 2 and args[1]["k"] in ("sgpr", "special", "slist")):
88 dsts, srcs = args[:2], args[2:] # vdst + scalar carry/scale-out dst
61 else: 89 else:
90 dst_read = (
91 op in SGPR_RMW or "fmac" in op or "mac_" in op
92 or op.startswith(("v_dot2c_", "v_dot4c_", "v_dot8c_"))
93 or op == "v_writelane_b32" or is_bi_atomic
94 )
62 dsts, srcs = args[:1], (args[:1] if dst_read else []) + args[1:] 95 dsts, srcs = args[:1], (args[:1] if dst_read else []) + args[1:]
63 for a in srcs: 96 for a in srcs:
64 regs = range(a["r"], a["r"] + a.get("n", 1)) if a["k"] in ("sgpr", "vgpr") else () 97 kind, regs = _expand_regs(a)
65 for r in regs: 98 for r in regs:
66 if a["k"] == "sgpr" and r not in written_s: 99 if kind == "s" and r not in written_s:
67 read_s.add(r) 100 read_s.add(r)
68 elif a["k"] == "vgpr" and r not in written_v: 101 elif kind == "v" and r not in written_v:
69 read_v.add(r) 102 read_v.add(r)
70 for a in dsts: 103 for a in dsts:
71 if a["k"] == "sgpr": 104 kind, regs = _expand_regs(a)
72 written_s.update(range(a["r"], a["r"] + a.get("n", 1))) 105 if kind == "s":
73 elif a["k"] == "vgpr": 106 written_s.update(regs)
74 written_v.update(range(a["r"], a["r"] + a.get("n", 1))) 107 elif kind == "v":
108 written_v.update(regs)
75 return read_s, read_v 109 return read_s, read_v
76 110
77 111
78def survey(dxbc_dir): 112def survey(dxbc_dir):
79 with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f: 113 with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f:
80 index = json.load(f) 114 index = json.load(f)
115 if not isinstance(index, list) or not all(isinstance(e, dict) for e in index):
116 raise ValueError("index.json is not a list of shader entries")
81 names = [os.path.splitext(e["file"])[0] for e in index if e.get("stage") == "vs"] 117 names = [os.path.splitext(e["file"])[0] for e in index if e.get("stage") == "vs"]
82 markers, vgprs, families = Counter(), Counter(), Counter() 118 markers, vgprs, families = Counter(), Counter(), Counter()
83 missing = 0 119 missing = 0
@@ -115,7 +151,15 @@ def main():
115 ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py") 151 ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py")
116 ap.add_argument("--json", help="also write the counts as JSON") 152 ap.add_argument("--json", help="also write the counts as JSON")
117 a = ap.parse_args() 153 a = ap.parse_args()
118 r = survey(a.dxbc) 154 index_path = os.path.join(a.dxbc, "index.json")
155 if a.json and os.path.exists(a.json) and os.path.exists(index_path) and os.path.samefile(a.json, index_path):
156 print(f"vs_input_survey: error: --json would overwrite the input {index_path}", file=sys.stderr)
157 return 2
158 try:
159 r = survey(a.dxbc)
160 except (OSError, ValueError) as e: # missing or non-folder <dxbc>, unreadable, non-UTF-8 or malformed index.json
161 print(f"vs_input_survey: error: cannot read {index_path}: {e}", file=sys.stderr)
162 return 2
119 m = r["markers"] 163 m = r["markers"]
120 print(f"{r['vertex_shaders']} vertex shaders ({r['missing_listings']} without a listing)") 164 print(f"{r['vertex_shaders']} vertex shaders ({r['missing_listings']} without a listing)")
121 print(f"NGG markers: exp prim {m.get('exp prim', 0)}, s_sendmsg {m.get('s_sendmsg', 0)}, v_mbcnt {m.get('v_mbcnt', 0)}") 165 print(f"NGG markers: exp prim {m.get('exp prim', 0)}, s_sendmsg {m.get('s_sendmsg', 0)}, v_mbcnt {m.get('v_mbcnt', 0)}")
@@ -125,8 +169,12 @@ def main():
125 legacy = not (m.get("exp prim") or m.get("s_sendmsg") or m.get("v_mbcnt")) 169 legacy = not (m.get("exp prim") or m.get("s_sendmsg") or m.get("v_mbcnt"))
126 print("layout:", "legacy (non-NGG) VS" if legacy else "NGG markers present: check the VS input layout") 170 print("layout:", "legacy (non-NGG) VS" if legacy else "NGG markers present: check the VS input layout")
127 if a.json: 171 if a.json:
128 with open(a.json, "w", encoding="utf-8", newline="\n") as f: 172 try:
129 json.dump(r, f, indent=1) 173 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
174 json.dump(r, f, indent=1)
175 except OSError as e:
176 print(f"vs_input_survey: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr)
177 return 2
130 return 0 178 return 0
131 179
132 180