upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/test
diff options
context:
space:
mode:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-23 00:19:13 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-23 00:19:13 +0100
commitfcda84bb0d2c6abb99e42409f413025d00ddb4be (patch)
tree27a5ee092be10547ffa5b4447ee050c623c62850 /runtime/test
parent3a1ed28bebf374321149bc4bbffc005ea6f691c4 (diff)
parent3986b50821272791333c00df80bdb8526a8fdb9c (diff)
Merge hw4-ps-oracle into hw4-ps-formats (#3499)
docs/shader_validation.md tools/ps_oracle.py AI-assisted.
Diffstat (limited to 'runtime/test')
-rw-r--r--runtime/test/bink_play.cpp487
-rw-r--r--runtime/test/bink_play.md51
-rw-r--r--runtime/test/buffer_va_index_test.cpp255
-rw-r--r--runtime/test/check_console_paths.cmake10
-rw-r--r--runtime/test/check_d3d12_trace.py2
-rw-r--r--runtime/test/check_game_dir.cmake34
-rw-r--r--runtime/test/check_loaded_gdk.cmake4
-rw-r--r--runtime/test/check_vk_pipeline_cli.cmake1
-rw-r--r--runtime/test/conservative_raster_test.cpp21
-rw-r--r--runtime/test/d3d12_bundle_forbidden_test.cpp289
-rw-r--r--runtime/test/d3d12_com_test.cpp7
-rw-r--r--runtime/test/d3d12_compute_test.cpp234
-rw-r--r--runtime/test/d3d12_conservative_raster_test.cpp385
-rw-r--r--runtime/test/d3d12_copy_compare.h31
-rw-r--r--runtime/test/d3d12_copy_xfmt_test.cpp9
-rw-r--r--runtime/test/d3d12_debug_markers_test.cpp16
-rw-r--r--runtime/test/d3d12_depth_resolve_test.cpp18
-rw-r--r--runtime/test/d3d12_descriptor_test.cpp173
-rw-r--r--runtime/test/d3d12_draw_test.cpp95
-rw-r--r--runtime/test/d3d12_fence_events_test.cpp6
-rw-r--r--runtime/test/d3d12_fence_timing_test.cpp47
-rw-r--r--runtime/test/d3d12_fspx_compute_test.cpp5
-rw-r--r--runtime/test/d3d12_gcl8_test.cpp2
-rw-r--r--runtime/test/d3d12_indirect_zero_test.cpp10
-rw-r--r--runtime/test/d3d12_m4_compute_test.cpp11
-rw-r--r--runtime/test/d3d12_msaa_draw_test.cpp9
-rw-r--r--runtime/test/d3d12_multithread_test.cpp10
-rw-r--r--runtime/test/d3d12_node_mask_test.cpp10
-rw-r--r--runtime/test/d3d12_pipeline_library_test.cpp6
-rw-r--r--runtime/test/d3d12_present_test.cpp3
-rw-r--r--runtime/test/d3d12_private_data_test.cpp2
-rw-r--r--runtime/test/d3d12_query_rules_test.cpp8
-rw-r--r--runtime/test/d3d12_queue_handover_test.cpp577
-rw-r--r--runtime/test/d3d12_resource_desc_test.cpp10
-rw-r--r--runtime/test/d3d12_rgb96_test.cpp35
-rw-r--r--runtime/test/d3d12_set0_compute_test.cpp5
-rw-r--r--runtime/test/d3d12_shader_cache_test.cpp138
-rw-r--r--runtime/test/d3d12_short_uav_clear_test.cpp192
-rw-r--r--runtime/test/d3d12_translated_draw_test.cpp4
-rw-r--r--runtime/test/d3d12_uav_clear_test.cpp15
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp30
-rw-r--r--runtime/test/dxgi_swapchain_test.cpp212
-rw-r--r--runtime/test/file_system_test.cpp91
-rw-r--r--runtime/test/fixtures/tiny_game.cpp21
-rw-r--r--runtime/test/fixtures/tiny_gdk_load.cpp30
-rw-r--r--runtime/test/free_image_base.h34
-rw-r--r--runtime/test/gameinput_probe.cpp29
-rw-r--r--runtime/test/gameinput_test.cpp247
-rw-r--r--runtime/test/glsl/cs_user_data.comp17
-rw-r--r--runtime/test/glsl/ps_conservative.frag3
-rw-r--r--runtime/test/glsl/ps_sg_probe.frag7
-rw-r--r--runtime/test/glsl/vs_conservative.vert4
-rw-r--r--runtime/test/host_adapter.h101
-rw-r--r--runtime/test/loader_test.cpp123
-rw-r--r--runtime/test/loader_tls_test.cpp151
-rw-r--r--runtime/test/process_cmdline_test.cpp11
-rw-r--r--runtime/test/replay_cpu_bench.cpp122
-rw-r--r--runtime/test/replay_uav_clear_offset_test.cpp58
-rw-r--r--runtime/test/resource_tiling_test.cpp16
-rw-r--r--runtime/test/shader_library_corpus_test.cpp22
-rw-r--r--runtime/test/shader_library_test.cpp7
-rw-r--r--runtime/test/shaders/build.py5
-rw-r--r--runtime/test/shaders/check.py154
-rw-r--r--runtime/test/shaders/cs_fmt_d16_xyz.asm98
-rw-r--r--runtime/test/shaders/cs_heap_init.asm14
-rw-r--r--runtime/test/shaders/cs_w32_andn2_exec.asm81
-rw-r--r--runtime/test/shaders/cs_w32_lds_subdword.asm57
-rw-r--r--runtime/test/shaders/cs_w32_lds_wide.asm57
-rw-r--r--runtime/test/shaders/cs_w64_mask_detect.asm4
-rw-r--r--runtime/test/shaders/mullit_readback.py122
-rw-r--r--runtime/test/shaders/ps_f64_round.asm25
-rw-r--r--runtime/test/shaders/ps_mul_legacy_denorm.asm16
-rw-r--r--runtime/test/shaders/ps_mul_legacy_denorm_mods.asm18
-rw-r--r--runtime/test/shaders/ps_vcmp_64.asm283
-rw-r--r--runtime/test/shaders/ps_vcmp_f32_nan.asm292
-rw-r--r--runtime/test/shaders/w64_graphics.py28
-rw-r--r--runtime/test/test_pe_loader_bounds.cpp6
-rw-r--r--runtime/test/unimplemented_policy_test.cpp3
-rw-r--r--runtime/test/vk_bindless_test.cpp10
-rw-r--r--runtime/test/vk_command_replay_test.cpp7
-rw-r--r--runtime/test/vk_compute_test.cpp21
-rw-r--r--runtime/test/vk_harness.cpp232
-rw-r--r--runtime/test/vk_overlapping_occlusion_test.cpp4
-rw-r--r--runtime/test/vk_pipeline_check.cpp57
-rw-r--r--runtime/test/vk_predicate_capture_test.cpp7
-rw-r--r--runtime/test/vk_predicated_copy_test.cpp7
-rw-r--r--runtime/test/vk_presenter_sync_test.cpp2
-rw-r--r--runtime/test/vk_queue_query_sync_test.cpp4
-rw-r--r--runtime/test/vk_store_test.cpp6
-rw-r--r--runtime/test/vk_test_device.h37
-rw-r--r--runtime/test/vk_texture_test.cpp8
-rw-r--r--runtime/test/vulkan13_features_test.cpp365
-rw-r--r--runtime/test/winhttp_offline_test.cpp24
-rw-r--r--runtime/test/xbox_present_test.cpp276
-rw-r--r--runtime/test/xgameruntime_test.cpp92
-rw-r--r--runtime/test/xmem_test.cpp30
96 files changed, 6742 insertions, 273 deletions
diff --git a/runtime/test/bink_play.cpp b/runtime/test/bink_play.cpp
new file mode 100644
index 000000000..da9360e2a
--- /dev/null
+++ b/runtime/test/bink_play.cpp
@@ -0,0 +1,487 @@
1// bink_play: play a Bink 2 stream in a window through the package's own Bink2Scarlett.dll, mapped by rt::Loader (the
2// same path bink_decode_test checks). A local viewing tool for movies carved from your own copy; nothing it reads or
3// shows is written anywhere.
4//
5// bink_play [NAME | movie.bk2 | archive.rpf@OFFSET] [--game-dir DIR] [--frames N] [--headless] [--loop]
6//
7// NAME is a movie's path in the game (Stinger/RSG_STINGER.bk2) or any unique part of it (stinger), looked up in the
8// name table tools/bink_play.py keeps (%LOCALAPPDATA%\Leonida\bink_names.csv); if there is none yet, bink_play runs
9// that tool once to build it. With no movie at all a windowed run plays the Rockstar stinger, so double-clicking
10// the executable plays it. The game folder comes from --game-dir, LEONIDA_GAME_DIR, or the archive the name table
11// was built from.
12//
13// A movie inside an archive plays where it is: `movies.rpf@OFFSET` hands BinkOpen the archive with
14// BinkSetFileOffset, so nothing is extracted (tools/bink_play.py finds the offset from the movie's name). A relative
15// archive path is taken from the game folder.
16//
17// --game-dir defaults to LEONIDA_GAME_DIR, the movie to LEONIDA_MOVIE. Without a package or a movie it prints
18// "SKIP (no package/movie)" and exits 77 (CTest skip). --headless decodes without a window (as fast as it can) and
19// prints the decode rate, so CTest can run it; --frames stops after N frames.
20//
21// Keys: Space pause/resume, Left/Right one second back/forward, Home restart, L loop on/off, Esc or closing the
22// window quits. The frame is scaled to the window, keeping its aspect ratio.
23#include <windows.h>
24
25#include <algorithm>
26#include <cctype>
27#include <chrono>
28#include <cstdint>
29#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <filesystem>
33#include <fstream>
34#include <stdexcept>
35#include <string>
36#include <thread>
37#include <vector>
38
39#include "../shims/shims.h"
40#include "../src/pe_loader.h"
41
42namespace {
43
44// A windowed run is often started by double-click, where a console line vanishes with its window: say it in a box.
45bool g_windowed = false;
46
47[[noreturn]] void fatal(const std::string& what) {
48 std::fprintf(stderr, "FAIL %s\n", what.c_str());
49 if (g_windowed) MessageBoxA(nullptr, what.c_str(), "bink_play", MB_OK | MB_ICONERROR);
50 std::exit(1);
51}
52
53std::string env(const char* name) {
54 const char* v = std::getenv(name);
55 return v ? v : "";
56}
57
58uint32_t read_u32(const uint8_t* p) {
59 return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
60}
61
62struct MovieHeader {
63 uint32_t frames = 0, width = 0, height = 0, fps_num = 0, fps_den = 0;
64};
65
66// The fixed Bink 2 header (docs/movies.md): frame count at 0x08, size at 0x14/0x18, frame rate at 0x1C/0x20.
67MovieHeader read_movie_header(const std::filesystem::path& path, uint64_t offset) {
68 std::ifstream f(path, std::ios::binary);
69 if (!f) fatal("cannot open movie " + path.string());
70 f.seekg((std::streamoff)offset);
71 uint8_t h[0x2C]{};
72 f.read(reinterpret_cast<char*>(h), sizeof(h));
73 if (f.gcount() != (std::streamsize)sizeof(h)) fatal("movie is shorter than the 44-byte Bink 2 header");
74 if (h[0] != 'K' || h[1] != 'B' || h[2] != '2' || h[3] < 'a' || h[3] > 'z')
75 fatal("movie does not start with KB2[a-z]");
76 MovieHeader out;
77 out.frames = read_u32(h + 0x08);
78 out.width = read_u32(h + 0x14);
79 out.height = read_u32(h + 0x18);
80 out.fps_num = read_u32(h + 0x1C);
81 out.fps_den = read_u32(h + 0x20);
82 if (!out.frames || !out.width || !out.height || !out.fps_num || !out.fps_den)
83 fatal("movie header has a zero frame count, size or fps");
84 if (out.width > 16384 || out.height > 16384) fatal("movie header has an implausible frame size");
85 return out;
86}
87
88struct BinkApi {
89 void* (*open)(const char*, uint32_t) = nullptr;
90 uint32_t (*do_frame)(void*) = nullptr;
91 uint32_t (*copy)(void*, void*, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t) = nullptr;
92 void (*next)(void*) = nullptr;
93 void (*go_to)(void*, uint32_t, uint32_t) = nullptr;
94 void (*close)(void*) = nullptr;
95 const char* (*get_error)() = nullptr;
96 void (*set_file_offset)(uint64_t) = nullptr; // applies to the next BinkOpen
97};
98
99template <class F> void bind(rt::Module& m, const char* name, F& out) {
100 auto it = m.exports.find(name);
101 if (it == m.exports.end()) fatal(std::string("Bink2Scarlett.dll does not export ") + name);
102 out = reinterpret_cast<F>(it->second);
103}
104
105constexpr uint32_t kCopyBgra32 = 3; // the BinkCopyToBuffer format bink_decode_test measured as 32-bit BGRA
106constexpr uint32_t kFileOffset = 0x20; // BinkOpen flag: start at the offset BinkSetFileOffset gave
107
108struct Player {
109 BinkApi api;
110 void* bink = nullptr;
111 MovieHeader header;
112 std::vector<uint8_t> frame;
113 uint32_t index = 0; // the frame in `frame`
114 bool paused = false;
115 bool loop = false;
116 bool quit = false;
117 bool seek_pending = false;
118 uint32_t seek_to = 0;
119
120 void decode() {
121 api.do_frame(bink);
122 api.copy(bink, frame.data(), header.width * 4, header.height, 0, 0, kCopyBgra32);
123 }
124 // Bink frame numbers in BinkGoto are 1-based.
125 void go_to(uint32_t target) {
126 index = std::min(target, header.frames - 1);
127 api.go_to(bink, index + 1, 0);
128 decode();
129 }
130 uint32_t fps_frames(double seconds) const {
131 return (uint32_t)(seconds * header.fps_num / header.fps_den);
132 }
133};
134
135Player* g_player = nullptr;
136
137void paint(HWND hwnd) {
138 PAINTSTRUCT ps;
139 HDC dc = BeginPaint(hwnd, &ps);
140 RECT rc;
141 GetClientRect(hwnd, &rc);
142 const int cw = rc.right - rc.left, ch = rc.bottom - rc.top;
143 const Player& p = *g_player;
144 // Fit the frame in the client area, keeping its aspect ratio, and black out the bars.
145 int w = cw, h = (int)((int64_t)cw * p.header.height / p.header.width);
146 if (h > ch) {
147 h = ch;
148 w = (int)((int64_t)ch * p.header.width / p.header.height);
149 }
150 const int x = (cw - w) / 2, y = (ch - h) / 2;
151 HBRUSH black = (HBRUSH)GetStockObject(BLACK_BRUSH);
152 RECT bars[] = {{0, 0, cw, y}, {0, y + h, cw, ch}, {0, y, x, y + h}, {x + w, y, cw, y + h}};
153 for (const RECT& b : bars) FillRect(dc, &b, black);
154 BITMAPINFO bi{};
155 bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
156 bi.bmiHeader.biWidth = (LONG)p.header.width;
157 bi.bmiHeader.biHeight = -(LONG)p.header.height; // top-down
158 bi.bmiHeader.biPlanes = 1;
159 bi.bmiHeader.biBitCount = 32;
160 bi.bmiHeader.biCompression = BI_RGB;
161 SetStretchBltMode(dc, COLORONCOLOR);
162 StretchDIBits(dc, x, y, w, h, 0, 0, (int)p.header.width, (int)p.header.height, p.frame.data(), &bi,
163 DIB_RGB_COLORS, SRCCOPY);
164 EndPaint(hwnd, &ps);
165}
166
167LRESULT CALLBACK window_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
168 Player& p = *g_player;
169 switch (msg) {
170 case WM_PAINT: paint(hwnd); return 0;
171 case WM_ERASEBKGND: return 1;
172 case WM_KEYDOWN:
173 switch (wp) {
174 case VK_ESCAPE: DestroyWindow(hwnd); return 0;
175 case VK_SPACE: p.paused = !p.paused; return 0;
176 case 'L': p.loop = !p.loop; return 0;
177 case VK_HOME: p.seek_pending = true; p.seek_to = 0; return 0;
178 case VK_LEFT: {
179 const uint32_t back = p.fps_frames(1.0);
180 p.seek_pending = true;
181 p.seek_to = p.index > back ? p.index - back : 0;
182 return 0;
183 }
184 case VK_RIGHT:
185 p.seek_pending = true;
186 p.seek_to = std::min(p.index + p.fps_frames(1.0), p.header.frames - 1);
187 return 0;
188 }
189 break;
190 case WM_DESTROY: p.quit = true; PostQuitMessage(0); return 0;
191 }
192 return DefWindowProcW(hwnd, msg, wp, lp);
193}
194
195void set_title(HWND hwnd, const Player& p, const std::wstring& name, double rate) {
196 wchar_t title[256];
197 swprintf(title, 256, L"bink_play - %s - frame %u/%u - decode %.1f fps%s%s", name.c_str(), p.index + 1,
198 p.header.frames, rate, p.paused ? L" - paused" : L"", p.loop ? L" - loop" : L"");
199 SetWindowTextW(hwnd, title);
200}
201
202constexpr const char* kDefaultMovie = "Stinger/RSG_STINGER.bk2";
203
204std::string lower_ascii(std::string v) {
205 for (char& c : v) c = (char)std::tolower((unsigned char)c);
206 std::replace(v.begin(), v.end(), '\\', '/');
207 return v;
208}
209
210struct NamedMovie {
211 std::string path;
212 uint64_t offset = 0;
213};
214
215struct NameTable {
216 std::filesystem::path archive; // the archive the table was built from (its first line)
217 std::vector<NamedMovie> movies;
218};
219
220std::filesystem::path name_table_path() {
221 const std::string base = env("LOCALAPPDATA");
222 return base.empty() ? std::filesystem::path() : std::filesystem::path(base) / "Leonida" / "bink_names.csv";
223}
224
225// tools/bink_play.py's table: "# <archive>|<size>|<mtime>", then a header and path,offset,width,height,frames rows.
226// Stale when the archive's size changed. Paths in the table have no commas (they are game file paths).
227bool read_name_table(NameTable& out) {
228 const std::filesystem::path p = name_table_path();
229 std::ifstream f(p);
230 std::string line;
231 if (p.empty() || !f || !std::getline(f, line) || line.rfind("# ", 0) != 0) return false;
232 const std::string stamp = line.substr(2);
233 const size_t bar1 = stamp.find('|'), bar2 = stamp.find('|', bar1 + 1);
234 if (bar1 == std::string::npos || bar2 == std::string::npos) return false;
235 out.archive = std::filesystem::path(stamp.substr(0, bar1));
236 std::error_code ec;
237 const auto size = std::filesystem::file_size(out.archive, ec);
238 if (ec || std::to_string(size) != stamp.substr(bar1 + 1, bar2 - bar1 - 1)) return false;
239 std::getline(f, line); // header
240 out.movies.clear();
241 while (std::getline(f, line)) {
242 if (!line.empty() && line.back() == '\r') line.pop_back();
243 const size_t c1 = line.find(','), c2 = line.find(',', c1 + 1);
244 if (c1 == std::string::npos || c2 == std::string::npos) continue;
245 out.movies.push_back({line.substr(0, c1), std::strtoull(line.substr(c1 + 1, c2 - c1 - 1).c_str(), nullptr, 10)});
246 }
247 return !out.movies.empty();
248}
249
250// Builds the table with tools/bink_play.py (the repository's copy, two folders up from runtime/build), once.
251bool build_name_table(const std::filesystem::path& game_dir) {
252 wchar_t exe[MAX_PATH];
253 GetModuleFileNameW(nullptr, exe, MAX_PATH);
254 std::filesystem::path tool;
255 for (std::filesystem::path d = std::filesystem::path(exe).parent_path(); !d.empty() && d != d.root_path();
256 d = d.parent_path())
257 if (std::filesystem::is_regular_file(d / "tools" / "bink_play.py")) {
258 tool = d / "tools" / "bink_play.py";
259 break;
260 }
261 if (tool.empty() || game_dir.empty()) return false;
262 std::printf("naming the movies in movies.rpf (about half a minute, once)...\n");
263 std::fflush(stdout);
264 const std::wstring cmd = L"python \"" + tool.wstring() + L"\" --list --game-dir \"" + game_dir.wstring() + L"\"";
265 STARTUPINFOW si{sizeof(si)};
266 si.dwFlags = STARTF_USESTDHANDLES;
267 HANDLE nul = CreateFileW(L"NUL", GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
268 si.hStdOutput = nul; // the list itself isn't wanted, only the table it leaves behind
269 si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
270 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
271 PROCESS_INFORMATION pi{};
272 std::vector<wchar_t> line(cmd.begin(), cmd.end());
273 line.push_back(0);
274 const bool ok = CreateProcessW(nullptr, line.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi);
275 if (ok) {
276 WaitForSingleObject(pi.hProcess, INFINITE);
277 CloseHandle(pi.hThread);
278 CloseHandle(pi.hProcess);
279 }
280 if (nul != INVALID_HANDLE_VALUE) CloseHandle(nul);
281 return ok;
282}
283
284// The movie a NAME means: exactly that path (case-insensitive), else the only path containing it.
285NamedMovie find_named(const NameTable& table, const std::string& name) {
286 const std::string want = lower_ascii(name);
287 std::vector<const NamedMovie*> part;
288 for (const NamedMovie& m : table.movies) {
289 const std::string have = lower_ascii(m.path);
290 if (have == want) return m;
291 if (have.find(want) != std::string::npos) part.push_back(&m);
292 }
293 if (part.size() == 1) return *part[0];
294 std::string why = part.empty() ? "no movie is named like \"" + name + "\"" :
295 std::to_string(part.size()) + " movies match \"" + name + "\"; be more specific:";
296 for (size_t i = 0; i < part.size() && i < 20; ++i) why += "\n " + part[i]->path;
297 if (part.empty()) why += " (python tools\\bink_play.py --list shows the names)";
298 fatal(why);
299}
300
301} // namespace
302
303int main(int argc, char** argv) {
304 std::string game_dir_arg = env("LEONIDA_GAME_DIR"), movie_arg = env("LEONIDA_MOVIE");
305 long max_frames = -1;
306 bool headless = false, loop = false;
307 for (int i = 1; i < argc; ++i) {
308 const std::string a = argv[i];
309 if (a == "--game-dir" && i + 1 < argc) game_dir_arg = argv[++i];
310 else if (a == "--frames" && i + 1 < argc) {
311 char* end = nullptr;
312 max_frames = std::strtol(argv[++i], &end, 10);
313 if (!end || *end || max_frames <= 0) fatal("--frames takes a positive count");
314 } else if (a == "--headless") headless = true;
315 else if (a == "--loop") loop = true;
316 else if (!a.empty() && a[0] != '-') movie_arg = a;
317 else {
318 std::fprintf(stderr, "usage: bink_play [NAME | movie.bk2 | archive.rpf@OFFSET] [--game-dir DIR] "
319 "[--frames N] [--headless] [--loop]\n");
320 return 2;
321 }
322 }
323 g_windowed = !headless;
324 // CTest's headless smoke run gives no movie: that is a skip, not a request for the default one.
325 if (movie_arg.empty() && headless) {
326 std::printf("SKIP (no package/movie)\n");
327 return 77;
328 }
329 if (movie_arg.empty()) movie_arg = kDefaultMovie;
330
331 // A name (not a file, not archive@OFFSET) goes through the name table, which also knows the game folder.
332 std::error_code ec;
333 const bool is_name = movie_arg.find('@') == std::string::npos && !std::filesystem::is_regular_file(movie_arg, ec);
334 if (is_name) {
335 NameTable table;
336 if (!read_name_table(table)) {
337 if (game_dir_arg.empty())
338 fatal("bink_play needs the game folder once, to name the movies:\n\n"
339 " bink_play " + movie_arg + " --game-dir <package folder>\n\n"
340 "After that, double-clicking bink_play.exe plays the stinger.");
341 build_name_table(game_dir_arg);
342 if (!read_name_table(table)) fatal("could not build the movie name table with tools\\bink_play.py");
343 }
344 const NamedMovie m = find_named(table, movie_arg);
345 std::printf("%s\n", m.path.c_str());
346 if (game_dir_arg.empty()) game_dir_arg = table.archive.parent_path().string();
347 movie_arg = table.archive.string() + "@" + std::to_string(m.offset);
348 }
349 if (game_dir_arg.empty()) fatal("no game folder: pass --game-dir or set LEONIDA_GAME_DIR");
350
351 const std::filesystem::path game_dir = game_dir_arg;
352 std::filesystem::path movie = movie_arg;
353 uint64_t offset = 0;
354 if (const size_t at = movie_arg.rfind('@'); at != std::string::npos) {
355 char* end = nullptr;
356 offset = std::strtoull(movie_arg.c_str() + at + 1, &end, 0);
357 if (at + 1 == movie_arg.size() || !end || *end) fatal("the movie's @OFFSET is not a number");
358 movie = movie_arg.substr(0, at);
359 if (movie.is_relative() && !std::filesystem::exists(movie)) movie = game_dir / movie;
360 }
361 if (!std::filesystem::is_regular_file(game_dir / "Bink2Scarlett.dll", ec))
362 fatal("the game folder does not contain Bink2Scarlett.dll");
363 if (!std::filesystem::is_regular_file(movie, ec)) fatal("the movie is not a file");
364
365 Player player;
366 g_player = &player;
367 player.header = read_movie_header(movie, offset);
368 player.loop = loop;
369 const MovieHeader& h = player.header;
370 std::printf("movie: %ux%u, %u frames, %u/%u fps\n", h.width, h.height, h.frames, h.fps_num, h.fps_den);
371
372 try {
373 rt::Loader loader(game_dir);
374 rt::Module& dll = loader.load(game_dir / "Bink2Scarlett.dll");
375 for (auto& r : dll.imports)
376 if (r.binding == rt::Binding::Unimplemented && rt::lower(r.dll).find("xaudio") == std::string::npos)
377 fatal("Bink2Scarlett.dll import " + r.dll + "!" + r.name + " is unimplemented");
378 BinkApi& api = player.api;
379 bind(dll, "BinkOpen", api.open);
380 bind(dll, "BinkDoFrame", api.do_frame);
381 bind(dll, "BinkCopyToBuffer", api.copy);
382 bind(dll, "BinkNextFrame", api.next);
383 bind(dll, "BinkGoto", api.go_to);
384 bind(dll, "BinkClose", api.close);
385 bind(dll, "BinkGetError", api.get_error);
386 if (offset) {
387 bind(dll, "BinkSetFileOffset", api.set_file_offset);
388 api.set_file_offset(offset);
389 }
390
391 player.bink = api.open(movie.string().c_str(), offset ? kFileOffset : 0);
392 if (!player.bink) {
393 const char* e = api.get_error ? api.get_error() : nullptr;
394 fatal(std::string("BinkOpen failed: ") + (e && *e ? e : "(no BinkGetError text)"));
395 }
396 player.frame.assign((size_t)h.width * 4 * h.height, 0);
397 player.decode();
398
399 using clock = std::chrono::steady_clock;
400 const auto frame_time = std::chrono::duration<double>((double)h.fps_den / h.fps_num);
401 const uint32_t last = max_frames > 0 ? (uint32_t)std::min<long>(max_frames, (long)h.frames) : h.frames;
402
403 if (headless) {
404 const auto start = clock::now();
405 uint32_t decoded = 1;
406 while (decoded < last) {
407 api.next(player.bink);
408 player.decode();
409 ++decoded;
410 }
411 const double s = std::chrono::duration<double>(clock::now() - start).count();
412 std::printf("decoded %u frames in %.2f s (%.1f fps; the movie runs at %.2f fps)\n", decoded, s,
413 s > 0 ? decoded / s : 0.0, (double)h.fps_num / h.fps_den);
414 api.close(player.bink);
415 std::printf("RESULT PASS\n");
416 return 0;
417 }
418
419 WNDCLASSW wc{};
420 wc.lpfnWndProc = window_proc;
421 wc.hInstance = GetModuleHandleW(nullptr);
422 wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
423 wc.lpszClassName = L"LeonidaBinkPlay";
424 RegisterClassW(&wc);
425 // Start at up to 1280 wide (or the movie's size if smaller), the movie's aspect ratio.
426 const int start_w = (int)std::min<uint32_t>(h.width, 1280);
427 RECT r{0, 0, start_w, (int)((int64_t)start_w * h.height / h.width)};
428 AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);
429 HWND hwnd = CreateWindowW(wc.lpszClassName, L"bink_play", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT,
430 CW_USEDEFAULT, r.right - r.left, r.bottom - r.top, nullptr, nullptr, wc.hInstance,
431 nullptr);
432 if (!hwnd) fatal("CreateWindow failed");
433 const std::wstring name = movie.filename().wstring() + (offset ? L"@" + std::to_wstring(offset) : L"");
434
435 auto due = clock::now() + frame_time;
436 auto rate_start = clock::now();
437 uint32_t rate_frames = 0, shown = 1;
438 double rate = 0;
439 while (!player.quit) {
440 MSG msg;
441 while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
442 TranslateMessage(&msg);
443 DispatchMessageW(&msg);
444 }
445 if (player.quit) break;
446 if (player.seek_pending) {
447 player.seek_pending = false;
448 player.go_to(player.seek_to);
449 InvalidateRect(hwnd, nullptr, FALSE);
450 due = clock::now() + frame_time;
451 }
452 if (player.paused || clock::now() < due) {
453 set_title(hwnd, player, name, rate);
454 std::this_thread::sleep_for(std::chrono::milliseconds(1));
455 continue;
456 }
457 if (player.index + 1 >= h.frames || (max_frames > 0 && shown >= last)) {
458 if (!player.loop) break;
459 player.go_to(0);
460 } else {
461 api.next(player.bink);
462 player.decode();
463 ++player.index;
464 }
465 ++shown;
466 InvalidateRect(hwnd, nullptr, FALSE);
467 UpdateWindow(hwnd);
468 ++rate_frames;
469 const double elapsed = std::chrono::duration<double>(clock::now() - rate_start).count();
470 if (elapsed >= 1.0) {
471 rate = rate_frames / elapsed;
472 rate_frames = 0;
473 rate_start = clock::now();
474 }
475 set_title(hwnd, player, name, rate);
476 // Hold the movie's frame rate; when decoding falls behind, don't try to catch up in a burst.
477 due += std::chrono::duration_cast<clock::duration>(frame_time);
478 if (clock::now() > due + std::chrono::duration_cast<clock::duration>(frame_time * 4)) due = clock::now();
479 }
480 if (IsWindow(hwnd)) DestroyWindow(hwnd);
481 api.close(player.bink);
482 std::printf("played %u frames\n", shown);
483 return 0;
484 } catch (const std::exception& e) {
485 fatal(e.what());
486 }
487}
diff --git a/runtime/test/bink_play.md b/runtime/test/bink_play.md
new file mode 100644
index 000000000..3fab83985
--- /dev/null
+++ b/runtime/test/bink_play.md
@@ -0,0 +1,51 @@
1# `bink_play`: watch a Bink 2 movie through the package's decoder
2
3`bink_play.cpp` maps the package's `Bink2Scarlett.dll` with `rt::Loader` (the path `bink_decode_test` checks) and plays
4a Bink 2 movie in a window at the movie's frame rate. A movie inside an archive plays where it is: nothing is
5extracted and nothing it decodes is written to disk.
6
7```sh
8bink_play # no movie: plays Stinger/RSG_STINGER.bk2 (so a double-click plays it)
9bink_play stinger # a movie's path in the game, or any unique part of it
10bink_play TV/<name>.bk2 --loop
11bink_play movies.rpf@OFFSET | file.bk2 # an offset in an archive, or a loose .bk2
12```
13
14Options: `--game-dir DIR`, `--frames N`, `--headless`, `--loop`. The game folder comes from `--game-dir`,
15`LEONIDA_GAME_DIR`, or the archive the name table was built from.
16
17Names come from the table `tools/bink_play.py` keeps in `%LOCALAPPDATA%\Leonida\bink_names.csv` (names, offsets
18and frame sizes from `tools/bink_names.py` and `common.rpf`'s mount lists; no movie data), rebuilt when the archive's
19size changes. Without a table, `bink_play` runs that tool once to build it, which takes about half a minute and needs
20the game folder the first time: `bink_play stinger --game-dir C:\path\to\package`. After that a double-click
21is enough. `python tools/bink_play.py --list [TEXT]` lists the names.
22
23For `archive@OFFSET` it calls `BinkSetFileOffset(OFFSET)` and opens the archive with `BinkOpen`'s `BINKFILEOFFSET`
24flag (0x20); without the flag the offset is ignored and `BinkOpen` reports "Not a Bink file". An error in a windowed
25run is shown in a message box too, since a double-clicked console closes with the process.
26
27| Key | Action |
28|---|---|
29| Space | pause / resume |
30| Left / Right | one second back / forward (`BinkGoto`) |
31| Home | back to the first frame |
32| L | loop on / off |
33| Esc, closing the window | quit |
34
35The window title shows the frame number and the rate frames are being shown. The frame is scaled to the window with
36its aspect ratio kept (GDI `StretchDIBits`, no GPU path).
37
38`--headless` decodes without a window as fast as it can and prints the decode rate; `--frames N` stops after N
39frames. CTest runs `bink_play --headless --frames 30` as `bink_play_headless`, which skips (exit 77) unless
40`LEONIDA_MOVIE` names a movie (a headless run never falls back to the stinger).
41
42## Measured on 1.0.2.1
43
44`Stinger/RSG_STINGER.bk2` (3840x2160, 450 frames, 30 fps), played from inside `movies.rpf`: 90 frames decode
45headless in about 1 s (81-118 fps over runs) on a Ryzen 7 5700X (the decoder is CPU-only), so the 4K stinger plays in
46real time; the windowed run shows all 450 frames.
47
48## Gaps
49
50No audio: the movie's Bink Audio tracks are not decoded and no sound system is opened (as in `bink_decode_test`).
51Playback uses the synchronous `BinkDoFrame` path only.
diff --git a/runtime/test/buffer_va_index_test.cpp b/runtime/test/buffer_va_index_test.cpp
new file mode 100644
index 000000000..3368e8b8b
--- /dev/null
+++ b/runtime/test/buffer_va_index_test.cpp
@@ -0,0 +1,255 @@
1// BufferVaIndex (runtime/src/buffer_va_index.h): the VA -> buffer lookup behind VulkanContext::buffer_at. CPU only.
2//
3// Checks fixed cases (edges, aliasing placed buffers, re-registration), then random tables against a linear scan
4// with the same rule, and prints how long a lookup takes against the linear scan over every resource it replaces.
5// `--bench` times larger tables.
6
7#include "../src/buffer_va_index.h"
8
9#include <chrono>
10#include <cstdint>
11#include <cstdio>
12#include <cstring>
13#include <random>
14#include <unordered_map>
15#include <vector>
16
17using leonida::BufferVaIndex;
18using Index = BufferVaIndex<std::uintptr_t>;
19
20namespace {
21
22int failures = 0;
23
24void check(bool ok, const char* what) {
25 if (ok) return;
26 std::printf("FAIL: %s\n", what);
27 ++failures;
28}
29
30// The id that holds `va`, 0 for none.
31std::uintptr_t at(const Index& index, std::uint64_t va) {
32 Index::Hit hit{};
33 return index.find(va, hit) ? hit.id : 0;
34}
35
36void fixed_cases() {
37 Index index;
38 check(at(index, 0x1000) == 0, "an empty index holds nothing");
39
40 index.insert(0x1000, 0x100, 1); // [0x1000, 0x1100)
41 index.insert(0x2000, 0x10, 2); // [0x2000, 0x2010)
42 check(at(index, 0x1000) == 1, "the first byte");
43 check(at(index, 0x10ff) == 1, "the last byte");
44 check(at(index, 0x1100) == 0, "one past the end");
45 check(at(index, 0x0fff) == 0, "one before the start");
46 check(at(index, 0x1800) == 0, "a gap between two buffers");
47 check(at(index, 0x200f) == 2, "the second buffer's last byte");
48 check(at(index, ~std::uint64_t(0)) == 0, "the highest VA");
49
50 Index::Hit hit{};
51 check(index.find(0x1080, hit) && hit.start == 0x1000 && hit.size == 0x100, "a hit names its range");
52
53 index.insert(0, 0x100, 3);
54 index.insert(0x3000, 0, 4);
55 check(index.size() == 2 && at(index, 0) == 0 && at(index, 0x3000) == 0, "a null VA or an empty range is not indexed");
56
57 // Aliasing placed buffers: a long one with two short ones inside it. The nearest start that holds the VA wins.
58 Index alias;
59 alias.insert(0x10000, 0x10000, 10); // [0x10000, 0x20000)
60 alias.insert(0x11000, 0x100, 11); // inside it
61 alias.insert(0x12000, 0x100, 12); // inside it
62 check(at(alias, 0x11080) == 11, "a short buffer inside a long one");
63 check(at(alias, 0x11100) == 10, "past the short buffer, the long one still holds the VA");
64 check(at(alias, 0x1f000) == 10, "past every short buffer");
65 check(at(alias, 0x20000) == 0, "past the long buffer");
66
67 // Two resources placed at the same offset: the larger ID, either way they were added.
68 alias.insert(0x30000, 0x100, 21);
69 alias.insert(0x30000, 0x200, 20);
70 check(at(alias, 0x30080) == 21, "the same start: the larger ID");
71 check(at(alias, 0x30180) == 20, "the same start: past the shorter one");
72
73 // Erasing and re-registering.
74 alias.erase(0x11000, 11);
75 check(at(alias, 0x11080) == 10, "an erased buffer leaves the one around it");
76 alias.erase(0x11000, 11); // twice: nothing
77 alias.erase(0x10000, 99); // a wrong ID: nothing
78 check(at(alias, 0x10000) == 10, "an erase with the wrong ID keeps the range");
79 alias.erase(0x10000, 10);
80 alias.erase(0x12000, 12);
81 alias.erase(0x30000, 20);
82 alias.erase(0x30000, 21);
83 check(alias.size() == 0 && at(alias, 0x10000) == 0, "everything erased");
84 alias.insert(0x40000, 0x10, 30); // the bound restarts from an empty index
85 check(at(alias, 0x40008) == 30 && at(alias, 0x40010) == 0, "an index refilled after it emptied");
86
87 // The bound follows the live ranges: freeing the longest one brings it down to the next longest.
88 Index bound;
89 bound.insert(0x10000, 0x100, 1);
90 bound.insert(0x20000, 0x100, 2); // the same size twice: dropping one keeps the other's
91 bound.insert(0x30000, 0x40000000, 3);
92 check(bound.longest() == 0x40000000, "the bound is the longest range");
93 bound.erase(0x30000, 3);
94 check(bound.longest() == 0x100, "freeing the longest range lowers the bound");
95 bound.erase(0x10000, 1);
96 check(bound.longest() == 0x100 && at(bound, 0x20080) == 2, "a range of the same size keeps the bound");
97 bound.insert(0x20000, 0x40, 2); // re-registered with a smaller size: the old size goes
98 check(bound.longest() == 0x40 && at(bound, 0x20040) == 0, "re-registering replaces the size");
99 bound.erase(0x20000, 2);
100 check(bound.longest() == 0 && bound.size() == 0, "an empty index has no bound");
101}
102
103// The rule BufferVaIndex follows, by a scan: among the ranges that hold va, the greatest (start, id).
104struct Range {
105 std::uint64_t start, size;
106 std::uintptr_t id;
107};
108
109std::uintptr_t scan(const std::vector<Range>& ranges, std::uint64_t va) {
110 const Range* best = nullptr;
111 for (const Range& r : ranges) {
112 if (va < r.start || va - r.start >= r.size) continue;
113 if (!best || r.start > best->start || (r.start == best->start && r.id > best->id)) best = &r;
114 }
115 return best ? best->id : 0;
116}
117
118void random_tables() {
119 std::mt19937_64 rng(0x1e0a1da);
120 for (int round = 0; round < 200; ++round) {
121 Index index;
122 std::vector<Range> ranges;
123 const bool aliasing = round % 2; // half the tables pack buffers apart, half overlap them
124 std::uint64_t next = 0x10000;
125 const int count = 1 + int(rng() % 64);
126 for (int i = 0; i < count; ++i) {
127 const std::uint64_t size = 1 + rng() % 0x4000;
128 const std::uint64_t start = aliasing ? 0x10000 + rng() % 0x20000 : next;
129 next += size + rng() % 0x1000;
130 const Range r{start, size, std::uintptr_t(i + 1)};
131 ranges.push_back(r);
132 index.insert(r.start, r.size, r.id);
133 }
134 // Drop a few, as remove_resource does.
135 for (int i = 0; i < count / 4; ++i) {
136 const std::size_t k = rng() % ranges.size();
137 index.erase(ranges[k].start, ranges[k].id);
138 ranges.erase(ranges.begin() + std::ptrdiff_t(k));
139 if (ranges.empty()) break;
140 }
141 std::uint64_t longest = 0;
142 for (const Range& r : ranges) longest = r.size > longest ? r.size : longest;
143 if (index.longest() != longest) {
144 std::printf("FAIL: round %d: bound %llu, longest live range %llu\n", round,
145 (unsigned long long)index.longest(), (unsigned long long)longest);
146 ++failures;
147 return;
148 }
149 for (int q = 0; q < 2000; ++q) {
150 const std::uint64_t va = 0x8000 + rng() % (next + 0x20000);
151 if (at(index, va) != scan(ranges, va)) {
152 std::printf("FAIL: round %d va 0x%llx: index %llu, scan %llu\n", round, (unsigned long long)va,
153 (unsigned long long)at(index, va), (unsigned long long)scan(ranges, va));
154 ++failures;
155 return;
156 }
157 }
158 }
159}
160
161// What buffer_at did before: a walk over every registered resource, images included, in an unordered_map.
162struct Binding {
163 bool image;
164 std::uint64_t va, size;
165};
166
167void time_lookups(std::size_t resources) {
168 std::unordered_map<std::uintptr_t, Binding> all;
169 Index index;
170 std::vector<std::uint64_t> vas;
171 std::mt19937_64 rng(resources);
172 std::uint64_t next = 0x10000;
173 for (std::size_t i = 1; i <= resources; ++i) {
174 if (i % 2) { // half images, as in a frame's working set
175 all[i] = {true, 0, 0};
176 continue;
177 }
178 const std::uint64_t size = 256 + rng() % (1 << 20);
179 all[i] = {false, next, size};
180 index.insert(next, size, i);
181 vas.push_back(next + rng() % size);
182 next += (size + 255) / 256 * 256;
183 }
184 constexpr int lookups = 20000;
185 using clock = std::chrono::steady_clock;
186 std::uint64_t sink = 0;
187
188 auto t0 = clock::now();
189 for (int i = 0; i < lookups; ++i) {
190 const std::uint64_t va = vas[std::size_t(i) % vas.size()];
191 for (const auto& [id, b] : all) {
192 if (b.image || va < b.va || va - b.va >= b.size) continue;
193 sink += id;
194 break;
195 }
196 }
197 const double linear = std::chrono::duration<double, std::nano>(clock::now() - t0).count() / lookups;
198
199 t0 = clock::now();
200 for (int i = 0; i < lookups; ++i) sink += at(index, vas[std::size_t(i) % vas.size()]);
201 const double indexed = std::chrono::duration<double, std::nano>(clock::now() - t0).count() / lookups;
202
203 std::printf("%7zu resources: linear scan %10.1f ns/lookup, index %6.1f ns/lookup (x%.0f)%s\n", resources, linear,
204 indexed, linear / (indexed > 0 ? indexed : 1), sink ? "" : " ");
205}
206
207// A miss past the last of many small buffers, once a large buffer has come and gone (found in review of #2823): the
208// index that held it must be as fast as one that never did.
209void time_miss_after_free() {
210 constexpr std::uint64_t count = 20000, stride = 256;
211 Index fresh, churned;
212 for (std::uint64_t i = 0; i < count; ++i) {
213 fresh.insert(0x10000 + i * stride, stride, i + 1);
214 churned.insert(0x10000 + i * stride, stride, i + 1);
215 }
216 churned.insert(0x10000, std::uint64_t(1) << 30, count + 1); // 1 GiB over all of them
217 churned.erase(0x10000, count + 1);
218 check(churned.longest() == stride, "the bound comes back down after a large buffer is freed");
219
220 const std::uint64_t miss = 0x10000 + count * stride + stride;
221 constexpr int lookups = 20000;
222 using clock = std::chrono::steady_clock;
223 std::uint64_t sink = 0;
224 double ns[2];
225 const Index* indexes[2] = {&fresh, &churned};
226 for (int k = 0; k < 2; ++k) {
227 const auto t0 = clock::now();
228 for (int i = 0; i < lookups; ++i) sink += at(*indexes[k], miss + std::uint64_t(i % 64));
229 ns[k] = std::chrono::duration<double, std::nano>(clock::now() - t0).count() / lookups;
230 }
231 std::printf("miss past %llu buffers: fresh index %.1f ns, after a freed 1 GiB buffer %.1f ns%s\n",
232 (unsigned long long)count, ns[0], ns[1], sink ? " (hit?)" : "");
233}
234
235} // namespace
236
237int main(int argc, char** argv) {
238 fixed_cases();
239 random_tables();
240 if (failures) {
241 std::printf("%d failure(s)\n", failures);
242 return 1;
243 }
244 time_miss_after_free();
245 if (failures) {
246 std::printf("%d failure(s)\n", failures);
247 return 1;
248 }
249 std::puts("BufferVaIndex: fixed cases and 200 random tables agree with the scan");
250 const bool bench = argc > 1 && std::strcmp(argv[1], "--bench") == 0;
251 for (const std::size_t n : {std::size_t(1000), std::size_t(10000)}) time_lookups(n);
252 if (bench)
253 for (const std::size_t n : {std::size_t(50000), std::size_t(100000)}) time_lookups(n);
254 return 0;
255}
diff --git a/runtime/test/check_console_paths.cmake b/runtime/test/check_console_paths.cmake
new file mode 100644
index 000000000..bfbfe2a96
--- /dev/null
+++ b/runtime/test/check_console_paths.cmake
@@ -0,0 +1,10 @@
1# Redirect the loader's stdout so both console paths must survive as UTF-8.
2execute_process(
3 COMMAND ${RUNNER} "${LOADER}" --game-dir "game-Игра" --overlay "overlay-保存"
4 --run "${GUEST}" -- hello 42
5 TIMEOUT 90 ENCODING UTF-8
6 RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error)
7if(NOT code STREQUAL "0" OR
8 NOT output MATCHES "console paths: GAME: -> [^\n]*game-Игра, writes -> [^\n]*overlay-保存\r?\n")
9 message(FATAL_ERROR "Runtime did not report both Unicode paths (exit ${code})\n${output}\n${error}")
10endif()
diff --git a/runtime/test/check_d3d12_trace.py b/runtime/test/check_d3d12_trace.py
index bbb7b6987..fb8eccac1 100644
--- a/runtime/test/check_d3d12_trace.py
+++ b/runtime/test/check_d3d12_trace.py
@@ -60,6 +60,8 @@ def main():
60 "ID3D12GraphicsCommandList::Reset ok", 60 "ID3D12GraphicsCommandList::Reset ok",
61 "ID3D12GraphicsCommandList::SetDescriptorHeaps ignored", 61 "ID3D12GraphicsCommandList::SetDescriptorHeaps ignored",
62 "ID3D12GraphicsCommandList::SetGraphicsRootDescriptorTable called", 62 "ID3D12GraphicsCommandList::SetGraphicsRootDescriptorTable called",
63 "ID3D12GraphicsCommandList::SetComputeRootSignature called",
64 "ID3D12GraphicsCommandList::Dispatch called",
63 "ID3D12GraphicsCommandList::DrawInstanced called", 65 "ID3D12GraphicsCommandList::DrawInstanced called",
64 "ID3D12GraphicsCommandList::DrawIndexedInstanced called", 66 "ID3D12GraphicsCommandList::DrawIndexedInstanced called",
65 "ID3D12GraphicsCommandList::Close failed", 67 "ID3D12GraphicsCommandList::Close failed",
diff --git a/runtime/test/check_game_dir.cmake b/runtime/test/check_game_dir.cmake
new file mode 100644
index 000000000..039a1ade3
--- /dev/null
+++ b/runtime/test/check_game_dir.cmake
@@ -0,0 +1,34 @@
1# Run the stand-in game from its own folder by bare name, as a player would (`gta6rt --run game.exe`), and again
2# with `--game-dir .`. In both, GAME: has to name that folder as an absolute path: the guest moves its current
3# directory away and then reads GAME:\tiny_game_probe.txt (argument game-file). Before, a bare name left GAME: with
4# an empty root (`console paths: GAME: -> , writes -> overlay`) and the open failed with ERROR_PATH_NOT_FOUND.
5# The verdict is checked from the output, as check_loaded_gdk.cmake does, because under Wine an exit status alone
6# can look successful.
7get_filename_component(guest_dir "${GUEST}" DIRECTORY)
8get_filename_component(guest_name "${GUEST}" NAME)
9file(WRITE "${guest_dir}/tiny_game_probe.txt" "game")
10set(failures "")
11foreach(variant "bare" "dot")
12 if(variant STREQUAL "dot")
13 set(dir_args --game-dir .)
14 else()
15 set(dir_args "")
16 endif()
17 execute_process(
18 COMMAND ${RUNNER} "${LOADER}" ${dir_args} --run "${guest_name}" -- hello 42 game-file
19 WORKING_DIRECTORY "${guest_dir}"
20 TIMEOUT 90
21 RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE output)
22 string(REPLACE "\r\n" "\n" output "${output}")
23 # An absolute GAME: root: a drive letter (Windows, and Wine's Z:) or a leading slash, and an overlay inside it.
24 if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_game: PASS GAME:"
25 OR NOT output MATCHES "(^|\n)tiny_game: OK(\n|$)"
26 OR NOT output MATCHES "(^|\n)console paths: GAME: -> ([A-Za-z]:|[\\/])[^\n]*, writes -> ([A-Za-z]:|[\\/])[^\n]*overlay(\n|$)"
27 OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)")
28 string(APPEND failures "--- ${variant}: returned ${code}\n${output}\n")
29 endif()
30endforeach()
31file(REMOVE "${guest_dir}/tiny_game_probe.txt")
32if(failures)
33 message(FATAL_ERROR "GAME: did not resolve to the game folder\n${failures}")
34endif()
diff --git a/runtime/test/check_loaded_gdk.cmake b/runtime/test/check_loaded_gdk.cmake
index 0df68a1d8..237a30066 100644
--- a/runtime/test/check_loaded_gdk.cmake
+++ b/runtime/test/check_loaded_gdk.cmake
@@ -2,11 +2,13 @@
2# check_loaded_async.cmake does: under Wine an exit status alone can look successful even when the guest failed. 2# check_loaded_async.cmake does: under Wine an exit status alone can look successful even when the guest failed.
3get_filename_component(guest_dir "${GUEST}" DIRECTORY) 3get_filename_component(guest_dir "${GUEST}" DIRECTORY)
4get_filename_component(guest_name "${GUEST}" NAME) 4get_filename_component(guest_name "${GUEST}" NAME)
5file(WRITE "${guest_dir}/host_shim_probe.txt" "shim")
5execute_process( 6execute_process(
6 COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" 7 COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" -- host-shim-probe
7 WORKING_DIRECTORY "${guest_dir}" 8 WORKING_DIRECTORY "${guest_dir}"
8 TIMEOUT 90 9 TIMEOUT 90
9 RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE output) 10 RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE output)
11file(REMOVE "${guest_dir}/host_shim_probe.txt")
10string(REPLACE "\r\n" "\n" output "${output}") 12string(REPLACE "\r\n" "\n" output "${output}")
11if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_gdk_load: PASS(\n|$)" 13if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_gdk_load: PASS(\n|$)"
12 OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") 14 OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)")
diff --git a/runtime/test/check_vk_pipeline_cli.cmake b/runtime/test/check_vk_pipeline_cli.cmake
index cec400b6d..3d3c39606 100644
--- a/runtime/test/check_vk_pipeline_cli.cmake
+++ b/runtime/test/check_vk_pipeline_cli.cmake
@@ -21,6 +21,7 @@ check_invalid(--large-module-bytes -1)
21check_invalid(--slow nonsense) 21check_invalid(--slow nonsense)
22check_invalid(--slow nan) 22check_invalid(--slow nan)
23check_invalid(--slow -0.5) 23check_invalid(--slow -0.5)
24check_invalid(--slow 1.2.3) # strtod must consume the whole token, not just its numeric prefix
24check_invalid(--stage --graphics-only) 25check_invalid(--stage --graphics-only)
25check_invalid(--stats) 26check_invalid(--stats)
26 27
diff --git a/runtime/test/conservative_raster_test.cpp b/runtime/test/conservative_raster_test.cpp
new file mode 100644
index 000000000..b16053f1e
--- /dev/null
+++ b/runtime/test/conservative_raster_test.cpp
@@ -0,0 +1,21 @@
1#include "../src/conservative_raster.h"
2#include <cstdio>
3#include <limits>
4
5int main() {
6 using leonida::conservative_raster::tier1;
7 unsigned failures = 0;
8 const auto check = [&](bool value) { if (!value) ++failures; };
9 check(tier1(true, 8, 0.0f));
10 check(tier1(true, 8, 1.0f / 256.0f));
11 check(tier1(true, 8, 0.5f - 1.0f / 512.0f));
12 check(!tier1(false, 8, 0.0f));
13 check(!tier1(true, 7, 0.0f));
14 check(!tier1(true, 8, 0.5f));
15 check(!tier1(true, 8, -0.001f));
16 check(!tier1(true, 8, std::numeric_limits<float>::infinity()));
17 check(!tier1(true, 8, std::numeric_limits<float>::quiet_NaN()));
18 if (failures) std::fprintf(stderr, "conservative raster capability checks: %u failures\n", failures);
19 else std::puts("conservative raster: enabled extension, precision and uncertainty bounds checked");
20 return failures ? 1 : 0;
21}
diff --git a/runtime/test/d3d12_bundle_forbidden_test.cpp b/runtime/test/d3d12_bundle_forbidden_test.cpp
new file mode 100644
index 000000000..3e3a5d133
--- /dev/null
+++ b/runtime/test/d3d12_bundle_forbidden_test.cpp
@@ -0,0 +1,289 @@
1// Calls a bundle may not make: what Close of the bundle and of the parent that executes it return for each, on the
2// layer and on Windows' own D3D12 (no debug layer; the default adapter and WARP). One call is recorded per bundle,
3// with valid arguments, on a bundle of its own; the parent direct list executes it, is closed and submitted, and the
4// device's removed reason is read after the fence. A host device is created per call, so a call that removes the
5// device does not touch the next one. Microsoft documents RSSetViewports, RSSetScissorRects, OMSetRenderTargets,
6// ClearState and the calls below as not allowed in a bundle; the table is what the PC runtime does without the debug
7// layer (every one of them fails the bundle's Close with E_FAIL, on both adapters, and executing such a bundle
8// crashes the PC runtime, so the parent is only closed for bundles that closed). The layer is held to the same
9// verdict for every call where both host adapters agree; its code for a refused bundle is E_INVALIDARG.
10// Both host adapters always run (LEONIDA_HOST_ADAPTER is not read), except under Wine, where the host is skipped.
11// No game data.
12#include "vk_test_device.h"
13#include "d3d12_test_shaders.h"
14#include "host_wine.h"
15#include "../shims/d3d12_com.h"
16
17#include <dxgi1_4.h>
18
19#include <cstdio>
20#include <functional>
21#include <string>
22#include <vector>
23
24#define CHECK(condition) do { \
25 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \
26} while (0)
27
28#define REQUIRE(condition) do { \
29 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
30} while (0)
31
32using namespace d3d12test;
33
34namespace {
35
36constexpr HRESULT not_run = HRESULT(0x7fff0000); // no parent Close: the bundle could not be executed
37
38struct Env {
39 ID3D12Device* device = nullptr;
40 Ref<ID3D12CommandQueue> queue;
41 Ref<ID3D12Fence> fence;
42 Ref<ID3D12Resource> target, buffer;
43 Ref<ID3D12DescriptorHeap> rtv_heap;
44 D3D12_CPU_DESCRIPTOR_HANDLE rtv{};
45 UINT64 fence_value = 0;
46 Ref<ID3D12CommandAllocator> other_allocator; // a closed bundle for ExecuteBundle inside a bundle
47 Ref<ID3D12GraphicsCommandList> other_bundle;
48
49 bool init(ID3D12Device* d) {
50 device = d;
51 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
52 D3D12_RESOURCE_DESC texture{};
53 texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
54 texture.Width = texture.Height = 16;
55 texture.DepthOrArraySize = texture.MipLevels = 1;
56 texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
57 texture.SampleDesc.Count = 1;
58 texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
59 CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture,
60 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
61 IID_PPV_ARGS(&target.p))));
62 const auto desc = buffer_desc(256);
63 CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc,
64 D3D12_RESOURCE_STATE_COMMON, nullptr,
65 IID_PPV_ARGS(&buffer.p))));
66 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
67 CHECK(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p))));
68 rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart();
69 device->CreateRenderTargetView(target.p, nullptr, rtv);
70 D3D12_COMMAND_QUEUE_DESC queue_desc{};
71 CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
72 CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
73 CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE,
74 IID_PPV_ARGS(&other_allocator.p))));
75 CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, other_allocator.p, nullptr,
76 IID_PPV_ARGS(&other_bundle.p))));
77 CHECK(SUCCEEDED(other_bundle->Close()));
78 return true;
79 }
80};
81
82using Recorder = std::function<void(Env&, ID3D12GraphicsCommandList*)>;
83
84struct Call {
85 const char* name;
86 Recorder record;
87};
88
89struct Outcome {
90 HRESULT bundle_close = E_FAIL, parent_close = not_run, removed = S_OK;
91 HRESULT direct_close = E_FAIL; // the same call, same arguments, on a direct list: the control
92};
93
94std::vector<Call> calls() {
95 return {
96 // Calls the layer did not refuse in a bundle before this test. Every call here is also valid on a direct
97 // list, which run_call checks as a control (none is bundle-only or meaningless there).
98 {"RSSetViewports", [](Env&, ID3D12GraphicsCommandList* b) {
99 const D3D12_VIEWPORT viewport{0, 0, 16, 16, 0, 1};
100 b->RSSetViewports(1, &viewport); }},
101 {"RSSetScissorRects", [](Env&, ID3D12GraphicsCommandList* b) {
102 const D3D12_RECT scissor{0, 0, 16, 16};
103 b->RSSetScissorRects(1, &scissor); }},
104 {"OMSetRenderTargets", [](Env& e, ID3D12GraphicsCommandList* b) {
105 b->OMSetRenderTargets(1, &e.rtv, FALSE, nullptr); }},
106 {"ClearState", [](Env&, ID3D12GraphicsCommandList* b) { b->ClearState(nullptr); }},
107 // Controls: calls the layer already refuses in a bundle.
108 {"ResourceBarrier", [](Env& e, ID3D12GraphicsCommandList* b) {
109 const auto barrier = transition(e.target.p, D3D12_RESOURCE_STATE_RENDER_TARGET,
110 D3D12_RESOURCE_STATE_COPY_SOURCE);
111 b->ResourceBarrier(1, &barrier); }},
112 {"ClearRenderTargetView", [](Env& e, ID3D12GraphicsCommandList* b) {
113 const FLOAT color[4] = {0, 1, 0, 1};
114 b->ClearRenderTargetView(e.rtv, color, 0, nullptr); }},
115 {"SetPredication(null)", [](Env&, ID3D12GraphicsCommandList* b) {
116 b->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); }},
117 {"ExecuteBundle", [](Env& e, ID3D12GraphicsCommandList* b) { b->ExecuteBundle(e.other_bundle.p); }},
118 // Controls: calls a bundle may make.
119 {"OMSetStencilRef", [](Env&, ID3D12GraphicsCommandList* b) { b->OMSetStencilRef(1); }},
120 {"OMSetBlendFactor", [](Env&, ID3D12GraphicsCommandList* b) {
121 const FLOAT factor[4] = {1, 1, 1, 1};
122 b->OMSetBlendFactor(factor); }},
123 };
124}
125
126// One call on one bundle, executed by a parent list, on `device` (its own for a host).
127bool run_call(Env& env, const Call& call, Outcome& out) {
128 ID3D12Device* device = env.device;
129 Ref<ID3D12CommandAllocator> bundle_allocator, allocator;
130 Ref<ID3D12GraphicsCommandList> bundle, list;
131 CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, IID_PPV_ARGS(&bundle_allocator.p))));
132 CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_allocator.p, nullptr,
133 IID_PPV_ARGS(&bundle.p))));
134 // The control: the call is valid, so its refusal in a bundle comes from the bundle rule and not its arguments.
135 {
136 Ref<ID3D12CommandAllocator> direct_allocator;
137 Ref<ID3D12GraphicsCommandList> direct;
138 CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
139 IID_PPV_ARGS(&direct_allocator.p))));
140 CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, direct_allocator.p, nullptr,
141 IID_PPV_ARGS(&direct.p))));
142 call.record(env, direct.p);
143 out.direct_close = direct->Close();
144 }
145 call.record(env, bundle.p);
146 out.bundle_close = bundle->Close();
147 // Executing a bundle whose Close failed crashes the PC runtime (measured), so the parent is left out then.
148 if (FAILED(out.bundle_close)) return true;
149 CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
150 CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
151 IID_PPV_ARGS(&list.p))));
152 list->ExecuteBundle(bundle.p);
153 out.parent_close = list->Close();
154 if (SUCCEEDED(out.parent_close)) {
155 ID3D12CommandList* lists[] = {list.p};
156 env.queue->ExecuteCommandLists(1, lists);
157 // A device that is removed here makes the wait fail; GetDeviceRemovedReason below reports it.
158 if (SUCCEEDED(env.queue->Signal(env.fence.p, ++env.fence_value)))
159 env.fence->SetEventOnCompletion(env.fence_value, nullptr);
160 }
161 out.removed = device->GetDeviceRemovedReason();
162 return true;
163}
164
165struct Run {
166 const char* name = "";
167 bool ran = false;
168 std::vector<Outcome> outcomes;
169};
170
171} // namespace
172
173int main() {
174 std::setvbuf(stdout, nullptr, _IONBF, 0);
175 vktest::Device vk;
176 const auto device_status = vk.initialize();
177 if (device_status == vktest::DeviceStatus::unavailable) {
178 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
179 return 77;
180 }
181 REQUIRE(device_status == vktest::DeviceStatus::ready);
182 const auto list = calls();
183 const unsigned errors_before = vk.validation_errors();
184
185 Run layer;
186 layer.name = "layer";
187 {
188 rt::d3d12::VulkanDeviceInfo info{};
189 info.get_instance_proc = vk.instance_proc;
190 info.instance = vk.instance;
191 info.physical = vk.physical;
192 info.device = vk.device;
193 info.queue = vk.queue;
194 info.queue_family = vk.family;
195 info.buffer_device_address = true;
196 Ref<ID3D12Device> ours;
197 REQUIRE(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p))));
198 Env env;
199 REQUIRE(env.init(ours.p));
200 for (const Call& call : list) {
201 layer.outcomes.emplace_back();
202 REQUIRE(run_call(env, call, layer.outcomes.back()));
203 }
204 layer.ran = true;
205 }
206
207 Run hosts[2];
208 hosts[0].name = "default adapter";
209 hosts[1].name = "WARP";
210 if (hostwine::host_is_wine()) {
211 // Wine's vkd3d answers differently; the host is not compared.
212 } else {
213 Ref<IDXGIFactory4> factory;
214 REQUIRE(SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))));
215 for (int i = 0; i < 2; ++i) {
216 bool usable = true;
217 for (const Call& call : list) {
218 Ref<IDXGIAdapter> adapter;
219 Ref<ID3D12Device> host;
220 if (i == 1 && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) usable = false;
221 if (!usable || FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) {
222 usable = false;
223 break;
224 }
225 Env env;
226 REQUIRE(env.init(host.p));
227 hosts[i].outcomes.emplace_back();
228 REQUIRE(run_call(env, call, hosts[i].outcomes.back()));
229 }
230 hosts[i].ran = usable;
231 }
232 }
233
234 // The layer's bundle Close must match the host's wherever the adapters that ran agree; where the two differ the
235 // case is reported and not compared. The direct-list control must succeed everywhere.
236 const auto text = [](HRESULT hr) {
237 char out[16];
238 if (hr == not_run) return std::string("n/a");
239 std::snprintf(out, sizeof(out), "0x%08lx", static_cast<unsigned long>(hr));
240 return std::string(out);
241 };
242 unsigned failures = 0, compared = 0, disagreed = 0;
243 std::printf("%-24s | %-26s | %-26s | %-26s\n", "call (bundle/parent/removed)", "layer", hosts[0].name, hosts[1].name);
244 for (std::size_t i = 0; i < list.size(); ++i) {
245 std::printf("%-24s", list[i].name);
246 const auto cell = [&](const Run& run) {
247 if (!run.ran) return std::printf(" | %-26s", "(not run)");
248 const Outcome& o = run.outcomes[i];
249 return std::printf(" | %s %s %s", text(o.bundle_close).c_str(), text(o.parent_close).c_str(),
250 text(o.removed).c_str());
251 };
252 cell(layer);
253 cell(hosts[0]);
254 cell(hosts[1]);
255 std::printf("\n");
256 for (const Run* run : {&layer, &hosts[0], &hosts[1]}) {
257 if (run->ran && FAILED(run->outcomes[i].direct_close)) {
258 std::fprintf(stderr, "FAIL %s on %s: Close of the direct-list control is %s\n", list[i].name,
259 run->name, text(run->outcomes[i].direct_close).c_str());
260 ++failures;
261 }
262 }
263 if (!hosts[0].ran && !hosts[1].ran) continue;
264 const Run& first = hosts[0].ran ? hosts[0] : hosts[1];
265 const HRESULT a = first.outcomes[i].bundle_close;
266 if (hosts[0].ran && hosts[1].ran && a != hosts[1].outcomes[i].bundle_close) {
267 std::printf(" the default adapter and WARP disagree on %s: not compared\n", list[i].name);
268 ++disagreed;
269 continue;
270 }
271 ++compared;
272 // The same verdict, not the same code: a refused bundle's Close is E_FAIL on the PC runtime and E_INVALIDARG here.
273 if (SUCCEEDED(layer.outcomes[i].bundle_close) != SUCCEEDED(a)) {
274 std::fprintf(stderr, "FAIL %s: layer bundle Close %s, host %s\n", list[i].name,
275 text(layer.outcomes[i].bundle_close).c_str(), text(a).c_str());
276 ++failures;
277 }
278 }
279 const unsigned validation_errors = vk.validation_errors() - errors_before;
280 if (validation_errors) {
281 std::fprintf(stderr, "%u Vulkan validation errors\n", validation_errors);
282 ++failures;
283 }
284 if (!hosts[0].ran && !hosts[1].ran && !hostwine::host_is_wine())
285 std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n");
286 std::printf("bundle forbidden calls: %zu on the layer, %u compared with the host, %u hosts disagree, %u failures\n",
287 list.size(), compared, disagreed, failures);
288 return failures ? 1 : 0;
289}
diff --git a/runtime/test/d3d12_com_test.cpp b/runtime/test/d3d12_com_test.cpp
index caeb70323..eb921ddce 100644
--- a/runtime/test/d3d12_com_test.cpp
+++ b/runtime/test/d3d12_com_test.cpp
@@ -288,6 +288,13 @@ int main(int argc, char** argv) {
288 EXPECT(invalid_bundle_call([&](auto* b) { 288 EXPECT(invalid_bundle_call([&](auto* b) {
289 b->ClearUnorderedAccessViewFloat({}, uav_view, rt_resource, uav_float, 0, nullptr); })); 289 b->ClearUnorderedAccessViewFloat({}, uav_view, rt_resource, uav_float, 0, nullptr); }));
290 EXPECT(invalid_bundle_call([&](auto* b) { b->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); })); 290 EXPECT(invalid_bundle_call([&](auto* b) { b->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); }));
291 // Measured on the PC runtime (default adapter and WARP, d3d12_bundle_forbidden_test): these fail a bundle's Close.
292 const D3D12_VIEWPORT bundle_viewport{0, 0, 4, 4, 0, 1};
293 const D3D12_RECT bundle_scissor{0, 0, 4, 4};
294 EXPECT(invalid_bundle_call([&](auto* b) { b->RSSetViewports(1, &bundle_viewport); }));
295 EXPECT(invalid_bundle_call([&](auto* b) { b->RSSetScissorRects(1, &bundle_scissor); }));
296 EXPECT(invalid_bundle_call([&](auto* b) { b->OMSetRenderTargets(1, &rtv_handle, FALSE, nullptr); }));
297 EXPECT(invalid_bundle_call([&](auto* b) { b->ClearState(nullptr); }));
291 // D3D-26: DiscardResource and the atomic copies are not allowed in a bundle; WriteBufferImmediate is 298 // D3D-26: DiscardResource and the atomic copies are not allowed in a bundle; WriteBufferImmediate is
292 // ("Recording command lists and bundles", the bundle restrictions and the API restrictions table). 299 // ("Recording command lists and bundles", the bundle restrictions and the API restrictions table).
293 EXPECT(invalid_bundle_call([&](auto* b) { b->DiscardResource(rt_resource, nullptr); })); 300 EXPECT(invalid_bundle_call([&](auto* b) { b->DiscardResource(rt_resource, nullptr); }));
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp
index 8f22c447b..cf7f7c533 100644
--- a/runtime/test/d3d12_compute_test.cpp
+++ b/runtime/test/d3d12_compute_test.cpp
@@ -287,6 +287,8 @@ int main() {
287 const std::uint32_t table_values[4] = {1000, 2000, 3000, 4000}; 287 const std::uint32_t table_values[4] = {1000, 2000, 3000, 4000};
288 std::vector<std::uint32_t> first(elements), second(elements), third(elements); 288 std::vector<std::uint32_t> first(elements), second(elements), third(elements);
289 std::vector<std::uint32_t> cbv_a_out(elements), cbv_oob_out(elements), cbv_b_out(elements), cbv_null_out(elements); 289 std::vector<std::uint32_t> cbv_a_out(elements), cbv_oob_out(elements), cbv_b_out(elements), cbv_null_out(elements);
290 std::vector<std::uint32_t> srv_raw_a(elements), srv_raw_b(elements), srv_struct_a(elements),
291 srv_struct_b(elements), srv_typed(elements), srv_null(elements);
290 { 292 {
291 rt::d3d12::VulkanDeviceInfo info{}; 293 rt::d3d12::VulkanDeviceInfo info{};
292 info.get_instance_proc = d.instance_proc; 294 info.get_instance_proc = d.instance_proc;
@@ -393,15 +395,15 @@ int main() {
393 Ref<ID3DBlob> blob; 395 Ref<ID3DBlob> blob;
394 EXPECT(pso->GetCachedBlob(&blob.p) == S_OK && blob.p); 396 EXPECT(pso->GetCachedBlob(&blob.p) == S_OK && blob.p);
395 const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer()); 397 const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
396 std::vector<std::uint8_t> bytes(p, p + blob->GetBufferSize()); 398 std::vector<std::uint8_t> blob_bytes(p, p + blob->GetBufferSize());
397 auto attempt = [&](const std::vector<std::uint8_t>& b) { 399 auto attempt = [&](const std::vector<std::uint8_t>& b) {
398 D3D12_COMPUTE_PIPELINE_STATE_DESC d = pso_desc; 400 D3D12_COMPUTE_PIPELINE_STATE_DESC d = pso_desc;
399 d.CachedPSO = {b.data(), b.size()}; 401 d.CachedPSO = {b.data(), b.size()};
400 Ref<ID3D12PipelineState> made; 402 Ref<ID3D12PipelineState> made;
401 return device->CreateComputePipelineState(&d, IID_PPV_ARGS(&made.p)); 403 return device->CreateComputePipelineState(&d, IID_PPV_ARGS(&made.p));
402 }; 404 };
403 for (std::size_t at = 0; at < bytes.size(); ++at) { 405 for (std::size_t at = 0; at < blob_bytes.size(); ++at) {
404 auto changed = bytes; 406 auto changed = blob_bytes;
405 changed[at] ^= 0x01; 407 changed[at] ^= 0x01;
406 EXPECT(attempt(changed) == E_INVALIDARG); 408 EXPECT(attempt(changed) == E_INVALIDARG);
407 } 409 }
@@ -411,11 +413,11 @@ int main() {
411 for (int i = 0; i < 4; ++i) b[b.size() - 4 + i] = std::uint8_t(sum >> (8 * i)); 413 for (int i = 0; i < 4; ++i) b[b.size() - 4 + i] = std::uint8_t(sum >> (8 * i));
412 return b; 414 return b;
413 }; 415 };
414 EXPECT(attempt(resealed(bytes, 8)) == D3D12_ERROR_ADAPTER_NOT_FOUND); // vendor 416 EXPECT(attempt(resealed(blob_bytes, 8)) == D3D12_ERROR_ADAPTER_NOT_FOUND); // vendor
415 EXPECT(attempt(resealed(bytes, 12)) == D3D12_ERROR_ADAPTER_NOT_FOUND); // device 417 EXPECT(attempt(resealed(blob_bytes, 12)) == D3D12_ERROR_ADAPTER_NOT_FOUND); // device
416 EXPECT(attempt(resealed(bytes, 16)) == D3D12_ERROR_DRIVER_VERSION_MISMATCH); 418 EXPECT(attempt(resealed(blob_bytes, 16)) == D3D12_ERROR_DRIVER_VERSION_MISMATCH);
417 EXPECT(attempt(resealed(bytes, 20)) == D3D12_ERROR_DRIVER_VERSION_MISMATCH); // pipelineCacheUUID 419 EXPECT(attempt(resealed(blob_bytes, 20)) == D3D12_ERROR_DRIVER_VERSION_MISMATCH); // pipelineCacheUUID
418 EXPECT(attempt(resealed(bytes, 4)) == E_INVALIDARG); // version 420 EXPECT(attempt(resealed(blob_bytes, 4)) == E_INVALIDARG); // version
419 } 421 }
420 422
421 // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so 423 // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so
@@ -470,7 +472,7 @@ int main() {
470 std::memcpy(mapped, table_values, sizeof(table_values)); 472 std::memcpy(mapped, table_values, sizeof(table_values));
471 473
472 // A shader-visible heap in the arena; its first slot gets the upload buffer's VA, written as raw bytes. 474 // A shader-visible heap in the arena; its first slot gets the upload buffer's VA, written as raw bytes.
473 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, 475 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8,
474 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; 476 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
475 Ref<ID3D12DescriptorHeap> heap; 477 Ref<ID3D12DescriptorHeap> heap;
476 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); 478 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
@@ -686,6 +688,191 @@ int main() {
686 std::memcpy(cbv_null_out.data(), src_bytes + 3 * bytes, bytes); 688 std::memcpy(cbv_null_out.data(), src_bytes + 3 * bytes, bytes);
687 } 689 }
688 690
691 // CreateShaderResourceView(buffer): raw, structured, and typed GFX10 V# descriptors in the shader-visible heap.
692 {
693 const UINT inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
694 EXPECT(inc == 32);
695 // 1024-byte arena buffer = 256 uint32 words = 64 16-byte structs / float4 elements.
696 constexpr UINT buf_bytes = 1024;
697 const auto srv_buf_desc = buffer_desc(buf_bytes, D3D12_RESOURCE_FLAG_NONE);
698 const auto deny_buf_desc = buffer_desc(256, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE);
699 Ref<ID3D12Resource> srv_upload, srv_default, srv_deny, srv_readback;
700 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &srv_buf_desc,
701 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
702 IID_PPV_ARGS(&srv_upload.p))));
703 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &srv_buf_desc,
704 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
705 IID_PPV_ARGS(&srv_default.p))));
706 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &deny_buf_desc,
707 D3D12_RESOURCE_STATE_COMMON, nullptr,
708 IID_PPV_ARGS(&srv_deny.p))));
709 const auto srv_rb_desc = buffer_desc(6 * bytes, D3D12_RESOURCE_FLAG_NONE);
710 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &srv_rb_desc,
711 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
712 IID_PPV_ARGS(&srv_readback.p))));
713 void* srv_mapped = nullptr;
714 EXPECT(SUCCEEDED(srv_upload->Map(0, nullptr, &srv_mapped)));
715 auto* words = static_cast<std::uint32_t*>(srv_mapped);
716 for (UINT w = 0; w < buf_bytes / 4; ++w) words[w] = 0x50000u + w;
717 const D3D12_GPU_VIRTUAL_ADDRESS srv_va = srv_default->GetGPUVirtualAddress();
718 EXPECT(srv_va >= 0x10000 && srv_va < (1ull << 32));
719
720 const auto slot_cpu = [&](UINT idx) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + idx * inc)}; };
721 const auto slot_gpu = [&](UINT idx) { return D3D12_GPU_DESCRIPTOR_HANDLE{gpu + idx * inc}; };
722 std::uint8_t zeros[32] = {};
723
724 // Slot 1: Raw buffer SRV A (FirstElement = 0, NumElements = 32 -> 128 bytes; words 32..63 must read 0).
725 D3D12_SHADER_RESOURCE_VIEW_DESC raw_a{};
726 raw_a.Format = DXGI_FORMAT_R32_TYPELESS;
727 raw_a.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
728 raw_a.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
729 raw_a.Buffer = {0, 32, 0, D3D12_BUFFER_SRV_FLAG_RAW};
730 device->CreateShaderResourceView(srv_default.p, &raw_a, slot_cpu(1));
731
732 // Slot 2: Raw buffer SRV B (FirstElement = 64, NumElements = 32 -> negative control shifted by +64 dwords).
733 D3D12_SHADER_RESOURCE_VIEW_DESC raw_b = raw_a;
734 raw_b.Buffer.FirstElement = 64;
735 device->CreateShaderResourceView(srv_default.p, &raw_b, slot_cpu(2));
736
737 // Slot 3: Structured buffer SRV A (stride 16, FirstElement = 0, NumElements = 32 -> elements 32..63 OOB).
738 D3D12_SHADER_RESOURCE_VIEW_DESC struct_a{};
739 struct_a.Format = DXGI_FORMAT_UNKNOWN;
740 struct_a.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
741 struct_a.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
742 struct_a.Buffer = {0, 32, 16, D3D12_BUFFER_SRV_FLAG_NONE};
743 device->CreateShaderResourceView(srv_default.p, &struct_a, slot_cpu(3));
744
745 // Slot 4: Structured buffer SRV B (stride 16, FirstElement = 16, NumElements = 32 -> shifted +16 structs).
746 D3D12_SHADER_RESOURCE_VIEW_DESC struct_b = struct_a;
747 struct_b.Buffer.FirstElement = 16;
748 device->CreateShaderResourceView(srv_default.p, &struct_b, slot_cpu(4));
749
750 // Slot 5: Typed buffer SRV (R32G32B32A32_FLOAT, stride 16, FirstElement = 8, NumElements = 24, custom swizzle).
751 D3D12_SHADER_RESOURCE_VIEW_DESC typed_desc{};
752 typed_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
753 typed_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
754 typed_desc.Shader4ComponentMapping = D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 5); // B,G,R,1
755 typed_desc.Buffer = {8, 24, 0, D3D12_BUFFER_SRV_FLAG_NONE};
756 device->CreateShaderResourceView(srv_default.p, &typed_desc, slot_cpu(5));
757
758 // Slot 6: Typed RGB96 buffer SRV (R32G32B32_FLOAT, stride 12, FirstElement = 2, NumElements = 10).
759 D3D12_SHADER_RESOURCE_VIEW_DESC rgb96_desc{};
760 rgb96_desc.Format = DXGI_FORMAT_R32G32B32_FLOAT;
761 rgb96_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
762 rgb96_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
763 rgb96_desc.Buffer = {2, 10, 0, D3D12_BUFFER_SRV_FLAG_NONE};
764 device->CreateShaderResourceView(srv_default.p, &rgb96_desc, slot_cpu(6));
765
766 // CPU V# decode verification for slots 1..6.
767 const auto decode_slot = [&](UINT idx, leonida::gfx10::Buffer& dec) -> bool {
768 leonida::gfx10::BufferWords rw{};
769 std::memcpy(rw.data(), reinterpret_cast<const void*>(slot_cpu(idx).ptr), sizeof(rw));
770 return leonida::gfx10::decode(rw, dec) &&
771 std::memcmp(reinterpret_cast<const std::uint8_t*>(slot_cpu(idx).ptr) + 16, zeros, 16) == 0;
772 };
773 {
774 leonida::gfx10::Buffer d1{}, d2{}, d3{}, d4{}, d5{}, d6{};
775 EXPECT(decode_slot(1, d1));
776 EXPECT(d1.address == srv_va && d1.stride == 0 && d1.num_records == 128 &&
777 d1.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT) &&
778 d1.oob_select == leonida::gfx10::OobSelect::raw);
779 EXPECT(decode_slot(2, d2));
780 EXPECT(d2.address == srv_va + 256 && d2.stride == 0 && d2.num_records == 128 &&
781 d2.oob_select == leonida::gfx10::OobSelect::raw);
782 EXPECT(decode_slot(3, d3));
783 EXPECT(d3.address == srv_va && d3.stride == 16 && d3.num_records == 32 &&
784 d3.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT) &&
785 d3.oob_select == leonida::gfx10::OobSelect::structured);
786 EXPECT(decode_slot(4, d4));
787 EXPECT(d4.address == srv_va + 256 && d4.stride == 16 && d4.num_records == 32 &&
788 d4.oob_select == leonida::gfx10::OobSelect::structured);
789 EXPECT(decode_slot(5, d5));
790 const leonida::gfx10::Swizzle want_swz = {leonida::gfx10::select_z, leonida::gfx10::select_y,
791 leonida::gfx10::select_x, leonida::gfx10::select_one};
792 EXPECT(d5.address == srv_va + 8 * 16 && d5.stride == 16 && d5.num_records == 24 &&
793 d5.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32G32B32A32_SFLOAT) &&
794 d5.swizzle == want_swz && d5.oob_select == leonida::gfx10::OobSelect::structured);
795 EXPECT(decode_slot(6, d6));
796 EXPECT(d6.address == srv_va + 2 * 12 && d6.stride == 12 && d6.num_records == 10 &&
797 d6.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32G32B32_SFLOAT) &&
798 d6.oob_select == leonida::gfx10::OobSelect::structured);
799 }
800
801 // Invalid/refused buffer SRVs must all leave slot 7 zeroed.
802 const auto expect_zero_srv = [&](ID3D12Resource* res, const D3D12_SHADER_RESOURCE_VIEW_DESC* d) -> bool {
803 std::memset(reinterpret_cast<void*>(slot_cpu(7).ptr), 0xA5, inc);
804 device->CreateShaderResourceView(res, d, slot_cpu(7));
805 return std::memcmp(reinterpret_cast<const void*>(slot_cpu(7).ptr), zeros, sizeof(zeros)) == 0;
806 };
807 EXPECT(expect_zero_srv(srv_default.p, nullptr)); // null desc on buffer
808 EXPECT(expect_zero_srv(srv_deny.p, &raw_a)); // DENY_SHADER_RESOURCE
809 auto bad = raw_a;
810 bad.Format = DXGI_FORMAT_R32_UINT;
811 EXPECT(expect_zero_srv(srv_default.p, &bad)); // RAW requires R32_TYPELESS
812 bad = raw_a;
813 bad.Buffer.StructureByteStride = 4;
814 EXPECT(expect_zero_srv(srv_default.p, &bad)); // RAW requires stride 0
815 bad = struct_a;
816 bad.Format = DXGI_FORMAT_R32_FLOAT;
817 EXPECT(expect_zero_srv(srv_default.p, &bad)); // structured requires DXGI_FORMAT_UNKNOWN
818 bad = struct_a;
819 bad.Buffer.FirstElement = 60;
820 bad.Buffer.NumElements = 10;
821 EXPECT(expect_zero_srv(srv_default.p, &bad)); // out of bounds (70 * 16 > 1024)
822 EXPECT(expect_zero_srv(nullptr, &raw_a)); // null resource -> null V#
823
824 // Upload buffer contents to arena and dispatch 6 GPU passes through the shader-visible descriptor table.
825 // out_a is already in D3D12_RESOURCE_STATE_UNORDERED_ACCESS at the end of the CBV pass.
826 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p)));
827 list->CopyBufferRegion(srv_default.p, 0, srv_upload.p, 0, buf_bytes);
828 const auto srv_ready = transition(srv_default.p, D3D12_RESOURCE_STATE_COPY_DEST,
829 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
830 list->ResourceBarrier(1, &srv_ready);
831 list->SetDescriptorHeaps(1, heaps);
832 list->SetComputeRootSignature(root.p);
833 list->SetComputeRootUnorderedAccessView(1, va_a);
834
835 const struct SrvDispatch {
836 UINT slot_idx;
837 UINT readback_offset;
838 } srv_dispatches[] = {
839 {1, 0 * bytes},
840 {2, 1 * bytes},
841 {3, 2 * bytes},
842 {4, 3 * bytes},
843 {5, 4 * bytes},
844 {7, 5 * bytes},
845 };
846 const std::uint32_t srv_mode[2] = {0u, 0xFFFFFFFFu}; // s1 == 0xFFFFFFFF selects buffer SRV V# mode
847 list->SetComputeRoot32BitConstants(0, 2, srv_mode, 0);
848 for (const auto& cfg : srv_dispatches) {
849 list->SetComputeRootDescriptorTable(2, slot_gpu(cfg.slot_idx));
850 list->Dispatch(1, 1, 1);
851 const auto to_src =
852 transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
853 list->ResourceBarrier(1, &to_src);
854 list->CopyBufferRegion(srv_readback.p, cfg.readback_offset, out_a.p, 0, bytes);
855 const auto to_uav =
856 transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
857 list->ResourceBarrier(1, &to_uav);
858 }
859 EXPECT(list->Close() == S_OK);
860 queue->ExecuteCommandLists(1, lists);
861 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
862 EXPECT(SUCCEEDED(queue->Signal(fence.p, 3)));
863 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(3, nullptr)));
864
865 void* srv_res = nullptr;
866 EXPECT(SUCCEEDED(srv_readback->Map(0, nullptr, &srv_res)));
867 const auto* rb = static_cast<const std::uint8_t*>(srv_res);
868 std::memcpy(srv_raw_a.data(), rb + 0 * bytes, bytes);
869 std::memcpy(srv_raw_b.data(), rb + 1 * bytes, bytes);
870 std::memcpy(srv_struct_a.data(), rb + 2 * bytes, bytes);
871 std::memcpy(srv_struct_b.data(), rb + 3 * bytes, bytes);
872 std::memcpy(srv_typed.data(), rb + 4 * bytes, bytes);
873 std::memcpy(srv_null.data(), rb + 5 * bytes, bytes);
874 }
875
689 for (auto* r : {&out_a, &out_b, &out_c, &constants, &readback}) r->reset(); 876 for (auto* r : {&out_a, &out_b, &out_c, &constants, &readback}) r->reset();
690 pso67.reset(); 877 pso67.reset();
691 unknown67.reset(); 878 unknown67.reset();
@@ -735,6 +922,35 @@ int main() {
735 std::printf("CreateConstantBufferView: 64/64 dwords matched for CBV A, 32 in-bounds + 32 OOB-zero matched at " 922 std::printf("CreateConstantBufferView: 64/64 dwords matched for CBV A, 32 in-bounds + 32 OOB-zero matched at "
736 "+128, negative controls flipped %u/%u (CBV B) and %u/%u (null CBV)\n", 923 "+128, negative controls flipped %u/%u (CBV B) and %u/%u (null CBV)\n",
737 cbv_b_diff, elements, cbv_null_diff, elements); 924 cbv_b_diff, elements, cbv_null_diff, elements);
925 UINT raw_diff = 0, struct_diff = 0, null_diff = 0;
926 for (std::uint32_t i = 0; i < elements; ++i) {
927 const std::uint32_t want_raw_a = i < 32 ? (0x50000u + i) : 0u;
928 const std::uint32_t want_raw_b = i < 32 ? (0x50000u + 64u + i) : 0u;
929 const std::uint32_t want_struct_a = i < 32 ? (0x50000u + i * 4u) : 0u;
930 const std::uint32_t want_struct_b = i < 32 ? (0x50000u + (16u + i) * 4u) : 0u;
931 const std::uint32_t want_typed = i < 24 ? (0x50000u + (8u + i) * 4u) : 0u;
932 if (srv_raw_a[i] != want_raw_a && mismatches++ < 4)
933 std::fprintf(stderr, "SRV raw A[%u]: got 0x%x want 0x%x\n", i, srv_raw_a[i], want_raw_a);
934 if (srv_raw_b[i] != want_raw_b && mismatches++ < 4)
935 std::fprintf(stderr, "SRV raw B[%u]: got 0x%x want 0x%x\n", i, srv_raw_b[i], want_raw_b);
936 if (srv_struct_a[i] != want_struct_a && mismatches++ < 4)
937 std::fprintf(stderr, "SRV struct A[%u]: got 0x%x want 0x%x\n", i, srv_struct_a[i], want_struct_a);
938 if (srv_struct_b[i] != want_struct_b && mismatches++ < 4)
939 std::fprintf(stderr, "SRV struct B[%u]: got 0x%x want 0x%x\n", i, srv_struct_b[i], want_struct_b);
940 if (srv_typed[i] != want_typed && mismatches++ < 4)
941 std::fprintf(stderr, "SRV typed[%u]: got 0x%x want 0x%x\n", i, srv_typed[i], want_typed);
942 if (srv_null[i] != 0u && mismatches++ < 4)
943 std::fprintf(stderr, "SRV null[%u]: got 0x%x want 0\n", i, srv_null[i]);
944 if (srv_raw_b[i] != srv_raw_a[i]) ++raw_diff;
945 if (srv_struct_b[i] != srv_struct_a[i]) ++struct_diff;
946 if (srv_null[i] != srv_raw_a[i]) ++null_diff;
947 }
948 EXPECT(!mismatches);
949 EXPECT(raw_diff == 32 && struct_diff == 32 && null_diff == 32);
950 std::printf("CreateShaderResourceView(buffer): raw (32 in-bounds + 32 OOB-zero), structured (32 + 32 OOB-zero), "
951 "typed (24 + 40 OOB-zero) matched; negative controls flipped %u/32 (raw B), %u/32 (struct B), %u/32 "
952 "(null)\n",
953 raw_diff, struct_diff, null_diff);
738 if (d.validation_errors()) { 954 if (d.validation_errors()) {
739 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 955 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
740 return 1; 956 return 1;
diff --git a/runtime/test/d3d12_conservative_raster_test.cpp b/runtime/test/d3d12_conservative_raster_test.cpp
new file mode 100644
index 000000000..31a861af2
--- /dev/null
+++ b/runtime/test/d3d12_conservative_raster_test.cpp
@@ -0,0 +1,385 @@
1// Synthetic D3D12/Vulkan conservative coverage. Required/forbidden pixels come from geometric clipping,
2// not a driver snapshot: Tier 1 may over-cover by half a pixel, so uncertain pixels are not compared exactly.
3#include "vk_test_device.h"
4#include "d3d12_copy_compare.h"
5#include "d3d12_test_shaders.h"
6#include "host_wine.h"
7#include "../src/conservative_raster.h"
8#include "../src/shader_library.h"
9#include <d3dcompiler.h>
10#include <array>
11#include <cmath>
12#include <climits>
13
14#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return false; } } while (0)
15namespace {
16constexpr UINT width = 32, height = 32, pitch = 256;
17struct Point { double x, y; };
18using Triangle = std::array<Point, 3>;
19using Mask = std::array<bool, width * height>;
20struct Fixture {
21 copycmp::Run run;
22 copycmp::Ptr<ID3D12RootSignature> root;
23 D3D12_SHADER_BYTECODE vs{}, ps{};
24};
25
26bool setup(Fixture& f, ID3D12Device* device, bool ours, D3D12_SHADER_BYTECODE vs, D3D12_SHADER_BYTECODE ps) {
27 f.vs = vs; f.ps = ps;
28 CHECK(f.run.init(device, ours));
29 D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{};
30 desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
31 desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
32 const auto bytes = d3d12test::serialize_root_signature(desc);
33 CHECK(!bytes.empty());
34 CHECK(SUCCEEDED(device->CreateRootSignature(0, bytes.data(), bytes.size(), IID_PPV_ARGS(&f.root.p))));
35 return true;
36}
37
38D3D12_GRAPHICS_PIPELINE_STATE_DESC description(const Fixture& f, bool conservative, UINT samples, bool variant) {
39 static const D3D12_INPUT_ELEMENT_DESC element{
40 "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0};
41 D3D12_GRAPHICS_PIPELINE_STATE_DESC d{};
42 d.pRootSignature = f.root.p;
43 d.VS = f.vs; d.PS = f.ps;
44 d.InputLayout = {&element, 1};
45 d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
46 d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
47 d.RasterizerState.DepthClipEnable = TRUE;
48 d.RasterizerState.MultisampleEnable = samples > 1;
49 d.RasterizerState.ConservativeRaster = conservative ? D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON
50 : D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
51 d.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
52 d.NumRenderTargets = variant ? 2 : 1;
53 d.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
54 if (variant) d.RTVFormats[1] = DXGI_FORMAT_R8G8B8A8_UNORM;
55 d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
56 d.SampleDesc.Count = samples;
57 d.SampleMask = UINT_MAX;
58 return d;
59}
60
61// Clip the triangle to a pixel rectangle and return its intersection area.
62double area(const Triangle& triangle, double left, double top, double right, double bottom, bool* intersects = nullptr) {
63 std::vector<Point> p(triangle.begin(), triangle.end());
64 for (unsigned side = 0; side < 4 && !p.empty(); ++side) {
65 const auto distance = [&](Point v) {
66 return side == 0 ? v.x - left : side == 1 ? right - v.x : side == 2 ? v.y - top : bottom - v.y;
67 };
68 std::vector<Point> out;
69 Point a = p.back(); double da = distance(a);
70 for (const Point b : p) {
71 const double db = distance(b);
72 if ((da >= 0) != (db >= 0)) {
73 const double t = da / (da - db);
74 out.push_back({a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)});
75 }
76 if (db >= 0) out.push_back(b);
77 a = b; da = db;
78 }
79 p = std::move(out);
80 }
81 double sum = 0;
82 if (intersects) *intersects = !p.empty(); // a degenerate triangle may cover pixels despite having zero area
83 for (std::size_t i = 0; i < p.size(); ++i) {
84 const Point a = p[i], b = p[(i + 1) % p.size()];
85 sum += a.x * b.y - a.y * b.x;
86 }
87 return std::abs(sum) * 0.5;
88}
89
90bool render(Fixture& f, const Triangle& triangle, bool conservative, UINT samples, bool variant,
91 const D3D12_RECT& scissor, Mask& mask, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE) {
92 auto& r = f.run;
93 auto desc = description(f, conservative, samples, variant);
94 desc.RasterizerState.CullMode = cull;
95 copycmp::Ptr<ID3D12PipelineState> pso;
96 const auto created = r.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p));
97 if (FAILED(created)) {
98 std::fprintf(stderr, "%s CreateGraphicsPipelineState=%08x conservative=%d samples=%u variant=%d\n",
99 r.ours ? "Vulkan" : "host", unsigned(created), int(conservative), samples, int(variant));
100 return false;
101 }
102 D3D12_RESOURCE_DESC tex{};
103 tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
104 tex.Width = width; tex.Height = height;
105 tex.DepthOrArraySize = tex.MipLevels = 1;
106 tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
107 tex.SampleDesc.Count = samples;
108 tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
109 copycmp::Ptr<ID3D12Resource> target, resolved, vertices, readback;
110 CHECK(r.texture(tex, D3D12_RESOURCE_STATE_RENDER_TARGET, target));
111 if (samples > 1) {
112 tex.SampleDesc.Count = 1; tex.Flags = D3D12_RESOURCE_FLAG_NONE;
113 CHECK(r.texture(tex, D3D12_RESOURCE_STATE_RESOLVE_DEST, resolved));
114 }
115 CHECK(r.buffer(D3D12_HEAP_TYPE_UPLOAD, 24, D3D12_RESOURCE_STATE_GENERIC_READ, vertices));
116 CHECK(r.buffer(D3D12_HEAP_TYPE_READBACK, pitch * height, D3D12_RESOURCE_STATE_COPY_DEST, readback));
117 void* data = nullptr;
118 const D3D12_RANGE none{};
119 CHECK(SUCCEEDED(vertices->Map(0, &none, &data)));
120 auto* positions = static_cast<float*>(data);
121 for (unsigned i = 0; i < 3; ++i) {
122 positions[i * 2] = float(triangle[i].x * 2 / width - 1);
123 positions[i * 2 + 1] = float(1 - triangle[i].y * 2 / height);
124 }
125 vertices->Unmap(0, nullptr);
126 copycmp::Ptr<ID3D12DescriptorHeap> heap;
127 const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1};
128 CHECK(SUCCEEDED(r.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap.p))));
129 const auto handle = heap->GetCPUDescriptorHandleForHeapStart();
130 r.device->CreateRenderTargetView(target.p, nullptr, handle);
131 r.begin();
132 const float clear[4] = {};
133 r.list->ClearRenderTargetView(handle, clear, 0, nullptr);
134 r.list->OMSetRenderTargets(1, &handle, FALSE, nullptr);
135 r.list->SetGraphicsRootSignature(f.root.p);
136 r.list->SetPipelineState(pso.p);
137 const D3D12_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1};
138 r.list->RSSetViewports(1, &viewport);
139 r.list->RSSetScissorRects(1, &scissor);
140 const D3D12_VERTEX_BUFFER_VIEW vb{vertices->GetGPUVirtualAddress(), 24, 8};
141 r.list->IASetVertexBuffers(0, 1, &vb);
142 r.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
143 r.list->DrawInstanced(3, 1, 0, 0);
144 ID3D12Resource* source = target.p;
145 if (samples > 1) {
146 r.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
147 r.list->ResolveSubresource(resolved.p, 0, target.p, 0, tex.Format);
148 r.barrier(resolved.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
149 source = resolved.p;
150 } else r.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
151 D3D12_TEXTURE_COPY_LOCATION from{}, to{};
152 from.pResource = source; from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
153 to.pResource = readback.p; to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
154 to.PlacedFootprint.Footprint = {tex.Format, width, height, 1, pitch};
155 r.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
156 const auto error = r.submit();
157 if (!error.empty()) { std::fprintf(stderr, "%s\n", error.c_str()); return false; }
158 CHECK(SUCCEEDED(readback->Map(0, nullptr, &data)));
159 const auto* pixels = static_cast<const unsigned char*>(data);
160 for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) {
161 const auto* p = pixels + y * pitch + x * 4;
162 CHECK(p[1] == 0 && p[2] == 0 && p[0] == p[3]);
163 if (conservative) CHECK(p[0] == 0 || p[0] == 255); // every MSAA sample is covered
164 mask[y * width + x] = p[0] != 0;
165 }
166 readback->Unmap(0, &none);
167 return true;
168}
169
170bool coverage(const Triangle& triangle, const D3D12_RECT& scissor, const Mask& mask) {
171 constexpr double epsilon = 1.0 / 256;
172 for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) {
173 const bool in = LONG(x) >= scissor.left && LONG(x) < scissor.right && LONG(y) >= scissor.top && LONG(y) < scissor.bottom;
174 const bool required = in && area(triangle, x + epsilon, y + epsilon, x + 1 - epsilon, y + 1 - epsilon) > 1e-9;
175 bool intersects = false;
176 area(triangle, x - 0.5 - epsilon, y - 0.5 - epsilon, x + 1.5 + epsilon, y + 1.5 + epsilon, &intersects);
177 const bool allowed = in && intersects;
178 if ((required && !mask[y * width + x]) || (!allowed && mask[y * width + x])) {
179 std::fprintf(stderr, "coverage (%u,%u): required=%d allowed=%d actual=%d\n", x, y,
180 int(required), int(allowed), int(mask[y * width + x]));
181 return false;
182 }
183 }
184 return true;
185}
186
187bool rejected_states(Fixture& f, bool enabled) {
188 auto desc = description(f, true, 1, false);
189 copycmp::Ptr<ID3D12PipelineState> pso;
190 if (!enabled) {
191 CHECK(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_INVALIDARG);
192 desc.RasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
193 CHECK(SUCCEEDED(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p))));
194 return true;
195 }
196 desc.RasterizerState.FillMode = D3D12_FILL_MODE_WIREFRAME;
197 CHECK(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_INVALIDARG);
198 desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
199 desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
200 CHECK(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_INVALIDARG);
201 desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
202 desc.RasterizerState.ForcedSampleCount = 4;
203 CHECK(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_NOTIMPL);
204 desc.RasterizerState.ForcedSampleCount = 0;
205 desc.RasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE(7);
206 CHECK(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_INVALIDARG);
207 return true;
208}
209
210bool owned_device_caps() {
211 copycmp::Ptr<ID3D12Device> device;
212 CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))));
213 const auto* info = rt::d3d12::vulkan_device_info(device.p);
214 CHECK(info);
215 const auto enumerate = reinterpret_cast<PFN_vkEnumerateDeviceExtensionProperties>(
216 info->get_instance_proc(info->instance, "vkEnumerateDeviceExtensionProperties"));
217 UINT count = 0;
218 CHECK(enumerate(info->physical, nullptr, &count, nullptr) == VK_SUCCESS);
219 std::vector<VkExtensionProperties> extensions(count);
220 CHECK(enumerate(info->physical, nullptr, &count, extensions.data()) == VK_SUCCESS);
221 const bool available = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) {
222 return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0;
223 });
224 CHECK(info->conservative_rasterization == available);
225 VkPhysicalDeviceConservativeRasterizationPropertiesEXT conservative{
226 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT};
227 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
228 if (available) properties.pNext = &conservative;
229 reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(info->get_instance_proc(info->instance,
230 "vkGetPhysicalDeviceProperties2"))(info->physical, &properties);
231 const bool expected = leonida::conservative_raster::tier1(available,
232 properties.properties.limits.subPixelPrecisionBits, conservative.primitiveOverestimationSize);
233 D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
234 CHECK(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))));
235 CHECK(options.ConservativeRasterizationTier == (expected ? D3D12_CONSERVATIVE_RASTERIZATION_TIER_1
236 : D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED));
237 return true;
238}
239} // namespace
240
241int main(int argc, char** argv) {
242 const bool compare_warp_msaa4 = argc == 2 && std::strcmp(argv[1], "--warp-msaa4") == 0;
243 if (argc != 1 && !compare_warp_msaa4) return 2;
244 if (hostwine::host_is_wine()) return 77;
245 vktest::Device vk;
246 vk.request_buffer_device_address = true;
247 const auto status = vk.initialize();
248 if (status == vktest::DeviceStatus::unavailable) return 77;
249 if (status != vktest::DeviceStatus::ready) return 1;
250 VkPhysicalDeviceConservativeRasterizationPropertiesEXT conservative_properties{
251 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT};
252 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
253 if (vk.conservative_rasterization) properties.pNext = &conservative_properties;
254 reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(vk.instance_proc(vk.instance, "vkGetPhysicalDeviceProperties2"))(
255 vk.physical, &properties);
256 if (!vk.buffer_device_address || properties.properties.limits.maxPushConstantsSize < 144) {
257 std::puts("SKIP: current graphics path needs bufferDeviceAddress and 144 push-constant bytes"); return 77;
258 }
259 const auto vs_program = d3d12test::fssm_program({0x43525653, 0xbf810000});
260 const auto ps_program = d3d12test::fssm_program({0x43525053, 0xbf810000});
261 const auto vs_bytes = d3d12test::shader_container(vs_program), ps_bytes = d3d12test::shader_container(ps_program);
262 const auto directory = std::filesystem::temp_directory_path() / ("leonida_conservative_" + std::to_string(GetCurrentProcessId()));
263 std::filesystem::create_directories(directory);
264 std::filesystem::copy_file(LEONIDA_CONSERVATIVE_VS, directory / "vs.spv", std::filesystem::copy_options::overwrite_existing);
265 std::filesystem::copy_file(LEONIDA_CONSERVATIVE_PS, directory / "ps.spv", std::filesystem::copy_options::overwrite_existing);
266 {
267 std::ofstream index(directory / "index.json", std::ios::binary);
268 index << "{\"vs\":{\"stage\":\"vs\",\"fssm_sha256\":\"" << leonida::sha256_hex(vs_program)
269 << "\",\"bindings\":[],\"push_constant_bytes\":0,\"input_signature\":[{\"semantic\":\"POSITION\",\"semantic_index\":0,\"register\":0,\"mask\":3,\"rw_mask\":3,\"system_value\":0,\"component_type\":\"float\"}]},"
270 "\"ps\":{\"stage\":\"ps\",\"fssm_sha256\":\"" << leonida::sha256_hex(ps_program)
271 << "\",\"bindings\":[],\"push_constant_bytes\":0,\"outputs\":[0]}}";
272 }
273 rt::d3d12::VulkanDeviceInfo info{};
274 info.get_instance_proc = vk.instance_proc; info.instance = vk.instance; info.physical = vk.physical;
275 info.device = vk.device; info.queue = vk.queue; info.queue_family = vk.family;
276 info.buffer_device_address = vk.buffer_device_address;
277 info.conservative_rasterization = vk.conservative_rasterization;
278 info.shader_dir = directory.string();
279 copycmp::Ptr<ID3D12Device> ours, host;
280 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1;
281 D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
282 if (FAILED(ours->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))) return 1;
283 const bool expected_tier1 = leonida::conservative_raster::tier1(vk.conservative_rasterization,
284 properties.properties.limits.subPixelPrecisionBits, conservative_properties.primitiveOverestimationSize);
285 if ((options.ConservativeRasterizationTier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_1) != expected_tier1) return 1;
286 if (options.ConservativeRasterizationTier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) {
287 std::puts("SKIP: Vulkan device does not meet conservative raster Tier 1 requirements"); return 77;
288 }
289 if (options.ConservativeRasterizationTier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_1) return 1;
290 if (!owned_device_caps()) return 1;
291 std::string adapter;
292 if (!copycmp::create_host(host, adapter)) return 1;
293 copycmp::Ptr<IDXGIFactory4> factory;
294 copycmp::Ptr<IDXGIAdapter1> host_adapter;
295 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) ||
296 FAILED(factory->EnumAdapterByLuid(host->GetAdapterLuid(), IID_PPV_ARGS(&host_adapter.p)))) return 1;
297 DXGI_ADAPTER_DESC1 adapter_desc{};
298 if (FAILED(host_adapter->GetDesc1(&adapter_desc))) return 1;
299 const bool software_reference = (adapter_desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0;
300 if (FAILED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))) return 1;
301 if (options.ConservativeRasterizationTier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) return 77;
302 copycmp::Ptr<ID3DBlob> vs, ps, error;
303 const HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
304 const auto compile = compiler ? reinterpret_cast<pD3DCompile>(reinterpret_cast<void*>(
305 GetProcAddress(compiler, "D3DCompile"))) : nullptr;
306 if (!compile) { std::puts("SKIP: d3dcompiler_47 is needed for the native reference shaders"); return 77; }
307 const char* hlsl = "float4 vs(float2 p:POSITION):SV_Position{return float4(p,0.5,1);} float4 ps():SV_Target{return float4(1,0,0,1);}";
308 if (FAILED(compile(hlsl, std::strlen(hlsl), nullptr, nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs.p, &error.p)) ||
309 FAILED(compile(hlsl, std::strlen(hlsl), nullptr, nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps.p, nullptr))) return 1;
310 Fixture a, b;
311 if (!setup(a, ours.p, true, {vs_bytes.data(), vs_bytes.size()}, {ps_bytes.data(), ps_bytes.size()}) ||
312 !setup(b, host.p, false, {vs->GetBufferPointer(), vs->GetBufferSize()}, {ps->GetBufferPointer(), ps->GetBufferSize()})) return 1;
313 if (!rejected_states(a, true)) return 1;
314 {
315 info.conservative_rasterization = false;
316 copycmp::Ptr<ID3D12Device> disabled;
317 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&disabled.p)))) return 1;
318 if (FAILED(disabled->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))) ||
319 options.ConservativeRasterizationTier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) return 1;
320 Fixture f;
321 if (!setup(f, disabled.p, true, {vs_bytes.data(), vs_bytes.size()}, {ps_bytes.data(), ps_bytes.size()}) ||
322 !rejected_states(f, false)) return 1;
323 }
324 bool msaa4 = true;
325 for (auto* device : {ours.p, host.p}) {
326 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS levels{DXGI_FORMAT_R8G8B8A8_UNORM, 4};
327 if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &levels, sizeof(levels))) ||
328 !levels.NumQualityLevels) msaa4 = false;
329 }
330 const Triangle scenes[] = {
331 {{{3.0625,3.0625},{3.3125,3.0625},{3.0625,3.3125}}},
332 {{{2.125,5.125},{25.125,6.125},{2.125,5.25}}},
333 {{{4.125,4.125},{24.125,4.125},{4.125,24.125}}},
334 {{{-0.25,2.125},{5.125,2.125},{2.125,15.125}}},
335 {{{4.125,24.125},{24.125,4.125},{4.125,4.125}}},
336 {{{3.0625,3.0625},{3.3125,3.0625},{3.0625,3.0625}}}, // Tier 1 permits degenerate triangles to be culled
337 };
338 unsigned comparisons = 0, host_comparisons = 0;
339 for (const UINT samples : {1u, 4u}) {
340 if (samples == 4 && !msaa4) continue;
341 // WARP's 4x path was observed to cover outside the Tier 1 uncertainty bound for the subpixel fixture.
342 // Keep Vulkan's 4x geometric oracle strict; use 1x for the ordinary software-reference comparisons.
343 // --warp-msaa4 explicitly reproduces that reference discrepancy without weakening either oracle.
344 const bool compare_host = samples == 1 || !software_reference || compare_warp_msaa4;
345 for (const bool variant : {false, true})
346 for (const auto scissor : {D3D12_RECT{0,0,32,32}, D3D12_RECT{4,4,20,20}})
347 for (const auto& triangle : scenes) {
348 Mask normal_a{}, normal_b{}, conservative_a{}, conservative_b{};
349 if (!render(a, triangle, false, samples, variant, scissor, normal_a) ||
350 (compare_host && !render(b, triangle, false, samples, variant, scissor, normal_b)) ||
351 !render(a, triangle, true, samples, variant, scissor, conservative_a) ||
352 (compare_host && !render(b, triangle, true, samples, variant, scissor, conservative_b))) return 1;
353 const bool ours_ok = coverage(triangle, scissor, conservative_a);
354 const bool host_ok = !compare_host || coverage(triangle, scissor, conservative_b);
355 if (!ours_ok || !host_ok) {
356 std::fprintf(stderr, "scene %zu samples %u variant %d scissor-left %ld: Vulkan=%d host=%d\n",
357 std::size_t(&triangle - scenes), samples, int(variant), scissor.left, int(ours_ok), int(host_ok));
358 return 1;
359 }
360 for (unsigned i = 0; i < normal_a.size(); ++i)
361 if ((normal_a[i] && !conservative_a[i]) || (normal_b[i] && !conservative_b[i])) return 1;
362 if (&triangle == &scenes[0] && samples == 1 && scissor.left == 0) {
363 if (std::any_of(normal_a.begin(), normal_a.end(), [](bool x) { return x; }) ||
364 std::any_of(normal_b.begin(), normal_b.end(), [](bool x) { return x; }) ||
365 !std::any_of(conservative_a.begin(), conservative_a.end(), [](bool x) { return x; }) ||
366 (compare_host && !std::any_of(conservative_b.begin(), conservative_b.end(), [](bool x) { return x; }))) return 1;
367 }
368 ++comparisons;
369 if (compare_host) ++host_comparisons;
370 }
371 }
372 for (auto* f : {&a, &b}) {
373 Mask front{}, back{}, all{};
374 const D3D12_RECT full{0,0,32,32};
375 if (!render(*f, scenes[2], true, 1, false, full, all) ||
376 !render(*f, scenes[2], true, 1, false, full, front, D3D12_CULL_MODE_FRONT) ||
377 !render(*f, scenes[2], true, 1, false, full, back, D3D12_CULL_MODE_BACK)) return 1;
378 for (unsigned i = 0; i < all.size(); ++i) if ((front[i] && back[i]) || ((front[i] || back[i]) != all[i])) return 1;
379 }
380 std::printf("conservative raster: %u Vulkan and %u %s scenario pairs; geometric bounds, culling, scissor, variants, rejections; Vulkan 4x MSAA %s\n",
381 comparisons, host_comparisons, adapter.c_str(), msaa4 ? "checked" : "unavailable");
382 if (software_reference && !compare_warp_msaa4)
383 std::puts("WARP comparison is 1x; --warp-msaa4 separately checks its observed 4x coverage discrepancy");
384 return vk.validation_errors() ? 1 : 0;
385}
diff --git a/runtime/test/d3d12_copy_compare.h b/runtime/test/d3d12_copy_compare.h
index 49583f1b5..da5c631fe 100644
--- a/runtime/test/d3d12_copy_compare.h
+++ b/runtime/test/d3d12_copy_compare.h
@@ -24,6 +24,7 @@
24#include <vector> 24#include <vector>
25 25
26#include "../shims/d3d12_com.h" 26#include "../shims/d3d12_com.h"
27#include "host_adapter.h"
27 28
28namespace copycmp { 29namespace copycmp {
29 30
@@ -66,31 +67,17 @@ inline bool try_create_host(Ptr<ID3D12Device>& host, std::string& name, const LU
66 if (!create || !create_factory) return false; 67 if (!create || !create_factory) return false;
67 Ptr<IDXGIFactory4> factory; 68 Ptr<IDXGIFactory4> factory;
68 if (FAILED(create_factory(IID_PPV_ARGS(&factory.p)))) return false; 69 if (FAILED(create_factory(IID_PPV_ARGS(&factory.p)))) return false;
69 char want[128] = {}; 70 // The variable and the name match are host_adapter.h's, shared with the tests that create their host devices
70 GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)); 71 // themselves.
72 const std::string needle = hostadapter::wanted();
71 Ptr<IDXGIAdapter1> adapter; 73 Ptr<IDXGIAdapter1> adapter;
72 if (luid) { 74 if (luid) {
73 if (FAILED(factory->EnumAdapterByLuid(*luid, IID_PPV_ARGS(&adapter.p)))) return false; 75 if (FAILED(factory->EnumAdapterByLuid(*luid, IID_PPV_ARGS(&adapter.p)))) return false;
74 } else if (want[0]) { 76 } else if (needle == "warp") {
75 std::string needle(want); 77 if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) return false;
76 std::transform(needle.begin(), needle.end(), needle.begin(), [](unsigned char c) { return char(std::tolower(c)); }); 78 } else if (!needle.empty()) {
77 if (needle == "warp") { 79 adapter.p = hostadapter::named(factory.p, needle);
78 if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) return false; 80 if (!adapter.p) return false;
79 } else {
80 for (UINT i = 0;; ++i) {
81 Ptr<IDXGIAdapter1> candidate;
82 if (FAILED(factory->EnumAdapters1(i, &candidate.p))) return false;
83 DXGI_ADAPTER_DESC1 desc{};
84 candidate->GetDesc1(&desc);
85 std::string text;
86 for (const wchar_t* c = desc.Description; *c; ++c) text += char(std::tolower(*c < 128 ? *c : '?'));
87 if (text.find(needle) != std::string::npos) {
88 adapter.p = candidate.p;
89 candidate.p = nullptr;
90 break;
91 }
92 }
93 }
94 } 81 }
95 if (FAILED(create(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) return false; 82 if (FAILED(create(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) return false;
96 Ptr<IDXGIAdapter1> used; 83 Ptr<IDXGIAdapter1> used;
diff --git a/runtime/test/d3d12_copy_xfmt_test.cpp b/runtime/test/d3d12_copy_xfmt_test.cpp
index 40e60b40b..0a504b266 100644
--- a/runtime/test/d3d12_copy_xfmt_test.cpp
+++ b/runtime/test/d3d12_copy_xfmt_test.cpp
@@ -1,6 +1,8 @@
1// Copies between two formats of one D3D12 copy family (depth <-> colour of the same size, BC <-> its uncompressed 1// Copies between two formats of one D3D12 copy family (depth <-> colour of the same size, BC <-> its uncompressed
2// equivalent), on the Vulkan-backed device and on host D3D12 (default adapter and WARP). Bytes read back compared. 2// equivalent), on the Vulkan-backed device and on host D3D12 (the layer's own adapter and WARP). Bytes read back
3// compared.
3#include "vk_test_device.h" 4#include "vk_test_device.h"
5#include "host_adapter.h"
4#include "host_wine.h" 6#include "host_wine.h"
5#include "../shims/d3d12_com.h" 7#include "../shims/d3d12_com.h"
6#include <d3d12sdklayers.h> 8#include <d3d12sdklayers.h>
@@ -222,12 +224,13 @@ int main() {
222 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) return 1; 224 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) return 1;
223 unsigned differ = 0, differ_depth = 0, compared = 0; 225 unsigned differ = 0, differ_depth = 0, compared = 0;
224 for (const bool warp : {false, true}) { 226 for (const bool warp : {false, true}) {
225 const char* hn = warp ? "WARP" : "default adapter";
226 for (const Case& c : cases) { 227 for (const Case& c : cases) {
227 // A fresh device per case: an invalid copy removes the host device. 228 // A fresh device per case: an invalid copy removes the host device.
228 Ref<IDXGIAdapter> adapter; 229 Ref<IDXGIAdapter> adapter;
229 Ref<ID3D12Device> host; 230 Ref<ID3D12Device> host;
230 if (warp && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue; 231 std::string adapter_name;
232 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue;
233 const char* hn = adapter_name.c_str();
231 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; 234 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
232 // Only WARP validates; a hardware driver may run an invalid copy. 235 // Only WARP validates; a hardware driver may run an invalid copy.
233 if (!warp && std::strncmp(c.name, "negative", 8) == 0) continue; 236 if (!warp && std::strncmp(c.name, "negative", 8) == 0) continue;
diff --git a/runtime/test/d3d12_debug_markers_test.cpp b/runtime/test/d3d12_debug_markers_test.cpp
index 1be8fffed..a87fd030f 100644
--- a/runtime/test/d3d12_debug_markers_test.cpp
+++ b/runtime/test/d3d12_debug_markers_test.cpp
@@ -186,7 +186,7 @@ struct Counted final : IUnknown {
186constexpr GUID kKey{0xd3d24a01, 0x0000, 0x4000, {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}; 186constexpr GUID kKey{0xd3d24a01, 0x0000, 0x4000, {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}};
187constexpr GUID kOtherKey{0xd3d24a01, 0x0000, 0x4000, {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}}; 187constexpr GUID kOtherKey{0xd3d24a01, 0x0000, 0x4000, {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}};
188// WKPDID_D3DDebugObjectNameW (d3dcommon.h). 188// WKPDID_D3DDebugObjectNameW (d3dcommon.h).
189constexpr GUID kDebugObjectNameW{0x4cca5fd8, 0x921f, 0x42c8, {0x85, 0x99, 0xd2, 0x86, 0x6a, 0x3e, 0x5f, 0x7e}}; 189constexpr GUID kDebugObjectNameW{0x4cca5fd8, 0x921f, 0x42c8, {0x85, 0x66, 0x70, 0xca, 0xf2, 0xa9, 0xb7, 0x41}};
190 190
191int check_private_data(ID3D12Object* object, const char* what) { 191int check_private_data(ID3D12Object* object, const char* what) {
192 std::printf("private data: %s\n", what); 192 std::printf("private data: %s\n", what);
@@ -230,13 +230,17 @@ int check_private_data(ID3D12Object* object, const char* what) {
230 EXPECT(object->SetPrivateData(kKey, 0, nullptr) == S_OK); 230 EXPECT(object->SetPrivateData(kKey, 0, nullptr) == S_OK);
231 EXPECT(object->GetPrivateData(kKey, &size, nullptr) == DXGI_ERROR_NOT_FOUND && size == 0); 231 EXPECT(object->GetPrivateData(kKey, &size, nullptr) == DXGI_ERROR_NOT_FOUND && size == 0);
232 232
233 // SetName is not readable through GetPrivateData, as on the host runtime: WKPDID_D3DDebugObjectNameW stays 233 // SetName is readable as WKPDID_D3DDebugObjectNameW, terminator included, as on the host runtime. A null name
234 // missing. A null name (which the host faults on) clears it. 234 // (which the host faults on) changes nothing.
235 const wchar_t name[] = L"leonida object"; 235 const wchar_t name[] = L"leonida object";
236 EXPECT(object->SetName(name) == S_OK); 236 EXPECT(object->SetName(name) == S_OK);
237 size = 0; 237 wchar_t stored[32] = {};
238 EXPECT(object->GetPrivateData(kDebugObjectNameW, &size, nullptr) == DXGI_ERROR_NOT_FOUND && size == 0); 238 size = sizeof(stored);
239 EXPECT(object->SetName(nullptr) == S_OK); 239 EXPECT(object->GetPrivateData(kDebugObjectNameW, &size, stored) == S_OK);
240 EXPECT(size == sizeof(name) && std::wcscmp(stored, name) == 0);
241 EXPECT(object->SetName(nullptr) == E_INVALIDARG);
242 size = sizeof(stored);
243 EXPECT(object->GetPrivateData(kDebugObjectNameW, &size, stored) == S_OK && size == sizeof(name));
240 244
241 // Left set: released when the object dies (checked for a fence below). 245 // Left set: released when the object dies (checked for a fence below).
242 EXPECT(object->SetPrivateDataInterface(kOtherKey, nullptr) == S_OK); 246 EXPECT(object->SetPrivateDataInterface(kOtherKey, nullptr) == S_OK);
diff --git a/runtime/test/d3d12_depth_resolve_test.cpp b/runtime/test/d3d12_depth_resolve_test.cpp
index 9d5d1321e..883a90745 100644
--- a/runtime/test/d3d12_depth_resolve_test.cpp
+++ b/runtime/test/d3d12_depth_resolve_test.cpp
@@ -1,4 +1,4 @@
1// Compare depth/stencil ResolveSubresourceRegion with Windows D3D12 on the default adapter and on WARP, through 1// Compare depth/stencil ResolveSubresourceRegion with Windows D3D12 on the layer's own adapter and on WARP, through
2// clears, resolves, copies and Map on both sides: MIN and MAX of either plane, named by the depth format or the 2// clears, resolves, copies and Map on both sides: MIN and MAX of either plane, named by the depth format or the
3// plane's own format, and AVERAGE of the depth plane by its own format (R32_FLOAT, R24_UNORM_X8_TYPELESS). 3// plane's own format, and AVERAGE of the depth plane by its own format (R32_FLOAT, R24_UNORM_X8_TYPELESS).
4// Clears write whole pixels, so all samples of a pixel are equal and every mode returns that value: these cases 4// Clears write whole pixels, so all samples of a pixel are equal and every mode returns that value: these cases
@@ -9,6 +9,7 @@
9// WARP, measured: a resolve with Format D32_FLOAT removes the device (DXGI_ERROR_DRIVER_INTERNAL_ERROR), and a 9// WARP, measured: a resolve with Format D32_FLOAT removes the device (DXGI_ERROR_DRIVER_INTERNAL_ERROR), and a
10// D24S8 resolve of one plane writes both. So WARP skips those and is compared on the plane resolved. 10// D24S8 resolve of one plane writes both. So WARP skips those and is compared on the plane resolved.
11#include "vk_test_device.h" 11#include "vk_test_device.h"
12#include "host_adapter.h"
12#include "host_wine.h" 13#include "host_wine.h"
13#include "../shims/d3d12_com.h" 14#include "../shims/d3d12_com.h"
14#include <dxgi1_4.h> 15#include <dxgi1_4.h>
@@ -152,7 +153,9 @@ bool resolve_and_read(ID3D12Device* device, const Case& c, Planes& out, bool run
152 Event event; 153 Event event;
153 CHECK(event.handle); 154 CHECK(event.handle);
154 CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, event.handle))); 155 CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, event.handle)));
155 CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0); 156 // 30 s, not 5 s: under `ctest -j 6` other GPU tests share the device, and a fence can take longer
157 // than this test's idle runtime to signal (TEST-514 flake). Sibling tests already wait 15-60 s.
158 CHECK(WaitForSingleObject(event.handle, 30000) == WAIT_OBJECT_0);
156 void* mapped = nullptr; 159 void* mapped = nullptr;
157 const D3D12_RANGE range{0, SIZE_T(total)}; 160 const D3D12_RANGE range{0, SIZE_T(total)};
158 CHECK(SUCCEEDED(readback->Map(0, &range, &mapped)) && mapped); 161 CHECK(SUCCEEDED(readback->Map(0, &range, &mapped)) && mapped);
@@ -320,9 +323,10 @@ int main() {
320 if (hostwine::host_is_wine()) break; // checked against the clears above 323 if (hostwine::host_is_wine()) break; // checked against the clears above
321 Ref<IDXGIAdapter> adapter; 324 Ref<IDXGIAdapter> adapter;
322 Ref<ID3D12Device> host; 325 Ref<ID3D12Device> host;
323 if (warp && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue; 326 std::string adapter_name;
327 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue;
324 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; 328 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
325 const char* name = warp ? "WARP" : "the default adapter"; 329 const char* name = adapter_name.c_str();
326 unsigned same = 0, compared = 0, refused_alike = 0, quirks = 0; 330 unsigned same = 0, compared = 0, refused_alike = 0, quirks = 0;
327 for (std::size_t i = 0; i < cases.size(); ++i) { 331 for (std::size_t i = 0; i < cases.size(); ++i) {
328 const Case& c = cases[i]; 332 const Case& c = cases[i];
@@ -331,7 +335,9 @@ int main() {
331 if (!resolve_and_read(host.p, c, expected, false)) return 1; 335 if (!resolve_and_read(host.p, c, expected, false)) return 1;
332 ++compared; 336 ++compared;
333 // The layer's result was checked against the clears above. A host that differs from the clears is a 337 // The layer's result was checked against the clears above. A host that differs from the clears is a
334 // host quirk (NVIDIA's D3D12 driver on D24S8 rectangle resolves), not a layer bug: report, don't fail. 338 // host quirk, not a layer bug: report, don't fail. Which D24S8 resolves is the driver's: with stencil
339 // MIN/MAX on both, an RTX 3070 (NVIDIA 610.74) adds "stencil as X24_G8" and "depth as R24_X8" AVERAGE,
340 // a Ryzen 7 9700X iGPU (AMD 32.0.21042.62) depth MIN/MAX; whole subresources and rectangles alike.
335 if (SUCCEEDED(expected.close) && !same_planes(expected, expected_planes(c), warp, c.plane)) { 341 if (SUCCEEDED(expected.close) && !same_planes(expected, expected_planes(c), warp, c.plane)) {
336 std::printf("%s %s rect %d against %s: host quirk: the host differs from the clears; the layer " 342 std::printf("%s %s rect %d against %s: host quirk: the host differs from the clears; the layer "
337 "matches them\n", c.name, mode_name(c.mode), int(c.rect), name); 343 "matches them\n", c.name, mode_name(c.mode), int(c.rect), name);
@@ -372,7 +378,7 @@ int main() {
372 if (validation_errors) 378 if (validation_errors)
373 std::fprintf(stderr, "d3d12_depth_resolve_test: %u new Vulkan validation error(s)\n", validation_errors); 379 std::fprintf(stderr, "d3d12_depth_resolve_test: %u new Vulkan validation error(s)\n", validation_errors);
374 const bool need_host = !hostwine::host_is_wine(); 380 const bool need_host = !hostwine::host_is_wine();
375 if (need_host && !references) std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n"); 381 if (need_host && !references) std::fprintf(stderr, "no D3D12 reference device (hardware adapter or WARP)\n");
376 if (run_failed || failures || validation_errors || (need_host && (!references || !matched))) return 1; 382 if (run_failed || failures || validation_errors || (need_host && (!references || !matched))) return 1;
377 std::printf("depth/stencil resolves: %u host comparisons matched, %u refusals kept the destination, %u modes the " 383 std::printf("depth/stencil resolves: %u host comparisons matched, %u refusals kept the destination, %u modes the "
378 "device lacks were refused\n", matched, refusals, lacking); 384 "device lacks were refused\n", matched, refusals, lacking);
diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp
index 9db94da9a..8859cd67c 100644
--- a/runtime/test/d3d12_descriptor_test.cpp
+++ b/runtime/test/d3d12_descriptor_test.cpp
@@ -15,7 +15,9 @@
15// at the same S# type, so this also checks that they are two samplers, not one. 15// at the same S# type, so this also checks that they are two samplers, not one.
16// - B8G8R8X8 (D3D-87): a B8G8R8X8_UNORM and a B8G8R8A8_UNORM texture uploaded with the same bytes, the fourth 16// - B8G8R8X8 (D3D-87): a B8G8R8X8_UNORM and a B8G8R8A8_UNORM texture uploaded with the same bytes, the fourth
17// never 255. Their default views read the same red, green and blue; B8G8R8X8 reads alpha 1, B8G8R8A8 the 17// never 255. Their default views read the same red, green and blue; B8G8R8X8 reads alpha 1, B8G8R8A8 the
18// stored byte. Views between the two typeless families give a null descriptor. 18// stored byte. Views between the two typeless families give a null descriptor, unless a castable-format list
19// names the view's format: then a B8G8R8X8 view of a B8G8R8A8 texture reads alpha 1, and a B8G8R8A8 view of a
20// B8G8R8X8 one the stored byte, as on WARP and AMD's D3D12 driver.
19// Multisample SRVs: four masked triangles seed different values per sample and array layer. A compute shader reads 21// Multisample SRVs: four masked triangles seed different values per sample and array layer. A compute shader reads
20// them back using the T#s for the 2D, full-array and sliced-array views. The test builds its pipelines in Vulkan 22// them back using the T#s for the 2D, full-array and sliced-array views. The test builds its pipelines in Vulkan
21// and binds the device's set (rt::d3d12::bindless_set). Without glslangValidator the GPU readbacks are skipped. 23// and binds the device's set (rt::d3d12::bindless_set). Without glslangValidator the GPU readbacks are skipped.
@@ -303,7 +305,7 @@ int main() {
303 if (device_status != vktest::DeviceStatus::ready) return 1; 305 if (device_status != vktest::DeviceStatus::ready) return 1;
304 306
305 constexpr UINT size = 8, texels = size * size, bytes = texels * 4; 307 constexpr UINT size = 8, texels = size * size, bytes = texels * 4;
306 std::vector<std::uint8_t> results(4 * bytes), after_destruction(bytes), borders(3 * bytes), bgr_results(2 * bytes); 308 std::vector<std::uint8_t> results(4 * bytes), after_destruction(bytes), borders(3 * bytes), bgr_results(6 * bytes);
307 bool sampled_through_set = false; 309 bool sampled_through_set = false;
308 UINT lod_mismatches = 0; 310 UINT lod_mismatches = 0;
309 { 311 {
@@ -545,22 +547,49 @@ int main() {
545 for (UINT x = 0; x < fp.Width; ++x) std::memcpy(row + 4 * x, color.data(), 4); 547 for (UINT x = 0; x < fp.Width; ++x) std::memcpy(row + 4 * x, color.data(), 4);
546 } 548 }
547 } 549 }
548 // A B8G8R8X8_UNORM texture and a B8G8R8A8_UNORM one, uploaded with the same bgrx_texel bytes past the cube 550 // Five textures uploaded with the same bgrx_texel bytes past the cube array's footprints: a B8G8R8X8_UNORM and
549 // array's footprints. 551 // a B8G8R8A8_UNORM one for their default views, then a B8G8R8A8_UNORM texture whose castable-format list names
550 constexpr DXGI_FORMAT bgr_formats[2] = {DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM}; 552 // B8G8R8X8_UNORM and a B8G8R8X8_UNORM one whose list names B8G8R8A8_UNORM, each viewed in the other family,
551 Ref<ID3D12Resource> bgr_textures[2]; 553 // and two R8G8B8A8_UNORM ones whose lists name B8G8R8X8_UNORM and B8G8R8A8_UNORM, viewed through them (red
552 D3D12_PLACED_SUBRESOURCE_FOOTPRINT bgr_placed[2]{}; 554 // and blue swap places).
555 constexpr UINT bgr_count = 6;
556 constexpr DXGI_FORMAT bgr_formats[bgr_count] = {DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM,
557 DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM,
558 DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM};
559 constexpr DXGI_FORMAT bgr_casts[bgr_count] = {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN,
560 DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM,
561 DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM};
562 Ref<ID3D12Resource> bgr_textures[bgr_count];
563 D3D12_PLACED_SUBRESOURCE_FOOTPRINT bgr_placed[bgr_count]{};
564 Ref<ID3D12Device10> bgr_device10;
565 EXPECT(SUCCEEDED(inner->QueryInterface(IID_PPV_ARGS(&bgr_device10.p))));
553 const auto& last_array = array_levels[std::size(array_levels) - 1]; 566 const auto& last_array = array_levels[std::size(array_levels) - 1];
554 constexpr UINT64 placement = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT; 567 constexpr UINT64 placement = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT;
555 const UINT64 bgr_start = 568 const UINT64 bgr_start =
556 (last_array.Offset + UINT64(last_array.Footprint.RowPitch) * last_array.Footprint.Height + placement - 1) & 569 (last_array.Offset + UINT64(last_array.Footprint.RowPitch) * last_array.Footprint.Height + placement - 1) &
557 ~(placement - 1); 570 ~(placement - 1);
558 for (UINT f = 0; f < 2; ++f) { 571 for (UINT f = 0; f < bgr_count; ++f) {
559 D3D12_RESOURCE_DESC desc = texture_desc; 572 D3D12_RESOURCE_DESC desc = texture_desc;
560 desc.Format = bgr_formats[f]; 573 desc.Format = bgr_formats[f];
561 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, 574 if (bgr_casts[f] == DXGI_FORMAT_UNKNOWN) {
562 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, 575 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc,
563 IID_PPV_ARGS(&bgr_textures[f].p)))); 576 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
577 IID_PPV_ARGS(&bgr_textures[f].p))));
578 } else {
579 D3D12_RESOURCE_DESC1 desc1{};
580 desc1.Dimension = desc.Dimension;
581 desc1.Width = desc.Width;
582 desc1.Height = desc.Height;
583 desc1.DepthOrArraySize = desc.DepthOrArraySize;
584 desc1.MipLevels = desc.MipLevels;
585 desc1.Format = desc.Format;
586 desc1.SampleDesc = desc.SampleDesc;
587 desc1.Layout = desc.Layout;
588 desc1.Flags = desc.Flags;
589 EXPECT(SUCCEEDED(bgr_device10->CreateCommittedResource3(
590 &default_heap, D3D12_HEAP_FLAG_NONE, &desc1, D3D12_BARRIER_LAYOUT_COPY_DEST, nullptr, nullptr, 1,
591 &bgr_casts[f], IID_PPV_ARGS(&bgr_textures[f].p))));
592 }
564 device->GetCopyableFootprints(&desc, 0, 1, bgr_start + 8192 * f, &bgr_placed[f], nullptr, nullptr, nullptr); 593 device->GetCopyableFootprints(&desc, 0, 1, bgr_start + 8192 * f, &bgr_placed[f], nullptr, nullptr, nullptr);
565 EXPECT(bgr_placed[f].Footprint.Format == bgr_formats[f]); 594 EXPECT(bgr_placed[f].Footprint.Format == bgr_formats[f]);
566 EXPECT(bgr_placed[f].Offset + UINT64(bgr_placed[f].Footprint.RowPitch) * size <= upload_desc.Width); 595 EXPECT(bgr_placed[f].Offset + UINT64(bgr_placed[f].Footprint.RowPitch) * size <= upload_desc.Width);
@@ -601,7 +630,8 @@ int main() {
601 volume_lod_slot = cube_lod_slot + cube_lod_count, 630 volume_lod_slot = cube_lod_slot + cube_lod_count,
602 ms_slot = volume_lod_slot + volume_lod_count, ms_array_slot, ms_slice_slot, ms_first_layer_slot, 631 ms_slot = volume_lod_slot + volume_lod_count, ms_array_slot, ms_slice_slot, ms_first_layer_slot,
603 ms_uint_slot, ms_uint_array_slot, ms_sint_slot, ms_sint_array_slot, 632 ms_uint_slot, ms_uint_array_slot, ms_sint_slot, ms_sint_array_slot,
604 line_default, line_mip, line_clamped, bgrx_slot, bgra_slot, typed_bgrx_slot, view_slot_count 633 line_default, line_mip, line_clamped, bgrx_slot, bgra_slot, typed_bgrx_slot, cast_bgrx_slot,
634 cast_bgra_slot, cast_rgbx_slot, cast_rgba_slot, view_slot_count
605 }; 635 };
606 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, view_slot_count, 636 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, view_slot_count,
607 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; 637 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
@@ -1185,6 +1215,35 @@ int main() {
1185 bgra_image.format == bgrx_image.format); 1215 bgra_image.format == bgrx_image.format);
1186 EXPECT((bgrx_image.swizzle == g::Swizzle{g::select_z, g::select_y, g::select_x, g::select_one})); 1216 EXPECT((bgrx_image.swizzle == g::Swizzle{g::select_z, g::select_y, g::select_x, g::select_one}));
1187 EXPECT((bgra_image.swizzle == g::Swizzle{g::select_z, g::select_y, g::select_x, g::select_w})); 1217 EXPECT((bgra_image.swizzle == g::Swizzle{g::select_z, g::select_y, g::select_x, g::select_w}));
1218 // A castable-format list lets a view cross the two families, and the view's own format decides the alpha:
1219 // WARP and AMD's D3D12 driver read 1 through a B8G8R8X8 view of a B8G8R8A8 texture, and the stored byte
1220 // through a B8G8R8A8 view of a B8G8R8X8 one. A format the list doesn't name stays refused.
1221 {
1222 D3D12_SHADER_RESOURCE_VIEW_DESC cast_view = flat_view;
1223 cast_view.Format = DXGI_FORMAT_B8G8R8X8_UNORM;
1224 device->CreateShaderResourceView(bgr_textures[2].p, &cast_view, view_slot(cast_bgrx_slot));
1225 cast_view.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
1226 device->CreateShaderResourceView(bgr_textures[3].p, &cast_view, view_slot(cast_bgra_slot));
1227 cast_view.Format = DXGI_FORMAT_B8G8R8X8_UNORM;
1228 device->CreateShaderResourceView(bgr_textures[4].p, &cast_view, view_slot(cast_rgbx_slot));
1229 cast_view.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
1230 device->CreateShaderResourceView(bgr_textures[5].p, &cast_view, view_slot(cast_rgba_slot));
1231 g::Image cast_bgrx_image{}, cast_bgra_image{}, cast_rgbx_image{}, cast_rgba_image{};
1232 EXPECT(image_at(cast_bgrx_slot, cast_bgrx_image) && image_at(cast_bgra_slot, cast_bgra_image) &&
1233 image_at(cast_rgbx_slot, cast_rgbx_image) && image_at(cast_rgba_slot, cast_rgba_image));
1234 EXPECT(cast_bgrx_image.format == bgrx_image.format && cast_bgra_image.format == bgrx_image.format &&
1235 cast_rgbx_image.format == bgrx_image.format && cast_rgba_image.format == bgrx_image.format);
1236 // The T#'s format code is the same for both channel orders, so the swizzle carries the view's order.
1237 EXPECT(cast_bgrx_image.swizzle == bgrx_image.swizzle && cast_bgra_image.swizzle == bgra_image.swizzle);
1238 EXPECT(cast_rgba_image.swizzle == bgra_image.swizzle); // B8G8R8A8 view of R8G8B8A8, no B8G8R8X8 involved
1239 EXPECT(cast_rgbx_image.swizzle == bgrx_image.swizzle);
1240 cast_view.Format = DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
1241 for (ID3D12Resource* listed : {bgr_textures[2].p, bgr_textures[3].p, bgr_textures[4].p, bgr_textures[5].p}) {
1242 std::memset(view_bytes(null_slot), 0x77, step);
1243 device->CreateShaderResourceView(listed, &cast_view, view_slot(null_slot));
1244 EXPECT(null_at(null_slot));
1245 }
1246 }
1188 Ref<ID3D12Resource> bgrx_typeless; 1247 Ref<ID3D12Resource> bgrx_typeless;
1189 D3D12_RESOURCE_DESC bgrx_typeless_desc = texture_desc; 1248 D3D12_RESOURCE_DESC bgrx_typeless_desc = texture_desc;
1190 bgrx_typeless_desc.Format = DXGI_FORMAT_B8G8R8X8_TYPELESS; 1249 bgrx_typeless_desc.Format = DXGI_FORMAT_B8G8R8X8_TYPELESS;
@@ -1325,7 +1384,7 @@ int main() {
1325 transition(bc.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); 1384 transition(bc.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
1326 list->ResourceBarrier(1, &barrier); 1385 list->ResourceBarrier(1, &barrier);
1327 } 1386 }
1328 for (UINT f = 0; f < 2; ++f) { 1387 for (UINT f = 0; f < bgr_count; ++f) {
1329 to_texture.pResource = bgr_textures[f].p; 1388 to_texture.pResource = bgr_textures[f].p;
1330 from_upload.PlacedFootprint = bgr_placed[f]; 1389 from_upload.PlacedFootprint = bgr_placed[f];
1331 list->CopyTextureRegion(&to_texture, 0, 0, 0, &from_upload, nullptr); 1390 list->CopyTextureRegion(&to_texture, 0, 0, 0, &from_upload, nullptr);
@@ -1350,6 +1409,14 @@ int main() {
1350 transition(bgr_textures[0].p, D3D12_RESOURCE_STATE_COPY_DEST, 1409 transition(bgr_textures[0].p, D3D12_RESOURCE_STATE_COPY_DEST,
1351 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), 1410 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1352 transition(bgr_textures[1].p, D3D12_RESOURCE_STATE_COPY_DEST, 1411 transition(bgr_textures[1].p, D3D12_RESOURCE_STATE_COPY_DEST,
1412 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1413 transition(bgr_textures[2].p, D3D12_RESOURCE_STATE_COPY_DEST,
1414 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1415 transition(bgr_textures[3].p, D3D12_RESOURCE_STATE_COPY_DEST,
1416 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1417 transition(bgr_textures[4].p, D3D12_RESOURCE_STATE_COPY_DEST,
1418 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE),
1419 transition(bgr_textures[5].p, D3D12_RESOURCE_STATE_COPY_DEST,
1353 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)}; 1420 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)};
1354 list->ResourceBarrier(UINT(std::size(sampled)), sampled); 1421 list->ResourceBarrier(UINT(std::size(sampled)), sampled);
1355 to_texture.pResource = array_texture.p; 1422 to_texture.pResource = array_texture.p;
@@ -1527,7 +1594,14 @@ int main() {
1527 lod_keys[i].first = i * texels; 1594 lod_keys[i].first = i * texels;
1528 } 1595 }
1529 EXPECT(sample_through_set(d, set0, set0_layout, lod_keys, lod_pixels.data())); 1596 EXPECT(sample_through_set(d, set0, set0_layout, lod_keys, lod_pixels.data()));
1530 std::array<UINT, std::size(lod_views)> lod_errors{}; 1597 // A fractional image-view minimum LOD is not exact on every driver: Vulkan defines the view's minimum as
1598 // minLodFloat (preferred) or minLodInteger = floor(minLodFloat) (alternative), and an implementation may use
1599 // either (Vulkan spec, "Image Level(s) Selection" and VkImageViewMinLodCreateInfoEXT). The UHD 770 floors it.
1600 // So a view with a fractional clamp inside its mip range passes if all of its texels follow one of the two
1601 // rules; the rest of the views have one answer either way.
1602 std::array<UINT, std::size(lod_views)> lod_errors{}, lod_errors_floored{};
1603 std::array<bool, std::size(lod_views)> lod_fractional{};
1604 char lod_first[std::size(lod_views)][160]{};
1531 for (UINT i = 0; i < texels; ++i) { 1605 for (UINT i = 0; i < texels; ++i) {
1532 using Pixel = std::array<std::uint8_t, 4>; 1606 using Pixel = std::array<std::uint8_t, 4>;
1533 const Pixel expected[] = { 1607 const Pixel expected[] = {
@@ -1536,18 +1610,34 @@ int main() {
1536 d.image_view_min_lod ? mip_colors[1] : Pixel{}, 1610 d.image_view_min_lod ? mip_colors[1] : Pixel{},
1537 {}, mip_colors[0], {0, 0, 0, 255} 1611 {}, mip_colors[0], {0, 0, 0, 255}
1538 }; 1612 };
1613 // The same views with the minimum floored where the extension is used (views 1 and 2: 0.75 -> 0, 1.75 -> 1).
1614 const Pixel floored[] = {
1615 expected[0], d.image_view_min_lod ? texel(i % size, i / size) : Pixel{},
1616 d.image_view_min_lod ? mip_colors[0] : Pixel{}, expected[3], expected[4], expected[5]
1617 };
1539 static_assert(std::size(expected) == std::size(lod_views)); 1618 static_assert(std::size(expected) == std::size(lod_views));
1619 lod_fractional[1] = lod_fractional[2] = d.image_view_min_lod;
1540 for (UINT view = 0; view < std::size(lod_views); ++view) { 1620 for (UINT view = 0; view < std::size(lod_views); ++view) {
1541 const auto* sample = &lod_pixels[view * bytes + 4 * i]; 1621 const auto* sample = &lod_pixels[view * bytes + 4 * i];
1622 if (std::memcmp(sample, floored[view].data(), 4)) ++lod_errors_floored[view];
1542 if (std::memcmp(sample, expected[view].data(), 4) && lod_errors[view]++ == 0) { 1623 if (std::memcmp(sample, expected[view].data(), 4) && lod_errors[view]++ == 0) {
1543 std::fprintf(stderr, "minimum LOD view %u texel %u: got %u %u %u %u, expected %u %u %u %u\n", 1624 std::snprintf(lod_first[view], sizeof(lod_first[view]),
1544 view, i, sample[0], sample[1], sample[2], sample[3], 1625 "minimum LOD view %u texel %u: got %u %u %u %u, expected %u %u %u %u\n", view, i,
1545 expected[view][0], expected[view][1], expected[view][2], expected[view][3]); 1626 sample[0], sample[1], sample[2], sample[3], expected[view][0], expected[view][1],
1627 expected[view][2], expected[view][3]);
1546 } 1628 }
1547 } 1629 }
1548 } 1630 }
1549 for (UINT view = 0; view < lod_errors.size(); ++view) { 1631 for (UINT view = 0; view < lod_errors.size(); ++view) {
1550 if (lod_errors[view]) std::fprintf(stderr, "2D LOD view %u: %u/%u mismatched\n", view, lod_errors[view], texels); 1632 if (lod_fractional[view] && lod_errors[view] && !lod_errors_floored[view]) {
1633 std::printf("2D LOD view %u: the driver floors the fractional minimum LOD (%.2f), as Vulkan allows\n",
1634 view, lod_views[view].clamp);
1635 lod_errors[view] = 0;
1636 }
1637 if (lod_errors[view]) {
1638 std::fputs(lod_first[view], stderr);
1639 std::fprintf(stderr, "2D LOD view %u: %u/%u mismatched\n", view, lod_errors[view], texels);
1640 }
1551 lod_mismatches += lod_errors[view]; 1641 lod_mismatches += lod_errors[view];
1552 } 1642 }
1553 1643
@@ -1559,26 +1649,37 @@ int main() {
1559 } 1649 }
1560 std::array<std::uint8_t, std::size(array_keys) * bytes> array_pixels{}; 1650 std::array<std::uint8_t, std::size(array_keys) * bytes> array_pixels{};
1561 EXPECT(sample_through_set(d, set0, set0_layout, array_keys, array_pixels.data())); 1651 EXPECT(sample_through_set(d, set0, set0_layout, array_keys, array_pixels.data()));
1562 std::array<UINT, std::size(array_clamps)> array_errors{}; 1652 std::array<UINT, std::size(array_clamps)> array_errors{}, array_errors_floored{};
1653 char array_first[std::size(array_clamps)][160]{};
1563 for (UINT i = 0; i < texels; ++i) { 1654 for (UINT i = 0; i < texels; ++i) {
1564 const UINT layer = 1 + i / 32; 1655 const UINT layer = 1 + i / 32;
1565 const std::array<std::uint8_t, 4> zero{}; 1656 const std::array<std::uint8_t, 4> zero{};
1566 const auto mip2 = d.image_view_min_lod ? array_color(layer, 2) : zero; 1657 const auto mip2 = d.image_view_min_lod ? array_color(layer, 2) : zero;
1567 const std::array expected{array_color(layer, 1), mip2, mip2, zero}; 1658 const std::array expected{array_color(layer, 1), mip2, mip2, zero};
1659 // View 1 (minimum 1.75) floors to mip 1 where the driver uses minLodInteger; see the 2D views above.
1660 const std::array floored{array_color(layer, 1), d.image_view_min_lod ? array_color(layer, 1) : zero, mip2, zero};
1568 static_assert(expected.size() == std::size(array_clamps)); 1661 static_assert(expected.size() == std::size(array_clamps));
1569 for (UINT view = 0; view < expected.size(); ++view) { 1662 for (UINT view = 0; view < expected.size(); ++view) {
1570 const auto* got = array_pixels.data() + view * bytes + i * 4; 1663 const auto* got = array_pixels.data() + view * bytes + i * 4;
1664 if (std::memcmp(got, floored[view].data(), 4)) ++array_errors_floored[view];
1571 if (std::memcmp(got, expected[view].data(), 4) && array_errors[view]++ == 0) { 1665 if (std::memcmp(got, expected[view].data(), 4) && array_errors[view]++ == 0) {
1572 std::fprintf(stderr, "array LOD %.2f, layer %u: got %u,%u,%u,%u; expected %u,%u,%u,%u\n", 1666 std::snprintf(array_first[view], sizeof(array_first[view]),
1573 array_clamps[view], layer, got[0], got[1], got[2], got[3], 1667 "array LOD %.2f, layer %u: got %u,%u,%u,%u; expected %u,%u,%u,%u\n",
1574 expected[view][0], expected[view][1], expected[view][2], expected[view][3]); 1668 array_clamps[view], layer, got[0], got[1], got[2], got[3], expected[view][0],
1669 expected[view][1], expected[view][2], expected[view][3]);
1575 } 1670 }
1576 } 1671 }
1577 } 1672 }
1673 if (d.image_view_min_lod && array_errors[1] && !array_errors_floored[1]) {
1674 std::printf("array LOD %.2f: the driver floors the fractional minimum LOD, as Vulkan allows\n", array_clamps[1]);
1675 array_errors[1] = 0;
1676 }
1578 UINT array_mismatches = 0; 1677 UINT array_mismatches = 0;
1579 for (UINT view = 0; view < array_errors.size(); ++view) { 1678 for (UINT view = 0; view < array_errors.size(); ++view) {
1580 if (array_errors[view]) std::fprintf(stderr, "array LOD %.2f: %u/%u mismatched\n", 1679 if (array_errors[view]) {
1581 array_clamps[view], array_errors[view], texels); 1680 std::fputs(array_first[view], stderr);
1681 std::fprintf(stderr, "array LOD %.2f: %u/%u mismatched\n", array_clamps[view], array_errors[view], texels);
1682 }
1582 array_mismatches += array_errors[view]; 1683 array_mismatches += array_errors[view];
1583 } 1684 }
1584 lod_mismatches += array_mismatches; 1685 lod_mismatches += array_mismatches;
@@ -2047,10 +2148,12 @@ int main() {
2047 } 2148 }
2048 EXPECT(rgb96_differ == 0); 2149 EXPECT(rgb96_differ == 0);
2049 } 2150 }
2050 // The B8G8R8X8 and B8G8R8A8 textures through their default views. 2151 // The B8G8R8X8 and B8G8R8A8 textures through their default views, then the two castable ones through a view
2051 SampleKeys bgr_keys[2] = {}; 2152 // of the other family.
2052 const UINT bgr_slots[2] = {bgrx_slot, bgra_slot}; 2153 SampleKeys bgr_keys[bgr_count] = {};
2053 for (UINT k = 0; k < 2; ++k) { 2154 const UINT bgr_slots[bgr_count] = {bgrx_slot, bgra_slot, cast_bgrx_slot,
2155 cast_bgra_slot, cast_rgbx_slot, cast_rgba_slot};
2156 for (UINT k = 0; k < bgr_count; ++k) {
2054 std::memcpy(bgr_keys[k].tsharp, view_bytes(bgr_slots[k]), sizeof(bgr_keys[k].tsharp)); 2157 std::memcpy(bgr_keys[k].tsharp, view_bytes(bgr_slots[k]), sizeof(bgr_keys[k].tsharp));
2055 std::memcpy(bgr_keys[k].ssharp, sampler_bytes, sizeof(bgr_keys[k].ssharp)); 2158 std::memcpy(bgr_keys[k].ssharp, sampler_bytes, sizeof(bgr_keys[k].ssharp));
2056 bgr_keys[k].first = k * texels; 2159 bgr_keys[k].first = k * texels;
@@ -2657,12 +2760,15 @@ int main() {
2657 } 2760 }
2658 EXPECT(!mismatches); 2761 EXPECT(!mismatches);
2659 EXPECT(lod_mismatches == 0); 2762 EXPECT(lod_mismatches == 0);
2660 // Both read red, green and blue from the same bytes; B8G8R8X8 reads alpha 1, B8G8R8A8 the stored byte. 2763 // All read red, green and blue from the same bytes; a B8G8R8X8 view reads alpha 1, a B8G8R8A8 view the stored
2661 const char* bgr_names[2] = {"B8G8R8X8_UNORM", "B8G8R8A8_UNORM"}; 2764 // byte, whatever the texture's own format (R8G8B8A8 textures read through B8G8R8X8 and B8G8R8A8 views included).
2662 for (UINT k = 0; k < 2; ++k) 2765 const char* bgr_names[] = {"B8G8R8X8_UNORM", "B8G8R8A8_UNORM", "B8G8R8X8_UNORM view of castable B8G8R8A8",
2766 "B8G8R8A8_UNORM view of castable B8G8R8X8", "B8G8R8X8_UNORM view of castable R8G8B8A8",
2767 "B8G8R8A8_UNORM view of castable R8G8B8A8"};
2768 for (UINT k = 0; k < 6; ++k)
2663 for (UINT i = 0; i < texels; ++i) { 2769 for (UINT i = 0; i < texels; ++i) {
2664 auto want = texel(i % size, i / size); 2770 auto want = texel(i % size, i / size);
2665 if (k == 1) want[3] = bgrx_texel(i % size, i / size)[3]; 2771 if (k == 1 || k == 3 || k == 5) want[3] = bgrx_texel(i % size, i / size)[3];
2666 const std::uint8_t* got = bgr_results.data() + k * bytes + i * 4; 2772 const std::uint8_t* got = bgr_results.data() + k * bytes + i * 4;
2667 if (std::memcmp(got, want.data(), 4) != 0 && mismatches++ < 4) 2773 if (std::memcmp(got, want.data(), 4) != 0 && mismatches++ < 4)
2668 std::fprintf(stderr, "%s texel %u: got %u,%u,%u,%u, want %u,%u,%u,%u\n", bgr_names[k], i, 2774 std::fprintf(stderr, "%s texel %u: got %u,%u,%u,%u, want %u,%u,%u,%u\n", bgr_names[k], i,
@@ -2677,7 +2783,8 @@ int main() {
2677 std::printf("descriptors: copies matched; a T# and an S# from CreateShaderResourceView and CreateSampler were " 2783 std::printf("descriptors: copies matched; a T# and an S# from CreateShaderResourceView and CreateSampler were "
2678 "found in the device's bindless set by a shader, %u RGBA8 and RGB9E5 texels matched, and an unknown descriptor " 2784 "found in the device's bindless set by a shader, %u RGBA8 and RGB9E5 texels matched, and an unknown descriptor "
2679 "and a destroyed texture's gave the fallback; UINT black, UINT white and float white borders read " 2785 "and a destroyed texture's gave the fallback; UINT black, UINT white and float white borders read "
2680 "0, 1 and 255; B8G8R8X8 read alpha 1 where B8G8R8A8 read the same bytes' alpha (%u texels each)\n", 2786 "0, 1 and 255; B8G8R8X8 views read alpha 1 where B8G8R8A8 views read the same bytes' alpha, also across "
2787 "a castable-format list (%u texels each)\n",
2681 texels, texels); 2788 texels, texels);
2682 return 0; 2789 return 0;
2683} 2790}
diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp
index 216534cd4..df79436e8 100644
--- a/runtime/test/d3d12_draw_test.cpp
+++ b/runtime/test/d3d12_draw_test.cpp
@@ -101,7 +101,9 @@ int main() {
101 std::vector<std::uint8_t> strip16_pixels(size * 256), strip32_pixels(size * 256), strip_nocut_pixels(size * 256); 101 std::vector<std::uint8_t> strip16_pixels(size * 256), strip32_pixels(size * 256), strip_nocut_pixels(size * 256);
102 std::vector<std::uint8_t> msaa_full_pixels(size * 256), msaa_half_pixels(size * 256); 102 std::vector<std::uint8_t> msaa_full_pixels(size * 256), msaa_half_pixels(size * 256);
103 bool ran_msaa = false; 103 bool ran_msaa = false;
104 std::vector<std::uint8_t> step2_pixels(size * 256), step1_pixels(size * 256);
104 const bool logic_op = d.enabled.logicOp == VK_TRUE; 105 const bool logic_op = d.enabled.logicOp == VK_TRUE;
106 const bool has_divisor = d.vertex_attribute_divisor;
105 { 107 {
106 rt::d3d12::VulkanDeviceInfo info{}; 108 rt::d3d12::VulkanDeviceInfo info{};
107 info.get_instance_proc = d.instance_proc; 109 info.get_instance_proc = d.instance_proc;
@@ -115,6 +117,7 @@ int main() {
115 info.shader_dir = library.string(); 117 info.shader_dir = library.string();
116 // Of the PSO features only logicOp is passed on, so the other feature refusals below still apply. 118 // Of the PSO features only logicOp is passed on, so the other feature refusals below still apply.
117 info.features.logicOp = d.enabled.logicOp; 119 info.features.logicOp = d.enabled.logicOp;
120 info.vertex_attribute_divisor = d.vertex_attribute_divisor;
118 ID3D12Device* inner = nullptr; 121 ID3D12Device* inner = nullptr;
119 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); 122 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
120 Ref<ID3D12Device> device; 123 Ref<ID3D12Device> device;
@@ -808,6 +811,69 @@ int main() {
808 unsigned(std::size(x8_cases))); 811 unsigned(std::size(x8_cases)));
809 } 812 }
810 813
814 // Instance step rate > 1 (VK_KHR/EXT_vertex_attribute_divisor): two per-instance colours in slot 1:
815 // entry 0 = red, entry 1 = magenta (both preserved by the {1,0,1} tint). With step rate 2:
816 // - Draw 1 (top-left, 2 instances from 0): instances 0 and 1 both read entry 0/2 = 0 (red).
817 // - Draw 2 (bottom-right, 3 instances from 0): instance 2 reads entry 2/2 = 1 (magenta) on top.
818 // Negative control (step rate 1, same 2-instance draw at top-left): instance 1 reads entry 1 (magenta) over
819 // instance 0, flipping all 1,024 top-left pixels from red to magenta.
820 if (has_divisor) {
821 const std::uint8_t inst_colors[2][4] = {{255, 0, 0, 255}, {255, 0, 255, 255}};
822 void* up_ptr = nullptr;
823 EXPECT(SUCCEEDED(upload->Map(0, nullptr, &up_ptr)));
824 std::memcpy(static_cast<std::uint8_t*>(up_ptr) + 1024, inst_colors, sizeof(inst_colors));
825 upload->Unmap(0, nullptr);
826
827 const D3D12_INPUT_ELEMENT_DESC step2_elements[2] = {
828 {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
829 {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 2},
830 };
831 const D3D12_INPUT_ELEMENT_DESC step1_elements[2] = {
832 {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
833 {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1},
834 };
835 auto step_desc = pso_desc;
836 Ref<ID3D12PipelineState> step2_pso, step1_pso;
837 step_desc.InputLayout = {step2_elements, 2};
838 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&step_desc, IID_PPV_ARGS(&step2_pso.p))));
839 step_desc.InputLayout = {step1_elements, 2};
840 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&step_desc, IID_PPV_ARGS(&step1_pso.p))));
841
842 const D3D12_VERTEX_BUFFER_VIEW step_vbvs[2] = {vbv, {upload_va + 1024, sizeof(inst_colors), 4}};
843 const float br_offset[2] = {1.0f, -1.0f};
844 UINT64 step_fence = 60;
845 for (UINT pass = 0; pass < 2; ++pass) {
846 EXPECT(SUCCEEDED(allocator->Reset()) &&
847 SUCCEEDED(list->Reset(allocator.p, pass == 0 ? step2_pso.p : step1_pso.p)));
848 list->ResourceBarrier(1, &to_target);
849 list->ClearRenderTargetView(rtv, blue, 0, nullptr);
850 list->SetGraphicsRootSignature(root.p);
851 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
852 list->IASetVertexBuffers(0, 2, step_vbvs);
853 list->IASetIndexBuffer(&ibv);
854 list->RSSetViewports(1, &viewport);
855 list->RSSetScissorRects(1, &scissor);
856 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
857 list->SetGraphicsRootConstantBufferView(1, upload_va + 512);
858 list->SetGraphicsRoot32BitConstants(0, 2, origin, 0);
859 list->DrawIndexedInstanced(6, 2, 0, 0, 0);
860 if (pass == 0) {
861 list->SetGraphicsRoot32BitConstants(0, 2, br_offset, 0);
862 list->DrawIndexedInstanced(6, 3, 0, 0, 0);
863 }
864 list->ResourceBarrier(1, &to_copy);
865 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
866 EXPECT(list->Close() == S_OK);
867 queue->ExecuteCommandLists(1, lists);
868 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
869 ++step_fence;
870 EXPECT(SUCCEEDED(queue->Signal(fence.p, step_fence)) &&
871 SUCCEEDED(fence->SetEventOnCompletion(step_fence, nullptr)));
872 auto& dst_buf = pass == 0 ? step2_pixels : step1_pixels;
873 std::memcpy(dst_buf.data(), mapped, dst_buf.size());
874 }
875 }
876
811 // A draw without a topology is invalid; Close reports it. 877 // A draw without a topology is invalid; Close reports it.
812 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p))); 878 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p)));
813 list->SetGraphicsRootSignature(root.p); 879 list->SetGraphicsRootSignature(root.p);
@@ -924,6 +990,35 @@ int main() {
924 "top-left pixels to purple)\n", 990 "top-left pixels to purple)\n",
925 half_changed, (size / 2) * (size / 2)); 991 half_changed, (size / 2) * (size / 2));
926 } 992 }
993 if (has_divisor) {
994 UINT step1_flipped = 0;
995 for (UINT row = 0; row < size; ++row) {
996 for (UINT col = 0; col < size; ++col) {
997 const bool top = row < size / 2, left = col < size / 2;
998 using Pixel = std::array<std::uint8_t, 4>;
999 const Pixel want2 = top && left ? Pixel{255, 0, 0, 255}
1000 : !top && !left ? Pixel{255, 0, 255, 255}
1001 : Pixel{0, 0, 255, 255};
1002 const std::uint8_t* got2 = step2_pixels.data() + row * 256 + col * 4;
1003 if (!std::equal(want2.begin(), want2.end(), got2) && mismatches++ < 6)
1004 std::fprintf(stderr, "step-rate 2 pixel (%u,%u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row,
1005 got2[0], got2[1], got2[2], got2[3], want2[0], want2[1], want2[2], want2[3]);
1006 if (top && left) {
1007 const std::uint8_t* got1 = step1_pixels.data() + row * 256 + col * 4;
1008 const Pixel want1{255, 0, 255, 255};
1009 if (!std::equal(want1.begin(), want1.end(), got1) && mismatches++ < 6)
1010 std::fprintf(stderr, "step-rate 1 control (%u,%u): got %u,%u,%u,%u want 255,0,255,255\n", col,
1011 row, got1[0], got1[1], got1[2], got1[3]);
1012 if (std::memcmp(got1, got2, 4) != 0) ++step1_flipped;
1013 }
1014 }
1015 }
1016 EXPECT(!mismatches);
1017 EXPECT(step1_flipped == (size / 2) * (size / 2));
1018 std::printf("instance step rate 2: 4096/4096 pixels matched (step-rate 1 control flipped %u/%u top-left "
1019 "pixels from red to magenta)\n",
1020 step1_flipped, (size / 2) * (size / 2));
1021 }
927 if (d.validation_errors()) { 1022 if (d.validation_errors()) {
928 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 1023 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
929 return 1; 1024 return 1;
diff --git a/runtime/test/d3d12_fence_events_test.cpp b/runtime/test/d3d12_fence_events_test.cpp
index 93685b033..c211c29b2 100644
--- a/runtime/test/d3d12_fence_events_test.cpp
+++ b/runtime/test/d3d12_fence_events_test.cpp
@@ -3,6 +3,7 @@
3// as one fence reached, ANY is satisfied), and SetEventOnMultipleFenceCompletion with no fences is E_INVALIDARG and 3// as one fence reached, ANY is satisfied), and SetEventOnMultipleFenceCompletion with no fences is E_INVALIDARG and
4// sets nothing. No shaders or game data. LEONIDA_VK_VALIDATION=1 fails the test on any validation error. 4// sets nothing. No shaders or game data. LEONIDA_VK_VALIDATION=1 fails the test on any validation error.
5#include "vk_test_device.h" 5#include "vk_test_device.h"
6#include "host_adapter.h"
6#include "host_wine.h" 7#include "host_wine.h"
7#include "../shims/d3d12_com.h" 8#include "../shims/d3d12_com.h"
8#include <dxgi1_4.h> 9#include <dxgi1_4.h>
@@ -95,9 +96,10 @@ int main() {
95 for (const bool warp : {false, true}) { // the reference the expectations were measured on 96 for (const bool warp : {false, true}) { // the reference the expectations were measured on
96 Ref<IDXGIAdapter> adapter; 97 Ref<IDXGIAdapter> adapter;
97 Ref<ID3D12Device> host; 98 Ref<ID3D12Device> host;
98 if (warp && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue; 99 std::string adapter_name;
100 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue;
99 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; 101 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
100 failures += check(host.p, warp ? "host WARP" : "host default adapter"); 102 failures += check(host.p, ("host " + adapter_name).c_str());
101 } 103 }
102 } 104 }
103 } 105 }
diff --git a/runtime/test/d3d12_fence_timing_test.cpp b/runtime/test/d3d12_fence_timing_test.cpp
index f5e067dfb..89ad8df49 100644
--- a/runtime/test/d3d12_fence_timing_test.cpp
+++ b/runtime/test/d3d12_fence_timing_test.cpp
@@ -1,9 +1,10 @@
1// D3D-30 on the Vulkan device, through the Xbox-ABI proxy: SetEventOnMultipleFenceCompletion (ALL and ANY, with an 1// D3D-30 on the Vulkan device, through the Xbox-ABI proxy: SetEventOnMultipleFenceCompletion (ALL and ANY, with an
2// event and blocking), queue GetClockCalibration on both paths (calibrated timestamps on the standalone device when 2// event and blocking), a CPU fence signal held behind a pending queue signal, queue GetClockCalibration on both
3// it exposes both clock domains, the submitted timestamp query otherwise), GetAdapterLuid (must name a 3// paths (calibrated timestamps on the standalone device when it exposes both clock domains, the submitted timestamp
4// DXGI adapter) and GetCustomHeapProperties (compared with the host PC runtime's answer when the host adapter is 4// query otherwise), GetAdapterLuid (must name a DXGI adapter) and GetCustomHeapProperties (compared with the host PC
5// NUMA, as the layer reports itself). No shaders or game data. LEONIDA_VK_VALIDATION=1 runs the test-made device 5// runtime's answer when the host adapter is NUMA, as the layer reports itself). No shaders or game data.
6// under VK_LAYER_KHRONOS_validation; any validation error fails the test. 6// LEONIDA_VK_VALIDATION=1 runs the test-made device under VK_LAYER_KHRONOS_validation; any validation error fails
7// the test.
7#include "vk_test_device.h" 8#include "vk_test_device.h"
8#include "../shims/d3d12_com.h" 9#include "../shims/d3d12_com.h"
9#include "../shims/d3d12_xs_device.h" 10#include "../shims/d3d12_xs_device.h"
@@ -165,6 +166,36 @@ int check_multiple_fences(ID3D12Device* device, ID3D12CommandQueue* queue) {
165 return 0; 166 return 0;
166} 167}
167 168
169// A CPU Signal above a queue Signal the GPU has not reached yet: vkSignalSemaphore would break
170// VUID-VkSemaphoreSignalInfo-value-03259, so the layer holds the CPU signal until the GPU passes the queue's value.
171// The queue's signal is kept pending by a Wait on a gate fence the CPU opens later.
172int check_held_cpu_signal(ID3D12Device* device, ID3D12CommandQueue* queue) {
173 Ref<ID3D12Fence> gate, f;
174 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate.p))));
175 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&f.p))));
176 EXPECT(SUCCEEDED(queue->Wait(gate.p, 1)));
177 EXPECT(SUCCEEDED(queue->Signal(f.p, 10)));
178 EXPECT(SUCCEEDED(f->Signal(20)));
179 Event reached;
180 EXPECT(SUCCEEDED(f->SetEventOnCompletion(20, reached.h)));
181 EXPECT(!reached.set_within(50));
182 EXPECT(f->GetCompletedValue() < 10); // held: the GPU has not reached 10, so 20 is not applied either
183 EXPECT(SUCCEEDED(gate->Signal(1)));
184 EXPECT(reached.set_within(5000));
185 EXPECT(f->GetCompletedValue() == 20);
186
187 // Two CPU signals held behind one queue signal are applied in order: the fence ends on the later one.
188 EXPECT(SUCCEEDED(queue->Wait(gate.p, 2)));
189 EXPECT(SUCCEEDED(queue->Signal(f.p, 30)));
190 EXPECT(SUCCEEDED(f->Signal(40)));
191 EXPECT(SUCCEEDED(f->Signal(50)));
192 EXPECT(f->GetCompletedValue() == 20);
193 EXPECT(SUCCEEDED(gate->Signal(2)));
194 EXPECT(SUCCEEDED(f->SetEventOnCompletion(50, nullptr)));
195 EXPECT(f->GetCompletedValue() == 50);
196 return 0;
197}
198
168int check_luid(ID3D12Device* device) { 199int check_luid(ID3D12Device* device) {
169 const LUID luid = device->GetAdapterLuid(); 200 const LUID luid = device->GetAdapterLuid();
170 EXPECT(luid.LowPart || luid.HighPart); 201 EXPECT(luid.LowPart || luid.HighPart);
@@ -282,6 +313,7 @@ int main() {
282 EXPECT(!rt::d3d12::queue_uses_calibrated_timestamps(queue.p)); 313 EXPECT(!rt::d3d12::queue_uses_calibrated_timestamps(queue.p));
283 EXPECT(check_calibration(queue.p, gpu_frequency, "fallback (submitted timestamp query)") == 0); 314 EXPECT(check_calibration(queue.p, gpu_frequency, "fallback (submitted timestamp query)") == 0);
284 EXPECT(check_multiple_fences(device.p, queue.p) == 0); 315 EXPECT(check_multiple_fences(device.p, queue.p) == 0);
316 EXPECT(check_held_cpu_signal(device.p, queue.p) == 0);
285 EXPECT(check_luid(device.p) == 0); 317 EXPECT(check_luid(device.p) == 0);
286 EXPECT(check_custom_heap_properties(device.p) == 0); 318 EXPECT(check_custom_heap_properties(device.p) == 0);
287 } 319 }
@@ -328,6 +360,7 @@ int main() {
328 const char* clock_path = calibrated ? "calibration-capable queue" : "standalone fallback"; 360 const char* clock_path = calibrated ? "calibration-capable queue" : "standalone fallback";
329 EXPECT(check_calibration(queue.p, gpu_frequency, clock_path) == 0); 361 EXPECT(check_calibration(queue.p, gpu_frequency, clock_path) == 0);
330 EXPECT(check_multiple_fences(standalone.p, queue.p) == 0); 362 EXPECT(check_multiple_fences(standalone.p, queue.p) == 0);
363 EXPECT(check_held_cpu_signal(standalone.p, queue.p) == 0);
331 EXPECT(check_luid(standalone.p) == 0); 364 EXPECT(check_luid(standalone.p) == 0);
332 } 365 }
333 366
@@ -335,7 +368,7 @@ int main() {
335 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 368 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
336 return 1; 369 return 1;
337 } 370 }
338 std::printf("fences and timing: multiple-fence waits, clock calibration, adapter LUID and custom heap " 371 std::printf("fences and timing: multiple-fence waits, held CPU signals, clock calibration, adapter LUID and "
339 "properties all checked\n"); 372 "custom heap properties all checked\n");
340 return 0; 373 return 0;
341} 374}
diff --git a/runtime/test/d3d12_fspx_compute_test.cpp b/runtime/test/d3d12_fspx_compute_test.cpp
index 607af18e4..b19605944 100644
--- a/runtime/test/d3d12_fspx_compute_test.cpp
+++ b/runtime/test/d3d12_fspx_compute_test.cpp
@@ -213,6 +213,11 @@ int main() {
213 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), 213 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
214 reinterpret_cast<void**>(&device.p)))); 214 reinterpret_cast<void**>(&device.p))));
215 rt::d3d12::set_device_outer(inner, device.p); 215 rt::d3d12::set_device_outer(inner, device.p);
216 if (rt::d3d12::device_push_constants_need_fallback(inner)) {
217 std::printf("d3d12_fspx_compute_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n",
218 rt::d3d12::device_max_push_constants_size(inner));
219 return 77;
220 }
216 221
217 // Root signature: [0] two constants (s0, s1), [1] a root UAV (s2:s3), [2] a one-CBV table (s4:s5). 222 // Root signature: [0] two constants (s0, s1), [1] a root UAV (s2:s3), [2] a one-CBV table (s4:s5).
218 D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; 223 D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0};
diff --git a/runtime/test/d3d12_gcl8_test.cpp b/runtime/test/d3d12_gcl8_test.cpp
index 3f5cb04dc..722f46f54 100644
--- a/runtime/test/d3d12_gcl8_test.cpp
+++ b/runtime/test/d3d12_gcl8_test.cpp
@@ -89,6 +89,8 @@ int main(int argc, char** argv) {
89 // Calls made before pipeline setup still belong in the trace. They invalidate this list without needing a GPU. 89 // Calls made before pipeline setup still belong in the trace. They invalidate this list without needing a GPU.
90 list7.p->SetDescriptorHeaps(0, nullptr); 90 list7.p->SetDescriptorHeaps(0, nullptr);
91 list7.p->SetGraphicsRootDescriptorTable(0, {}); 91 list7.p->SetGraphicsRootDescriptorTable(0, {});
92 list7.p->SetComputeRootSignature(nullptr);
93 list7.p->Dispatch(1, 1, 1);
92 list7.p->DrawInstanced(3, 1, 0, 0); 94 list7.p->DrawInstanced(3, 1, 0, 0);
93 list7.p->DrawIndexedInstanced(3, 1, 0, 0, 0); 95 list7.p->DrawIndexedInstanced(3, 1, 0, 0, 0);
94 EXPECT(list7.p->Close() == E_INVALIDARG); 96 EXPECT(list7.p->Close() == E_INVALIDARG);
diff --git a/runtime/test/d3d12_indirect_zero_test.cpp b/runtime/test/d3d12_indirect_zero_test.cpp
index 3e077e6e1..f56e24e88 100644
--- a/runtime/test/d3d12_indirect_zero_test.cpp
+++ b/runtime/test/d3d12_indirect_zero_test.cpp
@@ -1,6 +1,7 @@
1// ExecuteIndirect with MaxCommandCount 0 on the Vulkan-backed device against Windows D3D12 (the default adapter and 1// ExecuteIndirect with MaxCommandCount 0 on the Vulkan-backed device against Windows D3D12 (the layer's own adapter
2// WARP): the list's Close() result. A zero-command ExecuteIndirect is a no-op, not an error that fails the list. 2// and WARP): the list's Close() result. A zero-command ExecuteIndirect is a no-op, not an error that fails the list.
3#include "vk_test_device.h" 3#include "vk_test_device.h"
4#include "host_adapter.h"
4#include "host_wine.h" 5#include "host_wine.h"
5#include "../shims/d3d12_com.h" 6#include "../shims/d3d12_com.h"
6#include <dxgi1_4.h> 7#include <dxgi1_4.h>
@@ -77,7 +78,8 @@ int main() {
77 for (const bool warp : {false, true}) { 78 for (const bool warp : {false, true}) {
78 Ref<IDXGIAdapter> adapter; 79 Ref<IDXGIAdapter> adapter;
79 Ref<ID3D12Device> host; 80 Ref<ID3D12Device> host;
80 if (warp && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue; 81 std::string adapter_name;
82 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue;
81 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; 83 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
82 ++references; 84 ++references;
83 for (const Case& c : cases) { 85 for (const Case& c : cases) {
@@ -86,7 +88,7 @@ int main() {
86 const bool same = SUCCEEDED(a) == SUCCEEDED(e); 88 const bool same = SUCCEEDED(a) == SUCCEEDED(e);
87 if (!same) ++mismatched; 89 if (!same) ++mismatched;
88 std::printf("%s %s, MaxCommandCount 0: ours Close 0x%08lx, %s 0x%08lx\n", same ? "[ok] " : "[FAIL]", 90 std::printf("%s %s, MaxCommandCount 0: ours Close 0x%08lx, %s 0x%08lx\n", same ? "[ok] " : "[FAIL]",
89 c.name, static_cast<unsigned long>(a), warp ? "WARP" : "default adapter", 91 c.name, static_cast<unsigned long>(a), adapter_name.c_str(),
90 static_cast<unsigned long>(e)); 92 static_cast<unsigned long>(e));
91 } 93 }
92 } 94 }
diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp
index bd3a555fd..e3863e997 100644
--- a/runtime/test/d3d12_m4_compute_test.cpp
+++ b/runtime/test/d3d12_m4_compute_test.cpp
@@ -17,7 +17,7 @@
17// CopyTextureRegion) to a READBACK buffer, Signal(copy fence, 2). The CPU waits for that with 17// CopyTextureRegion) to a READBACK buffer, Signal(copy fence, 2). The CPU waits for that with
18// SetEventOnCompletion and an event. 18// SetEventOnCompletion and an event.
19// When the Vulkan family has two queues, the copy and the compute D3D12 queue get their own VkQueue (so the fences are 19// When the Vulkan family has two queues, the copy and the compute D3D12 queue get their own VkQueue (so the fences are
20// real cross-queue semaphores); with one, they share it. Either way the three batches are submitted in dependency order. 20// real cross-queue semaphores); with one, they share it. Either way the readback batch is submitted before the compute batch it waits for (the layer holds it until that Signal has been submitted).
21// Compared with a CPU reference, word by word, error 0: the input after the round trip, the structured buffer, the 21// Compared with a CPU reference, word by word, error 0: the input after the round trip, the structured buffer, the
22// argument buffer, the image and the indirect dispatch's output (which also shows that exactly the 3 groups the 22// argument buffer, the image and the indirect dispatch's output (which also shows that exactly the 3 groups the
23// first dispatch asked for ran). 23// first dispatch asked for ran).
@@ -331,10 +331,11 @@ int main() {
331 return SUCCEEDED(compute_queue->Wait(copy_fence.p, 1)) && execute(compute_queue.p, compute_list.p) && 331 return SUCCEEDED(compute_queue->Wait(copy_fence.p, 1)) && execute(compute_queue.p, compute_list.p) &&
332 SUCCEEDED(compute_queue->Signal(compute_fence.p, 1)); 332 SUCCEEDED(compute_queue->Signal(compute_fence.p, 1));
333 }; 333 };
334 // In dependency order: the layer replays a list at ExecuteCommandLists and tracks every image's layout in that 334 // The compute list goes last, after the copy-queue list that reads its results (the copy queue keeps its own
335 // order, so a list that waits for another queue's signal has to be submitted after the list it waits for 335 // order): a list that waits for a Signal submitted later is held by the layer
336 // (the Wait-before-Signal order d3d12_queue_wait_test covers, without a resource handed over). 336 // until it has been, so its layouts follow the dependency order (docs section 4.4; d3d12_queue_handover_test
337 EXPECT(submit_copy() && submit_compute() && submit_readback()); 337 // covers every order).
338 EXPECT(submit_copy() && submit_readback() && submit_compute());
338 339
339 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 340 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
340 EXPECT(event != nullptr); 341 EXPECT(event != nullptr);
diff --git a/runtime/test/d3d12_msaa_draw_test.cpp b/runtime/test/d3d12_msaa_draw_test.cpp
index 2c87e880c..f56057d73 100644
--- a/runtime/test/d3d12_msaa_draw_test.cpp
+++ b/runtime/test/d3d12_msaa_draw_test.cpp
@@ -47,7 +47,9 @@ D3D12_CPU_DESCRIPTOR_HANDLE heap_start(ID3D12DescriptorHeap* heap) {
47 47
48int main() { 48int main() {
49 vktest::Device d; 49 vktest::Device d;
50 EXPECT(d.create()); 50 const auto device_status = d.initialize();
51 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU (hosted CI): ctest skips
52 EXPECT(device_status == vktest::DeviceStatus::ready);
51 53
52 const auto vs_program = fssm_program({0x56530001, 0xbf810000}); 54 const auto vs_program = fssm_program({0x56530001, 0xbf810000});
53 const auto ps_program = fssm_program({0x50530001, 0xbf810000}); 55 const auto ps_program = fssm_program({0x50530001, 0xbf810000});
@@ -87,6 +89,11 @@ int main() {
87 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), 89 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
88 reinterpret_cast<void**>(&device.p)))); 90 reinterpret_cast<void**>(&device.p))));
89 rt::d3d12::set_device_outer(inner, device.p); 91 rt::d3d12::set_device_outer(inner, device.p);
92 if (rt::d3d12::device_push_constants_need_fallback(inner)) {
93 std::printf("d3d12_msaa_draw_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n",
94 rt::d3d12::device_max_push_constants_size(inner));
95 return 77;
96 }
90 97
91 D3D12_ROOT_PARAMETER params[2] = {}; 98 D3D12_ROOT_PARAMETER params[2] = {};
92 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; 99 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
diff --git a/runtime/test/d3d12_multithread_test.cpp b/runtime/test/d3d12_multithread_test.cpp
index 18e10642f..a3932d96e 100644
--- a/runtime/test/d3d12_multithread_test.cpp
+++ b/runtime/test/d3d12_multithread_test.cpp
@@ -197,9 +197,11 @@ int main() {
197 ID3D12CommandList* lists[1] = {cl.p}; 197 ID3D12CommandList* lists[1] = {cl.p};
198 queues[tid]->ExecuteCommandLists(1, lists); 198 queues[tid]->ExecuteCommandLists(1, lists);
199 const UINT64 target = ++fence_vals[tid]; 199 const UINT64 target = ++fence_vals[tid];
200 // 60 s, not 15 s: under heavy parallel load (two full `ctest -j 6` suites sharing the GPU) a fence can
201 // take longer than 15 s to signal; sibling GPU tests already wait 15-60 s (TEST-514 follow-up).
200 if (FAILED(queues[tid]->Signal(fences[tid].p, target)) || 202 if (FAILED(queues[tid]->Signal(fences[tid].p, target)) ||
201 FAILED(fences[tid]->SetEventOnCompletion(target, ev.h)) || 203 FAILED(fences[tid]->SetEventOnCompletion(target, ev.h)) ||
202 WaitForSingleObject(ev.h, 15000) != WAIT_OBJECT_0) { 204 WaitForSingleObject(ev.h, 60000) != WAIT_OBJECT_0) {
203 failures.fetch_add(1); 205 failures.fetch_add(1);
204 fail("Signal/SetEventOnCompletion/Wait", tid, it); 206 fail("Signal/SetEventOnCompletion/Wait", tid, it);
205 return; 207 return;
@@ -365,7 +367,7 @@ int main() {
365 const UINT64 v1 = ++fence_vals[1]; 367 const UINT64 v1 = ++fence_vals[1];
366 if (FAILED(queues[1]->Signal(fences[1].p, v1)) || 368 if (FAILED(queues[1]->Signal(fences[1].p, v1)) ||
367 FAILED(fences[1]->SetEventOnCompletion(v1, handoff_ev.h)) || 369 FAILED(fences[1]->SetEventOnCompletion(v1, handoff_ev.h)) ||
368 WaitForSingleObject(handoff_ev.h, 15000) != WAIT_OBJECT_0) 370 WaitForSingleObject(handoff_ev.h, 60000) != WAIT_OBJECT_0)
369 return fail("Signal/Wait q1 (handoff)"); 371 return fail("Signal/Wait q1 (handoff)");
370 372
371 void* mapped = nullptr; 373 void* mapped = nullptr;
@@ -400,7 +402,7 @@ int main() {
400 return fail("SetEventOnMultipleFenceCompletion (ALL)"); 402 return fail("SetEventOnMultipleFenceCompletion (ALL)");
401 if (FAILED(queues[0]->Signal(fences[0].p, targets[0])) || FAILED(queues[1]->Signal(fences[1].p, targets[1]))) 403 if (FAILED(queues[0]->Signal(fences[0].p, targets[0])) || FAILED(queues[1]->Signal(fences[1].p, targets[1])))
402 return fail("Signal (multi ALL)"); 404 return fail("Signal (multi ALL)");
403 if (WaitForSingleObject(multi_ev.h, 15000) != WAIT_OBJECT_0) return fail("WaitForSingleObject (multi ALL)"); 405 if (WaitForSingleObject(multi_ev.h, 60000) != WAIT_OBJECT_0) return fail("WaitForSingleObject (multi ALL)");
404 406
405 // Exercise SetEventOnMultipleFenceCompletion (ANY): signalling only fence 0 satisfies the wait while fence 1 stays below target. 407 // Exercise SetEventOnMultipleFenceCompletion (ANY): signalling only fence 0 satisfies the wait while fence 1 stays below target.
406 EventHandle any_ev; 408 EventHandle any_ev;
@@ -410,7 +412,7 @@ int main() {
410 any_ev.h))) 412 any_ev.h)))
411 return fail("SetEventOnMultipleFenceCompletion (ANY)"); 413 return fail("SetEventOnMultipleFenceCompletion (ANY)");
412 if (FAILED(queues[0]->Signal(fences[0].p, any_targets[0]))) return fail("Signal (multi ANY)"); 414 if (FAILED(queues[0]->Signal(fences[0].p, any_targets[0]))) return fail("Signal (multi ANY)");
413 if (WaitForSingleObject(any_ev.h, 15000) != WAIT_OBJECT_0) return fail("WaitForSingleObject (multi ANY)"); 415 if (WaitForSingleObject(any_ev.h, 60000) != WAIT_OBJECT_0) return fail("WaitForSingleObject (multi ANY)");
414 } 416 }
415 } // vktest::Device::~Device() destroys VkDevice here so any leaked-object VUIDs are counted below. 417 } // vktest::Device::~Device() destroys VkDevice here so any leaked-object VUIDs are counted below.
416 418
diff --git a/runtime/test/d3d12_node_mask_test.cpp b/runtime/test/d3d12_node_mask_test.cpp
index ca030c385..31ee215bf 100644
--- a/runtime/test/d3d12_node_mask_test.cpp
+++ b/runtime/test/d3d12_node_mask_test.cpp
@@ -1,10 +1,11 @@
1// Compare what ID3D12Resource::GetHeapProperties, ID3D12DescriptorHeap::GetDesc and ID3D12CommandQueue::GetDesc 1// Compare what ID3D12Resource::GetHeapProperties, ID3D12DescriptorHeap::GetDesc and ID3D12CommandQueue::GetDesc
2// report on the Vulkan-backed device with Windows D3D12 (the default adapter and WARP). On a single adapter a node 2// report on the Vulkan-backed device with Windows D3D12 (the layer's own adapter and WARP). On a single adapter a node
3// mask of 0 reads back as the one node (1), and a committed resource reports the heap flags the runtime resolves: 3// mask of 0 reads back as the one node (1), and a committed resource reports the heap flags the runtime resolves:
4// the caller's, plus the DENY bits of the 4// the caller's, plus the DENY bits of the
5// resource classes it is not (a buffer 0xC0, a texture without render-target or depth use 0x44, the rest 0x84). 5// resource classes it is not (a buffer 0xC0, a texture without render-target or depth use 0x44, the rest 0x84).
6// No game data or shaders. Run explicitly (needs Vulkan hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage. 6// No game data or shaders. Run explicitly (needs Vulkan hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage.
7#include "vk_test_device.h" 7#include "vk_test_device.h"
8#include "host_adapter.h"
8#include "host_wine.h" 9#include "host_wine.h"
9#include "../shims/d3d12_com.h" 10#include "../shims/d3d12_com.h"
10#include <dxgi1_4.h> 11#include <dxgi1_4.h>
@@ -253,9 +254,10 @@ int main() {
253 for (const bool warp : {false, true}) { 254 for (const bool warp : {false, true}) {
254 Ref<IDXGIAdapter> adapter; 255 Ref<IDXGIAdapter> adapter;
255 Ref<ID3D12Device> host; 256 Ref<ID3D12Device> host;
256 if (warp && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue; 257 std::string adapter_name;
258 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue;
257 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; 259 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
258 const char* name = warp ? "WARP" : "the default adapter"; 260 const char* name = adapter_name.c_str();
259 const Totals heap_totals = compare_heaps(ours.p, host.p, name, heaps); 261 const Totals heap_totals = compare_heaps(ours.p, host.p, name, heaps);
260 const Totals desc_totals = compare_descriptor_heaps(ours.p, host.p, name, descriptors); 262 const Totals desc_totals = compare_descriptor_heaps(ours.p, host.p, name, descriptors);
261 const Totals queue_totals = compare_queues(ours.p, host.p, name); 263 const Totals queue_totals = compare_queues(ours.p, host.p, name);
@@ -277,7 +279,7 @@ int main() {
277 } 279 }
278 } 280 }
279 if (!references) { 281 if (!references) {
280 std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n"); 282 std::fprintf(stderr, "no D3D12 reference device (hardware adapter or WARP)\n");
281 return 1; 283 return 1;
282 } 284 }
283 if (mismatched || !matched) return 1; 285 if (mismatched || !matched) return 1;
diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp
index 5643c0d73..fbc7bb5fc 100644
--- a/runtime/test/d3d12_pipeline_library_test.cpp
+++ b/runtime/test/d3d12_pipeline_library_test.cpp
@@ -118,6 +118,12 @@ int main() {
118 !bad.p); 118 !bad.p);
119 } 119 }
120 120
121 if (rt::d3d12::device_push_constants_need_fallback(device.p)) {
122 std::printf("d3d12_pipeline_library_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n",
123 rt::d3d12::device_max_push_constants_size(device.p));
124 return 77;
125 }
126
121 // 2. Build one compute PSO and one graphics PSO. 127 // 2. Build one compute PSO and one graphics PSO.
122 D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1, 0, 0}; 128 D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1, 0, 0};
123 D3D12_ROOT_PARAMETER cs_params[3]{}; 129 D3D12_ROOT_PARAMETER cs_params[3]{};
diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp
index c3a0f4d39..de0ff9a02 100644
--- a/runtime/test/d3d12_present_test.cpp
+++ b/runtime/test/d3d12_present_test.cpp
@@ -265,8 +265,7 @@ int main() {
265 std::fprintf(stderr, "FAIL: cannot create the presentation window (Win32 error %lu)\n", GetLastError()); 265 std::fprintf(stderr, "FAIL: cannot create the presentation window (Win32 error %lu)\n", GetLastError());
266 return 1; 266 return 1;
267 } 267 }
268 ShowWindow(window, SW_SHOWNORMAL); 268 ShowWindow(window, SW_SHOWNOACTIVATE);
269 SetForegroundWindow(window);
270 UpdateWindow(window); 269 UpdateWindow(window);
271 pump(); 270 pump();
272 271
diff --git a/runtime/test/d3d12_private_data_test.cpp b/runtime/test/d3d12_private_data_test.cpp
index 4c1848a9c..8acacb049 100644
--- a/runtime/test/d3d12_private_data_test.cpp
+++ b/runtime/test/d3d12_private_data_test.cpp
@@ -51,7 +51,7 @@ public:
51 51
52// WKPDID_D3DDebugObjectName / ...NameW (d3dcommon.h), spelled out so nothing needs dxguid.lib. 52// WKPDID_D3DDebugObjectName / ...NameW (d3dcommon.h), spelled out so nothing needs dxguid.lib.
53constexpr GUID kName{0x429b8c22, 0x9188, 0x4b0c, {0x87, 0x42, 0xac, 0xb0, 0xbf, 0x85, 0xc2, 0x00}}; 53constexpr GUID kName{0x429b8c22, 0x9188, 0x4b0c, {0x87, 0x42, 0xac, 0xb0, 0xbf, 0x85, 0xc2, 0x00}};
54constexpr GUID kNameW{0x4cca5fd8, 0x921f, 0x42c8, {0x85, 0x99, 0xd2, 0x86, 0x6a, 0x3e, 0x5f, 0x7e}}; 54constexpr GUID kNameW{0x4cca5fd8, 0x921f, 0x42c8, {0x85, 0x66, 0x70, 0xca, 0xf2, 0xa9, 0xb7, 0x41}};
55 55
56// A key of its own for each step, so no step sees another's entry. 56// A key of its own for each step, so no step sees another's entry.
57GUID key(unsigned step) { return GUID{0x5eed0000u + step, 0x1d3d, 0x4c12, {0x9a, 0x41, 0x77, 0x10, 0x2b, 0x6c, 0x00, 0x01}}; } 57GUID key(unsigned step) { return GUID{0x5eed0000u + step, 0x1d3d, 0x4c12, {0x9a, 0x41, 0x77, 0x10, 0x2b, 0x6c, 0x00, 0x01}}; }
diff --git a/runtime/test/d3d12_query_rules_test.cpp b/runtime/test/d3d12_query_rules_test.cpp
index f50536b6f..6d51ab704 100644
--- a/runtime/test/d3d12_query_rules_test.cpp
+++ b/runtime/test/d3d12_query_rules_test.cpp
@@ -1,9 +1,10 @@
1// Query heaps and query calls on the Vulkan-backed device against Windows D3D12 (the default adapter and WARP): 1// Query heaps and query calls on the Vulkan-backed device against Windows D3D12 (the layer's own adapter and WARP):
2// CreateQueryHeap results by type, count and node mask, Close() results of lists that use queries on each list type, 2// CreateQueryHeap results by type, count and node mask, Close() results of lists that use queries on each list type,
3// and timestamps resolved on direct, compute and copy queues (pipeline statistics heaps are left out: the test 3// and timestamps resolved on direct, compute and copy queues (pipeline statistics heaps are left out: the test
4// device does not enable pipelineStatisticsQuery). No game data or shaders. Run explicitly (needs Vulkan 4// device does not enable pipelineStatisticsQuery). No game data or shaders. Run explicitly (needs Vulkan
5// hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage. 5// hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage.
6#include "vk_test_device.h" 6#include "vk_test_device.h"
7#include "host_adapter.h"
7#include "host_wine.h" 8#include "host_wine.h"
8#include "../shims/d3d12_com.h" 9#include "../shims/d3d12_com.h"
9#include <dxgi1_4.h> 10#include <dxgi1_4.h>
@@ -289,14 +290,15 @@ int main() {
289 if (hostwine::host_is_wine()) break; 290 if (hostwine::host_is_wine()) break;
290 Ref<IDXGIAdapter> adapter; 291 Ref<IDXGIAdapter> adapter;
291 Ref<ID3D12Device> host; 292 Ref<ID3D12Device> host;
292 if (warp && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue; 293 std::string adapter_name;
294 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue;
293 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; 295 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
294 const auto a = lines(mine), b = lines(all_cases(host.p)); 296 const auto a = lines(mine), b = lines(all_cases(host.p));
295 for (size_t i = 0; i < a.size() || i < b.size(); ++i) { 297 for (size_t i = 0; i < a.size() || i < b.size(); ++i) {
296 const std::string x = i < a.size() ? a[i] : "", y = i < b.size() ? b[i] : ""; 298 const std::string x = i < a.size() ? a[i] : "", y = i < b.size() ? b[i] : "";
297 if (x != y) { 299 if (x != y) {
298 ++differ; 300 ++differ;
299 std::printf("[%s] ours: %s | host: %s\n", warp ? "WARP" : "GPU", x.c_str(), y.c_str()); 301 std::printf("[%s] ours: %s | host: %s\n", adapter_name.c_str(), x.c_str(), y.c_str());
300 } else if (!warp) { 302 } else if (!warp) {
301 std::printf("same: %s\n", x.c_str()); 303 std::printf("same: %s\n", x.c_str());
302 } 304 }
diff --git a/runtime/test/d3d12_queue_handover_test.cpp b/runtime/test/d3d12_queue_handover_test.cpp
new file mode 100644
index 000000000..c445fdfe6
--- /dev/null
+++ b/runtime/test/d3d12_queue_handover_test.cpp
@@ -0,0 +1,577 @@
1// Cross-queue Wait-before-Signal with a texture and a buffer handed over (docs/d3d12_vulkan.md section 4.4).
2//
3// d3d12_queue_wait_test covers Wait-before-Signal with nothing handed over. Here the COPY, COMPUTE and DIRECT queues
4// pass a texture and a buffer around, and the consumer is submitted BEFORE the producer it waits for, in every order:
5// produce(queue a) upload buffer -> texture + buffer (CopyTextureRegion / CopyBufferRegion, COMMON -> COPY_DEST)
6// relay(queue b) texture + buffer -> second texture + buffer
7// consume(queue c) texture + buffer -> readback buffer
8// linked by fences (a signals f1, b waits f1 and signals f2, c waits f2 and signals f3, the CPU waits f3), for every
9// assignment of queue types to a, b and c (27, repeats on separate queues) and every one of the 6 orders the three
10// submissions can reach the queues in. Then: a consumer waiting for a texture from one queue and a buffer from another
11// (two waits), a chain released by a CPU Signal (the producer waits for a fence the CPU sets after everything is
12// submitted), a CPU Signal before the Wait, and two layer-only cases that must not hang: a fence nobody signals (the
13// other queues keep working, the held batch never runs, the queue is destroyed and the layer reports it), and a fence
14// released while a batch waits for it.
15//
16// The same cases run on the Vulkan layer and on the host D3D12 runtime (the adapter is named in the output). Results are
17// compared byte for byte with the data written by the CPU: a consumer replayed against the layout from before its
18// producer ran reads a zero-filled texture and fails here (and with LEONIDA_VK_VALIDATION=1 under sync validation).
19// No game data.
20#include "../shims/d3d12_com.h"
21
22#include <dxgi1_4.h>
23#include <io.h>
24#include <share.h>
25#include <sys/stat.h>
26#include <fcntl.h>
27#include <wrl/client.h>
28
29#include <algorithm>
30#include <array>
31#include <atomic>
32#include <cstdint>
33#include <cstdio>
34#include <cstdlib>
35#include <cstring>
36#include <functional>
37#include <string>
38#include <thread>
39#include <vector>
40
41using Microsoft::WRL::ComPtr;
42
43namespace {
44
45constexpr UINT dim = 16; // 16 x 16 RGBA8
46constexpr UINT pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT;
47constexpr UINT64 buffer_bytes = 1024;
48constexpr UINT64 texture_offset = 1024; // in the upload and readback buffers; a multiple of 512
49constexpr UINT64 staging_bytes = texture_offset + UINT64(dim) * pitch;
50
51// The watchdog: a stuck case ends the process with a message instead of a ctest timeout with none.
52std::atomic<ULONGLONG> deadline{0};
53std::atomic<const char*> current_case{"start"};
54void arm(const char* name, ULONGLONG ms = 20000) {
55 current_case = name;
56 deadline = GetTickCount64() + ms;
57}
58
59std::uint32_t pattern(std::uint32_t seed, std::uint32_t i) {
60 std::uint32_t x = seed * 0x9e3779b1u + i * 0x85ebca6bu + 0x1234567u;
61 x ^= x >> 15; x *= 0x2c1b3c6du; x ^= x >> 12; x *= 0x297a2d39u; x ^= x >> 15;
62 return x | 0x01000000u; // never zero, so a zero-filled or stale resource cannot match
63}
64
65enum Type { copy_q = 0, compute_q = 1, direct_q = 2 };
66constexpr const char* type_name[] = {"COPY", "COMPUTE", "DIRECT"};
67constexpr D3D12_COMMAND_LIST_TYPE list_type[] = {D3D12_COMMAND_LIST_TYPE_COPY, D3D12_COMMAND_LIST_TYPE_COMPUTE,
68 D3D12_COMMAND_LIST_TYPE_DIRECT};
69constexpr int pool_size = 3; // queues per type: distinct roles of one type need distinct queues
70
71struct Rig {
72 ID3D12Device* device = nullptr;
73 ComPtr<ID3D12CommandQueue> queues[3][pool_size];
74 int available[3] = {0, 0, 0};
75};
76
77D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) {
78 D3D12_RESOURCE_DESC desc{};
79 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
80 desc.Width = bytes;
81 desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1;
82 desc.SampleDesc.Count = 1;
83 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
84 return desc;
85}
86
87D3D12_RESOURCE_DESC texture_desc() {
88 D3D12_RESOURCE_DESC desc{};
89 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
90 desc.Width = desc.Height = dim;
91 desc.DepthOrArraySize = desc.MipLevels = 1;
92 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
93 desc.SampleDesc.Count = 1;
94 return desc;
95}
96
97D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before,
98 D3D12_RESOURCE_STATES after) {
99 D3D12_RESOURCE_BARRIER barrier{};
100 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
101 barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after};
102 return barrier;
103}
104
105struct Set {
106 ComPtr<ID3D12Resource> texture, buffer;
107};
108
109struct Case {
110 Rig& rig;
111 int seed;
112 ComPtr<ID3D12Resource> upload, readback;
113 Set stage[2]; // [0] written by the producer, [1] by the relay
114 std::vector<ComPtr<ID3D12CommandAllocator>> allocators;
115 std::vector<ComPtr<ID3D12GraphicsCommandList>> lists;
116 std::vector<ComPtr<ID3D12Fence>> fences;
117 bool ok = true;
118
119 explicit Case(Rig& r, int s) : rig(r), seed(s) {}
120
121 bool fail(const char* what, int line) {
122 std::fprintf(stderr, "case \"%s\" (seed %d): line %d: %s\n", current_case.load(), seed, line, what);
123 ok = false;
124 return false;
125 }
126#define CHECK(c) do { if (!(c)) return fail(#c, __LINE__); } while (0)
127
128 bool make_resources() {
129 ID3D12Device* d = rig.device;
130 D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, up{D3D12_HEAP_TYPE_UPLOAD}, rb{D3D12_HEAP_TYPE_READBACK};
131 const auto staging = buffer_desc(staging_bytes);
132 const auto buf = buffer_desc(buffer_bytes);
133 const auto tex = texture_desc();
134 CHECK(SUCCEEDED(d->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &staging,
135 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload))));
136 CHECK(SUCCEEDED(d->CreateCommittedResource(&rb, D3D12_HEAP_FLAG_NONE, &staging, D3D12_RESOURCE_STATE_COPY_DEST,
137 nullptr, IID_PPV_ARGS(&readback))));
138 for (auto& s : stage) {
139 CHECK(SUCCEEDED(d->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_COMMON,
140 nullptr, IID_PPV_ARGS(&s.texture))));
141 CHECK(SUCCEEDED(d->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COMMON,
142 nullptr, IID_PPV_ARGS(&s.buffer))));
143 }
144 std::uint8_t* mapped = nullptr;
145 const D3D12_RANGE none{0, 0};
146 CHECK(SUCCEEDED(upload->Map(0, &none, reinterpret_cast<void**>(&mapped))));
147 for (UINT64 i = 0; i < buffer_bytes / 4; ++i)
148 reinterpret_cast<std::uint32_t*>(mapped)[i] = pattern(seed, std::uint32_t(i));
149 for (UINT y = 0; y < dim; ++y)
150 for (UINT x = 0; x < dim; ++x)
151 reinterpret_cast<std::uint32_t*>(mapped + texture_offset + y * pitch)[x] =
152 pattern(seed + 7919, y * dim + x);
153 upload->Unmap(0, nullptr);
154 return true;
155 }
156
157 ID3D12Fence* fence(int i) {
158 while (int(fences.size()) <= i) {
159 ComPtr<ID3D12Fence> f;
160 if (FAILED(rig.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&f)))) return nullptr;
161 fences.push_back(f);
162 }
163 return fences[i].Get();
164 }
165
166 static D3D12_TEXTURE_COPY_LOCATION footprint(ID3D12Resource* resource) {
167 D3D12_TEXTURE_COPY_LOCATION loc{};
168 loc.pResource = resource;
169 loc.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
170 loc.PlacedFootprint = {texture_offset, {DXGI_FORMAT_R8G8B8A8_UNORM, dim, dim, 1, pitch}};
171 return loc;
172 }
173 static D3D12_TEXTURE_COPY_LOCATION subresource(ID3D12Resource* resource) {
174 D3D12_TEXTURE_COPY_LOCATION loc{};
175 loc.pResource = resource;
176 loc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
177 return loc;
178 }
179
180 // A closed list of `type`: moves `src` (null: the upload buffer) to `dst` (null: the readback buffer), the parts in
181 // `mask` (1 texture, 2 buffer), with COMMON -> COPY_SOURCE / COPY_DEST before and COMMON again after.
182 ID3D12GraphicsCommandList* make_list(Type type, const Set* src, const Set* dst, int mask) {
183 ComPtr<ID3D12CommandAllocator> alloc;
184 ComPtr<ID3D12GraphicsCommandList> list;
185 if (FAILED(rig.device->CreateCommandAllocator(list_type[type], IID_PPV_ARGS(&alloc))) ||
186 FAILED(rig.device->CreateCommandList(0, list_type[type], alloc.Get(), nullptr, IID_PPV_ARGS(&list))))
187 return nullptr;
188 std::vector<D3D12_RESOURCE_BARRIER> before, after;
189 const auto track = [&](ID3D12Resource* r, D3D12_RESOURCE_STATES state) {
190 before.push_back(transition(r, D3D12_RESOURCE_STATE_COMMON, state));
191 after.push_back(transition(r, state, D3D12_RESOURCE_STATE_COMMON));
192 };
193 if (src) {
194 if (mask & 1) track(src->texture.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE);
195 if (mask & 2) track(src->buffer.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE);
196 }
197 if (dst) {
198 if (mask & 1) track(dst->texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST);
199 if (mask & 2) track(dst->buffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST);
200 }
201 if (!before.empty()) list->ResourceBarrier(UINT(before.size()), before.data());
202 if (mask & 2)
203 list->CopyBufferRegion(dst ? dst->buffer.Get() : readback.Get(), 0,
204 src ? src->buffer.Get() : upload.Get(), 0, buffer_bytes);
205 if (mask & 1) {
206 const auto to = dst ? subresource(dst->texture.Get()) : footprint(readback.Get());
207 const auto from = src ? subresource(src->texture.Get()) : footprint(upload.Get());
208 list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
209 }
210 if (!after.empty()) list->ResourceBarrier(UINT(after.size()), after.data());
211 if (FAILED(list->Close())) return nullptr;
212 allocators.push_back(alloc);
213 lists.push_back(list);
214 return list.Get();
215 }
216
217 // One submission, in the order the call reaches the queue: Wait(s), the list, Signal.
218 struct Job {
219 Type type;
220 int slot; // which queue of the type
221 const Set* src;
222 const Set* dst;
223 int mask;
224 std::vector<std::pair<int, UINT64>> waits; // (fence, value)
225 int signal = -1; // fence signaled with 1; -1: none
226 };
227
228 bool submit(const Job& job) {
229 ID3D12CommandQueue* queue = rig.queues[job.type][job.slot].Get();
230 ID3D12GraphicsCommandList* list = make_list(job.type, job.src, job.dst, job.mask);
231 CHECK(queue && list);
232 for (const auto& [f, v] : job.waits) {
233 ID3D12Fence* fe = fence(f);
234 CHECK(fe && SUCCEEDED(queue->Wait(fe, v)));
235 }
236 ID3D12CommandList* batch[] = {list};
237 queue->ExecuteCommandLists(1, batch);
238 if (job.signal >= 0) {
239 ID3D12Fence* fe = fence(job.signal);
240 CHECK(fe && SUCCEEDED(queue->Signal(fe, 1)));
241 }
242 return true;
243 }
244
245 bool wait_fence(int f, UINT64 value) {
246 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
247 ID3D12Fence* fe = fence(f);
248 CHECK(event && fe && SUCCEEDED(fe->SetEventOnCompletion(value, event)));
249 if (WaitForSingleObject(event, 15000) != WAIT_OBJECT_0) {
250 // A stuck queue can keep the destructors blocked: end the process without cleaning up.
251 std::fprintf(stderr, "case \"%s\" (seed %d): fence %d never reached %llu (completed %llu)\n",
252 current_case.load(), seed, f, static_cast<unsigned long long>(value),
253 static_cast<unsigned long long>(fe->GetCompletedValue()));
254 std::fflush(stderr);
255 std::_Exit(1);
256 }
257 CloseHandle(event);
258 return true;
259 }
260
261 // Compares the readback buffer with what the upload buffer held.
262 bool verify() {
263 std::uint8_t* mapped = nullptr;
264 CHECK(SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast<void**>(&mapped))));
265 unsigned bad = 0;
266 for (UINT64 i = 0; i < buffer_bytes / 4; ++i) {
267 const auto got = reinterpret_cast<const std::uint32_t*>(mapped)[i];
268 if (got != pattern(seed, std::uint32_t(i)) && bad++ < 3)
269 std::fprintf(stderr, "buffer word %llu: got %08x want %08x\n", static_cast<unsigned long long>(i), got,
270 pattern(seed, std::uint32_t(i)));
271 }
272 for (UINT y = 0; y < dim; ++y)
273 for (UINT x = 0; x < dim; ++x) {
274 const auto got = reinterpret_cast<const std::uint32_t*>(mapped + texture_offset + y * pitch)[x];
275 if (got != pattern(seed + 7919, y * dim + x) && bad++ < 3)
276 std::fprintf(stderr, "texel (%u,%u): got %08x want %08x\n", x, y, got,
277 pattern(seed + 7919, y * dim + x));
278 }
279 readback->Unmap(0, nullptr);
280 if (bad) std::fprintf(stderr, "%u words differ\n", bad);
281 return bad == 0 ? true : fail("result differs from the data the CPU wrote", __LINE__);
282 }
283};
284
285// A queue slot per role: the n-th role of a type uses the n-th queue of the type.
286struct Roles {
287 Type type[3];
288 int slot[3];
289 bool fits(const Rig& rig) const {
290 for (int r = 0; r < 3; ++r)
291 if (slot[r] >= rig.available[type[r]]) return false;
292 return true;
293 }
294 static Roles make(Type a, Type b, Type c) {
295 Roles roles{{a, b, c}, {0, 0, 0}};
296 for (int r = 0; r < 3; ++r)
297 for (int p = 0; p < r; ++p)
298 if (roles.type[p] == roles.type[r]) ++roles.slot[r];
299 return roles;
300 }
301};
302
303int cases_run = 0;
304
305// Chain a -> b -> c, with the three submissions in `order` (a permutation of 0 = produce, 1 = relay, 2 = consume).
306bool chain(Rig& rig, const Roles& roles, const std::array<int, 3>& order, int seed) {
307 std::string name = std::string("chain ") + type_name[roles.type[0]] + "->" + type_name[roles.type[1]] + "->" +
308 type_name[roles.type[2]] + " submitted " + char('A' + order[0]) + char('A' + order[1]) +
309 char('A' + order[2]);
310 arm(name.c_str());
311 Case c(rig, seed);
312 if (!c.make_resources()) return false;
313 const Case::Job jobs[3] = {
314 {roles.type[0], roles.slot[0], nullptr, &c.stage[0], 3, {}, 0},
315 {roles.type[1], roles.slot[1], &c.stage[0], &c.stage[1], 3, {{0, 1}}, 1},
316 {roles.type[2], roles.slot[2], &c.stage[1], nullptr, 3, {{1, 1}}, 2},
317 };
318 for (int i : order)
319 if (!c.submit(jobs[i])) return false;
320 ++cases_run;
321 return c.wait_fence(2, 1) && c.verify();
322}
323
324// The consumer waits for the texture from one queue and the buffer from another.
325bool two_producers(Rig& rig, Type a, Type b, Type consumer, const std::array<int, 3>& order, int seed) {
326 const int sa = 0, sb = a == b ? 1 : 0, sc = (consumer == a) + (consumer == b);
327 if (sa >= rig.available[a] || sb >= rig.available[b] || sc >= rig.available[consumer]) return true;
328 std::string name = std::string("two producers ") + type_name[a] + "(texture)+" + type_name[b] + "(buffer)->" +
329 type_name[consumer] + " submitted " + char('A' + order[0]) + char('A' + order[1]) +
330 char('A' + order[2]);
331 arm(name.c_str());
332 Case c(rig, seed);
333 if (!c.make_resources()) return false;
334 const Case::Job jobs[3] = {
335 {a, sa, nullptr, &c.stage[0], 1, {}, 0},
336 {b, sb, nullptr, &c.stage[0], 2, {}, 1},
337 {consumer, sc, &c.stage[0], nullptr, 3, {{0, 1}, {1, 1}}, 2},
338 };
339 for (int i : order)
340 if (!c.submit(jobs[i])) return false;
341 ++cases_run;
342 return c.wait_fence(2, 1) && c.verify();
343}
344
345// The whole chain is submitted consumer first and the producer waits for a fence the CPU signals last.
346bool cpu_released_chain(Rig& rig, const Roles& roles, int seed) {
347 std::string name = std::string("CPU Signal releases chain ") + type_name[roles.type[0]] + "->" +
348 type_name[roles.type[1]] + "->" + type_name[roles.type[2]];
349 arm(name.c_str());
350 Case c(rig, seed);
351 if (!c.make_resources()) return false;
352 const Case::Job jobs[3] = {
353 {roles.type[0], roles.slot[0], nullptr, &c.stage[0], 3, {{3, 1}}, 0},
354 {roles.type[1], roles.slot[1], &c.stage[0], &c.stage[1], 3, {{0, 1}}, 1},
355 {roles.type[2], roles.slot[2], &c.stage[1], nullptr, 3, {{1, 1}}, 2},
356 };
357 if (!c.submit(jobs[2]) || !c.submit(jobs[1]) || !c.submit(jobs[0])) return false;
358 Sleep(20);
359 if (c.fence(2)->GetCompletedValue() != 0) return c.fail("the chain ran before the CPU signaled its gate", __LINE__);
360 if (FAILED(c.fence(3)->Signal(1))) return c.fail("CPU Signal failed", __LINE__);
361 ++cases_run;
362 return c.wait_fence(2, 1) && c.verify();
363}
364
365// A CPU Signal that comes before the Wait (nothing is held), and one that comes after the batch was submitted.
366bool cpu_gate(Rig& rig, Type producer, Type consumer, bool signal_first, int seed) {
367 if (producer == consumer && rig.available[producer] < 2) return true;
368 const int cslot = producer == consumer ? 1 : 0;
369 std::string name = std::string("CPU Signal ") + (signal_first ? "before" : "after") + " the consumer's Wait, " +
370 type_name[producer] + "->" + type_name[consumer];
371 arm(name.c_str());
372 Case c(rig, seed);
373 if (!c.make_resources()) return false;
374 if (!c.submit({producer, 0, nullptr, &c.stage[0], 3, {}, 0}) || !c.wait_fence(0, 1)) return false;
375 if (signal_first && FAILED(c.fence(1)->Signal(1))) return c.fail("CPU Signal failed", __LINE__);
376 if (!c.submit({consumer, cslot, &c.stage[0], nullptr, 3, {{1, 1}}, 2})) return false;
377 if (!signal_first) {
378 Sleep(20);
379 if (c.fence(2)->GetCompletedValue() != 0) return c.fail("the consumer ran before the CPU Signal", __LINE__);
380 if (FAILED(c.fence(1)->Signal(1))) return c.fail("CPU Signal failed", __LINE__);
381 }
382 ++cases_run;
383 return c.wait_fence(2, 1) && c.verify();
384}
385
386// Runs `body` with stderr redirected to a file and returns what it wrote.
387std::string capture_stderr(const std::function<void()>& body) {
388 char dir[MAX_PATH], path[MAX_PATH];
389 GetTempPathA(MAX_PATH, dir);
390 GetTempFileNameA(dir, "qho", 0, path);
391 std::fflush(stderr);
392 const int saved = _dup(2);
393 int file = -1;
394 _sopen_s(&file, path, _O_RDWR | _O_CREAT | _O_TRUNC | _O_BINARY, _SH_DENYNO, _S_IREAD | _S_IWRITE);
395 _dup2(file, 2);
396 body();
397 std::fflush(stderr);
398 _dup2(saved, 2);
399 _close(saved);
400 _close(file);
401 std::string text;
402 FILE* f = nullptr;
403 if (fopen_s(&f, path, "rb") == 0 && f) {
404 char buffer[512];
405 std::size_t n;
406 while ((n = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, n);
407 std::fclose(f);
408 }
409 std::remove(path);
410 return text;
411}
412
413// A batch waits for a fence nobody signals. The other queues keep working, the batch never runs, destroying the queue
414// does not hang and the layer says why. Layer only: the host runtime has nothing to report.
415bool never_signaled(Rig& rig, int seed) {
416 arm("fence nobody signals");
417 Case c(rig, seed);
418 if (!c.make_resources()) return false;
419 ComPtr<ID3D12CommandQueue> victim;
420 const D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT};
421 if (FAILED(rig.device->CreateCommandQueue(&desc, IID_PPV_ARGS(&victim)))) {
422 std::puts("never-signaled case: no spare queue, skipped");
423 return true;
424 }
425 // The victim's batch would overwrite stage[1]; the working chain below uses stage[0] and the readback buffer.
426 ID3D12Fence* gate = c.fence(5);
427 ID3D12GraphicsCommandList* held = c.make_list(direct_q, nullptr, &c.stage[1], 3);
428 if (!gate || !held) return c.fail("setup", __LINE__);
429 ID3D12CommandList* batch[] = {held};
430 if (FAILED(victim->Wait(gate, 5))) return c.fail("Wait", __LINE__);
431 victim->ExecuteCommandLists(1, batch);
432 if (FAILED(victim->Signal(c.fence(6), 1))) return c.fail("Signal", __LINE__);
433 // Other queues are not held up behind it.
434 const Case::Job work[2] = {{copy_q, 0, nullptr, &c.stage[0], 3, {}, 0},
435 {direct_q, 0, &c.stage[0], nullptr, 3, {{0, 1}}, 2}};
436 if (!c.submit(work[1]) || !c.submit(work[0]) || !c.wait_fence(2, 1) || !c.verify()) return false;
437 Sleep(100);
438 if (c.fence(6)->GetCompletedValue() != 0) return c.fail("the held batch's Signal was reached", __LINE__);
439 arm("destroy a queue with a held batch");
440 const std::string log = capture_stderr([&] { victim.Reset(); });
441 if (log.find("queue destroyed with") == std::string::npos || log.find("never signaled") == std::string::npos) {
442 std::fprintf(stderr, "the layer did not report the held batch; stderr was: \"%s\"\n", log.c_str());
443 return c.fail("no report for the held batch", __LINE__);
444 }
445 std::printf("never-signaled fence: held, others unaffected, destroyed without a hang; layer says: %s",
446 log.c_str());
447 ++cases_run;
448 return true;
449}
450
451// The fence a batch waits for is released: the batch is dropped and reported, nothing hangs.
452bool fence_released(Rig& rig, int seed) {
453 arm("fence released while a batch waits");
454 Case c(rig, seed);
455 if (!c.make_resources()) return false;
456 ComPtr<ID3D12CommandQueue> victim;
457 const D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT};
458 if (FAILED(rig.device->CreateCommandQueue(&desc, IID_PPV_ARGS(&victim)))) return true;
459 ComPtr<ID3D12Fence> doomed;
460 if (FAILED(rig.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&doomed)))) return false;
461 ID3D12GraphicsCommandList* held = c.make_list(direct_q, nullptr, &c.stage[1], 3);
462 if (!held) return c.fail("setup", __LINE__);
463 ID3D12CommandList* batch[] = {held};
464 if (FAILED(victim->Wait(doomed.Get(), 9))) return c.fail("Wait", __LINE__);
465 victim->ExecuteCommandLists(1, batch);
466 const std::string log = capture_stderr([&] { doomed.Reset(); victim.Reset(); });
467 if (log.find("fence was released while a queue still held work") == std::string::npos) {
468 std::fprintf(stderr, "stderr was: \"%s\"\n", log.c_str());
469 return c.fail("no report for the dropped batch", __LINE__);
470 }
471 ++cases_run;
472 return true;
473}
474
475bool run_all(ID3D12Device* device, bool layer) {
476 Rig rig;
477 rig.device = device;
478 for (int t = 0; t < 3; ++t)
479 for (int i = 0; i < pool_size; ++i) {
480 D3D12_COMMAND_QUEUE_DESC desc{};
481 desc.Type = list_type[t];
482 if (FAILED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&rig.queues[t][i])))) break;
483 ++rig.available[t];
484 }
485 std::printf("queues available per type (COPY/COMPUTE/DIRECT): %d/%d/%d\n", rig.available[0], rig.available[1],
486 rig.available[2]);
487 if (!rig.available[0] || !rig.available[1] || !rig.available[2]) return true; // nothing to hand over between
488
489 bool ok = true;
490 int seed = 100, skipped = 0;
491 std::array<int, 3> order{0, 1, 2};
492 for (int a = 0; a < 3; ++a)
493 for (int b = 0; b < 3; ++b)
494 for (int cc = 0; cc < 3; ++cc) {
495 const Roles roles = Roles::make(Type(a), Type(b), Type(cc));
496 if (!roles.fits(rig)) { ++skipped; continue; }
497 order = {0, 1, 2};
498 do {
499 ok &= chain(rig, roles, order, ++seed);
500 } while (std::next_permutation(order.begin(), order.end()));
501 ok &= cpu_released_chain(rig, roles, ++seed);
502 }
503 for (int a = 0; a < 3; ++a)
504 for (int b = 0; b < 3; ++b)
505 for (int cc = 0; cc < 3; ++cc) {
506 order = {0, 1, 2};
507 do {
508 ok &= two_producers(rig, Type(a), Type(b), Type(cc), order, ++seed);
509 } while (std::next_permutation(order.begin(), order.end()));
510 }
511 for (int p = 0; p < 3; ++p)
512 for (int q = 0; q < 3; ++q)
513 for (bool first : {true, false}) ok &= cpu_gate(rig, Type(p), Type(q), first, ++seed);
514 if (layer) {
515 // The layer hands out a limited number of VkQueues: give the spare ones back for the two cases below.
516 for (auto& type_queues : rig.queues)
517 for (int i = 1; i < pool_size; ++i) type_queues[i].Reset();
518 ok &= never_signaled(rig, ++seed);
519 ok &= fence_released(rig, ++seed);
520 }
521 if (skipped) std::printf("(%d type assignments need more queues than the device gave)\n", skipped);
522 return ok;
523}
524
525ComPtr<ID3D12Device> native_device(std::wstring& name) {
526 ComPtr<IDXGIFactory4> factory;
527 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {};
528 for (UINT i = 0;; ++i) {
529 ComPtr<IDXGIAdapter1> adapter;
530 if (factory->EnumAdapters1(i, &adapter) != S_OK) return {};
531 DXGI_ADAPTER_DESC1 desc{};
532 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue;
533 ComPtr<ID3D12Device> device;
534 if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue;
535 name = desc.Description;
536 return device;
537 }
538}
539
540} // namespace
541
542int main() {
543 std::thread([] {
544 for (;;) {
545 Sleep(100);
546 const ULONGLONG limit = deadline.load();
547 if (limit && GetTickCount64() > limit) {
548 std::fprintf(stderr, "HANG in case \"%s\"\n", current_case.load());
549 std::fflush(stderr);
550 std::_Exit(1);
551 }
552 }
553 }).detach();
554
555 ComPtr<ID3D12Device> layer;
556 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&layer)))) {
557 std::puts("Vulkan standalone device unavailable");
558 return 77;
559 }
560 arm("Vulkan layer", 300000);
561 cases_run = 0;
562 if (!run_all(layer.Get(), true)) return 1;
563 const int layer_cases = cases_run;
564 std::printf("Vulkan layer: %d cases passed, every one exact\n", layer_cases);
565
566 std::wstring name;
567 if (auto host = native_device(name)) {
568 arm("host runtime", 300000);
569 cases_run = 0;
570 if (!run_all(host.Get(), false)) return 1;
571 std::printf("Host D3D12 (%ls): %d cases passed, every one exact\n", name.c_str(), cases_run);
572 } else {
573 std::puts("no host D3D12 adapter: the host comparison was skipped");
574 }
575 deadline = 0;
576 return 0;
577}
diff --git a/runtime/test/d3d12_resource_desc_test.cpp b/runtime/test/d3d12_resource_desc_test.cpp
index 3d04fe099..863abf479 100644
--- a/runtime/test/d3d12_resource_desc_test.cpp
+++ b/runtime/test/d3d12_resource_desc_test.cpp
@@ -1,7 +1,8 @@
1// Compare ID3D12Resource::GetDesc on the Vulkan-backed device with Windows D3D12 (the default adapter and WARP): 1// Compare ID3D12Resource::GetDesc on the Vulkan-backed device with Windows D3D12 (the layer's own adapter and WARP):
2// what a description that leaves fields at their defaults (Alignment 0, MipLevels 0) reads back as. 2// what a description that leaves fields at their defaults (Alignment 0, MipLevels 0) reads back as.
3// No game data or shaders. Run explicitly (needs Vulkan hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage. 3// No game data or shaders. Run explicitly (needs Vulkan hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage.
4#include "vk_test_device.h" 4#include "vk_test_device.h"
5#include "host_adapter.h"
5#include "host_wine.h" 6#include "host_wine.h"
6#include "../shims/d3d12_com.h" 7#include "../shims/d3d12_com.h"
7#include <dxgi1_4.h> 8#include <dxgi1_4.h>
@@ -183,9 +184,10 @@ int main() {
183 for (const bool warp : {false, true}) { 184 for (const bool warp : {false, true}) {
184 Ref<IDXGIAdapter> adapter; 185 Ref<IDXGIAdapter> adapter;
185 Ref<ID3D12Device> host; 186 Ref<ID3D12Device> host;
186 if (warp && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue; 187 std::string adapter_name;
188 if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue;
187 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; 189 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
188 const char* name = warp ? "WARP" : "the default adapter"; 190 const char* name = adapter_name.c_str();
189 const Totals totals = compare(ours.p, host.p, name, cases); 191 const Totals totals = compare(ours.p, host.p, name, cases);
190 std::printf("resource desc against %s: %u of %zu descriptions match, %u differ, %u refused by the host, " 192 std::printf("resource desc against %s: %u of %zu descriptions match, %u differ, %u refused by the host, "
191 "%u not created by the layer\n", 193 "%u not created by the layer\n",
@@ -196,7 +198,7 @@ int main() {
196 } 198 }
197 } 199 }
198 if (!references) { 200 if (!references) {
199 std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n"); 201 std::fprintf(stderr, "no D3D12 reference device (hardware adapter or WARP)\n");
200 return 1; 202 return 1;
201 } 203 }
202 if (mismatched || !matched) return 1; 204 if (mismatched || !matched) return 1;
diff --git a/runtime/test/d3d12_rgb96_test.cpp b/runtime/test/d3d12_rgb96_test.cpp
index c54025c94..2b93948d8 100644
--- a/runtime/test/d3d12_rgb96_test.cpp
+++ b/runtime/test/d3d12_rgb96_test.cpp
@@ -160,6 +160,33 @@ struct Footprints {
160 } 160 }
161}; 161};
162 162
163bool host_reports_no_tiling(ID3D12Device* device, const char* device_name, DXGI_FORMAT format) {
164 const D3D12_RESOURCE_DESC desc = texture_desc(format, false, 256, 256, 1, 1);
165 const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT};
166 Ref<ID3D12Resource> resource;
167 const HRESULT created = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc,
168 D3D12_RESOURCE_STATE_COMMON, nullptr,
169 IID_PPV_ARGS(&resource.p));
170 CHECK(SUCCEEDED(created));
171 UINT total = 0xdeadbeefu, count = 1;
172 D3D12_PACKED_MIP_INFO packed{0xdeu, 0xadu, 0xdeadbeefu, 0xdeadbeefu};
173 D3D12_TILE_SHAPE shape{0xdeadbeefu, 0xdeadbeefu, 0xdeadbeefu};
174 const D3D12_SUBRESOURCE_TILING untouched{0xdeadbeefu, 0xbeefu, 0xbeefu, 0xdeadbeefu};
175 D3D12_SUBRESOURCE_TILING subresource = untouched;
176 device->GetResourceTiling(resource.p, &total, &packed, &shape, &count, 0, &subresource);
177 if (total || shape.WidthInTexels || shape.HeightInTexels || shape.DepthInTexels ||
178 packed.NumStandardMips || packed.NumPackedMips || packed.NumTilesForPackedMips ||
179 packed.StartTileIndexInOverallResource || count ||
180 std::memcmp(&subresource, &untouched, sizeof(subresource)) != 0) {
181 std::fprintf(stderr, "%s format %d: unexpected tiling: total %u, shape %ux%ux%u, packed %u/%u/%u/%u, "
182 "subresources %u\n", device_name, int(format), total, shape.WidthInTexels,
183 shape.HeightInTexels, shape.DepthInTexels, packed.NumStandardMips, packed.NumPackedMips,
184 packed.NumTilesForPackedMips, packed.StartTileIndexInOverallResource, count);
185 return false;
186 }
187 return true;
188}
189
163// What the copies below leave in the second texture, and in the box read back from it: three words a texel. 190// What the copies below leave in the second texture, and in the box read back from it: three words a texel.
164struct Texels { 191struct Texels {
165 std::vector<std::vector<std::uint32_t>> subresources; 192 std::vector<std::vector<std::uint32_t>> subresources;
@@ -552,10 +579,15 @@ int main() {
552 std::fprintf(stderr, "WARP reference unavailable\n"); 579 std::fprintf(stderr, "WARP reference unavailable\n");
553 return 77; // Wine: ctest skips 580 return 77; // Wine: ctest skips
554 } 581 }
582 Ref<ID3D12Device> hardware;
583 if (FAILED(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&hardware.p)))) return 77;
555 584
556 constexpr DXGI_FORMAT formats[] = {DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32_UINT, 585 constexpr DXGI_FORMAT formats[] = {DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32_UINT,
557 DXGI_FORMAT_R32G32B32_SINT, DXGI_FORMAT_R32G32B32_TYPELESS}; 586 DXGI_FORMAT_R32G32B32_SINT, DXGI_FORMAT_R32G32B32_TYPELESS};
558 for (const DXGI_FORMAT format : formats) { 587 for (const DXGI_FORMAT format : formats) {
588 if (!host_reports_no_tiling(hardware.p, "hardware", format) ||
589 !host_reports_no_tiling(host.p, "WARP", format))
590 return 1;
559 for (const bool volume : {false, true}) { 591 for (const bool volume : {false, true}) {
560 const Shape shape{format, volume}; 592 const Shape shape{format, volume};
561 Footprints ours_footprints, host_footprints; 593 Footprints ours_footprints, host_footprints;
@@ -645,7 +677,8 @@ int main() {
645 } 677 }
646 } 678 }
647 if (vk.validation_errors()) return 1; 679 if (vk.validation_errors()) return 1;
648 std::printf("rgb96: %u texture shapes matched WARP and the expected texels bit for bit; CPU copies with%s\n", 680 std::printf("rgb96: %u texture shapes matched WARP and the expected texels bit for bit; CPU copies with%s; "
681 "the hardware adapter and WARP report no tiling for all four formats\n",
649 compared, vk.host_image_copy ? " and without host image copies on the device" : "out host image copies"); 682 compared, vk.host_image_copy ? " and without host image copies on the device" : "out host image copies");
650 return 0; 683 return 0;
651} 684}
diff --git a/runtime/test/d3d12_set0_compute_test.cpp b/runtime/test/d3d12_set0_compute_test.cpp
index 0b0646593..455f56b76 100644
--- a/runtime/test/d3d12_set0_compute_test.cpp
+++ b/runtime/test/d3d12_set0_compute_test.cpp
@@ -99,6 +99,11 @@ int main() {
99 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), 99 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
100 reinterpret_cast<void**>(&device.p)))); 100 reinterpret_cast<void**>(&device.p))));
101 rt::d3d12::set_device_outer(inner, device.p); 101 rt::d3d12::set_device_outer(inner, device.p);
102 if (rt::d3d12::device_push_constants_need_fallback(inner)) {
103 std::printf("d3d12_set0_compute_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n",
104 rt::d3d12::device_max_push_constants_size(inner));
105 return 77;
106 }
102 EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); 107 EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE);
103 108
104 // Root signature: [0] two constants (s0: the view slot's offset in dwords, s1: the first output element), 109 // Root signature: [0] two constants (s0: the view slot's offset in dwords, s1: the first output element),
diff --git a/runtime/test/d3d12_shader_cache_test.cpp b/runtime/test/d3d12_shader_cache_test.cpp
index 94b0aa5b9..8f6a68288 100644
--- a/runtime/test/d3d12_shader_cache_test.cpp
+++ b/runtime/test/d3d12_shader_cache_test.cpp
@@ -11,6 +11,7 @@
11#include <cstdio> 11#include <cstdio>
12#include <cstring> 12#include <cstring>
13#include <filesystem> 13#include <filesystem>
14#include <fstream>
14#include <vector> 15#include <vector>
15 16
16#define EXPECT(condition) do { \ 17#define EXPECT(condition) do { \
@@ -27,7 +28,7 @@ struct Ref {
27 T* operator->() const { return p; } 28 T* operator->() const { return p; }
28}; 29};
29 30
30int exercise_shader_cache(ID3D12Device9* dev, const char* label) { 31int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_in_params) {
31 // {7c83f2a1-4b5e-4d19-9a32-1f2e3d4c5b6a} 32 // {7c83f2a1-4b5e-4d19-9a32-1f2e3d4c5b6a}
32 const GUID id1 = {0x7c83f2a1, 0x4b5e, 0x4d19, {0x9a, 0x32, 0x1f, 0x2e, 0x3d, 0x4c, 0x5b, 0x6a}}; 33 const GUID id1 = {0x7c83f2a1, 0x4b5e, 0x4d19, {0x9a, 0x32, 0x1f, 0x2e, 0x3d, 0x4c, 0x5b, 0x6a}};
33 const GUID id2 = {0x1b74e9d0, 0x2c3a, 0x4f81, {0x8e, 0x11, 0x5a, 0x6b, 0x7c, 0x8d, 0x9e, 0x0f}}; 34 const GUID id2 = {0x1b74e9d0, 0x2c3a, 0x4f81, {0x8e, 0x11, 0x5a, 0x6b, 0x7c, 0x8d, 0x9e, 0x0f}};
@@ -40,7 +41,12 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label) {
40 desc.Version = 1; 41 desc.Version = 1;
41 42
42 // 1. CreateShaderCacheSession argument validation & capability check (null output -> S_FALSE). 43 // 1. CreateShaderCacheSession argument validation & capability check (null output -> S_FALSE).
43 EXPECT(dev->CreateShaderCacheSession(nullptr, __uuidof(ID3D12ShaderCacheSession), nullptr) == E_INVALIDARG); 44 // Passing nullptr for SAL _In_/_Inout_ parameters (pDesc, pKey, pValue, pValueSize) is undefined
45 // behaviour on older in-box Windows D3D12 runtimes (e.g. Win11 23H2 22621.5415 AVs), so those
46 // null-pointer guards are exercised only on the Vulkan layer.
47 if (test_null_in_params) {
48 EXPECT(dev->CreateShaderCacheSession(nullptr, __uuidof(ID3D12ShaderCacheSession), nullptr) == E_INVALIDARG);
49 }
44 EXPECT(dev->CreateShaderCacheSession(&desc, __uuidof(ID3D12ShaderCacheSession), nullptr) == S_FALSE); 50 EXPECT(dev->CreateShaderCacheSession(&desc, __uuidof(ID3D12ShaderCacheSession), nullptr) == S_FALSE);
45 51
46 D3D12_SHADER_CACHE_SESSION_DESC bad = desc; 52 D3D12_SHADER_CACHE_SESSION_DESC bad = desc;
@@ -75,13 +81,18 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label) {
75 UINT sz = sizeof(out_v); 81 UINT sz = sizeof(out_v);
76 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND); 82 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND);
77 EXPECT(sz == sizeof(out_v)); 83 EXPECT(sz == sizeof(out_v));
78 EXPECT(s1->FindValue(nullptr, sizeof(k1), &out_v, &sz) == E_INVALIDARG); 84 if (test_null_in_params) {
85 EXPECT(s1->FindValue(nullptr, sizeof(k1), &out_v, &sz) == E_INVALIDARG);
86 }
79 EXPECT(s1->FindValue(&k1, 0, &out_v, &sz) == E_INVALIDARG); 87 EXPECT(s1->FindValue(&k1, 0, &out_v, &sz) == E_INVALIDARG);
80 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, nullptr) == E_INVALIDARG); 88 if (test_null_in_params) {
81 89 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, nullptr) == E_INVALIDARG);
82 EXPECT(s1->StoreValue(nullptr, sizeof(k1), &v1, sizeof(v1)) == E_INVALIDARG); 90 EXPECT(s1->StoreValue(nullptr, sizeof(k1), &v1, sizeof(v1)) == E_INVALIDARG);
91 }
83 EXPECT(s1->StoreValue(&k1, 0, &v1, sizeof(v1)) == E_INVALIDARG); 92 EXPECT(s1->StoreValue(&k1, 0, &v1, sizeof(v1)) == E_INVALIDARG);
84 EXPECT(s1->StoreValue(&k1, sizeof(k1), nullptr, sizeof(v1)) == E_INVALIDARG); 93 if (test_null_in_params) {
94 EXPECT(s1->StoreValue(&k1, sizeof(k1), nullptr, sizeof(v1)) == E_INVALIDARG);
95 }
85 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, 0) == E_INVALIDARG); 96 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, 0) == E_INVALIDARG);
86 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, sizeof(v1)) == S_OK); 97 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, sizeof(v1)) == S_OK);
87 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, sizeof(v1)) == DXGI_ERROR_ALREADY_EXISTS); 98 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, sizeof(v1)) == DXGI_ERROR_ALREADY_EXISTS);
@@ -150,6 +161,7 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label) {
150} // namespace 161} // namespace
151 162
152int main() { 163int main() {
164 std::setvbuf(stdout, nullptr, _IONBF, 0);
153 vktest::Device d; 165 vktest::Device d;
154 const auto status = d.initialize(); 166 const auto status = d.initialize();
155 if (status == vktest::DeviceStatus::unavailable) { 167 if (status == vktest::DeviceStatus::unavailable) {
@@ -169,14 +181,16 @@ int main() {
169 181
170 Ref<ID3D12Device9> device; 182 Ref<ID3D12Device9> device;
171 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); 183 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
172 EXPECT(exercise_shader_cache(device.p, "Vulkan layer") == 0); 184 EXPECT(exercise_shader_cache(device.p, "Vulkan layer", true) == 0);
173 185
174 // Layer-specific ShaderCacheControl CLEAR / DISABLE / ENABLE and entry/byte limit checks. 186 // Layer-specific ShaderCacheControl CLEAR / DISABLE / ENABLE, default limits, DXGI_ERROR_CACHE_FULL,
187 // version-mismatch handling, MEMORY teardown discard, and malformed-disk-file bounds checks.
175 { 188 {
176 const GUID id_ctrl = {0x4a12b3c4, 0x5d6e, 0x47f8, {0x90, 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07}}; 189 const GUID id_ctrl = {0x4a12b3c4, 0x5d6e, 0x47f8, {0x90, 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07}};
177 D3D12_SHADER_CACHE_SESSION_DESC desc{}; 190 D3D12_SHADER_CACHE_SESSION_DESC desc{};
178 desc.Identifier = id_ctrl; 191 desc.Identifier = id_ctrl;
179 desc.Mode = D3D12_SHADER_CACHE_MODE_MEMORY; 192 desc.Mode = D3D12_SHADER_CACHE_MODE_MEMORY;
193 desc.Version = 1;
180 desc.MaximumInMemoryCacheEntries = 1; 194 desc.MaximumInMemoryCacheEntries = 1;
181 desc.MaximumInMemoryCacheSizeBytes = 8; 195 desc.MaximumInMemoryCacheSizeBytes = 8;
182 Ref<ID3D12ShaderCacheSession> s; 196 Ref<ID3D12ShaderCacheSession> s;
@@ -185,13 +199,27 @@ int main() {
185 const std::uint32_t k1 = 1, k2 = 2; 199 const std::uint32_t k1 = 1, k2 = 2;
186 const std::uint64_t v1 = 0x1122334455667788ull; 200 const std::uint64_t v1 = 0x1122334455667788ull;
187 EXPECT(s->StoreValue(&k1, sizeof(k1), &v1, sizeof(v1)) == S_OK); 201 EXPECT(s->StoreValue(&k1, sizeof(k1), &v1, sizeof(v1)) == S_OK);
188 EXPECT(s->StoreValue(&k2, sizeof(k2), &v1, sizeof(v1)) == E_OUTOFMEMORY); 202 // Full cache must return DXGI_ERROR_CACHE_FULL (not E_OUTOFMEMORY).
203 EXPECT(s->StoreValue(&k2, sizeof(k2), &v1, sizeof(v1)) == DXGI_ERROR_CACHE_FULL);
189 204
205 // Opening the same Identifier with a different Version while a session is live returns DXGI_ERROR_ALREADY_EXISTS.
206 D3D12_SHADER_CACHE_SESSION_DESC v2_desc = desc;
207 v2_desc.Version = 2;
208 Ref<ID3D12ShaderCacheSession> conflict;
209 EXPECT(device->CreateShaderCacheSession(&v2_desc, IID_PPV_ARGS(&conflict.p)) == DXGI_ERROR_ALREADY_EXISTS &&
210 !conflict.p);
211
212 // DISABLE must return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE on CreateShaderCacheSession, FindValue, and StoreValue.
190 EXPECT(device->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED, 213 EXPECT(device->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
191 D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) == S_OK); 214 D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) == S_OK);
215 Ref<ID3D12ShaderCacheSession> disabled_s;
216 EXPECT(device->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&disabled_s.p)) ==
217 DXGI_ERROR_NOT_CURRENTLY_AVAILABLE &&
218 !disabled_s.p);
192 std::uint64_t out = 0; 219 std::uint64_t out = 0;
193 UINT sz = sizeof(out); 220 UINT sz = sizeof(out);
194 EXPECT(s->FindValue(&k1, sizeof(k1), &out, &sz) == DXGI_ERROR_NOT_FOUND); 221 EXPECT(s->FindValue(&k1, sizeof(k1), &out, &sz) == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE);
222 EXPECT(s->StoreValue(&k2, sizeof(k2), &v1, sizeof(v1)) == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE);
195 223
196 EXPECT(device->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED, 224 EXPECT(device->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
197 D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE) == S_OK); 225 D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE) == S_OK);
@@ -202,7 +230,27 @@ int main() {
202 D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR) == S_OK); 230 D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR) == S_OK);
203 sz = sizeof(out); 231 sz = sizeof(out);
204 EXPECT(s->FindValue(&k1, sizeof(k1), &out, &sz) == DXGI_ERROR_NOT_FOUND); 232 EXPECT(s->FindValue(&k1, sizeof(k1), &out, &sz) == DXGI_ERROR_NOT_FOUND);
205 s->SetDeleteOnDestroy(); 233 s.reset();
234
235 // Zero limits select documented defaults (1 KiB in-memory bytes, 128 entries) and MEMORY discards on final release.
236 D3D12_SHADER_CACHE_SESSION_DESC def_desc{};
237 def_desc.Identifier = id_ctrl;
238 def_desc.Mode = D3D12_SHADER_CACHE_MODE_MEMORY;
239 def_desc.Version = 3;
240 Ref<ID3D12ShaderCacheSession> def_s;
241 EXPECT(SUCCEEDED(device->CreateShaderCacheSession(&def_desc, IID_PPV_ARGS(&def_s.p))) && def_s.p);
242 const std::vector<std::uint8_t> over_1k(1025, 0xAB);
243 EXPECT(def_s->StoreValue(&k1, sizeof(k1), over_1k.data(), static_cast<UINT>(over_1k.size())) ==
244 DXGI_ERROR_CACHE_FULL);
245 const std::vector<std::uint8_t> fit_1k(512, 0xCD);
246 EXPECT(def_s->StoreValue(&k1, sizeof(k1), fit_1k.data(), static_cast<UINT>(fit_1k.size())) == S_OK);
247 def_s.reset(); // final release without SetDeleteOnDestroy must still discard MEMORY contents
248 Ref<ID3D12ShaderCacheSession> reopened;
249 EXPECT(SUCCEEDED(device->CreateShaderCacheSession(&def_desc, IID_PPV_ARGS(&reopened.p))) && reopened.p);
250 sz = static_cast<UINT>(fit_1k.size());
251 std::vector<std::uint8_t> read_buf(512);
252 EXPECT(reopened->FindValue(&k1, sizeof(k1), read_buf.data(), &sz) == DXGI_ERROR_NOT_FOUND);
253 reopened.reset();
206 } 254 }
207 255
208 // Cross-device process-wide sharing: two distinct ID3D12Device9 objects in the same process share the store. 256 // Cross-device process-wide sharing: two distinct ID3D12Device9 objects in the same process share the store.
@@ -279,7 +327,26 @@ int main() {
279 std::uint64_t out = 0; 327 std::uint64_t out = 0;
280 UINT sz = sizeof(out); 328 UINT sz = sizeof(out);
281 EXPECT(s_b->FindValue(&k, sizeof(k), &out, &sz) == S_OK && sz == sizeof(v) && out == v); 329 EXPECT(s_b->FindValue(&k, sizeof(k), &out, &sz) == S_OK && sz == sizeof(v) && out == v);
282 s_b->SetDeleteOnDestroy(); 330 // Opening with a different Version while s_b is live returns DXGI_ERROR_ALREADY_EXISTS.
331 D3D12_SHADER_CACHE_SESSION_DESC bad_ver = disk_desc;
332 bad_ver.Version = 8;
333 Ref<ID3D12ShaderCacheSession> conflict;
334 EXPECT(dev_b->CreateShaderCacheSession(&bad_ver, IID_PPV_ARGS(&conflict.p)) == DXGI_ERROR_ALREADY_EXISTS &&
335 !conflict.p);
336 }
337 // Reopening with a new Version after all sessions closed clears and recreates the disk cache.
338 {
339 D3D12_SHADER_CACHE_SESSION_DESC v8_desc = disk_desc;
340 v8_desc.Version = 8;
341 Ref<ID3D12Device9> dev_v8;
342 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev_v8.p))));
343 Ref<ID3D12ShaderCacheSession> s_v8;
344 EXPECT(SUCCEEDED(dev_v8->CreateShaderCacheSession(&v8_desc, IID_PPV_ARGS(&s_v8.p))) && s_v8.p);
345 std::uint64_t out = 0;
346 UINT sz = sizeof(out);
347 EXPECT(s_v8->FindValue(&k, sizeof(k), &out, &sz) == DXGI_ERROR_NOT_FOUND);
348 EXPECT(s_v8->StoreValue(&k, sizeof(k), &v, sizeof(v)) == S_OK);
349 s_v8->SetDeleteOnDestroy();
283 } 350 }
284 // After SetDeleteOnDestroy + release, the file must be gone and a fresh session must miss. 351 // After SetDeleteOnDestroy + release, the file must be gone and a fresh session must miss.
285 bool file_remains = false; 352 bool file_remains = false;
@@ -287,17 +354,52 @@ int main() {
287 if (entry.is_regular_file() && entry.path().extension() == L".bin") file_remains = true; 354 if (entry.is_regular_file() && entry.path().extension() == L".bin") file_remains = true;
288 } 355 }
289 EXPECT(!file_remains); 356 EXPECT(!file_remains);
357 // Corrupt/truncated disk file with huge claimed sizes must be rejected safely without huge allocation.
290 { 358 {
359 const std::filesystem::path bad_file =
360 temp_dir / L"leonida_sc_31415926535849798323846264338327.bin";
361 std::ofstream out(bad_file, std::ios::binary | std::ios::trunc);
362 const std::uint32_t hdr[4] = {0x3143534Cu, 2u, 1u, 0u};
363 const std::uint64_t ver = 7;
364 const std::uint32_t huge_lens[2] = {0x7FFFFFFFu, 0x7FFFFFFFu};
365 out.write(reinterpret_cast<const char*>(hdr), sizeof(hdr));
366 out.write(reinterpret_cast<const char*>(&ver), sizeof(ver));
367 out.write(reinterpret_cast<const char*>(huge_lens), sizeof(huge_lens));
368 out.close();
369
291 Ref<ID3D12Device9> dev_c; 370 Ref<ID3D12Device9> dev_c;
292 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev_c.p)))); 371 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev_c.p))));
293 Ref<ID3D12ShaderCacheSession> s_c; 372 Ref<ID3D12ShaderCacheSession> s_c;
294 EXPECT(SUCCEEDED(dev_c->CreateShaderCacheSession(&disk_desc, IID_PPV_ARGS(&s_c.p))) && s_c.p); 373 EXPECT(SUCCEEDED(dev_c->CreateShaderCacheSession(&disk_desc, IID_PPV_ARGS(&s_c.p))) && s_c.p);
295 std::uint64_t out = 0; 374 std::uint64_t val = 0;
296 UINT sz = sizeof(out); 375 UINT sz = sizeof(val);
297 EXPECT(s_c->FindValue(&k, sizeof(k), &out, &sz) == DXGI_ERROR_NOT_FOUND); 376 EXPECT(s_c->FindValue(&k, sizeof(k), &val, &sz) == DXGI_ERROR_NOT_FOUND);
298 s_c->SetDeleteOnDestroy(); 377 s_c->SetDeleteOnDestroy();
299 } 378 }
300 std::printf("shader cache (disk persistence + cross-device sharing): OK\n"); 379 // Inactive non-USE_WORKING_DIR disk file must be removed by ShaderCacheControl CLEAR.
380 {
381 const GUID id_inactive = {0x27182818, 0x2845, 0x4045, {0x92, 0x35, 0x36, 0x02, 0x87, 0x47, 0x13, 0x52}};
382 D3D12_SHADER_CACHE_SESSION_DESC def_disk{};
383 def_disk.Identifier = id_inactive;
384 def_disk.Mode = D3D12_SHADER_CACHE_MODE_DISK;
385 def_disk.Version = 1;
386 {
387 Ref<ID3D12ShaderCacheSession> s_in;
388 EXPECT(SUCCEEDED(device->CreateShaderCacheSession(&def_disk, IID_PPV_ARGS(&s_in.p))) && s_in.p);
389 EXPECT(s_in->StoreValue(&k, sizeof(k), &v, sizeof(v)) == S_OK);
390 }
391 EXPECT(device->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
392 D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR) == S_OK);
393 {
394 Ref<ID3D12ShaderCacheSession> s_after;
395 EXPECT(SUCCEEDED(device->CreateShaderCacheSession(&def_disk, IID_PPV_ARGS(&s_after.p))) && s_after.p);
396 std::uint64_t val = 0;
397 UINT sz = sizeof(val);
398 EXPECT(s_after->FindValue(&k, sizeof(k), &val, &sz) == DXGI_ERROR_NOT_FOUND);
399 s_after->SetDeleteOnDestroy();
400 }
401 }
402 std::printf("shader cache (disk persistence + cross-device sharing + clear + bounds): OK\n");
301 } 403 }
302 404
303 // Compare the same scenarios against the host Windows D3D12 runtime when ID3D12Device9 is available. 405 // Compare the same scenarios against the host Windows D3D12 runtime when ID3D12Device9 is available.
@@ -307,7 +409,7 @@ int main() {
307 if (copycmp::create_host(host, adapter_name)) { 409 if (copycmp::create_host(host, adapter_name)) {
308 Ref<ID3D12Device9> host9; 410 Ref<ID3D12Device9> host9;
309 if (SUCCEEDED(host.p->QueryInterface(IID_PPV_ARGS(&host9.p))) && host9.p) { 411 if (SUCCEEDED(host.p->QueryInterface(IID_PPV_ARGS(&host9.p))) && host9.p) {
310 EXPECT(exercise_shader_cache(host9.p, adapter_name.c_str()) == 0); 412 EXPECT(exercise_shader_cache(host9.p, adapter_name.c_str(), false) == 0);
311 } 413 }
312 } 414 }
313 } 415 }
diff --git a/runtime/test/d3d12_short_uav_clear_test.cpp b/runtime/test/d3d12_short_uav_clear_test.cpp
new file mode 100644
index 000000000..8edb0d250
--- /dev/null
+++ b/runtime/test/d3d12_short_uav_clear_test.cpp
@@ -0,0 +1,192 @@
1// Short typed buffer UAV clears through the public COM API. The whole readback must match both the host and
2// literal byte patterns, including all untouched neighbours. CTest selects WARP; manual runs can select a native
3// adapter with LEONIDA_HOST_ADAPTER. Synthetic inputs only.
4#include "vk_test_device.h"
5#include "d3d12_copy_compare.h"
6#include "host_wine.h"
7#include <array>
8#include <bit>
9
10namespace {
11struct Format {
12 DXGI_FORMAT format;
13 UINT bytes;
14 bool floating;
15 std::array<UINT, 4> values;
16 std::array<unsigned char, 2> expected;
17};
18
19bool run(copycmp::Run& run, const Format& format, UINT first, UINT count,
20 const std::vector<D3D12_RECT>& rects, std::vector<unsigned char>& actual) {
21 constexpr UINT bytes = 256;
22 copycmp::Ptr<ID3D12Resource> target, upload, readback;
23 D3D12_RESOURCE_DESC desc{};
24 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
25 desc.Width = bytes;
26 desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1;
27 desc.SampleDesc.Count = 1;
28 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
29 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
30 if (!run.texture(desc, D3D12_RESOURCE_STATE_COPY_DEST, target) ||
31 !run.buffer(D3D12_HEAP_TYPE_UPLOAD, bytes, D3D12_RESOURCE_STATE_GENERIC_READ, upload) ||
32 !run.buffer(D3D12_HEAP_TYPE_READBACK, bytes, D3D12_RESOURCE_STATE_COPY_DEST, readback)) return false;
33 void* mapped = nullptr;
34 const D3D12_RANGE none{};
35 if (FAILED(upload->Map(0, &none, &mapped))) return false;
36 std::memset(mapped, 0xa5, bytes);
37 upload->Unmap(0, nullptr);
38 copycmp::Ptr<ID3D12DescriptorHeap> cpu, gpu;
39 D3D12_DESCRIPTOR_HEAP_DESC heap{};
40 heap.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
41 heap.NumDescriptors = 1;
42 if (FAILED(run.device->CreateDescriptorHeap(&heap, IID_PPV_ARGS(&cpu.p)))) return false;
43 heap.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
44 if (FAILED(run.device->CreateDescriptorHeap(&heap, IID_PPV_ARGS(&gpu.p)))) return false;
45 D3D12_UNORDERED_ACCESS_VIEW_DESC view{};
46 view.Format = format.format;
47 view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
48 view.Buffer.FirstElement = first;
49 view.Buffer.NumElements = count;
50 run.device->CreateUnorderedAccessView(target.p, nullptr, &view, cpu->GetCPUDescriptorHandleForHeapStart());
51 run.device->CreateUnorderedAccessView(target.p, nullptr, &view, gpu->GetCPUDescriptorHandleForHeapStart());
52 run.begin();
53 run.list->CopyBufferRegion(target.p, 0, upload.p, 0, bytes);
54 run.barrier(target.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
55 ID3D12DescriptorHeap* heaps[] = {gpu.p};
56 run.list->SetDescriptorHeaps(1, heaps);
57 if (format.floating) {
58 std::array<float, 4> value{};
59 for (unsigned i = 0; i < 4; ++i) value[i] = std::bit_cast<float>(format.values[i]);
60 run.list->ClearUnorderedAccessViewFloat(gpu->GetGPUDescriptorHandleForHeapStart(),
61 cpu->GetCPUDescriptorHandleForHeapStart(), target.p, value.data(), UINT(rects.size()), rects.data());
62 } else {
63 run.list->ClearUnorderedAccessViewUint(gpu->GetGPUDescriptorHandleForHeapStart(),
64 cpu->GetCPUDescriptorHandleForHeapStart(), target.p, format.values.data(), UINT(rects.size()), rects.data());
65 }
66 run.barrier(target.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
67 run.list->CopyBufferRegion(readback.p, 0, target.p, 0, bytes);
68 const auto error = run.submit();
69 if (!error.empty()) { std::fprintf(stderr, "%s\n", error.c_str()); return false; }
70 const D3D12_RANGE range{0, bytes};
71 if (FAILED(readback->Map(0, &range, &mapped))) return false;
72 actual.assign(static_cast<unsigned char*>(mapped), static_cast<unsigned char*>(mapped) + bytes);
73 readback->Unmap(0, &none);
74 return true;
75}
76
77std::vector<unsigned char> expected(const Format& format, UINT first, UINT count,
78 const std::vector<D3D12_RECT>& rects) {
79 std::vector<unsigned char> out(256, 0xa5);
80 const auto write = [&](LONG left, LONG right) {
81 for (UINT i = UINT(std::max(0L, left)); i < std::min(count, UINT(std::max(0L, right))); ++i)
82 for (UINT byte = 0; byte < format.bytes; ++byte)
83 out[(first + i) * format.bytes + byte] = format.expected[byte];
84 };
85 if (rects.empty()) write(0, LONG(count));
86 else for (const auto& rect : rects) if (rect.top <= 0 && rect.bottom > 0) write(rect.left, rect.right);
87 return out;
88}
89} // namespace
90
91int main() {
92 if (hostwine::host_is_wine()) return 77;
93 vktest::Device vk;
94 vk.request_buffer_device_address = true;
95 const auto status = vk.initialize();
96 if (status == vktest::DeviceStatus::unavailable) return 77;
97 if (status != vktest::DeviceStatus::ready) return 1;
98 if (!vk.buffer_device_address) return 77;
99 copycmp::Ptr<ID3D12Device> ours, host;
100 rt::d3d12::VulkanDeviceInfo info{};
101 info.get_instance_proc = vk.instance_proc;
102 info.instance = vk.instance;
103 info.physical = vk.physical;
104 info.device = vk.device;
105 info.queue = vk.queue;
106 info.queue_family = vk.family;
107 info.buffer_device_address = vk.buffer_device_address;
108 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1;
109 std::string adapter;
110 if (!copycmp::create_host(host, adapter)) return 1;
111 std::printf("short UAV clear reference: %s\n", adapter.c_str());
112 copycmp::Run a, b;
113 if (!a.init(ours.p, true) || !b.init(host.p, false)) return 1;
114 // Avoid a conversion midpoint in portable comparisons: native NVIDIA clears 0.5 to 0x7f/0x7fff,
115 // where WARP/AMD clear to 0x80/0x8000. Keep exact byte comparisons and test 0.5 separately against WARP.
116 const UINT quarter = std::bit_cast<UINT>(0.25f);
117 const Format formats[] = {
118 {DXGI_FORMAT_R8_UINT, 1, false, {0x7b, 0, 0, 0}, {0x7b, 0}},
119 {DXGI_FORMAT_R16_UINT, 2, false, {0xbeef, 0, 0, 0}, {0xef, 0xbe}},
120 {DXGI_FORMAT_R8G8_UINT, 2, false, {0x7b, 0x35, 0, 0}, {0x7b, 0x35}},
121 {DXGI_FORMAT_R8_UNORM, 1, true, {quarter, 0, 0, 0}, {0x40, 0}},
122 {DXGI_FORMAT_R16_UNORM, 2, true, {quarter, 0, 0, 0}, {0x00, 0x40}},
123 };
124 unsigned cases = 0;
125 const auto check = [&](copycmp::Run& reference_run, const Format& format, UINT first, UINT count,
126 const std::vector<D3D12_RECT>& rects) {
127 std::vector<unsigned char> actual, reference;
128 const auto literal = expected(format, first, count, rects);
129 const auto matches = [&](const char* backend, const std::vector<unsigned char>& bytes) {
130 if (bytes == literal) return true;
131 const auto mismatch = std::mismatch(bytes.begin(), bytes.end(), literal.begin());
132 const auto at = std::size_t(mismatch.first - bytes.begin());
133 std::fprintf(stderr, "%s byte %zu: got %02x, literal %02x\n", backend, at,
134 unsigned(bytes[at]), unsigned(literal[at]));
135 return false;
136 };
137 if (!run(reference_run, format, first, count, rects, reference) ||
138 !matches(reference_run.device == host.p ? adapter.c_str() : "WARP control", reference) ||
139 !run(a, format, first, count, rects, actual) || !matches("Vulkan", actual)) {
140 std::fprintf(stderr, "format %u first %u count %u rects %zu failed\n",
141 unsigned(format.format), first, count, rects.size());
142 return false;
143 }
144 ++cases;
145 return true;
146 };
147 for (const auto& format : formats) {
148 for (UINT first = 0; first < 4; ++first)
149 for (UINT count = 1; count <= 8; ++count) if (!check(b, format, first, count, {})) return 1;
150 if (!check(b, format, 256 / format.bytes - 1, 1, {})) return 1;
151 // Portable comparisons stay on the buffer's one row. NVIDIA D3D12 was independently observed to
152 // ignore Y for an out-of-row rectangle where WARP/AMD leave the buffer untouched (#2960).
153 if (!check(b, format, 1, 8, {{-3, 0, 1, 1}, {0, 0, 2, 1}, {3, 0, 4, 1}, {7, 0, 20, 1}})) return 1;
154 if (!check(b, format, 1, 8, {{-3, 0, 0, 1}, {8, 0, 10, 1}})) return 1;
155 }
156 const unsigned portable_cases = cases;
157 std::printf("short buffer UAV clears: %u portable cases matched host and literal bytes, including untouched neighbours\n",
158 portable_cases);
159
160 // Retain the original out-of-row coverage, explicitly against WARP even when the selected native reference
161 // is NVIDIA. This pins the existing replay policy without claiming a uniform native-driver result.
162 copycmp::Ptr<IDXGIFactory4> factory;
163 copycmp::Ptr<IDXGIAdapter> warp_adapter;
164 copycmp::Ptr<ID3D12Device> warp;
165 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) ||
166 FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp_adapter.p))) ||
167 FAILED(D3D12CreateDevice(warp_adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&warp.p)))) return 1;
168 copycmp::Run warp_run;
169 if (!warp_run.init(warp.p, false)) return 1;
170 for (const auto& format : formats) {
171 if (!check(warp_run, format, 1, 8, {{0, 1, 8, 2}})) return 1;
172 if (!check(warp_run, format, 1, 8,
173 {{-3, 0, 1, 1}, {0, 0, 2, 1}, {3, 0, 4, 1}, {7, 0, 20, 1}, {0, 1, 8, 2}})) return 1;
174 if (!check(warp_run, format, 1, 8, {{-3, 0, 0, 1}, {0, 1, 8, 2}, {8, 0, 10, 1}})) return 1;
175 }
176 std::printf("short buffer UAV clears: %u WARP-only out-of-row controls matched literal bytes; excluded from native comparisons\n",
177 cases - portable_cases);
178 const unsigned before_midpoints = cases;
179 for (auto format : formats) {
180 if (!format.floating) continue;
181 format.values[0] = std::bit_cast<UINT>(0.5f);
182 format.expected = format.bytes == 1 ? std::array<unsigned char, 2>{0x80, 0}
183 : std::array<unsigned char, 2>{0x00, 0x80};
184 if (!check(warp_run, format, 0, 1, {})) return 1;
185 if (!check(warp_run, format, 1, 1, {})) return 1;
186 if (!check(warp_run, format, 256 / format.bytes - 1, 1, {})) return 1;
187 if (!check(warp_run, format, 1, 8, {{0, 0, 1, 1}, {3, 0, 4, 1}, {7, 0, 8, 1}})) return 1;
188 }
189 std::printf("short buffer UAV clears: %u WARP-only UNORM midpoint controls matched literal bytes\n",
190 cases - before_midpoints);
191 return vk.validation_errors() ? 1 : 0;
192}
diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp
index c6b660dda..75dbf6282 100644
--- a/runtime/test/d3d12_translated_draw_test.cpp
+++ b/runtime/test/d3d12_translated_draw_test.cpp
@@ -83,7 +83,9 @@ std::array<std::uint32_t, 4> make_vsharp(std::uint64_t base, std::uint32_t recor
83 83
84int main() { 84int main() {
85 vktest::Device d; 85 vktest::Device d;
86 EXPECT(d.create()); 86 const auto device_status = d.initialize();
87 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
88 EXPECT(device_status == vktest::DeviceStatus::ready);
87 89
88 // The translator-style library the build wrote, and the FSSM programs its index entries are keyed by. 90 // The translator-style library the build wrote, and the FSSM programs its index entries are keyed by.
89 const std::filesystem::path root_dir = LEONIDA_TEST_M15_DIR; 91 const std::filesystem::path root_dir = LEONIDA_TEST_M15_DIR;
diff --git a/runtime/test/d3d12_uav_clear_test.cpp b/runtime/test/d3d12_uav_clear_test.cpp
index 27664696e..6bba27044 100644
--- a/runtime/test/d3d12_uav_clear_test.cpp
+++ b/runtime/test/d3d12_uav_clear_test.cpp
@@ -531,6 +531,21 @@ int main() {
531 buffers.push_back(narrow); 531 buffers.push_back(narrow);
532 } 532 }
533 { 533 {
534 for (UINT offset = 0; offset < 8; ++offset) {
535 BufferCase short_ranges{"short typed buffer ranges", 256, {whole(64)}};
536 for (UINT count = 1; count <= 8; ++count)
537 short_ranges.clears.push_back(typed(VK_FORMAT_R8_UINT, false, {offset * 17 + count, 0, 0, 0},
538 offset, count));
539 buffers.push_back(short_ranges);
540 }
541 BufferCase short_ranges{"short typed buffer boundary and rectangles", 256, {whole(64)}};
542 short_ranges.clears.push_back(typed(VK_FORMAT_R16_UINT, false, {0xbeef, 0, 0, 0}, 254, 1));
543 short_ranges.clears.push_back(typed(VK_FORMAT_R8_UINT, false, {0x7b, 0, 0, 0}, 255, 1));
544 short_ranges.clears.push_back(typed(VK_FORMAT_R16_UNORM, true, floats(1.0f, 0, 0, 0), 50, 4,
545 {{-1, 0, 1, 1}, {0, 0, 2, 1}, {3, 0, 8, 1}}));
546 buffers.push_back(short_ranges);
547 }
548 {
534 // 16-byte elements over more than vkCmdUpdateBuffer's 64 KiB: written once, then doubled by copies. 549 // 16-byte elements over more than vkCmdUpdateBuffer's 64 KiB: written once, then doubled by copies.
535 BufferCase wide{"typed buffer, 8- and 16-byte elements", 1 << 17, {whole((1 << 17) / 4)}}; 550 BufferCase wide{"typed buffer, 8- and 16-byte elements", 1 << 17, {whole((1 << 17) / 4)}};
536 wide.clears.push_back(typed(VK_FORMAT_R32G32B32A32_UINT, false, {1, 2, 3, 4}, 16, 8000)); 551 wide.clears.push_back(typed(VK_FORMAT_R32G32B32A32_UINT, false, {1, 2, 3, 4}, 16, 8000));
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index ad98eca7b..788b5c772 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -1849,6 +1849,11 @@ int compare_format_support(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInfo
1849 continue; 1849 continue;
1850 } 1850 }
1851 ++compared; 1851 ++compared;
1852 if ((f == DXGI_FORMAT_R8G8B8A8_UNORM || f == DXGI_FORMAT_B8G8R8A8_UNORM ||
1853 f == DXGI_FORMAT_B8G8R8X8_UNORM || f == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB ||
1854 f == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB || f == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) &&
1855 ((o1 ^ h1) & D3D12_FORMAT_SUPPORT1_BUFFER))
1856 fail(f, "buffer support differs from host", o1, o2, h1, h2);
1852 if (o1 & format_rules & ~h1) fail(f, "1D, 3D, depth-stencil or MIP the host doesn't have", o1, o2, h1, h2); 1857 if (o1 & format_rules & ~h1) fail(f, "1D, 3D, depth-stencil or MIP the host doesn't have", o1, o2, h1, h2);
1853 if (o2 & any_atomic & ~h2) fail(f, "UAV atomics the host doesn't have", o1, o2, h1, h2); 1858 if (o2 & any_atomic & ~h2) fail(f, "UAV atomics the host doesn't have", o1, o2, h1, h2);
1854 if (integer_format(DXGI_FORMAT(f)) && (o1 & filtered)) 1859 if (integer_format(DXGI_FORMAT(f)) && (o1 & filtered))
@@ -4950,6 +4955,15 @@ int main() {
4950 4955
4951 const int options_mismatches = compare_feature_options(device.p, info); 4956 const int options_mismatches = compare_feature_options(device.p, info);
4952 EXPECT(options_mismatches == 0); 4957 EXPECT(options_mismatches == 0);
4958 // Uncompressed 8-bit sRGB formats support texture reads but cannot type a D3D12 buffer view.
4959 for (DXGI_FORMAT format : {DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
4960 DXGI_FORMAT_B8G8R8X8_UNORM_SRGB}) {
4961 D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format};
4962 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))));
4963 EXPECT(!(support.Support1 & D3D12_FORMAT_SUPPORT1_BUFFER));
4964 EXPECT(support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_LOAD);
4965 EXPECT(support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D);
4966 }
4953 const int format_support_mismatches = compare_format_support(device.p, info); 4967 const int format_support_mismatches = compare_format_support(device.p, info);
4954 EXPECT(format_support_mismatches == 0); 4968 EXPECT(format_support_mismatches == 0);
4955 { 4969 {
@@ -5061,6 +5075,15 @@ int main() {
5061 EXPECT(newer.HighestVersion == D3D_ROOT_SIGNATURE_VERSION_1_1); 5075 EXPECT(newer.HighestVersion == D3D_ROOT_SIGNATURE_VERSION_1_1);
5062 D3D12_FEATURE_DATA_ROOT_SIGNATURE undefined{static_cast<D3D_ROOT_SIGNATURE_VERSION>(0)}; 5076 D3D12_FEATURE_DATA_ROOT_SIGNATURE undefined{static_cast<D3D_ROOT_SIGNATURE_VERSION>(0)};
5063 EXPECT(FAILED(device->CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &undefined, sizeof(undefined)))); 5077 EXPECT(FAILED(device->CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &undefined, sizeof(undefined))));
5078 // Anything above 1.2 is undefined: E_INVALIDARG with the value left alone, measured on an RTX 4070 Laptop
5079 // (621.24) and WARP. Checked here rather than against the host, which has crashed on undefined values of
5080 // the shader model query next to this one.
5081 for (const UINT undefined_version : {0x4u, 0x5u, 0x10u, 0xffu, 0x7fffffffu, 0x80000000u, 0xffffffffu}) {
5082 D3D12_FEATURE_DATA_ROOT_SIGNATURE refused{static_cast<D3D_ROOT_SIGNATURE_VERSION>(undefined_version)};
5083 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &refused, sizeof(refused)) ==
5084 E_INVALIDARG);
5085 EXPECT(static_cast<UINT>(refused.HighestVersion) == undefined_version);
5086 }
5064 // A wrong DataSize and a null buffer are refused for both queries. 5087 // A wrong DataSize and a null buffer are refused for both queries.
5065 D3D12_FEATURE_DATA_SHADER_MODEL short_model{D3D_SHADER_MODEL_6_0}; 5088 D3D12_FEATURE_DATA_SHADER_MODEL short_model{D3D_SHADER_MODEL_6_0};
5066 D3D12_FEATURE_DATA_ROOT_SIGNATURE short_signature{D3D_ROOT_SIGNATURE_VERSION_1_1}; 5089 D3D12_FEATURE_DATA_ROOT_SIGNATURE short_signature{D3D_ROOT_SIGNATURE_VERSION_1_1};
@@ -6577,7 +6600,14 @@ int main() {
6577 ext_query.pNext = &m8; 6600 ext_query.pNext = &m8;
6578 } 6601 }
6579#endif 6602#endif
6603 VkPhysicalDeviceShaderClockFeaturesKHR clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR};
6604 if (has(VK_KHR_SHADER_CLOCK_EXTENSION_NAME)) {
6605 clock.pNext = ext_query.pNext;
6606 ext_query.pNext = &clock;
6607 }
6580 if (features2) features2(made->physical, &ext_query); 6608 if (features2) features2(made->physical, &ext_query);
6609 EXPECT(made->shader_subgroup_clock == (clock.shaderSubgroupClock == VK_TRUE));
6610 EXPECT(made->shader_device_clock == (clock.shaderDeviceClock == VK_TRUE));
6581 EXPECT(made->fragment_shader_barycentric == (bary.fragmentShaderBarycentric == VK_TRUE)); 6611 EXPECT(made->fragment_shader_barycentric == (bary.fragmentShaderBarycentric == VK_TRUE));
6582 EXPECT(made->fragment_shader_interlock == (lock.fragmentShaderPixelInterlock == VK_TRUE)); 6612 EXPECT(made->fragment_shader_interlock == (lock.fragmentShaderPixelInterlock == VK_TRUE));
6583#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME 6613#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp
index 95bf9bb06..ca1491153 100644
--- a/runtime/test/dxgi_swapchain_test.cpp
+++ b/runtime/test/dxgi_swapchain_test.cpp
@@ -1,4 +1,4 @@
1// Real Win32 HWND GPU test for the Vulkan-backed IDXGIFactory4 / IDXGISwapChain3 COM shim 1// Real Win32 HWND GPU test for the Vulkan-backed IDXGIFactory7 / IDXGISwapChain3 COM shim
2// (runtime/shims/dxgi_swapchain.h, runtime/shims/dxgi_com.{h,cpp}). 2// (runtime/shims/dxgi_swapchain.h, runtime/shims/dxgi_com.{h,cpp}).
3// No shaders or game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation 3// No shaders or game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation
4// (Core + Synchronization Validation); any validation error fails the test. 4// (Core + Synchronization Validation); any validation error fails the test.
@@ -263,6 +263,17 @@ int main() {
263 if (FAILED(rt::d3d12::create_dxgi_factory(dev, IID_PPV_ARGS(&factory))) || !factory) 263 if (FAILED(rt::d3d12::create_dxgi_factory(dev, IID_PPV_ARGS(&factory))) || !factory)
264 return fail("create_dxgi_factory"); 264 return fail("create_dxgi_factory");
265 265
266 // Host-measured on Windows 11: MakeWindowAssociation takes DXGI_MWA_NO_WINDOW_CHANGES, DXGI_MWA_NO_ALT_ENTER
267 // and DXGI_MWA_NO_PRINT_SCREEN together or alone; any other bit is DXGI_ERROR_INVALID_CALL.
268 {
269 constexpr UINT known = DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_PRINT_SCREEN;
270 if (FAILED(factory->MakeWindowAssociation(hwnd, known))) return fail("MakeWindowAssociation(known flags)");
271 for (const UINT bad : {0x8u, 0x40u, known | 0x8u}) {
272 if (factory->MakeWindowAssociation(hwnd, bad) != DXGI_ERROR_INVALID_CALL)
273 return fail("MakeWindowAssociation accepted an unknown flag bit");
274 }
275 }
276
266 D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; 277 D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0};
267 ID3D12CommandQueue* queue = nullptr; 278 ID3D12CommandQueue* queue = nullptr;
268 ID3D12CommandAllocator* alloc = nullptr; 279 ID3D12CommandAllocator* alloc = nullptr;
@@ -499,6 +510,44 @@ int main() {
499 return 0; 510 return 0;
500 }; 511 };
501 512
513 {
514 DXGI_SWAP_CHAIN_DESC1 before{}, after{};
515 if (FAILED(sc->GetDesc1(&before)) || before.BufferCount < 2)
516 return fail("GetDesc1 before ResizeBuffers1 argument tests");
517 std::vector<UINT> masks(before.BufferCount, 1);
518 std::vector<IUnknown*> queues(before.BufferCount, queue);
519 const auto resize = [&](UINT count) {
520 return sc->ResizeBuffers1(count, before.Width + 1, before.Height, DXGI_FORMAT_UNKNOWN, 0,
521 masks.data(), queues.data());
522 };
523 for (UINT invalid_mask : {2u, 3u}) {
524 masks.back() = invalid_mask;
525 if (resize(0) != DXGI_ERROR_INVALID_CALL) return fail("ResizeBuffers1 invalid node mask with count zero");
526 }
527 masks.back() = 1;
528 queues.back() = dev;
529 if (resize(before.BufferCount) != DXGI_ERROR_INVALID_CALL)
530 return fail("ResizeBuffers1 should reject a non-queue object");
531
532 D3D12_COMMAND_QUEUE_DESC copy_desc{};
533 copy_desc.Type = D3D12_COMMAND_LIST_TYPE_COPY;
534 ID3D12CommandQueue* copy = nullptr;
535 if (FAILED(dev->CreateCommandQueue(&copy_desc, IID_PPV_ARGS(&copy))) || !copy)
536 return fail("CreateCommandQueue for ResizeBuffers1 copy queue test");
537 queues.back() = copy;
538 const HRESULT copy_hr = resize(0);
539 copy->Release();
540 if (copy_hr != DXGI_ERROR_INVALID_CALL) return fail("ResizeBuffers1 should reject a copy queue");
541
542 if (FAILED(sc->GetDesc1(&after)) || after.Width != before.Width || after.Height != before.Height ||
543 after.BufferCount != before.BufferCount)
544 return fail("Invalid ResizeBuffers1 arguments changed the swapchain");
545 queues.back() = queue;
546 masks.front() = 0;
547 if (FAILED(sc->ResizeBuffers1(0, before.Width, before.Height, DXGI_FORMAT_UNKNOWN, 0, masks.data(), queues.data())))
548 return fail("ResizeBuffers1 should accept node masks zero and one with direct queues");
549 }
550
502 // Invalid counts must leave the initial back buffers usable for the first frame. 551 // Invalid counts must leave the initial back buffers usable for the first frame.
503 { 552 {
504 DXGI_SWAP_CHAIN_DESC1 before_resize{}; 553 DXGI_SWAP_CHAIN_DESC1 before_resize{};
@@ -518,6 +567,26 @@ int main() {
518 return fail("Invalid resize changed swapchain buffers"); 567 return fail("Invalid resize changed swapchain buffers");
519 } 568 }
520 569
570 {
571 DXGI_SWAP_CHAIN_DESC1 buffer_desc{};
572 if (FAILED(sc->GetDesc1(&buffer_desc)) || buffer_desc.BufferCount == 0)
573 return fail("GetDesc1 before testing GetBuffer indices");
574 ID3D12Resource* last = nullptr;
575 if (FAILED(sc->GetBuffer(buffer_desc.BufferCount - 1, IID_PPV_ARGS(&last))) || !last)
576 return fail("GetBuffer should return the last back buffer");
577 last->Release();
578
579 for (UINT index : {buffer_desc.BufferCount, buffer_desc.BufferCount + 1, ~0u}) {
580 void* rejected = reinterpret_cast<void*>(1);
581 const HRESULT hr = sc->GetBuffer(index, __uuidof(ID3D12Resource), &rejected);
582 if (hr != DXGI_ERROR_INVALID_CALL || rejected != nullptr) {
583 std::fprintf(stderr, "FAIL: GetBuffer(%u) returned 0x%08lx, expected DXGI_ERROR_INVALID_CALL and null\n",
584 index, static_cast<unsigned long>(hr));
585 return 1;
586 }
587 }
588 }
589
521 // Frame 1: 128x128 clear to (64, 128, 255, 255), read back all 16,384 pixels, Present. 590 // Frame 1: 128x128 clear to (64, 128, 255, 255), read back all 16,384 pixels, Present.
522 const float blue_ish[4] = {64.0f / 255.0f, 128.0f / 255.0f, 1.0f, 1.0f}; 591 const float blue_ish[4] = {64.0f / 255.0f, 128.0f / 255.0f, 1.0f, 1.0f};
523 if (run_clear_readback_present(128, 128, blue_ish, 64, 128, 255) != 0) return 1; 592 if (run_clear_readback_present(128, 128, blue_ish, 64, 128, 255) != 0) return 1;
@@ -846,6 +915,20 @@ int main() {
846 adapter3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, nullptr) != E_INVALIDARG) 915 adapter3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, nullptr) != E_INVALIDARG)
847 return fail("QueryVideoMemoryInfo invalid args should return E_INVALIDARG"); 916 return fail("QueryVideoMemoryInfo invalid args should return E_INVALIDARG");
848 917
918 // Budget-change notification (Microsoft: IDXGIAdapter3::RegisterVideoMemoryBudgetChangeNotificationEvent
919 // returns a success code and a cookie for UnregisterVideoMemoryBudgetChangeNotification).
920 HANDLE budget_ev = CreateEventW(nullptr, FALSE, FALSE, nullptr);
921 DWORD budget_cookie = 0, budget_cookie2 = 0;
922 if (adapter3->RegisterVideoMemoryBudgetChangeNotificationEvent(budget_ev, &budget_cookie) != S_OK ||
923 budget_cookie == 0)
924 return fail("RegisterVideoMemoryBudgetChangeNotificationEvent should succeed with a cookie");
925 if (adapter3->RegisterVideoMemoryBudgetChangeNotificationEvent(budget_ev, &budget_cookie2) != S_OK ||
926 budget_cookie2 == 0 || budget_cookie2 == budget_cookie)
927 return fail("a second budget-change registration should get its own cookie");
928 adapter3->UnregisterVideoMemoryBudgetChangeNotification(budget_cookie);
929 adapter3->UnregisterVideoMemoryBudgetChangeNotification(budget_cookie2);
930 CloseHandle(budget_ev);
931
849 adapter3->Release(); 932 adapter3->Release();
850 adapter1->Release(); 933 adapter1->Release();
851 } 934 }
@@ -917,6 +1000,37 @@ int main() {
917 } 1000 }
918 } 1001 }
919 1002
1003 // ResizeTarget on a windowed swapchain resizes the target's client area to the mode; the back buffers keep
1004 // their size until ResizeBuffers(0, 0, 0) takes the new client area.
1005 {
1006 // Host-measured on Windows 11 / RX 7900 XTX: a null target is DXGI_ERROR_INVALID_CALL, and 0x0 is accepted
1007 // (the window's minimum tracking size decides the resulting client area).
1008 if (sc->ResizeTarget(nullptr) != DXGI_ERROR_INVALID_CALL)
1009 return fail("ResizeTarget(nullptr) should be DXGI_ERROR_INVALID_CALL");
1010 DXGI_MODE_DESC mode{};
1011 mode.Width = 234;
1012 mode.Height = 156;
1013 mode.RefreshRate.Numerator = 60;
1014 mode.RefreshRate.Denominator = 1;
1015 mode.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
1016 if (FAILED(sc->ResizeTarget(&mode))) return fail("ResizeTarget");
1017 RECT cr{};
1018 GetClientRect(hwnd, &cr);
1019 if (cr.right != 234 || cr.bottom != 156) {
1020 std::fprintf(stderr, "FAIL: ResizeTarget gave a %ldx%ld client area, want 234x156\n", cr.right, cr.bottom);
1021 return 1;
1022 }
1023 DXGI_SWAP_CHAIN_DESC1 d{};
1024 if (FAILED(sc->GetDesc1(&d))) return fail("GetDesc1 after ResizeTarget");
1025 if (d.Width != 300 || d.Height != 200)
1026 return fail("ResizeTarget should leave the back buffers for ResizeBuffers");
1027 if (FAILED(sc->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers after ResizeTarget");
1028 if (FAILED(sc->GetDesc1(&d)) || d.Width != 234 || d.Height != 156) {
1029 std::fprintf(stderr, "FAIL: ResizeBuffers after ResizeTarget gave %ux%u, want 234x156\n", d.Width, d.Height);
1030 return 1;
1031 }
1032 }
1033
920 // IDXGIFactory5::CheckFeatureSupport, DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING, and waitable frame-latency swapchains. 1034 // IDXGIFactory5::CheckFeatureSupport, DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING, and waitable frame-latency swapchains.
921 { 1035 {
922 IDXGIFactory5* factory5 = nullptr; 1036 IDXGIFactory5* factory5 = nullptr;
@@ -931,6 +1045,90 @@ int main() {
931 return fail("CheckFeatureSupport should reject null data or wrong size with E_INVALIDARG"); 1045 return fail("CheckFeatureSupport should reject null data or wrong size with E_INVALIDARG");
932 factory5->Release(); 1046 factory5->Release();
933 1047
1048 // IDXGIFactory6/7 (D3D-2). Every answer below is the host dxgi.dll's (Windows 11, RTX 3070).
1049 IDXGIFactory6* factory6 = nullptr;
1050 IDXGIFactory7* factory7 = nullptr;
1051 if (FAILED(factory->QueryInterface(IID_PPV_ARGS(&factory6))) || !factory6 ||
1052 FAILED(factory->QueryInterface(IID_PPV_ARGS(&factory7))) || !factory7)
1053 return fail("QueryInterface(IDXGIFactory6/7) failed");
1054 IDXGIFactory7* created7 = nullptr;
1055 if (FAILED(rt::d3d12::create_dxgi_factory(dev, IID_PPV_ARGS(&created7))) || !created7)
1056 return fail("create_dxgi_factory(IID_IDXGIFactory7) failed");
1057 created7->Release();
1058
1059 DXGI_ADAPTER_DESC1 enum_desc{};
1060 {
1061 IDXGIAdapter1* first = nullptr;
1062 if (FAILED(factory->EnumAdapters1(0, &first)) || !first || FAILED(first->GetDesc1(&enum_desc)))
1063 return fail("EnumAdapters1(0) for the preference comparison");
1064 first->Release();
1065 }
1066 // The host accepts a preference outside the enum, so -1 and 3 are checked as well.
1067 for (const int preference : {0, 1, 2, 3, -1}) {
1068 const auto pref = static_cast<DXGI_GPU_PREFERENCE>(preference);
1069 IDXGIAdapter1* by_pref = nullptr;
1070 DXGI_ADAPTER_DESC1 pref_desc{};
1071 if (FAILED(factory6->EnumAdapterByGpuPreference(0, pref, IID_PPV_ARGS(&by_pref))) || !by_pref ||
1072 FAILED(by_pref->GetDesc1(&pref_desc)))
1073 return fail("EnumAdapterByGpuPreference(0) failed");
1074 by_pref->Release();
1075 if (pref_desc.AdapterLuid.LowPart != enum_desc.AdapterLuid.LowPart ||
1076 pref_desc.AdapterLuid.HighPart != enum_desc.AdapterLuid.HighPart)
1077 return fail("EnumAdapterByGpuPreference(0) is not EnumAdapters1(0)'s adapter");
1078 void* missing = reinterpret_cast<void*>(1);
1079 if (factory6->EnumAdapterByGpuPreference(1, pref, __uuidof(IDXGIAdapter1), &missing) !=
1080 DXGI_ERROR_NOT_FOUND || missing != nullptr)
1081 return fail("EnumAdapterByGpuPreference past the last adapter should be DXGI_ERROR_NOT_FOUND");
1082 }
1083 if (factory6->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_UNSPECIFIED, __uuidof(IDXGIAdapter1),
1084 nullptr) != DXGI_ERROR_INVALID_CALL)
1085 return fail("EnumAdapterByGpuPreference(out = null) should be DXGI_ERROR_INVALID_CALL");
1086 {
1087 void* wrong = reinterpret_cast<void*>(1);
1088 if (factory6->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_UNSPECIFIED, __uuidof(IDXGIFactory),
1089 &wrong) != E_NOINTERFACE || wrong != nullptr)
1090 return fail("EnumAdapterByGpuPreference with a non-adapter riid should be E_NOINTERFACE");
1091 }
1092
1093 HANDLE changed = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1094 HANDLE changed2 = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1095 if (!changed || !changed2) return fail("CreateEventW (adapters changed)");
1096 DWORD c_null = 0xDEAD, c1 = 0, c2 = 0, c3 = 0;
1097 if (factory7->RegisterAdaptersChangedEvent(nullptr, &c_null) != DXGI_ERROR_INVALID_CALL || c_null != 0xDEAD)
1098 return fail("RegisterAdaptersChangedEvent(null event) should be DXGI_ERROR_INVALID_CALL");
1099 if (factory7->RegisterAdaptersChangedEvent(changed, nullptr) != DXGI_ERROR_INVALID_CALL)
1100 return fail("RegisterAdaptersChangedEvent(null cookie) should be DXGI_ERROR_INVALID_CALL");
1101 if (FAILED(factory7->RegisterAdaptersChangedEvent(changed, &c1)) || c1 != 1)
1102 return fail("RegisterAdaptersChangedEvent should succeed with cookie 1");
1103 if (factory7->RegisterAdaptersChangedEvent(changed, &c2) != DXGI_ERROR_INVALID_CALL)
1104 return fail("RegisterAdaptersChangedEvent with an event already registered should be DXGI_ERROR_INVALID_CALL");
1105 if (FAILED(factory7->RegisterAdaptersChangedEvent(changed2, &c3)) || c3 == c1)
1106 return fail("RegisterAdaptersChangedEvent with a second event should get its own cookie");
1107 if (WaitForSingleObject(changed, 0) != WAIT_TIMEOUT)
1108 return fail("registering must not signal the adapters-changed event");
1109 DWORD occlusion = 0;
1110 if (FAILED(factory7->RegisterOcclusionStatusEvent(changed, &occlusion)))
1111 return fail("RegisterOcclusionStatusEvent (cookie space check)");
1112 if (occlusion != c1 && occlusion != c3 &&
1113 factory7->UnregisterAdaptersChangedEvent(occlusion) != DXGI_ERROR_NOT_FOUND)
1114 return fail("an occlusion cookie should not unregister an adapters-changed event");
1115 factory7->UnregisterOcclusionStatus(occlusion);
1116 if (FAILED(factory7->UnregisterAdaptersChangedEvent(c1)) ||
1117 factory7->UnregisterAdaptersChangedEvent(c1) != DXGI_ERROR_NOT_FOUND ||
1118 factory7->UnregisterAdaptersChangedEvent(0) != DXGI_ERROR_NOT_FOUND ||
1119 factory7->UnregisterAdaptersChangedEvent(12345) != DXGI_ERROR_NOT_FOUND)
1120 return fail("UnregisterAdaptersChangedEvent: a cookie unregisters once, an unknown one is NOT_FOUND");
1121 // After unregistering, the same event can be registered again.
1122 DWORD c4 = 0;
1123 if (FAILED(factory7->RegisterAdaptersChangedEvent(changed, &c4)) ||
1124 FAILED(factory7->UnregisterAdaptersChangedEvent(c4)) ||
1125 FAILED(factory7->UnregisterAdaptersChangedEvent(c3)))
1126 return fail("re-registering an unregistered event");
1127 CloseHandle(changed);
1128 CloseHandle(changed2);
1129 factory7->Release();
1130 factory6->Release();
1131
934 constexpr UINT tearing_flag = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING; 1132 constexpr UINT tearing_flag = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
935 constexpr UINT waitable_flag = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; 1133 constexpr UINT waitable_flag = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
936 constexpr UINT both_flags = tearing_flag | waitable_flag; 1134 constexpr UINT both_flags = tearing_flag | waitable_flag;
@@ -979,8 +1177,9 @@ int main() {
979 UINT lat = 0; 1177 UINT lat = 0;
980 if (FAILED(wsc->GetMaximumFrameLatency(&lat)) || lat != 1) 1178 if (FAILED(wsc->GetMaximumFrameLatency(&lat)) || lat != 1)
981 return fail("Waitable swapchain default GetMaximumFrameLatency should be 1"); 1179 return fail("Waitable swapchain default GetMaximumFrameLatency should be 1");
982 if (wsc->SetMaximumFrameLatency(0) != E_INVALIDARG || wsc->SetMaximumFrameLatency(17) != E_INVALIDARG) 1180 if (wsc->SetMaximumFrameLatency(0) != DXGI_ERROR_INVALID_CALL ||
983 return fail("Waitable SetMaximumFrameLatency should reject 0 and > 16 with E_INVALIDARG"); 1181 FAILED(wsc->GetMaximumFrameLatency(&lat)) || lat != 1)
1182 return fail("Waitable SetMaximumFrameLatency(0) should return INVALID_CALL and preserve latency");
984 if (FAILED(wsc->SetMaximumFrameLatency(2)) || FAILED(wsc->GetMaximumFrameLatency(&lat)) || lat != 2) 1183 if (FAILED(wsc->SetMaximumFrameLatency(2)) || FAILED(wsc->GetMaximumFrameLatency(&lat)) || lat != 2)
985 return fail("Waitable SetMaximumFrameLatency(2) round-trip failed"); 1184 return fail("Waitable SetMaximumFrameLatency(2) round-trip failed");
986 HANDLE waitable = wsc->GetFrameLatencyWaitableObject(); 1185 HANDLE waitable = wsc->GetFrameLatencyWaitableObject();
@@ -1001,6 +1200,13 @@ int main() {
1001 if (FAILED(wsc->Present(0, DXGI_PRESENT_ALLOW_TEARING)) || 1200 if (FAILED(wsc->Present(0, DXGI_PRESENT_ALLOW_TEARING)) ||
1002 WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0) 1201 WaitForSingleObject(waitable, 5000) != WAIT_OBJECT_0)
1003 return fail("Present or wait after resizing the waitable swapchain failed"); 1202 return fail("Present or wait after resizing the waitable swapchain failed");
1203 if (FAILED(wsc->SetMaximumFrameLatency(40)) || FAILED(wsc->GetMaximumFrameLatency(&lat)) || lat != 40)
1204 return fail("Waitable SetMaximumFrameLatency(40) round-trip failed");
1205 if (WaitForSingleObject(waitable, 0) != WAIT_OBJECT_0)
1206 return fail("Waitable handle was not signaled after increasing latency from 2 to 40");
1207 if (wsc->SetMaximumFrameLatency(41) != DXGI_ERROR_INVALID_CALL ||
1208 FAILED(wsc->GetMaximumFrameLatency(&lat)) || lat != 40)
1209 return fail("Waitable SetMaximumFrameLatency(41) should return INVALID_CALL and preserve latency");
1004 CloseHandle(waitable); 1210 CloseHandle(waitable);
1005 wsc->Release(); 1211 wsc->Release();
1006 DestroyWindow(hwnd3); 1212 DestroyWindow(hwnd3);
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp
index 3a4bc5860..f51dd32e0 100644
--- a/runtime/test/file_system_test.cpp
+++ b/runtime/test/file_system_test.cpp
@@ -8,6 +8,7 @@
8#include <cstdio> 8#include <cstdio>
9#include <filesystem> 9#include <filesystem>
10#include <string> 10#include <string>
11#include <thread>
11#include <vector> 12#include <vector>
12 13
13#include "file_system.h" 14#include "file_system.h"
@@ -607,6 +608,96 @@ int main() {
607 if (hfa != INVALID_HANDLE_VALUE) find_close(hfa); 608 if (hfa != INVALID_HANDLE_VALUE) find_close(hfa);
608 } 609 }
609 610
611 // Copy-up under two threads: both write-open the same untouched package file at once. Each open must succeed and
612 // the overlay copy must hold the package's bytes; the copy goes through a private name, so neither thread can find
613 // the name taken mid-copy or read a half-written file.
614 {
615 const std::string big(256 * 1024, 'p'); // long enough that the two copies overlap
616 bool all_opened = true, all_intact = true;
617 for (int round = 0; round < 50; ++round) {
618 const std::wstring name = L"race" + std::to_wstring(round) + L".bin";
619 write_path(package / "data" / name, big);
620 const std::wstring game = L"GAME:\\data\\" + name;
621 HANDLE handles[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
622 std::thread threads[2];
623 for (int i = 0; i < 2; ++i)
624 threads[i] = std::thread([&, i] {
625 handles[i] = create_w(game.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
626 nullptr, OPEN_EXISTING, 0, nullptr); });
627 for (auto& t : threads) t.join();
628 for (HANDLE h : handles) {
629 if (h == INVALID_HANDLE_VALUE) all_opened = false;
630 else ::CloseHandle(h);
631 }
632 if (read_path(overlay / "data" / name) != big) all_intact = false;
633 }
634 check(all_opened, "two threads write-opening one package file both succeed");
635 check(all_intact, "the overlay copy made under two threads holds the whole package file");
636 std::error_code ec;
637 check(std::filesystem::is_empty(overlay / ".gta6rt-copy", ec) && !ec, "copy-up leaves no staging file behind");
638
639 // A leftover from a process killed mid-copy stays out of the title's view.
640 write_path(overlay / ".gta6rt-copy" / "123-1", "half");
641 check(!contains(list(first_w, next_w, find_close, L"GAME:\\*"), L".gta6rt-copy"),
642 "the copy staging folder is hidden from a GAME: listing");
643 }
644
645 // RT-218: "G:\" is the package and "T:\" a writable scratch folder in the overlay, as in the other console layers.
646 // A host path under the configured folders stays a host path, and a path that climbs out of the drive is refused.
647 {
648 write_path(package / "drives" / "sub" / "probe.txt", "probe");
649 HANDLE h = create_w(L"G:\\drives\\sub\\probe.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
650 check(h != INVALID_HANDLE_VALUE && read_handle(h) == "probe", "CreateFileW opens G:\\drives\\sub\\probe.txt from the package");
651 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
652 h = create_w(L"g:/drives/sub/probe.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
653 check(h != INVALID_HANDLE_VALUE, "the drive letter is case-insensitive and accepts forward slashes");
654 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
655 check(attributes_w(L"G:\\data\\sub") != INVALID_FILE_ATTRIBUTES, "GetFileAttributesW stats a G: folder");
656
657 SetLastError(0);
658 check(create_w(L"G:\\..\\x.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr) ==
659 INVALID_HANDLE_VALUE &&
660 GetLastError() == ERROR_INVALID_NAME,
661 "G:\\.. is refused with ERROR_INVALID_NAME");
662
663 h = create_w(L"T:\\cache\\scratch.bin", GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr);
664 check(h != INVALID_HANDLE_VALUE, "CreateFileW creates a file on T: (parent folders and all)");
665 if (h != INVALID_HANDLE_VALUE) {
666 DWORD written = 0;
667 ::WriteFile(h, "scratch", 7, &written, nullptr);
668 ::CloseHandle(h);
669 }
670 check(read_path(overlay / ".gta6rt-temp" / "cache" / "scratch.bin") == "scratch",
671 "a T: file lands in the overlay's scratch folder");
672 check(!std::filesystem::exists(package / "cache" / "scratch.bin") && !std::filesystem::exists(package / ".gta6rt-temp"),
673 "and the package is untouched");
674 h = create_w(L"t:/cache/scratch.bin", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
675 check(h != INVALID_HANDLE_VALUE && read_handle(h) == "scratch", "the T: file reads back");
676 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
677 check(attributes_w(L"GAME:\\cache\\scratch.bin") == INVALID_FILE_ATTRIBUTES,
678 "T: is its own drive: GAME: does not see the scratch file");
679 check(!contains(list(first_w, next_w, find_close, L"GAME:\\*"), L".gta6rt-temp"),
680 "a listing of GAME:\\ does not show the scratch folder");
681 SetLastError(0);
682 check(create_w(L"T:\\..\\data\\hello.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr) ==
683 INVALID_HANDLE_VALUE &&
684 GetLastError() == ERROR_INVALID_NAME,
685 "T:\\.. cannot climb out of the scratch folder into the package");
686
687 // A package that itself sits on drive G: is reached by host paths, which must stay host paths.
688 rt::fs::configure(L"G:\\leonida_missing_package", L"G:\\leonida_missing_overlay");
689 SetLastError(0);
690 check(attributes_w(L"G:\\leonida_missing_package\\data.txt") == INVALID_FILE_ATTRIBUTES &&
691 GetLastError() != ERROR_INVALID_NAME,
692 "a path under a configured G: game folder is a host path");
693 // No roots configured: nothing to map G: and T: onto, so they are host paths.
694 rt::fs::configure({}, {});
695 SetLastError(0);
696 check(attributes_w(L"T:\\x") == INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_INVALID_NAME,
697 "without configured folders G: and T: stay host drives");
698 rt::fs::configure(package, overlay);
699 }
700
610 std::filesystem::remove_all(root); 701 std::filesystem::remove_all(root);
611 std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); 702 std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures);
612 return g_failures == 0 ? 0 : 1; 703 return g_failures == 0 ? 0 : 1;
diff --git a/runtime/test/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp
index e54ba1885..dabe29c25 100644
--- a/runtime/test/fixtures/tiny_game.cpp
+++ b/runtime/test/fixtures/tiny_game.cpp
@@ -1,11 +1,12 @@
1// A stand-in game executable for `gta6rt --run`: what a real title does in its first second, run through the 1// A stand-in game executable for `gta6rt --run`: what a real title does in its first second, run through the
2// loader instead of the Windows one. Test code, not game content. Run as 2// loader instead of the Windows one. Test code, not game content. Run as
3// gta6rt --run tiny_game.exe -- hello 42 [tls] [eh] [exit-code] 3// gta6rt --run tiny_game.exe -- hello 42 [tls] [eh] [game-file] [exit-code]
4// It checks its arguments, a static initializer, the heap, a file round trip, a second thread, and the 4// It checks its arguments, a static initializer, the heap, a file round trip, a second thread, and the
5// xgameruntime.dll imports (answered by the shim registry: the stub DLL it links against would fail them), then 5// xgameruntime.dll imports (answered by the shim registry: the stub DLL it links against would fail them), then
6// calls exit() with 0 (42 with `exit-code`) when everything held. Two checks are opt-in, by argument (CTest's 6// calls exit() with 0 (42 with `exit-code`) when everything held. Two checks are opt-in, by argument (CTest's
7// run_tiny_game_tls and run_tiny_game_eh): `tls`, thread_local on the game's own threads, which needs the loader's 7// run_tiny_game_tls and run_tiny_game_eh): `tls`, thread_local on the game's own threads, which needs the loader's
8// per-thread TLS (gta6rt starts main on a separate thread); and `eh`, a C++ exception caught inside the image. 8// per-thread TLS (gta6rt starts main on a separate thread); and `eh`, a C++ exception caught inside the image.
9// A third, `game-file` (run_tiny_game_dir), reads GAME:\tiny_game_probe.txt after moving the current directory.
9// On MSVC, `eh` needs more than the unwind tables #176 registers: _CxxThrowException finds the throwing image 10// On MSVC, `eh` needs more than the unwind tables #176 registers: _CxxThrowException finds the throwing image
10// with RtlPcToFileHeader, which the loader redirects in the host MSVC runtime. Arguments, not environment variables, 11// with RtlPcToFileHeader, which the loader redirects in the host MSVC runtime. Arguments, not environment variables,
11// so scripts/run_wine_tests.py (which passes a test's command line but not its ENVIRONMENT) runs them too. stdout is 12// so scripts/run_wine_tests.py (which passes a test's command line but not its ENVIRONMENT) runs them too. stdout is
@@ -107,6 +108,24 @@ int main(int argc, char** argv) {
107 std::printf("tiny_game: SKIP C++ exception (argument eh)\n"); 108 std::printf("tiny_game: SKIP C++ exception (argument eh)\n");
108 } 109 }
109 110
111 if (has_arg(argc, argv, "game-file")) {
112 // The probe file sits in the game folder (check_game_dir.cmake writes it). Move the current directory away
113 // first, as a title may: GAME: must still name the game folder, whether gta6rt was given a bare image name
114 // or a relative --game-dir.
115 SetCurrentDirectoryA(tmp);
116 HANDLE file = CreateFileW(L"GAME:\\tiny_game_probe.txt", GENERIC_READ, FILE_SHARE_READ, nullptr,
117 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
118 char data[4] = {};
119 DWORD count = 0;
120 const bool read = file != INVALID_HANDLE_VALUE && ReadFile(file, data, sizeof(data), &count, nullptr) &&
121 count == sizeof(data) && std::memcmp(data, "game", sizeof(data)) == 0;
122 if (file == INVALID_HANDLE_VALUE) std::printf("tiny_game: GAME: open error %lu\n", GetLastError());
123 else CloseHandle(file);
124 check(read, "GAME:\\tiny_game_probe.txt is read from the game folder after SetCurrentDirectory");
125 } else {
126 std::printf("tiny_game: SKIP GAME: file (argument game-file)\n");
127 }
128
110 std::printf("tiny_game: %s\n", g_failures ? "FAILED" : "OK"); 129 std::printf("tiny_game: %s\n", g_failures ? "FAILED" : "OK");
111 std::fflush(stdout); 130 std::fflush(stdout);
112 // Reserve 42 for a successful guest test. The loader itself returns 1 on errors. 131 // Reserve 42 for a successful guest test. The loader itself returns 1 on errors.
diff --git a/runtime/test/fixtures/tiny_gdk_load.cpp b/runtime/test/fixtures/tiny_gdk_load.cpp
index 99a5c8c2b..b37307369 100644
--- a/runtime/test/fixtures/tiny_gdk_load.cpp
+++ b/runtime/test/fixtures/tiny_gdk_load.cpp
@@ -8,6 +8,9 @@
8#include <windows.h> 8#include <windows.h>
9 9
10#include <cstdio> 10#include <cstdio>
11#include <cstring>
12#include <cwchar>
13#include <initializer_list>
11 14
12namespace { 15namespace {
13 16
@@ -29,6 +32,33 @@ int fail(const char* stage, unsigned long value) {
29} // namespace 32} // namespace
30 33
31int main() { 34int main() {
35 for (const wchar_t* dll : {L"kernel32.dll", L"kernelbase.dll"}) {
36 HMODULE host = GetModuleHandleW(dll);
37 if (!host) return fail("host module handle", GetLastError());
38 auto command_a = reinterpret_cast<decltype(&GetCommandLineA)>(GetProcAddress(host, "GetCommandLineA"));
39 auto command_w = reinterpret_cast<decltype(&GetCommandLineW)>(GetProcAddress(host, "GetCommandLineW"));
40 if (!command_a || !command_w || std::strcmp(command_a(), GetCommandLineA()) != 0 ||
41 std::wcscmp(command_w(), GetCommandLineW()) != 0 ||
42 !std::strstr(command_a(), "host-shim-probe") || !std::wcsstr(command_w(), L"host-shim-probe"))
43 return fail("dynamic command line matches direct imports", 0);
44 auto process_id = reinterpret_cast<decltype(&GetCurrentProcessId)>(GetProcAddress(host, "GetCurrentProcessId"));
45 if (!process_id || process_id() != GetCurrentProcessId())
46 return fail("unshimmed host export", GetLastError());
47 SetLastError(0);
48 if (GetProcAddress(host, "LeonidaNoSuchHostExport") || GetLastError() != ERROR_PROC_NOT_FOUND)
49 return fail("missing host export", GetLastError());
50 auto create_file = reinterpret_cast<decltype(&CreateFileW)>(GetProcAddress(host, "CreateFileW"));
51 if (!create_file) return fail("dynamic CreateFileW", GetLastError());
52 HANDLE file = create_file(L"GAME:\\host_shim_probe.txt", GENERIC_READ, FILE_SHARE_READ, nullptr,
53 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
54 if (file == INVALID_HANDLE_VALUE) return fail("dynamic GAME: open", GetLastError());
55 char data[4]{};
56 DWORD count = 0;
57 const BOOL read = ReadFile(file, data, sizeof(data), &count, nullptr);
58 CloseHandle(file);
59 if (!read || count != sizeof(data) || std::memcmp(data, "shim", sizeof(data)) != 0)
60 return fail("dynamic GAME: contents", 0);
61 }
32 HMODULE runtime = LoadLibraryW(L"xgameruntime.dll"); 62 HMODULE runtime = LoadLibraryW(L"xgameruntime.dll");
33 if (!runtime) return fail("LoadLibraryW(xgameruntime.dll)", GetLastError()); 63 if (!runtime) return fail("LoadLibraryW(xgameruntime.dll)", GetLastError());
34 // The loader shim hands out a pseudo-handle for a module it owns: not an image the host loaded. 64 // The loader shim hands out a pseudo-handle for a module it owns: not an image the host loaded.
diff --git a/runtime/test/free_image_base.h b/runtime/test/free_image_base.h
new file mode 100644
index 000000000..4cc61493b
--- /dev/null
+++ b/runtime/test/free_image_base.h
@@ -0,0 +1,34 @@
1#pragma once
2
3// A preferred base for a synthetic test image without relocations, so the loader can map it where it asks.
4//
5// The tests fix their images at bases from 0x140000000 (the usual EXE base) up to 0x1a0000000 (DLLs). On Windows
6// that whole span is free, and free_image_base() returns the constants unchanged. Under arm64 Wine (CrossOver on
7// Apple Silicon) the process's own allocations sit at 0x100000000 and up and macOS maps its shared region at
8// 0x180000000 (RT-22), so such an image is rejected with "preferred base is taken" before a test checks what it is
9// about, and the span can be free when a test starts and taken by Wine's own allocations a few tests later. Under
10// Wine the span is therefore moved as a whole to a free window the system picks top-down, away from where the heap
11// grows: each constant keeps its offset, so images loaded together still get different bases.
12#include <windows.h>
13
14#include <cstdint>
15
16namespace leonida_test {
17
18inline std::uint64_t free_image_base(std::uint64_t preferred) {
19 constexpr std::uint64_t kFirst = 0x140000000, kEnd = 0x200000000;
20 if (preferred < kFirst || preferred >= kEnd) return preferred;
21 static const std::uint64_t window = [] {
22 constexpr SIZE_T size = kEnd - kFirst;
23 const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
24 if (!ntdll || !GetProcAddress(ntdll, "wine_get_version")) return kFirst; // Windows: the constants
25 if (void* p = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_TOP_DOWN, PAGE_NOACCESS)) {
26 VirtualFree(p, 0, MEM_RELEASE);
27 return reinterpret_cast<std::uint64_t>(p); // 64 KiB aligned, as an image base must be
28 }
29 return kFirst;
30 }();
31 return window + (preferred - kFirst);
32}
33
34} // namespace leonida_test
diff --git a/runtime/test/gameinput_probe.cpp b/runtime/test/gameinput_probe.cpp
index a56132ed5..510194f1d 100644
--- a/runtime/test/gameinput_probe.cpp
+++ b/runtime/test/gameinput_probe.cpp
@@ -2,7 +2,8 @@
2// 2//
3// gameinput_probe [--seconds N] [--rumble] 3// gameinput_probe [--seconds N] [--rumble]
4// 4//
5// Lists the gamepads the shim sees, then prints the live gamepad reading of each for N seconds (default 10). With 5// Lists the gamepads the shim sees, with the raw HID report tables of each pad opened through HID, then prints the
6// live gamepad reading (and its newest raw input report, when there is one) for N seconds (default 10). With
6// --rumble it first plays, on every pad: the low-frequency motor, the high-frequency motor, the left and the right 7// --rumble it first plays, on every pad: the low-frequency motor, the high-frequency motor, the left and the right
7// impulse trigger, one second each. On a DualSense the trigger steps run in the LEONIDA_DS_TRIGGERS mode (rumble by 8// impulse trigger, one second each. On a DualSense the trigger steps run in the LEONIDA_DS_TRIGGERS mode (rumble by
8// default; set it to resistance to feel that one). Everything goes through GameInputCreate from the shim registry, 9// default; set it to resistance to feel that one). Everything goes through GameInputCreate from the shim registry,
@@ -30,6 +31,22 @@ void CALLBACK on_device(GameInputCallbackToken, void*, IGameInputDevice* device,
30 (current & GameInputDeviceConnected) ? "connected " : "disconnected", 31 (current & GameInputDeviceConnected) ? "connected " : "disconnected",
31 i->displayName ? i->displayName->data : "?", i->vendorId, i->productId, i->supportedRumbleMotors, 32 i->displayName ? i->displayName->data : "?", i->vendorId, i->productId, i->supportedRumbleMotors,
32 i->forceFeedbackMotorCount, i->hapticFeedbackMotorCount); 33 i->forceFeedbackMotorCount, i->hapticFeedbackMotorCount);
34 // Raw HID (RT-175): the report tables read from the pad's HID report descriptor, or why there are none.
35 if (current & GameInputDeviceConnected) {
36 if (!(current & GameInputDeviceRawIoEnabled)) {
37 std::printf("raw hid: no raw I/O (no HID device the backend could open, or no readable descriptor)\n");
38 } else {
39 const auto list = [](const char* kind, uint32_t n, const void* p) {
40 const auto* r = static_cast<const GameInputRawDeviceReportInfo*>(p);
41 std::printf("raw hid: %u %s report(s):", n, kind);
42 for (uint32_t k = 0; k < n; ++k) std::printf(" id %u = %u bytes;", r[k].id, r[k].size);
43 std::printf("\n");
44 };
45 list("input", i->inputReportCount, i->inputReportInfo);
46 list("output", i->outputReportCount, i->outputReportInfo);
47 list("feature", i->featureReportCount, i->featureReportInfo);
48 }
49 }
33 if ((current & GameInputDeviceConnected) && !(previous & GameInputDeviceConnected)) { 50 if ((current & GameInputDeviceConnected) && !(previous & GameInputDeviceConnected)) {
34 device->AddRef(); 51 device->AddRef();
35 g_devices.push_back(device); 52 g_devices.push_back(device);
@@ -98,6 +115,16 @@ int main(int argc, char** argv) {
98 if (motion) // fractions of motionInfo's maxima: accel includes gravity, so a resting pad shows ~0.5 g 115 if (motion) // fractions of motionInfo's maxima: accel includes gravity, so a resting pad shows ~0.5 g
99 std::printf("\n[a]=(%+.2f,%+.2f,%+.2f) [w]=(%+.2f,%+.2f,%+.2f) ", m.accelerationX, m.accelerationY, 116 std::printf("\n[a]=(%+.2f,%+.2f,%+.2f) [w]=(%+.2f,%+.2f,%+.2f) ", m.accelerationX, m.accelerationY,
100 m.accelerationZ, m.angularVelocityX, m.angularVelocityY, m.angularVelocityZ); 117 m.accelerationZ, m.angularVelocityX, m.angularVelocityY, m.angularVelocityZ);
118 void* raw = nullptr;
119 if (r->GetRawReport(&raw) && raw) { // the newest raw input report: id and its first 16 bytes
120 auto* rr = static_cast<IGameInputRawDeviceReport*>(raw);
121 unsigned char b[16] = {};
122 const size_t n = rr->GetRawData(sizeof b, b);
123 std::printf("\nraw id %u (%zu bytes):", rr->GetReportInfo()->id, rr->GetRawDataSize());
124 for (size_t k = 0; k < n; ++k) std::printf(" %02x", b[k]);
125 std::printf(" ");
126 rr->Release();
127 }
101 std::fflush(stdout); 128 std::fflush(stdout);
102 r->Release(); 129 r->Release();
103 } 130 }
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp
index 99e74a082..1389b8f6d 100644
--- a/runtime/test/gameinput_test.cpp
+++ b/runtime/test/gameinput_test.cpp
@@ -11,10 +11,12 @@
11 11
12#include <SDL3/SDL.h> 12#include <SDL3/SDL.h>
13 13
14#include <algorithm>
14#include <cmath> 15#include <cmath>
15#include <cstdint> 16#include <cstdint>
16#include <cstdio> 17#include <cstdio>
17#include <cstring> 18#include <cstring>
19#include <deque>
18#include <string> 20#include <string>
19#include <vector> 21#include <vector>
20 22
@@ -131,10 +133,17 @@ void CALLBACK on_device(GameInputCallbackToken token, void*, IGameInputDevice* d
131 g_device_events.push_back({device, current, previous, token}); 133 g_device_events.push_back({device, current, previous, token});
132} 134}
133DWORD g_reading_sleep_ms = 0; // makes on_reading slow, for the Dispatch quota checks 135DWORD g_reading_sleep_ms = 0; // makes on_reading slow, for the Dispatch quota checks
136SDL_Joystick* g_requeue_pad = nullptr; // set: on_reading queues one more reading from inside the callback
137bool g_requeue_down = false;
134 138
135void CALLBACK on_reading(GameInputCallbackToken, void*, IGameInputReading* reading, bool) { 139void CALLBACK on_reading(GameInputCallbackToken, void*, IGameInputReading* reading, bool) {
136 if (reading) ++g_reading_events; 140 if (reading) ++g_reading_events;
137 if (g_reading_sleep_ms) Sleep(g_reading_sleep_ms); 141 if (g_reading_sleep_ms) Sleep(g_reading_sleep_ms);
142 if (g_requeue_pad) {
143 g_requeue_down = !g_requeue_down;
144 SDL_SetJoystickVirtualButton(g_requeue_pad, SDL_GAMEPAD_BUTTON_WEST, g_requeue_down);
145 rt::gameinput::poll();
146 }
138} 147}
139void CALLBACK on_guide(GameInputCallbackToken, void*, IGameInputDevice*, uint64_t, bool pressed) { 148void CALLBACK on_guide(GameInputCallbackToken, void*, IGameInputDevice*, uint64_t, bool pressed) {
140 g_guide_events.push_back(pressed); 149 g_guide_events.push_back(pressed);
@@ -232,6 +241,221 @@ GameInputMotionState motion_state(IGameInput* input, IGameInputDevice* dev, bool
232 return ms; 241 return ms;
233} 242}
234 243
244// ---- raw HID (RT-175) -------------------------------------------------------------------------------------------
245
246using rt::gameinput::RawReportSize;
247
248bool same_reports(const std::vector<RawReportSize>& got, std::initializer_list<RawReportSize> want) {
249 if (got.size() != want.size()) return false;
250 size_t i = 0;
251 for (const RawReportSize& w : want) {
252 if (got[i].kind != w.kind || got[i].id != w.id || got[i].bytes != w.bytes) return false;
253 ++i;
254 }
255 return true;
256}
257
258// A game pad with numbered reports: input 1 (3 bytes), output 2 (2 bytes), feature 3 (4 bytes).
259const uint8_t kRawPadDescriptor[] = {
260 0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, // usage page generic desktop, usage game pad, collection application
261 0x85, 0x01, 0x75, 0x08, 0x95, 0x03, 0x81, 0x02, // report id 1, size 8, count 3, input
262 0x85, 0x02, 0x95, 0x02, 0x91, 0x02, // report id 2, count 2, output
263 0x85, 0x03, 0x95, 0x04, 0xB1, 0x02, // report id 3, count 4, feature
264 0xC0, // end collection
265};
266
267void test_parse_report_descriptor() {
268 std::vector<RawReportSize> r;
269 check(rt::gameinput::parse_report_descriptor(kRawPadDescriptor, sizeof kRawPadDescriptor, &r) &&
270 same_reports(r, {{0, 1, 3}, {1, 2, 2}, {2, 3, 4}}),
271 "raw hid: a descriptor with report ids gives input 1 (3), output 2 (2), feature 3 (4)");
272 // No report id: one 16-bit input report under id 0, from two main items that add up (12 + 4 bits).
273 const uint8_t no_ids[] = {0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x75, 0x0C, 0x95, 0x01, 0x81, 0x02,
274 0x75, 0x04, 0x81, 0x03, 0xC0};
275 check(rt::gameinput::parse_report_descriptor(no_ids, sizeof no_ids, &r) && same_reports(r, {{0, 0, 2}}),
276 "raw hid: without report ids one input report of the summed bits (12 + 4 bits = 2 bytes)");
277 // Push saves the globals (size 8, count 2) and Pop restores them after a 32-bit item; a long item is skipped.
278 const uint8_t push_pop[] = {0x75, 0x08, 0x95, 0x02, 0xA4, 0x75, 0x20, 0x95, 0x01, 0x81, 0x02, 0xB4,
279 0xFE, 0x02, 0x10, 0xAA, 0xBB, 0x81, 0x02};
280 check(rt::gameinput::parse_report_descriptor(push_pop, sizeof push_pop, &r) && same_reports(r, {{0, 0, 6}}),
281 "raw hid: Push/Pop restore Report Size and Count, a long item is skipped (4 + 2 bytes)");
282 const uint8_t truncated[] = {0x75, 0x08, 0x96, 0x01}; // a two-byte Report Count cut after one byte
283 const uint8_t id_zero[] = {0x85, 0x00, 0x81, 0x02}; // Report ID 0 is reserved
284 const uint8_t pop_empty[] = {0xB4, 0x81, 0x02}; // Pop without Push
285 const uint8_t huge[] = {0x77, 0xFF, 0xFF, 0x00, 0x00, 0x97, 0xFF, 0xFF, 0x00, 0x00, 0x81, 0x02}; // > 64 KiB
286 check(!rt::gameinput::parse_report_descriptor(truncated, sizeof truncated, &r) &&
287 !rt::gameinput::parse_report_descriptor(id_zero, sizeof id_zero, &r) &&
288 !rt::gameinput::parse_report_descriptor(pop_empty, sizeof pop_empty, &r) &&
289 !rt::gameinput::parse_report_descriptor(huge, sizeof huge, &r),
290 "raw hid: a truncated item, Report ID 0, Pop without Push and a report over 64 KiB are refused");
291 check(rt::gameinput::parse_report_descriptor(nullptr, 0, &r) && r.empty(), "raw hid: an empty descriptor declares nothing");
292}
293
294// The fake HID device behind the raw pad: input reports to hand out, what the shim wrote, the feature reply.
295struct FakeRawHid {
296 uint16_t vendor = 0x1209, product = 0x0001; // pid.codes test ids, not a real pad
297 int opens = 0, closes = 0;
298 std::deque<std::vector<uint8_t>> inputs;
299 std::vector<std::vector<uint8_t>> writes, features_sent;
300 std::vector<uint8_t> feature_reply;
301 bool fail = false;
302};
303FakeRawHid g_raw;
304void* raw_open(const char*, uint16_t vendor, uint16_t product) {
305 if (vendor != g_raw.vendor || product != g_raw.product) return nullptr;
306 ++g_raw.opens;
307 return &g_raw;
308}
309void raw_close(void*) { ++g_raw.closes; }
310int raw_descriptor(void*, uint8_t* buf, size_t size) {
311 if (size < sizeof kRawPadDescriptor) return -1;
312 std::memcpy(buf, kRawPadDescriptor, sizeof kRawPadDescriptor);
313 return static_cast<int>(sizeof kRawPadDescriptor);
314}
315int raw_read(void*, uint8_t* buf, size_t size) {
316 if (g_raw.inputs.empty()) return 0;
317 const std::vector<uint8_t> r = g_raw.inputs.front();
318 g_raw.inputs.pop_front();
319 const size_t n = std::min(size, r.size());
320 std::memcpy(buf, r.data(), n);
321 return static_cast<int>(n);
322}
323int raw_write(void*, const uint8_t* buf, size_t size) {
324 if (g_raw.fail) return -1;
325 g_raw.writes.emplace_back(buf, buf + size);
326 return static_cast<int>(size);
327}
328int raw_get_feature(void*, uint8_t* buf, size_t size) {
329 if (g_raw.fail || g_raw.feature_reply.empty() || g_raw.feature_reply[0] != buf[0]) return -1;
330 const size_t n = std::min(size, g_raw.feature_reply.size());
331 std::memcpy(buf, g_raw.feature_reply.data(), n);
332 return static_cast<int>(n);
333}
334int raw_send_feature(void*, const uint8_t* buf, size_t size) {
335 if (g_raw.fail) return -1;
336 g_raw.features_sent.emplace_back(buf, buf + size);
337 return static_cast<int>(size);
338}
339const rt::gameinput::HidBackend kFakeRawHid = {raw_open, raw_close, raw_descriptor, raw_read,
340 raw_write, raw_get_feature, raw_send_feature};
341
342std::vector<uint8_t> raw_bytes(IGameInputRawDeviceReport* r) {
343 std::vector<uint8_t> v(r ? r->GetRawDataSize() : 0);
344 if (r) r->GetRawData(v.size(), v.data());
345 return v;
346}
347
348void test_raw_hid(IGameInput* input) {
349 test_parse_report_descriptor();
350 rt::gameinput::set_hid_backend(&kFakeRawHid);
351 const size_t events_before = g_device_events.size();
352 Pad raw_pad, plain;
353 attach(raw_pad, "Leonida virtual raw pad", g_raw.vendor, g_raw.product, false);
354 attach(plain, "Leonida virtual pad without HID", 0x045E, 0x02FF, false);
355 rt::gameinput::poll();
356 std::vector<IGameInputDevice*> found; // attach order: the raw pad first (see test_motion)
357 for (size_t i = events_before; i < g_device_events.size() && found.size() < 2; ++i) {
358 const DeviceEvent& e = g_device_events[i];
359 if ((e.current & GameInputDeviceConnected) && std::find(found.begin(), found.end(), e.device) == found.end())
360 found.push_back(e.device);
361 }
362 IGameInputDevice* rdev = found.size() > 0 ? found[0] : nullptr;
363 IGameInputDevice* pdev = found.size() > 1 ? found[1] : nullptr;
364 check(rdev && pdev && g_raw.opens == 1, "raw hid: both pads connected, the backend opened the raw pad only");
365 if (!rdev || !pdev) return;
366 rdev->AddRef();
367 pdev->AddRef();
368
369 const GameInputDeviceInfo* ri = rdev->GetDeviceInfo();
370 check((ri->supportedInput & GameInputKindRawDeviceReport) && (rdev->GetDeviceStatus() & GameInputDeviceRawIoEnabled),
371 "raw hid: the raw pad reports GameInputKindRawDeviceReport and GameInputDeviceRawIoEnabled");
372 const auto* in = static_cast<const GameInputRawDeviceReportInfo*>(ri->inputReportInfo);
373 const auto* out = static_cast<const GameInputRawDeviceReportInfo*>(ri->outputReportInfo);
374 const auto* feat = static_cast<const GameInputRawDeviceReportInfo*>(ri->featureReportInfo);
375 check(ri->inputReportCount == 1 && in && in->kind == GameInputRawInputReport && in->id == 1 && in->size == 3 &&
376 in->itemCount == 0 && ri->outputReportCount == 1 && out && out->id == 2 && out->size == 2 &&
377 ri->featureReportCount == 1 && feat && feat->id == 3 && feat->size == 4,
378 "raw hid: the report tables follow the descriptor (input 1/3, output 2/2, feature 3/4, no items)");
379 const GameInputDeviceInfo* pi = pdev->GetDeviceInfo();
380 check(!(pi->supportedInput & GameInputKindRawDeviceReport) && pi->inputReportCount == 0 &&
381 !(pdev->GetDeviceStatus() & GameInputDeviceRawIoEnabled),
382 "raw hid: a pad without a HID device has no raw reports");
383
384 IGameInputReading* reading = nullptr;
385 void* report = nullptr;
386 check(input->GetCurrentReading(GameInputKindGamepad, rdev, &reading) == S_OK && reading &&
387 !(reading->GetInputKind() & GameInputKindRawDeviceReport) && !reading->GetRawReport(&report) && !report,
388 "raw hid: before the first input report a reading carries no raw report");
389 if (reading) reading->Release();
390
391 g_raw.inputs.push_back({0x01, 0x11, 0x22, 0x33});
392 g_raw.inputs.push_back({0x09, 0x99}); // an id the descriptor does not declare: ignored
393 rt::gameinput::poll();
394 reading = nullptr;
395 check(input->GetCurrentReading(GameInputKindRawDeviceReport, rdev, &reading) == S_OK && reading &&
396 (reading->GetInputKind() & GameInputKindRawDeviceReport),
397 "raw hid: an input report makes a reading of kind GameInputKindRawDeviceReport");
398 IGameInputRawDeviceReport* rr = nullptr;
399 if (reading && reading->GetRawReport(&report)) rr = static_cast<IGameInputRawDeviceReport*>(report);
400 const GameInputRawDeviceReportInfo* rinfo = rr ? rr->GetReportInfo() : nullptr;
401 IGameInputDevice* owner = nullptr;
402 if (rr) rr->GetDevice(&owner);
403 check(rr && rinfo && rinfo->kind == GameInputRawInputReport && rinfo->id == 1 &&
404 raw_bytes(rr) == std::vector<uint8_t>({0x11, 0x22, 0x33}) && owner == rdev,
405 "raw hid: GetRawReport gives the newest declared input report, without its id byte, of this device");
406 if (owner) owner->Release();
407 int64_t item = 7;
408 check(rr && !rr->GetItemValue(0, &item) && item == 0 && !rr->SetItemValue(0, 1) && !rr->ResetAllItems(),
409 "raw hid: the item calls answer false (no item tables)");
410 if (rr) rr->Release();
411 if (reading) reading->Release();
412
413 void* created = nullptr;
414 check(rdev->CreateRawDeviceReport(2, GameInputRawOutputReport, &created) == S_OK && created,
415 "raw hid: CreateRawDeviceReport(2, output)");
416 auto* outr = static_cast<IGameInputRawDeviceReport*>(created);
417 const uint8_t payload[] = {0xAA, 0xBB};
418 check(outr && outr->GetRawDataSize() == 2 && raw_bytes(outr) == std::vector<uint8_t>({0, 0}) &&
419 !outr->SetRawData(1, payload) && outr->SetRawData(2, payload),
420 "raw hid: a new report is zeroed, and SetRawData takes exactly its size");
421 check(rdev->SendRawDeviceOutput(outr) == S_OK && !g_raw.writes.empty() &&
422 g_raw.writes.back() == std::vector<uint8_t>({0x02, 0xAA, 0xBB}),
423 "raw hid: SendRawDeviceOutput writes the id byte then the payload");
424 check(rdev->SetRawDeviceFeature(outr) == E_INVALIDARG && rdev->SendRawDeviceOutput(nullptr) == E_INVALIDARG,
425 "raw hid: an output report is not a feature report, and a null report is refused");
426 g_raw.fail = true;
427 check(rdev->SendRawDeviceOutput(outr) == E_FAIL, "raw hid: a failed write is E_FAIL");
428 g_raw.fail = false;
429 if (outr) outr->Release();
430
431 g_raw.feature_reply = {0x03, 0x01, 0x02, 0x03, 0x04};
432 void* fr = nullptr;
433 check(rdev->GetRawDeviceFeature(3, &fr) == S_OK && fr &&
434 raw_bytes(static_cast<IGameInputRawDeviceReport*>(fr)) == std::vector<uint8_t>({1, 2, 3, 4}),
435 "raw hid: GetRawDeviceFeature(3) reads the feature report");
436 check(fr && rdev->SetRawDeviceFeature(fr) == S_OK && !g_raw.features_sent.empty() &&
437 g_raw.features_sent.back() == std::vector<uint8_t>({0x03, 1, 2, 3, 4}),
438 "raw hid: SetRawDeviceFeature sends it back with its id byte");
439 if (fr) static_cast<IGameInputRawDeviceReport*>(fr)->Release();
440 void* none = reinterpret_cast<void*>(1);
441 check(rdev->CreateRawDeviceReport(9, GameInputRawOutputReport, &none) == E_INVALIDARG && !none &&
442 rdev->CreateRawDeviceReport(1, 7, &none) == E_INVALIDARG && rdev->GetRawDeviceFeature(2, &none) == E_INVALIDARG,
443 "raw hid: an undeclared id or kind is E_INVALIDARG");
444 check(pdev->CreateRawDeviceReport(1, GameInputRawInputReport, &none) == E_NOTIMPL && !none &&
445 pdev->GetRawDeviceFeature(3, &none) == E_NOTIMPL,
446 "raw hid: a pad without raw I/O answers E_NOTIMPL, as before");
447
448 detach(raw_pad);
449 detach(plain);
450 rt::gameinput::poll();
451 check(g_raw.closes == 1 && rt::gameinput::connected_count() == 0, "raw hid: unplugging closes the HID device");
452 check(rdev->CreateRawDeviceReport(2, GameInputRawOutputReport, &none) == E_NOTIMPL,
453 "raw hid: no raw I/O once the pad is gone");
454 rdev->Release();
455 pdev->Release();
456 rt::gameinput::set_hid_backend(nullptr);
457}
458
235void test_motion(IGameInput* input) { 459void test_motion(IGameInput* input) {
236 const size_t events_before = g_device_events.size(); // other tests' events are still queued in the vector 460 const size_t events_before = g_device_events.size(); // other tests' events are still queued in the vector
237 Pad gyro_pad, plain; 461 Pad gyro_pad, plain;
@@ -1361,6 +1585,8 @@ int main() {
1361 if (wait) WaitForSingleObject(wait, 0); // consume the signal from queueing 1585 if (wait) WaitForSingleObject(wait, 0); // consume the signal from queueing
1362 check(dispatcher->Dispatch(0) && g_reading_events == before_quota + 1, "Dispatch(0) runs exactly one event and reports more"); 1586 check(dispatcher->Dispatch(0) && g_reading_events == before_quota + 1, "Dispatch(0) runs exactly one event and reports more");
1363 check(wait && WaitForSingleObject(wait, 0) == WAIT_OBJECT_0, "the wait handle is signalled again while events remain"); 1587 check(wait && WaitForSingleObject(wait, 0) == WAIT_OBJECT_0, "the wait handle is signalled again while events remain");
1588 // The callback sleeps 5 ms, so at least 5 ms have passed after the first event however loaded the machine
1589 // is; a slower run only makes the 1 ms quota more clearly spent.
1364 g_reading_sleep_ms = 5; 1590 g_reading_sleep_ms = 5;
1365 before_quota = g_reading_events; 1591 before_quota = g_reading_events;
1366 check(dispatcher->Dispatch(1000) && g_reading_events == before_quota + 1, 1592 check(dispatcher->Dispatch(1000) && g_reading_events == before_quota + 1,
@@ -1370,6 +1596,26 @@ int main() {
1370 check(!dispatcher->Dispatch(1'000'000) && g_reading_events >= before_quota + 2, 1596 check(!dispatcher->Dispatch(1'000'000) && g_reading_events >= before_quota + 2,
1371 "a large quota drains the queue and returns false"); 1597 "a large quota drains the queue and returns false");
1372 check(!dispatcher->Dispatch(0), "Dispatch on an empty queue returns false"); 1598 check(!dispatcher->Dispatch(0), "Dispatch on an empty queue returns false");
1599
1600 // Events queued during a call wait for the next one: each callback here queues another reading, so a
1601 // Dispatch that kept draining would never return. With two events queued, each call runs exactly the batch
1602 // it started with and reports the readings queued meanwhile.
1603 queue_changes(2);
1604 g_requeue_pad = xbox.js;
1605 before_quota = g_reading_events;
1606 check(dispatcher->Dispatch(UINT64_MAX) && g_reading_events == before_quota + 2,
1607 "Dispatch runs only the events queued when it started");
1608 before_quota = g_reading_events;
1609 check(dispatcher->Dispatch(UINT64_MAX) && g_reading_events == before_quota + 2,
1610 "the events queued during the call run on the next one");
1611 g_requeue_pad = nullptr;
1612 while (dispatcher->Dispatch(UINT64_MAX)) {}
1613 if (g_requeue_down) {
1614 g_requeue_down = false;
1615 SDL_SetJoystickVirtualButton(xbox.js, SDL_GAMEPAD_BUTTON_WEST, false);
1616 rt::gameinput::poll();
1617 while (dispatcher->Dispatch(UINT64_MAX)) {}
1618 }
1373 } 1619 }
1374 if (wait) CloseHandle(wait); 1620 if (wait) CloseHandle(wait);
1375 if (dispatcher) dispatcher->Release(); 1621 if (dispatcher) dispatcher->Release();
@@ -1575,6 +1821,7 @@ int main() {
1575 test_aggregate_device(input); 1821 test_aggregate_device(input);
1576 test_force_feedback(input); 1822 test_force_feedback(input);
1577 test_haptic_motors(input); 1823 test_haptic_motors(input);
1824 test_raw_hid(input);
1578 input->Release(); 1825 input->Release();
1579 1826
1580 std::printf("%d checks, %d failures\n", g_checks, g_failures); 1827 std::printf("%d checks, %d failures\n", g_checks, g_failures);
diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp
index 82779ccb1..ee0583b6a 100644
--- a/runtime/test/glsl/cs_user_data.comp
+++ b/runtime/test/glsl/cs_user_data.comp
@@ -49,6 +49,23 @@ void main() {
49 } 49 }
50 return; 50 return;
51 } 51 }
52 if (pc.s[1] == 0xFFFFFFFFu) {
53 // Buffer SRV V# mode: decode 16-byte GFX10 buffer descriptor written by CreateShaderResourceView.
54 const uint stride = (table.w[1] >> 16u) & 0x3FFFu;
55 const uint num_records = table.w[2];
56 const uint oob_select = (table.w[3] >> 28u) & 3u;
57 const uvec2 base = uvec2(table.w[0], table.w[1] & 0xFFFFu);
58 if (oob_select == 3u) {
59 const uint byte_off = pc.s[0] + i * 4u;
60 result.w[i] = (byte_off + 4u <= num_records) ? at(base).w[byte_off >> 2u] : 0u;
61 } else if (oob_select == 1u && stride >= 4u) {
62 const uint idx = pc.s[0] + i;
63 result.w[i] = (idx < num_records) ? at(base).w[(idx * stride) >> 2u] : 0u;
64 } else {
65 result.w[i] = 0u;
66 }
67 return;
68 }
52 Words constants = at(uvec2(table.w[0], table.w[1])); 69 Words constants = at(uvec2(table.w[0], table.w[1]));
53 Words code = at(pc.code_base); 70 Words code = at(pc.code_base);
54 result.w[i] = pc.s[0] + pc.s[1] * i + constants.w[i % 4] + code.w[1]; 71 result.w[i] = pc.s[0] + pc.s[1] * i + constants.w[i % 4] + code.w[1];
diff --git a/runtime/test/glsl/ps_conservative.frag b/runtime/test/glsl/ps_conservative.frag
new file mode 100644
index 000000000..3816ca025
--- /dev/null
+++ b/runtime/test/glsl/ps_conservative.frag
@@ -0,0 +1,3 @@
1#version 450
2layout(location=0) out vec4 color;
3void main() { color = vec4(1.0, 0.0, 0.0, 1.0); }
diff --git a/runtime/test/glsl/ps_sg_probe.frag b/runtime/test/glsl/ps_sg_probe.frag
index 7b4f74e1a..a2c809141 100644
--- a/runtime/test/glsl/ps_sg_probe.frag
+++ b/runtime/test/glsl/ps_sg_probe.frag
@@ -6,6 +6,9 @@
6layout(location = 0) out vec4 target; 6layout(location = 0) out vec4 target;
7 7
8void main() { 8void main() {
9 target = uintBitsToFloat(uvec4(0x40000000u | gl_SubgroupSize, 0x40000000u | gl_SubgroupInvocationID, 0x40000000u, 9 // glslang marks the subgroup built-ins RelaxedPrecision, and the Intel driver then runs the or in 16 bits and drops
10 0x40000000u)); 10 // the 0x40000000 tag. highp copies keep the full-width or.
11 highp uint size = gl_SubgroupSize;
12 highp uint lane = gl_SubgroupInvocationID;
13 target = uintBitsToFloat(uvec4(0x40000000u | size, 0x40000000u | lane, 0x40000000u, 0x40000000u));
11} 14}
diff --git a/runtime/test/glsl/vs_conservative.vert b/runtime/test/glsl/vs_conservative.vert
new file mode 100644
index 000000000..af1694475
--- /dev/null
+++ b/runtime/test/glsl/vs_conservative.vert
@@ -0,0 +1,4 @@
1#version 450
2// Synthetic screen-space coverage fixture; no game shader or user data.
3layout(location=0) in vec2 position;
4void main() { gl_Position = vec4(position, 0.5, 1.0); }
diff --git a/runtime/test/host_adapter.h b/runtime/test/host_adapter.h
new file mode 100644
index 000000000..ec1e12ba0
--- /dev/null
+++ b/runtime/test/host_adapter.h
@@ -0,0 +1,101 @@
1// Which adapter a test's host D3D12 reference devices run on, for the tests that create those devices themselves and
2// compare the layer with a hardware adapter and with WARP. copycmp::create_host (d3d12_copy_compare.h) answers the
3// same question for the tests that go through it. It reads LEONIDA_HOST_ADAPTER and matches the name through wanted()
4// and named() below, so the two cannot come to read the variable differently. The rule:
5// - LEONIDA_HOST_ADAPTER names the hardware side by part of an adapter's name, without case. A name that matches no
6// adapter ends the run with an error: a typo must not turn the comparisons into a silent pass. "warp" leaves the
7// hardware side out, since these tests always compare with WARP as well.
8// - Unset, the hardware side is the adapter behind the layer's Vulkan device (VkPhysicalDeviceIDProperties::
9// deviceLUID). On a PC with two GPUs D3D12's default adapter can be the other one, and the comparison is then
10// between the layer on one GPU and the host driver of the other. Measured with the layer on a Ryzen 7 9700X iGPU
11// (AMD 32.0.21042.62) while an RTX 3070 (NVIDIA 610.74) was the default adapter: d3d12_depth_resolve set the four
12// "D24S8 stencil as X24_G8" resolves aside as host quirks, which are NVIDIA's, and compared the four D24S8 depth
13// MIN/MAX resolves, which the Radeon's own host driver does not resolve to the clears either.
14// - The default adapter, as before, when the Vulkan device has no LUID or that adapter gives no D3D12 device.
15#pragma once
16
17#include "vk_test_device.h"
18
19#include <windows.h>
20#include <d3d12.h>
21#include <dxgi1_4.h>
22
23#include <cctype>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <string>
28
29namespace hostadapter {
30
31inline std::string description(IDXGIAdapter* adapter) {
32 DXGI_ADAPTER_DESC desc{};
33 std::string text;
34 if (adapter && SUCCEEDED(adapter->GetDesc(&desc)))
35 for (const wchar_t* c = desc.Description; *c; ++c) text += char(*c < 128 ? *c : '?');
36 return text;
37}
38
39// LEONIDA_HOST_ADAPTER in lower case; empty when it is unset.
40inline std::string wanted() {
41 char want[128] = {};
42 GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want));
43 std::string needle(want);
44 for (char& c : needle) c = char(std::tolower(static_cast<unsigned char>(c)));
45 return needle;
46}
47
48// The first adapter whose name contains `needle` (lower case), with a reference the caller releases; null when none
49// does.
50inline IDXGIAdapter1* named(IDXGIFactory1* factory, const std::string& needle) {
51 for (UINT i = 0;; ++i) {
52 IDXGIAdapter1* candidate = nullptr;
53 if (FAILED(factory->EnumAdapters1(i, &candidate))) return nullptr;
54 std::string lower = description(candidate);
55 for (char& c : lower) c = char(std::tolower(static_cast<unsigned char>(c)));
56 if (lower.find(needle) != std::string::npos) return candidate;
57 candidate->Release();
58 }
59}
60
61// The adapter for one pass of a test's `for (const bool warp : {false, true})` loop, with a reference the caller
62// releases (null: the default adapter), and the name the test prints for it. False when the pass has no adapter: no
63// WARP on this PC, or LEONIDA_HOST_ADAPTER=warp on the hardware pass.
64inline bool reference(IDXGIFactory4* factory, const vktest::Device& vk, bool warp, IDXGIAdapter** adapter,
65 std::string& name) {
66 *adapter = nullptr;
67 if (warp) {
68 name = "WARP";
69 return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(adapter)));
70 }
71 const std::string needle = wanted();
72 if (needle == "warp") return false;
73 if (!needle.empty()) {
74 if (IDXGIAdapter1* found = named(factory, needle)) {
75 name = description(found);
76 *adapter = found;
77 return true;
78 }
79 std::fprintf(stderr, "LEONIDA_HOST_ADAPTER=%s: no such adapter\n", needle.c_str());
80 std::exit(1);
81 }
82 VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
83 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
84 if (vk.physical)
85 vk.instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(vk.physical, &properties);
86 LUID luid{};
87 static_assert(sizeof(luid) == sizeof(id.deviceLUID));
88 std::memcpy(&luid, id.deviceLUID, sizeof(luid));
89 // With a null device pointer D3D12CreateDevice only says whether the adapter would give one.
90 if (id.deviceLUIDValid && SUCCEEDED(factory->EnumAdapterByLuid(luid, IID_PPV_ARGS(adapter))) &&
91 SUCCEEDED(D3D12CreateDevice(*adapter, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), nullptr))) {
92 name = description(*adapter);
93 return true;
94 }
95 if (*adapter) (*adapter)->Release();
96 *adapter = nullptr;
97 name = "the default adapter";
98 return true;
99}
100
101} // namespace hostadapter
diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp
index 73bc49206..71a5ede73 100644
--- a/runtime/test/loader_test.cpp
+++ b/runtime/test/loader_test.cpp
@@ -20,6 +20,7 @@
20 20
21#include "../shims/shims.h" 21#include "../shims/shims.h"
22#include "../src/pe_loader.h" 22#include "../src/pe_loader.h"
23#include "free_image_base.h"
23 24
24namespace { 25namespace {
25 26
@@ -56,7 +57,7 @@ std::vector<uint8_t> make_image() {
56 nt->FileHeader.NumberOfSections = 1; 57 nt->FileHeader.NumberOfSections = 1;
57 nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); 58 nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
58 nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; 59 nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
59 nt->OptionalHeader.ImageBase = 0x140000000; 60 nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x140000000);
60 nt->OptionalHeader.AddressOfEntryPoint = 0x1000; 61 nt->OptionalHeader.AddressOfEntryPoint = 0x1000;
61 nt->OptionalHeader.SizeOfHeaders = 0x200; 62 nt->OptionalHeader.SizeOfHeaders = 0x200;
62 nt->OptionalHeader.SizeOfImage = 0x2000; 63 nt->OptionalHeader.SizeOfImage = 0x2000;
@@ -101,7 +102,7 @@ std::filesystem::path write_image_as(const std::vector<uint8_t>& bytes, const st
101std::vector<uint8_t> make_forwarder_image(const char* target, uint64_t image_base) { 102std::vector<uint8_t> make_forwarder_image(const char* target, uint64_t image_base) {
102 auto img = make_image(); 103 auto img = make_image();
103 std::fill(img.begin() + 0x200, img.begin() + 0x400, uint8_t{0}); // real tables end in a zero descriptor 104 std::fill(img.begin() + 0x200, img.begin() + 0x400, uint8_t{0}); // real tables end in a zero descriptor
104 nt_of(img)->OptionalHeader.ImageBase = image_base; 105 nt_of(img)->OptionalHeader.ImageBase = leonida_test::free_image_base(image_base);
105 auto* ed = reinterpret_cast<IMAGE_EXPORT_DIRECTORY*>(img.data() + 0x200); 106 auto* ed = reinterpret_cast<IMAGE_EXPORT_DIRECTORY*>(img.data() + 0x200);
106 ed->Base = 1; 107 ed->Base = 1;
107 ed->NumberOfFunctions = 1; 108 ed->NumberOfFunctions = 1;
@@ -381,6 +382,56 @@ void test_exports() {
381 } 382 }
382} 383}
383 384
385void test_empty_named_export() {
386 const char* what = "an empty named export stays unresolved without hiding valid exports";
387 auto img = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000);
388 auto* ed = reinterpret_cast<IMAGE_EXPORT_DIRECTORY*>(img.data() + 0x200);
389 ed->NumberOfFunctions = 3;
390 ed->NumberOfNames = 3;
391 nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = 0x1A0;
392 auto* funcs = reinterpret_cast<uint32_t*>(img.data() + 0x300);
393 funcs[1] = 0;
394 funcs[2] = 0x11C0; // a code export outside the export directory
395 auto* names = reinterpret_cast<uint32_t*>(img.data() + 0x320);
396 names[0] = 0x1188;
397 names[1] = 0x1180;
398 names[2] = 0x1190;
399 auto* ords = reinterpret_cast<uint16_t*>(img.data() + 0x340);
400 ords[0] = 1;
401 ords[1] = 0;
402 ords[2] = 2;
403 std::memcpy(img.data() + 0x388, "empty\0", 6);
404 std::memcpy(img.data() + 0x390, "valid\0", 6);
405 auto provider = write_image_as(img, "empty_exports.dll");
406 try {
407 rt::Loader loader(g_dir);
408 rt::Module& m = loader.load(provider);
409 for (const char* sym : {"empty", "#2"}) {
410 bool owns = false;
411 if (m.exports.count(sym) || m.forwarders.count(sym) ||
412 loader.resolve_module_export(m.base, sym, owns) || !owns)
413 return failed(what, std::string(sym) + " did not remain absent from the mapped module");
414 }
415 for (const char* sym : {"valid", "#3", "fwd", "#1"}) {
416 bool owns = false;
417 void* expected = (std::strcmp(sym, "valid") == 0 || std::strcmp(sym, "#3") == 0)
418 ? m.base + 0x11C0 : host_symbol("kernel32.dll", "GetCurrentProcessId");
419 if (!expected || loader.resolve_module_export(m.base, sym, owns) != expected || !owns)
420 return failed(what, std::string(sym) + " no longer resolves to its valid target");
421 }
422 auto importer = write_image_as(make_import_image("empty_exports.dll", "empty"), "empty_import.exe");
423 rt::Module& importing = loader.load(importer);
424 if (importing.imports.size() != 1 || importing.imports[0].binding != rt::Binding::Unimplemented)
425 return failed(what, "an import of the empty slot did not bind as unimplemented");
426 void* bound = *reinterpret_cast<void**>(importing.base + 0x1180);
427 if (!bound || bound == m.base)
428 return failed(what, "the empty import was not given a failure thunk");
429 pass(what);
430 } catch (const std::exception& e) {
431 failed(what, e.what());
432 }
433}
434
384void test_imports() { 435void test_imports() {
385 { 436 {
386 auto img = make_image(); 437 auto img = make_image();
@@ -419,6 +470,42 @@ void test_imports() {
419 } 470 }
420} 471}
421 472
473void test_import_name_rvas() {
474 for (bool delay : {false, true}) {
475 auto img = make_import_image("testshim.dll", "F");
476 if (delay) {
477 std::fill(img.begin() + 0x200, img.begin() + 0x240, uint8_t{0});
478 auto* d = reinterpret_cast<IMAGE_DELAYLOAD_DESCRIPTOR*>(img.data() + 0x200);
479 d->Attributes.AllAttributes = 1;
480 d->DllNameRVA = 0x1060;
481 d->ImportNameTableRVA = 0x1100;
482 d->ImportAddressTableRVA = 0x1180;
483 auto* nt = nt_of(img);
484 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = {};
485 auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT];
486 dir.VirtualAddress = 0x1000;
487 dir.Size = 2 * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR);
488 }
489 const char* valid = delay ? "a valid delay-import name RVA loads" : "a valid import name RVA loads";
490 std::string error;
491 if (load(write_image(img), error) != 0)
492 failed(valid, error);
493 else
494 pass(valid);
495
496 *reinterpret_cast<uint64_t*>(img.data() + 0x300) = (1ull << 32) | 0x1120;
497 const char* invalid = delay ? "a delay-import name RVA with high bits is rejected"
498 : "an import name RVA with high bits is rejected";
499 error.clear();
500 if (load(write_image(img), error) == 0)
501 failed(invalid, "the image loaded");
502 else if (error.find("an import name runs past the image") == std::string::npos)
503 failed(invalid, error);
504 else
505 pass(invalid);
506 }
507}
508
422void test_delay_imports() { 509void test_delay_imports() {
423 { 510 {
424 auto img = make_image(); 511 auto img = make_image();
@@ -469,8 +556,6 @@ void emit_store_stub(std::vector<uint8_t>& img, size_t off, uint64_t addr, uint3
469 img[n++] = 0xC3; 556 img[n++] = 0xC3;
470} 557}
471 558
472constexpr uint64_t kInitBase = 0x140000000;
473
474// make_image() plus a TLS directory and an entry point, both aimed at real machine code: a stub that stores a 559// make_image() plus a TLS directory and an entry point, both aimed at real machine code: a stub that stores a
475// sentinel in this process, so the test can tell a callback ran rather than only that it was parsed. 560// sentinel in this process, so the test can tell a callback ran rather than only that it was parsed.
476std::vector<uint8_t> make_init_image() { 561std::vector<uint8_t> make_init_image() {
@@ -478,7 +563,8 @@ std::vector<uint8_t> make_init_image() {
478 auto* nt = nt_of(img); 563 auto* nt = nt_of(img);
479 nt->FileHeader.Characteristics |= IMAGE_FILE_DLL; 564 nt->FileHeader.Characteristics |= IMAGE_FILE_DLL;
480 nt->OptionalHeader.AddressOfEntryPoint = 0x1040; 565 nt->OptionalHeader.AddressOfEntryPoint = 0x1040;
481 auto va = [](uint32_t rva) { return kInitBase + rva; }; 566 const uint64_t base = nt->OptionalHeader.ImageBase; // the TLS callback addresses below are absolute
567 auto va = [base](uint32_t rva) { return base + rva; };
482 constexpr size_t text = 0x200; // file offset of RVA 0x1000 568 constexpr size_t text = 0x200; // file offset of RVA 0x1000
483 emit_store_stub(img, text + 0x00, reinterpret_cast<uint64_t>(&g_tls_ran), 1, 0); 569 emit_store_stub(img, text + 0x00, reinterpret_cast<uint64_t>(&g_tls_ran), 1, 0);
484 emit_store_stub(img, text + 0x40, reinterpret_cast<uint64_t>(&g_main_ran), 2, 1); 570 emit_store_stub(img, text + 0x40, reinterpret_cast<uint64_t>(&g_main_ran), 2, 1);
@@ -555,7 +641,7 @@ void test_initialise_rejects() {
555 { 641 {
556 auto img = make_init_image(); 642 auto img = make_init_image();
557 auto* callbacks = reinterpret_cast<uint64_t*>(img.data() + 0x290); // file offset of RVA 0x1090 643 auto* callbacks = reinterpret_cast<uint64_t*>(img.data() + 0x290); // file offset of RVA 0x1090
558 callbacks[0] = kInitBase + 0x9000; // well past SizeOfImage 644 callbacks[0] = nt_of(img)->OptionalHeader.ImageBase + 0x9000; // well past SizeOfImage
559 expect_init_rejects("a TLS callback outside the image is rejected", img); 645 expect_init_rejects("a TLS callback outside the image is rejected", img);
560 } 646 }
561 { 647 {
@@ -753,7 +839,7 @@ void test_process_detach_without_entry() {
753 reset_notifications(); 839 reset_notifications();
754 auto first = make_lifecycle_image(); 840 auto first = make_lifecycle_image();
755 auto second = make_image(); 841 auto second = make_image();
756 nt_of(second)->OptionalHeader.ImageBase = 0x180000000; 842 nt_of(second)->OptionalHeader.ImageBase = leonida_test::free_image_base(0x180000000);
757 nt_of(second)->FileHeader.Characteristics |= IMAGE_FILE_DLL; 843 nt_of(second)->FileHeader.Characteristics |= IMAGE_FILE_DLL;
758 emit_jump_stub(second, 0x200, reinterpret_cast<uint64_t>(&observe_dllmain)); 844 emit_jump_stub(second, 0x200, reinterpret_cast<uint64_t>(&observe_dllmain));
759 void* first_base = nullptr; 845 void* first_base = nullptr;
@@ -805,6 +891,26 @@ void test_process_detach_dependencies() {
805 g_live_modules.clear(); 891 g_live_modules.clear();
806} 892}
807 893
894// A dependency whose import table is corrupt fails while the parent binds it. Neither must stay findable by name:
895// a later load or GetModuleHandle would otherwise get a mapped image whose imports were never bound.
896void test_failed_dependency_not_registered() {
897 const char* what = "a failed load leaves neither the module nor its failed dependency loaded";
898 auto dep = make_import_image("kernel32.dll", "GetCurrentProcessId");
899 reinterpret_cast<IMAGE_IMPORT_DESCRIPTOR*>(dep.data() + 0x200)->Name = 0x5000; // past SizeOfImage
900 const auto dep_path = write_image_as(dep, "fail_dep.dll");
901 const auto parent_path = write_image_as(make_import_image("fail_dep.dll", "x"), "fail_parent.dll");
902 rt::Loader loader(g_dir);
903 auto throws = [&](const std::filesystem::path& p) {
904 try { loader.load(p); return false; } catch (const std::exception&) { return true; }
905 };
906 if (!throws(parent_path)) return failed(what, "the parent loaded over a corrupt dependency");
907 if (loader.find_loaded_module("fail_dep.dll") || loader.find_loaded_module("fail_parent.dll"))
908 return failed(what, "a failed module is still found by name");
909 if (!throws(dep_path)) return failed(what, "a second load of the dependency returned the half-loaded module");
910 if (!throws(parent_path)) return failed(what, "a second load of the parent returned the half-loaded module");
911 pass(what);
912}
913
808void test_forwarded_exports() { 914void test_forwarded_exports() {
809 { 915 {
810 const char* what = "a forwarded export binds to its target instead of into the string"; 916 const char* what = "a forwarded export binds to its target instead of into the string";
@@ -1134,7 +1240,9 @@ int main() {
1134 test_truncation(); 1240 test_truncation();
1135 test_relocations(); 1241 test_relocations();
1136 test_exports(); 1242 test_exports();
1243 test_empty_named_export();
1137 test_imports(); 1244 test_imports();
1245 test_import_name_rvas();
1138 test_delay_imports(); 1246 test_delay_imports();
1139 test_initialise(); 1247 test_initialise();
1140 test_initialise_rejects(); 1248 test_initialise_rejects();
@@ -1142,6 +1250,7 @@ int main() {
1142 test_process_detach_invalid_tls(); 1250 test_process_detach_invalid_tls();
1143 test_process_detach_without_entry(); 1251 test_process_detach_without_entry();
1144 test_process_detach_dependencies(); 1252 test_process_detach_dependencies();
1253 test_failed_dependency_not_registered();
1145 test_delay_descriptor_fields(); 1254 test_delay_descriptor_fields();
1146 test_forwarded_exports(); 1255 test_forwarded_exports();
1147 test_export_bounds(); 1256 test_export_bounds();
diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp
index 8b7b7b179..6d5a06dd3 100644
--- a/runtime/test/loader_tls_test.cpp
+++ b/runtime/test/loader_tls_test.cpp
@@ -443,6 +443,149 @@ void test_multiple_tls_modules(const fs::path& dll, const fs::path& temp) {
443 } 443 }
444} 444}
445 445
446// A worker thread that outlives Loader #1 keeps an orphaned g_thread_tls_slots[slot] record until it exits.
447// Even if Loader #2 reuses the same TLS slot (and even the same Module* address), the generation token must
448// prevent Loader #2 from mistaking the orphaned entry for its own on install_tls_for_thread or DLL_THREAD_DETACH.
449void test_orphan_slot_generation_reuse(const fs::path& dll) {
450 std::printf("\n-- orphan thread slot generation vs reused slot --\n");
451 HANDLE ready = CreateEventW(nullptr, TRUE, FALSE, nullptr);
452 HANDLE go = CreateEventW(nullptr, TRUE, FALSE, nullptr);
453 struct Ctx {
454 HANDLE ready;
455 HANDLE go;
456 } ctx{ready, go};
457
458 HANDLE thread = nullptr;
459 uint32_t old_slot = rt::kNoTlsIndex;
460 {
461 rt::Loader loader1(dll.parent_path());
462 rt::Module& m1 = loader1.load(dll);
463 loader1.initialise();
464 old_slot = m1.tls_slot;
465 thread = CreateThread(
466 nullptr, 0,
467 [](void* p) -> DWORD {
468 auto* c = static_cast<Ctx*>(p);
469 SetEvent(c->ready);
470 WaitForSingleObject(c->go, INFINITE);
471 return 0;
472 },
473 &ctx, 0, nullptr);
474 WaitForSingleObject(ready, INFINITE);
475 } // loader1 destroyed while worker thread is still alive
476
477 rt::Loader loader2(dll.parent_path());
478 rt::Module& m2 = loader2.load(dll);
479 loader2.initialise();
480 check(m2.tls_slot == old_slot, "second loader reuses the released TLS slot");
481
482 auto watch = find_export<void(__cdecl*)(DWORD)>(m2, "tiny_tls_watch_thread");
483 auto td = find_export<int(__cdecl*)()>(m2, "tiny_tls_thread_detach_count");
484 watch(GetThreadId(thread));
485
486 SetEvent(go);
487 WaitForSingleObject(thread, INFINITE);
488 CloseHandle(thread);
489 CloseHandle(go);
490 CloseHandle(ready);
491
492 check(td() == 0, "orphaned worker exit does not dispatch DLL_THREAD_DETACH to the new generation's module");
493}
494
495// Spawns cmd.exe to obtain one guaranteed-dead PID and one guaranteed-live one for the purge-ownership checks.
496struct ChildProcess {
497 HANDLE process = nullptr;
498 DWORD pid = 0;
499 explicit ChildProcess(const wchar_t* args) {
500 STARTUPINFOW si{};
501 si.cb = sizeof(si);
502 PROCESS_INFORMATION pi{};
503 std::wstring cmd = std::wstring(L"cmd.exe ") + args;
504 if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
505 &pi))
506 throw std::runtime_error("CreateProcessW for cmd.exe failed");
507 CloseHandle(pi.hThread);
508 process = pi.hProcess;
509 pid = pi.dwProcessId;
510 }
511 ChildProcess(const ChildProcess&) = delete;
512 ChildProcess& operator=(const ChildProcess&) = delete;
513 void wait_exit() {
514 WaitForSingleObject(process, INFINITE);
515 CloseHandle(process);
516 process = nullptr;
517 }
518 ~ChildProcess() {
519 if (process) {
520 TerminateProcess(process, 0);
521 WaitForSingleObject(process, INFINITE);
522 CloseHandle(process);
523 }
524 }
525};
526
527// Clone files live in the temp root (the loader's clone directory), named with this process's PID.
528std::vector<fs::path> own_clone_files() {
529 const std::wstring own = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_";
530 std::vector<fs::path> found;
531 WIN32_FIND_DATAW fd{};
532 HANDLE h = FindFirstFileW((fs::temp_directory_path() / (own + L"*.dll")).c_str(), &fd);
533 if (h == INVALID_HANDLE_VALUE) return found;
534 do {
535 if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
536 found.push_back(fs::temp_directory_path() / fd.cFileName);
537 } while (FindNextFileW(h, &fd));
538 FindClose(h);
539 return found;
540}
541
542// The startup purge must delete only clones whose owning process is gone and that nothing holds open: a concurrent
543// process between its CopyFileW and its LoadLibraryExW must keep its file. Runs before any other clone-creating
544// test, because the sweep fires once per process.
545void test_purge_ownership_scoping(const fs::path& dll, const fs::path& temp) {
546 std::printf("\n-- startup purge deletes only ownerless clones --\n");
547 ChildProcess dead(L"/c exit 0");
548 dead.wait_exit();
549 ChildProcess live(L"/c timeout /t 30 /nobreak > nul");
550
551 const fs::path clone_root = fs::temp_directory_path();
552 // An own-PID name stands in for a leftover of a dead run whose PID this process reused: the sweep runs before
553 // this process has created any clone, so such a file is always ownerless here.
554 const fs::path stale_file = clone_root / (L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_31.dll");
555 const fs::path held_file = clone_root / (L"leonida_tls_host_" + std::to_wstring(dead.pid) + L"_32.dll");
556 const fs::path live_file = clone_root / (L"leonida_tls_host_" + std::to_wstring(live.pid) + L"_33.dll");
557 const char bytes[8] = "purgeXX";
558 write_file(stale_file, bytes, 8);
559 write_file(held_file, bytes, 8);
560 write_file(live_file, bytes, 8);
561 // An open handle without FILE_SHARE_DELETE stands in for another process's guard or mapped image: the purge's
562 // exclusive-open probe must fail against it.
563 HANDLE held = CreateFileW(held_file.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
564 FILE_ATTRIBUTE_NORMAL, nullptr);
565 check(held != INVALID_HANDLE_VALUE, "opened the held clone stand-in without FILE_SHARE_DELETE");
566
567 const fs::path second = temp / "tiny_tls_purge_second.dll";
568 check(CopyFileW(dll.c_str(), second.c_str(), FALSE) != 0, "copied the TLS fixture for the purge test");
569 {
570 rt::Loader loader(dll.parent_path());
571 rt::Module& first = loader.load(dll); // slot 0: primary helper, no clone
572 rt::Module& mapped_second = loader.load(second); // slot 1: clone; the purge sweep runs here
573 check(first.tls_index != rt::kNoTlsIndex && mapped_second.tls_index != rt::kNoTlsIndex,
574 "the purge test loads two simultaneous TLS modules");
575 }
576 const auto clone_of_this_process = own_clone_files();
577 check(clone_of_this_process.size() == 1, "this process owns exactly one clone file after the two-module load");
578
579 check(!fs::exists(stale_file), "the purge deleted the clone whose owner process is gone");
580 check(fs::exists(held_file), "the purge skipped the clone another handle holds open");
581 check(fs::exists(live_file), "the purge skipped the clone whose owner process is still alive");
582
583 CloseHandle(held);
584 std::error_code ec;
585 fs::remove(held_file, ec);
586 fs::remove(live_file, ec);
587}
588
446void print_result() { 589void print_result() {
447 if (g_failures == 0) 590 if (g_failures == 0)
448 std::printf("\nloader_tls_test: OK (%d checks)\n", g_checks); 591 std::printf("\nloader_tls_test: OK (%d checks)\n", g_checks);
@@ -470,10 +613,18 @@ int main(int argc, char** argv) {
470 } 613 }
471 614
472 TempDir temp; 615 TempDir temp;
616 test_purge_ownership_scoping(tls_dll, temp.path); // first: the sweep fires once per process
473 test_tls(tls_dll); 617 test_tls(tls_dll);
474 test_thread_events(tls_dll); 618 test_thread_events(tls_dll);
475 test_thread_outlives_loader(tls_dll); 619 test_thread_outlives_loader(tls_dll);
476 test_multiple_tls_modules(tls_dll, temp.path); 620 test_multiple_tls_modules(tls_dll, temp.path);
621 test_orphan_slot_generation_reuse(tls_dll);
622
623 // The --run path calls cleanup_tls_clones() before ExitProcess because atexit never runs there.
624 std::printf("\n-- explicit clone cleanup (the ExitProcess path) --\n");
625 check(!own_clone_files().empty(), "TLS helper clone files exist before explicit cleanup");
626 rt::cleanup_tls_clones();
627 check(own_clone_files().empty(), "cleanup_tls_clones deletes every clone file of this process");
477 } catch (const std::exception& e) { 628 } catch (const std::exception& e) {
478 ++g_checks; 629 ++g_checks;
479 ++g_failures; 630 ++g_failures;
diff --git a/runtime/test/process_cmdline_test.cpp b/runtime/test/process_cmdline_test.cpp
index 01f1b38a5..79aeed11b 100644
--- a/runtime/test/process_cmdline_test.cpp
+++ b/runtime/test/process_cmdline_test.cpp
@@ -193,6 +193,17 @@ int main() {
193 // A byte above 0x7f in the narrow program name is part of the name, not the end of it. 193 // A byte above 0x7f in the narrow program name is part of the name, not the end of it.
194 check_winmain(L"caf\u00e9.exe", {L"-x"}, L"-x", "a non-ASCII program name"); 194 check_winmain(L"caf\u00e9.exe", {L"-x"}, L"-x", "a non-ASCII program name");
195 195
196 // If the entry thread exits via ExitThread() without going through end_run(), run_entry() must preserve its exit
197 // code (and claim g_exited before closing g_done).
198 {
199 auto exit_thread_entry = +[](void*) -> DWORD { ExitThread(42); };
200 const int code = rt::process::run_entry(reinterpret_cast<void*>(exit_thread_entry), 0);
201 if (code != 42) {
202 std::fprintf(stderr, "FAIL run_entry with ExitThread(42) returned %d, want 42\n", code);
203 ++failures;
204 }
205 }
206
196 if (failures) return 1; 207 if (failures) return 1;
197 std::printf("process_cmdline: GetCommandLineW parses back to __wargv, non-ASCII arguments intact (code page %u); " 208 std::printf("process_cmdline: GetCommandLineW parses back to __wargv, non-ASCII arguments intact (code page %u); "
198 "the WinMain line and the kernelbase/API-set names are the game's\n", 209 "the WinMain line and the kernelbase/API-set names are the game's\n",
diff --git a/runtime/test/replay_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp
index 8e85452bc..f3eb316c1 100644
--- a/runtime/test/replay_cpu_bench.cpp
+++ b/runtime/test/replay_cpu_bench.cpp
@@ -8,8 +8,8 @@
8// Two measurements: 8// Two measurements:
9// - per command type: a list of N commands of one kind (transitions come in pairs, queries as Begin+End), 9// - per command type: a list of N commands of one kind (transitions come in pairs, queries as Begin+End),
10// timed on its own, so one slow kind stands out; 10// timed on its own, so one slow kind stands out;
11// - a frame: L lists of P passes, each pass a mix of what a frame without draws records today (barriers, 11// - a frame: L lists of P passes, each pass a mix of what a frame records (barriers, whole-view and rectangle
12// whole-view and rectangle clears, buffer and texture copies, a UAV clear, queries and predication). 12// clears, buffer and texture copies, a UAV clear, queries, predication and indexed and non-indexed draws).
13// prepare includes refilling the PreparedList storage kept from the last execution (as VulkanQueue::execute keeps 13// prepare includes refilling the PreparedList storage kept from the last execution (as VulkanQueue::execute keeps
14// prepared_) and planning the query batch. emit includes committing query state, as execute does. 14// prepared_) and planning the query batch. emit includes committing query state, as execute does.
15// Each figure is the median over --reps runs after --warmup runs. Heap allocations (global operator new) and 15// Each figure is the median over --reps runs after --warmup runs. Heap allocations (global operator new) and
@@ -17,8 +17,6 @@
17// 17//
18// Usage: 18// Usage:
19// replay_cpu_bench [--lists L] [--passes P] [--count N] [--reps R] [--warmup W] [--csv] [--self-test] 19// replay_cpu_bench [--lists L] [--passes P] [--count N] [--reps R] [--warmup W] [--csv] [--self-test]
20//
21// Draws join the frame once the draw path (#291) is on main.
22#ifndef VK_NO_PROTOTYPES 20#ifndef VK_NO_PROTOTYPES
23#define VK_NO_PROTOTYPES 21#define VK_NO_PROTOTYPES
24#endif 22#endif
@@ -104,6 +102,14 @@ struct Scene {
104 VkImageView> 102 VkImageView>
105 views; 103 views;
106 QueryPool occlusion, timestamps; 104 QueryPool occlusion, timestamps;
105 // One graphics pipeline: an RGBA8 target, D32 depth and two vertex input slots, as VulkanContext keeps them.
106 GraphicsPipeline pipeline;
107 static constexpr std::uintptr_t pipeline_id = 0x7000;
108 // A second one with no depth and one vertex slot, for the self-test's draw-storage check.
109 GraphicsPipeline bare;
110 static constexpr std::uintptr_t bare_id = 0x7001;
111 static constexpr std::uint64_t geometry_va = 0x100000000ull; // a 16 MiB vertex and index arena
112 static constexpr std::uint64_t geometry_size = 16ull << 20;
107 LayoutTracker tracker; 113 LayoutTracker tracker;
108 ReplayFunctions vk; 114 ReplayFunctions vk;
109 115
@@ -184,6 +190,47 @@ struct Scene {
184 if (id == timestamp_heap) return &timestamps; 190 if (id == timestamp_heap) return &timestamps;
185 return nullptr; 191 return nullptr;
186 }; 192 };
193
194 pipeline.pipeline = fake_handle<VkPipeline>(0x6000);
195 pipeline.layout = fake_handle<VkPipelineLayout>(0x6001);
196 pipeline.push_stages = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
197 pipeline.color_formats = {rgba8};
198 pipeline.depth_format = VK_FORMAT_D32_SFLOAT;
199 pipeline.depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT;
200 pipeline.vertex_slots = 0b11;
201 pipeline.variant = [](std::uint32_t) { return fake_handle<VkPipeline>(0x6002); };
202 bare.pipeline = fake_handle<VkPipeline>(0x6010);
203 bare.layout = pipeline.layout;
204 bare.push_stages = pipeline.push_stages;
205 bare.color_formats = {rgba8};
206 bare.vertex_slots = 0b1;
207 vk.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* {
208 if (id == pipeline_id) return &pipeline;
209 if (id == bare_id) return &bare;
210 return nullptr;
211 };
212 vk.buffer_at = [](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) {
213 if (va < geometry_va || va >= geometry_va + geometry_size) return false;
214 buffer = fake_handle<VkBuffer>(0x2100);
215 offset = va - geometry_va;
216 size = std::min<std::uint64_t>(size, geometry_va + geometry_size - va);
217 return true;
218 };
219 vk.zero_buffer = fake_handle<VkBuffer>(0x2101);
220 vk.zero_size = 65536;
221 vk.bind_pipeline = nop<PFN_vkCmdBindPipeline>();
222 vk.push_constants = nop<PFN_vkCmdPushConstants>();
223 vk.bind_descriptor_sets = nop<PFN_vkCmdBindDescriptorSets>();
224 vk.bind_vertex_buffers2 = nop<PFN_vkCmdBindVertexBuffers2>();
225 vk.bind_index_buffer = nop<PFN_vkCmdBindIndexBuffer>();
226 vk.set_viewport = nop<PFN_vkCmdSetViewport>();
227 vk.set_scissor = nop<PFN_vkCmdSetScissor>();
228 vk.set_primitive_topology = nop<PFN_vkCmdSetPrimitiveTopology>();
229 vk.set_primitive_restart_enable = nop<PFN_vkCmdSetPrimitiveRestartEnable>();
230 vk.set_stencil_reference = nop<PFN_vkCmdSetStencilReference>();
231 vk.set_blend_constants = nop<PFN_vkCmdSetBlendConstants>();
232 vk.draw = nop<PFN_vkCmdDraw>();
233 vk.draw_indexed = nop<PFN_vkCmdDrawIndexed>();
187 } 234 }
188 235
189 const ResourceBinding* resolve(ResourceId id) const { 236 const ResourceBinding* resolve(ResourceId id) const {
@@ -224,6 +271,27 @@ bool uav_clear(CommandList& list, std::uint32_t index) {
224 return list.clear_unordered_access(view, false, {index, 0, 0, 0}); 271 return list.clear_unordered_access(view, false, {index, 0, 0, 0});
225} 272}
226 273
274// A draw into the colour and depth targets, as a scene's mesh draws are: two vertex streams, and for `indexed`
275// a 16-bit index buffer; each draw reads its own part of the geometry arena.
276bool draw(CommandList& list, std::uint32_t index, bool indexed) {
277 Draw d{};
278 d.pipeline = Scene::pipeline_id;
279 d.render_targets = {color_view};
280 d.depth = depth_view;
281 const std::uint64_t base = Scene::geometry_va + (index % 256) * 65536ull;
282 d.vertex_buffers[0] = {base, 24576, 12}; // by input slot, inlined since D3D-289
283 d.vertex_buffers[1] = {base + 24576, 16384, 8};
284 if (indexed) d.index = {base + 40960, 6144, 57};
285 d.topology = 4; // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST
286 d.viewport = {0, 0, 1920, 1080, 0, 1};
287 d.scissor = {0, 0, 1920, 1080};
288 d.blend_factor = {1, 1, 1, 1};
289 d.indexed = indexed;
290 d.count = indexed ? 3072 : 2048;
291 d.instances = 1;
292 return list.draw(d);
293}
294
227const Kind kinds[] = { 295const Kind kinds[] = {
228 {"transition pair", 296 {"transition pair",
229 [](CommandList& l, std::uint32_t) { 297 [](CommandList& l, std::uint32_t) {
@@ -267,6 +335,8 @@ const Kind kinds[] = {
267 return l.resolve_queries({Scene::occlusion_heap, q::binary_occlusion, first, 16, Scene::results, first * 8ull}); 335 return l.resolve_queries({Scene::occlusion_heap, q::binary_occlusion, first, 16, Scene::results, first * 8ull});
268 }, 336 },
269 1}, 337 1},
338 {"draw", [](CommandList& l, std::uint32_t i) { return draw(l, i, false); }, 1},
339 {"draw indexed", [](CommandList& l, std::uint32_t i) { return draw(l, i, true); }, 1},
270 {"predication on+off", 340 {"predication on+off",
271 [](CommandList& l, std::uint32_t) { 341 [](CommandList& l, std::uint32_t) {
272 return l.set_predication({Scene::predicate, 0, d3d12_predication::equal_zero}) && 342 return l.set_predication({Scene::predicate, 0, d3d12_predication::equal_zero}) &&
@@ -275,14 +345,20 @@ const Kind kinds[] = {
275 2}, 345 2},
276}; 346};
277 347
278// One pass of the frame: what a render pass without draws records today. 348// Draws per pass; a frame's draws outnumber its other commands.
349constexpr std::uint32_t draws_per_pass = 16;
350
351// One pass of the frame.
279bool frame_pass(CommandList& l, std::uint32_t pass) { 352bool frame_pass(CommandList& l, std::uint32_t pass) {
280 const std::uint32_t query = (pass * 2) % Scene::queries; 353 const std::uint32_t query = (pass * 2) % Scene::queries;
281 return l.end_query({Scene::timestamp_heap, q::timestamp, query}) && 354 bool ok = l.end_query({Scene::timestamp_heap, q::timestamp, query}) &&
282 l.transition({Scene::color, all_subresources, s::pixel_shader_resource, s::render_target}) && 355 l.transition({Scene::color, all_subresources, s::pixel_shader_resource, s::render_target}) &&
283 l.clear_render_target(color_view, black) && l.clear_depth_stencil(depth_view, clear_depth, 1, 0) && 356 l.clear_render_target(color_view, black) && l.clear_depth_stencil(depth_view, clear_depth, 1, 0) &&
284 l.begin_query({Scene::occlusion_heap, q::binary_occlusion, query}) && 357 l.begin_query({Scene::occlusion_heap, q::binary_occlusion, query}) &&
285 l.clear_render_target(color_view, black, two_rects) && 358 l.clear_render_target(color_view, black, two_rects);
359 for (std::uint32_t i = 0; ok && i < draws_per_pass; ++i)
360 ok = draw(l, pass * draws_per_pass + i, i % 4 != 3); // three of four indexed
361 return ok &&
286 l.end_query({Scene::occlusion_heap, q::binary_occlusion, query}) && 362 l.end_query({Scene::occlusion_heap, q::binary_occlusion, query}) &&
287 l.transition({Scene::color, all_subresources, s::render_target, s::pixel_shader_resource}) && 363 l.transition({Scene::color, all_subresources, s::render_target, s::pixel_shader_resource}) &&
288 l.copy_buffer({Scene::constants, (pass % 256) * 256ull, Scene::upload, (pass % 4096) * 256ull, 256}) && 364 l.copy_buffer({Scene::constants, (pass % 256) * 256ull, Scene::upload, (pass % 4096) * 256ull, 256}) &&
@@ -496,6 +572,32 @@ int main(int argc, char** argv) {
496 const Result f = run(scene, lists, frame, reps, warmup); 572 const Result f = run(scene, lists, frame, reps, warmup);
497 check("frame", f); 573 check("frame", f);
498 if (self_test) { 574 if (self_test) {
575 // A PreparedList keeps its draws' storage from one execution to the next. A draw prepared in an entry an
576 // indexed draw with depth used before must not keep that draw's depth attachment or index buffer.
577 CommandList earlier, later;
578 Draw plain{};
579 plain.pipeline = Scene::bare_id;
580 plain.render_targets = {color_view};
581 plain.topology = 4;
582 plain.viewport = {0, 0, 1920, 1080, 0, 1};
583 plain.scissor = {0, 0, 1920, 1080};
584 plain.count = 3;
585 plain.instances = 1;
586 PreparedList prepared;
587 const auto resolve = [&scene](ResourceId id) { return scene.resolve(id); };
588 const bool recorded = draw(earlier, 0, true) && draw(earlier, 1, true) && earlier.close() &&
589 later.draw(plain) && later.close();
590 const bool replayed = recorded && prepare(earlier, resolve, scene.vk, prepared) == ReplayResult::success &&
591 prepare(later, resolve, scene.vk, prepared) == ReplayResult::success;
592 const detail::PreparedDraw* d =
593 replayed && prepared.draw_count == 1 ? &prepared.draws[prepared.commands[0].draw] : nullptr;
594 if (!d || d->graphics != &scene.bare || d->pipeline != scene.bare.pipeline || d->depth.id ||
595 d->index_buffer || d->vertex_buffers.size() != 1 || d->vertex_buffers[0] != scene.vk.zero_buffer ||
596 d->colors.size() != 1 || d->colors[0].id != Scene::color) {
597 std::fprintf(stderr, "FAIL draw storage: a draw kept state from the draw prepared there before\n");
598 ++failures;
599 }
600
499 // The counts don't depend on timing: a second run must make exactly the same allocations and calls. 601 // The counts don't depend on timing: a second run must make exactly the same allocations and calls.
500 const Result again = run(scene, lists, frame, reps, warmup); 602 const Result again = run(scene, lists, frame, reps, warmup);
501 if (again.emit.vk_calls != f.emit.vk_calls || again.prepare.allocations != f.prepare.allocations) { 603 if (again.emit.vk_calls != f.emit.vk_calls || again.prepare.allocations != f.prepare.allocations) {
diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp
index 6b59c0245..35818fe8e 100644
--- a/runtime/test/replay_uav_clear_offset_test.cpp
+++ b/runtime/test/replay_uav_clear_offset_test.cpp
@@ -13,6 +13,7 @@ namespace {
13struct Write { 13struct Write {
14 char kind; // 'f' fill, 'u' update, 'c' copy (dst; src in from) 14 char kind; // 'f' fill, 'u' update, 'c' copy (dst; src in from)
15 VkDeviceSize offset, size, from; 15 VkDeviceSize offset, size, from;
16 VkBuffer buffer = VK_NULL_HANDLE, source = VK_NULL_HANDLE;
16}; 17};
17std::vector<Write> writes; 18std::vector<Write> writes;
18 19
@@ -37,14 +38,14 @@ void reset_texture_capture() {
37VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, 38VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags,
38 std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, 39 std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*,
39 std::uint32_t, const VkImageMemoryBarrier*) {} 40 std::uint32_t, const VkImageMemoryBarrier*) {}
40VKAPI_ATTR void VKAPI_CALL fill(VkCommandBuffer, VkBuffer, VkDeviceSize offset, VkDeviceSize size, std::uint32_t) { 41VKAPI_ATTR void VKAPI_CALL fill(VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, std::uint32_t) {
41 writes.push_back({'f', offset, size, 0}); 42 writes.push_back({'f', offset, size, 0, buffer});
42} 43}
43VKAPI_ATTR void VKAPI_CALL update(VkCommandBuffer, VkBuffer, VkDeviceSize offset, VkDeviceSize size, const void*) { 44VKAPI_ATTR void VKAPI_CALL update(VkCommandBuffer, VkBuffer, VkDeviceSize offset, VkDeviceSize size, const void*) {
44 writes.push_back({'u', offset, size, 0}); 45 writes.push_back({'u', offset, size, 0});
45} 46}
46VKAPI_ATTR void VKAPI_CALL copy(VkCommandBuffer, VkBuffer, VkBuffer, std::uint32_t count, const VkBufferCopy* r) { 47VKAPI_ATTR void VKAPI_CALL copy(VkCommandBuffer, VkBuffer source, VkBuffer buffer, std::uint32_t count, const VkBufferCopy* r) {
47 for (std::uint32_t i = 0; i < count; ++i) writes.push_back({'c', r[i].dstOffset, r[i].size, r[i].srcOffset}); 48 for (std::uint32_t i = 0; i < count; ++i) writes.push_back({'c', r[i].dstOffset, r[i].size, r[i].srcOffset, buffer, source});
48} 49}
49VKAPI_ATTR void VKAPI_CALL clear_image(VkCommandBuffer, VkImage, VkImageLayout, const VkClearColorValue* value, 50VKAPI_ATTR void VKAPI_CALL clear_image(VkCommandBuffer, VkImage, VkImageLayout, const VkClearColorValue* value,
50 std::uint32_t, const VkImageSubresourceRange*) { 51 std::uint32_t, const VkImageSubresourceRange*) {
@@ -126,6 +127,55 @@ int main() {
126 "rectangle clear replays"); 127 "rectangle clear replays");
127 expect(inside(at + 16, at + 28), "elements 2..5 of a view at 8 are [at + 16, at + 28)"); 128 expect(inside(at + 16, at + 28), "elements 2..5 of a view at 8 are [at + 16, at + 28)");
128 129
130 const auto scratch = reinterpret_cast<VkBuffer>(std::uintptr_t{0x3000});
131 constexpr VkDeviceSize scratch_at = 512;
132 unsigned allocations = 0;
133 expect(run({1, true, VK_FORMAT_R8_UINT, 1, 1, 1, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
134 "short clear without scratch is rejected before any command is emitted");
135 vk.copy_scratch = [&](VkDeviceSize size, VkBuffer& buffer, VkDeviceSize& offset) {
136 expect(size == 8, "short clear requests eight scratch bytes");
137 ++allocations;
138 buffer = scratch;
139 offset = scratch_at;
140 return true;
141 };
142 for (VkDeviceSize offset = 0; offset < 8; ++offset) {
143 for (VkDeviceSize size = 1; size <= 8; ++size) {
144 allocations = 0;
145 expect(run({1, true, VK_FORMAT_R8_UINT, offset, size, 1, 0, 0, 1}) == ReplayResult::success,
146 "small R8 range replays at every word phase");
147 const bool short_range = size < (4 - offset % 4) % 4 + 4;
148 expect(allocations == unsigned(short_range), "only ranges lacking an aligned word allocate scratch");
149 if (short_range) {
150 expect(writes.size() == 2 && writes[0].kind == 'f' && writes[0].buffer == scratch &&
151 writes[0].offset == scratch_at && writes[0].size == 8 &&
152 writes[1].kind == 'c' && writes[1].source == scratch && writes[1].buffer == range.buffer &&
153 writes[1].from == scratch_at && writes[1].offset == at + offset && writes[1].size == size,
154 "short clear writes exactly the requested bytes from scratch, not neighbouring resource bytes");
155 } else expect(inside(at + offset, at + offset + size), "fast path stays within the range");
156 }
157 }
158 allocations = 0;
159 const std::array<Rect, 3> small_rects{{{0, 0, 1, 1}, {0, 0, 2, 1}, {3, 0, 4, 1}}};
160 expect(run({1, true, VK_FORMAT_R16_UINT, 2, 8, 2, 0, 0, 1}, small_rects) == ReplayResult::success && allocations == 1,
161 "overlapping short R16 rectangles share one scratch allocation per clear");
162 vk.copy_scratch = [](VkDeviceSize, VkBuffer&, VkDeviceSize&) { return false; };
163 expect(run({1, true, VK_FORMAT_R8_UINT, 255, 1, 1, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
164 "scratch allocation failure rejects the list without emitting commands");
165 vk.copy_scratch = [&](VkDeviceSize, VkBuffer& buffer, VkDeviceSize& offset) {
166 buffer = scratch; offset = 1; return true;
167 };
168 expect(run({1, true, VK_FORMAT_R8_UINT, 255, 1, 1, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
169 "misaligned scratch is rejected before vkCmdFillBuffer");
170 const std::array<Rect, 2> empty_rects{{{-3, 0, 0, 1}, {0, 1, 1, 2}}};
171 expect(run({1, true, VK_FORMAT_R8_UINT, 255, 1, 1, 0, 0, 1}, empty_rects) == ReplayResult::success && writes.empty(),
172 "empty clipped rectangles need no scratch");
173 range.buffer_offset = UINT64_MAX - 2;
174 expect(run({1, true, VK_FORMAT_R8_UINT, 1, 2, 1, 0, 0, 1}) == ReplayResult::invalid_clear && writes.empty(),
175 "backing range overflow is rejected before scratch allocation or emission");
176 range.buffer_offset = at;
177 vk.copy_scratch = {};
178
129 // Typeless / mutable texture UAV clears where view_format != binding.format must clear through an attachment view 179 // Typeless / mutable texture UAV clears where view_format != binding.format must clear through an attachment view
130 // of view_format with clear_color decoded in view_format, avoiding SFLOAT NaN round-trips (issue #1902). 180 // of view_format with clear_color decoded in view_format, avoiding SFLOAT NaN round-trips (issue #1902).
131 ReplayFunctions tex_vk = vk; 181 ReplayFunctions tex_vk = vk;
diff --git a/runtime/test/resource_tiling_test.cpp b/runtime/test/resource_tiling_test.cpp
index 9bbcfbf3a..ad9a9a8d7 100644
--- a/runtime/test/resource_tiling_test.cpp
+++ b/runtime/test/resource_tiling_test.cpp
@@ -1,8 +1,8 @@
1// GetResourceTiling's arithmetic (src/resource_tiling.h), without a GPU. The expected tile shapes, standard mip 1// GetResourceTiling's arithmetic (src/resource_tiling.h), without a GPU. The expected tile shapes, per-mip tile
2// counts, per-mip tile counts and start indices are what the PC D3D12 runtime reported for the same reserved 2// counts and start indices are what the PC D3D12 runtime reported for the same reserved resources on an RTX 5070.
3// resources on an RTX 5070; packed-tile counts are this layer's own rule (tight linear size in whole tiles), and 3// Where the packed tail starts and how many tiles it takes follow AMD's PC runtime (D3D-65): the AmdCase table holds
4// where the PC runtime chose differently the comment says so. d3d12_vulkan_device_test makes the same comparison 4// AMD's values, and where another runtime chose differently the comment says so. d3d12_vulkan_device_test makes the
5// against the host runtime on the machine it runs on. 5// same comparison against the host runtime on the machine it runs on.
6#include "../src/resource_tiling.h" 6#include "../src/resource_tiling.h"
7 7
8#include <cstdio> 8#include <cstdio>
@@ -111,7 +111,7 @@ int main() {
111 // AMD's split (D3D-65). Every layout below was measured on the AMD PC runtime and is identical on an RX 9070 XT 111 // AMD's split (D3D-65). Every layout below was measured on the AMD PC runtime and is identical on an RX 9070 XT
112 // (RDNA4, driver 32.0.31041.1004) and a Ryzen 7 9800X3D iGPU (RDNA2, 32.0.21045.5002): compare_tiling's 17 texture 112 // (RDNA4, driver 32.0.31041.1004) and a Ryzen 7 9800X3D iGPU (RDNA2, 32.0.21045.5002): compare_tiling's 17 texture
113 // layouts, then 30 edge cases (a mip exactly at or just past half a tile, thin and tall textures, non-square 2D and 113 // layouts, then 30 edge cases (a mip exactly at or just past half a tile, thin and tall textures, non-square 2D and
114 // volume tiles), then 36 volumes whose packed tail is deeper than a tile. Every field is AMD's: the standard and 114 // volume tiles), then 32 volumes whose packed tail is deeper than a tile. Every field is AMD's: the standard and
115 // packed mip counts, the packed start, and the packed tiles, one per tile-depth slice the tail spans. 115 // packed mip counts, the packed start, and the packed tiles, one per tile-depth slice the tail spans.
116 struct AmdCase { 116 struct AmdCase {
117 const char* name; 117 const char* name;
@@ -171,14 +171,11 @@ int main() {
171 {"8x8x32 R8 vol", {TiledKind::texture3d, 8, 8, 32, 6, 1, 1}, 0, 6, 1, 0}, 171 {"8x8x32 R8 vol", {TiledKind::texture3d, 8, 8, 32, 6, 1, 1}, 0, 6, 1, 0},
172 {"8x8x33 R8 vol", {TiledKind::texture3d, 8, 8, 33, 6, 1, 1}, 0, 6, 2, 0}, 172 {"8x8x33 R8 vol", {TiledKind::texture3d, 8, 8, 33, 6, 1, 1}, 0, 6, 2, 0},
173 {"8x8x48 R8 vol", {TiledKind::texture3d, 8, 8, 48, 6, 1, 1}, 0, 6, 2, 0}, 173 {"8x8x48 R8 vol", {TiledKind::texture3d, 8, 8, 48, 6, 1, 1}, 0, 6, 2, 0},
174 {"8x8x64 R8 vol", {TiledKind::texture3d, 8, 8, 64, 7, 1, 1}, 0, 7, 2, 0},
175 {"8x8x65 R8 vol", {TiledKind::texture3d, 8, 8, 65, 7, 1, 1}, 0, 7, 3, 0}, 174 {"8x8x65 R8 vol", {TiledKind::texture3d, 8, 8, 65, 7, 1, 1}, 0, 7, 3, 0},
176 {"8x8x96 R8 vol", {TiledKind::texture3d, 8, 8, 96, 7, 1, 1}, 0, 7, 3, 0}, 175 {"8x8x96 R8 vol", {TiledKind::texture3d, 8, 8, 96, 7, 1, 1}, 0, 7, 3, 0},
177 {"8x8x128 R8 vol", {TiledKind::texture3d, 8, 8, 128, 8, 1, 1}, 0, 8, 4, 0}, 176 {"8x8x128 R8 vol", {TiledKind::texture3d, 8, 8, 128, 8, 1, 1}, 0, 8, 4, 0},
178 {"8x8x129 R8 vol", {TiledKind::texture3d, 8, 8, 129, 8, 1, 1}, 0, 8, 5, 0}, 177 {"8x8x129 R8 vol", {TiledKind::texture3d, 8, 8, 129, 8, 1, 1}, 0, 8, 5, 0},
179 {"8x8x256 R8 vol", {TiledKind::texture3d, 8, 8, 256, 9, 1, 1}, 0, 9, 8, 0}, 178 {"8x8x256 R8 vol", {TiledKind::texture3d, 8, 8, 256, 9, 1, 1}, 0, 9, 8, 0},
180 {"16x16x16 RGBA8 vol", {TiledKind::texture3d, 16, 16, 16, 5, 4, 1}, 0, 5, 1, 0},
181 {"16x16x17 RGBA8 vol", {TiledKind::texture3d, 16, 16, 17, 5, 4, 1}, 0, 5, 2, 0},
182 {"16x16x32 RGBA8 vol", {TiledKind::texture3d, 16, 16, 32, 6, 4, 1}, 0, 6, 2, 0}, 179 {"16x16x32 RGBA8 vol", {TiledKind::texture3d, 16, 16, 32, 6, 4, 1}, 0, 6, 2, 0},
183 {"16x16x33 RGBA8 vol", {TiledKind::texture3d, 16, 16, 33, 6, 4, 1}, 0, 6, 3, 0}, 180 {"16x16x33 RGBA8 vol", {TiledKind::texture3d, 16, 16, 33, 6, 4, 1}, 0, 6, 3, 0},
184 {"16x16x48 RGBA8 vol", {TiledKind::texture3d, 16, 16, 48, 6, 4, 1}, 0, 6, 3, 0}, 181 {"16x16x48 RGBA8 vol", {TiledKind::texture3d, 16, 16, 48, 6, 4, 1}, 0, 6, 3, 0},
@@ -191,7 +188,6 @@ int main() {
191 {"16x16x16 RGBA16F vol", {TiledKind::texture3d, 16, 16, 16, 5, 8, 1}, 0, 5, 1, 0}, 188 {"16x16x16 RGBA16F vol", {TiledKind::texture3d, 16, 16, 16, 5, 8, 1}, 0, 5, 1, 0},
192 {"16x16x17 RGBA16F vol", {TiledKind::texture3d, 16, 16, 17, 5, 8, 1}, 0, 5, 2, 0}, 189 {"16x16x17 RGBA16F vol", {TiledKind::texture3d, 16, 16, 17, 5, 8, 1}, 0, 5, 2, 0},
193 {"16x16x64 RGBA16F vol", {TiledKind::texture3d, 16, 16, 64, 7, 8, 1}, 0, 7, 4, 0}, 190 {"16x16x64 RGBA16F vol", {TiledKind::texture3d, 16, 16, 64, 7, 8, 1}, 0, 7, 4, 0},
194 {"8x8x8 RGBA32F vol", {TiledKind::texture3d, 8, 8, 8, 4, 16, 1}, 0, 4, 1, 0},
195 {"8x8x16 RGBA32F vol", {TiledKind::texture3d, 8, 8, 16, 5, 16, 1}, 0, 5, 1, 0}, 191 {"8x8x16 RGBA32F vol", {TiledKind::texture3d, 8, 8, 16, 5, 16, 1}, 0, 5, 1, 0},
196 {"8x8x17 RGBA32F vol", {TiledKind::texture3d, 8, 8, 17, 5, 16, 1}, 0, 5, 2, 0}, 192 {"8x8x17 RGBA32F vol", {TiledKind::texture3d, 8, 8, 17, 5, 16, 1}, 0, 5, 2, 0},
197 {"8x8x64 RGBA32F vol", {TiledKind::texture3d, 8, 8, 64, 7, 16, 1}, 0, 7, 4, 0}, 193 {"8x8x64 RGBA32F vol", {TiledKind::texture3d, 8, 8, 64, 7, 16, 1}, 0, 7, 4, 0},
diff --git a/runtime/test/shader_library_corpus_test.cpp b/runtime/test/shader_library_corpus_test.cpp
index 7bf31bdd0..9e8af470e 100644
--- a/runtime/test/shader_library_corpus_test.cpp
+++ b/runtime/test/shader_library_corpus_test.cpp
@@ -6,9 +6,11 @@
6// For every container the test does what d3d12_vulkan_device.cpp does with a PSO's bytecode: inflate the FSSM program 6// For every container the test does what d3d12_vulkan_device.cpp does with a PSO's bytecode: inflate the FSSM program
7// from the DXIL/XDAT/XBCH entry, hash it and look it up under the container's stage. The stage comes from the DXIL 7// from the DXIL/XDAT/XBCH entry, hash it and look it up under the container's stage. The stage comes from the DXIL
8// part's program header, not from index.json. Every container has to resolve to its own entry (the one named after 8// part's program header, not from index.json. Every container has to resolve to its own entry (the one named after
9// the file, or one of its `~N` duplicates) with a readable SPIR-V module, and every index entry has to be reached by 9// the file, or one of its `~N` duplicates) with a readable SPIR-V module, and every RPF index entry has to be reached
10// a container. Containers with more than one 0x0D payload are counted, and their first payload must not stand in for 10// by a container. The entries from <shaders>/fspx/index.json are counted apart: their programs come from FidelityFX
11// the last: that is the rule fssm_program follows, so a regression to the first payload fails here. 11// DLLs, not from the DXBC containers, so they are not orphans. Containers with more than one 0x0D payload are
12// counted, and their first payload must not stand in for the last: that is the rule fssm_program follows, so a
13// regression to the first payload fails here.
12// 14//
13// A container with no index entry under its name at all is reported apart, as "not translated": the translator left 15// A container with no index entry under its name at all is reported apart, as "not translated": the translator left
14// it out (for example a module over SPIR-V's id bound), so the lookup has nothing to find. That still fails the test, 16// it out (for example a module over SPIR-V's id bound), so the lookup has nothing to find. That still fails the test,
@@ -189,11 +191,15 @@ int main() {
189 } 191 }
190 192
191 if (containers == 0) fail("no .dxbc containers in", dxbc_dir); 193 if (containers == 0) fail("no .dxbc containers in", dxbc_dir);
192 if (reached.size() != library.size()) 194 const std::size_t rpf_entries = library.size() - library.fspx_size();
193 fail(std::to_string(library.size() - reached.size()) + " index entries reached by no container", spirv_dir); 195 if (reached.size() != rpf_entries)
194 std::printf("%zu containers, %zu index entries, %zu reached; %zu containers with more than one program; " 196 fail(std::to_string(reached.size() > rpf_entries ? reached.size() - rpf_entries : rpf_entries - reached.size()) +
195 "%zu not translated; %d failures\n", containers, library.size(), reached.size(), multi, untranslated, 197 " RPF index entries not matched one to one",
196 failures); 198 spirv_dir);
199 std::printf("%zu containers, %zu RPF index entries, %zu reached, %zu FSPX index entries; "
200 "%zu containers with more than one program; "
201 "%zu not translated; %d failures\n",
202 containers, rpf_entries, reached.size(), library.fspx_size(), multi, untranslated, failures);
197 if (untranslated) 203 if (untranslated)
198 std::fprintf(stderr, "%zu container(s) have no index entry: the translator left them out, so the lookup had " 204 std::fprintf(stderr, "%zu container(s) have no index entry: the translator left them out, so the lookup had "
199 "nothing to find. Run the shaders stage again with a current translator.\n", 205 "nothing to find. Run the shaders stage again with a current translator.\n",
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index 3a37018d6..85d7a2b6a 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -432,7 +432,7 @@ int main() {
432 spv.write(reinterpret_cast<const char*>(words), sizeof(words)); 432 spv.write(reinterpret_cast<const char*>(words), sizeof(words));
433 } 433 }
434 ShaderLibrary fspx; 434 ShaderLibrary fspx;
435 CHECK(fspx.load(dir.string(), &error) && fspx.size() == 3); 435 CHECK(fspx.load(dir.string(), &error) && fspx.size() == 3 && fspx.fspx_size() == 1);
436 const auto found = fspx.fspx_candidates("cs", code_hash); 436 const auto found = fspx.fspx_candidates("cs", code_hash);
437 CHECK(found.size() == 1 && found[0]->name == "fspx/upscaler_00" && found[0]->local_size[0] == 8 && 437 CHECK(found.size() == 1 && found[0]->name == "fspx/upscaler_00" && found[0]->local_size[0] == 8 &&
438 found[0]->wave64 && found[0]->fssm_sha256.empty()); 438 found[0]->wave64 && found[0]->fssm_sha256.empty());
@@ -452,9 +452,10 @@ int main() {
452 std::ofstream sub(dir / "fspx" / "index.json", std::ios::binary | std::ios::trunc); 452 std::ofstream sub(dir / "fspx" / "index.json", std::ios::binary | std::ios::trunc);
453 sub << "{broken"; 453 sub << "{broken";
454 } 454 }
455 CHECK(fspx.load(dir.string(), &error) && fspx.size() == 2 && fspx.fspx_candidates("cs", code_hash).empty()); 455 CHECK(fspx.load(dir.string(), &error) && fspx.size() == 2 && fspx.fspx_size() == 0 &&
456 fspx.fspx_candidates("cs", code_hash).empty());
456 std::filesystem::remove(dir / "fspx" / "index.json"); 457 std::filesystem::remove(dir / "fspx" / "index.json");
457 CHECK(fspx.load(dir.string(), &error) && fspx.size() == 2 && fspx.find("cs", hash)); 458 CHECK(fspx.load(dir.string(), &error) && fspx.size() == 2 && fspx.fspx_size() == 0 && fspx.find("cs", hash));
458 std::filesystem::remove_all(dir); 459 std::filesystem::remove_all(dir);
459 } 460 }
460 461
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index 4dd01f8e4..b002201c9 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -100,6 +100,8 @@ def cs_fssm_extra(path):
100 100
101 101
102def shader_source(name): 102def shader_source(name):
103 if name == "ps_mullit":
104 return "../../../tests/semantic/fixtures/ps_mullit"
103 return "vs_clip" if name in CLIP_CASES else name 105 return "vs_clip" if name in CLIP_CASES else name
104 106
105 107
@@ -184,7 +186,8 @@ def main():
184 out = Path(sys.argv[1]) 186 out = Path(sys.argv[1])
185 available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys()) 187 available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys())
186 names = sys.argv[2:] or available 188 names = sys.argv[2:] or available
187 unknown = sorted(set(names) - set(available)) 189 # mullit_readback.py uses the CPU semantic fixture as an explicit build target.
190 unknown = sorted(set(names) - set(available) - {"ps_mullit"})
188 if unknown: 191 if unknown:
189 sys.exit("Unknown test shaders: " + ", ".join(unknown)) 192 sys.exit("Unknown test shaders: " + ", ".join(unknown))
190 skipped = [n for n in names if n.startswith("ms_")] 193 skipped = [n for n in names if n.startswith("ms_")]
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 9771f17b1..330af9f4f 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -82,8 +82,9 @@ CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed001
82SIGNED_ZERO_NAN = [0x80000000, 0x80000000, 0x80008000, 0x00008000, 1, 1, 1, 0x00007c00] 82SIGNED_ZERO_NAN = [0x80000000, 0x80000000, 0x80008000, 0x00008000, 1, 1, 1, 0x00007c00]
83WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", 83WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute",
84 "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", 84 "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32",
85 "cs_w32_lds_subdword", "cs_w32_lds_wide",
85 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", 86 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext",
86 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", 87 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_w32_andn2_exec",
87 "cs_mask_vgpr_exec") 88 "cs_mask_vgpr_exec")
88# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is 89# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is
89# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with 90# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with
@@ -91,7 +92,7 @@ WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm
91# otherwise pick a narrower size and return different words (#774). 92# otherwise pick a narrower size and return different words (#774).
92WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} 93WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"}
93WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const", 94WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const",
94 "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_mask_vgpr_exec") 95 "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_w32_andn2_exec", "cs_mask_vgpr_exec")
95CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), 96CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]),
96 ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), 97 ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]),
97 ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), 98 ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]),
@@ -119,6 +120,10 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
119 ("cs_w32_salu64", [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE]), 120 ("cs_w32_salu64", [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE]),
120 # SHADER-85: 8-bit LDS reads into one half of a VGPR, the other half kept 121 # SHADER-85: 8-bit LDS reads into one half of a VGPR, the other half kept
121 ("cs_w32_lds_u8_d16", [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234]), 122 ("cs_w32_lds_u8_d16", [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234]),
123 # 8/16-bit LDS writes (incl. _d16_hi) and sign/zero-extending reads
124 ("cs_w32_lds_subdword", [0x11B2D444, 0xA1B2C3D4, 0xFFFFFFB2, 0x000000B2, 0x00000011, 0xFFFFA1B2, 0x0000A1B2, 0xFFFFC3D4]),
125 # 64/96/128-bit LDS accesses and ds_read2st64_b32
126 ("cs_w32_lds_wide", [0xCAFEF00D, 0xFEEDFACE, 0x600DD00D, 0x00000000, 0x8BADF00D, 0xDEADC0DE, 0x12345678, 0x9ABCDEF0]),
122 # ds_cmpst_b32 and the b64 2-address forms (cs_lds_b64_cmpst.asm header) 127 # ds_cmpst_b32 and the b64 2-address forms (cs_lds_b64_cmpst.asm header)
123 ("cs_lds_b64_cmpst", [0x11110001, 0x22220002, 0x33330003, 0x44440004, 128 ("cs_lds_b64_cmpst", [0x11110001, 0x22220002, 0x33330003, 0x44440004,
124 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC]), 129 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC]),
@@ -130,6 +135,8 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
130 ("cs_w64_mask_imm", [2056, 1084, 828, 2052, 319, 2104, 516, 2064]), 135 ("cs_w64_mask_imm", [2056, 1084, 828, 2052, 319, 2104, 516, 2064]),
131 # SHADER-99: -0 and NaN survive translation (SignedZeroInfNanPreserve); words 0, 2, 3 on Apple: see below 136 # SHADER-99: -0 and NaN survive translation (SignedZeroInfNanPreserve); words 0, 2, 3 on Apple: see below
132 ("cs_signed_zero_nan", SIGNED_ZERO_NAN), 137 ("cs_signed_zero_nan", SIGNED_ZERO_NAN),
138 # s_andn2_saveexec_b32 / s_andn2_wrexec_b32: EXEC = S0 & ~EXEC, D old / new EXEC, SCC (cs_w32_andn2_exec.asm)
139 ("cs_w32_andn2_exec", [1, 8, 16, 2064, 2068, 3, 20, 1544]),
133 ("cs_wave64_ballot", [32, 16, 24, 40, 8, 48]), 140 ("cs_wave64_ballot", [32, 16, 24, 40, 8, 48]),
134 ("cs_wm_half_ops", [32, 16, 16, 0, 16]), ("cs_wm_half_cmp", [1, 0, 1, 1]), 141 ("cs_wm_half_ops", [32, 16, 16, 0, 16]), ("cs_wm_half_cmp", [1, 0, 1, 1]),
135 ("cs_wm_bfm64", [16, 8, 8, 40]), ("cs_wm_scc_rfl", [55, 48]), 142 ("cs_wm_bfm64", [16, 8, 8, 40]), ("cs_wm_scc_rfl", [55, 48]),
@@ -230,19 +237,46 @@ TBUFFER_STORE_WORDS = [
230 0xFF0080FF, 0xA5A50284, 0xA5A50288, 0xA5A5028C, 0xA5A50290, 0xA5A50294, 0xA5A50298, 0xA5A5029C, 237 0xFF0080FF, 0xA5A50284, 0xA5A50288, 0xA5A5028C, 0xA5A50290, 0xA5A50294, 0xA5A50298, 0xA5A5029C,
231 0xA5A502FF, 0xA5A502A4, 0xA5A502A8, 0xA5A502AC, 0x3F800000, 0xA5A502B4, 0xA5A502B8, 0xA5A502BC, 238 0xA5A502FF, 0xA5A502A4, 0xA5A502A8, 0xA5A502AC, 0x3F800000, 0xA5A502B4, 0xA5A502B8, 0xA5A502BC,
232 0xA5A502C0, 0xA5A502C4, 0xA5A502C8, 0xA5A502CC] 239 0xA5A502C0, 0xA5A502C4, 0xA5A502C8, 0xA5A502CC]
240# cs_fmt_d16_xyz.asm: d16_xyz / d16_xy typed-buffer loads (out[0..10]), the two d16_xyz stores (out[16..18] and
241# out[20..22]) and the inputs at 0x100 (out[64..72]); everything else is the untouched fill. Derivation in the header.
242FMT_D16_XYZ_WORDS = [
243 0xABCD1234, 0xA5A57FFF, 0xFFFF0005, 0x1234FFFF, 0xC0003C00, 0xC0003C00, 0xBEEF3555, 0x00003C00,
244 0xCAFE3C00, 0xFFFF0005, 0x0BADFFFF, *[0xEEEEEEEE] * 5,
245 0x00000007, 0x00008001, 0x0000FFFE, 0xEEEEEEEE, 0x3F800000, 0xC0000000, 0x3F000000, 0xEEEEEEEE,
246 *[0xEEEEEEEE] * 40,
247 0xABCD1234, 0x55557FFF, 0xC0003C00, 0x7BFF3555, 5, 0x10000, 0xFFFFFFFF, 0, 0x80FF00FF, *[0xEEEEEEEE] * 7]
233# Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups make a 0x2800-byte heap that holds 248# Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups make a 0x2800-byte heap that holds
234# both the right addresses and the 4096-lower ones; only group 0 thread 0 runs, so no wave64 requirement. 249# both the right addresses and the 4096-lower ones; only group 0 thread 0 runs, so no wave64 requirement.
235GLOBAL_OFFSET = [("cs_global_neg_offset", "40", [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4, 250GLOBAL_OFFSET = [("cs_global_neg_offset", "40", [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4,
236 0x0000009E, 0xFFFF8BAD, 0x57023FFC, 0xEEEEEEEE])] 251 0x0000009E, 0xFFFF8BAD, 0x57023FFC, 0xEEEEEEEE])]
252# cs_heap_init.asm: vk_compute_test's VKC_HEAP_INIT copies this file (zeros, then four words at 0x100) to the start
253# of the heap; the shader copies the four words to 0, and out[4..7] are the file's zeros, not the 0xEE fill.
254HEAP_INIT_WORDS = [0x1BADB002, 0xCAFEF00D, 0x80000001, 0x0000FFFF]
255HEAP_INIT_FILE = bytes(0x100) + struct.pack("<4I", *HEAP_INIT_WORDS)
256HEAP_INIT_EXPECTED = HEAP_INIT_WORDS + [0] * 4
257
258
259def heap_init_env():
260 """vk_compute_test's environment for cs_heap_init: the init file (written to the temp folder) and a buffer big
261 enough to hold it (68 words for its 0x110 bytes; one group's default is 64)."""
262 path = os.path.join(tempfile.gettempdir(), "leonida_cs_heap_init.bin")
263 with open(path, "wb") as f:
264 f.write(HEAP_INIT_FILE)
265 return {"VKC_HEAP_INIT": path, "VKC_OUT_WORDS": str(len(HEAP_INIT_FILE) // 4)}
266
267
237# cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back. 268# cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back.
238USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF] 269USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF]
239USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)} 270USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)}
240USER_SGPRS_WORDS = USER_SGPRS + [0xEEEEEEEE] * 4 271USER_SGPRS_WORDS = USER_SGPRS + [0xEEEEEEEE] * 4
241# cs_fma_fused.asm: single-rounded f32 multiply-adds (and one f16). The operands arrive in s4..s7 so no driver can fold 272# cs_fma_fused.asm: single-rounded f32 multiply-adds (and one f16). The operands arrive in s4..s7 so no driver can fold
242# them; the words are the exact fused results (derivations in the .asm header). The same with --fma glsl and --fma khr 273# them; FMA_FUSED are the exact single-rounded words and FMA_SPLIT are the exact split-rounded words (derivations in
243# (LEONIDA_FMA=khr for build.py): GLSL Fma may be split into two roundings by a driver, OpFmaKHR may not. 274# the .asm header; out[7] is f16 round-to-odd, never GLSL Fma, so it is always 0x7351). Under --fma khr
275# (LEONIDA_FMA=khr, shaderFmaFloat32 in index.json) every word must match FMA_FUSED; under default --fma glsl a
276# spec-compliant driver (e.g. Mesa RADV 26.2.6) may legally split GLSL.std.450 Fma.
244FMA_FUSED_ENV = {"VKC_SGPRS": "0x3f800800,0x3f800001,0x3f7ffffe,0xbf800002"} 277FMA_FUSED_ENV = {"VKC_SGPRS": "0x3f800800,0x3f800001,0x3f7ffffe,0xbf800002"}
245FMA_FUSED = [0x33800000, 0xa8800000, 0x3a000400, 0x33800000, 0x33800000, 0x33800000, 0x28800000, 0x00007351] 278FMA_FUSED = [0x33800000, 0xa8800000, 0x3a000400, 0x33800000, 0x33800000, 0x33800000, 0x28800000, 0x00007351]
279FMA_SPLIT = [0x00000000, 0x00000000, 0x3a000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00007351]
246# cs_cvt_f32_sat.asm (#300): s4 is a binary32 input, out[0] = v_cvt_u32_f32, out[1] = v_cvt_i32_f32 (truncate, 280# cs_cvt_f32_sat.asm (#300): s4 is a binary32 input, out[0] = v_cvt_u32_f32, out[1] = v_cvt_i32_f32 (truncate,
247# saturate, NaN -> 0). One dispatch per input through VKC_SGPRS; the inputs of tests/semantic/test_float_to_int.py. 281# saturate, NaN -> 0). One dispatch per input through VKC_SGPRS; the inputs of tests/semantic/test_float_to_int.py.
248CVT_F32_SAT_CASES = ( 282CVT_F32_SAT_CASES = (
@@ -288,6 +322,8 @@ W64X_PARTIAL = [("cs_w64x_partial", [40, 40, 528, 0, 0, 532, 539, 524820]),
288 ("cs_w64x_partial_scmp", [0, 1, 0, 1, 1, 1, 1, 0])] 322 ("cs_w64x_partial_scmp", [0, 1, 0, 1, 1, 1, 1, 0])]
289PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000), 323PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
290 "ps_legacy_mul": (0, 0, 0, 0x40c00000), 324 "ps_legacy_mul": (0, 0, 0, 0x40c00000),
325 "ps_mul_legacy_denorm": (0, 0, 0, 0x80000000),
326 "ps_mul_legacy_denorm_mods": (0, 0, 0, 0x40400000),
291 "ps_ops": (0x48804300, 5, 7, 0xbffffffc), "ps_ops2": (0xabcd4400, 0x46001234, 0xbffffffa, 7), 327 "ps_ops": (0x48804300, 5, 7, 0xbffffffc), "ps_ops2": (0xabcd4400, 0x46001234, 0xbffffffa, 7),
292 "ps_ops3": (0xbffffffa, 0x44660066, 0x44aabbcc, 16), "ps_ops4": (0x34000010, 0x00120800, 0xbeef0000, 0x12343c00), 328 "ps_ops3": (0xbffffffa, 0x44660066, 0x44aabbcc, 16), "ps_ops4": (0x34000010, 0x00120800, 0xbeef0000, 0x12343c00),
293 "ps_ops5": (0x12340010, 0xbeef0800, 0xaaaaffff, 0xdeadbc00), 329 "ps_ops5": (0x12340010, 0xbeef0800, 0xaaaaffff, 0xdeadbc00),
@@ -307,6 +343,7 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
307 "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), 343 "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16),
308 "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000), 344 "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000),
309 "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000), 345 "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000),
346 "ps_f64_round": (0xc12af665, 0x3fe7ffff, 0xbfffffff, 0xc12af666),
310 "ps_outmods_f16": (0xaaaa3c00, 0xaaaa3e00, 0x7c000000, 0x3c000000), 347 "ps_outmods_f16": (0xaaaa3c00, 0xaaaa3e00, 0x7c000000, 0x3c000000),
311 # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers) 348 # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers)
312 "ps_f16_med3_opsel": (0xaaaa4100, 0xaaaa4200, 0xaaaa3e00, 0x40005555), 349 "ps_f16_med3_opsel": (0xaaaa4100, 0xaaaa4200, 0xaaaa3e00, 0x40005555),
@@ -341,6 +378,9 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
341 # v_mad_u32_u16 / v_mad_i32_i16 and v_subrev_f16, which had CPU checks only (derivations in the .asm headers) 378 # v_mad_u32_u16 / v_mad_i32_i16 and v_subrev_f16, which had CPU checks only (derivations in the .asm headers)
342 "ps_valu16_mad": (0x00000002, 0x00030002, 0x00008000, 0x00000004), 379 "ps_valu16_mad": (0x00000002, 0x00030002, 0x00008000, 0x00000004),
343 "ps_valu16_subrev": (0xaaaabc00, 0xaaaac000, 0xaaaa3c00, 0x42003800), 380 "ps_valu16_subrev": (0xaaaabc00, 0xaaaac000, 0xaaaa3c00, 0x42003800),
381 # f32 VOPC ordered/unordered with a NaN, 64-bit integer VOPC (derivations in the .asm headers)
382 "ps_vcmp_f32_nan": (0x0000376c, 0x0000fd5b, 0x0000d36c, 0x00000fe7),
383 "ps_vcmp_64": (0x0000b3c4, 0x000091e6, 0x00006787, 0x00007c93),
344 # v_readlane_b32 across both halves of a wave64 (the .asm header derives the words) 384 # v_readlane_b32 across both halves of a wave64 (the .asm header derives the words)
345 "ps_w64x_readlane": (0x40000079, 0x40000010, 0x40000064, 0x400000be)} 385 "ps_w64x_readlane": (0x40000079, 0x40000010, 0x40000064, 0x400000be)}
346# Pixel shaders that are exact only when the pixel stage really ran 64 lanes wide. vk_harness says so when it chained 386# Pixel shaders that are exact only when the pixel stage really ran 64 lanes wide. vk_harness says so when it chained
@@ -363,7 +403,14 @@ PIXEL_ENV = {"ps_vcc_x2": {"VKH_SGPRS": "0x1000,0,16,0", "VKH_HEAP": "0x1000=0x1
363 "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x40e00000,0x1008=0x40a00000," 403 "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x40e00000,0x1008=0x40a00000,"
364 "0x100c=0x7fc10001,0x1010=0x40600000,0x1014=0xc0200000"}, 404 "0x100c=0x7fc10001,0x1010=0x40600000,0x1014=0xc0200000"},
365 "ps_fnan_fract": {"VKH_SGPRS": "0x1000,0,16,0", 405 "ps_fnan_fract": {"VKH_SGPRS": "0x1000,0,16,0",
366 "VKH_HEAP": "0x1000=0xaedbe6ff,0x1004=0x00008800,0x1008=0x7fc10001,0x100c=0xc0200000"}} 406 "VKH_HEAP": "0x1000=0xaedbe6ff,0x1004=0x00008800,0x1008=0x7fc10001,0x100c=0xc0200000"},
407 # f32 VOPC with a NaN, 64-bit integer VOPC: inputs from memory (derivations in the .asm headers)
408 "ps_vcmp_f32_nan": {"VKH_SGPRS": "0x1000,0,16,0",
409 "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x3f800000,0x1008=0x40000000"},
410 "ps_vcmp_64": {"VKH_SGPRS": "0x1000,0,64,0",
411 "VKH_HEAP": "0x1000=0x80000000,0x1004=0,0x1008=1,0x100c=0,0x1010=0xffffffff,"
412 "0x1014=0xffffffff,0x1018=1,0x101c=0,0x1020=1,0x1024=0,0x1028=0x80000000,"
413 "0x102c=0,0x1030=7,0x1034=5,0x1038=7,0x103c=5"}}
367# ps_gather_wrap.asm (SHADER-36): image_gather4_l_o under each S# address mode, run by vk_texture_test (the 8x8 gradient 414# ps_gather_wrap.asm (SHADER-36): image_gather4_l_o under each S# address mode, run by vk_texture_test (the 8x8 gradient
368# texture); the expected channels are derived in the .asm header. 415# texture); the expected channels are derived in the .asm header.
369TEXTURE_CONSTANTS = { 416TEXTURE_CONSTANTS = {
@@ -538,6 +585,11 @@ def tbuffer_store_test(tools, spirv, env=None):
538 return dump_test(tools, spirv, "cs_tbuffer_store", TBUFFER_STORE_WORDS + [0xEEEEEEEE] * 76, 192, env) 585 return dump_test(tools, spirv, "cs_tbuffer_store", TBUFFER_STORE_WORDS + [0xEEEEEEEE] * 76, 192, env)
539 586
540 587
588def fmt_d16_xyz_test(tools, spirv, env=None):
589 """The d16_xyz/d16_xy loads and d16_xyz stores of cs_fmt_d16_xyz.asm: the whole 80-word heap."""
590 return dump_test(tools, spirv, "cs_fmt_d16_xyz", FMT_D16_XYZ_WORDS, len(FMT_D16_XYZ_WORDS), env)
591
592
541class Skip(str): 593class Skip(str):
542 """A result that is neither a pass nor a failure: the device can't run the test.""" 594 """A result that is neither a pass nor a failure: the device can't run the test."""
543 595
@@ -659,6 +711,10 @@ def bitmask_perm_narrow_skip(out, px):
659 return None 711 return None
660 lanes = {p[0] for p in px} 712 lanes = {p[0] for p in px}
661 width = max(lanes) + 1 713 width = max(lanes) + 1
714 # "pippi" reads lane ^ 9. Where that lane runs (every lane at 16 wide, none at 8) the word is defined and has
715 # to be right: a narrow run excuses only the sources that aren't there.
716 if any(a != lane ^ 9 for lane, a, _, _ in px if lane ^ 9 < width):
717 return None
662 if lo <= width < 32 and width & (width - 1) == 0 and lanes == set(range(width)): 718 if lo <= width < 32 and width & (width - 1) == 0 and lanes == set(range(width)):
663 return Skip(f"SKIP (fragment subgroup ran at {width} lanes on {lo}..{hi} device; needs 32)") 719 return Skip(f"SKIP (fragment subgroup ran at {width} lanes on {lo}..{hi} device; needs 32)")
664 return None 720 return None
@@ -749,6 +805,63 @@ def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expe
749 return failure(code, out, 2) 805 return failure(code, out, 2)
750 806
751 807
808def shader_features(spirv, name):
809 """The Vulkan feature names recorded for a shader in index.json, or an empty set."""
810 try:
811 with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f:
812 feats = json.load(f).get(name, {}).get("features") or ()
813 return set(feats)
814 except (OSError, ValueError, TypeError):
815 return set()
816
817
818def judge_fma_fused(words, khr):
819 """Judge cs_fma_fused's 8 words: (ok, detail). Under --fma khr every word must be exact fused; under --fma glsl
820 each of the 7 f32 words may be either fused or exact split (Vulkan allows splitting GLSL.std.450 Fma), while the
821 f16 round-to-odd word out[7] must always be exact 0x00007351."""
822 if not words or len(words) < 8:
823 return False, "missing out[0..7] dump"
824 if khr:
825 for i, (got, want) in enumerate(zip(words, FMA_FUSED)):
826 if got != want:
827 return False, f"word {i}: got {got:#010x}, want fused {want:#010x} (OpFmaKHR)"
828 return True, "8/8 fused exact (OpFmaKHR)"
829 if words[7] != FMA_FUSED[7]:
830 return False, f"word 7 (f16): got {words[7]:#010x}, want {FMA_FUSED[7]:#010x}"
831 n_split = 0
832 for i in range(7):
833 got, fused, split = words[i], FMA_FUSED[i], FMA_SPLIT[i]
834 if got == fused:
835 continue
836 if got == split:
837 n_split += 1
838 continue
839 return False, f"word {i}: got {got:#010x}, want fused {fused:#010x} or split {split:#010x}"
840 if n_split == 0:
841 return True, "8/8 fused exact (GLSL Fma)"
842 return True, f"{7 - n_split}/7 f32 fused, {n_split}/7 split (GLSL Fma; LEONIDA_FMA=khr for OpFmaKHR), f16 exact"
843
844
845def fma_fused_test(tools, spirv):
846 """Run cs_fma_fused and judge against FMA_FUSED (strict under --fma khr, fused-or-split f32 under --fma glsl)."""
847 shader = os.path.join(spirv, "cs_fma_fused.spv")
848 khr = ("shaderFmaFloat32" in shader_features(spirv, "cs_fma_fused")
849 or os.environ.get("LEONIDA_FMA") == "khr")
850 code, out = run(os.path.join(tools, "vk_compute_test" + EXE), shader, "1", "dump",
851 env=dict(os.environ, **FMA_FUSED_ENV))
852 if code == UNSUPPORTED:
853 m = re.search(r"unsupported: .*", out)
854 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})")
855 if code != 0:
856 return failure(code, out, 2)
857 m = re.search(r"^out\[0\.\.7\] = ((?:[0-9]+ ){7}[0-9]+)$", out, re.MULTILINE)
858 if not m:
859 return failure(code, out, 2)
860 words = [int(x) for x in m.group(1).split()]
861 ok, detail = judge_fma_fused(words, khr=khr)
862 return "" if ok else detail
863
864
752def cvt_f32_sat_test(tools, spirv): 865def cvt_f32_sat_test(tools, spirv):
753 """cs_cvt_f32_sat once per input of CVT_F32_SAT_CASES: an empty string when every pair of words is exact.""" 866 """cs_cvt_f32_sat once per input of CVT_F32_SAT_CASES: an empty string when every pair of words is exact."""
754 wrong = [] 867 wrong = []
@@ -1269,6 +1382,24 @@ def mandelbrot_problem(px):
1269 return f"{len(wrong)} of {len(px)} iteration counts differ, e.g. pixel ({i % w}, {i // w}) {got} instead of {e}" 1382 return f"{len(wrong)} of {len(px)} iteration counts differ, e.g. pixel ({i % w}, {i // w}) {got} instead of {e}"
1270 1383
1271 1384
1385def barycentric_problem(px: list[tuple[float, float, float, float]], abs_tol: float) -> str:
1386 """Check ps_bary over the 64-by-64 frame covered by the vs_ids triangle."""
1387 if len(px) != 64 * 64:
1388 return f"expected 4096 pixels, got {len(px)}"
1389 for index, pixel in enumerate(px):
1390 a, b, _, _ = pixel
1391 if not all(math.isfinite(v) for v in pixel):
1392 return "barycentrics contain non-finite values"
1393 y, x = divmod(index, 64)
1394 # vs_ids exports (0,0), (2,0), (0,2) at the vertices. Check that gradient
1395 # independently so a failure that zeros both interpolation paths is visible.
1396 u, v = (x + 0.5) / 64, (y + 0.5) / 64
1397 expected = (u, v, a / 2, b / 2)
1398 if any(abs(got - want) > abs_tol for got, want in zip(pixel, expected)):
1399 return f"at ({x},{y}): got {pixel}, expected {expected}"
1400 return ""
1401
1402
1272def pixel_test(tools, spirv, name): 1403def pixel_test(tools, spirv, name):
1273 path = os.path.join(spirv, name + ".spv") 1404 path = os.path.join(spirv, name + ".spv")
1274 if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES): 1405 if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES):
@@ -1304,11 +1435,8 @@ def pixel_test(tools, spirv, name):
1304 if name in PIXEL_BITS: 1435 if name in PIXEL_BITS:
1305 wrong = sum(p != PIXEL_BITS[name] for p in px) 1436 wrong = sum(p != PIXEL_BITS[name] for p in px)
1306 return "" if not wrong else f"{wrong} of {n} pixels differ, e.g. {[hex(x) for x in next(p for p in px if p != PIXEL_BITS[name])]}" 1437 return "" if not wrong else f"{wrong} of {n} pixels differ, e.g. {[hex(x) for x in next(p for p in px if p != PIXEL_BITS[name])]}"
1307 if name == "ps_bary": # raw i, j against the interpolated attr0.xy / 2 1438 if name == "ps_bary":
1308 if any(not math.isfinite(v) for p in px for v in p): 1439 return barycentric_problem(px, 1e-6)
1309 return "barycentrics contain non-finite values"
1310 err = max(max(abs(a / 2 - i), abs(b / 2 - j)) for a, b, i, j in px)
1311 return "" if err < 1e-6 else f"barycentrics off by {err:.3g}"
1312 if name == "ps_flat": 1440 if name == "ps_flat":
1313 if any(not math.isfinite(v) for p in px for v in p[2:]): 1441 if any(not math.isfinite(v) for p in px for v in p[2:]):
1314 return "UVs contain non-finite values" 1442 return "UVs contain non-finite values"
@@ -1392,13 +1520,15 @@ def main():
1392 results.append(("cs_fmt_int_narrow", fmt_int_narrow_test(tools, spirv))) 1520 results.append(("cs_fmt_int_narrow", fmt_int_narrow_test(tools, spirv)))
1393 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv))) 1521 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv)))
1394 results.append(("cs_tbuffer_store", tbuffer_store_test(tools, spirv))) 1522 results.append(("cs_tbuffer_store", tbuffer_store_test(tools, spirv)))
1523 results.append(("cs_fmt_d16_xyz", fmt_d16_xyz_test(tools, spirv)))
1395 for name, groups, want in GLOBAL_OFFSET: 1524 for name, groups, want in GLOBAL_OFFSET:
1396 results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want))) 1525 results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want)))
1397 results.append(("cs_user_sgprs", compute_test(tools, spirv, "cs_user_sgprs", "1", "dump", 1526 results.append(("cs_user_sgprs", compute_test(tools, spirv, "cs_user_sgprs", "1", "dump",
1398 expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV))) 1527 expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV)))
1528 results.append(("cs_heap_init", compute_test(tools, spirv, "cs_heap_init", "1", "dump",
1529 expected_words=HEAP_INIT_EXPECTED, env=heap_init_env())))
1399 results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv))) 1530 results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv)))
1400 results.append(("cs_fma_fused", compute_test(tools, spirv, "cs_fma_fused", "1", "dump", expected_words=FMA_FUSED, 1531 results.append(("cs_fma_fused", fma_fused_test(tools, spirv)))
1401 env=FMA_FUSED_ENV)))
1402 results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump", 1532 results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump",
1403 expected_words=CVT_PK_U8_WORDS))) 1533 expected_words=CVT_PK_U8_WORDS)))
1404 for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1 1534 for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1
diff --git a/runtime/test/shaders/cs_fmt_d16_xyz.asm b/runtime/test/shaders/cs_fmt_d16_xyz.asm
new file mode 100644
index 000000000..c471a6439
--- /dev/null
+++ b/runtime/test/shaders/cs_fmt_d16_xyz.asm
@@ -0,0 +1,98 @@
1; The d16 typed-buffer forms no other test runs: buffer_load_format_d16_xyz, tbuffer_load_format_d16_xy,
2; tbuffer_load_format_d16_xyz and buffer_store_format_d16_xyz. One thread (lane 0) does everything.
3; RDNA2 ISA (MUBUF/MTBUF): a d16 load converts each component to 16 bits (f16 for float and normalized formats, the
4; integer saturated to 16 bits for UINT/SINT) and packs two per VGPR, X in bits 15:0 and Y in 31:16 of the first, Z
5; in 15:0 of the second. docs/design.md (d16 and f16 format narrowing): an odd final component (d16_x, d16_xyz)
6; writes only the low 16 bits of its VGPR and the high half keeps its bits; unsigned 32-bit channels clamp to 65535.
7; A d16 store takes the components from the same halves and encodes them in the V# format (an f16 widened to the
8; f32 of a 32_FLOAT channel, a 16-bit integer zero-extended into a 32_UINT channel).
9; MUBUF uses the V# format (word3 bits 18:12) and DST_SEL (bits 11:0, here X Y Z W); MTBUF uses the instruction's
10; format and identity selectors with a bound V# (32_FLOAT). V# word3 = 0x31000fac | format << 12.
11; Inputs, written first by lane 0:
12; 0x100: 0xabcd1234 0x55557fff 16_16_16_16 X=0x1234 Y=0xabcd Z=0x7fff W=0x5555
13; 0x108: 0xc0003c00 0x7bff3555 f16 X=1.0 (0x3c00) Y=-2.0 (0xc000) Z=0x3555 (0.33325) W=0x7bff
14; 0x110: 5 0x10000 0xffffffff 0 32-bit X Y Z (and a zero pad)
15; 0x120: 0x80ff00ff 8_8_8_8 X=0xff Y=0x00 Z=0xff W=0x80
16; Loads (the second VGPR of each _xyz is seeded first; its high half must survive):
17; L1 buffer_load_format_d16_xyz v[8:9] @0x100, V# 16_16_16_16_UINT (69): X, Y, Z fit in 16 bits.
18; v8 = 0xabcd1234; v9 = 0xa5a5 << 16 | 0x7fff = 0xa5a57fff (seed 0xa5a55a5a)
19; L2 buffer_load_format_d16_xyz v[10:11] @0x110, V# 32_32_32_UINT (72): 5, min(0x10000, 65535) = 0xffff,
20; min(0xffffffff, 65535) = 0xffff. v10 = 0xffff0005; v11 = 0x1234ffff (seed 0x12345678)
21; L3 tbuffer_load_format_d16_xy v12 @0x108, BUF_FMT_16_16_FLOAT: the f16 bits as they are. v12 = 0xc0003c00
22; L4 tbuffer_load_format_d16_xyz v[13:14] @0x108, BUF_FMT_16_16_16_16_FLOAT: v13 = 0xc0003c00;
23; v14 = 0xbeef3555 (seed 0xbeef7777)
24; L5 tbuffer_load_format_d16_xyz v[15:16] @0x120, BUF_FMT_8_8_8_8_UNORM: 255/255 = 1.0 -> 0x3c00, 0/255 = 0,
25; 255/255 = 1.0 -> 0x3c00 (exact, no rounding). v15 = 0x00003c00; v16 = 0xcafe3c00 (seed 0xcafe1111)
26; L6 tbuffer_load_format_d16_xyz v[17:18] @0x110, BUF_FMT_32_32_32_UINT: as L2. v17 = 0xffff0005;
27; v18 = 0x0badffff (seed 0x0bad0bad)
28; v8..v18 go to out[0..10] (0x00..0x28); out[11..15] are untouched (0xeeeeeeee).
29; Stores (the fourth word of each 16-byte region stays untouched):
30; S1 buffer_store_format_d16_xyz v[20:21] @0x40, V# 32_32_32_UINT (72): v20 = 0x80010007, v21 = 0xdeadfffe
31; -> X = 0x0007, Y = 0x8001, Z = 0xfffe (v21's high half is not a component), zero-extended:
32; out[16..19] = 0x00000007 0x00008001 0x0000fffe 0xeeeeeeee
33; S2 buffer_store_format_d16_xyz v[22:23] @0x50, V# 32_32_32_FLOAT (74): v22 = 0xc0003c00, v23 = 0x12343800
34; -> 1.0, -2.0, 0.5 (0x3800) as f32: out[20..23] = 0x3f800000 0xc0000000 0x3f000000 0xeeeeeeee
35; out[24..63] are untouched except the inputs at out[64..72] (0x100..0x120); the dump is 80 words.
36; Run: VKC_OUT_WORDS=80 VKC_DUMP=<file> vk_compute_test cs_fmt_d16_xyz.spv 1 dump
37v_cmpx_eq_u32_e32 0, v0
38s_mov_b32 s4, s0
39s_mov_b32 s5, s1
40s_mov_b32 s6, s2
41v_mov_b32_e32 v1, 0xabcd1234
42v_mov_b32_e32 v2, 0x55557fff
43v_mov_b32_e32 v3, 0xc0003c00
44v_mov_b32_e32 v4, 0x7bff3555
45v_mov_b32_e32 v5, 0x100
46buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
47v_mov_b32_e32 v1, 5
48v_mov_b32_e32 v2, 0x10000
49v_mov_b32_e32 v3, -1
50v_mov_b32_e32 v4, 0
51v_mov_b32_e32 v5, 0x110
52buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
53v_mov_b32_e32 v1, 0x80ff00ff
54v_mov_b32_e32 v5, 0x120
55buffer_store_dword v1, v5, s[0:3], 0 offen
56s_waitcnt vmcnt(0)
57; L1
58s_mov_b32 s7, 0x31045fac
59v_mov_b32_e32 v5, 0x100
60v_mov_b32_e32 v9, 0xa5a55a5a
61buffer_load_format_d16_xyz v[8:9], v5, s[4:7], 0 offen
62; L2
63s_mov_b32 s7, 0x31048fac
64v_mov_b32_e32 v5, 0x110
65v_mov_b32_e32 v11, 0x12345678
66buffer_load_format_d16_xyz v[10:11], v5, s[4:7], 0 offen
67; L3..L6: MTBUF with a bound 32_FLOAT V#
68s_mov_b32 s7, 0x31016fac
69v_mov_b32_e32 v5, 0x108
70tbuffer_load_format_d16_xy v12, v5, s[4:7], 0 format:[BUF_FMT_16_16_FLOAT] offen
71v_mov_b32_e32 v14, 0xbeef7777
72tbuffer_load_format_d16_xyz v[13:14], v5, s[4:7], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen
73v_mov_b32_e32 v5, 0x120
74v_mov_b32_e32 v16, 0xcafe1111
75tbuffer_load_format_d16_xyz v[15:16], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UNORM] offen
76v_mov_b32_e32 v5, 0x110
77v_mov_b32_e32 v18, 0x0bad0bad
78tbuffer_load_format_d16_xyz v[17:18], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_UINT] offen
79s_waitcnt vmcnt(0)
80v_mov_b32_e32 v6, 0
81buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
82v_mov_b32_e32 v6, 0x10
83buffer_store_dwordx4 v[12:15], v6, s[0:3], 0 offen
84v_mov_b32_e32 v6, 0x20
85buffer_store_dwordx3 v[16:18], v6, s[0:3], 0 offen
86; S1
87s_mov_b32 s7, 0x31048fac
88v_mov_b32_e32 v20, 0x80010007
89v_mov_b32_e32 v21, 0xdeadfffe
90v_mov_b32_e32 v6, 0x40
91buffer_store_format_d16_xyz v[20:21], v6, s[4:7], 0 offen
92; S2
93s_mov_b32 s7, 0x3104afac
94v_mov_b32_e32 v22, 0xc0003c00
95v_mov_b32_e32 v23, 0x12343800
96v_mov_b32_e32 v6, 0x50
97buffer_store_format_d16_xyz v[22:23], v6, s[4:7], 0 offen
98s_endpgm
diff --git a/runtime/test/shaders/cs_heap_init.asm b/runtime/test/shaders/cs_heap_init.asm
new file mode 100644
index 000000000..fdd670763
--- /dev/null
+++ b/runtime/test/shaders/cs_heap_init.asm
@@ -0,0 +1,14 @@
1; group: 1,1,1
2; rsrc2: 0x8090
3; vk_compute_test's VKC_HEAP_INIT copies a file to the start of the heap before the dispatch. Both runners write a
4; 0x110-byte file (zeros, then the words 0x1badb002, 0xcafef00d, 0x80000001, 0x0000ffff at 0x100) and pass
5; VKC_OUT_WORDS=68 so it fits. One thread loads the four words through the output V# and stores them at 0, so
6; out[0..3] are the seeded words and out[4..7] the file's zeros at 0x10..0x1f (not the 0xEE fill): the whole file was
7; copied. Without VKC_HEAP_INIT every word reads 0xEEEEEEEE.
8; Run: VKC_OUT_WORDS=68 VKC_HEAP_INIT=init.bin vk_compute_test cs_heap_init.spv 1 dump
9; out[0..7] = 1BADB002 CAFEF00D 80000001 0000FFFF 00000000 00000000 00000000 00000000 (hex)
10v_mov_b32_e32 v1, 0
11buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:256
12s_waitcnt vmcnt(0)
13buffer_store_dwordx4 v[2:5], v1, s[0:3], 0 offen
14s_endpgm
diff --git a/runtime/test/shaders/cs_w32_andn2_exec.asm b/runtime/test/shaders/cs_w32_andn2_exec.asm
new file mode 100644
index 000000000..29a58990d
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_andn2_exec.asm
@@ -0,0 +1,81 @@
1; s_andn2_saveexec_b32 and s_andn2_wrexec_b32 in a 32-thread wave32 (v0 = lane 0..31). Neither had a test.
2; RDNA2 ISA: s_andn2_saveexec_b32: D = EXEC; EXEC = S0 & ~EXEC; SCC = (EXEC != 0)
3; s_andn2_wrexec_b32: EXEC = S0 & ~EXEC; D = EXEC; SCC = (EXEC != 0) (D gets the new EXEC)
4; S0 is a compare result in VCC, written with all 32 lanes on. The masks are only looked at through mask-aware
5; instructions (s_bcnt1, s_ff1, EXEC writes), not read as data.
6; 1) VCC = lanes with bit 3 clear = 0x00ff00ff; EXEC = 0x0000ffff. saveexec: D = 0x0000ffff,
7; EXEC = 0x00ff00ff & 0xffff0000 = 0x00ff0000 (lanes 16..23), SCC 1.
8; out[0] = s_cselect 1/2 = 1; out[1] = s_bcnt1(EXEC) = 8; out[2] = s_bcnt1(EXEC after EXEC = D) = 16;
9; v1 = 1 under the new EXEC only, so the lanes with v1 != 0 are 16..23: out[3] = bcnt << 8 | ff1 = 8 << 8 | 16 = 2064.
10; 2) VCC = lanes 16..31 = 0xffff0000; EXEC = 0x0f0f0f0f. wrexec: EXEC = 0xffff0000 & 0xf0f0f0f0 = 0xf0f00000
11; (lanes 20-23, 28-31), D = 0xf0f00000, SCC 1.
12; out[4] = bcnt << 8 | ff1 of EXEC = 8 << 8 | 20 = 2068; out[5] = s_cselect 3/4 = 3;
13; out[6] = s_ff1(D) = 20 (D = the old EXEC 0x0f0f0f0f would give 0).
14; 3) VCC = lanes 0..7. EXEC = 0x0000ffff, saveexec: EXEC = 0x000000ff & 0xffff0000 = 0, SCC 0 -> s_cselect 5/6 = 6;
15; EXEC = -1, wrexec: EXEC = 0x000000ff & 0 = 0, SCC 0 -> s_cselect 7/8 = 8. out[7] = 6 << 8 | 8 = 1544.
16; Lane 0 stores the eight words.
17; group: 32,1,1
18; Run: VKC_SUBGROUP_SIZE=32 vk_compute_test cs_w32_andn2_exec.spv 1 dump -> out[0..7] = 1 8 16 2064 2068 3 20 1544
19; mattr: +wavefrontsize32,-wavefrontsize64
20v_mov_b32_e32 v1, 0
21v_and_b32_e32 v2, 8, v0
22v_cmp_eq_u32_e32 vcc_lo, 0, v2
23s_mov_b32 exec_lo, 0xffff
24s_andn2_saveexec_b32 s7, vcc_lo
25s_cselect_b32 s8, 1, 2
26s_bcnt1_i32_b32 s9, exec_lo
27v_mov_b32_e32 v1, 1
28s_mov_b32 exec_lo, s7
29s_bcnt1_i32_b32 s10, exec_lo
30s_mov_b32 exec_lo, -1
31v_cmp_ne_u32_e32 vcc_lo, 0, v1
32s_bcnt1_i32_b32 s11, vcc_lo
33s_ff1_i32_b32 s12, vcc_lo
34s_lshl_b32 s11, s11, 8
35s_or_b32 s11, s11, s12
36v_cmp_le_u32_e32 vcc_lo, 16, v0
37s_mov_b32 exec_lo, 0xf0f0f0f
38s_andn2_wrexec_b32 s13, vcc_lo
39s_cselect_b32 s14, 3, 4
40s_bcnt1_i32_b32 s15, exec_lo
41s_ff1_i32_b32 s16, exec_lo
42s_lshl_b32 s15, s15, 8
43s_or_b32 s15, s15, s16
44s_mov_b32 exec_lo, -1
45s_ff1_i32_b32 s17, s13
46v_cmp_gt_u32_e32 vcc_lo, 8, v0
47s_mov_b32 exec_lo, 0xffff
48s_andn2_saveexec_b32 s18, vcc_lo
49s_cselect_b32 s19, 5, 6
50s_mov_b32 exec_lo, -1
51s_andn2_wrexec_b32 s20, vcc_lo
52s_cselect_b32 s21, 7, 8
53s_mov_b32 exec_lo, -1
54s_lshl_b32 s19, s19, 8
55s_or_b32 s19, s19, s21
56v_cmpx_eq_u32_e32 0, v0
57v_mov_b32_e32 v20, s8
58v_mov_b32_e32 v21, 0
59buffer_store_dword v20, v21, s[0:3], 0 offen
60v_mov_b32_e32 v20, s9
61v_mov_b32_e32 v21, 4
62buffer_store_dword v20, v21, s[0:3], 0 offen
63v_mov_b32_e32 v20, s10
64v_mov_b32_e32 v21, 8
65buffer_store_dword v20, v21, s[0:3], 0 offen
66v_mov_b32_e32 v20, s11
67v_mov_b32_e32 v21, 12
68buffer_store_dword v20, v21, s[0:3], 0 offen
69v_mov_b32_e32 v20, s15
70v_mov_b32_e32 v21, 16
71buffer_store_dword v20, v21, s[0:3], 0 offen
72v_mov_b32_e32 v20, s14
73v_mov_b32_e32 v21, 20
74buffer_store_dword v20, v21, s[0:3], 0 offen
75v_mov_b32_e32 v20, s17
76v_mov_b32_e32 v21, 24
77buffer_store_dword v20, v21, s[0:3], 0 offen
78v_mov_b32_e32 v20, s19
79v_mov_b32_e32 v21, 28
80buffer_store_dword v20, v21, s[0:3], 0 offen
81s_endpgm
diff --git a/runtime/test/shaders/cs_w32_lds_subdword.asm b/runtime/test/shaders/cs_w32_lds_subdword.asm
new file mode 100644
index 000000000..16ffa2edf
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_lds_subdword.asm
@@ -0,0 +1,57 @@
1; ds_write_b8 / ds_write_b8_d16_hi / ds_write_b16 / ds_write_b16_d16_hi and ds_read_u8 / ds_read_i8 / ds_read_u16 /
2; ds_read_i16 (RDNA2 ISA, "Data Share Instructions"). ADDR = vaddr + offset: (bytes).
3; ds_write_b8 MEM[ADDR][7:0] = DATA[7:0] ds_write_b8_d16_hi MEM[ADDR][7:0] = DATA[23:16]
4; ds_write_b16 MEM[ADDR][15:0] = DATA[15:0] ds_write_b16_d16_hi MEM[ADDR][15:0] = DATA[31:16]
5; ds_read_u8/i8 D = zero/sign-extend 8 -> 32 of MEM[ADDR][7:0]
6; ds_read_u16/i16 D = zero/sign-extend 16 -> 32 of MEM[ADDR][15:0]
7; LDS dword 0 = 0x11223344, dword 1 = 0x55667788; DATA = 0xA1B2C3D4. The narrow writes give
8; dword 0 = 0x11B2D444 (byte 1 = 0xD4 from b8, byte 2 = 0xB2 from b8_d16_hi; bytes 0 and 3 kept)
9; dword 1 = 0xA1B2C3D4 (low half 0xC3D4 from b16, high half 0xA1B2 from b16_d16_hi)
10; out[0] ds_read_b32 offset:0 -> 0x11B2D444 out[1] ds_read_b32 offset:4 -> 0xA1B2C3D4
11; out[2] ds_read_i8 offset:2 -> 0xFFFFFFB2 out[3] ds_read_u8 offset:2 -> 0x000000B2
12; out[4] ds_read_i8 offset:3 -> 0x00000011 out[5] ds_read_i16 offset:6 -> 0xFFFFA1B2
13; out[6] ds_read_u16 offset:6 -> 0x0000A1B2 out[7] ds_read_i16 offset:4 -> 0xFFFFC3D4
14; Every lane writes the same bytes, so the result does not depend on lane order.
15; group: 32,1,1
16; Run: vk_compute_test cs_w32_lds_subdword.spv 1 dump
17; -> out[0..7] = 0x11B2D444 0xA1B2C3D4 0xFFFFFFB2 0x000000B2 0x00000011 0xFFFFA1B2 0x0000A1B2 0xFFFFC3D4
18; mattr: +wavefrontsize32,-wavefrontsize64
19v_mov_b32_e32 v2, 0
20v_mov_b32_e32 v4, 0x11223344
21v_mov_b32_e32 v5, 0x55667788
22ds_write_b32 v2, v4
23ds_write_b32 v2, v5 offset:4
24s_waitcnt lgkmcnt(0)
25v_mov_b32_e32 v3, 0xa1b2c3d4
26ds_write_b8 v2, v3 offset:1
27ds_write_b8_d16_hi v2, v3 offset:2
28ds_write_b16 v2, v3 offset:4
29ds_write_b16_d16_hi v2, v3 offset:6
30s_waitcnt lgkmcnt(0)
31ds_read_b32 v10, v2
32ds_read_b32 v11, v2 offset:4
33ds_read_i8 v12, v2 offset:2
34ds_read_u8 v13, v2 offset:2
35ds_read_i8 v14, v2 offset:3
36ds_read_i16 v15, v2 offset:6
37ds_read_u16 v16, v2 offset:6
38ds_read_i16 v17, v2 offset:4
39s_waitcnt lgkmcnt(0)
40v_cmpx_eq_u32_e32 0, v0
41v_mov_b32_e32 v21, 0
42buffer_store_dword v10, v21, s[0:3], 0 offen
43v_mov_b32_e32 v21, 4
44buffer_store_dword v11, v21, s[0:3], 0 offen
45v_mov_b32_e32 v21, 8
46buffer_store_dword v12, v21, s[0:3], 0 offen
47v_mov_b32_e32 v21, 12
48buffer_store_dword v13, v21, s[0:3], 0 offen
49v_mov_b32_e32 v21, 16
50buffer_store_dword v14, v21, s[0:3], 0 offen
51v_mov_b32_e32 v21, 20
52buffer_store_dword v15, v21, s[0:3], 0 offen
53v_mov_b32_e32 v21, 24
54buffer_store_dword v16, v21, s[0:3], 0 offen
55v_mov_b32_e32 v21, 28
56buffer_store_dword v17, v21, s[0:3], 0 offen
57s_endpgm
diff --git a/runtime/test/shaders/cs_w32_lds_wide.asm b/runtime/test/shaders/cs_w32_lds_wide.asm
new file mode 100644
index 000000000..ab563d265
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_lds_wide.asm
@@ -0,0 +1,57 @@
1; ds_write_b64 / ds_write_b96 / ds_write_b128, ds_read_b64 / ds_read_b96 / ds_read_b128 and ds_read2st64_b32
2; (RDNA2 ISA, "Data Share Instructions"). ADDR = vaddr + offset: (bytes); an N-dword access covers
3; MEM[ADDR .. ADDR + 4N - 1], lowest register first. ds_read2st64_b32 reads MEM[ADDR + offset0 * 256] and
4; MEM[ADDR + offset1 * 256] (offsets count 64 dwords).
5; v[30:33] = A B C D, v[34:35] = E F (values below). Writes:
6; b128 v[30:33] at byte 16, b32 0 at byte 60 then b96 v[30:32] at byte 48 (byte 60 stays 0),
7; b64 v[34:35] at byte 64, b32 G at byte 0 and b32 H at byte 256 (LDS is 512 B, the default header).
8; out[0] b128 at 16, first reg -> A 0xCAFEF00D out[1] b128 at 16, last reg -> D 0xFEEDFACE
9; out[2] b96 at 48, last reg -> C 0x600DD00D out[3] b32 at 60 (after b96) -> 0x00000000
10; out[4] b64 at 64, low reg -> E 0x8BADF00D out[5] b64 at 64, high reg -> F 0xDEADC0DE
11; out[6] read2st64 offset0:0 -> G 0x12345678 out[7] read2st64 offset1:1 -> H 0x9ABCDEF0
12; Every lane writes the same dwords, so the result does not depend on lane order.
13; group: 32,1,1
14; Run: vk_compute_test cs_w32_lds_wide.spv 1 dump
15; -> out[0..7] = 0xCAFEF00D 0xFEEDFACE 0x600DD00D 0x00000000 0x8BADF00D 0xDEADC0DE 0x12345678 0x9ABCDEF0
16; mattr: +wavefrontsize32,-wavefrontsize64
17v_mov_b32_e32 v2, 0
18v_mov_b32_e32 v30, 0xcafef00d
19v_mov_b32_e32 v31, 0x0badbeef
20v_mov_b32_e32 v32, 0x600dd00d
21v_mov_b32_e32 v33, 0xfeedface
22v_mov_b32_e32 v34, 0x8badf00d
23v_mov_b32_e32 v35, 0xdeadc0de
24v_mov_b32_e32 v4, 0x12345678
25v_mov_b32_e32 v5, 0x9abcdef0
26ds_write_b128 v2, v[30:33] offset:16
27ds_write_b32 v2, v2 offset:60
28s_waitcnt lgkmcnt(0)
29ds_write_b96 v2, v[30:32] offset:48
30ds_write_b64 v2, v[34:35] offset:64
31ds_write_b32 v2, v4
32ds_write_b32 v2, v5 offset:256
33s_waitcnt lgkmcnt(0)
34ds_read_b128 v[40:43], v2 offset:16
35ds_read_b96 v[44:46], v2 offset:48
36ds_read_b32 v47, v2 offset:60
37ds_read_b64 v[48:49], v2 offset:64
38ds_read2st64_b32 v[50:51], v2 offset1:1
39s_waitcnt lgkmcnt(0)
40v_cmpx_eq_u32_e32 0, v0
41v_mov_b32_e32 v21, 0
42buffer_store_dword v40, v21, s[0:3], 0 offen
43v_mov_b32_e32 v21, 4
44buffer_store_dword v43, v21, s[0:3], 0 offen
45v_mov_b32_e32 v21, 8
46buffer_store_dword v46, v21, s[0:3], 0 offen
47v_mov_b32_e32 v21, 12
48buffer_store_dword v47, v21, s[0:3], 0 offen
49v_mov_b32_e32 v21, 16
50buffer_store_dword v48, v21, s[0:3], 0 offen
51v_mov_b32_e32 v21, 20
52buffer_store_dword v49, v21, s[0:3], 0 offen
53v_mov_b32_e32 v21, 24
54buffer_store_dword v50, v21, s[0:3], 0 offen
55v_mov_b32_e32 v21, 28
56buffer_store_dword v51, v21, s[0:3], 0 offen
57s_endpgm
diff --git a/runtime/test/shaders/cs_w64_mask_detect.asm b/runtime/test/shaders/cs_w64_mask_detect.asm
index 48d3e5313..249e89a9f 100644
--- a/runtime/test/shaders/cs_w64_mask_detect.asm
+++ b/runtime/test/shaders/cs_w64_mask_detect.asm
@@ -5,10 +5,12 @@
5; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64_mask_detect.spv 1 dump --require-wave64 5; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64_mask_detect.spv 1 dump --require-wave64
6; -> out[0] = 48 6; -> out[0] = 48
7; With LEONIDA_W64_EMULATE=1 the same on a 32-wide subgroup. 7; With LEONIDA_W64_EMULATE=1 the same on a 32-wide subgroup.
8; Every lane stores the count at lane * 4, so the 64 lanes fill the 256 bytes vk_compute_test gives one group. (At
9; lane * 64, lanes 4-63 wrote past the buffer through its device address: the V# allows any offset.)
8v_and_b32_e32 v5, 5, v0 10v_and_b32_e32 v5, 5, v0
9v_cmp_ne_u32_e64 s[20:21], 0, v5 11v_cmp_ne_u32_e64 s[20:21], 0, v5
10s_bcnt1_i32_b64 s30, s[20:21] 12s_bcnt1_i32_b64 s30, s[20:21]
11v_mov_b32 v1, s30 13v_mov_b32 v1, s30
12v_lshlrev_b32_e32 v13, 6, v0 14v_lshlrev_b32_e32 v13, 2, v0
13buffer_store_dword v1, v13, s[0:3], 0 offen 15buffer_store_dword v1, v13, s[0:3], 0 offen
14s_endpgm 16s_endpgm
diff --git a/runtime/test/shaders/mullit_readback.py b/runtime/test/shaders/mullit_readback.py
new file mode 100644
index 000000000..007b516b1
--- /dev/null
+++ b/runtime/test/shaders/mullit_readback.py
@@ -0,0 +1,122 @@
1"""Check the ps_mullit semantic fixture with runtime SGPR inputs and RGBA32F readback.
2
3python -I runtime/test/shaders/build.py <work> vs_ids ps_mullit
4python -I runtime/test/shaders/mullit_readback.py <work> <harness directory>
5"""
6import argparse
7import itertools
8import os
9from pathlib import Path
10import random
11import struct
12import sys
13import tempfile
14
15sys.path.insert(0, str(Path(__file__).resolve().parent))
16from check import EXE, run
17
18SIGN = 0x80000000
19INF = 0x7f800000
20MIN_NORMAL = 0x00800000
21ONE = 0x3f800000
22LIGHT_OFF = 0xff7fffff
23PAYLOAD_MASK = 0x40000000
24
25
26def lighting_product(x, y, gate):
27 """Return the expected f32 word using integer significands throughout."""
28 ax, ay = x & ~SIGN, y & ~SIGN
29 if not MIN_NORMAL <= gate <= INF or y in (LIGHT_OFF, SIGN | INF) or ay > INF:
30 return LIGHT_OFF
31 if min(ax, ay) < MIN_NORMAL:
32 return 0
33 if ax > INF:
34 return x
35 sign = (x ^ y) & SIGN
36 if INF in (ax, ay):
37 return sign | INF
38
39 product = (MIN_NORMAL + ax % MIN_NORMAL) * (MIN_NORMAL + ay % MIN_NORMAL)
40 shift = product.bit_length() - 24
41 unit = 1 << shift
42 mantissa, remainder = divmod(product, unit)
43 if 2 * remainder > unit or (2 * remainder == unit and mantissa % 2):
44 mantissa += 1
45 exponent = (ax >> 23) + (ay >> 23) - 127 + shift - 23
46 if mantissa == 2 * MIN_NORMAL:
47 mantissa //= 2
48 exponent += 1
49 # Round before flushing. A product just below MIN_NORMAL can carry into it.
50 if exponent <= 0:
51 return sign
52 if exponent >= 255:
53 return sign | INF
54 return sign | (exponent << 23) | (mantissa - MIN_NORMAL)
55
56
57def operand_triples():
58 gates = (ONE, INF, MIN_NORMAL, 1, MIN_NORMAL - 1, 0, SIGN, SIGN | ONE, 0x7fc23456, 0xffa54321)
59 yield from ((0x40400000, 0xc0200000, gate) for gate in gates)
60 yield from itertools.product(
61 (0, SIGN, 1, SIGN | (MIN_NORMAL - 1), 0x7fa12345, 0xffc12345, INF),
62 (0, SIGN | 1, LIGHT_OFF, INF, SIGN | INF, 0x7fc09876, ONE), (ONE,))
63 yield from itertools.product(
64 (ONE - 4, ONE - 3, ONE - 2, ONE - 1, ONE, SIGN | ONE, 0xbf7ffffe, 0xbf7fffff),
65 (MIN_NORMAL, MIN_NORMAL + 1, MIN_NORMAL + 2), (ONE,))
66 for x, y in ((INF - 1, 0x40000000), (LIGHT_OFF, 0x40000000), (INF - 1, MIN_NORMAL),
67 (MIN_NORMAL, 0x3f000000), (SIGN | MIN_NORMAL, 0x3f000000),
68 (INF, SIGN | ONE), (ONE, LIGHT_OFF - 1)):
69 yield x, y, ONE
70 # Halfway products round up to 0x3fc00002 and down to 0x3fc00004.
71 yield 0x3fc00000, ONE + 1, ONE
72 yield 0x3fc00000, ONE + 3, ONE
73 rng = random.Random(578)
74 for _ in range(28):
75 x = rng.randrange(MIN_NORMAL, INF) | rng.choice((0, SIGN))
76 y = rng.randrange(MIN_NORMAL, INF) | rng.choice((0, SIGN))
77 yield x, y, ONE
78
79
80def mismatch(data, x, y, gate):
81 result = lighting_product(x, y, gate)
82 modified = lighting_product(x ^ SIGN, y & ~SIGN, gate)
83 expected = (result, modified, LIGHT_OFF, result ^ PAYLOAD_MASK)
84 if len(data) != 4 * 4 * 16:
85 return f"expected 256 bytes, got {len(data)}"
86 for i, pixel in enumerate(struct.iter_unpack("<4I", data)):
87 for channel, want, got in zip("RGBA", expected, pixel):
88 # A float attachment can change a NaN payload. Alpha exposes the raw
89 # R payload as a finite word in exactly those cases.
90 if want & ~SIGN > INF and got & ~SIGN > INF:
91 continue
92 if got != want:
93 return f"pixel {i} {channel}: got {got:#010x}, expected {want:#010x}"
94 return None
95
96
97def main():
98 parser = argparse.ArgumentParser(description=__doc__)
99 parser.add_argument("work", type=Path)
100 parser.add_argument("build", type=Path)
101 args = parser.parse_args()
102 spirv = args.work / "spirv"
103 cases = dict.fromkeys(operand_triples())
104 with tempfile.TemporaryDirectory() as tmp:
105 raw = Path(tmp) / "pixels.raw"
106 for inputs in cases:
107 raw.unlink(missing_ok=True)
108 words = ",".join(map(hex, inputs))
109 code, output = run(args.build / ("vk_harness" + EXE), spirv / "vs_ids.spv",
110 spirv / "ps_mullit.spv", raw, "4", "4", env=dict(os.environ, VKH_SGPRS=words))
111 if code:
112 print(f"{words}: vk_harness exited {code}\n{output}", file=sys.stderr)
113 return code
114 problem = mismatch(raw.read_bytes(), *inputs) if raw.is_file() else "missing readback"
115 if problem:
116 sys.exit(f"{words}: {problem}")
117 print(f"{len(cases)} operand triples, {16 * len(cases)} pixels matched")
118 return 0
119
120
121if __name__ == "__main__":
122 sys.exit(main())
diff --git a/runtime/test/shaders/ps_f64_round.asm b/runtime/test/shaders/ps_f64_round.asm
new file mode 100644
index 000000000..41cb8b247
--- /dev/null
+++ b/runtime/test/shaders/ps_f64_round.asm
@@ -0,0 +1,25 @@
1; v_add_f64 under MODE.FP_ROUND[3:2] (3 = toward zero, 0 = nearest even) with extreme magnitudes near +-DBL_MAX.
2; Expected mrt0 bits: 0xc12af665, 0x3fe7ffff, 0xbfffffff, 0xc12af666
3;
4; mrt0.x: 0x7fdd9bb47daa1333 + 0xffefffffffffffff (RTZ) -> 0xffe13225:c12af665; low word 0xc12af665 (#2891; RNE 0xc12af666)
5; mrt0.y: 0xffcffffffffffffe + 0x7fefffffffffffff (RTZ) -> 0x7fe7ffff:ffffffff (borrow across lo=0); hi ^ 0x40000000 = 0x3fe7ffff
6; mrt0.z: 0x7fefffffffffffff + 0x7fefffffffffffff (RTZ) -> 0x7fefffff:ffffffff (finite overflow -> +DBL_MAX); lo ^ 0x40000000 = 0xbfffffff
7; mrt0.w: 0x7fdd9bb47daa1333 + 0xffefffffffffffff after switching back to RNE (0) -> low word 0xc12af666
8s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3
9v_mov_b32_e32 v0, 0x7daa1333
10v_mov_b32_e32 v1, 0x7fdd9bb4
11v_mov_b32_e32 v2, 0xffffffff
12v_mov_b32_e32 v3, 0xffefffff
13v_add_f64 v[4:5], v[0:1], v[2:3]
14v_mov_b32_e32 v6, 0xfffffffe
15v_mov_b32_e32 v7, 0xffcfffff
16v_mov_b32_e32 v8, 0xffffffff
17v_mov_b32_e32 v9, 0x7fefffff
18v_add_f64 v[10:11], v[6:7], v[8:9]
19v_xor_b32_e32 v11, 0x40000000, v11
20v_add_f64 v[12:13], v[8:9], v[8:9]
21v_xor_b32_e32 v12, 0x40000000, v12
22s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0
23v_add_f64 v[14:15], v[0:1], v[2:3]
24exp mrt0 v4, v11, v12, v14 done vm
25s_endpgm
diff --git a/runtime/test/shaders/ps_mul_legacy_denorm.asm b/runtime/test/shaders/ps_mul_legacy_denorm.asm
new file mode 100644
index 000000000..fcca28896
--- /dev/null
+++ b/runtime/test/shaders/ps_mul_legacy_denorm.asm
@@ -0,0 +1,16 @@
1; v_mul_legacy_f32 in the inferred f32 denorm-mode 0 (flush input and output).
2; The two input denormals become signed zero, then DX9 0*x overrides the sign to +0.
3; A finite, nonzero product that underflows keeps its sign when flushed.
4; Expected mrt0 bits: 0x00000000 0x00000000 0x00000000 0x80000000
5v_mov_b32 v0, 0x00000001
6v_mov_b32 v1, 0x4b800000
7v_mul_legacy_f32 v4, v0, v1
8v_mov_b32 v0, 0x80000001
9v_mul_legacy_f32 v5, v0, v1
10v_mov_b32 v0, 0x00800000
11v_mov_b32 v1, 0x3f000000
12v_mul_legacy_f32 v6, v0, v1
13v_mov_b32 v0, 0x80800000
14v_mul_legacy_f32 v7, v0, v1
15exp mrt0 v4, v5, v6, v7 done vm
16s_endpgm
diff --git a/runtime/test/shaders/ps_mul_legacy_denorm_mods.asm b/runtime/test/shaders/ps_mul_legacy_denorm_mods.asm
new file mode 100644
index 000000000..641eaecb3
--- /dev/null
+++ b/runtime/test/shaders/ps_mul_legacy_denorm_mods.asm
@@ -0,0 +1,18 @@
1; The product is flushed before VOP3 output modifiers, and the modified result is flushed again.
2; A subnormal scaled to a normal number by mul:2 or mul:4 must already be zero.
3; On native RDNA2 with IEEE off an omod changes -0 into +0. An ordinary normal product can still
4; be modified. Legacy -0 * -inf gives +0.
5; Expected mrt0 bits: 0x00000000 0x00000000 0x00000000 0x40400000
6v_mov_b32 v0, 0x00800000
7v_mov_b32 v1, 0x3f000000
8v_mul_legacy_f32_e64 v4, v0, v1 mul:2
9v_mov_b32 v2, 0x80800000
10v_mul_legacy_f32_e64 v5, v2, v1 mul:4
11v_mov_b32 v3, 0xff800000
12v_mov_b32 v6, 0x80000000
13v_mul_legacy_f32 v7, v6, v3
14v_mov_b32 v9, 0x40000000
15v_mov_b32 v10, 0x40400000
16v_mul_legacy_f32_e64 v8, v9, v10 div:2
17exp mrt0 v4, v5, v7, v8 done vm
18s_endpgm
diff --git a/runtime/test/shaders/ps_vcmp_64.asm b/runtime/test/shaders/ps_vcmp_64.asm
new file mode 100644
index 000000000..5890e2c54
--- /dev/null
+++ b/runtime/test/shaders/ps_vcmp_64.asm
@@ -0,0 +1,283 @@
1; 64-bit integer VOPC compares: v_cmp_{lt,le,gt,ge}_{u64,i64}, v_cmp_ne_u64, v_cmp_{eq,ne}_i64 (e32 VCC and e64
2; SGPR destination) and v_cmpx_{lt,ge,ne}_i64 / v_cmpx_{gt,le}_u64 (EXEC copied out and put back after each one).
3; Only v_cmp_eq_u64 / v_cmpx_eq_u64 had a test. Inputs read from memory at run time: the V# in s[0:3] points at
4; 0x1000 (num_records 64) and the test seeds 16 dwords, four pairs (A, B) as A.lo A.hi B.lo B.hi:
5; Q0: A = 0x00000000_80000000 B = 0x00000000_00000001 (equal high words; low words differ in bit 31)
6; Q1: A = 0xffffffff_ffffffff B = 0x00000000_00000001 (high words decide; -1 < 1 signed, > unsigned)
7; Q2: A = 0x00000000_00000001 B = 0x00000000_80000000 (Q0 swapped)
8; Q3: A = 0x00000005_00000007 B = 0x00000005_00000007 (equal)
9; RDNA2 ISA: _U64 compares S0.u64 with S1.u64, _I64 compares S0.i64 with S1.i64 (whole 64-bit values; the low word
10; is never signed, so Q0 is A > B for both). Bit 4*k + i of a word is op k of that word on pair Qi:
11; Q0: u A>B, s A>B Q1: u A>B, s A<B Q2: u A<B, s A<B Q3: A == B
12; lt_u64 Q2 = 0x4 lt_i64 Q1 Q2 = 0x6
13; le_u64 Q2 Q3 = 0xc le_i64 Q1 Q2 Q3 = 0xe
14; gt_u64 Q0 Q1 = 0x3 gt_i64 Q0 = 0x1
15; ge_u64 Q0 Q1 Q3 = 0xb ge_i64 Q0 Q3 = 0x9
16; ne Q0 Q1 Q2 = 0x7 eq Q3 = 0x8
17; word 0 = lt_u64 | le_u64<<4 | gt_u64<<8 | ge_u64<<12 = 0x4 | 0xc0 | 0x300 | 0xb000 = 0x0000b3c4
18; word 1 = lt_i64 | le_i64<<4 | gt_i64<<8 | ge_i64<<12 = 0x6 | 0xe0 | 0x100 | 0x9000 = 0x000091e6
19; word 2 = ne_u64 | eq_i64<<4 | ne_i64<<8 | cmpx lt_i64<<12 = 0x7 | 0x80 | 0x700 | 0x6000 = 0x00006787
20; word 3 = cmpx gt_u64 | ge_i64<<4 | le_u64<<8 | ne_i64<<12 = 0x3 | 0x90 | 0xc00 | 0x7000 = 0x00007c93
21; A translation that compared the low words signed would set Q0's lt bits (0x80000000 < 1) and clear Q2's.
22; Expected mrt0 bits: 0x0000b3c4, 0x000091e6, 0x00006787, 0x00007c93
23s_buffer_load_dwordx16 s[4:19], s[0:3], 0
24s_waitcnt lgkmcnt(0)
25v_mov_b32_e32 v0, s4
26v_mov_b32_e32 v1, s5
27v_mov_b32_e32 v2, s6
28v_mov_b32_e32 v3, s7
29v_mov_b32_e32 v4, s8
30v_mov_b32_e32 v5, s9
31v_mov_b32_e32 v6, s10
32v_mov_b32_e32 v7, s11
33v_mov_b32_e32 v8, s12
34v_mov_b32_e32 v9, s13
35v_mov_b32_e32 v10, s14
36v_mov_b32_e32 v11, s15
37v_mov_b32_e32 v12, s16
38v_mov_b32_e32 v13, s17
39v_mov_b32_e32 v14, s18
40v_mov_b32_e32 v15, s19
41s_mov_b32 s20, exec_lo
42; word 0: lt_u64, le_u64, gt_u64, ge_u64
43v_mov_b32_e32 v40, 0
44v_cmp_lt_u64_e32 vcc_lo, v[0:1], v[2:3]
45v_cndmask_b32_e64 v20, 0, 1, vcc_lo
46v_lshl_or_b32 v40, v20, 0, v40
47v_cmp_lt_u64_e32 vcc_lo, v[4:5], v[6:7]
48v_cndmask_b32_e64 v20, 0, 1, vcc_lo
49v_lshl_or_b32 v40, v20, 1, v40
50v_cmp_lt_u64_e32 vcc_lo, v[8:9], v[10:11]
51v_cndmask_b32_e64 v20, 0, 1, vcc_lo
52v_lshl_or_b32 v40, v20, 2, v40
53v_cmp_lt_u64_e32 vcc_lo, v[12:13], v[14:15]
54v_cndmask_b32_e64 v20, 0, 1, vcc_lo
55v_lshl_or_b32 v40, v20, 3, v40
56v_cmp_le_u64_e32 vcc_lo, v[0:1], v[2:3]
57v_cndmask_b32_e64 v20, 0, 1, vcc_lo
58v_lshl_or_b32 v40, v20, 4, v40
59v_cmp_le_u64_e32 vcc_lo, v[4:5], v[6:7]
60v_cndmask_b32_e64 v20, 0, 1, vcc_lo
61v_lshl_or_b32 v40, v20, 5, v40
62v_cmp_le_u64_e32 vcc_lo, v[8:9], v[10:11]
63v_cndmask_b32_e64 v20, 0, 1, vcc_lo
64v_lshl_or_b32 v40, v20, 6, v40
65v_cmp_le_u64_e32 vcc_lo, v[12:13], v[14:15]
66v_cndmask_b32_e64 v20, 0, 1, vcc_lo
67v_lshl_or_b32 v40, v20, 7, v40
68v_cmp_gt_u64_e64 s22, v[0:1], v[2:3]
69v_cndmask_b32_e64 v20, 0, 1, s22
70v_lshl_or_b32 v40, v20, 8, v40
71v_cmp_gt_u64_e64 s22, v[4:5], v[6:7]
72v_cndmask_b32_e64 v20, 0, 1, s22
73v_lshl_or_b32 v40, v20, 9, v40
74v_cmp_gt_u64_e64 s22, v[8:9], v[10:11]
75v_cndmask_b32_e64 v20, 0, 1, s22
76v_lshl_or_b32 v40, v20, 10, v40
77v_cmp_gt_u64_e64 s22, v[12:13], v[14:15]
78v_cndmask_b32_e64 v20, 0, 1, s22
79v_lshl_or_b32 v40, v20, 11, v40
80v_cmp_ge_u64_e64 s22, v[0:1], v[2:3]
81v_cndmask_b32_e64 v20, 0, 1, s22
82v_lshl_or_b32 v40, v20, 12, v40
83v_cmp_ge_u64_e64 s22, v[4:5], v[6:7]
84v_cndmask_b32_e64 v20, 0, 1, s22
85v_lshl_or_b32 v40, v20, 13, v40
86v_cmp_ge_u64_e64 s22, v[8:9], v[10:11]
87v_cndmask_b32_e64 v20, 0, 1, s22
88v_lshl_or_b32 v40, v20, 14, v40
89v_cmp_ge_u64_e64 s22, v[12:13], v[14:15]
90v_cndmask_b32_e64 v20, 0, 1, s22
91v_lshl_or_b32 v40, v20, 15, v40
92; word 1: lt_i64, le_i64, gt_i64, ge_i64
93v_mov_b32_e32 v41, 0
94v_cmp_lt_i64_e32 vcc_lo, v[0:1], v[2:3]
95v_cndmask_b32_e64 v20, 0, 1, vcc_lo
96v_lshl_or_b32 v41, v20, 0, v41
97v_cmp_lt_i64_e32 vcc_lo, v[4:5], v[6:7]
98v_cndmask_b32_e64 v20, 0, 1, vcc_lo
99v_lshl_or_b32 v41, v20, 1, v41
100v_cmp_lt_i64_e32 vcc_lo, v[8:9], v[10:11]
101v_cndmask_b32_e64 v20, 0, 1, vcc_lo
102v_lshl_or_b32 v41, v20, 2, v41
103v_cmp_lt_i64_e32 vcc_lo, v[12:13], v[14:15]
104v_cndmask_b32_e64 v20, 0, 1, vcc_lo
105v_lshl_or_b32 v41, v20, 3, v41
106v_cmp_le_i64_e64 s22, v[0:1], v[2:3]
107v_cndmask_b32_e64 v20, 0, 1, s22
108v_lshl_or_b32 v41, v20, 4, v41
109v_cmp_le_i64_e64 s22, v[4:5], v[6:7]
110v_cndmask_b32_e64 v20, 0, 1, s22
111v_lshl_or_b32 v41, v20, 5, v41
112v_cmp_le_i64_e64 s22, v[8:9], v[10:11]
113v_cndmask_b32_e64 v20, 0, 1, s22
114v_lshl_or_b32 v41, v20, 6, v41
115v_cmp_le_i64_e64 s22, v[12:13], v[14:15]
116v_cndmask_b32_e64 v20, 0, 1, s22
117v_lshl_or_b32 v41, v20, 7, v41
118v_cmp_gt_i64_e32 vcc_lo, v[0:1], v[2:3]
119v_cndmask_b32_e64 v20, 0, 1, vcc_lo
120v_lshl_or_b32 v41, v20, 8, v41
121v_cmp_gt_i64_e32 vcc_lo, v[4:5], v[6:7]
122v_cndmask_b32_e64 v20, 0, 1, vcc_lo
123v_lshl_or_b32 v41, v20, 9, v41
124v_cmp_gt_i64_e32 vcc_lo, v[8:9], v[10:11]
125v_cndmask_b32_e64 v20, 0, 1, vcc_lo
126v_lshl_or_b32 v41, v20, 10, v41
127v_cmp_gt_i64_e32 vcc_lo, v[12:13], v[14:15]
128v_cndmask_b32_e64 v20, 0, 1, vcc_lo
129v_lshl_or_b32 v41, v20, 11, v41
130v_cmp_ge_i64_e64 s22, v[0:1], v[2:3]
131v_cndmask_b32_e64 v20, 0, 1, s22
132v_lshl_or_b32 v41, v20, 12, v41
133v_cmp_ge_i64_e64 s22, v[4:5], v[6:7]
134v_cndmask_b32_e64 v20, 0, 1, s22
135v_lshl_or_b32 v41, v20, 13, v41
136v_cmp_ge_i64_e64 s22, v[8:9], v[10:11]
137v_cndmask_b32_e64 v20, 0, 1, s22
138v_lshl_or_b32 v41, v20, 14, v41
139v_cmp_ge_i64_e64 s22, v[12:13], v[14:15]
140v_cndmask_b32_e64 v20, 0, 1, s22
141v_lshl_or_b32 v41, v20, 15, v41
142; word 2: ne_u64, eq_i64, ne_i64, x:lt_i64
143v_mov_b32_e32 v42, 0
144v_cmp_ne_u64_e32 vcc_lo, v[0:1], v[2:3]
145v_cndmask_b32_e64 v20, 0, 1, vcc_lo
146v_lshl_or_b32 v42, v20, 0, v42
147v_cmp_ne_u64_e32 vcc_lo, v[4:5], v[6:7]
148v_cndmask_b32_e64 v20, 0, 1, vcc_lo
149v_lshl_or_b32 v42, v20, 1, v42
150v_cmp_ne_u64_e32 vcc_lo, v[8:9], v[10:11]
151v_cndmask_b32_e64 v20, 0, 1, vcc_lo
152v_lshl_or_b32 v42, v20, 2, v42
153v_cmp_ne_u64_e32 vcc_lo, v[12:13], v[14:15]
154v_cndmask_b32_e64 v20, 0, 1, vcc_lo
155v_lshl_or_b32 v42, v20, 3, v42
156v_cmp_eq_i64_e64 s22, v[0:1], v[2:3]
157v_cndmask_b32_e64 v20, 0, 1, s22
158v_lshl_or_b32 v42, v20, 4, v42
159v_cmp_eq_i64_e64 s22, v[4:5], v[6:7]
160v_cndmask_b32_e64 v20, 0, 1, s22
161v_lshl_or_b32 v42, v20, 5, v42
162v_cmp_eq_i64_e64 s22, v[8:9], v[10:11]
163v_cndmask_b32_e64 v20, 0, 1, s22
164v_lshl_or_b32 v42, v20, 6, v42
165v_cmp_eq_i64_e64 s22, v[12:13], v[14:15]
166v_cndmask_b32_e64 v20, 0, 1, s22
167v_lshl_or_b32 v42, v20, 7, v42
168v_cmp_ne_i64_e32 vcc_lo, v[0:1], v[2:3]
169v_cndmask_b32_e64 v20, 0, 1, vcc_lo
170v_lshl_or_b32 v42, v20, 8, v42
171v_cmp_ne_i64_e32 vcc_lo, v[4:5], v[6:7]
172v_cndmask_b32_e64 v20, 0, 1, vcc_lo
173v_lshl_or_b32 v42, v20, 9, v42
174v_cmp_ne_i64_e32 vcc_lo, v[8:9], v[10:11]
175v_cndmask_b32_e64 v20, 0, 1, vcc_lo
176v_lshl_or_b32 v42, v20, 10, v42
177v_cmp_ne_i64_e32 vcc_lo, v[12:13], v[14:15]
178v_cndmask_b32_e64 v20, 0, 1, vcc_lo
179v_lshl_or_b32 v42, v20, 11, v42
180v_cmpx_lt_i64_e32 v[0:1], v[2:3]
181s_mov_b32 s21, exec_lo
182s_mov_b32 exec_lo, s20
183v_cndmask_b32_e64 v20, 0, 1, s21
184v_lshl_or_b32 v42, v20, 12, v42
185v_cmpx_lt_i64_e32 v[4:5], v[6:7]
186s_mov_b32 s21, exec_lo
187s_mov_b32 exec_lo, s20
188v_cndmask_b32_e64 v20, 0, 1, s21
189v_lshl_or_b32 v42, v20, 13, v42
190v_cmpx_lt_i64_e32 v[8:9], v[10:11]
191s_mov_b32 s21, exec_lo
192s_mov_b32 exec_lo, s20
193v_cndmask_b32_e64 v20, 0, 1, s21
194v_lshl_or_b32 v42, v20, 14, v42
195v_cmpx_lt_i64_e32 v[12:13], v[14:15]
196s_mov_b32 s21, exec_lo
197s_mov_b32 exec_lo, s20
198v_cndmask_b32_e64 v20, 0, 1, s21
199v_lshl_or_b32 v42, v20, 15, v42
200; word 3: x:gt_u64, x:ge_i64, x:le_u64, x:ne_i64
201v_mov_b32_e32 v43, 0
202v_cmpx_gt_u64_e32 v[0:1], v[2:3]
203s_mov_b32 s21, exec_lo
204s_mov_b32 exec_lo, s20
205v_cndmask_b32_e64 v20, 0, 1, s21
206v_lshl_or_b32 v43, v20, 0, v43
207v_cmpx_gt_u64_e32 v[4:5], v[6:7]
208s_mov_b32 s21, exec_lo
209s_mov_b32 exec_lo, s20
210v_cndmask_b32_e64 v20, 0, 1, s21
211v_lshl_or_b32 v43, v20, 1, v43
212v_cmpx_gt_u64_e32 v[8:9], v[10:11]
213s_mov_b32 s21, exec_lo
214s_mov_b32 exec_lo, s20
215v_cndmask_b32_e64 v20, 0, 1, s21
216v_lshl_or_b32 v43, v20, 2, v43
217v_cmpx_gt_u64_e32 v[12:13], v[14:15]
218s_mov_b32 s21, exec_lo
219s_mov_b32 exec_lo, s20
220v_cndmask_b32_e64 v20, 0, 1, s21
221v_lshl_or_b32 v43, v20, 3, v43
222v_cmpx_ge_i64_e32 v[0:1], v[2:3]
223s_mov_b32 s21, exec_lo
224s_mov_b32 exec_lo, s20
225v_cndmask_b32_e64 v20, 0, 1, s21
226v_lshl_or_b32 v43, v20, 4, v43
227v_cmpx_ge_i64_e32 v[4:5], v[6:7]
228s_mov_b32 s21, exec_lo
229s_mov_b32 exec_lo, s20
230v_cndmask_b32_e64 v20, 0, 1, s21
231v_lshl_or_b32 v43, v20, 5, v43
232v_cmpx_ge_i64_e32 v[8:9], v[10:11]
233s_mov_b32 s21, exec_lo
234s_mov_b32 exec_lo, s20
235v_cndmask_b32_e64 v20, 0, 1, s21
236v_lshl_or_b32 v43, v20, 6, v43
237v_cmpx_ge_i64_e32 v[12:13], v[14:15]
238s_mov_b32 s21, exec_lo
239s_mov_b32 exec_lo, s20
240v_cndmask_b32_e64 v20, 0, 1, s21
241v_lshl_or_b32 v43, v20, 7, v43
242v_cmpx_le_u64_e32 v[0:1], v[2:3]
243s_mov_b32 s21, exec_lo
244s_mov_b32 exec_lo, s20
245v_cndmask_b32_e64 v20, 0, 1, s21
246v_lshl_or_b32 v43, v20, 8, v43
247v_cmpx_le_u64_e32 v[4:5], v[6:7]
248s_mov_b32 s21, exec_lo
249s_mov_b32 exec_lo, s20
250v_cndmask_b32_e64 v20, 0, 1, s21
251v_lshl_or_b32 v43, v20, 9, v43
252v_cmpx_le_u64_e32 v[8:9], v[10:11]
253s_mov_b32 s21, exec_lo
254s_mov_b32 exec_lo, s20
255v_cndmask_b32_e64 v20, 0, 1, s21
256v_lshl_or_b32 v43, v20, 10, v43
257v_cmpx_le_u64_e32 v[12:13], v[14:15]
258s_mov_b32 s21, exec_lo
259s_mov_b32 exec_lo, s20
260v_cndmask_b32_e64 v20, 0, 1, s21
261v_lshl_or_b32 v43, v20, 11, v43
262v_cmpx_ne_i64_e32 v[0:1], v[2:3]
263s_mov_b32 s21, exec_lo
264s_mov_b32 exec_lo, s20
265v_cndmask_b32_e64 v20, 0, 1, s21
266v_lshl_or_b32 v43, v20, 12, v43
267v_cmpx_ne_i64_e32 v[4:5], v[6:7]
268s_mov_b32 s21, exec_lo
269s_mov_b32 exec_lo, s20
270v_cndmask_b32_e64 v20, 0, 1, s21
271v_lshl_or_b32 v43, v20, 13, v43
272v_cmpx_ne_i64_e32 v[8:9], v[10:11]
273s_mov_b32 s21, exec_lo
274s_mov_b32 exec_lo, s20
275v_cndmask_b32_e64 v20, 0, 1, s21
276v_lshl_or_b32 v43, v20, 14, v43
277v_cmpx_ne_i64_e32 v[12:13], v[14:15]
278s_mov_b32 s21, exec_lo
279s_mov_b32 exec_lo, s20
280v_cndmask_b32_e64 v20, 0, 1, s21
281v_lshl_or_b32 v43, v20, 15, v43
282exp mrt0 v40, v41, v42, v43 done vm
283s_endpgm
diff --git a/runtime/test/shaders/ps_vcmp_f32_nan.asm b/runtime/test/shaders/ps_vcmp_f32_nan.asm
new file mode 100644
index 000000000..09c89a4c6
--- /dev/null
+++ b/runtime/test/shaders/ps_vcmp_f32_nan.asm
@@ -0,0 +1,292 @@
1; f32 VOPC compares with a quiet NaN, inputs read from memory at run time (not inline constants, which the driver
2; could fold): v_cmp_{ge,lg,neq,nge}_f32 (e32, VCC), v_cmp_{ngt,nle,nlt,tru}_f32 (e64, SGPR destination) and
3; v_cmpx_{ge,lg,nge,nlt,neq,o,tru,f}_f32 (EXEC is copied out and put back after each one). None of these had a test.
4; The V# in s[0:3] points at 0x1000 (num_records 16); the test seeds 0x1000..0x1008 with 0x7fc10001 0x3f800000
5; 0x40000000, so v1 = NaN, v2 = 1.0, v3 = 2.0.
6; Each compare runs on four pairs; bit 4*k + i of a word is op k of that word on pair i:
7; P0 = (NaN, 1.0) P1 = (1.0, 2.0) P2 = (2.0, 1.0) P3 = (1.0, 1.0)
8; RDNA2 ISA VOPC definitions: GE = S0 >= S1, LG = S0 <> S1 (ordered: false on NaN), O = !isNan(S0) && !isNan(S1),
9; F = 0, TRU = 1; the N forms are the negations, so true on NaN: NGE = !(S0 >= S1), NGT = !(S0 > S1),
10; NLE = !(S0 <= S1), NLT = !(S0 < S1), NEQ = !(S0 == S1). Nibble per op, bits P3 P2 P1 P0:
11; ge P2 P3 = 0b1100 = 0xc ngt P0 P1 P3 = 0b1011 = 0xb
12; lg P1 P2 = 0b0110 = 0x6 nle P0 P2 = 0b0101 = 0x5
13; neq P0 P1 P2 = 0b0111 = 0x7 nlt P0 P2 P3 = 0b1101 = 0xd
14; nge P0 P1 = 0b0011 = 0x3 tru all = 0xf
15; o P1 P2 P3 = 0b1110 = 0xe f none = 0x0
16; word 0 = ge | lg<<4 | neq<<8 | nge<<12 = 0xc | 0x60 | 0x700 | 0x3000 = 0x0000376c
17; word 1 = ngt | nle<<4 | nlt<<8 | tru<<12 = 0xb | 0x50 | 0xd00 | 0xf000 = 0x0000fd5b
18; word 2 = cmpx ge | lg<<4 | nge<<8 | nlt<<12 = 0xc | 0x60 | 0x300 | 0xd000 = 0x0000d36c
19; word 3 = cmpx neq | o<<4 | tru<<8 | f<<12 = 0x7 | 0xe0 | 0xf00 | 0x0000 = 0x00000fe7
20; Expected mrt0 bits: 0x0000376c, 0x0000fd5b, 0x0000d36c, 0x00000fe7
21s_buffer_load_dwordx4 s[4:7], s[0:3], 0
22s_waitcnt lgkmcnt(0)
23v_mov_b32_e32 v1, s4
24v_mov_b32_e32 v2, s5
25v_mov_b32_e32 v3, s6
26s_mov_b32 s20, exec_lo
27; word 0: ge, lg, neq, nge
28v_mov_b32_e32 v40, 0
29v_cmp_ge_f32_e32 vcc_lo, v1, v2
30v_cndmask_b32_e64 v20, 0, 1, vcc_lo
31v_lshl_or_b32 v40, v20, 0, v40
32v_cmp_ge_f32_e32 vcc_lo, v2, v3
33v_cndmask_b32_e64 v20, 0, 1, vcc_lo
34v_lshl_or_b32 v40, v20, 1, v40
35v_cmp_ge_f32_e32 vcc_lo, v3, v2
36v_cndmask_b32_e64 v20, 0, 1, vcc_lo
37v_lshl_or_b32 v40, v20, 2, v40
38v_cmp_ge_f32_e32 vcc_lo, v2, v2
39v_cndmask_b32_e64 v20, 0, 1, vcc_lo
40v_lshl_or_b32 v40, v20, 3, v40
41v_cmp_lg_f32_e32 vcc_lo, v1, v2
42v_cndmask_b32_e64 v20, 0, 1, vcc_lo
43v_lshl_or_b32 v40, v20, 4, v40
44v_cmp_lg_f32_e32 vcc_lo, v2, v3
45v_cndmask_b32_e64 v20, 0, 1, vcc_lo
46v_lshl_or_b32 v40, v20, 5, v40
47v_cmp_lg_f32_e32 vcc_lo, v3, v2
48v_cndmask_b32_e64 v20, 0, 1, vcc_lo
49v_lshl_or_b32 v40, v20, 6, v40
50v_cmp_lg_f32_e32 vcc_lo, v2, v2
51v_cndmask_b32_e64 v20, 0, 1, vcc_lo
52v_lshl_or_b32 v40, v20, 7, v40
53v_cmp_neq_f32_e32 vcc_lo, v1, v2
54v_cndmask_b32_e64 v20, 0, 1, vcc_lo
55v_lshl_or_b32 v40, v20, 8, v40
56v_cmp_neq_f32_e32 vcc_lo, v2, v3
57v_cndmask_b32_e64 v20, 0, 1, vcc_lo
58v_lshl_or_b32 v40, v20, 9, v40
59v_cmp_neq_f32_e32 vcc_lo, v3, v2
60v_cndmask_b32_e64 v20, 0, 1, vcc_lo
61v_lshl_or_b32 v40, v20, 10, v40
62v_cmp_neq_f32_e32 vcc_lo, v2, v2
63v_cndmask_b32_e64 v20, 0, 1, vcc_lo
64v_lshl_or_b32 v40, v20, 11, v40
65v_cmp_nge_f32_e32 vcc_lo, v1, v2
66v_cndmask_b32_e64 v20, 0, 1, vcc_lo
67v_lshl_or_b32 v40, v20, 12, v40
68v_cmp_nge_f32_e32 vcc_lo, v2, v3
69v_cndmask_b32_e64 v20, 0, 1, vcc_lo
70v_lshl_or_b32 v40, v20, 13, v40
71v_cmp_nge_f32_e32 vcc_lo, v3, v2
72v_cndmask_b32_e64 v20, 0, 1, vcc_lo
73v_lshl_or_b32 v40, v20, 14, v40
74v_cmp_nge_f32_e32 vcc_lo, v2, v2
75v_cndmask_b32_e64 v20, 0, 1, vcc_lo
76v_lshl_or_b32 v40, v20, 15, v40
77; word 1: ngt, nle, nlt, tru
78v_mov_b32_e32 v41, 0
79v_cmp_ngt_f32_e64 s22, v1, v2
80v_cndmask_b32_e64 v20, 0, 1, s22
81v_lshl_or_b32 v41, v20, 0, v41
82v_cmp_ngt_f32_e64 s22, v2, v3
83v_cndmask_b32_e64 v20, 0, 1, s22
84v_lshl_or_b32 v41, v20, 1, v41
85v_cmp_ngt_f32_e64 s22, v3, v2
86v_cndmask_b32_e64 v20, 0, 1, s22
87v_lshl_or_b32 v41, v20, 2, v41
88v_cmp_ngt_f32_e64 s22, v2, v2
89v_cndmask_b32_e64 v20, 0, 1, s22
90v_lshl_or_b32 v41, v20, 3, v41
91v_cmp_nle_f32_e64 s22, v1, v2
92v_cndmask_b32_e64 v20, 0, 1, s22
93v_lshl_or_b32 v41, v20, 4, v41
94v_cmp_nle_f32_e64 s22, v2, v3
95v_cndmask_b32_e64 v20, 0, 1, s22
96v_lshl_or_b32 v41, v20, 5, v41
97v_cmp_nle_f32_e64 s22, v3, v2
98v_cndmask_b32_e64 v20, 0, 1, s22
99v_lshl_or_b32 v41, v20, 6, v41
100v_cmp_nle_f32_e64 s22, v2, v2
101v_cndmask_b32_e64 v20, 0, 1, s22
102v_lshl_or_b32 v41, v20, 7, v41
103v_cmp_nlt_f32_e64 s22, v1, v2
104v_cndmask_b32_e64 v20, 0, 1, s22
105v_lshl_or_b32 v41, v20, 8, v41
106v_cmp_nlt_f32_e64 s22, v2, v3
107v_cndmask_b32_e64 v20, 0, 1, s22
108v_lshl_or_b32 v41, v20, 9, v41
109v_cmp_nlt_f32_e64 s22, v3, v2
110v_cndmask_b32_e64 v20, 0, 1, s22
111v_lshl_or_b32 v41, v20, 10, v41
112v_cmp_nlt_f32_e64 s22, v2, v2
113v_cndmask_b32_e64 v20, 0, 1, s22
114v_lshl_or_b32 v41, v20, 11, v41
115v_cmp_tru_f32_e64 s22, v1, v2
116v_cndmask_b32_e64 v20, 0, 1, s22
117v_lshl_or_b32 v41, v20, 12, v41
118v_cmp_tru_f32_e64 s22, v2, v3
119v_cndmask_b32_e64 v20, 0, 1, s22
120v_lshl_or_b32 v41, v20, 13, v41
121v_cmp_tru_f32_e64 s22, v3, v2
122v_cndmask_b32_e64 v20, 0, 1, s22
123v_lshl_or_b32 v41, v20, 14, v41
124v_cmp_tru_f32_e64 s22, v2, v2
125v_cndmask_b32_e64 v20, 0, 1, s22
126v_lshl_or_b32 v41, v20, 15, v41
127; word 2: x:ge, x:lg, x:nge, x:nlt
128v_mov_b32_e32 v42, 0
129v_cmpx_ge_f32_e32 v1, v2
130s_mov_b32 s21, exec_lo
131s_mov_b32 exec_lo, s20
132v_cndmask_b32_e64 v20, 0, 1, s21
133v_lshl_or_b32 v42, v20, 0, v42
134v_cmpx_ge_f32_e32 v2, v3
135s_mov_b32 s21, exec_lo
136s_mov_b32 exec_lo, s20
137v_cndmask_b32_e64 v20, 0, 1, s21
138v_lshl_or_b32 v42, v20, 1, v42
139v_cmpx_ge_f32_e32 v3, v2
140s_mov_b32 s21, exec_lo
141s_mov_b32 exec_lo, s20
142v_cndmask_b32_e64 v20, 0, 1, s21
143v_lshl_or_b32 v42, v20, 2, v42
144v_cmpx_ge_f32_e32 v2, v2
145s_mov_b32 s21, exec_lo
146s_mov_b32 exec_lo, s20
147v_cndmask_b32_e64 v20, 0, 1, s21
148v_lshl_or_b32 v42, v20, 3, v42
149v_cmpx_lg_f32_e32 v1, v2
150s_mov_b32 s21, exec_lo
151s_mov_b32 exec_lo, s20
152v_cndmask_b32_e64 v20, 0, 1, s21
153v_lshl_or_b32 v42, v20, 4, v42
154v_cmpx_lg_f32_e32 v2, v3
155s_mov_b32 s21, exec_lo
156s_mov_b32 exec_lo, s20
157v_cndmask_b32_e64 v20, 0, 1, s21
158v_lshl_or_b32 v42, v20, 5, v42
159v_cmpx_lg_f32_e32 v3, v2
160s_mov_b32 s21, exec_lo
161s_mov_b32 exec_lo, s20
162v_cndmask_b32_e64 v20, 0, 1, s21
163v_lshl_or_b32 v42, v20, 6, v42
164v_cmpx_lg_f32_e32 v2, v2
165s_mov_b32 s21, exec_lo
166s_mov_b32 exec_lo, s20
167v_cndmask_b32_e64 v20, 0, 1, s21
168v_lshl_or_b32 v42, v20, 7, v42
169v_cmpx_nge_f32_e32 v1, v2
170s_mov_b32 s21, exec_lo
171s_mov_b32 exec_lo, s20
172v_cndmask_b32_e64 v20, 0, 1, s21
173v_lshl_or_b32 v42, v20, 8, v42
174v_cmpx_nge_f32_e32 v2, v3
175s_mov_b32 s21, exec_lo
176s_mov_b32 exec_lo, s20
177v_cndmask_b32_e64 v20, 0, 1, s21
178v_lshl_or_b32 v42, v20, 9, v42
179v_cmpx_nge_f32_e32 v3, v2
180s_mov_b32 s21, exec_lo
181s_mov_b32 exec_lo, s20
182v_cndmask_b32_e64 v20, 0, 1, s21
183v_lshl_or_b32 v42, v20, 10, v42
184v_cmpx_nge_f32_e32 v2, v2
185s_mov_b32 s21, exec_lo
186s_mov_b32 exec_lo, s20
187v_cndmask_b32_e64 v20, 0, 1, s21
188v_lshl_or_b32 v42, v20, 11, v42
189v_cmpx_nlt_f32_e32 v1, v2
190s_mov_b32 s21, exec_lo
191s_mov_b32 exec_lo, s20
192v_cndmask_b32_e64 v20, 0, 1, s21
193v_lshl_or_b32 v42, v20, 12, v42
194v_cmpx_nlt_f32_e32 v2, v3
195s_mov_b32 s21, exec_lo
196s_mov_b32 exec_lo, s20
197v_cndmask_b32_e64 v20, 0, 1, s21
198v_lshl_or_b32 v42, v20, 13, v42
199v_cmpx_nlt_f32_e32 v3, v2
200s_mov_b32 s21, exec_lo
201s_mov_b32 exec_lo, s20
202v_cndmask_b32_e64 v20, 0, 1, s21
203v_lshl_or_b32 v42, v20, 14, v42
204v_cmpx_nlt_f32_e32 v2, v2
205s_mov_b32 s21, exec_lo
206s_mov_b32 exec_lo, s20
207v_cndmask_b32_e64 v20, 0, 1, s21
208v_lshl_or_b32 v42, v20, 15, v42
209; word 3: x:neq, x:o, x:tru, x:f
210v_mov_b32_e32 v43, 0
211v_cmpx_neq_f32_e32 v1, v2
212s_mov_b32 s21, exec_lo
213s_mov_b32 exec_lo, s20
214v_cndmask_b32_e64 v20, 0, 1, s21
215v_lshl_or_b32 v43, v20, 0, v43
216v_cmpx_neq_f32_e32 v2, v3
217s_mov_b32 s21, exec_lo
218s_mov_b32 exec_lo, s20
219v_cndmask_b32_e64 v20, 0, 1, s21
220v_lshl_or_b32 v43, v20, 1, v43
221v_cmpx_neq_f32_e32 v3, v2
222s_mov_b32 s21, exec_lo
223s_mov_b32 exec_lo, s20
224v_cndmask_b32_e64 v20, 0, 1, s21
225v_lshl_or_b32 v43, v20, 2, v43
226v_cmpx_neq_f32_e32 v2, v2
227s_mov_b32 s21, exec_lo
228s_mov_b32 exec_lo, s20
229v_cndmask_b32_e64 v20, 0, 1, s21
230v_lshl_or_b32 v43, v20, 3, v43
231v_cmpx_o_f32_e32 v1, v2
232s_mov_b32 s21, exec_lo
233s_mov_b32 exec_lo, s20
234v_cndmask_b32_e64 v20, 0, 1, s21
235v_lshl_or_b32 v43, v20, 4, v43
236v_cmpx_o_f32_e32 v2, v3
237s_mov_b32 s21, exec_lo
238s_mov_b32 exec_lo, s20
239v_cndmask_b32_e64 v20, 0, 1, s21
240v_lshl_or_b32 v43, v20, 5, v43
241v_cmpx_o_f32_e32 v3, v2
242s_mov_b32 s21, exec_lo
243s_mov_b32 exec_lo, s20
244v_cndmask_b32_e64 v20, 0, 1, s21
245v_lshl_or_b32 v43, v20, 6, v43
246v_cmpx_o_f32_e32 v2, v2
247s_mov_b32 s21, exec_lo
248s_mov_b32 exec_lo, s20
249v_cndmask_b32_e64 v20, 0, 1, s21
250v_lshl_or_b32 v43, v20, 7, v43
251v_cmpx_tru_f32_e32 v1, v2
252s_mov_b32 s21, exec_lo
253s_mov_b32 exec_lo, s20
254v_cndmask_b32_e64 v20, 0, 1, s21
255v_lshl_or_b32 v43, v20, 8, v43
256v_cmpx_tru_f32_e32 v2, v3
257s_mov_b32 s21, exec_lo
258s_mov_b32 exec_lo, s20
259v_cndmask_b32_e64 v20, 0, 1, s21
260v_lshl_or_b32 v43, v20, 9, v43
261v_cmpx_tru_f32_e32 v3, v2
262s_mov_b32 s21, exec_lo
263s_mov_b32 exec_lo, s20
264v_cndmask_b32_e64 v20, 0, 1, s21
265v_lshl_or_b32 v43, v20, 10, v43
266v_cmpx_tru_f32_e32 v2, v2
267s_mov_b32 s21, exec_lo
268s_mov_b32 exec_lo, s20
269v_cndmask_b32_e64 v20, 0, 1, s21
270v_lshl_or_b32 v43, v20, 11, v43
271v_cmpx_f_f32_e32 v1, v2
272s_mov_b32 s21, exec_lo
273s_mov_b32 exec_lo, s20
274v_cndmask_b32_e64 v20, 0, 1, s21
275v_lshl_or_b32 v43, v20, 12, v43
276v_cmpx_f_f32_e32 v2, v3
277s_mov_b32 s21, exec_lo
278s_mov_b32 exec_lo, s20
279v_cndmask_b32_e64 v20, 0, 1, s21
280v_lshl_or_b32 v43, v20, 13, v43
281v_cmpx_f_f32_e32 v3, v2
282s_mov_b32 s21, exec_lo
283s_mov_b32 exec_lo, s20
284v_cndmask_b32_e64 v20, 0, 1, s21
285v_lshl_or_b32 v43, v20, 14, v43
286v_cmpx_f_f32_e32 v2, v2
287s_mov_b32 s21, exec_lo
288s_mov_b32 exec_lo, s20
289v_cndmask_b32_e64 v20, 0, 1, s21
290v_lshl_or_b32 v43, v20, 15, v43
291exp mrt0 v40, v41, v42, v43 done vm
292s_endpgm
diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py
index 988fa4a43..cea4f29c0 100644
--- a/runtime/test/shaders/w64_graphics.py
+++ b/runtime/test/shaders/w64_graphics.py
@@ -18,6 +18,10 @@ second device stand in for the missing size: W64G_SAVE_REF=<dir> stores each 64-
18it (or that has 64 as its only size: AMD GCN), and W64G_REF=<dir> compares every run of the other device with those 18it (or that has 64 as its only size: AMD GCN), and W64G_REF=<dir> compares every run of the other device with those
19files (equal for A and B, different for C). 19files (equal for A and B, different for C).
20 20
21A device whose subgroups can be narrower than 32 (Intel: 8..32) and that could not be held to 32 or 64 skips the tier
22A and B pixel fixtures: its fragment stage may run fewer live lanes than 32 (Intel UHD 770 reports 32 but runs 16 live
23invocations), and tiers A and B assume 32 or 64 live lanes (TEST-433).
24
21The vs_w64_* fixtures (TEST-251) are vertex shaders: Vulkan cannot require a vertex subgroup size, so the two sizes 25The vs_w64_* fixtures (TEST-251) are vertex shaders: Vulkan cannot require a vertex subgroup size, so the two sizes
22come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+). 26come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+).
23Each draws 960 vertices with zero area (VKH_VERTICES) and stores four words per vertex to the heap; vs_w64_c_lane_id 27Each draws 960 vertices with zero area (VKH_VERTICES) and stores four words per vertex to the heap; vs_w64_c_lane_id
@@ -30,6 +34,7 @@ drawn after vs_ids with VKH_GS, finds its triangle from the vertex number vs_ids
30words per triangle to the heap; gs_w64_c_lane_id is the geometry probe. RADV puts at most 42 GS invocations in a wave64. 34words per triangle to the heap; gs_w64_c_lane_id is the geometry probe. RADV puts at most 42 GS invocations in a wave64.
31""" 35"""
32import os 36import os
37import re
33import struct 38import struct
34import subprocess 39import subprocess
35import sys 40import sys
@@ -237,6 +242,9 @@ def _draw_heap(tools, spirv, name, size, tmp):
237 return [tuple(words[VS_RECORDS + 4 * v:VS_RECORDS + 4 * v + 4]) for v in range(records)], words 242 return [tuple(words[VS_RECORDS + 4 * v:VS_RECORDS + 4 * v + 4]) for v in range(records)], words
238 243
239 244
245_device_min = [None] # the smallest subgroup size vk_harness reported for the device
246
247
240def draw(tools, spirv, name, size, tmp): 248def draw(tools, spirv, name, size, tmp):
241 """(words per pixel, heap words or None, applied) of one draw. `applied`: the required size took effect (size 249 """(words per pixel, heap words or None, applied) of one draw. `applied`: the required size took effect (size
242 None: no size asked, applied is None). The words are None when the draw failed; then `heap` is the message.""" 250 None: no size asked, applied is None). The words are None when the draw failed; then `heap` is the message."""
@@ -264,6 +272,9 @@ def draw(tools, spirv, name, size, tmp):
264 data = raw.read_bytes() 272 data = raw.read_bytes()
265 if len(data) != W * H * 16: 273 if len(data) != W * H * 16:
266 return None, f"{len(data)} bytes of pixels, expected {W * H * 16}", None 274 return None, f"{len(data)} bytes of pixels, expected {W * H * 16}", None
275 m = re.search(r"subgroup (\d+)\.\.(\d+)", out)
276 if m:
277 _device_min[0] = int(m.group(1))
267 applied = None 278 applied = None
268 if size: 279 if size:
269 applied = f"fragment subgroup size: {size}\n" in out.replace("\r", "") 280 applied = f"fragment subgroup size: {size}\n" in out.replace("\r", "")
@@ -330,6 +341,13 @@ def check(tools, spirv, name):
330 if size is None or applied: 341 if size is None or applied:
331 runs[size] = (words, heap) 342 runs[size] = (words, heap)
332 compared = False 343 compared = False
344 # Tiers A and B mean exact on 32 or 64 live lanes. A device whose subgroups can be narrower than 32 (Intel:
345 # 8..32) and that could not be held to 32 or 64 may run fewer live lanes than it reports (UHD 770: 16 live
346 # behind a reported 32): reads across them return garbage.
347 if tier in ("A", "B") and name.startswith("ps_") and 64 not in runs and 32 not in runs \
348 and _device_min[0] is not None and _device_min[0] < 32:
349 return Skip(f"SKIP (the fragment stage may run fewer live lanes than 32 here ({_device_min[0]}..) "
350 "and 32 or 64 could not be required: tiers A and B assume 32 or 64 live lanes)")
333 if save and 64 in runs: 351 if save and 64 in runs:
334 Path(save).mkdir(parents=True, exist_ok=True) 352 Path(save).mkdir(parents=True, exist_ok=True)
335 (Path(save) / (name + ".ref64.raw")).write_bytes(b"".join(struct.pack("<4I", *w) for w in runs[64][0])) 353 (Path(save) / (name + ".ref64.raw")).write_bytes(b"".join(struct.pack("<4I", *w) for w in runs[64][0]))
@@ -354,6 +372,8 @@ def check(tools, spirv, name):
354 for size, (words, heap) in runs.items(): 372 for size, (words, heap) in runs.items():
355 if size == 64: 373 if size == 64:
356 continue 374 continue
375 if tier == "C" and comparable(name, ref_words, None) != comparable(name, words, None):
376 return "a partition-invariant word differs from the 64-lane reference"
357 if tier == "C": 377 if tier == "C":
358 if comparable(name, ref_words, None) != comparable(name, words, None): 378 if comparable(name, ref_words, None) != comparable(name, words, None):
359 return "a word that must not depend on the partition differs from the 64-lane reference" 379 return "a word that must not depend on the partition differs from the 64-lane reference"
@@ -372,7 +392,13 @@ def main(argv):
372 sys.exit(__doc__) 392 sys.exit(__doc__)
373 spirv = os.path.join(argv[0], "spirv") 393 spirv = os.path.join(argv[0], "spirv")
374 tools = argv[1] if len(argv) > 1 and os.path.isdir(argv[1]) else os.path.join(os.path.dirname(__file__), "..", "..", "build") 394 tools = argv[1] if len(argv) > 1 and os.path.isdir(argv[1]) else os.path.join(os.path.dirname(__file__), "..", "..", "build")
375 names = [a for a in argv[1:] if a in FIXTURES] or sorted(FIXTURES) 395 start = 2 if len(argv) > 1 and os.path.isdir(argv[1]) else 1
396 requested = argv[start:]
397 unknown = [a for a in requested if a not in FIXTURES]
398 if unknown:
399 print(f"Unknown fixture name{'s' if len(unknown) > 1 else ''}: {', '.join(unknown)}", file=sys.stderr)
400 return 1
401 names = requested or sorted(FIXTURES)
376 failed = 0 402 failed = 0
377 for name in names: 403 for name in names:
378 problem = check(os.path.abspath(tools), spirv, name) 404 problem = check(os.path.abspath(tools), spirv, name)
diff --git a/runtime/test/test_pe_loader_bounds.cpp b/runtime/test/test_pe_loader_bounds.cpp
index 5055df312..bc64c7f5d 100644
--- a/runtime/test/test_pe_loader_bounds.cpp
+++ b/runtime/test/test_pe_loader_bounds.cpp
@@ -20,6 +20,8 @@
20#include "pe_loader.h" 20#include "pe_loader.h"
21#endif 21#endif
22 22
23#include "free_image_base.h"
24
23#if __has_include("../shims/shims.h") 25#if __has_include("../shims/shims.h")
24#include "../shims/shims.h" 26#include "../shims/shims.h"
25#elif __has_include("shims.h") 27#elif __has_include("shims.h")
@@ -159,7 +161,7 @@ std::vector<uint8_t> make_base_image(uint32_t image_size = 0x2000, uint32_t file
159 nt->FileHeader.NumberOfSections = 1; 161 nt->FileHeader.NumberOfSections = 1;
160 nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); 162 nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
161 nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; 163 nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
162 nt->OptionalHeader.ImageBase = 0x140000000; 164 nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x140000000);
163 nt->OptionalHeader.AddressOfEntryPoint = 0x1000; 165 nt->OptionalHeader.AddressOfEntryPoint = 0x1000;
164 nt->OptionalHeader.SizeOfHeaders = 0x200; 166 nt->OptionalHeader.SizeOfHeaders = 0x200;
165 nt->OptionalHeader.SizeOfImage = image_size; 167 nt->OptionalHeader.SizeOfImage = image_size;
@@ -736,7 +738,7 @@ void test_forwarder_ordinal_range() {
736 auto dll = make_base_image(0x2000, 0x400); 738 auto dll = make_base_image(0x2000, 0x400);
737 std::fill(dll.begin() + 0x200, dll.end(), uint8_t{0}); 739 std::fill(dll.begin() + 0x200, dll.end(), uint8_t{0});
738 auto* dnt = nt_header_of(dll); 740 auto* dnt = nt_header_of(dll);
739 dnt->OptionalHeader.ImageBase = 0x150000000ull; 741 dnt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x150000000ull);
740 dnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] = {0x1000, 0x100}; 742 dnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] = {0x1000, 0x100};
741 auto* ed = reinterpret_cast<IMAGE_EXPORT_DIRECTORY*>(dll.data() + 0x200); // RVA 0x1000 743 auto* ed = reinterpret_cast<IMAGE_EXPORT_DIRECTORY*>(dll.data() + 0x200); // RVA 0x1000
742 ed->Base = 1; 744 ed->Base = 1;
diff --git a/runtime/test/unimplemented_policy_test.cpp b/runtime/test/unimplemented_policy_test.cpp
index 3bacf40a0..77a6e5595 100644
--- a/runtime/test/unimplemented_policy_test.cpp
+++ b/runtime/test/unimplemented_policy_test.cpp
@@ -27,6 +27,7 @@
27 27
28#include "../shims/shims.h" 28#include "../shims/shims.h"
29#include "../src/pe_loader.h" 29#include "../src/pe_loader.h"
30#include "free_image_base.h"
30 31
31namespace { 32namespace {
32 33
@@ -73,7 +74,7 @@ std::vector<uint8_t> make_image() {
73 nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); 74 nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
74 nt->FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_LARGE_ADDRESS_AWARE; 75 nt->FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_LARGE_ADDRESS_AWARE;
75 nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; 76 nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
76 nt->OptionalHeader.ImageBase = 0x180000000; 77 nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x180000000);
77 nt->OptionalHeader.AddressOfEntryPoint = 0; 78 nt->OptionalHeader.AddressOfEntryPoint = 0;
78 nt->OptionalHeader.SizeOfHeaders = 0x200; 79 nt->OptionalHeader.SizeOfHeaders = 0x200;
79 nt->OptionalHeader.SizeOfImage = 0x2000; 80 nt->OptionalHeader.SizeOfImage = 0x2000;
diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp
index 6b72034e5..caa77be76 100644
--- a/runtime/test/vk_bindless_test.cpp
+++ b/runtime/test/vk_bindless_test.cpp
@@ -119,8 +119,14 @@ int main(int argc, char** argv) {
119 } 119 }
120 constexpr std::uint32_t W = 64, H = 64, TW = 8; 120 constexpr std::uint32_t W = 64, H = 64, TW = 8;
121 constexpr std::uint32_t table_va = 256; // console VA of the descriptor table: T# at +0, S# at +32 121 constexpr std::uint32_t table_va = 256; // console VA of the descriptor table: T# at +0, S# at +32
122 const DescriptorKey tsharp{0x11111111, 0x22222222, 0x33333333, 0x44444444, 122 // Any 8 dwords as the lookup key, except FORMAT (word 1 [28:20]): the translator picks the float, uint or sint
123 0x55555555, 0x66666666, 0x77777777, 0x88888888}; // any 8 dwords: only the key matters 123 // view of the image from it, and every view this test binds is R8G8B8A8_UNORM, so it is 56 (8_8_8_8_UNORM).
124 // 0x22222222 had 34 (10_11_11_UINT): every sample went through the uint alias of a UNORM view, which Vulkan
125 // leaves undefined (VUID-vkCmdDraw-format-07753, reported by GPU-assisted validation).
126 constexpr std::uint32_t tsharp_word1 = (0x22222222u & ~(0x1FFu << 20)) | (56u << 20);
127 static_assert(((tsharp_word1 >> 20) & 0x1FF) == 56, "the T#'s FORMAT must be 8_8_8_8_UNORM");
128 const DescriptorKey tsharp{0x11111111, tsharp_word1, 0x33333333, 0x44444444,
129 0x55555555, 0x66666666, 0x77777777, 0x88888888};
124 const std::array<std::uint32_t, 4> ssharp{0x5a5a0001, 0x00000002, 0x00000003, 0x00000004}; 130 const std::array<std::uint32_t, 4> ssharp{0x5a5a0001, 0x00000002, 0x00000003, 0x00000004};
125 131
126 const PFN_vkGetInstanceProcAddr gipa = load_vulkan(); 132 const PFN_vkGetInstanceProcAddr gipa = load_vulkan();
diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp
index bb620a2f1..cf32f094b 100644
--- a/runtime/test/vk_command_replay_test.cpp
+++ b/runtime/test/vk_command_replay_test.cpp
@@ -1192,7 +1192,12 @@ int part_i(vktest::Device& d) {
1192 1192
1193int main() { 1193int main() {
1194 vktest::Device device; 1194 vktest::Device device;
1195 EXPECT(device.create()); 1195 const auto status = device.initialize();
1196 if (status == vktest::DeviceStatus::unavailable) {
1197 std::printf("vk_command_replay_test: no Vulkan device, skipped\n");
1198 return 77;
1199 }
1200 EXPECT(status == vktest::DeviceStatus::ready);
1196 if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) || 1201 if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) ||
1197 part_g(device) || part_h(device) || part_i(device)) 1202 part_g(device) || part_h(device) || part_i(device))
1198 return 1; 1203 return 1;
diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp
index f0f7c4605..69e3bd014 100644
--- a/runtime/test/vk_compute_test.cpp
+++ b/runtime/test/vk_compute_test.cpp
@@ -7,6 +7,9 @@
7// dispatch (submit to queue idle) as "bench ms: median=.. min=.. max=.. n=..". The buffer is not cleared in between. 7// dispatch (submit to queue idle) as "bench ms: median=.. min=.. max=.. n=..". The buffer is not cleared in between.
8// VKC_OUT_WORDS=N (env): make the output buffer at least N words (default groups * 64), so a single group can 8// VKC_OUT_WORDS=N (env): make the output buffer at least N words (default groups * 64), so a single group can
9// write more than one word per thread. VKC_DUMP=<file> (env): write the whole buffer to <file> after the dispatch. 9// write more than one word per thread. VKC_DUMP=<file> (env): write the whole buffer to <file> after the dispatch.
10// VKC_HEAP_INIT=<file> (env): copy the file's bytes to the start of the buffer (Xbox VA 0) after the default fill
11// and before the dispatch, so a program can read prepared inputs (a root table, descriptors, data) from the heap.
12// The file must fit in the buffer (raise VKC_OUT_WORDS); bytes past it keep the fill.
10// --require-wave64: require full 64-wide subgroups (local size X must be a multiple of 64), or exit 77. 13// --require-wave64: require full 64-wide subgroups (local size X must be a multiple of 64), or exit 77.
11// VKC_SGPRS=w4,w5,... (env): set s4, s5, ... (decimal or 0x hex, up to s31), the user SGPRs after the output V#, 14// VKC_SGPRS=w4,w5,... (env): set s4, s5, ... (decimal or 0x hex, up to s31), the user SGPRs after the output V#,
12// so a test can take input words (cs_user_sgprs.asm). They are zero otherwise. Same syntax as vk_harness's VKH_SGPRS. 15// so a test can take input words (cs_user_sgprs.asm). They are zero otherwise. Same syntax as vk_harness's VKH_SGPRS.
@@ -87,6 +90,16 @@ int main(int argc, char** argv) {
87 const uint32_t origins = workgroup_yz ? groups * groups_y * groups_z : 0; 90 const uint32_t origins = workgroup_yz ? groups * groups_y * groups_z : 0;
88 const char* out_words_env = std::getenv("VKC_OUT_WORDS"); 91 const char* out_words_env = std::getenv("VKC_OUT_WORDS");
89 const char* dump_path = std::getenv("VKC_DUMP"); 92 const char* dump_path = std::getenv("VKC_DUMP");
93 const char* heap_init_path = std::getenv("VKC_HEAP_INIT");
94 std::vector<char> heap_init;
95 if (heap_init_path) {
96 std::ifstream f(heap_init_path, std::ios::binary);
97 if (!f) {
98 std::fprintf(stderr, "VKC_HEAP_INIT: could not read %s\n", heap_init_path);
99 return 2;
100 }
101 heap_init.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
102 }
90 uint32_t out_words = 0; 103 uint32_t out_words = 0;
91 if (out_words_env) { 104 if (out_words_env) {
92 char* end; 105 char* end;
@@ -218,6 +231,14 @@ int main(int argc, char** argv) {
218 CHECK(vkBindBufferMemory(dev, buf, mem, 0)); 231 CHECK(vkBindBufferMemory(dev, buf, mem, 0));
219 void* map; CHECK(vkMapMemory(dev, mem, 0, bytes, 0, &map)); 232 void* map; CHECK(vkMapMemory(dev, mem, 0, bytes, 0, &map));
220 std::memset(map, workgroup_yz || !std::strcmp(argv[3], "exec64") ? 0 : 0xEE, size_t(bytes)); 233 std::memset(map, workgroup_yz || !std::strcmp(argv[3], "exec64") ? 0 : 0xEE, size_t(bytes));
234 if (heap_init_path) {
235 if (heap_init.size() > size_t(bytes)) {
236 std::fprintf(stderr, "VKC_HEAP_INIT: %s is %zu bytes, the buffer %llu (raise VKC_OUT_WORDS)\n",
237 heap_init_path, heap_init.size(), static_cast<unsigned long long>(bytes));
238 return 2;
239 }
240 if (!heap_init.empty()) std::memcpy(map, heap_init.data(), heap_init.size());
241 }
221 if (!std::strcmp(argv[3], "bvh")) { 242 if (!std::strcmp(argv[3], "bvh")) {
222 // AMD-format BVH in the heap (runtime/test/shaders/cs_bvh.asm): box32 root at 0x100 whose children are a 243 // AMD-format BVH in the heap (runtime/test/shaders/cs_bvh.asm): box32 root at 0x100 whose children are a
223 // triangle at z=10 (node 0x40, addr 0x200), a triangle at z=5 (node 0x48, addr 0x240), a box the ray 244 // triangle at z=10 (node 0x40, addr 0x200), a triangle at z=5 (node 0x48, addr 0x240), a box the ray
diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp
index 89505eab3..7bd679f10 100644
--- a/runtime/test/vk_harness.cpp
+++ b/runtime/test/vk_harness.cpp
@@ -23,12 +23,18 @@
23// VKH_SUBGROUP_SIZE=32|64 requires that subgroup size of the fragment shader (or of the compute or geometry 23// VKH_SUBGROUP_SIZE=32|64 requires that subgroup size of the fragment shader (or of the compute or geometry
24// stage under test); stderr says "fragment subgroup size: N" when it took effect and 24// stage under test); stderr says "fragment subgroup size: N" when it took effect and
25// "... not available" when the device cannot require it (exit code stays 0). 25// "... not available" when the device cannot require it (exit code stays 0).
26// VKH_TEX_RGBA=<file> binds a 2D RGBA8 texture (u32 width, u32 height, width*height*4 bytes) at bindless
27// set 0 image index 1 (with 1x1 magenta at index 0), writes a T# at VKH_TSHARP_VA
28// (default 0x100) in the 64 KiB heap, and registers VKH_SSHARP (4 comma-separated
29// dwords, default 0x92,0xc00000,0x14500000,0) at sampler index 1.
26// 30//
27#define VK_NO_PROTOTYPES 31#define VK_NO_PROTOTYPES
28#include "vulkan_loader.h" 32#include "vulkan_loader.h"
29#include "vk_device_pick.h" 33#include "vk_device_pick.h"
30#include "vk_shader_fma.h" 34#include "vk_shader_fma.h"
31#include "vk_pc_tail.h" 35#include "vk_pc_tail.h"
36#include "../src/descriptor_table.h"
37#include "../src/gfx10_descriptors.h"
32 38
33#include <cctype> 39#include <cctype>
34#include <cstddef> 40#include <cstddef>
@@ -185,6 +191,55 @@ int main(int argc, char** argv) {
185 heap_bytes, heap_env); 191 heap_bytes, heap_env);
186 return 2; 192 return 2;
187 } 193 }
194 const char* tex_rgba_path = std::getenv("VKH_TEX_RGBA");
195 if (tex_rgba_path && !*tex_rgba_path) tex_rgba_path = nullptr;
196 uint32_t tsharp_va = 0x100;
197 uint32_t ssharp[8] = {0x92, 0xc00000, 0x14500000, 0,
198 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu};
199 uint32_t tex_w = 0, tex_h = 0;
200 std::vector<uint8_t> tex_pixels;
201 if (tex_rgba_path) {
202 if (const char* va_env = std::getenv("VKH_TSHARP_VA"); va_env && *va_env) {
203 const char* p = va_env;
204 if (!parse_u32(p, tsharp_va) || *p || (tsharp_va & 3u) || tsharp_va > heap_bytes - 32) {
205 std::fprintf(stderr, "VKH_TSHARP_VA: expected 4-byte aligned offset at most 0x%x, got \"%s\"\n",
206 heap_bytes - 32, va_env);
207 return 2;
208 }
209 }
210 if (const char* ss_env = std::getenv("VKH_SSHARP"); ss_env && *ss_env) {
211 const char* p = ss_env;
212 for (int i = 0; i < 4; ++i) {
213 if (i && *p++ != ',') {
214 std::fprintf(stderr, "VKH_SSHARP: expected 4 comma-separated dwords, got \"%s\"\n", ss_env);
215 return 2;
216 }
217 if (!parse_u32(p, ssharp[i])) {
218 std::fprintf(stderr, "VKH_SSHARP: expected 4 comma-separated dwords, got \"%s\"\n", ss_env);
219 return 2;
220 }
221 }
222 if (*p) {
223 std::fprintf(stderr, "VKH_SSHARP: expected 4 comma-separated dwords, got \"%s\"\n", ss_env);
224 return 2;
225 }
226 }
227 std::ifstream tf(tex_rgba_path, std::ios::binary);
228 uint32_t hdr[2] = {};
229 if (!tf.read(reinterpret_cast<char*>(hdr), 8) || hdr[0] == 0 || hdr[1] == 0 ||
230 uint64_t(hdr[0]) * uint64_t(hdr[1]) > (1ull << 26)) {
231 std::fprintf(stderr, "VKH_TEX_RGBA: invalid header in %s\n", tex_rgba_path);
232 return 1;
233 }
234 tex_w = hdr[0];
235 tex_h = hdr[1];
236 tex_pixels.resize(size_t(tex_w) * size_t(tex_h) * 4);
237 if (!tf.read(reinterpret_cast<char*>(tex_pixels.data()), std::streamsize(tex_pixels.size()))) {
238 std::fprintf(stderr, "VKH_TEX_RGBA: truncated pixel data in %s\n", tex_rgba_path);
239 return 1;
240 }
241 }
242 const bool need_heap = heap_env != nullptr || tex_rgba_path != nullptr;
188 gipa = load_vulkan(); 243 gipa = load_vulkan();
189 if (!gipa) return 1; 244 if (!gipa) return 1;
190 VkInstance inst = VK_NULL_HANDLE; 245 VkInstance inst = VK_NULL_HANDLE;
@@ -365,13 +420,22 @@ int main(int argc, char** argv) {
365 chain = &f13; 420 chain = &f13;
366 } 421 }
367 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 422 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
368 if (heap_env || mesh_compute) { 423 if (need_heap || mesh_compute) {
369 // 77 is the "this device cannot run the test" code that check.py and run_gpu_tests.py report as SKIP. 424 // 77 is the "this device cannot run the test" code that check.py and run_gpu_tests.py report as SKIP.
370 if (!f12q.bufferDeviceAddress) { 425 if (!f12q.bufferDeviceAddress) {
371 std::fprintf(stderr, "unsupported: %s needs bufferDeviceAddress\n", heap_env ? "VKH_HEAP" : "VKH_MESH_COMPUTE"); 426 std::fprintf(stderr, "unsupported: %s needs bufferDeviceAddress\n",
427 tex_rgba_path ? "VKH_TEX_RGBA" : heap_env ? "VKH_HEAP" : "VKH_MESH_COMPUTE");
372 return 77; 428 return 77;
373 } 429 }
374 f12.bufferDeviceAddress = VK_TRUE; 430 f12.bufferDeviceAddress = VK_TRUE;
431 if (tex_rgba_path) {
432 if (!f12q.runtimeDescriptorArray || !f12q.descriptorIndexing) {
433 std::fprintf(stderr, "unsupported: VKH_TEX_RGBA needs runtimeDescriptorArray and descriptorIndexing\n");
434 return 77;
435 }
436 f12.runtimeDescriptorArray = VK_TRUE;
437 f12.descriptorIndexing = VK_TRUE;
438 }
375 f12.pNext = chain; 439 f12.pNext = chain;
376 chain = &f12; 440 chain = &f12;
377 } 441 }
@@ -425,10 +489,17 @@ int main(int argc, char** argv) {
425 } 489 }
426 feats.shaderFloat64 = VK_TRUE; 490 feats.shaderFloat64 = VK_TRUE;
427 } 491 }
428 if (heap_env || mesh_compute) { 492 if (need_heap || mesh_compute) {
429 if (!f2q.features.shaderInt64) { std::fprintf(stderr, "unsupported: 64-bit addresses need shaderInt64\n"); return 77; } 493 if (!f2q.features.shaderInt64) { std::fprintf(stderr, "unsupported: 64-bit addresses need shaderInt64\n"); return 77; }
430 feats.shaderInt64 = VK_TRUE; // heap and --mesh-compute output addresses are 64-bit 494 feats.shaderInt64 = VK_TRUE; // heap and --mesh-compute output addresses are 64-bit
431 } 495 }
496 if (tex_rgba_path) {
497 if (!f2q.features.shaderSampledImageArrayDynamicIndexing) {
498 std::fprintf(stderr, "unsupported: VKH_TEX_RGBA needs shaderSampledImageArrayDynamicIndexing\n");
499 return 77;
500 }
501 feats.shaderSampledImageArrayDynamicIndexing = VK_TRUE;
502 }
432 dci.pEnabledFeatures = &feats; 503 dci.pEnabledFeatures = &feats;
433 VkDevice dev; 504 VkDevice dev;
434 CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); 505 CHECK(vkCreateDevice(pd, &dci, nullptr, &dev));
@@ -603,8 +674,27 @@ int main(int argc, char** argv) {
603 const VkShaderStageFlags pcs = (mesh ? VK_SHADER_STAGE_MESH_BIT_EXT : VK_SHADER_STAGE_VERTEX_BIT) | 674 const VkShaderStageFlags pcs = (mesh ? VK_SHADER_STAGE_MESH_BIT_EXT : VK_SHADER_STAGE_VERTEX_BIT) |
604 VK_SHADER_STAGE_FRAGMENT_BIT | (gs_path ? VK_SHADER_STAGE_GEOMETRY_BIT : 0) | 675 VK_SHADER_STAGE_FRAGMENT_BIT | (gs_path ? VK_SHADER_STAGE_GEOMETRY_BIT : 0) |
605 (mesh_compute ? VK_SHADER_STAGE_COMPUTE_BIT : 0); 676 (mesh_compute ? VK_SHADER_STAGE_COMPUTE_BIT : 0);
677 VkDescriptorSetLayout dsl = VK_NULL_HANDLE;
678 VkDescriptorSet ds = VK_NULL_HANDLE;
679 VkImage tex_fallback_img = VK_NULL_HANDLE, tex_img = VK_NULL_HANDLE;
680 VkBuffer tex_staging = VK_NULL_HANDLE;
681 if (tex_rgba_path) {
682 LOADD(vkCreateDescriptorSetLayout);
683 VkDescriptorSetLayoutBinding dslb[3]{};
684 dslb[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_ALL, nullptr};
685 dslb[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 2, VK_SHADER_STAGE_ALL, nullptr};
686 dslb[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_ALL, nullptr};
687 VkDescriptorSetLayoutCreateInfo dslci{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
688 dslci.bindingCount = 3;
689 dslci.pBindings = dslb;
690 CHECK(vkCreateDescriptorSetLayout(dev, &dslci, nullptr, &dsl));
691 }
606 VkPushConstantRange pcr{pcs, 0, pc_bytes}; 692 VkPushConstantRange pcr{pcs, 0, pc_bytes};
607 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 693 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
694 if (dsl) {
695 pli.setLayoutCount = 1;
696 pli.pSetLayouts = &dsl;
697 }
608 pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; 698 pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
609 // --pc-tail-ubo: the tail block at set 1 (set 0 stays empty here), one slot for the one draw. 699 // --pc-tail-ubo: the tail block at set 1 (set 0 stays empty here), one slot for the one draw.
610 leonida::vk_test::PcTail tail; 700 leonida::vk_test::PcTail tail;
@@ -757,7 +847,9 @@ int main(int argc, char** argv) {
757 std::memcpy(imap, mesh_indices.data(), mesh_indices.size() * 4); 847 std::memcpy(imap, mesh_indices.data(), mesh_indices.size() * 4);
758 } 848 }
759 void* heap_map = nullptr; 849 void* heap_map = nullptr;
760 if (heap_env) { 850 uint32_t tsharp[8] = {0x11111111, leonida::gfx10::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM) << 20, 0x33333333,
851 0x44444444, 0x55555555, 0x66666666, 0x77777777, 0x88888888};
852 if (need_heap) {
761 LOADD(vkGetBufferDeviceAddress); 853 LOADD(vkGetBufferDeviceAddress);
762 VkBufferCreateInfo hbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 854 VkBufferCreateInfo hbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
763 hbi.size = heap_bytes; 855 hbi.size = heap_bytes;
@@ -774,12 +866,108 @@ int main(int argc, char** argv) {
774 void* hp; CHECK(vkMapMemory(dev, hmem, 0, heap_bytes, 0, &hp)); 866 void* hp; CHECK(vkMapMemory(dev, hmem, 0, heap_bytes, 0, &hp));
775 heap_map = hp; 867 heap_map = hp;
776 std::memset(hp, 0, heap_bytes); 868 std::memset(hp, 0, heap_bytes);
869 if (tex_rgba_path) std::memcpy(static_cast<char*>(hp) + tsharp_va, tsharp, 32);
777 for (auto [addr, word] : heap_words) std::memcpy(static_cast<char*>(hp) + addr, &word, 4); 870 for (auto [addr, word] : heap_words) std::memcpy(static_cast<char*>(hp) + addr, &word, 4);
778 VkBufferDeviceAddressInfo hda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; 871 VkBufferDeviceAddressInfo hda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
779 hda.buffer = heap; 872 hda.buffer = heap;
780 const uint64_t base = vkGetBufferDeviceAddress(dev, &hda); 873 const uint64_t base = vkGetBufferDeviceAddress(dev, &hda);
781 pc[32] = uint32_t(base); pc[33] = uint32_t(base >> 32); 874 pc[32] = uint32_t(base); pc[33] = uint32_t(base >> 32);
782 } 875 }
876 if (tex_rgba_path) {
877 LOADD(vkCreateSampler); LOADD(vkCreateDescriptorPool); LOADD(vkAllocateDescriptorSets);
878 LOADD(vkUpdateDescriptorSets);
879 leonida::DescriptorTable desc_table(16);
880 desc_table.insert(tsharp, 1);
881 desc_table.insert(ssharp, 1);
882 const auto table = desc_table.build_gpu_buffer(true);
883 VkBuffer tb = VK_NULL_HANDLE;
884 VkDeviceMemory tbm = VK_NULL_HANDLE;
885 void* tbp = nullptr;
886 {
887 VkBufferCreateInfo tbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
888 tbi.size = table.size() * 4; tbi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
889 CHECK(vkCreateBuffer(dev, &tbi, nullptr, &tb));
890 VkMemoryRequirements tmr; vkGetBufferMemoryRequirements(dev, tb, &tmr);
891 VkMemoryAllocateInfo tai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
892 tai.allocationSize = tmr.size;
893 tai.memoryTypeIndex = memtype(tmr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
894 CHECK(vkAllocateMemory(dev, &tai, nullptr, &tbm));
895 CHECK(vkBindBufferMemory(dev, tb, tbm, 0));
896 CHECK(vkMapMemory(dev, tbm, 0, tbi.size, 0, &tbp));
897 std::memcpy(tbp, table.data(), table.size() * 4);
898 }
899 auto make_sampled_tex = [&](uint32_t tw, uint32_t th, VkImage& out_img, VkImageView& out_view) -> int {
900 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
901 ii.imageType = VK_IMAGE_TYPE_2D; ii.format = VK_FORMAT_R8G8B8A8_UNORM; ii.extent = {tw, th, 1};
902 ii.mipLevels = 1; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT;
903 ii.tiling = VK_IMAGE_TILING_OPTIMAL;
904 ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
905 CHECK(vkCreateImage(dev, &ii, nullptr, &out_img));
906 VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, out_img, &mr);
907 VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
908 mai.allocationSize = mr.size;
909 mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
910 VkDeviceMemory mem; CHECK(vkAllocateMemory(dev, &mai, nullptr, &mem));
911 CHECK(vkBindImageMemory(dev, out_img, mem, 0));
912 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
913 vi.image = out_img; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = VK_FORMAT_R8G8B8A8_UNORM;
914 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
915 CHECK(vkCreateImageView(dev, &vi, nullptr, &out_view));
916 return 0;
917 };
918 VkImageView tex_views[2]{};
919 if (make_sampled_tex(1, 1, tex_fallback_img, tex_views[0]) ||
920 make_sampled_tex(tex_w, tex_h, tex_img, tex_views[1])) return 1;
921 {
922 const VkDeviceSize stage_bytes = 4 + tex_pixels.size();
923 VkBufferCreateInfo sbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
924 sbi.size = stage_bytes; sbi.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
925 CHECK(vkCreateBuffer(dev, &sbi, nullptr, &tex_staging));
926 VkMemoryRequirements smr; vkGetBufferMemoryRequirements(dev, tex_staging, &smr);
927 VkMemoryAllocateInfo sai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
928 sai.allocationSize = smr.size;
929 sai.memoryTypeIndex = memtype(smr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
930 VkDeviceMemory smem; CHECK(vkAllocateMemory(dev, &sai, nullptr, &smem));
931 CHECK(vkBindBufferMemory(dev, tex_staging, smem, 0));
932 void* sp = nullptr; CHECK(vkMapMemory(dev, smem, 0, stage_bytes, 0, &sp));
933 const uint32_t magenta = 0xFFFF00FFu;
934 std::memcpy(sp, &magenta, 4);
935 std::memcpy(static_cast<char*>(sp) + 4, tex_pixels.data(), tex_pixels.size());
936 }
937 VkSampler samplers[2]{};
938 VkSamplerCreateInfo def_sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
939 def_sci.magFilter = VK_FILTER_NEAREST; def_sci.minFilter = VK_FILTER_NEAREST;
940 CHECK(vkCreateSampler(dev, &def_sci, nullptr, &samplers[0]));
941 const leonida::gfx10::SamplerWords sw{ssharp[0], ssharp[1], ssharp[2], ssharp[3]};
942 VkSamplerCreateInfo sci = leonida::gfx10::vulkan_sampler(leonida::gfx10::decode(sw));
943 sci.anisotropyEnable = VK_FALSE;
944 CHECK(vkCreateSampler(dev, &sci, nullptr, &samplers[1]));
945 VkDescriptorPoolSize dps[3] = {
946 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2},
947 {VK_DESCRIPTOR_TYPE_SAMPLER, 2},
948 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1},
949 };
950 VkDescriptorPoolCreateInfo dpci{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
951 dpci.maxSets = 1; dpci.poolSizeCount = 3; dpci.pPoolSizes = dps;
952 VkDescriptorPool dpool; CHECK(vkCreateDescriptorPool(dev, &dpci, nullptr, &dpool));
953 VkDescriptorSetAllocateInfo dsai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
954 dsai.descriptorPool = dpool; dsai.descriptorSetCount = 1; dsai.pSetLayouts = &dsl;
955 CHECK(vkAllocateDescriptorSets(dev, &dsai, &ds));
956 VkDescriptorImageInfo img_infos[2] = {
957 {VK_NULL_HANDLE, tex_views[0], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL},
958 {VK_NULL_HANDLE, tex_views[1], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL},
959 };
960 VkDescriptorImageInfo smp_infos[2] = {
961 {samplers[0], VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED},
962 {samplers[1], VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED},
963 };
964 VkDescriptorBufferInfo tbl_info{tb, 0, VK_WHOLE_SIZE};
965 VkWriteDescriptorSet writes[3]{};
966 writes[0] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, ds, 0, 0, 2, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, img_infos};
967 writes[1] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, ds, 1, 0, 2, VK_DESCRIPTOR_TYPE_SAMPLER, smp_infos};
968 writes[2] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, ds, 2, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, nullptr, &tbl_info};
969 vkUpdateDescriptorSets(dev, 3, writes, 0, nullptr);
970 }
783 const uint64_t mesh_groups = uint64_t(groups[0]) * groups[1] * groups[2]; 971 const uint64_t mesh_groups = uint64_t(groups[0]) * groups[1] * groups[2];
784 if (mesh_compute) { 972 if (mesh_compute) {
785 LOADD(vkGetBufferDeviceAddress); 973 LOADD(vkGetBufferDeviceAddress);
@@ -818,6 +1006,38 @@ int main(int argc, char** argv) {
818 std::memcpy(pc, shifts, sizeof(shifts)); 1006 std::memcpy(pc, shifts, sizeof(shifts));
819 } 1007 }
820 auto push = reinterpret_cast<PFN_vkCmdPushConstants>(vkGetDeviceProcAddr(dev, "vkCmdPushConstants")); 1008 auto push = reinterpret_cast<PFN_vkCmdPushConstants>(vkGetDeviceProcAddr(dev, "vkCmdPushConstants"));
1009 if (tex_rgba_path) {
1010 LOADD(vkCmdPipelineBarrier); LOADD(vkCmdCopyBufferToImage);
1011 VkImageMemoryBarrier to_dst[2]{};
1012 for (int i = 0; i < 2; ++i) {
1013 to_dst[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1014 to_dst[i].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1015 to_dst[i].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1016 to_dst[i].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1017 to_dst[i].image = i == 0 ? tex_fallback_img : tex_img;
1018 to_dst[i].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
1019 }
1020 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
1021 0, nullptr, 0, nullptr, 2, to_dst);
1022 VkBufferImageCopy c0{};
1023 c0.bufferOffset = 0; c0.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; c0.imageExtent = {1, 1, 1};
1024 vkCmdCopyBufferToImage(cmd, tex_staging, tex_fallback_img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c0);
1025 VkBufferImageCopy c1{};
1026 c1.bufferOffset = 4; c1.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; c1.imageExtent = {tex_w, tex_h, 1};
1027 vkCmdCopyBufferToImage(cmd, tex_staging, tex_img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c1);
1028 VkImageMemoryBarrier to_ro[2]{};
1029 for (int i = 0; i < 2; ++i) {
1030 to_ro[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1031 to_ro[i].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1032 to_ro[i].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
1033 to_ro[i].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1034 to_ro[i].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1035 to_ro[i].image = i == 0 ? tex_fallback_img : tex_img;
1036 to_ro[i].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
1037 }
1038 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
1039 0, nullptr, 0, nullptr, 2, to_ro);
1040 }
821 if (mesh_compute) { 1041 if (mesh_compute) {
822 // The mesh shader as compute, then make its stores visible to the vertex shader's reads. 1042 // The mesh shader as compute, then make its stores visible to the vertex shader's reads.
823 LOADD(vkCmdDispatch); 1043 LOADD(vkCmdDispatch);
@@ -843,6 +1063,10 @@ int main(int argc, char** argv) {
843 std::fprintf(stderr, "mesh workgroups: %u x %u x %u\n", groups[0], groups[1], groups[2]); 1063 std::fprintf(stderr, "mesh workgroups: %u x %u x %u\n", groups[0], groups[1], groups[2]);
844 } 1064 }
845 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); 1065 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);
1066 if (ds) {
1067 LOADD(vkCmdBindDescriptorSets);
1068 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, 0, 1, &ds, 0, nullptr);
1069 }
846 push(cmd, pl, pcs, 0, pc_bytes, pc); 1070 push(cmd, pl, pcs, 0, pc_bytes, pc);
847 if (tail_block) { 1071 if (tail_block) {
848 LOADD(vkCmdBindDescriptorSets); 1072 LOADD(vkCmdBindDescriptorSets);
diff --git a/runtime/test/vk_overlapping_occlusion_test.cpp b/runtime/test/vk_overlapping_occlusion_test.cpp
index 43ffd5002..b668f965c 100644
--- a/runtime/test/vk_overlapping_occlusion_test.cpp
+++ b/runtime/test/vk_overlapping_occlusion_test.cpp
@@ -211,6 +211,10 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
211 EXPECT(copy_control.create(d, context, properties.limits)); 211 EXPECT(copy_control.create(d, context, properties.limits));
212 VulkanQueue queue(context, d.queue, d.family); 212 VulkanQueue queue(context, d.queue, d.family);
213 EXPECT(queue.ok() && gate.semaphore()); 213 EXPECT(queue.ok() && gate.semaphore());
214 // The gate stalls the GPU while the queue replays (the point of this test). A Wait on a fence with no submitted
215 // Signal is held on the CPU instead (queue_holds.h), so the gate is declared as having one: its Signal is
216 // "submitted" and the CPU completes it later, as a GPU-side signal behind long work would be.
217 context.holds().signaled(gate.semaphore(), 1);
214 struct OpenGate { VulkanFence& fence; ~OpenGate() { fence.signal(1); } } open_gate{gate}; 218 struct OpenGate { VulkanFence& fence; ~OpenGate() { fence.signal(1); } } open_gate{gate};
215 constexpr QueryHeapId a = 1, b = 2, stats = 3; 219 constexpr QueryHeapId a = 1, b = 2, stats = 3;
216 constexpr auto occ = d3d12_query::occlusion; 220 constexpr auto occ = d3d12_query::occlusion;
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp
index 65a53a5f3..0312b48a4 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -10,7 +10,7 @@
10// whose required features or partner stubs are unavailable are reported as skipped rather than failed. 10// whose required features or partner stubs are unavailable are reported as skipped rather than failed.
11// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every 11// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every
12// 10 minutes and at the end 12// 10 minutes and at the end
13// --jobs N compile on N threads (default: half the hardware threads) 13// --jobs N compile on up to N worker threads (default: half the hardware threads)
14// --large-module-bytes N compile modules larger than N bytes alone (default: 4194304; 0 disables isolation) 14// --large-module-bytes N compile modules larger than N bytes alone (default: 4194304; 0 disables isolation)
15// --start I --count N check only index entries [I, I+N) (sorted by name) 15// --start I --count N check only index entries [I, I+N) (sorted by name)
16// --slow SEC print pipelines slower than SEC (default 30); compiles past 60 s are named while running 16// --slow SEC print pipelines slower than SEC (default 30); compiles past 60 s are named while running
@@ -51,10 +51,12 @@
51#include <chrono> 51#include <chrono>
52#include <cmath> 52#include <cmath>
53#include <condition_variable> 53#include <condition_variable>
54#include <cerrno>
54#include <csignal> 55#include <csignal>
55#include <cstdlib> 56#include <cstdlib>
56#include <cstdio> 57#include <cstdio>
57#include <cstring> 58#include <cstring>
59#include <type_traits>
58#include <fstream> 60#include <fstream>
59#include <iterator> 61#include <iterator>
60#include <limits> 62#include <limits>
@@ -610,9 +612,21 @@ int main(int argc, char** argv) {
610 auto number = [&](auto& dest) { 612 auto number = [&](auto& dest) {
611 const auto text = value(); 613 const auto text = value();
612 if (text.empty()) return false; 614 if (text.empty()) return false;
613 const auto end = text.data() + text.size(); 615 if constexpr (std::is_floating_point_v<std::decay_t<decltype(dest)>>) {
614 const auto [ptr, ec] = std::from_chars(text.data(), end, dest); 616 // Apple's libc++ has no floating-point from_chars overload. Parse the whole token with strtod,
615 return ec == std::errc{} && ptr == end; 617 // as shader_library.h does for JSON numbers; --slow also checks isfinite and >= 0 below.
618 const std::string token(text);
619 char* end = nullptr;
620 errno = 0;
621 const double parsed = std::strtod(token.c_str(), &end);
622 if (errno == ERANGE || end != token.c_str() + token.size()) return false;
623 dest = static_cast<std::decay_t<decltype(dest)>>(parsed);
624 return true;
625 } else {
626 const auto end = text.data() + text.size();
627 const auto [ptr, ec] = std::from_chars(text.data(), end, dest);
628 return ec == std::errc{} && ptr == end;
629 }
616 }; 630 };
617 bool valid = true; 631 bool valid = true;
618 if (a == "--jobs") { 632 if (a == "--jobs") {
@@ -813,7 +827,7 @@ int main(int argc, char** argv) {
813#endif 827#endif
814 828
815 // Scan selected shaders to request only the optional extensions they actually use. 829 // Scan selected shaders to request only the optional extensions they actually use.
816 bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false; 830 bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false, want_clock = false;
817 for (auto& [_, meta] : work) { 831 for (auto& [_, meta] : work) {
818 if (meta->stage == "ms") want_mesh = true; 832 if (meta->stage == "ms") want_mesh = true;
819 if (meta->needs_maintenance8) want_m8 = true; 833 if (meta->needs_maintenance8) want_m8 = true;
@@ -822,6 +836,7 @@ int main(int argc, char** argv) {
822 else if (feat == "fragmentShaderBarycentric") want_bary = true; 836 else if (feat == "fragmentShaderBarycentric") want_bary = true;
823 else if (feat == "fragmentShaderPixelInterlock") want_lock = true; 837 else if (feat == "fragmentShaderPixelInterlock") want_lock = true;
824 else if (feat == "shaderFmaFloat32") want_fma = true; // OpFmaKHR (rdna2spirv.py --fma khr) 838 else if (feat == "shaderFmaFloat32") want_fma = true; // OpFmaKHR (rdna2spirv.py --fma khr)
839 else if (feat == "shaderSubgroupClock" || feat == "shaderDeviceClock") want_clock = true;
825 } 840 }
826 } 841 }
827 842
@@ -905,6 +920,8 @@ int main(int argc, char** argv) {
905 const bool ext_fma = false; 920 const bool ext_fma = false;
906 (void)want_fma; 921 (void)want_fma;
907#endif 922#endif
923 VkPhysicalDeviceShaderClockFeaturesKHR clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR};
924 const bool ext_clock = link(&clock, reinterpret_cast<VkBaseOutStructure*>(&clock), VK_KHR_SHADER_CLOCK_EXTENSION_NAME, want_clock);
908 const bool ext_exe = link(&exe, reinterpret_cast<VkBaseOutStructure*>(&exe), 925 const bool ext_exe = link(&exe, reinterpret_cast<VkBaseOutStructure*>(&exe),
909 VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, !stats_path.empty()); 926 VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, !stats_path.empty());
910 if (!stats_path.empty() && !ext_exe) { 927 if (!stats_path.empty() && !ext_exe) {
@@ -991,10 +1008,13 @@ int main(int argc, char** argv) {
991 return "no VK_KHR_maintenance8"; 1008 return "no VK_KHR_maintenance8";
992#endif 1009#endif
993 } 1010 }
994 // Execution modes the translator declares (SignedZeroInfNanPreserve 32) need a device property, not a feature. 1011 // Execution modes the translator declares (SignedZeroInfNanPreserve 32, DenormPreserve 16) need a device
1012 // property, not a feature.
995 for (const auto& fc : meta.float_controls) { 1013 for (const auto& fc : meta.float_controls) {
996 if (fc == "shaderSignedZeroInfNanPreserveFloat32") { 1014 if (fc == "shaderSignedZeroInfNanPreserveFloat32") {
997 if (!fcProps.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc; 1015 if (!fcProps.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc;
1016 } else if (fc == "shaderDenormPreserveFloat16") {
1017 if (!fcProps.shaderDenormPreserveFloat16) return "no " + fc;
998 } else { 1018 } else {
999 return "unknown float control " + fc; 1019 return "unknown float control " + fc;
1000 } 1020 }
@@ -1011,6 +1031,8 @@ int main(int argc, char** argv) {
1011 return "no VK_KHR_shader_fma (shaderFmaFloat32)"; 1031 return "no VK_KHR_shader_fma (shaderFmaFloat32)";
1012#endif 1032#endif
1013 } 1033 }
1034 if (feat == "shaderSubgroupClock" && !(ext_clock && clock.shaderSubgroupClock)) return "no shaderSubgroupClock";
1035 if (feat == "shaderDeviceClock" && !(ext_clock && clock.shaderDeviceClock)) return "no shaderDeviceClock";
1014 if (feat == "shaderFloat64" && !f2.features.shaderFloat64) return "no shaderFloat64"; 1036 if (feat == "shaderFloat64" && !f2.features.shaderFloat64) return "no shaderFloat64";
1015 if (feat == "shaderInt64" && !f2.features.shaderInt64) return "no shaderInt64"; 1037 if (feat == "shaderInt64" && !f2.features.shaderInt64) return "no shaderInt64";
1016 if (feat == "shaderDrawParameters" && !f11.shaderDrawParameters) return "no shaderDrawParameters"; 1038 if (feat == "shaderDrawParameters" && !f11.shaderDrawParameters) return "no shaderDrawParameters";
@@ -1109,8 +1131,9 @@ int main(int argc, char** argv) {
1109 } 1131 }
1110 }; 1132 };
1111 1133
1134 const auto worker_count = static_cast<unsigned>(std::min<size_t>(jobs, work.size()));
1112 std::fprintf(stderr, "checking %zu shaders [%zu, %zu) (stage=%s) on %u threads\n", 1135 std::fprintf(stderr, "checking %zu shaders [%zu, %zu) (stage=%s) on %u threads\n",
1113 work.size(), lo, hi, stage_filter.c_str(), jobs); 1136 work.size(), lo, hi, stage_filter.c_str(), worker_count);
1114 1137
1115 std::mutex mu; // guards counters, stdout, stub cache and in-flight table 1138 std::mutex mu; // guards counters, stdout, stub cache and in-flight table
1116 std::shared_mutex compile_gate; // large modules exclude other shader and pipeline work 1139 std::shared_mutex compile_gate; // large modules exclude other shader and pipeline work
@@ -1127,14 +1150,20 @@ int main(int argc, char** argv) {
1127 const char* phase; // "module" or "pipeline" 1150 const char* phase; // "module" or "pipeline"
1128 }; 1151 };
1129 std::map<std::thread::id, InFlight> inflight; 1152 std::map<std::thread::id, InFlight> inflight;
1130 // --inflight-file: rewrite the file from `inflight`, one "name<TAB>phase" line per module. Called with mu held, at 1153 // Publish a complete snapshot at the moments named in the header. This keeps the last full report if the
1131 // the moments named in the header. 1154 // process dies while staging the next one. Called with mu held.
1132 auto write_inflight = [&] { 1155 auto write_inflight = [&] {
1133 if (inflight_path.empty()) return; 1156 if (inflight_path.empty()) return;
1134 if (std::FILE* f = std::fopen(inflight_path.c_str(), "w")) { 1157 std::string snapshot;
1135 for (const auto& [tid, job] : inflight) std::fprintf(f, "%s\t%s\n", job.name.c_str(), job.phase); 1158 for (const auto& [tid, job] : inflight) {
1136 std::fclose(f); 1159 snapshot += job.name;
1160 snapshot += '\t';
1161 snapshot += job.phase;
1162 snapshot += '\n';
1137 } 1163 }
1164 if (const auto error = write_pipeline_cache_file(inflight_path, snapshot.data(), snapshot.size()))
1165 std::fprintf(stderr, "in-flight snapshot save to %s failed: %s\n",
1166 inflight_path.c_str(), error.message().c_str());
1138 }; 1167 };
1139 const auto t_start = std::chrono::steady_clock::now(); 1168 const auto t_start = std::chrono::steady_clock::now();
1140 auto elapsed = [&] { return std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count(); }; 1169 auto elapsed = [&] { return std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count(); };
@@ -1530,7 +1559,7 @@ int main(int argc, char** argv) {
1530 if (iso_child) std::printf("ISO-READY\n"); 1559 if (iso_child) std::printf("ISO-READY\n");
1531 std::fflush(stdout); 1560 std::fflush(stdout);
1532 std::vector<std::thread> pool; 1561 std::vector<std::thread> pool;
1533 for (uint32_t t = 0; t < jobs; t++) pool.emplace_back(worker); 1562 for (unsigned t = 0; t < worker_count; t++) pool.emplace_back(worker);
1534 // Watchdog: names every compile running past 60 s (about once a minute) and saves the cache every 10 minutes. 1563 // Watchdog: names every compile running past 60 s (about once a minute) and saves the cache every 10 minutes.
1535 std::condition_variable watch_cv; 1564 std::condition_variable watch_cv;
1536 bool all_done = false; 1565 bool all_done = false;
@@ -1631,7 +1660,7 @@ int main(int argc, char** argv) {
1631 if (isolated_modules) 1660 if (isolated_modules)
1632 std::printf("large modules checked exclusively: %zu (over %zu bytes)\n", isolated_modules, 1661 std::printf("large modules checked exclusively: %zu (over %zu bytes)\n", isolated_modules,
1633 large_module_bytes); 1662 large_module_bytes);
1634 std::printf("wall time: %.1fs on %u threads\n", elapsed(), jobs); 1663 std::printf("wall time: %.1fs on %u threads\n", elapsed(), worker_count);
1635 const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed 1664 const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed
1636 if (stats_out) std::fclose(stats_out); 1665 if (stats_out) std::fclose(stats_out);
1637 return (check_failed || !cache_saved) ? 1 : 0; 1666 return (check_failed || !cache_saved) ? 1 : 0;
diff --git a/runtime/test/vk_predicate_capture_test.cpp b/runtime/test/vk_predicate_capture_test.cpp
index 13c9c4592..65a1eea57 100644
--- a/runtime/test/vk_predicate_capture_test.cpp
+++ b/runtime/test/vk_predicate_capture_test.cpp
@@ -22,7 +22,12 @@ VKAPI_ATTR void VKAPI_CALL observe_barrier2(VkCommandBuffer cb, const VkDependen
22} 22}
23int main() { 23int main() {
24 vktest::Device d; 24 vktest::Device d;
25 if (!d.create()) return 1; 25 const auto status = d.initialize();
26 if (status == vktest::DeviceStatus::unavailable) {
27 std::printf("vk_predicate_capture_test: no Vulkan device, skipped\n");
28 return 77;
29 }
30 if (status != vktest::DeviceStatus::ready) return 1;
26 if (!d.conditional_rendering) { std::puts("predicate capture: skipped (no conditional rendering)"); return 0; } 31 if (!d.conditional_rendering) { std::puts("predicate capture: skipped (no conditional rendering)"); return 0; }
27 using namespace leonida; 32 using namespace leonida;
28 VkPhysicalDeviceMemoryProperties memory{}; 33 VkPhysicalDeviceMemoryProperties memory{};
diff --git a/runtime/test/vk_predicated_copy_test.cpp b/runtime/test/vk_predicated_copy_test.cpp
index f77eb1aac..e5e9ff587 100644
--- a/runtime/test/vk_predicated_copy_test.cpp
+++ b/runtime/test/vk_predicated_copy_test.cpp
@@ -19,7 +19,12 @@ VKAPI_ATTR void VKAPI_CALL observe_host(VkCommandBuffer cb, const VkDependencyIn
19} 19}
20int main() { 20int main() {
21 vktest::Device d; 21 vktest::Device d;
22 if(!d.create())return 1; 22 const auto status = d.initialize();
23 if (status == vktest::DeviceStatus::unavailable) {
24 std::printf("vk_predicated_copy_test: no Vulkan device, skipped\n");
25 return 77;
26 }
27 if (status != vktest::DeviceStatus::ready) return 1;
23 if(!d.conditional_rendering || !d.storage_buffer_8bit) { 28 if(!d.conditional_rendering || !d.storage_buffer_8bit) {
24 std::puts("predicated copy: skipped (requires conditional rendering and storageBuffer8BitAccess)"); return 0; 29 std::puts("predicated copy: skipped (requires conditional rendering and storageBuffer8BitAccess)"); return 0;
25 } 30 }
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp
index b4585ce20..c26703ef5 100644
--- a/runtime/test/vk_presenter_sync_test.cpp
+++ b/runtime/test/vk_presenter_sync_test.cpp
@@ -171,7 +171,7 @@ int main() {
171 HWND window = CreateWindowExW(0, wc.lpszClassName, L"Leonida presenter sync test", WS_OVERLAPPEDWINDOW, 80, 80, 171 HWND window = CreateWindowExW(0, wc.lpszClassName, L"Leonida presenter sync test", WS_OVERLAPPEDWINDOW, 80, 80,
172 fr.right - fr.left, fr.bottom - fr.top, nullptr, nullptr, wc.hInstance, nullptr); 172 fr.right - fr.left, fr.bottom - fr.top, nullptr, nullptr, wc.hInstance, nullptr);
173 EXPECT(window); 173 EXPECT(window);
174 ShowWindow(window, SW_SHOWNORMAL); 174 ShowWindow(window, SW_SHOWNOACTIVATE);
175 UpdateWindow(window); 175 UpdateWindow(window);
176 pump(); 176 pump();
177 177
diff --git a/runtime/test/vk_queue_query_sync_test.cpp b/runtime/test/vk_queue_query_sync_test.cpp
index a9daf6477..a03e369b9 100644
--- a/runtime/test/vk_queue_query_sync_test.cpp
+++ b/runtime/test/vk_queue_query_sync_test.cpp
@@ -267,12 +267,14 @@ int main() {
267 EXPECT(copy_list.close()); 267 EXPECT(copy_list.close());
268 const CommandList* ptr = &copy_list; 268 const CommandList* ptr = &copy_list;
269 269
270 // The Signal comes first: a Wait with no submitted Signal holds the batch on the CPU (queue_holds.h) and
271 // never reaches vkQueueSubmit, so it could not fail there.
272 EXPECT(fence.signal(1));
270 queue_a.wait(fence.semaphore(), 1); 273 queue_a.wait(fence.semaphore(), 1);
271 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); 274 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
272 EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::unsupported); 275 EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::unsupported);
273 276
274 // Retry: the pending wait on (fence, 1) must still be attached to the next vkQueueSubmit. 277 // Retry: the pending wait on (fence, 1) must still be attached to the next vkQueueSubmit.
275 EXPECT(fence.signal(1));
276 driver::captured_wait_count.store(0); 278 driver::captured_wait_count.store(0);
277 driver::captured_wait_sem.store(0); 279 driver::captured_wait_sem.store(0);
278 driver::captured_wait_val.store(0); 280 driver::captured_wait_val.store(0);
diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp
index e6b76d363..5612a7119 100644
--- a/runtime/test/vk_store_test.cpp
+++ b/runtime/test/vk_store_test.cpp
@@ -462,6 +462,12 @@ int main(int argc, char** argv) {
462 bic.imageSubresource = vol_layers; bic.imageExtent = {VOL, VOL, VOL}; 462 bic.imageSubresource = vol_layers; bic.imageExtent = {VOL, VOL, VOL};
463 vkCmdCopyImageToBuffer(cmd, vol, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, vol_rb, 1, &bic); 463 vkCmdCopyImageToBuffer(cmd, vol, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, vol_rb, 1, &bic);
464 } 464 }
465 // Make every copy's readback writes visible to the host before it reads the mapped buffers.
466 VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
467 host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
468 host.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
469 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT,
470 0, 1, &host, 0, nullptr, 0, nullptr);
465 CHECK(vkEndCommandBuffer(cmd)); 471 CHECK(vkEndCommandBuffer(cmd));
466 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; 472 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd;
467 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); 473 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE));
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index b1d5f8f73..114ca187f 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -102,6 +102,7 @@ public:
102 bool partially_bound = false; // and its slots can stay empty 102 bool partially_bound = false; // and its slots can stay empty
103 bool image_view_min_lod = false; 103 bool image_view_min_lod = false;
104 bool sampler_filter_minmax = false; 104 bool sampler_filter_minmax = false;
105 bool vertex_attribute_divisor = false;
105 bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled 106 bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled
106 bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available 107 bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available
107 bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled 108 bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled
@@ -114,6 +115,7 @@ public:
114 bool request_debug_utils = false; // set before create(): enable VK_EXT_debug_utils when the loader has it 115 bool request_debug_utils = false; // set before create(): enable VK_EXT_debug_utils when the loader has it
115 bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported 116 bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported
116 bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) 117 bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address())
118 bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available
117 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance 119 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance
118 // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them. 120 // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them.
119 leonida::SubgroupSizeCaps subgroup; 121 leonida::SubgroupSizeCaps subgroup;
@@ -450,6 +452,36 @@ public:
450 *v13_.next() = &min_lod; 452 *v13_.next() = &min_lod;
451 } 453 }
452 } 454 }
455 const char* divisor_extension = nullptr;
456 for (const char* name :
457 {VK_KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME, VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME}) {
458 if (std::any_of(extensions.begin(), extensions.end(),
459 [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; })) {
460 divisor_extension = name;
461 break;
462 }
463 }
464 VkPhysicalDeviceVertexAttributeDivisorFeaturesKHR divisor_khr{
465 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_KHR};
466 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT divisor_ext{
467 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT};
468 if (divisor_extension) {
469 const bool is_khr = std::strcmp(divisor_extension, VK_KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME) == 0;
470 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
471 is_khr ? static_cast<void*>(&divisor_khr) : static_cast<void*>(&divisor_ext)};
472 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
473 vertex_attribute_divisor = (is_khr ? divisor_khr.vertexAttributeInstanceRateDivisor
474 : divisor_ext.vertexAttributeInstanceRateDivisor) == VK_TRUE;
475 if (vertex_attribute_divisor) {
476 if (is_khr) {
477 divisor_khr.pNext = *v13_.next();
478 *v13_.next() = &divisor_khr;
479 } else {
480 divisor_ext.pNext = *v13_.next();
481 *v13_.next() = &divisor_ext;
482 }
483 }
484 }
453 VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{ 485 VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{
454 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT}; 486 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT};
455 for (const auto& extension : extensions) { 487 for (const auto& extension : extensions) {
@@ -507,7 +539,12 @@ public:
507 enabled = enable; 539 enabled = enable;
508 std::vector<const char*> device_extensions; 540 std::vector<const char*> device_extensions;
509 v13_.add_extensions(device_extensions); 541 v13_.add_extensions(device_extensions);
542 conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) {
543 return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0;
544 });
545 if (conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME);
510 if (image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); 546 if (image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME);
547 if (vertex_attribute_divisor) device_extensions.push_back(divisor_extension);
511 if (conditional_rendering) device_extensions.push_back(conditional_extension); 548 if (conditional_rendering) device_extensions.push_back(conditional_extension);
512 if (host_image_copy) device_extensions.push_back(host_image_copy_name); 549 if (host_image_copy) device_extensions.push_back(host_image_copy_name);
513 const char* swapchain = "VK_KHR_swapchain"; 550 const char* swapchain = "VK_KHR_swapchain";
diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp
index 2deb3f812..a2191eae3 100644
--- a/runtime/test/vk_texture_test.cpp
+++ b/runtime/test/vk_texture_test.cpp
@@ -512,6 +512,14 @@ int main(int argc, char** argv) {
512 vkCmdEndRenderPass(cmd); 512 vkCmdEndRenderPass(cmd);
513 VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1}; 513 VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1};
514 vkCmdCopyImageToBuffer(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb, 1, &rc); 514 vkCmdCopyImageToBuffer(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb, 1, &rc);
515 VkBufferMemoryBarrier readback{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
516 readback.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
517 readback.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
518 readback.srcQueueFamilyIndex = readback.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
519 readback.buffer = rb;
520 readback.size = VK_WHOLE_SIZE;
521 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT,
522 0, 0, nullptr, 1, &readback, 0, nullptr);
515 CHECK(vkEndCommandBuffer(cmd)); 523 CHECK(vkEndCommandBuffer(cmd));
516 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; 524 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd;
517 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); CHECK(vkQueueWaitIdle(q)); 525 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); CHECK(vkQueueWaitIdle(q));
diff --git a/runtime/test/vulkan13_features_test.cpp b/runtime/test/vulkan13_features_test.cpp
new file mode 100644
index 000000000..cf1b4d99c
--- /dev/null
+++ b/runtime/test/vulkan13_features_test.cpp
@@ -0,0 +1,365 @@
1// Unit tests for Vulkan13Features and device_proc_or_khr (runtime/src/vulkan13_features.h). CPU-only, no Vulkan
2// instance and no GPU: synthetic callbacks exercise the 1.1 rejection, 1.2 KHR/EXT fallback, and 1.3 core paths.
3#ifndef VK_NO_PROTOTYPES
4#define VK_NO_PROTOTYPES
5#endif
6#include "../src/vulkan13_features.h"
7
8#include <algorithm>
9#include <cstdio>
10#include <cstring>
11#include <string>
12#include <vector>
13
14#define EXPECT(condition) do { \
15 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
16} while (0)
17
18using leonida::Vulkan13Features;
19using leonida::device_proc_or_khr;
20
21namespace {
22
23struct FakeDevice {
24 std::vector<const char*> extensions;
25 VkBool32 dynamic_rendering = VK_FALSE;
26 VkBool32 synchronization2 = VK_FALSE;
27 VkBool32 subgroup_size_control = VK_FALSE;
28 VkBool32 compute_full_subgroups = VK_FALSE;
29 VkBool32 eds = VK_FALSE;
30 VkBool32 eds2 = VK_FALSE;
31 int features2_calls = 0;
32 int enum_calls = 0;
33 std::vector<VkStructureType> queried_types;
34};
35
36FakeDevice* g_device = nullptr;
37
38VKAPI_ATTR VkResult VKAPI_CALL fake_enumerate_extensions(
39 VkPhysicalDevice, const char*, std::uint32_t* count, VkExtensionProperties* properties) {
40 ++g_device->enum_calls;
41 if (!properties) {
42 *count = static_cast<std::uint32_t>(g_device->extensions.size());
43 return VK_SUCCESS;
44 }
45 const std::uint32_t n = static_cast<std::uint32_t>(g_device->extensions.size());
46 const std::uint32_t write = *count < n ? *count : n;
47 for (std::uint32_t i = 0; i < write; ++i) {
48 std::memset(&properties[i], 0, sizeof(properties[i]));
49 const std::size_t len = std::min<std::size_t>(std::strlen(g_device->extensions[i]), VK_MAX_EXTENSION_NAME_SIZE - 1);
50 std::memcpy(properties[i].extensionName, g_device->extensions[i], len);
51 }
52 *count = write;
53 return VK_SUCCESS;
54}
55
56VKAPI_ATTR void VKAPI_CALL fake_get_features2(VkPhysicalDevice, VkPhysicalDeviceFeatures2* features) {
57 ++g_device->features2_calls;
58 g_device->queried_types.clear();
59 for (auto* node = static_cast<VkBaseOutStructure*>(features->pNext); node; node = node->pNext) {
60 g_device->queried_types.push_back(node->sType);
61 switch (node->sType) {
62 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES: {
63 auto* f = reinterpret_cast<VkPhysicalDeviceVulkan13Features*>(node);
64 f->dynamicRendering = g_device->dynamic_rendering;
65 f->synchronization2 = g_device->synchronization2;
66 f->subgroupSizeControl = g_device->subgroup_size_control;
67 f->computeFullSubgroups = g_device->compute_full_subgroups;
68 break;
69 }
70 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR:
71 reinterpret_cast<VkPhysicalDeviceDynamicRenderingFeaturesKHR*>(node)->dynamicRendering =
72 g_device->dynamic_rendering;
73 break;
74 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR:
75 reinterpret_cast<VkPhysicalDeviceSynchronization2FeaturesKHR*>(node)->synchronization2 =
76 g_device->synchronization2;
77 break;
78 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT:
79 reinterpret_cast<VkPhysicalDeviceExtendedDynamicStateFeaturesEXT*>(node)->extendedDynamicState =
80 g_device->eds;
81 break;
82 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT:
83 reinterpret_cast<VkPhysicalDeviceExtendedDynamicState2FeaturesEXT*>(node)->extendedDynamicState2 =
84 g_device->eds2;
85 break;
86 default:
87 break;
88 }
89 }
90}
91
92std::vector<VkStructureType> chain_types(const void* head) {
93 std::vector<VkStructureType> types;
94 for (const auto* node = static_cast<const VkBaseInStructure*>(head); node; node = node->pNext) {
95 types.push_back(node->sType);
96 }
97 return types;
98}
99
100VKAPI_ATTR void VKAPI_CALL stub_core() {}
101VKAPI_ATTR void VKAPI_CALL stub_khr() {}
102VKAPI_ATTR void VKAPI_CALL stub_ext() {}
103
104struct ProcLookup {
105 const char* core_name = nullptr;
106 const char* khr_name = nullptr;
107 const char* ext_name = nullptr;
108 std::vector<std::string> queries;
109};
110
111ProcLookup* g_proc = nullptr;
112
113VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL fake_get_device_proc(VkDevice, const char* name) {
114 g_proc->queries.emplace_back(name);
115 if (g_proc->core_name && std::strcmp(name, g_proc->core_name) == 0) return stub_core;
116 if (g_proc->khr_name && std::strcmp(name, g_proc->khr_name) == 0) return stub_khr;
117 if (g_proc->ext_name && std::strcmp(name, g_proc->ext_name) == 0) return stub_ext;
118 return nullptr;
119}
120
121} // namespace
122
123int main() {
124 // Vulkan 1.3 core device: queries VkPhysicalDeviceVulkan13Features without enumerating extensions.
125 {
126 FakeDevice dev;
127 dev.dynamic_rendering = VK_TRUE;
128 dev.synchronization2 = VK_TRUE;
129 dev.subgroup_size_control = VK_TRUE;
130 dev.compute_full_subgroups = VK_FALSE;
131 g_device = &dev;
132
133 Vulkan13Features v13;
134 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr);
135 EXPECT(dev.features2_calls == 1 && dev.enum_calls == 0);
136 EXPECT(dev.queried_types.size() == 1 &&
137 dev.queried_types[0] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES);
138 EXPECT(v13.core && v13.usable());
139 EXPECT(v13.dynamic_rendering && v13.synchronization2);
140 EXPECT(v13.subgroup_size_control && !v13.compute_full_subgroups);
141 EXPECT(v13.extended_dynamic_state);
142
143 VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr};
144 void* head = v13.enable(&tail);
145 const auto* enable13 = static_cast<const VkPhysicalDeviceVulkan13Features*>(head);
146 EXPECT(enable13->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES);
147 EXPECT(enable13->dynamicRendering == VK_TRUE && enable13->synchronization2 == VK_TRUE);
148 EXPECT(enable13->subgroupSizeControl == VK_TRUE && enable13->computeFullSubgroups == VK_FALSE);
149 EXPECT(enable13->pNext == &tail);
150
151 // Inserting a later feature struct through next() places it between enable13 and tail.
152 VkBaseOutStructure extra{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, nullptr};
153 extra.pNext = static_cast<VkBaseOutStructure*>(*v13.next());
154 *v13.next() = &extra;
155 const auto types = chain_types(head);
156 EXPECT(types.size() == 3);
157 EXPECT(types[0] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES);
158 EXPECT(types[1] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
159 EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2);
160
161 // Core 1.3 needs no extra extensions.
162 std::vector<const char*> exts = {"VK_KHR_swapchain"};
163 v13.add_extensions(exts);
164 EXPECT(exts.size() == 1 && std::strcmp(exts[0], "VK_KHR_swapchain") == 0);
165 }
166
167 // Vulkan 1.3 missing either required feature is not usable; Vulkan 1.4 still takes the core path.
168 {
169 FakeDevice dev;
170 dev.dynamic_rendering = VK_TRUE;
171 dev.synchronization2 = VK_FALSE;
172 g_device = &dev;
173
174 Vulkan13Features v13;
175 v13.query(VK_NULL_HANDLE, VK_MAKE_API_VERSION(0, 1, 4, 0), fake_get_features2, nullptr);
176 EXPECT(v13.core && v13.dynamic_rendering && !v13.synchronization2 && !v13.usable());
177
178 dev.dynamic_rendering = VK_FALSE;
179 dev.synchronization2 = VK_TRUE;
180 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr);
181 EXPECT(v13.core && !v13.dynamic_rendering && v13.synchronization2 && !v13.usable());
182 }
183
184 // Vulkan 1.1 and null callbacks never qualify, and reset flags from an earlier query.
185 {
186 FakeDevice dev;
187 dev.dynamic_rendering = VK_TRUE;
188 dev.synchronization2 = VK_TRUE;
189 dev.subgroup_size_control = VK_TRUE;
190 g_device = &dev;
191
192 Vulkan13Features v13;
193 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr);
194 EXPECT(v13.usable());
195
196 dev.features2_calls = 0;
197 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_1, fake_get_features2, fake_enumerate_extensions);
198 EXPECT(!v13.core && !v13.usable() && !v13.extended_dynamic_state && !v13.subgroup_size_control);
199 EXPECT(dev.features2_calls == 0 && dev.enum_calls == 0);
200
201 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, nullptr, nullptr);
202 EXPECT(v13.core && !v13.usable() && !v13.extended_dynamic_state);
203
204 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, nullptr);
205 EXPECT(!v13.core && !v13.usable() && dev.features2_calls == 0);
206 }
207
208 // Vulkan 1.2 missing a required KHR extension returns before querying features2.
209 {
210 FakeDevice dev;
211 dev.extensions = {VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME};
212 dev.dynamic_rendering = VK_TRUE;
213 dev.synchronization2 = VK_TRUE;
214 g_device = &dev;
215
216 Vulkan13Features v13;
217 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions);
218 EXPECT(!v13.core && !v13.usable());
219 EXPECT(dev.enum_calls == 2 && dev.features2_calls == 0);
220 }
221
222 // Vulkan 1.2 with KHR dynamic_rendering + synchronization2, without extended_dynamic_state(2).
223 {
224 FakeDevice dev;
225 dev.extensions = {VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME};
226 dev.dynamic_rendering = VK_TRUE;
227 dev.synchronization2 = VK_TRUE;
228 g_device = &dev;
229
230 Vulkan13Features v13;
231 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions);
232 EXPECT(!v13.core && v13.usable() && !v13.extended_dynamic_state);
233 EXPECT(!v13.subgroup_size_control && !v13.compute_full_subgroups);
234 EXPECT(dev.queried_types.size() == 2);
235 EXPECT(dev.queried_types[0] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR);
236 EXPECT(dev.queried_types[1] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR);
237
238 VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr};
239 void* head = v13.enable(&tail);
240 VkBaseOutStructure extra{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, nullptr};
241 extra.pNext = static_cast<VkBaseOutStructure*>(*v13.next());
242 *v13.next() = &extra;
243
244 const auto types = chain_types(head);
245 EXPECT(types.size() == 4);
246 EXPECT(types[0] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR);
247 EXPECT(types[1] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR);
248 EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
249 EXPECT(types[3] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2);
250
251 std::vector<const char*> exts;
252 v13.add_extensions(exts);
253 EXPECT(exts.size() == 2);
254 EXPECT(std::strcmp(exts[0], VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0);
255 EXPECT(std::strcmp(exts[1], VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0);
256 }
257
258 // Vulkan 1.2 with only EDS1 (missing EDS2), or both extensions with one feature bit false: EDS stays off.
259 {
260 FakeDevice dev;
261 dev.extensions = {
262 VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME,
263 VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME,
264 VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME,
265 };
266 dev.dynamic_rendering = VK_TRUE;
267 dev.synchronization2 = VK_TRUE;
268 dev.eds = VK_TRUE;
269 dev.eds2 = VK_TRUE;
270 g_device = &dev;
271
272 Vulkan13Features v13;
273 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions);
274 EXPECT(v13.usable() && !v13.extended_dynamic_state);
275 EXPECT(dev.queried_types.size() == 3);
276 EXPECT(dev.queried_types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT);
277
278 dev.extensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME);
279 dev.eds2 = VK_FALSE;
280 v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions);
281 EXPECT(v13.usable() && !v13.extended_dynamic_state);
282 EXPECT(dev.queried_types.size() == 4);
283 }
284
285 // Vulkan 1.2 with KHR + EDS1 + EDS2 all supported: enables all four structs and adds all four extensions.
286 {
287 FakeDevice dev;
288 dev.extensions = {
289 VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME,
290 VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME,
291 VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME,
292 VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME,
293 };
294 dev.dynamic_rendering = VK_TRUE;
295 dev.synchronization2 = VK_TRUE;
296 dev.eds = VK_TRUE;
297 dev.eds2 = VK_TRUE;
298 g_device = &dev;
299
300 Vulkan13Features candidate;
301 candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions);
302 EXPECT(!candidate.core && candidate.usable() && candidate.extended_dynamic_state);
303
304 // choose() preserves the winning device's flags even after candidate is overwritten.
305 Vulkan13Features chosen;
306 chosen.choose(candidate);
307 candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_1, fake_get_features2, fake_enumerate_extensions);
308 EXPECT(!candidate.usable());
309 EXPECT(!chosen.core && chosen.usable() && chosen.extended_dynamic_state);
310
311 VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr};
312 void* head = chosen.enable(&tail);
313 VkBaseOutStructure extra{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, nullptr};
314 extra.pNext = static_cast<VkBaseOutStructure*>(*chosen.next());
315 *chosen.next() = &extra;
316
317 const auto types = chain_types(head);
318 EXPECT(types.size() == 6);
319 EXPECT(types[0] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR);
320 EXPECT(types[1] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR);
321 EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT);
322 EXPECT(types[3] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT);
323 EXPECT(types[4] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
324 EXPECT(types[5] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2);
325
326 std::vector<const char*> exts;
327 chosen.add_extensions(exts);
328 EXPECT(exts.size() == 4);
329 EXPECT(std::strcmp(exts[0], VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0);
330 EXPECT(std::strcmp(exts[1], VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0);
331 EXPECT(std::strcmp(exts[2], VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME) == 0);
332 EXPECT(std::strcmp(exts[3], VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) == 0);
333 }
334
335 // device_proc_or_khr resolves core first, then KHR, then EXT, else null.
336 {
337 ProcLookup lookup;
338 g_proc = &lookup;
339
340 lookup.core_name = "vkCmdPipelineBarrier2";
341 lookup.khr_name = "vkCmdPipelineBarrier2KHR";
342 lookup.ext_name = "vkCmdPipelineBarrier2EXT";
343 EXPECT(device_proc_or_khr(fake_get_device_proc, VK_NULL_HANDLE, "vkCmdPipelineBarrier2") == stub_core);
344 EXPECT(lookup.queries.size() == 1 && lookup.queries[0] == "vkCmdPipelineBarrier2");
345
346 lookup.queries.clear();
347 lookup.core_name = nullptr;
348 EXPECT(device_proc_or_khr(fake_get_device_proc, VK_NULL_HANDLE, "vkCmdPipelineBarrier2") == stub_khr);
349 EXPECT(lookup.queries.size() == 2 && lookup.queries[1] == "vkCmdPipelineBarrier2KHR");
350
351 lookup.queries.clear();
352 lookup.khr_name = nullptr;
353 lookup.ext_name = "vkCmdSetPrimitiveTopologyEXT";
354 EXPECT(device_proc_or_khr(fake_get_device_proc, VK_NULL_HANDLE, "vkCmdSetPrimitiveTopology") == stub_ext);
355 EXPECT(lookup.queries.size() == 3 && lookup.queries[2] == "vkCmdSetPrimitiveTopologyEXT");
356
357 lookup.queries.clear();
358 lookup.ext_name = nullptr;
359 EXPECT(device_proc_or_khr(fake_get_device_proc, VK_NULL_HANDLE, "vkCmdBeginRendering") == nullptr);
360 EXPECT(lookup.queries.size() == 3);
361 }
362
363 std::printf("vulkan13_features: all checks passed\n");
364 return 0;
365}
diff --git a/runtime/test/winhttp_offline_test.cpp b/runtime/test/winhttp_offline_test.cpp
index 3d80c7f02..4181103fd 100644
--- a/runtime/test/winhttp_offline_test.cpp
+++ b/runtime/test/winhttp_offline_test.cpp
@@ -126,6 +126,30 @@ int main() {
126 "request headers are accepted"); 126 "request headers are accepted");
127 check(set_timeouts(request, 1000, 1000, 1000, 1000) != FALSE, "timeouts are accepted"); 127 check(set_timeouts(request, 1000, 1000, 1000, 1000) != FALSE, "timeouts are accepted");
128 128
129 // The same answers the host's winhttp.dll gives (measured on Windows 11 26300).
130 const auto rejects = [](BOOL ok) { return ok == FALSE && GetLastError() == ERROR_INVALID_PARAMETER; };
131 SetLastError(0);
132 check(rejects(add_headers(request, nullptr, 0, WINHTTP_ADDREQ_FLAG_ADD)), "a null header block is rejected");
133 SetLastError(0);
134 check(rejects(add_headers(request, L"", static_cast<DWORD>(-1), WINHTTP_ADDREQ_FLAG_ADD)),
135 "an empty header block is rejected");
136 SetLastError(0);
137 check(rejects(add_headers(request, L"nocolon", static_cast<DWORD>(-1), WINHTTP_ADDREQ_FLAG_ADD)),
138 "a header with no colon is rejected");
139 SetLastError(0);
140 check(rejects(add_headers(request, L"X-C: b", 2, WINHTTP_ADDREQ_FLAG_ADD)),
141 "a length that cuts the header before its colon is rejected");
142 check(add_headers(request, L"X-D: b", 6, WINHTTP_ADDREQ_FLAG_ADD) != FALSE,
143 "an explicit length that covers the colon is accepted");
144 check(set_timeouts(request, 0, 0, 0, 0) != FALSE && set_timeouts(request, -1, -1, -1, -1) != FALSE,
145 "timeouts of 0 and -1 (infinite) are accepted");
146 for (int field = 0; field < 4; ++field) {
147 int t[4] = {0, 0, 0, 0};
148 t[field] = -2;
149 SetLastError(0);
150 check(rejects(set_timeouts(request, t[0], t[1], t[2], t[3])), "a timeout below -1 is rejected");
151 }
152
129 SetLastError(0); 153 SetLastError(0);
130 const auto start = std::chrono::steady_clock::now(); 154 const auto start = std::chrono::steady_clock::now();
131 const BOOL sent = send(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); 155 const BOOL sent = send(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp
index 6d8860c99..4bf37f8c6 100644
--- a/runtime/test/xbox_present_test.cpp
+++ b/runtime/test/xbox_present_test.cpp
@@ -96,8 +96,10 @@ bool region_is(const Frame& frame, UINT x0, UINT y0, UINT x1, UINT y1, Px want,
96// A CPU model of runtime/src/present_compose.comp, in double precision, written from the documented behaviour 96// A CPU model of runtime/src/present_compose.comp, in double precision, written from the documented behaviour
97// (docs/d3d12_vulkan.md section 4.5), not from the shader's code: planes scaled from a source rectangle to a 97// (docs/d3d12_vulkan.md section 4.5), not from the shader's code: planes scaled from a source rectangle to a
98// destination rectangle (point: the texel containing the sample; bilinear: four texels clamped inside the source 98// destination rectangle (point: the texel containing the sample; bilinear: four texels clamped inside the source
99// rectangle), SDR = G2.2 Rec.709, HDR10 = PQ Rec.2020, conversions through linear light and `white` nits, plane 1 blended 99// rectangle). SDR = piecewise sRGB (or G2.2, `gamma22`) Rec.709, HDR10 = PQ Rec.2020. Every texel is decoded to linear light,
100// over plane 0 in the output's encoded space, premultiplied or straight. 100// premultiplied, before it is weighted; the filtered plane is converted to the output's linear working space (HDR10 output:
101// Rec.2020 nits with SDR white = `white` nits; SDR output: Rec.709 with SDR white = 1, HDR10 content tone mapped by
102// extended Reinhard with its white point at `hdr_peak` nits), plane 1 is blended over plane 0 there and the sum is encoded once.
101namespace xbox_present_ref { 103namespace xbox_present_ref {
102 104
103struct Tex { 105struct Tex {
@@ -110,6 +112,8 @@ struct Ref_plane {
110 bool point = false, hdr = false, straight = false; 112 bool point = false, hdr = false, straight = false;
111}; 113};
112using V3 = std::array<double, 3>; 114using V3 = std::array<double, 3>;
115bool gamma22 = false; // SDR EOTF: false piecewise sRGB, true pure 2.2
116double hdr_peak = 1000.0; // nits, the tone map's white point
113 117
114double pq_encode(double nits) { 118double pq_encode(double nits) {
115 const double m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875; 119 const double m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875;
@@ -121,43 +125,74 @@ double pq_decode(double e) {
121 const double ep = std::pow(std::clamp(e, 0.0, 1.0), 1.0 / m2); 125 const double ep = std::pow(std::clamp(e, 0.0, 1.0), 1.0 / m2);
122 return 10000.0 * std::pow(std::max(ep - c1, 0.0) / (c2 - c3 * ep), 1.0 / m1); 126 return 10000.0 * std::pow(std::max(ep - c1, 0.0) / (c2 - c3 * ep), 1.0 / m1);
123} 127}
124V3 convert(V3 c, bool plane_hdr, bool out_hdr, double white) { 128double sdr_decode(double e) {
125 if (plane_hdr == out_hdr) return c; 129 e = std::max(e, 0.0);
126 if (!plane_hdr) { // SDR -> PQ 130 if (gamma22) return std::pow(e, 2.2);
127 const double r = std::pow(std::clamp(c[0], 0.0, 1.0), 2.2), g = std::pow(std::clamp(c[1], 0.0, 1.0), 2.2), 131 return e <= 0.04045 ? e / 12.92 : std::pow((e + 0.055) / 1.055, 2.4);
128 b = std::pow(std::clamp(c[2], 0.0, 1.0), 2.2); 132}
129 return {pq_encode((0.627404 * r + 0.329283 * g + 0.043313 * b) * white), 133double sdr_encode(double l) {
130 pq_encode((0.069097 * r + 0.919540 * g + 0.011362 * b) * white), 134 l = std::clamp(l, 0.0, 1.0);
131 pq_encode((0.016391 * r + 0.088013 * g + 0.895595 * b) * white)}; 135 if (gamma22) return std::pow(l, 1.0 / 2.2);
136 return l <= 0.0031308 ? l * 12.92 : 1.055 * std::pow(l, 1.0 / 2.4) - 0.055;
137}
138// The tone map's luminance curve, in units of SDR white: identity up to the knee (0.8), above it extended Reinhard on the
139// excess (Reinhard et al. 2002, eq. 4) with value and slope continuous at the knee and the content peak mapped to 1.0.
140double tone_y(double y, double white) {
141 const double knee = 0.8, t = 1.0 - knee;
142 if (y <= knee) return y;
143 const double lw = std::max(hdr_peak / white, 1.0), w = (lw - knee) / t, u = (y - knee) / t;
144 return knee + t * u * (1.0 + u / (w * w)) / (1.0 + u);
145}
146// v in linear Rec.709 with SDR white = 1: colour scaled by Yd / Y.
147V3 tone_map(V3 v, double white) {
148 const double y = 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];
149 const double s = y > 0.0 ? tone_y(y, white) / y : 1.0;
150 return {v[0] * s, v[1] * s, v[2] * s};
151}
152// A premultiplied linear colour of alpha `a` from the plane's space to the output's working space.
153V3 to_working(V3 lin, double a, bool plane_hdr, bool out_hdr, double white) {
154 if (plane_hdr == out_hdr) return lin;
155 if (!plane_hdr) // Rec.709 -> Rec.2020, SDR white at `white` nits
156 return {(0.627404 * lin[0] + 0.329283 * lin[1] + 0.043313 * lin[2]) * white,
157 (0.069097 * lin[0] + 0.919540 * lin[1] + 0.011362 * lin[2]) * white,
158 (0.016391 * lin[0] + 0.088013 * lin[1] + 0.895595 * lin[2]) * white};
159 if (a <= 0.0) return {0, 0, 0};
160 const double r = lin[0] / a, g = lin[1] / a, b = lin[2] / a;
161 V3 v{std::max((1.660491 * r - 0.587641 * g - 0.072850 * b) / white, 0.0),
162 std::max((-0.124550 * r + 1.132900 * g - 0.008349 * b) / white, 0.0),
163 std::max((-0.018151 * r - 0.100579 * g + 1.118730 * b) / white, 0.0)};
164 v = tone_map(v, white);
165 return {v[0] * a, v[1] * a, v[2] * a};
166}
167// The texel as linear premultiplied colour and alpha, in the plane's space. `opaque`: plane 0, whose alpha is ignored.
168std::array<double, 4> decode_texel(const std::array<double, 4>& t, const Ref_plane& p, bool opaque) {
169 const double a = opaque ? 1.0 : std::clamp(t[3], 0.0, 1.0);
170 std::array<double, 4> out{0, 0, 0, a};
171 for (int c = 0; c < 3; ++c) {
172 double e = t[c];
173 if (!opaque && !p.straight) e = a > 0.0 ? e / a : 0.0; // premultiplied data is divided by alpha for the decode
174 out[c] = (p.hdr ? pq_decode(e) : sdr_decode(e)) * a;
132 } 175 }
133 const double r = pq_decode(c[0]), g = pq_decode(c[1]), b = pq_decode(c[2]); 176 return out;
134 const auto sdr = [&](double v) { return std::pow(std::clamp(v / white, 0.0, 1.0), 1.0 / 2.2); };
135 return {sdr(1.660491 * r - 0.587641 * g - 0.072850 * b), sdr(-0.124550 * r + 1.132900 * g - 0.008349 * b),
136 sdr(-0.018151 * r - 0.100579 * g + 1.118730 * b)};
137} 177}
138std::array<double, 4> sample(const Ref_plane& p, int x, int y) { 178std::array<double, 4> sample(const Ref_plane& p, bool opaque, int x, int y) {
139 const Tex& t = *p.tex; 179 const Tex& t = *p.tex;
140 const double u = (x + 0.5 - p.dest[0]) / (p.dest[2] - p.dest[0]), v = (y + 0.5 - p.dest[1]) / (p.dest[3] - p.dest[1]); 180 const double u = (x + 0.5 - p.dest[0]) / (p.dest[2] - p.dest[0]), v = (y + 0.5 - p.dest[1]) / (p.dest[3] - p.dest[1]);
141 const double sx = p.src[0] + u * (p.src[2] - p.src[0]), sy = p.src[1] + v * (p.src[3] - p.src[1]); 181 const double sx = p.src[0] + u * (p.src[2] - p.src[0]), sy = p.src[1] + v * (p.src[3] - p.src[1]);
142 const auto at = [&](int ix, int iy) { return t.px[std::size_t(iy) * t.w + ix]; }; 182 const auto at = [&](int ix, int iy) { return decode_texel(t.px[std::size_t(iy) * t.w + ix], p, opaque); };
143 if (p.point) 183 if (p.point)
144 return at(int(std::clamp(std::floor(sx), p.src[0], p.src[2] - 1)), int(std::clamp(std::floor(sy), p.src[1], p.src[3] - 1))); 184 return at(int(std::clamp(std::floor(sx), p.src[0], p.src[2] - 1)), int(std::clamp(std::floor(sy), p.src[1], p.src[3] - 1)));
145 const double fx = std::clamp(sx - 0.5, p.src[0], p.src[2] - 1), fy = std::clamp(sy - 0.5, p.src[1], p.src[3] - 1); 185 const double fx = std::clamp(sx - 0.5, p.src[0], p.src[2] - 1), fy = std::clamp(sy - 0.5, p.src[1], p.src[3] - 1);
146 const int x0 = int(std::floor(fx)), y0 = int(std::floor(fy)); 186 const int x0 = int(std::floor(fx)), y0 = int(std::floor(fy));
147 const int x1 = int(std::min(double(x0) + 1, p.src[2] - 1)), y1 = int(std::min(double(y0) + 1, p.src[3] - 1)); 187 const int x1 = int(std::min(double(x0) + 1, p.src[2] - 1)), y1 = int(std::min(double(y0) + 1, p.src[3] - 1));
148 const double wx = fx - x0, wy = fy - y0; 188 const double wx = fx - x0, wy = fy - y0;
149 // Four texels with their bilinear weights. Straight-alpha colour is weighted by its alpha (filtering associated colour), 189 // Four decoded texels with their bilinear weights: linear light, premultiplied, so a transparent texel contributes no
150 // then divided by the filtered alpha: a transparent texel contributes no colour of its own. 190 // colour of its own.
151 const double weight[4] = {(1 - wx) * (1 - wy), wx * (1 - wy), (1 - wx) * wy, wx * wy}; 191 const double weight[4] = {(1 - wx) * (1 - wy), wx * (1 - wy), (1 - wx) * wy, wx * wy};
152 const std::array<double, 4> texel[4] = {at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1)}; 192 const std::array<double, 4> texel[4] = {at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1)};
153 std::array<double, 4> out{}; 193 std::array<double, 4> out{};
154 for (int i = 0; i < 4; ++i) { 194 for (int i = 0; i < 4; ++i)
155 const double colour_weight = p.straight ? weight[i] * texel[i][3] : weight[i]; 195 for (int c = 0; c < 4; ++c) out[c] += texel[i][c] * weight[i];
156 for (int c = 0; c < 3; ++c) out[c] += texel[i][c] * colour_weight;
157 out[3] += texel[i][3] * weight[i];
158 }
159 if (p.straight)
160 for (int c = 0; c < 3; ++c) out[c] = out[3] > 0.0 ? out[c] / out[3] : 0.0;
161 return out; 196 return out;
162} 197}
163V3 compose(const Ref_plane* planes, int count, bool out_hdr, double white, int x, int y) { 198V3 compose(const Ref_plane* planes, int count, bool out_hdr, double white, int x, int y) {
@@ -166,21 +201,15 @@ V3 compose(const Ref_plane* planes, int count, bool out_hdr, double white, int x
166 }; 201 };
167 V3 base{0, 0, 0}; 202 V3 base{0, 0, 0};
168 if (inside(planes[0])) { 203 if (inside(planes[0])) {
169 const auto c = sample(planes[0], x, y); 204 const auto c = sample(planes[0], true, x, y);
170 base = convert({c[0], c[1], c[2]}, planes[0].hdr, out_hdr, white); 205 base = to_working({c[0], c[1], c[2]}, 1.0, planes[0].hdr, out_hdr, white);
171 } 206 }
172 if (count > 1 && inside(planes[1])) { 207 if (count > 1 && inside(planes[1])) {
173 const Ref_plane& p = planes[1]; 208 const auto c = sample(planes[1], false, x, y);
174 const auto c = sample(p, x, y); 209 const V3 over = to_working({c[0], c[1], c[2]}, c[3], planes[1].hdr, out_hdr, white);
175 const double a = std::clamp(c[3], 0.0, 1.0); 210 for (int i = 0; i < 3; ++i) base[i] = over[i] + (1 - c[3]) * base[i];
176 V3 over{c[0], c[1], c[2]};
177 if (p.hdr != out_hdr) { // converted as unassociated colour, premultiplied again afterwards
178 if (!p.straight && a > 0.0) over = {c[0] / a, c[1] / a, c[2] / a};
179 over = convert(over, p.hdr, out_hdr, white);
180 if (!p.straight) over = {over[0] * a, over[1] * a, over[2] * a};
181 }
182 for (int i = 0; i < 3; ++i) base[i] = p.straight ? base[i] * (1 - a) + over[i] * a : over[i] + (1 - a) * base[i];
183 } 211 }
212 for (double& v : base) v = out_hdr ? pq_encode(std::max(v, 0.0)) : sdr_encode(v);
184 return base; 213 return base;
185} 214}
186 215
@@ -246,7 +275,7 @@ int main() {
246 100, 100, frame_rect.right - frame_rect.left, frame_rect.bottom - frame_rect.top, 275 100, 100, frame_rect.right - frame_rect.left, frame_rect.bottom - frame_rect.top,
247 nullptr, nullptr, window_class.hInstance, nullptr); 276 nullptr, nullptr, window_class.hInstance, nullptr);
248 EXPECT(window); 277 EXPECT(window);
249 ShowWindow(window, SW_SHOWNORMAL); 278 ShowWindow(window, SW_SHOWNOACTIVATE);
250 UpdateWindow(window); 279 UpdateWindow(window);
251 pump(); 280 pump();
252 281
@@ -632,6 +661,15 @@ int main() {
632 p.tex.px[std::size_t(y) * p.tex.w + x] = {R / 1023.0, G / 1023.0, B / 1023.0, 1.0}; 661 p.tex.px[std::size_t(y) * p.tex.w + x] = {R / 1023.0, G / 1023.0, B / 1023.0, 1.0};
633 return true; 662 return true;
634 }; 663 };
664 // R10G10B10A2 with a 2-bit alpha (0..3): stored colour is premultiplied by the caller.
665 const auto paint10a = [&](Painted& p, D3D12_RECT r, int R, int G, int B, int A) {
666 const FLOAT c[4] = {R / 1023.0f, G / 1023.0f, B / 1023.0f, A / 3.0f};
667 if (!fill(p.source, c, 1, &r)) return false;
668 for (LONG y = r.top; y < r.bottom; ++y)
669 for (LONG x = r.left; x < r.right; ++x)
670 p.tex.px[std::size_t(y) * p.tex.w + x] = {R / 1023.0, G / 1023.0, B / 1023.0, A / 3.0};
671 return true;
672 };
635 // One PresentX of `count` planes, a fresh token for all; the swapchain frame is read back into `frame`. 673 // One PresentX of `count` planes, a fresh token for all; the swapchain frame is read back into `frame`.
636 const auto present_planes = [&](rt::d3d12::XboxPresentPlaneParameters* planes_, UINT count_, HRESULT want = S_OK) { 674 const auto present_planes = [&](rt::d3d12::XboxPresentPlaneParameters* planes_, UINT count_, HRESULT want = S_OK) {
637 clock.advance_us(4 * period); 675 clock.advance_us(4 * period);
@@ -673,6 +711,32 @@ int main() {
673 const std::uint64_t composed_start = xbox.presenter().composed_presents(); 711 const std::uint64_t composed_start = xbox.presenter().composed_presents();
674 std::uint64_t composed_expected = composed_start; 712 std::uint64_t composed_expected = composed_start;
675 const auto composed_ok = [&] { return xbox.presenter().composed_presents() == ++composed_expected; }; 713 const auto composed_ok = [&] { return xbox.presenter().composed_presents() == ++composed_expected; };
714 // Fixed inputs whatever the machine says: SDR white 203 nits (not the Windows slider), piecewise sRGB (not
715 // LEONIDA_SDR_EOTF), peak 1000 nits. The query itself is checked on its own below.
716 xbox.set_sdr_white_nits(203.0f);
717 xbox.set_sdr_eotf(leonida::PresentPlanes::SdrEotf::srgb);
718 xbox.set_hdr_peak_nits(1000.0f);
719 xbox_present_ref::gamma22 = false;
720 xbox_present_ref::hdr_peak = 1000.0;
721 {
722 EXPECT(rt::d3d12::sdr_white_nits_from_level(1000) == 80.0f && rt::d3d12::sdr_white_nits_from_level(2500) == 200.0f &&
723 rt::d3d12::sdr_white_nits_from_level(6000) == 480.0f);
724 // The query's cost: why PresentX does not run it (the layer caches it from a background thread).
725 float windows_white = 0.0f;
726 double total_us = 0, worst_us = 0;
727 const int queries = 50;
728 for (int q = 0; q < queries; ++q) {
729 const auto t0 = std::chrono::steady_clock::now();
730 windows_white = xbox.presenter().display_sdr_white_nits(); // 0 when Windows has no answer
731 const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
732 total_us += us;
733 worst_us = std::max(worst_us, us);
734 }
735 std::printf("SDR white level query: %.0f us mean, %.0f us worst over %d calls\n", total_us / queries, worst_us, queries);
736 EXPECT(windows_white == 0.0f || (windows_white >= 80.0f && windows_white <= 480.0f));
737 std::printf("SDR white level of this window's output from Windows: %s%.1f nits (hdr_active %d)\n",
738 windows_white > 0 ? "" : "unavailable, ", windows_white, int(xbox.presenter().hdr_active()));
739 }
676 740
677 // A: one plane, scaled 2x to the middle of the output, point and linear; the rest of the output is black. 741 // A: one plane, scaled 2x to the middle of the output, point and linear; the rest of the output is black.
678 Painted quad; 742 Painted quad;
@@ -754,8 +818,7 @@ int main() {
754 // Straight alpha with bilinear filtering across a transparent edge: opaque white on the left, transparent black on the 818 // Straight alpha with bilinear filtering across a transparent edge: opaque white on the left, transparent black on the
755 // right. Colour is filtered premultiplied, so the edge is white at partial alpha, not grey (filtering the 819 // right. Colour is filtered premultiplied, so the edge is white at partial alpha, not grey (filtering the
756 // unassociated colour would also quarter the colour and quarter it again by the alpha). At output x=160 the sample 820 // unassociated colour would also quarter the colour and quarter it again by the alpha). At output x=160 the sample
757 // is 0.75 of the way from the white texel to the transparent one: alpha 0.25, colour white: 821 // is 0.75 of the way from the white texel to the transparent one: alpha 0.25, colour white, blended in linear light.
758 // base 51 + 0.25 * (255 - 51) = 102.
759 Painted edge; 822 Painted edge;
760 EXPECT(make_painted(edge, 80, 60)); 823 EXPECT(make_painted(edge, 80, 60));
761 EXPECT(paint(edge, {0, 0, 40, 60}, 255, 255, 255, 255) && paint(edge, {40, 0, 80, 60}, 0, 0, 0, 0)); 824 EXPECT(paint(edge, {0, 0, 40, 60}, 255, 255, 255, 255) && paint(edge, {40, 0, 80, 60}, 0, 0, 0, 0));
@@ -766,8 +829,13 @@ int main() {
766 EXPECT(frame_matches(frame, refs, 2, false, 203.0, 1)); 829 EXPECT(frame_matches(frame, refs, 2, false, 203.0, 1));
767 { 830 {
768 const Px edge_px = frame.at(160, 120); 831 const Px edge_px = frame.at(160, 120);
769 // red: 51 + 0.25 * 204 = 102 (blue: 230 + 0.25 * 25 = 236); the unfiltered-colour result would be near 54 832 // Linear light: red 0.25 + 0.75 * lin(51/255), blue 0.25 + 0.75 * lin(230/255), then encoded (piecewise sRGB:
770 EXPECT(std::abs(edge_px.r - 102) <= 1 && std::abs(edge_px.b - 236) <= 1); 833 // about 143 and 237); the unfiltered-colour result would be near 54 and blending the encoded values would give 102.
834 const auto expect_level = [](double base255) {
835 return int(std::lround(255 * xbox_present_ref::sdr_encode(0.25 + 0.75 * xbox_present_ref::sdr_decode(base255 / 255))));
836 };
837 EXPECT(std::abs(edge_px.r - expect_level(51)) <= 1 && std::abs(edge_px.b - expect_level(230)) <= 1);
838 std::printf("compose: edge pixel %d,%d,%d (linear-light model %d,%d)\n", edge_px.r, edge_px.g, edge_px.b, expect_level(51), expect_level(230));
771 } 839 }
772 std::printf("compose: straight alpha, bilinear across a transparent edge (premultiplied filtering): ok\n"); 840 std::printf("compose: straight alpha, bilinear across a transparent edge (premultiplied filtering): ok\n");
773 841
@@ -785,7 +853,7 @@ int main() {
785 const bool surface_hdr = xbox.presenter().hdr_active(); 853 const bool surface_hdr = xbox.presenter().hdr_active();
786 if (!surface_hdr) { 854 if (!surface_hdr) {
787 EXPECT(frame_matches(frame, &href, 1, false, 203.0, 2)); 855 EXPECT(frame_matches(frame, &href, 1, false, 203.0, 2));
788 std::printf("compose: HDR10 plane to an SDR swapchain (clipped to SDR, white = 203 nits): within 2 levels of the model\n"); 856 std::printf("compose: HDR10 plane to an SDR swapchain (tone mapped to SDR, white = 203 nits, peak 1000): within 2 levels of the model\n");
789 } else { 857 } else {
790 // A real HDR10 swapchain: the 10-bit codes come out as they went in (plane 0, point, 1:1 PQ). 858 // A real HDR10 swapchain: the 10-bit codes come out as they went in (plane 0, point, 1:1 PQ).
791 EXPECT(frame.format == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || frame.format == VK_FORMAT_A2R10G10B10_UNORM_PACK32); 859 EXPECT(frame.format == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || frame.format == VK_FORMAT_A2R10G10B10_UNORM_PACK32);
@@ -834,9 +902,129 @@ int main() {
834 std::printf("compose: the surface has HDR10: the forced-encoding checks are skipped on it\n"); 902 std::printf("compose: the surface has HDR10: the forced-encoding checks are skipped on it\n");
835 } 903 }
836 if (!surface_hdr) 904 if (!surface_hdr)
837 std::printf("compose: HDR10 swapchain: this surface/display lists no ST.2084 format, so only the SDR clip and " 905 std::printf("compose: HDR10 swapchain: this surface/display lists no ST.2084 format, so only the SDR tone map and "
838 "the PQ encoder were run (HDR10 swapchain case skipped)\n"); 906 "the PQ encoder were run (HDR10 swapchain case skipped)\n");
839 907
908 // C2: linear-light blending and the SDR EOTF option. A 50% white overlay (premultiplied 128,128,128 alpha 128) over
909 // black is half the light: byte 188 with piecewise sRGB, 186 with gamma 2.2 (blending the encoded values would give
910 // 128), checked against the model and against these numbers.
911 {
912 Painted black, half_white;
913 EXPECT(make_painted(black, width, height));
914 EXPECT(paint(black, {0, 0, LONG(width), LONG(height)}, 0, 0, 0, 255));
915 EXPECT(make_painted(half_white, 8, 8));
916 EXPECT(paint(half_white, {0, 0, 8, 8}, 128, 128, 128, 128));
917 pair[0] = parameters(black.source, nullptr, xbox_scale_filter_point);
918 pair[1] = parameters(half_white.source, nullptr, xbox_scale_filter_point, 0, rt::d3d12::xbox_plane_flag_overlay);
919 Ref_plane lrefs[2] = {model(black, nullptr, true), model(half_white, nullptr, true)};
920 const double alpha = 128.0 / 255.0;
921 for (const bool g22 : {false, true}) {
922 xbox.set_sdr_eotf(g22 ? leonida::PresentPlanes::SdrEotf::gamma22 : leonida::PresentPlanes::SdrEotf::srgb);
923 xbox_present_ref::gamma22 = g22;
924 EXPECT(present_planes(pair, 2) && composed_ok());
925 EXPECT(frame_matches(frame, lrefs, 2, false, 203.0, 1));
926 // the overlay's white, as light (premultiplied 128/255 over alpha 0.502 is white): 0.502 of full white
927 const int want = int(std::lround(255 * xbox_present_ref::sdr_encode(alpha)));
928 EXPECT(region_is(frame, 0, 0, width, height, {want, want, want}, 1));
929 // independent of the model's formulas (hand calculation: 0.50196 as light is 187.8 and 186.4 in bytes)
930 EXPECT(region_is(frame, 0, 0, width, height, g22 ? Px{186, 186, 186} : Px{188, 188, 188}, 1));
931 std::printf("compose: 50%% white over black, %s: byte %d (model %d, encoded-space blend would be 128)\n",
932 g22 ? "gamma 2.2" : "piecewise sRGB", frame.at(10, 10).r, want);
933 // an SDR plane 0 alone through the same EOTF: bytes come out as they went in
934 one = parameters(quad.source, nullptr, xbox_scale_filter_point);
935 EXPECT(present_planes(&one, 1) && composed_ok());
936 Ref_plane q = model(quad, nullptr, true);
937 EXPECT(frame_matches(frame, &q, 1, false, 203.0, 0));
938 }
939 xbox.set_sdr_eotf(leonida::PresentPlanes::SdrEotf::srgb);
940 xbox_present_ref::gamma22 = false;
941 std::printf("compose: SDR EOTF sRGB and gamma 2.2: linear blend matches the model, single planes unchanged: ok\n");
942 }
943
944 // C3: HDR10 -> SDR output is tone mapped, not clipped: identity on luminance up to 0.8 of SDR white (162 nits), then
945 // a Reinhard shoulder that maps the content peak to 1.0. Eight columns of grey (50, 100, 150, 203, 300, 500, 750, 1000
946 // nits). The expected bytes are hand calculations (sRGB encode of the knee curve), not the model's code; 10-bit PQ
947 // codes make them good to 2.
948 {
949 // the curve itself: monotonic, identity below the knee, continuous in slope, peak -> 1
950 for (const double white : {203.0, 100.0}) {
951 double previous = -1;
952 for (double y = 0; y <= 20; y += 0.01) {
953 const double d_y = xbox_present_ref::tone_y(y, white);
954 EXPECT(d_y >= previous);
955 EXPECT(y > 0.8 || d_y == y);
956 previous = d_y;
957 }
958 const double lw = xbox_present_ref::hdr_peak / white;
959 EXPECT(std::abs(xbox_present_ref::tone_y(std::max(lw, 1.0), white) - 1.0) < 1e-12);
960 const double e = 1e-6;
961 EXPECT(std::abs((xbox_present_ref::tone_y(0.8 + e, white) - 0.8) / e - 1.0) < 1e-3);
962 }
963 }
964 if (!surface_hdr) {
965 Painted ramp;
966 EXPECT(make_painted(ramp, 80, 60, DXGI_FORMAT_R10G10B10A2_UNORM));
967 const double ramp_nits[8] = {50, 100, 150, 203, 300, 500, 750, 1000};
968 const int want_1000[8] = {136, 186, 223, 243, 250, 253, 254, 255};
969 const int want_600[8] = {136, 186, 223, 244, 250, 254, 255, 255};
970 for (int i = 0; i < 8; ++i)
971 EXPECT(paint10(ramp, {10 * i, 0, 10 * i + 10, 60}, code(ramp_nits[i]), code(ramp_nits[i]), code(ramp_nits[i])));
972 for (const float peak_nits : {1000.0f, 600.0f}) {
973 xbox.set_hdr_peak_nits(peak_nits);
974 xbox_present_ref::hdr_peak = peak_nits;
975 one = parameters(ramp.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020);
976 EXPECT(present_planes(&one, 1) && composed_ok());
977 Ref_plane rref = model(ramp, nullptr, true, nullptr, true);
978 EXPECT(frame_matches(frame, &rref, 1, false, 203.0, 2));
979 const int* want = peak_nits == 1000.0f ? want_1000 : want_600;
980 int previous = -1;
981 bool ok = true;
982 for (int i = 0; i < 8; ++i) {
983 const Px got = frame.at(UINT(i * 40 + 20), 10);
984 ok = ok && std::abs(got.r - want[i]) <= 2 && got.r >= previous;
985 previous = got.r;
986 }
987 EXPECT(ok);
988 // SDR-range content (100 and 150 nits are below the knee) is not touched by the tone map
989 EXPECT(std::abs(frame.at(60, 10).r - 186) <= 2 && std::abs(frame.at(100, 10).r - 223) <= 2);
990 std::printf("compose: HDR10 ramp tone mapped onto SDR, peak %.0f nits: bytes", peak_nits);
991 for (int i = 0; i < 8; ++i) std::printf(" %d", frame.at(UINT(i * 40 + 20), 10).r);
992 std::printf(" (hand calculation:");
993 for (int i = 0; i < 8; ++i) std::printf(" %d", want[i]);
994 std::printf(")\n");
995 }
996 xbox.set_hdr_peak_nits(1000.0f);
997 xbox_present_ref::hdr_peak = 1000.0;
998 }
999
1000 // C4: an HDR10 plane 1 over an SDR plane 0 (the reverse of the case above), on a forced HDR10 encoding and on the SDR
1001 // output. Plane 1 is premultiplied grey of 400 nits at alpha 2/3 (stored code = PQ(400) * 2/3), plane 0 black. As
1002 // light the result is 266.7 nits (PQ byte 155, hand calculation) on the HDR10 output; on the SDR output 400 nits is
1003 // 1.97 of SDR white, shoulder-mapped to 0.973, times 2/3, sRGB encoded: byte 211.
1004 if (!surface_hdr) {
1005 Painted black4, hdr_ui;
1006 EXPECT(make_painted(black4, width, height));
1007 EXPECT(paint(black4, {0, 0, LONG(width), LONG(height)}, 0, 0, 0, 255));
1008 EXPECT(make_painted(hdr_ui, 16, 16, DXGI_FORMAT_R10G10B10A2_UNORM));
1009 const int stored = int(std::lround(code(400) * 2.0 / 3.0));
1010 EXPECT(paint10a(hdr_ui, {0, 0, 16, 16}, stored, stored, stored, 2));
1011 pair[0] = parameters(black4.source, nullptr, xbox_scale_filter_point);
1012 pair[1] = parameters(hdr_ui.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020,
1013 rt::d3d12::xbox_plane_flag_overlay);
1014 Ref_plane urefs[2] = {model(black4, nullptr, true), model(hdr_ui, nullptr, true, nullptr, true)};
1015 xbox.presenter().force_hdr_encoding(true);
1016 EXPECT(present_planes(pair, 2) && composed_ok());
1017 EXPECT(frame_matches(frame, urefs, 2, true, 203.0, 2));
1018 const int hdr_byte = int(frame.at(5, 5).r);
1019 EXPECT(region_is(frame, 0, 0, width, height, {155, 155, 155}, 3));
1020 xbox.presenter().force_hdr_encoding(false);
1021 EXPECT(present_planes(pair, 2) && composed_ok());
1022 EXPECT(frame_matches(frame, urefs, 2, false, 203.0, 2));
1023 EXPECT(region_is(frame, 0, 0, width, height, {211, 211, 211}, 3));
1024 std::printf("compose: HDR10 plane 1 (premultiplied, alpha 2/3) over SDR plane 0: HDR10 output byte %d (hand 155), SDR output byte %d (hand 211): ok\n",
1025 hdr_byte, int(frame.at(5, 5).r));
1026 }
1027
840 // D: an SDR plane 1 next to an HDR10 plane 0 that is not flagged an overlay is the GameDVR copy: not shown. 1028 // D: an SDR plane 1 next to an HDR10 plane 0 that is not flagged an overlay is the GameDVR copy: not shown.
841 pair[0] = parameters(hdr.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020); 1029 pair[0] = parameters(hdr.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020);
842 pair[1] = parameters(second, nullptr, xbox_scale_filter_point, 0); 1030 pair[1] = parameters(second, nullptr, xbox_scale_filter_point, 0);
diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp
index c5a0e988e..6464b4907 100644
--- a/runtime/test/xgameruntime_test.cpp
+++ b/runtime/test/xgameruntime_test.cpp
@@ -12,11 +12,16 @@
12#include <cstdio> 12#include <cstdio>
13#include <cstdlib> 13#include <cstdlib>
14#include <cstring> 14#include <cstring>
15#include <filesystem>
16#include <fstream>
17#include <string>
18#include <system_error>
15 19
16#include <XAsync.h> 20#include <XAsync.h>
17#include <XAsyncProvider.h> 21#include <XAsyncProvider.h>
18#include <XTaskQueue.h> 22#include <XTaskQueue.h>
19 23
24#include "file_system.h"
20#include "shims.h" 25#include "shims.h"
21 26
22namespace { 27namespace {
@@ -279,6 +284,20 @@ void check_run_time_load() {
279 reinterpret_cast<SetSensitive>(slot(t, 27))(t, false) == S_OK && 284 reinterpret_cast<SetSensitive>(slot(t, 27))(t, false) == S_OK &&
280 !reinterpret_cast<IsSensitive>(slot(t, 30))(t), 285 !reinterpret_cast<IsSensitive>(slot(t, 30))(t),
281 "slots 27 and 30 set and read this thread's time-sensitive flag"); 286 "slots 27 and 30 set and read this thread's time-sensitive flag");
287 // Slot 8 (XAsyncBeginAlloc, private, signature not measured) must not report a begun call whose provider
288 // never received XAsyncOp::Begin: either it refuses, or the provider saw Begin exactly once.
289 static std::atomic<int> s_begins{0};
290 XAsyncProvider* provider = [](XAsyncOp op, const XAsyncProviderData*) -> HRESULT {
291 if (op == XAsyncOp::Begin) s_begins.fetch_add(1);
292 return S_OK;
293 };
294 XAsyncBlock alloc_block{};
295 using BeginAlloc = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, const void*, const char*, XAsyncProvider*,
296 size_t, size_t, void*);
297 const HRESULT alloc_hr =
298 reinterpret_cast<BeginAlloc>(slot(t, 8))(t, &alloc_block, nullptr, "test", provider, 16, 0, nullptr);
299 check(FAILED(alloc_hr) || s_begins.load() == 1,
300 "slot 8 (XAsyncBeginAlloc) never reports success for a call whose provider did not begin");
282 void* unk = nullptr; 301 void* unk = nullptr;
283 const GUID iunknown = {0, 0, 0, {0xc0, 0, 0, 0, 0, 0, 0, 0x46}}; 302 const GUID iunknown = {0, 0, 0, {0xc0, 0, 0, 0, 0, 0, 0, 0x46}};
284 using QI = HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**); 303 using QI = HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**);
@@ -373,6 +392,79 @@ void check_run_time_load() {
373 release(n); 392 release(n);
374 } 393 }
375 394
395 // XPersistentLocalStorageImpl (RT-219): the class id with IXPersistentLocalStorageImpl3's interface id, over a
396 // temporary overlay. The storage folder is <overlay>\persistent.
397 const GUID pls_class = {0xf4faf4d4, 0x2d04, 0x4fce, {0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84}};
398 const GUID pls3 = {0x41a4e10c, 0x5a7e, 0x41d9, {0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6}};
399 const std::filesystem::path scratch =
400 std::filesystem::temp_directory_path() / (L"gta6rt_pls_test_" + std::to_wstring(GetCurrentProcessId()));
401 std::error_code scratch_ec;
402 std::filesystem::remove_all(scratch, scratch_ec);
403 rt::fs::configure(scratch / L"game", scratch / L"overlay");
404 void* pls = nullptr;
405 check(query(&pls_class, pls3, &pls) == S_OK && pls, "QueryApiImpl hands out XPersistentLocalStorageImpl for IXPersistentLocalStorageImpl3");
406 if (pls) {
407 using GetPathSize = HRESULT(STDMETHODCALLTYPE*)(void*, size_t*);
408 using GetPath = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*, size_t*);
409 using GetSpaceInfo = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t*);
410 using PromptAsync = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, XAsyncBlock*);
411 using PromptResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*);
412 using Mount = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, void**);
413
414 size_t size = 0;
415 check(reinterpret_cast<GetPathSize>(slot(pls, 3))(pls, &size) == S_OK && size > 1,
416 "slot 3 (GetPathSize) reports the length of the path with its NUL");
417 std::string path(size, '\xA5');
418 size_t used = 0;
419 check(reinterpret_cast<GetPath>(slot(pls, 4))(pls, size, path.data(), &used) == S_OK && used == size &&
420 path[size - 1] == '\0',
421 "slot 4 (GetPath) fills the buffer and reports the bytes used");
422 const std::filesystem::path folder = std::filesystem::path(path.c_str());
423 check(folder == scratch / L"overlay" / L"persistent" && std::filesystem::is_directory(folder),
424 "the path is <overlay>\\persistent and the folder exists");
425 char tiny[2] = {'x', 'x'};
426 used = 99;
427 check(reinterpret_cast<GetPath>(slot(pls, 4))(pls, 2, tiny, &used) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) &&
428 used == 0,
429 "slot 4 refuses a buffer that is too small");
430
431 {
432 std::ofstream cache_file(folder / L"cache.bin", std::ios::binary);
433 const std::string kilobyte(1024, 'z');
434 cache_file << kilobyte;
435 }
436 uint64_t info[4] = {9, 9, 9, 9}; // available free, total free, used, total
437 const HRESULT info_hr = reinterpret_cast<GetSpaceInfo>(slot(pls, 5))(pls, info);
438 check(info_hr == S_OK && info[3] == 2048ull * 1024 * 1024 && info[2] == 1024 && info[1] == info[3] - 1024 &&
439 info[0] > 0 && info[0] <= info[1],
440 "slot 5 (GetSpaceInfo): the 2048 MB quota, the bytes used, and what is left");
441
442 XAsyncBlock fits{};
443 check(reinterpret_cast<PromptAsync>(slot(pls, 6))(pls, 1024, &fits) == S_OK &&
444 XAsyncGetStatus(&fits, true) == S_OK && reinterpret_cast<PromptResult>(slot(pls, 7))(pls, &fits) == S_OK,
445 "slots 6/7: a prompt for space the quota can hold succeeds");
446 XAsyncBlock too_big{};
447 check(reinterpret_cast<PromptAsync>(slot(pls, 6))(pls, 4096ull * 1024 * 1024, &too_big) == S_OK &&
448 XAsyncGetStatus(&too_big, true) == HRESULT_FROM_WIN32(ERROR_DISK_FULL) &&
449 reinterpret_cast<PromptResult>(slot(pls, 7))(pls, &too_big) == HRESULT_FROM_WIN32(ERROR_DISK_FULL),
450 "slots 6/7: a prompt for more than the quota fails with ERROR_DISK_FULL");
451
452 void* handle = reinterpret_cast<void*>(1);
453 check(reinterpret_cast<Mount>(slot(pls, 8))(pls, "pkg", &handle) == E_NOTIMPL && handle == nullptr,
454 "slot 8 (MountForPackage) is E_NOTIMPL and leaves no handle");
455 release(pls);
456 }
457 rt::fs::configure({}, {});
458 check(query(&pls_class, pls_class, &pls) == S_OK, "the class answers with its own id too");
459 if (pls) {
460 using GetPathSize = HRESULT(STDMETHODCALLTYPE*)(void*, size_t*);
461 size_t size = 99;
462 check(reinterpret_cast<GetPathSize>(slot(pls, 3))(pls, &size) == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) && size == 0,
463 "with no overlay configured the path size fails instead of answering S_OK with nothing");
464 release(pls);
465 }
466 std::filesystem::remove_all(scratch, scratch_ec);
467
376 // XSystemImpl, asked for as libHttpClient.GDK.dll does: the class id with IXSystemImpl5's interface id. 468 // XSystemImpl, asked for as libHttpClient.GDK.dll does: the class id with IXSystemImpl5's interface id.
377 const GUID system_cls = {0xe349bd1a, 0xfc20, 0x4e40, {0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f}}; 469 const GUID system_cls = {0xe349bd1a, 0xfc20, 0x4e40, {0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f}};
378 const GUID system5 = {0x1861cf2e, 0xe18b, 0x4834, {0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf}}; 470 const GUID system5 = {0x1861cf2e, 0xe18b, 0x4834, {0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf}};
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index 7e4948f1f..1ad4080f7 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -204,6 +204,34 @@ void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn ge
204 "nonzero XMem allocation attributes are rejected before host allocation"); 204 "nonzero XMem allocation attributes are rejected before host allocation");
205} 205}
206 206
207using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD);
208
209// RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host
210// rejects. The registered shim has to drop them and still allocate.
211void test_title_virtual_alloc() {
212 constexpr DWORD kMemGraphics = 0x10000000;
213 constexpr DWORD kMemTitle = 0x40000000;
214 const char* const dlls[] = {"kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-l1-1-0.dll"};
215 for (const char* dll : dlls) {
216 const auto alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find(dll, "VirtualAlloc"));
217 char what[160];
218 std::snprintf(what, sizeof what, "registry exposes %s!VirtualAlloc", dll);
219 check(alloc != nullptr, what);
220 if (!alloc) continue;
221
222 for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) {
223 void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE);
224 std::snprintf(what, sizeof what, "%s!VirtualAlloc with type bits %#lx returns memory", dll,
225 static_cast<unsigned long>(bits));
226 check(p != nullptr, what);
227 if (!p) continue;
228 static_cast<volatile uint8_t*>(p)[0] = 0x5a;
229 check(static_cast<volatile uint8_t*>(p)[0] == 0x5a, "the allocation is committed and writable");
230 check(VirtualFree(p, 0, MEM_RELEASE), "release the allocation");
231 }
232 }
233}
234
207void print_result() { 235void print_result() {
208 if (g_failures == 0) { 236 if (g_failures == 0) {
209 std::printf("xmem_test: OK (%d checks)\n", g_checks); 237 std::printf("xmem_test: OK (%d checks)\n", g_checks);
@@ -250,6 +278,8 @@ int main() {
250 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch); 278 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch);
251 } 279 }
252 280
281 test_title_virtual_alloc();
282
253 print_result(); 283 print_result();
254 return g_failures ? 1 : 0; 284 return g_failures ? 1 : 0;
255} 285}