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-22 19:08:54 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 19:08:54 +0100
commit3af42c619253941610d9809e8a28a07e8dfdfdf2 (patch)
treea675793195f8bc69c3caebb0e9614ecfb65e1c4c /runtime/test
parente6af0a0931639ff33cdd4a28289da984f194c87e (diff)
parentec8ec4c9a46c6623f1a9c125afd3566da97f1e0c (diff)
merge: preserve upstream changes alongside the asset fix
Diffstat (limited to 'runtime/test')
-rw-r--r--runtime/test/bindless_sizing_test.cpp16
-rw-r--r--runtime/test/command_list_test.cpp18
-rw-r--r--runtime/test/d3d12_bundle_test.cpp840
-rw-r--r--runtime/test/d3d12_com_test.cpp15
-rw-r--r--runtime/test/d3d12_compute_test.cpp158
-rw-r--r--runtime/test/d3d12_descriptor_test.cpp360
-rw-r--r--runtime/test/d3d12_draw_test.cpp34
-rw-r--r--runtime/test/d3d12_first_light_test.cpp395
-rw-r--r--runtime/test/d3d12_shader_cache_test.cpp322
-rw-r--r--runtime/test/d3d12_texture1d_test.cpp272
-rw-r--r--runtime/test/d3d12_typeless_families_test.cpp416
-rw-r--r--runtime/test/d3d12_uav_clear_test.cpp42
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp201
-rw-r--r--runtime/test/d3d12_xdxr_rt_test.cpp2
-rw-r--r--runtime/test/file_system_test.cpp323
-rw-r--r--runtime/test/fixtures/tiny_bundled_load.cpp9
-rw-r--r--runtime/test/fixtures/tiny_gdk_load.cpp26
-rw-r--r--runtime/test/fixtures/tiny_tls_cb_only.cpp42
-rw-r--r--runtime/test/frame_pacer_test.cpp25
-rw-r--r--runtime/test/gameinput_test.cpp56
-rw-r--r--runtime/test/gfx10_descriptors_test.cpp49
-rw-r--r--runtime/test/glsl/ps_typeless_float.frag8
-rw-r--r--runtime/test/glsl/ps_typeless_uint.frag9
-rw-r--r--runtime/test/loader_tls_test.cpp149
-rw-r--r--runtime/test/process_cmdline_test.cpp61
-rw-r--r--runtime/test/replay_uav_clear_offset_test.cpp165
-rw-r--r--runtime/test/shaders/build.py18
-rw-r--r--runtime/test/shaders/check.py80
-rw-r--r--runtime/test/shaders/cs_buf_swizzle.asm19
-rw-r--r--runtime/test/shaders/cs_fmt_int_narrow.asm126
-rw-r--r--runtime/test/shaders/cs_fmt_sint32.asm6
-rw-r--r--runtime/test/shaders/cs_mask_vgpr_exec.asm15
-rw-r--r--runtime/test/shaders/cs_signed_zero_nan.asm63
-rw-r--r--runtime/test/shaders/gs_w64_a_ring.asm40
-rw-r--r--runtime/test/shaders/gs_w64_c_lane_id.asm36
-rw-r--r--runtime/test/shaders/ps_sdwa_f16_const.asm32
-rw-r--r--runtime/test/shaders/ps_w64_a_bpermute.asm44
-rw-r--r--runtime/test/shaders/ps_w64_a_permlane.asm42
-rw-r--r--runtime/test/shaders/ps_w64_a_swizzle.asm35
-rw-r--r--runtime/test/shaders/w64_graphics.py76
-rw-r--r--runtime/test/typeless_rtv_test.cpp6
-rw-r--r--runtime/test/vk_bindless_test.cpp5
-rw-r--r--runtime/test/vk_harness.cpp5
-rw-r--r--runtime/test/vk_pipeline_check.cpp149
-rw-r--r--runtime/test/vk_presenter_sync_test.cpp22
-rw-r--r--runtime/test/xgameruntime_test.cpp60
46 files changed, 4754 insertions, 138 deletions
diff --git a/runtime/test/bindless_sizing_test.cpp b/runtime/test/bindless_sizing_test.cpp
index 07715f01e..4553f25b6 100644
--- a/runtime/test/bindless_sizing_test.cpp
+++ b/runtime/test/bindless_sizing_test.cpp
@@ -203,6 +203,22 @@ int main() {
203 EXPECT(totals(f).all <= 6159 || (count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024)); 203 EXPECT(totals(f).all <= 6159 || (count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024));
204 } 204 }
205 205
206 // MoltenVK 1.4.3 on an M3 Max: update-after-bind limits of 1000000 sampled images and 500000 samplers, but
207 // maxPerSetDescriptors 1212 and a vkGetDescriptorSetLayoutSupport that accepts only fewer descriptors than that
208 // (MVKDevice::getDescriptorSetLayoutSupport), though the device creates and samples far larger sets. So the
209 // set keeps the default counts: 1024 samplers, short of a full D3D12 sampler heap (d3d12_descriptor_test).
210 {
211 Device d = uniform(1048576, 1000000);
212 d.v12.maxPerStageDescriptorUpdateAfterBindSamplers = d.v12.maxDescriptorSetUpdateAfterBindSamplers = 500000;
213 d.limits.maxSamplerAllocationCount = 500000;
214 d.v11.maxPerSetDescriptors = 1212;
215 const auto below_1212 = [](const BindlessFeatures& candidate) { return totals(candidate).all < 1212; };
216 BindlessFeatures f = with_ms(true);
217 EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, below_1212));
218 EXPECT(count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024 &&
219 storage(f, D::dim_2d) == 256);
220 }
221
206 // The default features are today's counts, which the device-less users (vk_image_fuzz) still get. 222 // The default features are today's counts, which the device-less users (vk_image_fuzz) still get.
207 EXPECT(BindlessFeatures{}.counts == defaults); 223 EXPECT(BindlessFeatures{}.counts == defaults);
208 std::printf("bindless sizing: synthetic limits gave the expected counts\n"); 224 std::printf("bindless sizing: synthetic limits gave the expected counts\n");
diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp
index 69fe14679..e459b4cc8 100644
--- a/runtime/test/command_list_test.cpp
+++ b/runtime/test/command_list_test.cpp
@@ -223,6 +223,24 @@ int main() {
223 CHECK(std::get<CopyResource>(parent.commands()[1]).src == 4); 223 CHECK(std::get<CopyResource>(parent.commands()[1]).src == 4);
224 CHECK(!parent.execute_bundle(bundle)); // parent is closed 224 CHECK(!parent.execute_bundle(bundle)); // parent is closed
225 225
226 // The range form: [first, last) of the bundle, with last clamped to its size.
227 {
228 CommandList source, target, other;
229 CHECK(source.copy_resource({1, 2}) && source.copy_resource({3, 4}) && source.copy_resource({5, 6}));
230 CHECK(source.close());
231 CHECK(target.execute_bundle(source, 1, 2)); // the middle command only
232 CHECK(target.commands().size() == 1 && std::get<CopyResource>(target.commands()[0]).src == 4);
233 CHECK(target.execute_bundle(source, 2, 100)); // last beyond the size is clamped
234 CHECK(target.commands().size() == 2 && std::get<CopyResource>(target.commands()[1]).src == 6);
235 CHECK(target.execute_bundle(source, 1, 1) && target.commands().size() == 2); // first == last: nothing
236 CHECK(target.execute_bundle(source, 3, 3) && target.execute_bundle(source, 7, 9)); // first beyond the size
237 CHECK(target.execute_bundle(source, 2, 1) && target.commands().size() == 2); // first after last: nothing
238 CHECK(target.commands().size() == 2);
239 CHECK(other.execute_bundle(source)); // the default arguments copy all of it, as before
240 CHECK(other.commands().size() == 3 && std::get<CopyResource>(other.commands()[0]).src == 2 &&
241 std::get<CopyResource>(other.commands()[2]).src == 6);
242 }
243
226 CommandList open_parent, open_bundle; 244 CommandList open_parent, open_bundle;
227 CHECK(!open_parent.execute_bundle(open_bundle)); // bundle must be closed 245 CHECK(!open_parent.execute_bundle(open_bundle)); // bundle must be closed
228 CHECK(!open_parent.execute_bundle(open_parent)); // a list cannot execute itself 246 CHECK(!open_parent.execute_bundle(open_parent)); // a list cannot execute itself
diff --git a/runtime/test/d3d12_bundle_test.cpp b/runtime/test/d3d12_bundle_test.cpp
new file mode 100644
index 000000000..fd14dc29b
--- /dev/null
+++ b/runtime/test/d3d12_bundle_test.cpp
@@ -0,0 +1,840 @@
1// ExecuteBundle: what a bundle's draws inherit from the list that executes it, and what the bundle hands back.
2// The same scenarios run on the layer (a Vulkan device, shaders written to the translator's contract, the ones
3// d3d12_draw_test uses) and on Windows' own D3D12 (HLSL from D3DCompile, the default adapter and WARP), and each
4// is read back as an 8x8 grid of letters: B blue (the clear), R, G, Y the draw's colour, C a green-only write over
5// the clear, K black. The expected grids are what the host produced when they were measured (docs/d3d12_vulkan.md
6// section 3.2); the default adapter and WARP gave the same grid in every scenario, so the layer is held to the PC
7// runtime's behaviour and each host is checked against the table too.
8// Only valid bundle usage is run: a bundle never calls RSSetViewports, RSSetScissorRects, OMSetRenderTargets or any
9// barrier, clear or copy, sets its root signature before any root argument and sets its topology before a draw
10// (the default adapter inherits the parent's topology when it does not, WARP removes the device, so that is not
11// asserted). The layer alone is also checked for the order of a bundle's commands in its parent, for the trace
12// (one line per call the application made, however often the bundle runs) and for object lifetimes.
13// Both host adapters always run (LEONIDA_HOST_ADAPTER is not read), except under Wine, where the host is skipped.
14// No game data.
15#include "vk_test_device.h"
16#include "d3d12_test_shaders.h"
17#include "host_wine.h"
18#include "../shims/d3d12_com.h"
19#include "../shims/d3d12_trace.h"
20#include "../src/shader_library.h"
21
22#include <d3dcompiler.h>
23#include <dxgi1_4.h>
24#include <io.h>
25
26#include <cstdint>
27#include <cstdio>
28#include <cstring>
29#include <filesystem>
30#include <fstream>
31#include <functional>
32#include <iterator>
33#include <string>
34#include <variant>
35#include <vector>
36
37#if !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_PS_SPV)
38#error "LEONIDA_TEST_VS_SPV and LEONIDA_TEST_PS_SPV must name the compiled test shaders"
39#endif
40
41#define CHECK(condition) do { \
42 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \
43} while (0)
44
45#define REQUIRE(condition) do { \
46 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
47} while (0)
48
49using namespace d3d12test;
50
51namespace {
52
53constexpr UINT target_px = 64;
54constexpr UINT grid_cells = 8;
55
56struct Vertex {
57 float x, y;
58 std::uint8_t r, g, b, a;
59};
60
61// Upload-heap layout, in bytes.
62constexpr UINT64 vb_quad = 0; // the top-left quadrant as a strip: (-1,1) (0,1) (-1,0) (0,0)
63constexpr UINT64 vb_other = 64; // the same shape in the bottom-right quadrant
64constexpr UINT64 ib_quad = 128; // 0 1 2 2 1 3: both triangles of the quad
65constexpr UINT64 ib_half = 144; // 3 2 1: the lower-right half
66constexpr UINT64 tint_red = 256; // (1, 0, 1): the red vertices stay red
67constexpr UINT64 tint_green = 512; // (0, 1, 0)
68constexpr UINT64 tint_yellow = 768; // (1, 1, 1)
69
70// An expected grid: eight rows of eight letters, rows separated by a space.
71#define BLANK4 "BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
72#define ROWS4(row) row " " row " " row " " row
73
74using Recorder = std::function<void(struct Rig&, ID3D12GraphicsCommandList*)>;
75
76struct Rig {
77 ID3D12Device* device = nullptr;
78 Ref<ID3D12RootSignature> root1, root2; // root2 adds a third parameter, so it is a different signature
79 Ref<ID3D12PipelineState> pso_a, pso_b, pso_a2; // b writes only green and alpha; a2 is a on root2
80 Ref<ID3D12CommandQueue> queue;
81 Ref<ID3D12Fence> fence;
82 Ref<ID3D12Resource> upload, target, readback;
83 Ref<ID3D12DescriptorHeap> rtv_heap;
84 D3D12_CPU_DESCRIPTOR_HANDLE rtv{};
85 D3D12_GPU_VIRTUAL_ADDRESS upload_va = 0;
86 UINT64 fence_value = 0;
87 bool bundle_failed = false;
88 std::vector<Ref<ID3D12CommandAllocator>> bundle_allocators;
89 std::vector<Ref<ID3D12GraphicsCommandList>> bundles;
90
91 std::vector<std::uint8_t> vs_code, ps_code;
92
93 // A root signature of two parameters (constants s0 s1, a CBV) or three (and one more constant).
94 bool make_root(UINT count, Ref<ID3D12RootSignature>& root) {
95 D3D12_ROOT_PARAMETER params[3] = {};
96 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
97 params[0].Constants = {0, 0, 2};
98 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
99 params[1].Descriptor = {1, 0};
100 params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
101 params[2].Constants = {2, 0, 1};
102 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
103 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
104 root_desc.Desc_1_0 = {count, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT};
105 const auto blob = serialize_root_signature(root_desc);
106 CHECK(!blob.empty());
107 CHECK(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p))));
108 return true;
109 }
110
111 bool make_pso(ID3D12RootSignature* root, UINT8 write_mask, Ref<ID3D12PipelineState>& pso) {
112 static const D3D12_INPUT_ELEMENT_DESC elements[2] = {
113 {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
114 {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT,
115 D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
116 D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{};
117 desc.pRootSignature = root;
118 desc.VS = {vs_code.data(), vs_code.size()};
119 desc.PS = {ps_code.data(), ps_code.size()};
120 desc.BlendState.RenderTarget[0].RenderTargetWriteMask = write_mask;
121 desc.SampleMask = 0xffffffff;
122 desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
123 desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
124 desc.RasterizerState.DepthClipEnable = TRUE;
125 desc.InputLayout = {elements, 2};
126 desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
127 desc.NumRenderTargets = 1;
128 desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
129 desc.SampleDesc.Count = 1;
130 CHECK(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p))));
131 return true;
132 }
133
134 bool init(ID3D12Device* d, const std::vector<std::uint8_t>& vs, const std::vector<std::uint8_t>& ps) {
135 device = d;
136 vs_code = vs;
137 ps_code = ps;
138 CHECK(make_root(2, root1) && make_root(3, root2));
139 constexpr UINT8 all = D3D12_COLOR_WRITE_ENABLE_ALL;
140 CHECK(make_pso(root1.p, all, pso_a));
141 CHECK(make_pso(root1.p, D3D12_COLOR_WRITE_ENABLE_GREEN | D3D12_COLOR_WRITE_ENABLE_ALPHA, pso_b));
142 CHECK(make_pso(root2.p, all, pso_a2));
143
144 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
145 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
146 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
147 auto buffer = buffer_desc(4096);
148 CHECK(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer,
149 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
150 IID_PPV_ARGS(&upload.p))));
151 buffer = buffer_desc(target_px * 256);
152 CHECK(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer,
153 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
154 IID_PPV_ARGS(&readback.p))));
155 D3D12_RESOURCE_DESC texture{};
156 texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
157 texture.Width = texture.Height = target_px;
158 texture.DepthOrArraySize = texture.MipLevels = 1;
159 texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
160 texture.SampleDesc.Count = 1;
161 texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
162 CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture,
163 D3D12_RESOURCE_STATE_COMMON, nullptr,
164 IID_PPV_ARGS(&target.p))));
165 const Vertex quad[4] = {{-1, 1, 255, 0, 0, 255}, {0, 1, 255, 0, 0, 255}, {-1, 0, 255, 0, 0, 255},
166 {0, 0, 255, 0, 0, 255}};
167 const Vertex other[4] = {{0, 0, 255, 0, 0, 255}, {1, 0, 255, 0, 0, 255}, {0, -1, 255, 0, 0, 255},
168 {1, -1, 255, 0, 0, 255}};
169 const std::uint16_t indices[6] = {0, 1, 2, 2, 1, 3};
170 const float tints[3][3] = {{1, 0, 1}, {0, 1, 0}, {1, 1, 1}};
171 std::uint8_t* up = nullptr;
172 CHECK(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&up))));
173 std::memset(up, 0, 4096);
174 std::memcpy(up + vb_quad, quad, sizeof(quad));
175 std::memcpy(up + vb_other, other, sizeof(other));
176 std::memcpy(up + ib_quad, indices, sizeof(indices));
177 const std::uint16_t half[3] = {3, 2, 1};
178 std::memcpy(up + ib_half, half, sizeof(half));
179 std::memcpy(up + tint_red, tints[0], sizeof(tints[0]));
180 std::memcpy(up + tint_green, tints[1], sizeof(tints[1]));
181 std::memcpy(up + tint_yellow, tints[2], sizeof(tints[2]));
182 upload->Unmap(0, nullptr);
183 upload_va = upload->GetGPUVirtualAddress();
184
185 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
186 CHECK(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p))));
187 rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart();
188 device->CreateRenderTargetView(target.p, nullptr, rtv);
189 D3D12_COMMAND_QUEUE_DESC queue_desc{};
190 CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
191 CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
192 return true;
193 }
194
195 // A closed bundle created with `initial` as its pipeline state, kept alive until the rig goes.
196 template<class F>
197 ID3D12GraphicsCommandList* bundle(ID3D12PipelineState* initial, F&& record) {
198 bundle_allocators.emplace_back();
199 bundles.emplace_back();
200 if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE,
201 IID_PPV_ARGS(&bundle_allocators.back().p))) ||
202 FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_allocators.back().p, initial,
203 IID_PPV_ARGS(&bundles.back().p))))
204 return nullptr;
205 record(bundles.back().p);
206 if (FAILED(bundles.back()->Close())) return nullptr;
207 return bundles.back().p;
208 }
209
210 // ExecuteBundle, unless the bundle's Close failed (reported in the output, the layer refuses such bundles).
211 void execute(ID3D12GraphicsCommandList* list, ID3D12GraphicsCommandList* b) {
212 if (b)
213 list->ExecuteBundle(b);
214 else
215 bundle_failed = true;
216 }
217
218 // The parent's own targets, viewport and scissor: a bundle may not set them.
219 void targets(ID3D12GraphicsCommandList* list, float x = 0, float y = 0, float w = target_px, float h = target_px) {
220 const D3D12_VIEWPORT viewport{x, y, w, h, 0, 1};
221 const D3D12_RECT scissor{0, 0, LONG(target_px), LONG(target_px)};
222 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
223 list->RSSetViewports(1, &viewport);
224 list->RSSetScissorRects(1, &scissor);
225 }
226 void vertices(ID3D12GraphicsCommandList* list, UINT64 offset) {
227 const D3D12_VERTEX_BUFFER_VIEW view{upload_va + offset, 4 * sizeof(Vertex), sizeof(Vertex)};
228 list->IASetVertexBuffers(0, 1, &view);
229 }
230 void indices(ID3D12GraphicsCommandList* list, UINT64 offset) {
231 const D3D12_INDEX_BUFFER_VIEW view{upload_va + offset, 12, DXGI_FORMAT_R16_UINT};
232 list->IASetIndexBuffer(&view);
233 }
234 void offset(ID3D12GraphicsCommandList* list, float x, float y) {
235 const float xy[2] = {x, y};
236 list->SetGraphicsRoot32BitConstants(0, 2, xy, 0);
237 }
238 void tint(ID3D12GraphicsCommandList* list, UINT64 which) {
239 list->SetGraphicsRootConstantBufferView(1, upload_va + which);
240 }
241
242 // Clears the target blue, runs `record` on the parent list and reads the target back as letters.
243 bool render(const Recorder& record, std::string& out, HRESULT& close) {
244 Ref<ID3D12CommandAllocator> allocator;
245 Ref<ID3D12GraphicsCommandList> list;
246 CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
247 CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
248 IID_PPV_ARGS(&list.p))));
249 D3D12_RESOURCE_BARRIER to_target = transition(target.p, D3D12_RESOURCE_STATE_COMMON,
250 D3D12_RESOURCE_STATE_RENDER_TARGET);
251 list->ResourceBarrier(1, &to_target);
252 const FLOAT blue[4] = {0, 0, 1, 1};
253 list->ClearRenderTargetView(rtv, blue, 0, nullptr);
254 record(*this, list.p);
255 D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET,
256 D3D12_RESOURCE_STATE_COPY_SOURCE);
257 list->ResourceBarrier(1, &to_copy);
258 D3D12_TEXTURE_COPY_LOCATION dst{}, src{};
259 dst.pResource = readback.p;
260 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
261 dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, target_px, target_px, 1, 256}};
262 src.pResource = target.p;
263 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
264 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
265 close = list->Close();
266 if (FAILED(close)) return true; // reported by the caller
267 ID3D12CommandList* lists[] = {list.p};
268 queue->ExecuteCommandLists(1, lists);
269 CHECK(SUCCEEDED(queue->Signal(fence.p, ++fence_value)));
270 CHECK(SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr)));
271 const std::uint8_t* pixels = nullptr;
272 const HRESULT mapped = readback->Map(0, nullptr, const_cast<void**>(reinterpret_cast<const void* const*>(&pixels)));
273 if (FAILED(mapped)) {
274 char text[96];
275 std::snprintf(text, sizeof(text), "Map 0x%08lx, device removed 0x%08lx\n", static_cast<unsigned long>(mapped),
276 static_cast<unsigned long>(device->GetDeviceRemovedReason()));
277 out = text;
278 return true;
279 }
280 out = bundle_failed ? "bundle Close failed " : "";
281 for (UINT row = 0; row < grid_cells; ++row) {
282 for (UINT column = 0; column < grid_cells; ++column) {
283 // Away from pixel centres on the quadrant diagonal (x + y = 32).
284 const std::uint8_t* p = pixels + (row * 8 + 3) * 256 + (column * 8 + 3) * 4;
285 char letter = '?';
286 if (p[3] == 255) {
287 if (p[0] == 0 && p[1] == 0 && p[2] == 255) letter = 'B';
288 else if (p[0] == 255 && p[1] == 0 && p[2] == 0) letter = 'R';
289 else if (p[0] == 0 && p[1] == 255 && p[2] == 0) letter = 'G';
290 else if (p[0] == 255 && p[1] == 255 && p[2] == 0) letter = 'Y';
291 else if (p[0] == 0 && p[1] == 255 && p[2] == 255) letter = 'C';
292 else if (p[0] == 0 && p[1] == 0 && p[2] == 0) letter = 'K';
293 }
294 out += letter;
295 }
296 if (row + 1 < grid_cells) out += ' ';
297 }
298 readback->Unmap(0, nullptr);
299 return true;
300 }
301};
302
303struct Scenario {
304 const char* name;
305 Recorder record;
306 const char* expected; // null: print only
307};
308
309constexpr auto strip = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
310constexpr auto tlist = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
311
312std::vector<Scenario> scenarios() {
313 std::vector<Scenario> s;
314 // The parent's state a bundle must see: targets, viewport and scissor, root signature and arguments, a vertex
315 // buffer and a topology. No pipeline state is set: a bundle starts with its creation one.
316 const auto parent_state = [](Rig& r, ID3D12GraphicsCommandList* l, D3D_PRIMITIVE_TOPOLOGY topology) {
317 r.targets(l);
318 l->SetGraphicsRootSignature(r.root1.p);
319 l->IASetPrimitiveTopology(topology);
320 r.vertices(l, vb_quad);
321 r.offset(l, 0, 0);
322 r.tint(l, tint_red);
323 };
324 s.push_back({"inherit: a draw sees the parent's targets, viewport, root arguments and vertex buffer",
325 [parent_state](Rig& r, ID3D12GraphicsCommandList* l) {
326 auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) {
327 b->IASetPrimitiveTopology(strip);
328 b->DrawInstanced(4, 1, 0, 0);
329 });
330 parent_state(r, l, tlist);
331 r.execute(l, b);
332 }, ROWS4("RRRRBBBB") " " BLANK4});
333 s.push_back({"inherit: an indexed draw sees the parent's index buffer",
334 [parent_state](Rig& r, ID3D12GraphicsCommandList* l) {
335 auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) {
336 b->IASetPrimitiveTopology(tlist);
337 b->DrawIndexedInstanced(6, 1, 0, 0, 0);
338 });
339 parent_state(r, l, strip);
340 r.indices(l, ib_quad);
341 r.execute(l, b);
342 }, ROWS4("RRRRBBBB") " " BLANK4});
343 s.push_back({"inherit: a bundle that sets the same root signature keeps the parent's root arguments",
344 [parent_state](Rig& r, ID3D12GraphicsCommandList* l) {
345 auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) {
346 b->SetGraphicsRootSignature(r.root1.p);
347 b->IASetPrimitiveTopology(strip);
348 b->DrawInstanced(4, 1, 0, 0);
349 });
350 parent_state(r, l, tlist);
351 r.offset(l, 1, -1);
352 r.tint(l, tint_green);
353 r.execute(l, b);
354 }, BLANK4 " " ROWS4("BBBBGGGG")});
355 s.push_back({"inherit: one bundle, executed twice with other root arguments and viewports in between",
356 [](Rig& r, ID3D12GraphicsCommandList* l) {
357 auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) {
358 b->IASetPrimitiveTopology(strip);
359 b->DrawInstanced(4, 1, 0, 0);
360 });
361 l->SetGraphicsRootSignature(r.root1.p);
362 r.vertices(l, vb_quad);
363 r.offset(l, 0, 0);
364 r.targets(l, 0, 0, target_px / 2, target_px);
365 r.tint(l, tint_red);
366 r.execute(l, b);
367 r.targets(l, target_px / 2, 0, target_px / 2, target_px);
368 r.tint(l, tint_green);
369 r.execute(l, b);
370 }, ROWS4("RRBBGGBB") " " BLANK4});
371 s.push_back({"pipeline state: a bundle starts with its creation one, not the parent's, and hands it back",
372 [parent_state](Rig& r, ID3D12GraphicsCommandList* l) {
373 auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) {
374 b->IASetPrimitiveTopology(strip);
375 b->DrawInstanced(4, 1, 0, 0);
376 });
377 parent_state(r, l, tlist);
378 l->SetPipelineState(r.pso_b.p);
379 r.tint(l, tint_green);
380 r.execute(l, b);
381 r.offset(l, 1, -1);
382 l->DrawInstanced(4, 1, 0, 0);
383 }, ROWS4("GGGGBBBB") " " ROWS4("BBBBGGGG")});
384 s.push_back({"hand back: a pipeline state the bundle sets",
385 [parent_state](Rig& r, ID3D12GraphicsCommandList* l) {
386 auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) {
387 b->SetPipelineState(r.pso_b.p);
388 b->IASetPrimitiveTopology(strip);
389 });
390 parent_state(r, l, tlist);
391 l->SetPipelineState(r.pso_a.p);
392 r.tint(l, tint_green);
393 r.execute(l, b);
394 l->DrawInstanced(4, 1, 0, 0);
395 }, ROWS4("CCCCBBBB") " " BLANK4});
396 s.push_back({"hand back: topology",
397 [parent_state](Rig& r, ID3D12GraphicsCommandList* l) {
398 auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) { b->IASetPrimitiveTopology(strip); });
399 parent_state(r, l, tlist);
400 r.execute(l, b);
401 l->DrawInstanced(4, 1, 0, 0);
402 }, ROWS4("RRRRBBBB") " " BLANK4});
403 s.push_back({"hand back: root constants and a root CBV, after the same root signature",
404 [parent_state](Rig& r, ID3D12GraphicsCommandList* l) {
405 auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) {
406 b->SetGraphicsRootSignature(r.root1.p);
407 b->IASetPrimitiveTopology(strip);
408 r.offset(b, 1, -1);
409 r.tint(b, tint_green);
410 });
411 parent_state(r, l, tlist);
412 r.execute(l, b);
413 l->DrawInstanced(4, 1, 0, 0);
414 }, BLANK4 " " ROWS4("BBBBGGGG")});
415 s.push_back({"hand back: vertex and index buffers",
416 [parent_state](Rig& r, ID3D12GraphicsCommandList* l) {
417 auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) {
418 b->IASetPrimitiveTopology(tlist);
419 r.vertices(b, vb_other);
420 r.indices(b, ib_half);
421 });
422 parent_state(r, l, strip);
423 r.indices(l, ib_quad);
424 r.execute(l, b);
425 l->DrawIndexedInstanced(3, 1, 0, 0, 0);
426 }, BLANK4 " BBBBBBBB BBBBBBBR BBBBBBRR BBBBBRRR"});
427 // A different root signature: the bundle (created with pso_a2, on root2) sets it and its own arguments. The
428 // parent's arguments are gone afterwards and the bundle's are the parent's.
429 s.push_back({"root signature: a bundle sets another one; the parent continues with it and the bundle's arguments",
430 [parent_state](Rig& r, ID3D12GraphicsCommandList* l) {
431 auto* b = r.bundle(r.pso_a2.p, [&](ID3D12GraphicsCommandList* b) {
432 b->SetGraphicsRootSignature(r.root2.p);
433 b->IASetPrimitiveTopology(strip);
434 r.offset(b, 0, 0);
435 r.tint(b, tint_yellow);
436 const UINT extra = 0;
437 b->SetGraphicsRoot32BitConstants(2, 1, &extra, 0);
438 b->DrawInstanced(4, 1, 0, 0);
439 });
440 parent_state(r, l, tlist);
441 r.offset(l, 1, -1);
442 r.tint(l, tint_green);
443 r.execute(l, b);
444 r.vertices(l, vb_other);
445 l->DrawInstanced(4, 1, 0, 0);
446 }, ROWS4("YYYYBBBB") " " ROWS4("BBBBYYYY")});
447 return s;
448}
449
450} // namespace
451
452namespace {
453
454bool compile_hlsl(const char* source, const char* entry, const char* profile, std::vector<std::uint8_t>& out) {
455 const HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
456 const auto compile = compiler ? reinterpret_cast<pD3DCompile>(GetProcAddress(compiler, "D3DCompile")) : nullptr;
457 if (!compile) return false;
458 ID3DBlob* blob = nullptr;
459 ID3DBlob* errors = nullptr;
460 const HRESULT hr = compile(source, std::strlen(source), "bundle.hlsl", nullptr, nullptr, entry, profile, 0, 0,
461 &blob, &errors);
462 if (FAILED(hr) && errors) std::fprintf(stderr, "%s\n", static_cast<const char*>(errors->GetBufferPointer()));
463 if (errors) errors->Release();
464 if (FAILED(hr) || !blob) return false;
465 const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
466 out.assign(p, p + blob->GetBufferSize());
467 blob->Release();
468 return true;
469}
470
471// The same two shaders as test/glsl/vs_draw.vert and ps_draw.frag: s0, s1 offset the vertex, the root CBV tints.
472constexpr char hlsl[] =
473 "cbuffer Offset : register(b0) { float2 offset; };\n"
474 "cbuffer Tint : register(b1) { float3 tint; };\n"
475 "struct V { float4 position : SV_Position; float4 color : COLOR; };\n"
476 "V vs(float2 position : POSITION, float4 color : COLOR) {\n"
477 " V v; v.position = float4(position + offset, 0, 1); v.color = color; return v; }\n"
478 "float4 ps(V v) : SV_Target { return float4(v.color.r * tint.x, tint.y, v.color.b * tint.z, 1); }\n";
479
480// Runs every scenario and stores the grids; false on a harness failure. A host scenario gets a device of its own
481// (`adapter`, null for the default one): a scenario that removes a host device must not hide the ones after it.
482bool run_all(ID3D12Device* shared, bool own_device, IDXGIAdapter* adapter, const std::vector<std::uint8_t>& vs, const std::vector<std::uint8_t>& ps,
483 const std::vector<Scenario>& list, std::vector<std::string>& grids, std::vector<HRESULT>& closes) {
484 for (const Scenario& scenario : list) {
485 Rig rig;
486 Ref<ID3D12Device> own;
487 if (own_device) D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&own.p));
488 ID3D12Device* device = own_device ? own.p : shared;
489 if (!device || !rig.init(device, vs, ps)) {
490 grids.push_back("device unusable\n");
491 closes.push_back(E_FAIL);
492 continue;
493 }
494 std::string grid_text;
495 HRESULT close = S_OK;
496 if (!rig.render(scenario.record, grid_text, close)) return false;
497 grids.push_back(grid_text);
498 closes.push_back(close);
499 }
500 return true;
501}
502
503} // namespace
504
505// What the layer alone can show: the order of commands in the parent, the trace, and object lifetimes.
506int count_of(const std::string& text, const char* needle) {
507 int count = 0;
508 for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++count;
509 return count;
510}
511
512// Sends stderr (where the trace goes) to a file while it lives, with the trace on.
513struct TraceCapture {
514 std::filesystem::path path;
515 int saved = -1;
516 explicit TraceCapture(const std::filesystem::path& file) : path(file) {
517 std::fflush(stderr);
518 std::FILE* out = std::fopen(path.string().c_str(), "wb");
519 saved = _dup(2);
520 if (out && saved >= 0) _dup2(_fileno(out), 2);
521 if (out) std::fclose(out);
522 rt::d3d12_trace::set_enabled(true);
523 }
524 std::string finish() {
525 rt::d3d12_trace::set_enabled(false);
526 std::fflush(stderr);
527 if (saved >= 0) {
528 _dup2(saved, 2);
529 _close(saved);
530 saved = -1;
531 }
532 std::ifstream in(path, std::ios::binary);
533 return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
534 }
535 ~TraceCapture() { finish(); }
536};
537
538bool layer_checks(ID3D12Device* device, const std::vector<std::uint8_t>& vs, const std::vector<std::uint8_t>& ps,
539 const std::filesystem::path& scratch) {
540 constexpr UINT8 all = D3D12_COLOR_WRITE_ENABLE_ALL;
541 // The parent's commands hold the bundle's markers and draws where the bundle made them, between the parent's own.
542 {
543 Rig r;
544 CHECK(r.init(device, vs, ps));
545 const auto mark = [](ID3D12GraphicsCommandList* l, const char* text) {
546 l->SetMarker(1, text, UINT(std::strlen(text) + 1));
547 };
548 auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) {
549 mark(b, "b1");
550 b->IASetPrimitiveTopology(strip);
551 b->DrawInstanced(4, 1, 0, 0);
552 mark(b, "b2");
553 b->DrawInstanced(4, 1, 0, 0);
554 mark(b, "b3");
555 });
556 CHECK(b);
557 Ref<ID3D12CommandAllocator> allocator;
558 Ref<ID3D12GraphicsCommandList> parent;
559 CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
560 CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
561 IID_PPV_ARGS(&parent.p))));
562 mark(parent.p, "p0");
563 r.targets(parent.p);
564 parent.p->SetGraphicsRootSignature(r.root1.p);
565 r.vertices(parent.p, vb_quad);
566 r.offset(parent.p, 0, 0);
567 r.tint(parent.p, tint_red);
568 mark(parent.p, "p1");
569 parent.p->ExecuteBundle(b);
570 mark(parent.p, "p2");
571 std::string order;
572 std::vector<leonida::Command> recorded;
573 CHECK(rt::d3d12::recorded_commands(parent.p, recorded));
574 for (const auto& command : recorded) {
575 if (const auto* marker = std::get_if<leonida::DebugMarker>(&command)) order += marker->label + ",";
576 else if (std::holds_alternative<leonida::Draw>(command)) order += "draw,";
577 }
578 if (order != "p0,p1,b1,draw,b2,draw,b3,p2,") {
579 std::fprintf(stderr, "bundle commands in the parent: %s\n", order.c_str());
580 return false;
581 }
582 CHECK(parent->Close() == S_OK);
583 }
584
585 // The trace has one line per call the application made on the bundle, however often it is executed, and none for
586 // the pipeline state it was created or reset with.
587 {
588 Rig r;
589 CHECK(r.init(device, vs, ps));
590 TraceCapture capture(scratch / "trace.txt");
591 auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) {
592 b->SetGraphicsRootSignature(r.root1.p);
593 b->IASetPrimitiveTopology(strip);
594 b->DrawInstanced(4, 1, 0, 0);
595 });
596 CHECK(b);
597 std::string grid_text;
598 HRESULT close = S_OK;
599 CHECK(r.render([&](Rig& rig, ID3D12GraphicsCommandList* l) {
600 rig.targets(l);
601 rig.vertices(l, vb_quad);
602 for (int i = 0; i < 3; ++i) rig.execute(l, b);
603 }, grid_text, close));
604 CHECK(close == S_OK);
605 CHECK(SUCCEEDED(b->Reset(r.bundle_allocators.back().p, r.pso_a.p)));
606 b->SetGraphicsRootSignature(r.root1.p);
607 r.offset(b, 0, 0);
608 r.tint(b, tint_red);
609 b->IASetPrimitiveTopology(tlist);
610 b->DrawIndexedInstanced(6, 1, 0, 0, 0);
611 CHECK(SUCCEEDED(b->Close()));
612 CHECK(r.render([&](Rig& rig, ID3D12GraphicsCommandList* l) {
613 rig.targets(l);
614 rig.vertices(l, vb_quad);
615 rig.indices(l, ib_quad);
616 rig.execute(l, b);
617 rig.execute(l, b);
618 }, grid_text, close));
619 CHECK(close == S_OK && grid_text == ROWS4("RRRRBBBB") " " BLANK4);
620 const std::string trace = capture.finish();
621 const int pipeline = count_of(trace, "GraphicsCommandList::SetPipelineState called");
622 const int root = count_of(trace, "GraphicsCommandList::SetGraphicsRootSignature called");
623 const int draw = count_of(trace, "GraphicsCommandList::DrawInstanced called");
624 const int indexed = count_of(trace, "GraphicsCommandList::DrawIndexedInstanced called");
625 const int execute = count_of(trace, "GraphicsCommandList::ExecuteBundle called");
626 if (pipeline != 0 || root != 2 || draw != 1 || indexed != 1 || execute != 5) {
627 std::fprintf(stderr, "trace lines: SetPipelineState %d, root signature %d, draw %d, indexed %d, "
628 "ExecuteBundle %d (expected 0, 2, 1, 1, 5)\n", pipeline, root, draw, indexed, execute);
629 return false;
630 }
631 }
632
633 // A root-constant call of zero dwords is as valid in a bundle as on a direct list; a closed bundle takes no more
634 // state calls (they are ignored) and a draw on it makes it invalid, so a parent that executes it fails.
635 {
636 Rig r;
637 CHECK(r.init(device, vs, ps));
638 const UINT none = 0;
639 auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) {
640 b->SetGraphicsRootSignature(r.root1.p);
641 b->SetGraphicsRoot32BitConstants(0, 0, &none, 0);
642 b->IASetPrimitiveTopology(strip);
643 r.offset(b, 0, 0);
644 r.tint(b, tint_red);
645 b->DrawInstanced(4, 1, 0, 0);
646 });
647 CHECK(b);
648 std::string grid_text;
649 HRESULT close = S_OK;
650 const auto run = [&](ID3D12GraphicsCommandList* bundle) {
651 return r.render([&](Rig& rig, ID3D12GraphicsCommandList* l) {
652 rig.targets(l);
653 rig.vertices(l, vb_quad);
654 rig.execute(l, bundle);
655 }, grid_text, close);
656 };
657 CHECK(run(b));
658 CHECK(close == S_OK && grid_text == ROWS4("RRRRBBBB") " " BLANK4);
659 b->IASetPrimitiveTopology(tlist); // closed: ignored, so the bundle still draws the whole quad
660 CHECK(run(b));
661 CHECK(close == S_OK && grid_text == ROWS4("RRRRBBBB") " " BLANK4);
662 b->DrawInstanced(4, 1, 0, 0); // closed: invalid
663 CHECK(run(b));
664 CHECK(close == E_INVALIDARG);
665 }
666
667 // The application may release the pipeline state and root signature as soon as it has recorded them, and the
668 // bundle itself while a list that executed it is still open.
669 {
670 Rig r;
671 CHECK(r.init(device, vs, ps));
672 ID3D12GraphicsCommandList* b = nullptr;
673 {
674 Ref<ID3D12RootSignature> root;
675 Ref<ID3D12PipelineState> pso;
676 CHECK(r.make_root(2, root) && r.make_pso(root.p, all, pso));
677 b = r.bundle(pso.p, [&](ID3D12GraphicsCommandList* b) {
678 b->SetGraphicsRootSignature(root.p);
679 b->IASetPrimitiveTopology(strip);
680 r.offset(b, 0, 0);
681 r.tint(b, tint_red);
682 b->DrawInstanced(4, 1, 0, 0);
683 });
684 }
685 CHECK(b);
686 std::string grid_text;
687 HRESULT close = S_OK;
688 bool reset_ok = false;
689 CHECK(r.render([&](Rig& rig, ID3D12GraphicsCommandList* l) {
690 rig.targets(l);
691 rig.vertices(l, vb_quad);
692 rig.execute(l, b);
693 }, grid_text, close));
694 if (close != S_OK || grid_text != ROWS4("RRRRBBBB") " " BLANK4) {
695 std::fprintf(stderr, "first parent of a released bundle: Close 0x%08lx, %s\n",
696 static_cast<unsigned long>(close), grid_text.c_str());
697 return false;
698 }
699 CHECK(r.render([&](Rig& rig, ID3D12GraphicsCommandList* l) {
700 rig.targets(l);
701 rig.vertices(l, vb_quad);
702 rig.execute(l, b);
703 reset_ok = SUCCEEDED(rig.bundles.back()->Reset(rig.bundle_allocators.back().p, nullptr));
704 rig.bundles.clear();
705 rig.bundle_allocators.clear();
706 rig.offset(l, 1, -1); // the bundle's root signature and pipeline state are the parent's now
707 l->DrawInstanced(4, 1, 0, 0);
708 }, grid_text, close));
709 if (!reset_ok || close != S_OK || grid_text != ROWS4("RRRRBBBB") " " ROWS4("BBBBRRRR")) {
710 std::fprintf(stderr, "second parent, bundle released while open: Close 0x%08lx, %s\n",
711 static_cast<unsigned long>(close), grid_text.c_str());
712 return false;
713 }
714 }
715 return true;
716}
717
718int main() {
719 std::setvbuf(stdout, nullptr, _IONBF, 0);
720 vktest::Device vk;
721 const auto device_status = vk.initialize();
722 if (device_status == vktest::DeviceStatus::unavailable) {
723 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
724 return 77;
725 }
726 REQUIRE(device_status == vktest::DeviceStatus::ready);
727 const auto list = scenarios();
728
729 // Layer shaders: FSSM-shaped containers found by hash in a translator-style index.
730 const auto vs_program = fssm_program({0x56530101, 0xbf810000});
731 const auto ps_program = fssm_program({0x50530101, 0xbf810000});
732 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program);
733 // Removed on every way out of main.
734 struct Scratch {
735 std::filesystem::path path = std::filesystem::temp_directory_path() / "leonida_bundle_test";
736 Scratch() { std::filesystem::create_directories(path); }
737 ~Scratch() {
738 std::error_code ignored;
739 std::filesystem::remove_all(path, ignored);
740 }
741 } scratch;
742 const auto& library = scratch.path;
743 std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing);
744 std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing);
745 {
746 std::ofstream index(library / "index.json", std::ios::binary);
747 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
748 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": ["
749 "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 0, \"mask\": 15, \"rw_mask\": 15, "
750 "\"system_value\": 0, \"component_type\": \"float\"}, "
751 "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 1, \"mask\": 3, \"rw_mask\": 3, "
752 "\"system_value\": 0, \"component_type\": \"float\"}]},\n"
753 " \"ps_draw\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_program)
754 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]}}";
755 }
756 const unsigned errors_before = vk.validation_errors();
757 std::vector<std::string> layer_grids;
758 std::vector<HRESULT> layer_closes;
759 {
760 rt::d3d12::VulkanDeviceInfo info{};
761 info.get_instance_proc = vk.instance_proc;
762 info.instance = vk.instance;
763 info.physical = vk.physical;
764 info.device = vk.device;
765 info.queue = vk.queue;
766 info.queue_family = vk.family;
767 info.buffer_device_address = true;
768 info.shader_dir = library.string();
769 Ref<ID3D12Device> ours;
770 REQUIRE(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p))));
771 REQUIRE(run_all(ours.p, false, nullptr, vs_container, ps_container, list, layer_grids, layer_closes));
772 REQUIRE(layer_checks(ours.p, vs_container, ps_container, library));
773 }
774
775 // The host: Windows' D3D12 on the default adapter and on WARP.
776 std::vector<std::uint8_t> host_vs, host_ps;
777 const bool wine = hostwine::host_is_wine();
778 const bool host_shaders = !wine && compile_hlsl(hlsl, "vs", "vs_5_0", host_vs) &&
779 compile_hlsl(hlsl, "ps", "ps_5_0", host_ps);
780 struct HostRun {
781 const char* name = "";
782 bool ran = false;
783 std::vector<std::string> grids;
784 std::vector<HRESULT> closes;
785 } hosts[2];
786 hosts[0].name = "the default adapter";
787 hosts[1].name = "WARP";
788 if (host_shaders) {
789 Ref<IDXGIFactory4> factory;
790 REQUIRE(SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))));
791 for (int i = 0; i < 2; ++i) {
792 Ref<IDXGIAdapter> adapter;
793 Ref<ID3D12Device> host;
794 if (i == 1 && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue;
795 if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue;
796 REQUIRE(run_all(nullptr, true, adapter.p, host_vs, host_ps, list, hosts[i].grids, hosts[i].closes));
797 hosts[i].ran = true;
798 }
799 } else if (!wine) {
800 std::fprintf(stderr, "no HLSL compiler: the host is not run\n");
801 }
802
803 // Every grid, the layer's against the table and each host's against it too. A host that is unavailable or
804 // Wine's vkd3d (which answers differently, see host_wine.h) is not compared; the table still holds the layer.
805 unsigned failures = 0, compared = 0;
806 const auto verdict = [&](const char* who, const Scenario& scenario, const std::string& grid, HRESULT close) {
807 const bool ok = grid == scenario.expected && close == S_OK;
808 if (!ok) {
809 std::fprintf(stderr, "FAIL %s on %s: Close 0x%08lx\n got %s\n expected %s\n", scenario.name, who,
810 static_cast<unsigned long>(close), grid.c_str(), scenario.expected);
811 ++failures;
812 }
813 };
814 for (std::size_t i = 0; i < list.size(); ++i) {
815 if (!list[i].expected) {
816 std::printf("%s | layer %s", list[i].name, layer_grids[i].c_str());
817 for (const auto& host : hosts)
818 if (host.ran) std::printf(" | %s %s", host.name, host.grids[i].c_str());
819 std::printf("\n");
820 ++failures;
821 continue;
822 }
823 verdict("the layer", list[i], layer_grids[i], layer_closes[i]);
824 for (const auto& host : hosts) {
825 if (!host.ran) continue;
826 verdict(host.name, list[i], host.grids[i], host.closes[i]);
827 ++compared;
828 }
829 }
830 const unsigned validation_errors = vk.validation_errors() - errors_before;
831 if (validation_errors) {
832 std::fprintf(stderr, "%u Vulkan validation errors\n", validation_errors);
833 ++failures;
834 }
835 if (!hosts[0].ran && !hosts[1].ran && !hostwine::host_is_wine())
836 std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n");
837 std::printf("bundles: %zu scenarios on the layer, %u host comparisons, %u failures\n", list.size(), compared,
838 failures);
839 return failures ? 1 : 0;
840}
diff --git a/runtime/test/d3d12_com_test.cpp b/runtime/test/d3d12_com_test.cpp
index 134617ad2..5f30d83b5 100644
--- a/runtime/test/d3d12_com_test.cpp
+++ b/runtime/test/d3d12_com_test.cpp
@@ -5,6 +5,7 @@
5#include "vk_test_device.h" 5#include "vk_test_device.h"
6#include "../shims/d3d12_com.h" 6#include "../shims/d3d12_com.h"
7#include "../shims/d3d12_trace.h" 7#include "../shims/d3d12_trace.h"
8#include "../src/gfx10_descriptors.h"
8 9
9#include <array> 10#include <array>
10#include <cstdint> 11#include <cstdint>
@@ -97,7 +98,7 @@ int main(int argc, char** argv) {
97 EXPECT(queue->GetDesc().Type == D3D12_COMMAND_LIST_TYPE_DIRECT); 98 EXPECT(queue->GetDesc().Type == D3D12_COMMAND_LIST_TYPE_DIRECT);
98 EXPECT(list->GetType() == D3D12_COMMAND_LIST_TYPE_DIRECT); 99 EXPECT(list->GetType() == D3D12_COMMAND_LIST_TYPE_DIRECT);
99 100
100 // ExecuteBundle: a closed bundle is inlined at the call site, and its recorded sticky state spills back. 101 // ExecuteBundle: a closed bundle's state calls play on the parent, so what the bundle set stays there.
101 Ref<ID3D12GraphicsCommandList8> list8; 102 Ref<ID3D12GraphicsCommandList8> list8;
102 EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list8.p)))); 103 EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list8.p))));
103 list8->OMSetFrontAndBackStencilRef(1, 2); 104 list8->OMSetFrontAndBackStencilRef(1, 2);
@@ -269,6 +270,18 @@ int main(int argc, char** argv) {
269 EXPECT(invalid_bundle_call([&](auto* b) { b->ClearRenderTargetView(rtv_handle, bundle_clear_color, 0, nullptr); })); 270 EXPECT(invalid_bundle_call([&](auto* b) { b->ClearRenderTargetView(rtv_handle, bundle_clear_color, 0, nullptr); }));
270 EXPECT(invalid_bundle_call([&](auto* b) { b->ClearDepthStencilView(dsv_handle, D3D12_CLEAR_FLAG_DEPTH, 271 EXPECT(invalid_bundle_call([&](auto* b) { b->ClearDepthStencilView(dsv_handle, D3D12_CLEAR_FLAG_DEPTH,
271 0.5f, 0, 0, nullptr); })); 272 0.5f, 0, 0, nullptr); }));
273 // A valid texture UAV descriptor, which a direct list would accept: only the bundle refuses the clear.
274 const UINT uav_uint[4] = {};
275 const FLOAT uav_float[4] = {};
276 leonida::gfx10::Image uav_image{};
277 uav_image.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
278 uav_image.width = uav_image.height = 4;
279 const auto uav_words = leonida::gfx10::encode(uav_image);
280 const D3D12_CPU_DESCRIPTOR_HANDLE uav_view{reinterpret_cast<SIZE_T>(uav_words.data())};
281 EXPECT(invalid_bundle_call([&](auto* b) {
282 b->ClearUnorderedAccessViewUint({}, uav_view, rt_resource, uav_uint, 0, nullptr); }));
283 EXPECT(invalid_bundle_call([&](auto* b) {
284 b->ClearUnorderedAccessViewFloat({}, uav_view, rt_resource, uav_float, 0, nullptr); }));
272 EXPECT(invalid_bundle_call([&](auto* b) { b->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); })); 285 EXPECT(invalid_bundle_call([&](auto* b) { b->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); }));
273 // D3D-26: DiscardResource and the atomic copies are not allowed in a bundle; WriteBufferImmediate is 286 // D3D-26: DiscardResource and the atomic copies are not allowed in a bundle; WriteBufferImmediate is
274 // ("Recording command lists and bundles", the bundle restrictions and the API restrictions table). 287 // ("Recording command lists and bundles", the bundle restrictions and the API restrictions table).
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp
index d88560a48..8aa5611f2 100644
--- a/runtime/test/d3d12_compute_test.cpp
+++ b/runtime/test/d3d12_compute_test.cpp
@@ -11,9 +11,12 @@
11#include "vk_test_device.h" 11#include "vk_test_device.h"
12#include "../shims/d3d12_com.h" 12#include "../shims/d3d12_com.h"
13#include "../src/gfx10_descriptors.h" 13#include "../src/gfx10_descriptors.h"
14#include "../src/cached_pso.h"
14#include "../src/shader_library.h" 15#include "../src/shader_library.h"
15#include "../shims/d3d12_xs_device.h" 16#include "../shims/d3d12_xs_device.h"
16 17
18#include <dxgi1_4.h>
19
17#include <cstdint> 20#include <cstdint>
18#include <cstring> 21#include <cstring>
19#include <filesystem> 22#include <filesystem>
@@ -136,6 +139,116 @@ D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATE
136 return barrier; 139 return barrier;
137} 140}
138 141
142// The CachedPSO cases both devices answer, in this order: the same description, another Flags, an equal root
143// signature object, a root signature with other content, a truncated blob, a blob of junk, its first, middle and last
144// byte changed, a pointer with size 0, a null pointer with a size.
145constexpr int cached_case_count = 11;
146
147template<class Device>
148std::vector<HRESULT> cached_pso_cases(Device* device, D3D12_COMPUTE_PIPELINE_STATE_DESC desc,
149 const std::vector<std::uint8_t>& root_blob,
150 const std::vector<std::uint8_t>& other_root_blob) {
151 std::vector<HRESULT> out;
152 auto create = [&](D3D12_COMPUTE_PIPELINE_STATE_DESC d, const void* p, SIZE_T n) {
153 d.CachedPSO = {p, n};
154 ID3D12PipelineState* made = nullptr;
155 HRESULT hr = device->CreateComputePipelineState(&d, IID_PPV_ARGS(&made));
156 if (SUCCEEDED(hr) != (made != nullptr)) hr = E_UNEXPECTED; // a result and its object disagree
157 if (made) made->Release();
158 return hr;
159 };
160 ID3D12PipelineState* pso = nullptr;
161 if (FAILED(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso)))) return out;
162 ID3DBlob* blob = nullptr;
163 const HRESULT got = pso->GetCachedBlob(&blob);
164 const HRESULT got_null = pso->GetCachedBlob(nullptr);
165 pso->Release();
166 if (FAILED(got) || !blob || got_null != S_OK) {
167 if (blob) blob->Release();
168 return out;
169 }
170 const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
171 std::vector<std::uint8_t> bytes(p, p + blob->GetBufferSize());
172 blob->Release();
173 ID3D12RootSignature* same_root = nullptr;
174 ID3D12RootSignature* other_root = nullptr;
175 device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&same_root));
176 device->CreateRootSignature(0, other_root_blob.data(), other_root_blob.size(), IID_PPV_ARGS(&other_root));
177 if (!same_root || !other_root) return out;
178
179 out.push_back(create(desc, bytes.data(), bytes.size()));
180 D3D12_COMPUTE_PIPELINE_STATE_DESC flags = desc;
181 flags.Flags = D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG;
182 out.push_back(create(flags, bytes.data(), bytes.size()));
183 D3D12_COMPUTE_PIPELINE_STATE_DESC same = desc;
184 same.pRootSignature = same_root;
185 out.push_back(create(same, bytes.data(), bytes.size()));
186 D3D12_COMPUTE_PIPELINE_STATE_DESC other = desc;
187 other.pRootSignature = other_root;
188 out.push_back(create(other, bytes.data(), bytes.size()));
189 out.push_back(create(desc, bytes.data(), bytes.size() / 2));
190 const std::vector<std::uint8_t> junk(bytes.size(), 0xab);
191 out.push_back(create(desc, junk.data(), junk.size()));
192 for (const std::size_t at : {std::size_t(0), bytes.size() / 2, bytes.size() - 1}) {
193 bytes[at] ^= 0xff;
194 out.push_back(create(desc, bytes.data(), bytes.size()));
195 bytes[at] ^= 0xff;
196 }
197 out.push_back(create(desc, bytes.data(), 0));
198 out.push_back(create(desc, nullptr, 16));
199 same_root->Release();
200 other_root->Release();
201 return out;
202}
203
204// The same cases on the PC runtime, with an empty compute shader from d3dcompiler_47: the default adapter, then WARP.
205// Empty when the host has no D3D12 device or no compiler (Wine), which the caller reports as a skip.
206std::vector<std::vector<HRESULT>> host_cached_pso_cases(const std::vector<std::uint8_t>& root_blob,
207 const std::vector<std::uint8_t>& other_root_blob) {
208 using CompileFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, LPCSTR, const void*, void*, LPCSTR, LPCSTR, UINT, UINT,
209 ID3DBlob**, ID3DBlob**);
210 using CreateDeviceFn = decltype(&::D3D12CreateDevice);
211 std::vector<std::vector<HRESULT>> out;
212 const HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
213 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
214 const HMODULE dxgi = LoadLibraryExA("dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
215 if (!compiler || !d3d12 || !dxgi) return out;
216 const auto compile = reinterpret_cast<CompileFn>(reinterpret_cast<void*>(GetProcAddress(compiler, "D3DCompile")));
217 const auto create_device =
218 reinterpret_cast<CreateDeviceFn>(reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")));
219 using FactoryFn = HRESULT(WINAPI*)(REFIID, void**);
220 const auto create_factory =
221 reinterpret_cast<FactoryFn>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory1")));
222 if (!compile || !create_device || !create_factory) return out;
223 static const char source[] = "[numthreads(1, 1, 1)] void main() {}";
224 ID3DBlob* shader = nullptr;
225 if (FAILED(compile(source, sizeof(source) - 1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, &shader,
226 nullptr)) || !shader)
227 return out;
228 IDXGIFactory4* factory = nullptr;
229 if (SUCCEEDED(create_factory(IID_PPV_ARGS(&factory)))) {
230 IDXGIAdapter* warp = nullptr;
231 factory->EnumWarpAdapter(IID_PPV_ARGS(&warp));
232 for (IUnknown* adapter : {static_cast<IUnknown*>(nullptr), static_cast<IUnknown*>(warp)}) {
233 ID3D12Device* host = nullptr;
234 if (FAILED(create_device(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host)))) continue;
235 ID3D12RootSignature* root = nullptr;
236 if (SUCCEEDED(host->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root)))) {
237 D3D12_COMPUTE_PIPELINE_STATE_DESC desc{};
238 desc.pRootSignature = root;
239 desc.CS = {shader->GetBufferPointer(), shader->GetBufferSize()};
240 out.push_back(cached_pso_cases(host, desc, root_blob, other_root_blob));
241 root->Release();
242 }
243 host->Release();
244 }
245 if (warp) warp->Release();
246 factory->Release();
247 }
248 shader->Release();
249 return out;
250}
251
139} // namespace 252} // namespace
140 253
141int main() { 254int main() {
@@ -258,6 +371,51 @@ int main() {
258 device.p, &native_desc, nullptr, &out_null) == E_POINTER && !out_null); 371 device.p, &native_desc, nullptr, &out_null) == E_POINTER && !out_null);
259 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))( 372 EXPECT(reinterpret_cast<XboxNativeComputePipelineFn>(slot(device.p, 67))(
260 device.p, &native_desc, &pso_iid, nullptr) == E_POINTER); 373 device.p, &native_desc, &pso_iid, nullptr) == E_POINTER);
374 // GetCachedBlob and CachedPSO answer as the PC runtime does (src/cached_pso.h).
375 {
376 D3D12_VERSIONED_ROOT_SIGNATURE_DESC other_desc = root_desc;
377 other_desc.Desc_1_0.NumParameters = 2;
378 const auto other_root_blob = serialize(other_desc);
379 EXPECT(!other_root_blob.empty());
380 const std::vector<HRESULT> layer = cached_pso_cases(device.p, pso_desc, root_blob, other_root_blob);
381 EXPECT(int(layer.size()) == cached_case_count);
382 const std::vector<HRESULT> expected = {S_OK, S_OK, S_OK, E_INVALIDARG,
383 E_INVALIDARG, E_INVALIDARG, E_INVALIDARG, E_INVALIDARG,
384 E_INVALIDARG, E_INVALIDARG, S_OK};
385 EXPECT(layer == expected);
386 const auto hosts = host_cached_pso_cases(root_blob, other_root_blob);
387 if (hosts.empty()) std::printf("SKIP: no host D3D12 device or compiler for the CachedPSO comparison\n");
388 for (const auto& host : hosts) EXPECT(host == layer);
389 if (!hosts.empty()) std::printf("cached PSO: %zu host adapter(s) gave the same %d answers\n", hosts.size(), cached_case_count);
390
391 // Every byte of the blob counts, and the adapter and driver fields give the runtime's own errors.
392 Ref<ID3DBlob> blob;
393 EXPECT(pso->GetCachedBlob(&blob.p) == S_OK && blob.p);
394 const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
395 std::vector<std::uint8_t> bytes(p, p + blob->GetBufferSize());
396 auto attempt = [&](const std::vector<std::uint8_t>& b) {
397 D3D12_COMPUTE_PIPELINE_STATE_DESC d = pso_desc;
398 d.CachedPSO = {b.data(), b.size()};
399 Ref<ID3D12PipelineState> made;
400 return device->CreateComputePipelineState(&d, IID_PPV_ARGS(&made.p));
401 };
402 for (std::size_t at = 0; at < bytes.size(); ++at) {
403 auto changed = bytes;
404 changed[at] ^= 0x01;
405 EXPECT(attempt(changed) == E_INVALIDARG);
406 }
407 auto resealed = [](std::vector<std::uint8_t> b, std::size_t at) {
408 b[at] ^= 0x01;
409 const std::uint32_t sum = leonida::cached_pso::fnv1a(b.data(), b.size() - 4);
410 for (int i = 0; i < 4; ++i) b[b.size() - 4 + i] = std::uint8_t(sum >> (8 * i));
411 return b;
412 };
413 EXPECT(attempt(resealed(bytes, 8)) == D3D12_ERROR_ADAPTER_NOT_FOUND); // vendor
414 EXPECT(attempt(resealed(bytes, 12)) == D3D12_ERROR_ADAPTER_NOT_FOUND); // device
415 EXPECT(attempt(resealed(bytes, 16)) == D3D12_ERROR_DRIVER_VERSION_MISMATCH);
416 EXPECT(attempt(resealed(bytes, 20)) == D3D12_ERROR_DRIVER_VERSION_MISMATCH); // pipelineCacheUUID
417 EXPECT(attempt(resealed(bytes, 4)) == E_INVALIDARG); // version
418 }
261 419
262 // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so 420 // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so
263 // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag). 421 // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag).
diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp
index d28ebda9f..f2a33c4f2 100644
--- a/runtime/test/d3d12_descriptor_test.cpp
+++ b/runtime/test/d3d12_descriptor_test.cpp
@@ -1784,11 +1784,19 @@ int main() {
1784 // More than 4096 SRVs and more than a full shader-visible sampler heap (2048): 5000 distinct views of the 1784 // More than 4096 SRVs and more than a full shader-visible sampler heap (2048): 5000 distinct views of the
1785 // texture (mip ranges by swizzles), then one more that samples as the texture, and 2100 distinct wrapping 1785 // texture (mip ranges by swizzles), then one more that samples as the texture, and 2100 distinct wrapping
1786 // samplers (MaxLOD apart). The last view through the last sampler must give the texture, one tile to the 1786 // samplers (MaxLOD apart). The last view through the last sampler must give the texture, one tile to the
1787 // right; a fallback view or the fallback (clamping) sampler would not. 1787 // right; a fallback view or the fallback (clamping) sampler would not. A set with less room than that
1788 // (MoltenVK's keeps the default 4096 2D images and 1024 samplers, docs/d3d12_vulkan.md section 5) gets as
1789 // many as fill each short array exactly: its last view and sampler must still give the texture, and one
1790 // more of each must be refused and read as the fallbacks.
1788 { 1791 {
1789 constexpr UINT many_views = 5000, many_samplers = 2100, heap_samplers = 2048; 1792 constexpr UINT wanted_views = 5000, wanted_samplers = 2100, heap_samplers = 2048;
1793 const auto room = rt::d3d12::bindless_room(device.p);
1794 EXPECT(room.images_2d >= 2 && room.samplers >= 1);
1795 const bool views_capped = room.images_2d < wanted_views + 1, samplers_capped = room.samplers < wanted_samplers;
1796 const UINT many_views = views_capped ? room.images_2d - 1 : wanted_views;
1797 const UINT many_samplers = samplers_capped ? room.samplers : wanted_samplers;
1790 Ref<ID3D12DescriptorHeap> many_view_heap, many_sampler_heaps[2]; 1798 Ref<ID3D12DescriptorHeap> many_view_heap, many_sampler_heaps[2];
1791 D3D12_DESCRIPTOR_HEAP_DESC many_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, many_views + 1, 1799 D3D12_DESCRIPTOR_HEAP_DESC many_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, many_views + 2,
1792 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; 1800 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
1793 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&many_desc, IID_PPV_ARGS(&many_view_heap.p)))); 1801 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&many_desc, IID_PPV_ARGS(&many_view_heap.p))));
1794 many_desc = {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, heap_samplers, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 1802 many_desc = {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, heap_samplers, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
@@ -1815,28 +1823,41 @@ int main() {
1815 std::memcpy(tsharps.emplace_back().data(), reinterpret_cast<const void*>(many_view_cpu + i * step), 32); 1823 std::memcpy(tsharps.emplace_back().data(), reinterpret_cast<const void*>(many_view_cpu + i * step), 32);
1816 } 1824 }
1817 // Every mip with alpha forced to one: the texture's texels (alpha 255), under a T# no other view has. 1825 // Every mip with alpha forced to one: the texture's texels (alpha 255), under a T# no other view has.
1826 // The one past it, a short array's extra, forces alpha to zero.
1818 D3D12_SHADER_RESOURCE_VIEW_DESC last_srv{}; 1827 D3D12_SHADER_RESOURCE_VIEW_DESC last_srv{};
1819 last_srv.Format = sampled_desc.Format; 1828 last_srv.Format = sampled_desc.Format;
1820 last_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; 1829 last_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
1821 last_srv.Shader4ComponentMapping = 1830 last_srv.Shader4ComponentMapping =
1822 D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1); 1831 D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1);
1823 last_srv.Texture2D = {0, UINT(-1), 0, 0}; 1832 last_srv.Texture2D = {0, UINT(-1), 0, 0};
1824 const std::uint64_t last_view = many_view_cpu + many_views * step; 1833 const std::uint64_t last_view = many_view_cpu + many_views * step, extra_view = last_view + step;
1825 device->CreateShaderResourceView(texture.p, &last_srv, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(last_view)}); 1834 device->CreateShaderResourceView(texture.p, &last_srv, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(last_view)});
1826 std::memcpy(tsharps.emplace_back().data(), reinterpret_cast<const void*>(last_view), 32); 1835 std::memcpy(tsharps.emplace_back().data(), reinterpret_cast<const void*>(last_view), 32);
1836 if (views_capped) {
1837 EXPECT(rt::d3d12::bindless_room(device.p).images_2d == 0);
1838 last_srv.Shader4ComponentMapping =
1839 D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0);
1840 device->CreateShaderResourceView(texture.p, &last_srv, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(extra_view)});
1841 std::memcpy(tsharps.emplace_back().data(), reinterpret_cast<const void*>(extra_view), 32);
1842 }
1827 std::memcpy(tsharps.emplace_back().data(), view_bytes(own), 32); 1843 std::memcpy(tsharps.emplace_back().data(), view_bytes(own), 32);
1828 std::sort(tsharps.begin(), tsharps.end()); 1844 std::sort(tsharps.begin(), tsharps.end());
1829 EXPECT(std::unique(tsharps.begin(), tsharps.end()) == tsharps.end()); // distinct set entries 1845 EXPECT(std::unique(tsharps.begin(), tsharps.end()) == tsharps.end()); // distinct set entries
1830 1846
1831 std::vector<std::array<std::uint32_t, 4>> ssharps; 1847 std::vector<std::array<std::uint32_t, 4>> ssharps;
1832 std::uint64_t last_sampler = 0; 1848 std::uint64_t last_sampler = 0;
1833 for (UINT i = 0; i < many_samplers; ++i) { 1849 const UINT created_samplers = many_samplers + (samplers_capped ? 1 : 0);
1850 for (UINT i = 0; i < created_samplers; ++i) {
1851 if (i == many_samplers) EXPECT(rt::d3d12::bindless_room(device.p).samplers == 0);
1834 D3D12_SAMPLER_DESC many_sampler = sampler_desc; 1852 D3D12_SAMPLER_DESC many_sampler = sampler_desc;
1835 many_sampler.MaxLOD = float(i + 1) / 256.0f; // the S# keeps 8 fraction bits; LOD 0 is sampled 1853 many_sampler.MaxLOD = float(i + 1) / 256.0f; // the S# keeps 8 fraction bits; LOD 0 is sampled
1836 last_sampler = cpu_start(many_sampler_heaps[i / heap_samplers].p) + (i % heap_samplers) * sampler_step; 1854 const std::uint64_t at =
1837 device->CreateSampler(&many_sampler, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(last_sampler)}); 1855 cpu_start(many_sampler_heaps[i / heap_samplers].p) + (i % heap_samplers) * sampler_step;
1838 std::memcpy(ssharps.emplace_back().data(), reinterpret_cast<const void*>(last_sampler), 16); 1856 device->CreateSampler(&many_sampler, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(at)});
1857 std::memcpy(ssharps.emplace_back().data(), reinterpret_cast<const void*>(at), 16);
1858 if (i < many_samplers) last_sampler = at;
1839 } 1859 }
1860 const std::uint64_t extra_sampler = last_sampler + sampler_step; // many_samplers < heap_samplers then
1840 std::memcpy(ssharps.emplace_back().data(), sampler_bytes, 16); 1861 std::memcpy(ssharps.emplace_back().data(), sampler_bytes, 16);
1841 std::sort(ssharps.begin(), ssharps.end()); 1862 std::sort(ssharps.begin(), ssharps.end());
1842 EXPECT(std::unique(ssharps.begin(), ssharps.end()) == ssharps.end()); 1863 EXPECT(std::unique(ssharps.begin(), ssharps.end()) == ssharps.end());
@@ -1847,20 +1868,63 @@ int main() {
1847 queue->ExecuteCommandLists(1, lists); 1868 queue->ExecuteCommandLists(1, lists);
1848 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); 1869 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
1849 d.fn<PFN_vkDeviceWaitIdle>("vkDeviceWaitIdle")(d.device); 1870 d.fn<PFN_vkDeviceWaitIdle>("vkDeviceWaitIdle")(d.device);
1850 SampleKeys last_keys{}; 1871 const auto in_table = [&](std::uint64_t descriptor, bool sampler) {
1851 std::memcpy(last_keys.tsharp, reinterpret_cast<const void*>(last_view), sizeof(last_keys.tsharp)); 1872 std::uint32_t key[8]{~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u};
1852 std::memcpy(last_keys.ssharp, reinterpret_cast<const void*>(last_sampler), sizeof(last_keys.ssharp)); 1873 std::memcpy(key, reinterpret_cast<const void*>(descriptor), sampler ? 16 : 32);
1853 std::array<std::uint8_t, bytes> last_texels{}; 1874 return rt::d3d12::bindless_hash_lookup(device.p, key) != 0;
1854 EXPECT(sample_through_set(d, set0, set0_layout, {&last_keys, 1}, last_texels.data())); 1875 };
1876 EXPECT(in_table(last_view, false) && in_table(last_sampler, true));
1877 if (views_capped) EXPECT(!in_table(extra_view, false));
1878 if (samplers_capped) EXPECT(!in_table(extra_sampler, true));
1879
1880 // The last view through the last sampler; then a short array's extra in its place, which reads as the
1881 // fallback: zeros for the view, and the clamping sampler's edge column for the sampler.
1882 SampleKeys last_keys[3]{};
1883 std::memcpy(last_keys[0].tsharp, reinterpret_cast<const void*>(last_view), sizeof(last_keys[0].tsharp));
1884 std::memcpy(last_keys[0].ssharp, reinterpret_cast<const void*>(last_sampler), sizeof(last_keys[0].ssharp));
1885 UINT key_count = 1;
1886 if (views_capped) {
1887 last_keys[key_count] = last_keys[0];
1888 std::memcpy(last_keys[key_count].tsharp, reinterpret_cast<const void*>(extra_view),
1889 sizeof(last_keys[key_count].tsharp));
1890 last_keys[key_count].first = key_count * texels;
1891 ++key_count;
1892 }
1893 if (samplers_capped) {
1894 last_keys[key_count] = last_keys[0];
1895 std::memcpy(last_keys[key_count].ssharp, reinterpret_cast<const void*>(extra_sampler),
1896 sizeof(last_keys[key_count].ssharp));
1897 last_keys[key_count].first = key_count * texels;
1898 ++key_count;
1899 }
1900 std::array<std::uint8_t, 3 * bytes> last_texels{};
1901 EXPECT(sample_through_set(d, set0, set0_layout, {last_keys, key_count}, last_texels.data()));
1902 const char* const names[] = {"the last view through the last sampler", "the refused view",
1903 "the refused sampler"};
1855 UINT differ = 0; 1904 UINT differ = 0;
1856 for (UINT i = 0; i < texels; ++i) 1905 for (UINT k = 0; k < key_count; ++k) {
1857 if (std::memcmp(last_texels.data() + 4 * i, texel(i % size, i / size).data(), 4) != 0 && differ++ < 4) 1906 const UINT kind = k == 0 ? 0 : views_capped && k == 1 ? 1 : 2;
1858 std::fprintf(stderr, "view %u through sampler %u, texel %u: got %u,%u,%u,%u\n", many_views + 1, 1907 for (UINT i = 0; i < texels; ++i) {
1859 many_samplers, i, last_texels[4 * i], last_texels[4 * i + 1], last_texels[4 * i + 2], 1908 const auto want = kind == 0 ? texel(i % size, i / size)
1860 last_texels[4 * i + 3]); 1909 : kind == 1 ? std::array<std::uint8_t, 4>{}
1910 : texel(size - 1, i / size);
1911 const auto* got = last_texels.data() + k * bytes + 4 * i;
1912 if (std::memcmp(got, want.data(), 4) != 0 && differ++ < 4)
1913 std::fprintf(stderr, "%s, texel %u: got %u,%u,%u,%u; expected %u,%u,%u,%u\n", names[kind], i,
1914 got[0], got[1], got[2], got[3], want[0], want[1], want[2], want[3]);
1915 }
1916 }
1861 EXPECT(differ == 0); 1917 EXPECT(differ == 0);
1862 std::printf("bindless capacity: the %uth SRV through the %uth sampler gave the texture\n", many_views + 1, 1918 if (!views_capped && !samplers_capped)
1863 many_samplers); 1919 std::printf("bindless capacity: the %uth SRV through the %uth sampler gave the texture\n",
1920 many_views + 1, many_samplers);
1921 else
1922 std::printf("bindless capacity: the set had room for %u more 2D views and %u more samplers, fewer than "
1923 "%u and %u: the last of each gave the texture, and one more %s refused and read as the "
1924 "fallback\n", room.images_2d, room.samplers, wanted_views + 1, wanted_samplers,
1925 views_capped && samplers_capped ? "of each was"
1926 : views_capped ? "view was"
1927 : "sampler was");
1864 } 1928 }
1865 1929
1866 // 96-bit textures (D3D-62): R32G32B32_FLOAT holding the texture's red, green and blue as n/255, 1930 // 96-bit textures (D3D-62): R32G32B32_FLOAT holding the texture's red, green and blue as n/255,
@@ -2261,6 +2325,262 @@ int main() {
2261 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, cast_key) != 0); 2325 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, cast_key) != 0);
2262 } 2326 }
2263 2327
2328 // Depth SRVs: D16_UNORM / R16_TYPELESS (depth) and D32_FLOAT / R32_TYPELESS (depth) only allow matching depth
2329 // view formats (R16_UNORM / R32_FLOAT, plus UNKNOWN on typed D16/D32). Colour casts on depth textures
2330 // (R16_FLOAT/SNORM/UINT/SINT on D16, R32_UINT/SINT on D32, or any colour format on D24S8/D32S8) must produce
2331 // null descriptors with zero Vulkan validation errors.
2332 {
2333 const unsigned validation_before_depth = d.validation_errors();
2334 constexpr UINT depth_tex_count = 4;
2335 constexpr DXGI_FORMAT depth_tex_formats[depth_tex_count] = {
2336 DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R32_TYPELESS};
2337 constexpr DXGI_FORMAT depth_dsv_formats[depth_tex_count] = {
2338 DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_D32_FLOAT};
2339 // Multiples of 1/255 are exact in both D16_UNORM (65535 = 255 * 257) and D32_FLOAT.
2340 constexpr std::uint8_t depth_clear_u8[depth_tex_count] = {51, 102, 153, 204};
2341 Ref<ID3D12Resource> depth_textures[depth_tex_count];
2342 for (UINT i = 0; i < depth_tex_count; ++i) {
2343 D3D12_RESOURCE_DESC dd = texture_desc;
2344 dd.Format = depth_tex_formats[i];
2345 dd.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
2346 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &dd,
2347 D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr,
2348 IID_PPV_ARGS(&depth_textures[i].p))));
2349 }
2350 Ref<ID3D12DescriptorHeap> depth_dsv_heap, depth_srv_heap;
2351 const D3D12_DESCRIPTOR_HEAP_DESC depth_dsv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, depth_tex_count,
2352 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
2353 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&depth_dsv_hd, IID_PPV_ARGS(&depth_dsv_heap.p))));
2354 const UINT dsv_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
2355 const std::uint64_t dsv_cpu = reinterpret_cast<XboxHeapHandleFn>(slot(depth_dsv_heap.p, 9))(depth_dsv_heap.p);
2356 const auto dsv_slot = [&](UINT i) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(dsv_cpu + i * dsv_step)}; };
2357 for (UINT i = 0; i < depth_tex_count; ++i) {
2358 D3D12_DEPTH_STENCIL_VIEW_DESC dsv{};
2359 dsv.Format = depth_dsv_formats[i];
2360 dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
2361 device->CreateDepthStencilView(depth_textures[i].p, &dsv, dsv_slot(i));
2362 }
2363
2364 // Valid depth SRVs: 0: D16 default, 1: D16->R16_UNORM, 2: R16_TYPELESS->R16_UNORM,
2365 // 3: D32 default, 4: D32->R32_FLOAT, 5: R32_TYPELESS->R32_FLOAT; 6: scratch for invalid.
2366 constexpr UINT valid_depth_srvs = 6, depth_scratch = 6;
2367 const D3D12_DESCRIPTOR_HEAP_DESC depth_srv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, valid_depth_srvs + 1,
2368 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
2369 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&depth_srv_hd, IID_PPV_ARGS(&depth_srv_heap.p))));
2370 const std::uint64_t depth_srv_cpu =
2371 reinterpret_cast<XboxHeapHandleFn>(slot(depth_srv_heap.p, 9))(depth_srv_heap.p);
2372 const auto depth_slot = [&](UINT i) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(depth_srv_cpu + i * step)}; };
2373 const auto depth_bytes = [&](UINT i) { return reinterpret_cast<std::uint8_t*>(depth_srv_cpu + i * step); };
2374 const auto depth_null = [&](UINT i) {
2375 return std::all_of(depth_bytes(i), depth_bytes(i) + step, [](std::uint8_t b) { return b == 0; });
2376 };
2377
2378 struct ValidDepthSrv {
2379 UINT tex_index;
2380 DXGI_FORMAT view_format; // UNKNOWN => pass nullptr
2381 VkFormat expected_vk;
2382 };
2383 constexpr ValidDepthSrv valid_cases[valid_depth_srvs] = {
2384 {0, DXGI_FORMAT_UNKNOWN, VK_FORMAT_D16_UNORM},
2385 {0, DXGI_FORMAT_R16_UNORM, VK_FORMAT_D16_UNORM},
2386 {1, DXGI_FORMAT_R16_UNORM, VK_FORMAT_D16_UNORM},
2387 {2, DXGI_FORMAT_UNKNOWN, VK_FORMAT_D32_SFLOAT},
2388 {2, DXGI_FORMAT_R32_FLOAT, VK_FORMAT_D32_SFLOAT},
2389 {3, DXGI_FORMAT_R32_FLOAT, VK_FORMAT_D32_SFLOAT},
2390 };
2391 for (UINT i = 0; i < valid_depth_srvs; ++i) {
2392 const auto& vc = valid_cases[i];
2393 D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
2394 srv.Format = vc.view_format;
2395 srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
2396 srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
2397 srv.Texture2D.MipLevels = 1;
2398 device->CreateShaderResourceView(depth_textures[vc.tex_index].p,
2399 vc.view_format == DXGI_FORMAT_UNKNOWN ? nullptr : &srv, depth_slot(i));
2400 g::ImageWords words{};
2401 std::memcpy(words.data(), depth_bytes(i), sizeof(words));
2402 g::Image decoded{};
2403 EXPECT(g::is_image(words) && g::decode(words, decoded));
2404 EXPECT(decoded.type == g::ImageType::image_2d);
2405 EXPECT(decoded.format == g::format_from_vulkan(vc.expected_vk));
2406 EXPECT(decoded.swizzle == g::channels_r);
2407 std::uint32_t key[8]{};
2408 std::memcpy(key, words.data(), sizeof(key));
2409 EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) != 0);
2410 }
2411
2412 // Invalid depth SRVs: every non-depth colour format and mismatched/typeless format must leave a null
2413 // descriptor and emit zero Vulkan validation errors.
2414 const auto expect_depth_srv_null = [&](ID3D12Resource* res, const D3D12_SHADER_RESOURCE_VIEW_DESC* srv) {
2415 std::memset(depth_bytes(depth_scratch), 0x77, step);
2416 device->CreateShaderResourceView(res, srv, depth_slot(depth_scratch));
2417 return depth_null(depth_scratch);
2418 };
2419 const auto check_bad_formats = [&](ID3D12Resource* res, std::initializer_list<DXGI_FORMAT> bad_formats) {
2420 for (const DXGI_FORMAT fmt : bad_formats) {
2421 D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
2422 srv.Format = fmt;
2423 srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
2424 srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
2425 srv.Texture2D.MipLevels = 1;
2426 if (!expect_depth_srv_null(res, &srv)) return false;
2427 }
2428 return true;
2429 };
2430 // D16_UNORM and R16_TYPELESS (depth): R16_FLOAT, R16_SNORM, R16_UINT, R16_SINT and other mismatched views.
2431 EXPECT(check_bad_formats(depth_textures[0].p,
2432 {DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_SNORM, DXGI_FORMAT_R16_UINT,
2433 DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_D16_UNORM,
2434 DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R8G8B8A8_UNORM}));
2435 EXPECT(expect_depth_srv_null(depth_textures[1].p, nullptr)); // UNKNOWN on R16_TYPELESS (depth)
2436 EXPECT(check_bad_formats(depth_textures[1].p,
2437 {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_SNORM,
2438 DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R16_TYPELESS,
2439 DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R8G8B8A8_UNORM}));
2440 // D32_FLOAT and R32_TYPELESS (depth): R32_UINT, R32_SINT and other mismatched views.
2441 EXPECT(check_bad_formats(depth_textures[2].p,
2442 {DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_SINT, DXGI_FORMAT_R32_TYPELESS,
2443 DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM}));
2444 EXPECT(expect_depth_srv_null(depth_textures[3].p, nullptr)); // UNKNOWN on R32_TYPELESS (depth)
2445 EXPECT(check_bad_formats(depth_textures[3].p,
2446 {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_SINT,
2447 DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R16_UNORM,
2448 DXGI_FORMAT_R8G8B8A8_UNORM}));
2449
2450 // D24_UNORM_S8_UINT / R24G8_TYPELESS and D32_FLOAT_S8X24_UINT / R32G8X24_TYPELESS: colour view formats
2451 // must also be rejected, while depth-plane and stencil-plane views continue working.
2452 for (const auto& [res_fmt, valid_depth_fmt, valid_stencil_fmt, is_typeless] :
2453 {std::tuple{DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_R24_UNORM_X8_TYPELESS,
2454 DXGI_FORMAT_X24_TYPELESS_G8_UINT, false},
2455 std::tuple{DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R24_UNORM_X8_TYPELESS,
2456 DXGI_FORMAT_X24_TYPELESS_G8_UINT, true},
2457 std::tuple{DXGI_FORMAT_D32_FLOAT_S8X24_UINT, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS,
2458 DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, false},
2459 std::tuple{DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS,
2460 DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, true}}) {
2461 D3D12_RESOURCE_DESC ds_desc = texture_desc;
2462 ds_desc.Format = res_fmt;
2463 ds_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
2464 Ref<ID3D12Resource> ds_tex;
2465 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &ds_desc,
2466 D3D12_RESOURCE_STATE_COMMON, nullptr,
2467 IID_PPV_ARGS(&ds_tex.p))));
2468 if (is_typeless) EXPECT(expect_depth_srv_null(ds_tex.p, nullptr));
2469 EXPECT(check_bad_formats(ds_tex.p,
2470 {DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_SINT,
2471 DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R8G8B8A8_UNORM,
2472 DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
2473 DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R32G8X24_TYPELESS}));
2474 D3D12_SHADER_RESOURCE_VIEW_DESC ds_srv{};
2475 ds_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
2476 ds_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
2477 ds_srv.Texture2D.MipLevels = 1;
2478 ds_srv.Format = valid_depth_fmt;
2479 ds_srv.Texture2D.PlaneSlice = 0;
2480 device->CreateShaderResourceView(ds_tex.p, &ds_srv, depth_slot(depth_scratch));
2481 EXPECT(!depth_null(depth_scratch));
2482 ds_srv.Format = valid_stencil_fmt;
2483 ds_srv.Texture2D.PlaneSlice = 1;
2484 device->CreateShaderResourceView(ds_tex.p, &ds_srv, depth_slot(depth_scratch));
2485 EXPECT(!depth_null(depth_scratch));
2486 }
2487
2488 // Colour R16_TYPELESS and R32_TYPELESS (without ALLOW_DEPTH_STENCIL) still allow colour casts,
2489 // while rejecting depth view formats on colour textures.
2490 for (const auto& [colour_typeless, good_colour, bad_depth] :
2491 {std::tuple{DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_D16_UNORM},
2492 std::tuple{DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_D32_FLOAT}}) {
2493 D3D12_RESOURCE_DESC col_desc = texture_desc;
2494 col_desc.Format = colour_typeless;
2495 Ref<ID3D12Resource> col_tex;
2496 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &col_desc,
2497 D3D12_RESOURCE_STATE_COMMON, nullptr,
2498 IID_PPV_ARGS(&col_tex.p))));
2499 D3D12_SHADER_RESOURCE_VIEW_DESC col_srv{};
2500 col_srv.Format = good_colour;
2501 col_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
2502 col_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
2503 col_srv.Texture2D.MipLevels = 1;
2504 device->CreateShaderResourceView(col_tex.p, &col_srv, depth_slot(depth_scratch));
2505 EXPECT(!depth_null(depth_scratch));
2506 EXPECT(check_bad_formats(col_tex.p, {bad_depth}));
2507 }
2508
2509 // Depth resource with a castable format list (allow_channel_cast = true): valid depth SRV still works
2510 // and colour SRVs still leave a null descriptor with zero validation errors.
2511 {
2512 Ref<ID3D12Device10> inner10;
2513 EXPECT(SUCCEEDED(inner->QueryInterface(IID_PPV_ARGS(&inner10.p))));
2514 D3D12_RESOURCE_DESC1 d16_cast_desc{};
2515 d16_cast_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
2516 d16_cast_desc.Width = size;
2517 d16_cast_desc.Height = size;
2518 d16_cast_desc.DepthOrArraySize = 1;
2519 d16_cast_desc.MipLevels = 1;
2520 d16_cast_desc.Format = DXGI_FORMAT_D16_UNORM;
2521 d16_cast_desc.SampleDesc = {1, 0};
2522 d16_cast_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
2523 const DXGI_FORMAT d16_list[] = {DXGI_FORMAT_D16_UNORM};
2524 Ref<ID3D12Resource> d16_cast_tex;
2525 EXPECT(SUCCEEDED(inner10->CreateCommittedResource3(
2526 &default_heap, D3D12_HEAP_FLAG_NONE, &d16_cast_desc, D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr,
2527 1, d16_list, IID_PPV_ARGS(&d16_cast_tex.p))));
2528 D3D12_SHADER_RESOURCE_VIEW_DESC d16_srv{};
2529 d16_srv.Format = DXGI_FORMAT_R16_UNORM;
2530 d16_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
2531 d16_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
2532 d16_srv.Texture2D.MipLevels = 1;
2533 device->CreateShaderResourceView(d16_cast_tex.p, &d16_srv, depth_slot(depth_scratch));
2534 EXPECT(!depth_null(depth_scratch));
2535 EXPECT(check_bad_formats(d16_cast_tex.p,
2536 {DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_SNORM, DXGI_FORMAT_R16_UINT,
2537 DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R8G8B8A8_UNORM}));
2538 }
2539
2540 // Clear each depth texture and sample all 6 valid depth SRVs on the GPU to confirm they read back their
2541 // cleared depth value in R (with G=0, B=0, A=1).
2542 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)));
2543 for (UINT i = 0; i < depth_tex_count; ++i) {
2544 list->ClearDepthStencilView(dsv_slot(i), D3D12_CLEAR_FLAG_DEPTH, float(depth_clear_u8[i]) / 255.0f, 0,
2545 0, nullptr);
2546 const D3D12_RESOURCE_BARRIER barrier = transition(
2547 depth_textures[i].p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
2548 list->ResourceBarrier(1, &barrier);
2549 }
2550 EXPECT(list->Close() == S_OK);
2551 queue->ExecuteCommandLists(1, lists);
2552 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
2553 ++packed_signal;
2554 EXPECT(SUCCEEDED(queue->Signal(fence.p, packed_signal)) &&
2555 SUCCEEDED(fence->SetEventOnCompletion(packed_signal, nullptr)));
2556#ifdef LEONIDA_TEST_CS_SAMPLE_SPV
2557 SampleKeys depth_keys[valid_depth_srvs]{};
2558 for (UINT i = 0; i < valid_depth_srvs; ++i) {
2559 std::memcpy(depth_keys[i].tsharp, depth_bytes(i), sizeof(depth_keys[i].tsharp));
2560 std::memcpy(depth_keys[i].ssharp, sampler_bytes, sizeof(depth_keys[i].ssharp));
2561 depth_keys[i].first = i * texels;
2562 }
2563 std::vector<std::uint8_t> depth_pixels(valid_depth_srvs * bytes);
2564 EXPECT(sample_through_set(d, set0, set0_layout, depth_keys, depth_pixels.data()));
2565 UINT depth_differ = 0;
2566 for (UINT k = 0; k < valid_depth_srvs; ++k) {
2567 const std::uint8_t want[4] = {depth_clear_u8[valid_cases[k].tex_index], 0, 0, 255};
2568 for (UINT i = 0; i < texels; ++i) {
2569 const std::uint8_t* got = depth_pixels.data() + k * bytes + i * 4;
2570 if (std::memcmp(got, want, 4) != 0 && depth_differ++ < 4)
2571 std::fprintf(stderr, "depth SRV %u texel %u: got %u,%u,%u,%u, want %u,%u,%u,%u\n", k, i,
2572 unsigned(got[0]), unsigned(got[1]), unsigned(got[2]), unsigned(got[3]),
2573 unsigned(want[0]), unsigned(want[1]), unsigned(want[2]), unsigned(want[3]));
2574 }
2575 }
2576 EXPECT(depth_differ == 0);
2577 std::printf("depth SRVs: %u valid D16/D32 views sampled cleared depth values; invalid colour casts rejected "
2578 "as null descriptors (validation errors: %u)\n",
2579 valid_depth_srvs, d.validation_errors() - validation_before_depth);
2580#endif
2581 EXPECT(d.validation_errors() == validation_before_depth);
2582 }
2583
2264 upload.reset(); 2584 upload.reset();
2265 array_texture.reset(); 2585 array_texture.reset();
2266 line.reset(); 2586 line.reset();
diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp
index 79fb69a70..b108fa8ec 100644
--- a/runtime/test/d3d12_draw_test.cpp
+++ b/runtime/test/d3d12_draw_test.cpp
@@ -202,6 +202,40 @@ int main() {
202 instance_desc.InputLayout = {instance_elements, 2}; 202 instance_desc.InputLayout = {instance_elements, 2};
203 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&instance_desc, IID_PPV_ARGS(&instanced.p)))); 203 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&instance_desc, IID_PPV_ARGS(&instanced.p))));
204 204
205 // CachedPSO on a graphics description: what the PC runtime matches, measured on an RTX 3060
206 // (src/cached_pso.h). Flags is not part of it; every state below is.
207 {
208 Ref<ID3DBlob> blob;
209 EXPECT(pso->GetCachedBlob(&blob.p) == S_OK && blob.p && blob->GetBufferSize());
210 auto with_blob = [&](D3D12_GRAPHICS_PIPELINE_STATE_DESC d) {
211 d.CachedPSO = {blob->GetBufferPointer(), blob->GetBufferSize()};
212 Ref<ID3D12PipelineState> made;
213 const HRESULT hr = device->CreateGraphicsPipelineState(&d, IID_PPV_ARGS(&made.p));
214 return SUCCEEDED(hr) == (made.p != nullptr) ? hr : E_UNEXPECTED;
215 };
216 EXPECT(with_blob(pso_desc) == S_OK);
217 D3D12_GRAPHICS_PIPELINE_STATE_DESC changed = pso_desc;
218 changed.Flags = D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG;
219 EXPECT(with_blob(changed) == S_OK);
220 EXPECT(with_blob(mrt_desc) == E_INVALIDARG);
221 EXPECT(with_blob(instance_desc) == E_INVALIDARG);
222 changed = pso_desc;
223 changed.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
224 EXPECT(with_blob(changed) == E_INVALIDARG);
225 changed = pso_desc;
226 changed.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_RED;
227 EXPECT(with_blob(changed) == E_INVALIDARG);
228 changed = pso_desc;
229 changed.SampleMask = 1;
230 EXPECT(with_blob(changed) == E_INVALIDARG);
231 changed = pso_desc;
232 changed.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF;
233 EXPECT(with_blob(changed) == E_INVALIDARG);
234 changed = pso_desc;
235 changed.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
236 EXPECT(with_blob(changed) == E_INVALIDARG);
237 }
238
205 // State that needs a Vulkan feature this test device does not enable is refused, not passed to the driver. 239 // State that needs a Vulkan feature this test device does not enable is refused, not passed to the driver.
206 D3D12_GRAPHICS_PIPELINE_STATE_DESC needs_feature = pso_desc; 240 D3D12_GRAPHICS_PIPELINE_STATE_DESC needs_feature = pso_desc;
207 needs_feature.RasterizerState.FillMode = D3D12_FILL_MODE_WIREFRAME; // fillModeNonSolid 241 needs_feature.RasterizerState.FillMode = D3D12_FILL_MODE_WIREFRAME; // fillModeNonSolid
diff --git a/runtime/test/d3d12_first_light_test.cpp b/runtime/test/d3d12_first_light_test.cpp
new file mode 100644
index 000000000..8dcc2ca9c
--- /dev/null
+++ b/runtime/test/d3d12_first_light_test.cpp
@@ -0,0 +1,395 @@
1// First light through the port's D3D12 layer (docs/first_light.md section 5): the real model and the real translated
2// VS/PS that tools/first_light.py assembled from the user's package, drawn through the Xbox-ABI device proxy over the
3// Vulkan device. Package-gated: it reads everything at run time from LEONIDA_FIRST_LIGHT_DIR (the first_light.py
4// output folder) and prints SKIP and exits 77 when that is unset. No game data is in the repository.
5// - CreateGraphicsPipelineState gets the game's own DXBC containers (vs.dxbc, ps.dxbc) and finds both stages by the
6// SHA-256 of the FSSM program inside them, in the translator index first_light.py wrote (index.json, vs.spv,
7// ps.spv); nothing bypasses the lookup. The hashes must also be the ones manifest.json records;
8// - the input layout (POSITION float3, TEXCOORD float2, stride 20) is matched to the VS input signature by
9// semantic; mesh.bin's vertices and indices go through an upload heap into DEFAULT buffers in the GPU address
10// arena, and one DrawIndexedInstanced draws the whole mesh with no depth test and no culling, as vk_harness does;
11// - the R32G32B32A32_FLOAT target is cleared to -1 (vk_harness's clear) and read back through CopyTextureRegion.
12// The oracle is vk_harness's (tests/test_first_light.py): coverage in the manifest's window, the clear corner keeps
13// -1, and the centre pixel is the UV the mesh's last covering triangle gives there. D3D12 clip space is y-up and the
14// layer flips the viewport, while vk_harness draws with a y-down viewport, so vk_harness row r is row H-1-r here.
15// When the folder also has vk_harness's image.raw, every pixel must equal it with the rows flipped.
16// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
17#include "vk_test_device.h"
18#include "d3d12_test_shaders.h"
19#include "../shims/d3d12_com.h"
20#include "../shims/d3d12_xs_device.h"
21#include "../src/shader_library.h"
22
23#include <array>
24#include <cmath>
25#include <cstdlib>
26#include <cstring>
27
28#define EXPECT(condition) do { \
29 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
30} while (0)
31
32using namespace d3d12test;
33using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX
34using Pixel = std::array<float, 4>;
35
36namespace {
37
38std::vector<std::uint8_t> read_file(const std::filesystem::path& path) {
39 std::ifstream in(path, std::ios::binary);
40 return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
41}
42
43double number(const leonida::Json& object, std::string_view key, double fallback = -1) {
44 const leonida::Json* value = object.find(key);
45 return value && value->kind == leonida::Json::Kind::number ? value->number : fallback;
46}
47
48// [x, y] from the manifest, or false when it is missing.
49bool pixel_of(const leonida::Json& object, std::string_view key, std::array<double, 2>& out) {
50 const leonida::Json* value = object.find(key);
51 if (!value || value->kind != leonida::Json::Kind::array || value->array.size() != 2) return false;
52 for (int i = 0; i < 2; ++i) {
53 if (value->array[i].kind != leonida::Json::Kind::number) return false;
54 out[i] = value->array[i].number;
55 }
56 return true;
57}
58
59std::string stage_hash(const leonida::Json& manifest, std::string_view stage) {
60 const leonida::Json* entry = manifest.find(stage);
61 const leonida::Json* hash = entry ? entry->find("fssm_sha256") : nullptr;
62 return hash && hash->kind == leonida::Json::Kind::string ? hash->string : std::string();
63}
64
65} // namespace
66
67int main() {
68 const char* dir_env = std::getenv("LEONIDA_FIRST_LIGHT_DIR");
69 if (!dir_env || !*dir_env) {
70 std::printf("SKIP: LEONIDA_FIRST_LIGHT_DIR is not set (run tools/first_light.py first)\n");
71 return 77;
72 }
73 vktest::Device d;
74 const auto device_status = d.initialize();
75 if (device_status == vktest::DeviceStatus::unavailable) {
76 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
77 return 77;
78 }
79 EXPECT(device_status == vktest::DeviceStatus::ready);
80
81 // The work folder: the manifest, the mesh, the game's two containers and the translator's index for them.
82 const std::filesystem::path dir = dir_env;
83 const auto manifest_text = read_file(dir / "manifest.json");
84 leonida::Json manifest;
85 EXPECT(leonida::JsonReader(std::string_view(reinterpret_cast<const char*>(manifest_text.data()),
86 manifest_text.size()))
87 .parse(manifest));
88 for (const char* name : {"vs.dxbc", "ps.dxbc", "index.json", "vs.spv", "ps.spv", "mesh.bin"}) {
89 if (!std::filesystem::is_regular_file(dir / name)) {
90 std::fprintf(stderr, "%s has no %s: re-run tools/first_light.py (it writes the D3D12 inputs too)\n",
91 dir.string().c_str(), name);
92 return 1;
93 }
94 }
95 const UINT width = UINT(number(manifest, "width")), height = UINT(number(manifest, "height"));
96 EXPECT(width > 0 && width <= 4096 && height > 0 && height <= 4096);
97 const UINT pitch = (width * sizeof(Pixel) + 255) / 256 * 256;
98
99 const auto vs_container = read_file(dir / "vs.dxbc"), ps_container = read_file(dir / "ps.dxbc");
100 const std::string vs_hash = leonida::sha256_hex(leonida::fssm_program(vs_container));
101 const std::string ps_hash = leonida::sha256_hex(leonida::fssm_program(ps_container));
102 EXPECT(vs_hash == stage_hash(manifest, "vs") && ps_hash == stage_hash(manifest, "ps"));
103 leonida::ShaderLibrary library;
104 EXPECT(library.load(dir.string()));
105 EXPECT(library.find("vs", vs_hash) && library.find("ps", ps_hash));
106 // The lookup is keyed by stage as well as hash: each program must not be found as the other stage.
107 EXPECT(!library.find("vs", ps_hash) && !library.find("ps", vs_hash));
108
109 // mesh.bin: u32 vertex_count, u32 index_count, (x, y, z, u, v) f32 per vertex, u32 indices.
110 const auto mesh = read_file(dir / "mesh.bin");
111 EXPECT(mesh.size() >= 8);
112 std::uint32_t vertex_count = 0, index_count = 0;
113 std::memcpy(&vertex_count, mesh.data(), 4);
114 std::memcpy(&index_count, mesh.data() + 4, 4);
115 constexpr UINT stride = 5 * sizeof(float);
116 const std::size_t vertex_bytes = std::size_t(vertex_count) * stride, index_bytes = std::size_t(index_count) * 4;
117 EXPECT(vertex_count && index_count && mesh.size() == 8 + vertex_bytes + index_bytes);
118 EXPECT(vertex_count == number(manifest, "vertex_count") && index_count == number(manifest, "index_count"));
119 const std::size_t index_offset = (vertex_bytes + 255) / 256 * 256;
120
121 std::vector<Pixel> pixels(std::size_t(width) * height);
122 {
123 rt::d3d12::VulkanDeviceInfo info{};
124 info.get_instance_proc = d.instance_proc;
125 info.instance = d.instance;
126 info.physical = d.physical;
127 info.device = d.device;
128 info.queue = d.queue;
129 info.queue_family = d.family;
130 info.buffer_device_address = true;
131 info.subgroup = d.subgroup;
132 info.shader_dir = dir.string();
133 ID3D12Device* inner = nullptr;
134 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
135 Ref<ID3D12Device> device;
136 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
137 reinterpret_cast<void**>(&device.p))));
138 rt::d3d12::set_device_outer(inner, device.p);
139
140 // No root parameters: the VS applies no matrix and the PS has no bindings (vk_harness pushes zeros too).
141 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
142 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
143 root_desc.Desc_1_0 = {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT};
144 const auto root_blob = serialize_root_signature(root_desc);
145 EXPECT(!root_blob.empty());
146 Ref<ID3D12RootSignature> root;
147 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
148
149 const D3D12_INPUT_ELEMENT_DESC elements[2] = {
150 {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
151 {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
152 D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{};
153 pso_desc.pRootSignature = root.p;
154 pso_desc.VS = {vs_container.data(), vs_container.size()};
155 pso_desc.PS = {ps_container.data(), ps_container.size()};
156 pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
157 pso_desc.SampleMask = 0xffffffff;
158 pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
159 pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
160 pso_desc.RasterizerState.DepthClipEnable = TRUE;
161 pso_desc.InputLayout = {elements, 2};
162 pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
163 pso_desc.NumRenderTargets = 1;
164 pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;
165 pso_desc.SampleDesc.Count = 1;
166 {
167 // The pixel shader's container as the VS: the proxy finds no vs program with that hash, so no PSO.
168 D3D12_GRAPHICS_PIPELINE_STATE_DESC swapped = pso_desc;
169 swapped.VS = pso_desc.PS;
170 Ref<ID3D12PipelineState> wrong;
171 EXPECT(FAILED(device->CreateGraphicsPipelineState(&swapped, IID_PPV_ARGS(&wrong.p))) && !wrong.p);
172 }
173 Ref<ID3D12PipelineState> pso;
174 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p))));
175
176 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
177 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
178 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
179 Ref<ID3D12Resource> vertex_buffer, index_buffer, upload, readback, target;
180 const auto vb_desc = buffer_desc(vertex_bytes), ib_desc = buffer_desc(index_bytes);
181 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc,
182 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
183 IID_PPV_ARGS(&vertex_buffer.p))));
184 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &ib_desc,
185 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
186 IID_PPV_ARGS(&index_buffer.p))));
187 const auto upload_desc = buffer_desc(index_offset + index_bytes);
188 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc,
189 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
190 IID_PPV_ARGS(&upload.p))));
191 const auto readback_desc = buffer_desc(UINT64(pitch) * height);
192 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
193 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
194 IID_PPV_ARGS(&readback.p))));
195 D3D12_RESOURCE_DESC rt_desc{};
196 rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
197 rt_desc.Width = width;
198 rt_desc.Height = height;
199 rt_desc.DepthOrArraySize = 1;
200 rt_desc.MipLevels = 1;
201 rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
202 rt_desc.SampleDesc.Count = 1;
203 rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
204 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc,
205 D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p))));
206
207 std::uint8_t* up = nullptr;
208 EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&up))));
209 std::memcpy(up, mesh.data() + 8, vertex_bytes);
210 std::memcpy(up + index_offset, mesh.data() + 8 + vertex_bytes, index_bytes);
211
212 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
213 Ref<ID3D12DescriptorHeap> rtv_heap;
214 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p))));
215 const D3D12_CPU_DESCRIPTOR_HANDLE rtv{
216 SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(rtv_heap.p, 9))(rtv_heap.p))};
217 device->CreateRenderTargetView(target.p, nullptr, rtv);
218
219 D3D12_COMMAND_QUEUE_DESC queue_desc{};
220 Ref<ID3D12CommandQueue> queue;
221 Ref<ID3D12CommandAllocator> allocator;
222 Ref<ID3D12GraphicsCommandList> list;
223 Ref<ID3D12Fence> fence;
224 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
225 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
226 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p,
227 IID_PPV_ARGS(&list.p))));
228 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
229
230 list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, vertex_bytes);
231 list->CopyBufferRegion(index_buffer.p, 0, upload.p, index_offset, index_bytes);
232 D3D12_RESOURCE_BARRIER barriers[3] = {
233 transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER),
234 transition(index_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER),
235 transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)};
236 list->ResourceBarrier(3, barriers);
237 const FLOAT clear[4] = {-1, -1, -1, -1}; // vk_harness's clear: marks untouched pixels
238 list->ClearRenderTargetView(rtv, clear, 0, nullptr);
239
240 list->SetGraphicsRootSignature(root.p);
241 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
242 const D3D12_VERTEX_BUFFER_VIEW vbv{vertex_buffer->GetGPUVirtualAddress(), UINT(vertex_bytes), stride};
243 list->IASetVertexBuffers(0, 1, &vbv);
244 const D3D12_INDEX_BUFFER_VIEW ibv{index_buffer->GetGPUVirtualAddress(), UINT(index_bytes),
245 DXGI_FORMAT_R32_UINT};
246 list->IASetIndexBuffer(&ibv);
247 const D3D12_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1};
248 const D3D12_RECT scissor{0, 0, LONG(width), LONG(height)};
249 list->RSSetViewports(1, &viewport);
250 list->RSSetScissorRects(1, &scissor);
251 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
252 list->DrawIndexedInstanced(index_count, 1, 0, 0, 0);
253
254 D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET,
255 D3D12_RESOURCE_STATE_COPY_SOURCE);
256 list->ResourceBarrier(1, &to_copy);
257 D3D12_TEXTURE_COPY_LOCATION dst{};
258 dst.pResource = readback.p;
259 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
260 dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, width, height, 1, pitch}};
261 D3D12_TEXTURE_COPY_LOCATION src{};
262 src.pResource = target.p;
263 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
264 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
265 EXPECT(list->Close() == S_OK);
266 ID3D12CommandList* lists[] = {list.p};
267 queue->ExecuteCommandLists(1, lists);
268 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
269 EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)));
270 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
271 std::uint8_t* mapped = nullptr;
272 EXPECT(SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast<void**>(&mapped))));
273 for (UINT row = 0; row < height; ++row)
274 std::memcpy(&pixels[std::size_t(row) * width], mapped + std::size_t(row) * pitch, width * sizeof(Pixel));
275
276 for (auto* r : {&vertex_buffer, &index_buffer, &upload, &readback, &target}) r->reset();
277 pso.reset();
278 root.reset();
279 rtv_heap.reset();
280 list.reset();
281 allocator.reset();
282 queue.reset();
283 fence.reset();
284 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
285 }
286
287 // vk_harness's (x, y) is (x, H-1-y) here: same clip-space point, opposite viewport direction.
288 const auto at = [&](UINT x, UINT vk_y) -> const Pixel& { return pixels[std::size_t(height - 1 - vk_y) * width + x]; };
289 unsigned covered = 0;
290 for (const Pixel& p : pixels) covered += p[3] > 0.5f;
291 const double ratio = double(covered) / (double(width) * height);
292 std::printf("covered %u/%u (%.3f)\n", covered, width * height, ratio);
293 EXPECT(ratio >= number(manifest, "min_coverage", 0.0) && ratio <= number(manifest, "max_coverage", 1.0));
294 std::array<double, 2> clear_xy{}, centre_xy{}, centre_uv{};
295 if (pixel_of(manifest, "clear_pixel", clear_xy)) {
296 const Pixel& p = at(UINT(clear_xy[0]), UINT(clear_xy[1]));
297 const float want = float(number(manifest, "clear", -1.0));
298 std::printf("clear pixel (%u, %u): %g %g %g %g\n", UINT(clear_xy[0]), height - 1 - UINT(clear_xy[1]), p[0],
299 p[1], p[2], p[3]);
300 for (float c : p) EXPECT(std::fabs(c - want) <= 1e-5f);
301 }
302 if (pixel_of(manifest, "centre_uv", centre_uv)) {
303 if (!pixel_of(manifest, "centre_pixel", centre_xy)) centre_xy = {double(width / 2), double(height / 2)};
304 const Pixel& p = at(UINT(centre_xy[0]), UINT(centre_xy[1]));
305 std::printf("centre pixel (%u, %u): %.5f %.5f %.5f %.5f (mesh UV %.5f %.5f)\n", UINT(centre_xy[0]),
306 height - 1 - UINT(centre_xy[1]), p[0], p[1], p[2], p[3], centre_uv[0], centre_uv[1]);
307 const double want[4] = {centre_uv[0], centre_uv[1], 0.0, 1.0};
308 for (int c = 0; c < 4; ++c) EXPECT(std::fabs(p[c] - want[c]) <= 2e-3);
309 }
310 // first_light.py's probes: pixels where U and V differ, so a swapped or mirrored UV cannot pass (#1906).
311 if (const leonida::Json* probes = manifest.find("uv_probes"); probes && probes->kind == leonida::Json::Kind::array) {
312 for (const leonida::Json& probe : probes->array) {
313 std::array<double, 2> xy{}, uv{};
314 EXPECT(pixel_of(probe, "pixel", xy) && pixel_of(probe, "uv", uv));
315 const Pixel& p = at(UINT(xy[0]), UINT(xy[1]));
316 const double want[4] = {uv[0], uv[1], 0.0, 1.0};
317 for (int c = 0; c < 4; ++c) EXPECT(std::fabs(p[c] - want[c]) <= 2e-3);
318 }
319 std::printf("%zu UV probes match\n", probes->array.size());
320 }
321
322 // vk_harness's own image of the same draw, which first_light.py --run writes; required, so the whole-image check
323 // cannot be skipped silently. The PS exports with v_cvt_pkrtz_f16_f32 (round toward zero to f16), so an f32
324 // interpolant a few ulps apart, which the opposite viewport direction gives, can land on the adjacent f16 value:
325 // measured on an RTX 3060, 1 of 16,384 pixels, and vk_harness drawing the mesh mirrored in y reproduces this
326 // image bit for bit. Coverage (alpha) must match exactly.
327 const auto vk_raw = read_file(dir / "image.raw");
328 if (vk_raw.empty()) {
329 std::fprintf(stderr, "%s has no image.raw: run tools/first_light.py with --run first\n", dir.string().c_str());
330 return 1;
331 }
332 {
333 EXPECT(vk_raw.size() == pixels.size() * sizeof(Pixel));
334 // Both values must be exact halves (the PS exported f16) and adjacent in half order: ordered index = the
335 // half's bits for +, minus the magnitude bits for -, so 0x3bff and 0x3c00 are one step and so are 0 and 0x0001.
336 const auto half_index = [](float f, int& out) {
337 const float a = std::fabs(f);
338 if (!(a <= 65504.0f)) return false;
339 int e = 0;
340 const float m = std::frexp(a, &e); // a = m * 2^e, m in [0.5, 1)
341 int bits;
342 if (a == 0.0f) {
343 bits = 0;
344 } else if (e <= -14) { // subnormal half: a = k * 2^-24
345 const float k = std::ldexp(a, 24);
346 if (k != std::floor(k)) return false;
347 bits = int(k);
348 } else {
349 const float k = std::ldexp(m, 11); // 11 significant bits, implicit one included
350 if (k != std::floor(k)) return false;
351 bits = ((e + 14) << 10) | (int(k) & 0x3ff);
352 }
353 out = std::signbit(f) ? -bits : bits;
354 return true;
355 };
356 const auto one_f16_step = [&](float a, float b) {
357 int ia = 0, ib = 0;
358 return half_index(a, ia) && half_index(b, ib) && std::abs(ia - ib) <= 1;
359 };
360 EXPECT(one_f16_step(1.0f, 0.99951171875f) && !one_f16_step(1.0f, 0.9990234375f)); // 0x3c00 vs 0x3bff, 0x3bfe
361 EXPECT(one_f16_step(0.0f, 5.9604645e-8f) && !one_f16_step(0.0f, 1.1920929e-7f)); // 0 vs 0x0001, 0x0002
362 unsigned exact = 0, f16_step = 0, differ = 0;
363 for (UINT y = 0; y < height; ++y) {
364 for (UINT x = 0; x < width; ++x) {
365 Pixel want;
366 std::memcpy(want.data(), vk_raw.data() + (std::size_t(y) * width + x) * sizeof(Pixel), sizeof(Pixel));
367 const Pixel& got = at(x, y);
368 if (std::memcmp(got.data(), want.data(), sizeof(Pixel)) == 0) {
369 ++exact;
370 continue;
371 }
372 const bool close = got[3] == want[3] && one_f16_step(got[0], want[0]) &&
373 one_f16_step(got[1], want[1]) && one_f16_step(got[2], want[2]);
374 ++(close ? f16_step : differ);
375 std::fprintf(stderr, "vk_harness (%u, %u): %g %g %g %g, here (%u, %u): %g %g %g %g%s\n", x, y,
376 want[0], want[1], want[2], want[3], x, height - 1 - y, got[0], got[1], got[2], got[3],
377 close ? " (one f16 step)" : "");
378 if (differ > 8) return 1;
379 }
380 }
381 std::printf("against vk_harness's image.raw (rows flipped): %u of %u pixels bit-exact, %u one f16 step apart, "
382 "%u different\n", exact, width * height, f16_step, differ);
383 EXPECT(differ == 0);
384 // An adjacent half only appears where the f32 interpolant sits a few ulps from an f16 truncation boundary,
385 // about 2^-11 of values per channel: 1 pixel of 12,804 covered on the RTX 3060. Allow at most one covered
386 // pixel in a thousand, so a regression that moves the whole image by one half step (thousands) fails.
387 EXPECT(f16_step <= covered / 1000);
388 }
389 if (d.validation_errors()) {
390 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
391 return 1;
392 }
393 std::printf("first light through D3D12: the game's VS+PS found by FSSM hash drew %u triangles\n", index_count / 3);
394 return 0;
395}
diff --git a/runtime/test/d3d12_shader_cache_test.cpp b/runtime/test/d3d12_shader_cache_test.cpp
new file mode 100644
index 000000000..94b0aa5b9
--- /dev/null
+++ b/runtime/test/d3d12_shader_cache_test.cpp
@@ -0,0 +1,322 @@
1// Synthetic test for ID3D12Device9::CreateShaderCacheSession, ID3D12ShaderCacheSession
2// (FindValue, StoreValue, SetDeleteOnDestroy, GetDesc), and ID3D12Device9::ShaderCacheControl (D3D-34).
3// Compares argument validation, StoreValue/FindValue semantics, size queries, duplicate rejection,
4// shared-session visibility, and SetDeleteOnDestroy against the host Windows D3D12 runtime when available.
5// No game data.
6#include "vk_test_device.h"
7#include "d3d12_copy_compare.h"
8#include "../shims/d3d12_com.h"
9
10#include <cstdint>
11#include <cstdio>
12#include <cstring>
13#include <filesystem>
14#include <vector>
15
16#define EXPECT(condition) do { \
17 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
18} while (0)
19
20namespace {
21
22template<typename T>
23struct Ref {
24 T* p = nullptr;
25 ~Ref() { reset(); }
26 void reset() { if (p) { p->Release(); p = nullptr; } }
27 T* operator->() const { return p; }
28};
29
30int exercise_shader_cache(ID3D12Device9* dev, const char* label) {
31 // {7c83f2a1-4b5e-4d19-9a32-1f2e3d4c5b6a}
32 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 zero_id{};
35
36 D3D12_SHADER_CACHE_SESSION_DESC desc{};
37 desc.Identifier = id1;
38 desc.Mode = D3D12_SHADER_CACHE_MODE_MEMORY;
39 desc.Flags = D3D12_SHADER_CACHE_FLAG_NONE;
40 desc.Version = 1;
41
42 // 1. CreateShaderCacheSession argument validation & capability check (null output -> S_FALSE).
43 EXPECT(dev->CreateShaderCacheSession(nullptr, __uuidof(ID3D12ShaderCacheSession), nullptr) == E_INVALIDARG);
44 EXPECT(dev->CreateShaderCacheSession(&desc, __uuidof(ID3D12ShaderCacheSession), nullptr) == S_FALSE);
45
46 D3D12_SHADER_CACHE_SESSION_DESC bad = desc;
47 bad.Identifier = zero_id;
48 Ref<ID3D12ShaderCacheSession> bad_s;
49 EXPECT(dev->CreateShaderCacheSession(&bad, IID_PPV_ARGS(&bad_s.p)) == E_INVALIDARG && !bad_s.p);
50 EXPECT(dev->CreateShaderCacheSession(&bad, __uuidof(ID3D12ShaderCacheSession), nullptr) == E_INVALIDARG);
51
52 bad = desc;
53 bad.Mode = static_cast<D3D12_SHADER_CACHE_MODE>(2);
54 EXPECT(dev->CreateShaderCacheSession(&bad, IID_PPV_ARGS(&bad_s.p)) == E_INVALIDARG && !bad_s.p);
55
56 bad = desc;
57 bad.Flags = static_cast<D3D12_SHADER_CACHE_FLAGS>(0x4);
58 EXPECT(dev->CreateShaderCacheSession(&bad, IID_PPV_ARGS(&bad_s.p)) == E_INVALIDARG && !bad_s.p);
59
60 void* wrong_iid = nullptr;
61 EXPECT(dev->CreateShaderCacheSession(&desc, __uuidof(ID3D12Fence), &wrong_iid) == E_NOINTERFACE && !wrong_iid);
62
63 // 2. StoreValue / FindValue / GetDesc / GetDevice.
64 Ref<ID3D12ShaderCacheSession> s1;
65 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s1.p))) && s1.p);
66 const D3D12_SHADER_CACHE_SESSION_DESC got = s1->GetDesc();
67 EXPECT(std::memcmp(&got.Identifier, &desc.Identifier, sizeof(GUID)) == 0);
68 EXPECT(got.Mode == desc.Mode && got.Flags == desc.Flags && got.Version == desc.Version);
69 Ref<ID3D12Device> parent;
70 EXPECT(SUCCEEDED(s1->GetDevice(IID_PPV_ARGS(&parent.p))) && parent.p);
71
72 const std::uint32_t k1 = 0x12345678u;
73 const std::uint32_t v1 = 0xCAFEBABEu;
74 std::uint32_t out_v = 0;
75 UINT sz = sizeof(out_v);
76 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND);
77 EXPECT(sz == sizeof(out_v));
78 EXPECT(s1->FindValue(nullptr, sizeof(k1), &out_v, &sz) == E_INVALIDARG);
79 EXPECT(s1->FindValue(&k1, 0, &out_v, &sz) == E_INVALIDARG);
80 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, nullptr) == E_INVALIDARG);
81
82 EXPECT(s1->StoreValue(nullptr, sizeof(k1), &v1, sizeof(v1)) == E_INVALIDARG);
83 EXPECT(s1->StoreValue(&k1, 0, &v1, sizeof(v1)) == E_INVALIDARG);
84 EXPECT(s1->StoreValue(&k1, sizeof(k1), nullptr, sizeof(v1)) == E_INVALIDARG);
85 EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, 0) == E_INVALIDARG);
86 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);
88
89 // Size query (pValue == nullptr) returns S_OK and writes stored size.
90 sz = 0;
91 EXPECT(s1->FindValue(&k1, sizeof(k1), nullptr, &sz) == S_OK && sz == sizeof(v1));
92 sz = 2;
93 EXPECT(s1->FindValue(&k1, sizeof(k1), nullptr, &sz) == S_OK && sz == sizeof(v1));
94 // Non-null buffer too small returns DXGI_ERROR_MORE_DATA and writes required size.
95 sz = 2;
96 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_MORE_DATA && sz == sizeof(v1));
97 // Oversized buffer returns S_OK, writes exact stored size, and copies payload.
98 sz = 8;
99 out_v = 0;
100 EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, &sz) == S_OK && sz == sizeof(v1) && out_v == v1);
101
102 // 3. Shared store across sessions with the same (Identifier, Mode, Version) + SetDeleteOnDestroy.
103 Ref<ID3D12ShaderCacheSession> s2;
104 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s2.p))) && s2.p);
105 sz = sizeof(out_v);
106 out_v = 0;
107 EXPECT(s2->FindValue(&k1, sizeof(k1), &out_v, &sz) == S_OK && sz == sizeof(v1) && out_v == v1);
108
109 // Different Identifier does not see k1.
110 D3D12_SHADER_CACHE_SESSION_DESC desc2 = desc;
111 desc2.Identifier = id2;
112 Ref<ID3D12ShaderCacheSession> other;
113 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc2, IID_PPV_ARGS(&other.p))) && other.p);
114 sz = sizeof(out_v);
115 EXPECT(other->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND);
116 other->SetDeleteOnDestroy();
117 other.reset();
118
119 // Marking s1 delete-on-destroy keeps data alive while s2 is still open, then deletes once s2 releases.
120 s1->SetDeleteOnDestroy();
121 s1.reset();
122 sz = sizeof(out_v);
123 out_v = 0;
124 EXPECT(s2->FindValue(&k1, sizeof(k1), &out_v, &sz) == S_OK && sz == sizeof(v1) && out_v == v1);
125 s2.reset();
126
127 Ref<ID3D12ShaderCacheSession> s3;
128 EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s3.p))) && s3.p);
129 sz = sizeof(out_v);
130 EXPECT(s3->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND);
131 s3->SetDeleteOnDestroy();
132 s3.reset();
133
134 // 4. ShaderCacheControl invalid-argument checks (same on host and layer).
135 EXPECT(dev->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAGS(0), D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE) ==
136 E_INVALIDARG);
137 EXPECT(dev->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
138 D3D12_SHADER_CACHE_CONTROL_FLAGS(0)) == E_INVALIDARG);
139 EXPECT(dev->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
140 D3D12_SHADER_CACHE_CONTROL_FLAGS(0x8)) == E_INVALIDARG);
141 EXPECT(dev->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
142 D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE | D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) ==
143 E_INVALIDARG);
144
145 std::printf("shader cache (%s): validation, StoreValue/FindValue, size queries, sharing and SetDeleteOnDestroy OK\n",
146 label);
147 return 0;
148}
149
150} // namespace
151
152int main() {
153 vktest::Device d;
154 const auto status = d.initialize();
155 if (status == vktest::DeviceStatus::unavailable) {
156 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
157 return 77;
158 }
159 EXPECT(status == vktest::DeviceStatus::ready);
160
161 rt::d3d12::VulkanDeviceInfo info{};
162 info.get_instance_proc = d.instance_proc;
163 info.instance = d.instance;
164 info.physical = d.physical;
165 info.device = d.device;
166 info.queue = d.queue;
167 info.queue_family = d.family;
168 info.buffer_device_address = true;
169
170 Ref<ID3D12Device9> device;
171 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
172 EXPECT(exercise_shader_cache(device.p, "Vulkan layer") == 0);
173
174 // Layer-specific ShaderCacheControl CLEAR / DISABLE / ENABLE and entry/byte limit checks.
175 {
176 const GUID id_ctrl = {0x4a12b3c4, 0x5d6e, 0x47f8, {0x90, 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07}};
177 D3D12_SHADER_CACHE_SESSION_DESC desc{};
178 desc.Identifier = id_ctrl;
179 desc.Mode = D3D12_SHADER_CACHE_MODE_MEMORY;
180 desc.MaximumInMemoryCacheEntries = 1;
181 desc.MaximumInMemoryCacheSizeBytes = 8;
182 Ref<ID3D12ShaderCacheSession> s;
183 EXPECT(SUCCEEDED(device->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s.p))) && s.p);
184
185 const std::uint32_t k1 = 1, k2 = 2;
186 const std::uint64_t v1 = 0x1122334455667788ull;
187 EXPECT(s->StoreValue(&k1, sizeof(k1), &v1, sizeof(v1)) == S_OK);
188 EXPECT(s->StoreValue(&k2, sizeof(k2), &v1, sizeof(v1)) == E_OUTOFMEMORY);
189
190 EXPECT(device->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
191 D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) == S_OK);
192 std::uint64_t out = 0;
193 UINT sz = sizeof(out);
194 EXPECT(s->FindValue(&k1, sizeof(k1), &out, &sz) == DXGI_ERROR_NOT_FOUND);
195
196 EXPECT(device->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
197 D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE) == S_OK);
198 sz = sizeof(out);
199 EXPECT(s->FindValue(&k1, sizeof(k1), &out, &sz) == S_OK && out == v1);
200
201 EXPECT(device->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
202 D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR) == S_OK);
203 sz = sizeof(out);
204 EXPECT(s->FindValue(&k1, sizeof(k1), &out, &sz) == DXGI_ERROR_NOT_FOUND);
205 s->SetDeleteOnDestroy();
206 }
207
208 // Cross-device process-wide sharing: two distinct ID3D12Device9 objects in the same process share the store.
209 {
210 const GUID id_shared = {0x99887766, 0x5544, 0x4321, {0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89}};
211 D3D12_SHADER_CACHE_SESSION_DESC desc{};
212 desc.Identifier = id_shared;
213 desc.Mode = D3D12_SHADER_CACHE_MODE_MEMORY;
214 desc.Version = 2;
215
216 Ref<ID3D12Device9> device2;
217 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device2.p))));
218 Ref<ID3D12ShaderCacheSession> s_dev1, s_dev2;
219 EXPECT(SUCCEEDED(device->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s_dev1.p))) && s_dev1.p);
220 EXPECT(SUCCEEDED(device2->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s_dev2.p))) && s_dev2.p);
221
222 const std::uint32_t k = 0x55AA1234u;
223 const std::uint64_t v = 0xDEADBEEFCAFEBABEull;
224 EXPECT(s_dev1->StoreValue(&k, sizeof(k), &v, sizeof(v)) == S_OK);
225 std::uint64_t out = 0;
226 UINT sz = sizeof(out);
227 EXPECT(s_dev2->FindValue(&k, sizeof(k), &out, &sz) == S_OK && sz == sizeof(v) && out == v);
228 s_dev1->SetDeleteOnDestroy();
229 s_dev1.reset();
230 s_dev2.reset();
231 device2.reset();
232 }
233
234 // D3D12_SHADER_CACHE_MODE_DISK persistence across session + device teardown and cleanup on SetDeleteOnDestroy.
235 {
236 const auto prev_cwd = std::filesystem::current_path();
237 const auto temp_dir = std::filesystem::temp_directory_path() / L"leonida_shader_cache_disk_test";
238 std::error_code ec;
239 std::filesystem::remove_all(temp_dir, ec);
240 std::filesystem::create_directories(temp_dir);
241 struct RestoreCwd {
242 std::filesystem::path prev;
243 std::filesystem::path dir;
244 ~RestoreCwd() {
245 std::error_code e;
246 std::filesystem::current_path(prev, e);
247 std::filesystem::remove_all(dir, e);
248 }
249 } restore_cwd{prev_cwd, temp_dir};
250 std::filesystem::current_path(temp_dir);
251
252 const GUID id_disk = {0x31415926, 0x5358, 0x4979, {0x83, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27}};
253 D3D12_SHADER_CACHE_SESSION_DESC disk_desc{};
254 disk_desc.Identifier = id_disk;
255 disk_desc.Mode = D3D12_SHADER_CACHE_MODE_DISK;
256 disk_desc.Flags = D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR;
257 disk_desc.Version = 7;
258
259 const std::uint32_t k = 0x0F1E2D3Cu;
260 const std::uint64_t v = 0x0123456789ABCDEFull;
261 {
262 Ref<ID3D12Device9> dev_a;
263 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev_a.p))));
264 Ref<ID3D12ShaderCacheSession> s_a;
265 EXPECT(SUCCEEDED(dev_a->CreateShaderCacheSession(&disk_desc, IID_PPV_ARGS(&s_a.p))) && s_a.p);
266 EXPECT(s_a->StoreValue(&k, sizeof(k), &v, sizeof(v)) == S_OK);
267 }
268 // After dev_a and s_a are destroyed, the cache file must exist on disk and reload into a brand-new device.
269 bool found_file = false;
270 for (const auto& entry : std::filesystem::directory_iterator(temp_dir)) {
271 if (entry.is_regular_file() && entry.path().extension() == L".bin") found_file = true;
272 }
273 EXPECT(found_file);
274 {
275 Ref<ID3D12Device9> dev_b;
276 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev_b.p))));
277 Ref<ID3D12ShaderCacheSession> s_b;
278 EXPECT(SUCCEEDED(dev_b->CreateShaderCacheSession(&disk_desc, IID_PPV_ARGS(&s_b.p))) && s_b.p);
279 std::uint64_t out = 0;
280 UINT sz = sizeof(out);
281 EXPECT(s_b->FindValue(&k, sizeof(k), &out, &sz) == S_OK && sz == sizeof(v) && out == v);
282 s_b->SetDeleteOnDestroy();
283 }
284 // After SetDeleteOnDestroy + release, the file must be gone and a fresh session must miss.
285 bool file_remains = false;
286 for (const auto& entry : std::filesystem::directory_iterator(temp_dir)) {
287 if (entry.is_regular_file() && entry.path().extension() == L".bin") file_remains = true;
288 }
289 EXPECT(!file_remains);
290 {
291 Ref<ID3D12Device9> dev_c;
292 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev_c.p))));
293 Ref<ID3D12ShaderCacheSession> s_c;
294 EXPECT(SUCCEEDED(dev_c->CreateShaderCacheSession(&disk_desc, IID_PPV_ARGS(&s_c.p))) && s_c.p);
295 std::uint64_t out = 0;
296 UINT sz = sizeof(out);
297 EXPECT(s_c->FindValue(&k, sizeof(k), &out, &sz) == DXGI_ERROR_NOT_FOUND);
298 s_c->SetDeleteOnDestroy();
299 }
300 std::printf("shader cache (disk persistence + cross-device sharing): OK\n");
301 }
302
303 // Compare the same scenarios against the host Windows D3D12 runtime when ID3D12Device9 is available.
304 {
305 copycmp::Ptr<ID3D12Device> host;
306 std::string adapter_name;
307 if (copycmp::create_host(host, adapter_name)) {
308 Ref<ID3D12Device9> host9;
309 if (SUCCEEDED(host.p->QueryInterface(IID_PPV_ARGS(&host9.p))) && host9.p) {
310 EXPECT(exercise_shader_cache(host9.p, adapter_name.c_str()) == 0);
311 }
312 }
313 }
314
315 device.reset();
316 if (d.validation_errors()) {
317 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
318 return 1;
319 }
320 std::printf("d3d12_shader_cache_test: passed (0 validation errors)\n");
321 return 0;
322}
diff --git a/runtime/test/d3d12_texture1d_test.cpp b/runtime/test/d3d12_texture1d_test.cpp
new file mode 100644
index 000000000..007c513b4
--- /dev/null
+++ b/runtime/test/d3d12_texture1d_test.cpp
@@ -0,0 +1,272 @@
1// Minimal smoke test for D3D12 1D texture creation and RTV/DSV/SRV/UAV views.
2
3#include "../shims/d3d12_com.h"
4#include "../src/gfx10_descriptors.h"
5
6#include <cstdio>
7#include <cstring>
8
9namespace {
10
11int fail(const char* msg, HRESULT hr = S_OK) {
12 std::fprintf(stderr, "FAIL: %s (hr=0x%08X)\n", msg, static_cast<unsigned>(hr));
13 return 1;
14}
15
16D3D12_HEAP_PROPERTIES default_heap() {
17 D3D12_HEAP_PROPERTIES hp{};
18 hp.Type = D3D12_HEAP_TYPE_DEFAULT;
19 return hp;
20}
21
22} // namespace
23
24int main() {
25 ID3D12Device* dev = nullptr;
26 HRESULT hr = rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&dev));
27 if (FAILED(hr) || !dev) {
28 std::printf("SKIP: no Vulkan device (hr=0x%08X)\n", static_cast<unsigned>(hr));
29 return 77;
30 }
31
32 D3D12_DESCRIPTOR_HEAP_DESC cbv_heap_desc{};
33 cbv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
34 cbv_heap_desc.NumDescriptors = 8;
35 ID3D12DescriptorHeap* cbv_heap = nullptr;
36 hr = dev->CreateDescriptorHeap(&cbv_heap_desc, IID_PPV_ARGS(&cbv_heap));
37 if (FAILED(hr) || !cbv_heap) return fail("CreateDescriptorHeap(CBV_SRV_UAV)", hr);
38
39 D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{};
40 rtv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
41 rtv_heap_desc.NumDescriptors = 2;
42 ID3D12DescriptorHeap* rtv_heap = nullptr;
43 hr = dev->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap));
44 if (FAILED(hr) || !rtv_heap) return fail("CreateDescriptorHeap(RTV)", hr);
45
46 D3D12_DESCRIPTOR_HEAP_DESC dsv_heap_desc{};
47 dsv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
48 dsv_heap_desc.NumDescriptors = 2;
49 ID3D12DescriptorHeap* dsv_heap = nullptr;
50 hr = dev->CreateDescriptorHeap(&dsv_heap_desc, IID_PPV_ARGS(&dsv_heap));
51 if (FAILED(hr) || !dsv_heap) return fail("CreateDescriptorHeap(DSV)", hr);
52
53 const UINT cbv_inc = dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
54 const UINT rtv_inc = dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
55 const UINT dsv_inc = dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
56
57 // 1D color texture (DepthOrArraySize = 1) and 1D array (DepthOrArraySize = 4)
58 D3D12_RESOURCE_DESC tex1d_single_desc{};
59 tex1d_single_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D;
60 tex1d_single_desc.Width = 64;
61 tex1d_single_desc.Height = 1;
62 tex1d_single_desc.DepthOrArraySize = 1;
63 tex1d_single_desc.MipLevels = 2;
64 tex1d_single_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
65 tex1d_single_desc.SampleDesc = {1, 0};
66 tex1d_single_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
67 tex1d_single_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
68
69 D3D12_RESOURCE_DESC tex1d_desc = tex1d_single_desc;
70 tex1d_desc.DepthOrArraySize = 4;
71
72 ID3D12Resource* tex1d_single = nullptr;
73 ID3D12Resource* tex1d = nullptr;
74 const D3D12_HEAP_PROPERTIES hp = default_heap();
75 hr = dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &tex1d_single_desc, D3D12_RESOURCE_STATE_COMMON,
76 nullptr, IID_PPV_ARGS(&tex1d_single));
77 if (FAILED(hr) || !tex1d_single) return fail("CreateCommittedResource(TEXTURE1D single)", hr);
78 hr = dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &tex1d_desc, D3D12_RESOURCE_STATE_COMMON,
79 nullptr, IID_PPV_ARGS(&tex1d));
80 if (FAILED(hr) || !tex1d) return fail("CreateCommittedResource(TEXTURE1D array)", hr);
81
82 D3D12_CPU_DESCRIPTOR_HANDLE cbv_cpu = cbv_heap->GetCPUDescriptorHandleForHeapStart();
83 D3D12_CPU_DESCRIPTOR_HANDLE rtv_cpu = rtv_heap->GetCPUDescriptorHandleForHeapStart();
84 D3D12_CPU_DESCRIPTOR_HANDLE dsv_cpu = dsv_heap->GetCPUDescriptorHandleForHeapStart();
85
86 // SRV: default (nullptr) on 1D single, explicit TEXTURE1D on 1D single (mip 1) and array (slice 0)
87 dev->CreateShaderResourceView(tex1d_single, nullptr, cbv_cpu);
88
89 D3D12_SHADER_RESOURCE_VIEW_DESC srv1d_mip1{};
90 srv1d_mip1.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
91 srv1d_mip1.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D;
92 srv1d_mip1.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
93 srv1d_mip1.Texture1D.MostDetailedMip = 1;
94 srv1d_mip1.Texture1D.MipLevels = 1;
95 dev->CreateShaderResourceView(tex1d_single, &srv1d_mip1, {cbv_cpu.ptr + cbv_inc * 1});
96
97 D3D12_SHADER_RESOURCE_VIEW_DESC srv1d{};
98 srv1d.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
99 srv1d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D;
100 srv1d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
101 srv1d.Texture1D.MipLevels = 2;
102 dev->CreateShaderResourceView(tex1d, &srv1d, {cbv_cpu.ptr + cbv_inc * 2});
103
104 // UAV: default (nullptr) on 1D single, explicit TEXTURE1D on 1D single (mip 0) and array (slice 0, mip 1)
105 dev->CreateUnorderedAccessView(tex1d_single, nullptr, nullptr, {cbv_cpu.ptr + cbv_inc * 3});
106
107 D3D12_UNORDERED_ACCESS_VIEW_DESC uav1d_single{};
108 uav1d_single.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
109 uav1d_single.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D;
110 uav1d_single.Texture1D.MipSlice = 0;
111 dev->CreateUnorderedAccessView(tex1d_single, nullptr, &uav1d_single, {cbv_cpu.ptr + cbv_inc * 4});
112
113 D3D12_UNORDERED_ACCESS_VIEW_DESC uav1d{};
114 uav1d.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
115 uav1d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D;
116 uav1d.Texture1D.MipSlice = 1;
117 dev->CreateUnorderedAccessView(tex1d, nullptr, &uav1d, {cbv_cpu.ptr + cbv_inc * 5});
118
119 // Default (nullptr) SRV and UAV on a 1D array must write a null descriptor (set 0 has no 1D-array binding).
120 std::memset(reinterpret_cast<void*>(cbv_cpu.ptr + cbv_inc * 6), 0x77, cbv_inc * 2);
121 dev->CreateShaderResourceView(tex1d, nullptr, {cbv_cpu.ptr + cbv_inc * 6});
122 dev->CreateUnorderedAccessView(tex1d, nullptr, nullptr, {cbv_cpu.ptr + cbv_inc * 7});
123
124 namespace g = leonida::gfx10;
125 const auto decode_and_lookup = [&](UINT slot, g::Image& img) {
126 g::ImageWords words{};
127 std::memcpy(words.data(), reinterpret_cast<const void*>(cbv_cpu.ptr + cbv_inc * slot), sizeof(words));
128 if (!g::is_image(words) || !g::decode(words, img)) return false;
129 std::uint32_t key[8]{};
130 std::memcpy(key, words.data(), sizeof(key));
131 return rt::d3d12::bindless_hash_lookup(dev, key) != 0;
132 };
133 g::Image img{};
134 if (!decode_and_lookup(0, img) || img.type != g::ImageType::image_1d || img.width != 64 || img.mip_count != 2 ||
135 img.layer_count != 1)
136 return fail("default 1D SRV T# or bindless lookup mismatch");
137 if (!decode_and_lookup(1, img) || img.type != g::ImageType::image_1d || img.first_mip != 1 ||
138 img.mip_count != 1 || img.layer_count != 1)
139 return fail("explicit 1D mip-1 SRV T# or bindless lookup mismatch");
140 if (!decode_and_lookup(2, img) || img.type != g::ImageType::image_1d || img.layer_count != 1 || img.mip_count != 2)
141 return fail("explicit 1D SRV on array T# or bindless lookup mismatch");
142 if (!decode_and_lookup(3, img) || img.type != g::ImageType::image_1d || img.mip_count != 1 || img.layer_count != 1)
143 return fail("default 1D UAV T# or bindless lookup mismatch");
144 if (!decode_and_lookup(4, img) || img.type != g::ImageType::image_1d || img.first_mip != 0 ||
145 img.mip_count != 1 || img.layer_count != 1)
146 return fail("explicit 1D UAV T# or bindless lookup mismatch");
147 if (!decode_and_lookup(5, img) || img.type != g::ImageType::image_1d || img.first_mip != 1 || img.mip_count != 1 ||
148 img.layer_count != 1)
149 return fail("explicit 1D UAV on array T# or bindless lookup mismatch");
150 for (UINT slot = 6; slot < 8; ++slot) {
151 const auto* bytes = reinterpret_cast<const std::uint8_t*>(cbv_cpu.ptr + cbv_inc * slot);
152 for (UINT b = 0; b < 32; ++b)
153 if (bytes[b] != 0) return fail("default 1DArray view should write a null descriptor");
154 }
155
156 // RTV / DSV 1D bounds validation (out-of-bounds mip/slice must write a null TargetView)
157 D3D12_RENDER_TARGET_VIEW_DESC bad_rtv{};
158 bad_rtv.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
159 bad_rtv.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY;
160 bad_rtv.Texture1DArray.MipSlice = 5;
161 bad_rtv.Texture1DArray.FirstArraySlice = 0;
162 bad_rtv.Texture1DArray.ArraySize = 1;
163 dev->CreateRenderTargetView(tex1d, &bad_rtv, {rtv_cpu.ptr + rtv_inc});
164 if (*reinterpret_cast<const std::uint64_t*>(rtv_cpu.ptr + rtv_inc) != 0)
165 return fail("out-of-bounds 1D RTV should be null");
166
167 D3D12_DEPTH_STENCIL_VIEW_DESC bad_dsv{};
168 bad_dsv.Format = DXGI_FORMAT_D32_FLOAT;
169 bad_dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1DARRAY;
170 bad_dsv.Texture1DArray.MipSlice = 0;
171 bad_dsv.Texture1DArray.FirstArraySlice = 4;
172 bad_dsv.Texture1DArray.ArraySize = 1;
173 dev->CreateDepthStencilView(tex1d, &bad_dsv, {dsv_cpu.ptr + dsv_inc});
174 if (*reinterpret_cast<const std::uint64_t*>(dsv_cpu.ptr + dsv_inc) != 0)
175 return fail("out-of-bounds 1D DSV should be null");
176
177 // GPU round-trip: upload buffer -> CopyTextureRegion -> TEXTURE1D -> CopyTextureRegion -> readback buffer
178 D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
179 UINT num_rows = 0;
180 UINT64 row_bytes = 0, total_bytes = 0;
181 dev->GetCopyableFootprints(&tex1d_desc, 0, 1, 0, &footprint, &num_rows, &row_bytes, &total_bytes);
182 if (total_bytes == 0 || footprint.Footprint.Height != 1 || footprint.Footprint.Depth != 1) {
183 return fail("GetCopyableFootprints(TEXTURE1D)");
184 }
185
186 D3D12_HEAP_PROPERTIES upload_hp{D3D12_HEAP_TYPE_UPLOAD};
187 D3D12_HEAP_PROPERTIES readback_hp{D3D12_HEAP_TYPE_READBACK};
188 D3D12_RESOURCE_DESC buf_desc{};
189 buf_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
190 buf_desc.Width = total_bytes;
191 buf_desc.Height = 1;
192 buf_desc.DepthOrArraySize = 1;
193 buf_desc.MipLevels = 1;
194 buf_desc.Format = DXGI_FORMAT_UNKNOWN;
195 buf_desc.SampleDesc = {1, 0};
196 buf_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
197
198 ID3D12Resource* upload_buf = nullptr;
199 ID3D12Resource* readback_buf = nullptr;
200 hr = dev->CreateCommittedResource(&upload_hp, D3D12_HEAP_FLAG_NONE, &buf_desc,
201 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload_buf));
202 if (FAILED(hr) || !upload_buf) return fail("CreateCommittedResource(upload)", hr);
203 hr = dev->CreateCommittedResource(&readback_hp, D3D12_HEAP_FLAG_NONE, &buf_desc,
204 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback_buf));
205 if (FAILED(hr) || !readback_buf) return fail("CreateCommittedResource(readback)", hr);
206
207 unsigned char* mapped = nullptr;
208 hr = upload_buf->Map(0, nullptr, reinterpret_cast<void**>(&mapped));
209 if (FAILED(hr) || !mapped) return fail("upload_buf->Map", hr);
210 for (UINT i = 0; i < 64 * 4; ++i) mapped[i] = static_cast<unsigned char>((i * 7 + 13) & 0xFF);
211 upload_buf->Unmap(0, nullptr);
212
213 D3D12_COMMAND_QUEUE_DESC qd{};
214 ID3D12CommandQueue* queue = nullptr;
215 ID3D12CommandAllocator* alloc = nullptr;
216 ID3D12GraphicsCommandList* cmd = nullptr;
217 ID3D12Fence* fence = nullptr;
218 if (FAILED(hr = dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue)))) return fail("CreateCommandQueue", hr);
219 if (FAILED(hr = dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc))))
220 return fail("CreateCommandAllocator", hr);
221 if (FAILED(hr = dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc, nullptr, IID_PPV_ARGS(&cmd))))
222 return fail("CreateCommandList", hr);
223 if (FAILED(hr = dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return fail("CreateFence", hr);
224
225 D3D12_TEXTURE_COPY_LOCATION src_loc{upload_buf, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, footprint};
226 D3D12_TEXTURE_COPY_LOCATION dst_loc{tex1d, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
227 cmd->CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, nullptr);
228
229 D3D12_RESOURCE_BARRIER barrier{};
230 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
231 barrier.Transition = {tex1d, 0, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE};
232 cmd->ResourceBarrier(1, &barrier);
233
234 D3D12_TEXTURE_COPY_LOCATION rb_loc{readback_buf, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, footprint};
235 cmd->CopyTextureRegion(&rb_loc, 0, 0, 0, &dst_loc, nullptr);
236 if (FAILED(hr = cmd->Close())) return fail("cmd->Close", hr);
237
238 ID3D12CommandList* lists[] = {cmd};
239 queue->ExecuteCommandLists(1, lists);
240 HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr);
241 if (FAILED(hr = queue->Signal(fence, 1))) return fail("queue->Signal", hr);
242 if (fence->GetCompletedValue() < 1) {
243 fence->SetEventOnCompletion(1, ev);
244 WaitForSingleObject(ev, INFINITE);
245 }
246 CloseHandle(ev);
247
248 unsigned char* rb_mapped = nullptr;
249 hr = readback_buf->Map(0, nullptr, reinterpret_cast<void**>(&rb_mapped));
250 if (FAILED(hr) || !rb_mapped) return fail("readback_buf->Map", hr);
251 for (UINT i = 0; i < 64 * 4; ++i) {
252 const unsigned char expected = static_cast<unsigned char>((i * 7 + 13) & 0xFF);
253 if (rb_mapped[i] != expected) return fail("1D texture readback mismatch");
254 }
255 readback_buf->Unmap(0, nullptr);
256
257 fence->Release();
258 cmd->Release();
259 alloc->Release();
260 queue->Release();
261 readback_buf->Release();
262 upload_buf->Release();
263 tex1d->Release();
264 tex1d_single->Release();
265 dsv_heap->Release();
266 rtv_heap->Release();
267 cbv_heap->Release();
268 dev->Release();
269
270 std::printf("PASS: d3d12_texture1d_test (1D/1DArray SRV, UAV + CopyTextureRegion round-trip)\n");
271 return 0;
272}
diff --git a/runtime/test/d3d12_typeless_families_test.cpp b/runtime/test/d3d12_typeless_families_test.cpp
new file mode 100644
index 000000000..936fbbbee
--- /dev/null
+++ b/runtime/test/d3d12_typeless_families_test.cpp
@@ -0,0 +1,416 @@
1// Typed RTVs of every TYPELESS color family (D3D-275): ClearRenderTargetView through an RTV in each typed format of
2// the family, read back byte for byte and compared with the host's D3D12 on the same adapter (matched by LUID, the
3// D3D-188 rule) and with WARP. Before D3D-275 only the RGBA8 family was reinterpreted: an R16_UINT or R32G32_UINT RTV
4// of a typeless texture cleared through the resource's own (float or UNORM) format.
5// Then draws: a full-screen pass writing a constant (integers for UINT views, floats for FLOAT and UNORM ones) into a
6// typed RTV of a typeless texture, whose PSO names the typed format, compared with the same pass on the host (HLSL
7// compiled by d3dcompiler_47). The layer's shaders are GLSL stand-ins for translated ones (test/glsl/vs_fullscreen.vert,
8// ps_typeless_float.frag, ps_typeless_uint.frag), found by the FSSM hash of their containers in a translator-style
9// index; without glslangValidator at build time only the clears run.
10// A view format the layer does not map yet (its CheckFeatureSupport gives no RENDER_TARGET) is reported and skipped,
11// so the R8 family and the 16-bit integer and normalized formats are covered as soon as their mapping lands.
12// Synthetic data only. LEONIDA_VK_VALIDATION=1 runs it under VK_LAYER_KHRONOS_validation.
13#include "vk_test_device.h"
14#include "host_wine.h"
15#include "../shims/d3d12_com.h"
16#if defined(LEONIDA_TYPELESS_VS_SPV)
17#include "d3d12_test_shaders.h"
18#include "../src/shader_library.h"
19
20#include <d3dcompiler.h>
21#endif
22
23#include <dxgi1_4.h>
24
25#include <cstdint>
26#include <cstdio>
27#include <cstring>
28#include <filesystem>
29#include <fstream>
30#include <string>
31#include <vector>
32
33namespace {
34
35template<class T>
36struct Ref {
37 T* p = nullptr;
38 ~Ref() { if (p) p->Release(); }
39 T* operator->() const { return p; }
40};
41
42struct Family {
43 DXGI_FORMAT typeless;
44 std::vector<DXGI_FORMAT> views;
45};
46
47// Values that tell the interpretations apart: a fraction (UNORM / FLOAT), 7 (UINT keeps it, UNORM clamps it to 1),
48// a negative one (SINT / SNORM keep it, unsigned ones clamp it), one past every 8- and 16-bit integer range.
49constexpr float kValues[2][4] = {{0.5f, 7.0f, -1.0f, 300.0f}, {0.25f, 1.0f, -128.0f, 70000.0f}};
50
51// A full-screen pass for one device: its root signature blob and VS / PS bytecode (shader containers for the layer,
52// DXBC for the host).
53struct Pass {
54 const std::vector<std::uint8_t>* root;
55 const std::vector<std::uint8_t>* vs;
56 const std::vector<std::uint8_t>* ps;
57};
58
59// Renders into a 4x4 TYPELESS texture through an RTV in `view` and reads it back: a clear to `value`, or (`pass`
60// given) a full-screen draw whose PSO names `view`. False when a step failed.
61bool render_and_read(ID3D12Device* device, DXGI_FORMAT typeless, DXGI_FORMAT view, const float* value,
62 const Pass* pass, std::vector<unsigned char>& bytes) {
63 D3D12_RESOURCE_DESC desc{};
64 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
65 desc.Width = 4;
66 desc.Height = 4;
67 desc.DepthOrArraySize = 1;
68 desc.MipLevels = 1;
69 desc.Format = typeless;
70 desc.SampleDesc = {1, 0};
71 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
72 const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT}, rb_heap{D3D12_HEAP_TYPE_READBACK};
73 Ref<ID3D12Resource> texture, readback;
74 if (FAILED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_RENDER_TARGET,
75 nullptr, IID_PPV_ARGS(&texture.p))))
76 return false;
77 D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
78 UINT rows = 0;
79 UINT64 row_bytes = 0, total = 0;
80 device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, &rows, &row_bytes, &total);
81 D3D12_RESOURCE_DESC buffer{};
82 buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
83 buffer.Width = total;
84 buffer.Height = 1;
85 buffer.DepthOrArraySize = 1;
86 buffer.MipLevels = 1;
87 buffer.SampleDesc = {1, 0};
88 buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
89 if (FAILED(device->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST,
90 nullptr, IID_PPV_ARGS(&readback.p))))
91 return false;
92 Ref<ID3D12DescriptorHeap> heap;
93 const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1};
94 if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap.p)))) return false;
95 D3D12_RENDER_TARGET_VIEW_DESC rtv{};
96 rtv.Format = view;
97 rtv.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
98 const auto handle = heap->GetCPUDescriptorHandleForHeapStart();
99 device->CreateRenderTargetView(texture.p, &rtv, handle);
100 Ref<ID3D12RootSignature> root;
101 Ref<ID3D12PipelineState> pso;
102 if (pass) {
103 if (FAILED(device->CreateRootSignature(0, pass->root->data(), pass->root->size(), IID_PPV_ARGS(&root.p))))
104 return false;
105 D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{};
106 pd.pRootSignature = root.p;
107 pd.VS = {pass->vs->data(), pass->vs->size()};
108 pd.PS = {pass->ps->data(), pass->ps->size()};
109 pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
110 pd.SampleMask = UINT_MAX;
111 pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
112 pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
113 pd.RasterizerState.DepthClipEnable = TRUE;
114 pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
115 pd.NumRenderTargets = 1;
116 pd.RTVFormats[0] = view;
117 pd.SampleDesc = {1, 0};
118 if (FAILED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p)))) return false;
119 }
120 Ref<ID3D12CommandQueue> queue;
121 Ref<ID3D12CommandAllocator> alloc;
122 Ref<ID3D12GraphicsCommandList> list;
123 Ref<ID3D12Fence> fence;
124 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT};
125 if (FAILED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))) ||
126 FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p))) ||
127 FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, IID_PPV_ARGS(&list.p))) ||
128 FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))))
129 return false;
130 if (pass) {
131 const D3D12_VIEWPORT viewport{0, 0, 4, 4, 0, 1};
132 const D3D12_RECT scissor{0, 0, 4, 4};
133 list->SetGraphicsRootSignature(root.p);
134 list->SetPipelineState(pso.p);
135 list->OMSetRenderTargets(1, &handle, FALSE, nullptr);
136 list->RSSetViewports(1, &viewport);
137 list->RSSetScissorRects(1, &scissor);
138 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
139 list->DrawInstanced(3, 1, 0, 0);
140 } else {
141 list->ClearRenderTargetView(handle, value, 0, nullptr);
142 }
143 D3D12_RESOURCE_BARRIER barrier{};
144 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
145 barrier.Transition = {texture.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_RENDER_TARGET,
146 D3D12_RESOURCE_STATE_COPY_SOURCE};
147 list->ResourceBarrier(1, &barrier);
148 D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
149 dst.PlacedFootprint = footprint;
150 D3D12_TEXTURE_COPY_LOCATION src{texture.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
151 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
152 if (FAILED(list->Close())) return false;
153 ID3D12CommandList* lists[] = {list.p};
154 queue->ExecuteCommandLists(1, lists);
155 if (FAILED(queue->Signal(fence.p, 1)) || FAILED(fence->SetEventOnCompletion(1, nullptr))) return false;
156 void* mapped = nullptr;
157 if (FAILED(readback->Map(0, nullptr, &mapped))) return false;
158 bytes.clear();
159 for (UINT y = 0; y < rows; ++y) {
160 const auto* row = static_cast<const unsigned char*>(mapped) + footprint.Offset + y * footprint.Footprint.RowPitch;
161 bytes.insert(bytes.end(), row, row + row_bytes);
162 }
163 const D3D12_RANGE none{};
164 readback->Unmap(0, &none);
165 return true;
166}
167
168// The host's D3D12 device on the adapter whose LUID the Vulkan device reports (not the default adapter: D3D-188).
169bool host_device(const vktest::Device& vk, Ref<ID3D12Device>& out, std::string& name) {
170 VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
171 VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
172 vk.instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(vk.physical, &props);
173 Ref<IDXGIFactory4> factory;
174 if (!id.deviceLUIDValid || FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) return false;
175 LUID luid{};
176 std::memcpy(&luid, id.deviceLUID, sizeof(luid));
177 Ref<IDXGIAdapter1> adapter;
178 if (FAILED(factory->EnumAdapterByLuid(luid, IID_PPV_ARGS(&adapter.p)))) return false;
179 DXGI_ADAPTER_DESC1 desc{};
180 adapter->GetDesc1(&desc);
181 char utf8[256]{};
182 WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, utf8, sizeof(utf8), nullptr, nullptr);
183 name = utf8;
184 return SUCCEEDED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&out.p)));
185}
186
187std::string hex(const std::vector<unsigned char>& bytes, std::size_t texel) {
188 std::string s;
189 char b[4];
190 for (std::size_t i = 0; i < texel && i < bytes.size(); ++i) {
191 std::snprintf(b, sizeof(b), "%02x", bytes[i]);
192 s += b;
193 }
194 return s;
195}
196
197// The layer and the host report the format in the same way: no RENDER_TARGET support means the layer has no mapping.
198bool renders(ID3D12Device* device, DXGI_FORMAT typeless, DXGI_FORMAT view) {
199 D3D12_FEATURE_DATA_FORMAT_SUPPORT typeless_support{typeless}, support{view};
200 return SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &typeless_support,
201 sizeof(typeless_support))) &&
202 (typeless_support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D) &&
203 SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) &&
204 (support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET);
205}
206
207#if defined(LEONIDA_TYPELESS_VS_SPV)
208// HLSL for the host's pass, the same constants as the GLSL stand-ins.
209constexpr char kHostVs[] =
210 "float4 main(uint id : SV_VertexID) : SV_Position {\n"
211 " float2 corner = float2(id & 2, (id << 1) & 2);\n"
212 " return float4(corner * 2.0 - 1.0, 0.0, 1.0);\n"
213 "}\n";
214constexpr char kHostPsFloat[] = "float4 main() : SV_Target { return float4(0.5, -2.0, 1.5, 0.25); }\n";
215constexpr char kHostPsUint[] = "uint4 main() : SV_Target { return uint4(7, 300, 1000, 3); }\n";
216
217bool compile_hlsl(pD3DCompile compile, const char* source, const char* target, std::vector<std::uint8_t>& out) {
218 ID3DBlob* code = nullptr;
219 ID3DBlob* errors = nullptr;
220 const HRESULT hr = compile(source, std::strlen(source), nullptr, nullptr, nullptr, "main", target, 0, 0, &code,
221 &errors);
222 if (errors) {
223 std::fprintf(stderr, "%s\n", static_cast<const char*>(errors->GetBufferPointer()));
224 errors->Release();
225 }
226 if (FAILED(hr) || !code) return false;
227 const auto* p = static_cast<const std::uint8_t*>(code->GetBufferPointer());
228 out.assign(p, p + code->GetBufferSize());
229 code->Release();
230 return true;
231}
232#endif
233
234} // namespace
235
236int main() {
237 vktest::Device vk;
238 vk.request_buffer_device_address = true;
239 const auto status = vk.initialize();
240 if (status == vktest::DeviceStatus::unavailable) return 77;
241 if (status != vktest::DeviceStatus::ready) return 1;
242 if (hostwine::host_is_wine()) return 77; // the host D3D12 runtime is the reference
243 rt::d3d12::VulkanDeviceInfo info{};
244 info.get_instance_proc = vk.instance_proc;
245 info.instance = vk.instance;
246 info.physical = vk.physical;
247 info.device = vk.device;
248 info.queue = vk.queue;
249 info.queue_family = vk.family;
250 info.bindless = vk.bindless;
251 info.bindless_partially_bound = vk.partially_bound;
252 info.host_image_copy = vk.host_image_copy;
253 info.buffer_device_address = vk.buffer_device_address;
254#if defined(LEONIDA_TYPELESS_VS_SPV)
255 // The layer's pass: shader containers around synthetic FSSM programs, and the index that maps their hashes to the
256 // compiled GLSL stand-ins.
257 const auto vs_program = d3d12test::fssm_program({0x56530275, 0xbf810000});
258 const auto ps_float_program = d3d12test::fssm_program({0x50530275, 0xbf810000});
259 const auto ps_uint_program = d3d12test::fssm_program({0x50530276, 0xbf810000});
260 const auto vs_container = d3d12test::shader_container(vs_program);
261 const auto ps_float_container = d3d12test::shader_container(ps_float_program);
262 const auto ps_uint_container = d3d12test::shader_container(ps_uint_program);
263 const auto library = std::filesystem::temp_directory_path() / "leonida_typeless_families_test";
264 std::filesystem::create_directories(library);
265 const auto overwrite = std::filesystem::copy_options::overwrite_existing;
266 std::filesystem::copy_file(LEONIDA_TYPELESS_VS_SPV, library / "vs.spv", overwrite);
267 std::filesystem::copy_file(LEONIDA_TYPELESS_PS_FLOAT_SPV, library / "ps_float.spv", overwrite);
268 std::filesystem::copy_file(LEONIDA_TYPELESS_PS_UINT_SPV, library / "ps_uint.spv", overwrite);
269 {
270 std::ofstream index(library / "index.json", std::ios::binary);
271 index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
272 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n"
273 " \"ps_float\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_float_program)
274 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]},\n"
275 " \"ps_uint\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_uint_program)
276 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]}}";
277 }
278 info.shader_dir = library.string();
279#endif
280 Ref<ID3D12Device> ours, host, warp;
281 std::string adapter;
282 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1;
283 if (!host_device(vk, host, adapter)) {
284 std::fprintf(stderr, "no host D3D12 device on the Vulkan device's adapter\n");
285 return 77;
286 }
287 {
288 Ref<IDXGIFactory4> factory;
289 Ref<IDXGIAdapter> warp_adapter;
290 if (SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) &&
291 SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp_adapter.p))))
292 D3D12CreateDevice(warp_adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&warp.p));
293 }
294 std::printf("host reference: %s%s\n", adapter.c_str(), warp.p ? ", and WARP" : "");
295 const std::vector<Family> families = {
296 {DXGI_FORMAT_R8G8B8A8_TYPELESS, {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
297 DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R8G8B8A8_SNORM, DXGI_FORMAT_R8G8B8A8_SINT}},
298 {DXGI_FORMAT_B8G8R8A8_TYPELESS, {DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB}},
299 {DXGI_FORMAT_R16G16B16A16_TYPELESS, {DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_UNORM,
300 DXGI_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_SNORM,
301 DXGI_FORMAT_R16G16B16A16_SINT}},
302 {DXGI_FORMAT_R32G32B32A32_TYPELESS, {DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32B32A32_UINT,
303 DXGI_FORMAT_R32G32B32A32_SINT}},
304 {DXGI_FORMAT_R32G32_TYPELESS, {DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32G32_UINT, DXGI_FORMAT_R32G32_SINT}},
305 {DXGI_FORMAT_R16G16_TYPELESS, {DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_UINT,
306 DXGI_FORMAT_R16G16_SNORM, DXGI_FORMAT_R16G16_SINT}},
307 {DXGI_FORMAT_R10G10B10A2_TYPELESS, {DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R10G10B10A2_UINT}},
308 {DXGI_FORMAT_R8G8_TYPELESS, {DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R8G8_UINT, DXGI_FORMAT_R8G8_SNORM,
309 DXGI_FORMAT_R8G8_SINT}},
310 {DXGI_FORMAT_R32_TYPELESS, {DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_SINT}},
311 {DXGI_FORMAT_R16_TYPELESS, {DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT,
312 DXGI_FORMAT_R16_SNORM, DXGI_FORMAT_R16_SINT}},
313 {DXGI_FORMAT_R8_TYPELESS, {DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8_UINT, DXGI_FORMAT_R8_SNORM, DXGI_FORMAT_R8_SINT}},
314 };
315 unsigned compared = 0, skipped = 0, failed = 0, warp_differs = 0;
316 for (const auto& family : families) {
317 for (const DXGI_FORMAT view : family.views) {
318 if (!renders(ours.p, family.typeless, view)) {
319 std::printf("typeless %d view %d: SKIP, the layer has no render target in this format yet\n",
320 int(family.typeless), int(view));
321 ++skipped;
322 continue;
323 }
324 for (const auto& value : kValues) {
325 std::vector<unsigned char> mine, reference, software;
326 if (!render_and_read(host.p, family.typeless, view, value, nullptr, reference)) {
327 std::fprintf(stderr, "typeless %d view %d: the host refused\n", int(family.typeless), int(view));
328 return 1;
329 }
330 if (!render_and_read(ours.p, family.typeless, view, value, nullptr, mine)) {
331 std::fprintf(stderr, "typeless %d view %d: the layer failed\n", int(family.typeless), int(view));
332 return 1;
333 }
334 const std::size_t texel = reference.size() / 16;
335 ++compared;
336 const bool same = mine == reference;
337 failed += !same;
338 if (warp.p && render_and_read(warp.p, family.typeless, view, value, nullptr, software) &&
339 software != reference)
340 ++warp_differs;
341 std::printf("typeless %d view %d clear (%g, %g, %g, %g): host %s, layer %s%s%s\n", int(family.typeless),
342 int(view), value[0], value[1], value[2], value[3], hex(reference, texel).c_str(),
343 hex(mine, texel).c_str(), same ? "" : " MISMATCH",
344 software.empty() || software == reference ? "" : (" WARP " + hex(software, texel)).c_str());
345 }
346 }
347 }
348 std::printf("%u clears compared with %s, %u differ; %u view formats skipped; WARP differs from the host in %u\n",
349 compared, adapter.c_str(), failed, skipped, warp_differs);
350
351 unsigned drawn = 0, draws_failed = 0;
352#if defined(LEONIDA_TYPELESS_VS_SPV)
353 // Draws: the PSO names the typed format, the attachment must be a view of the typeless image in that format.
354 const HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
355 const auto compile = compiler ? reinterpret_cast<pD3DCompile>(reinterpret_cast<void*>(
356 GetProcAddress(compiler, "D3DCompile")))
357 : nullptr;
358 std::vector<std::uint8_t> host_vs, host_ps_float, host_ps_uint;
359 if (!compile || !compile_hlsl(compile, kHostVs, "vs_5_0", host_vs) ||
360 !compile_hlsl(compile, kHostPsFloat, "ps_5_0", host_ps_float) ||
361 !compile_hlsl(compile, kHostPsUint, "ps_5_0", host_ps_uint)) {
362 std::fprintf(stderr, "d3dcompiler_47 could not compile the host's pass\n");
363 return 1;
364 }
365 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
366 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
367 const auto root_blob = d3d12test::serialize_root_signature(root_desc);
368 if (root_blob.empty()) return 1;
369 const Pass host_float{&root_blob, &host_vs, &host_ps_float}, host_uint{&root_blob, &host_vs, &host_ps_uint};
370 const Pass ours_float{&root_blob, &vs_container, &ps_float_container};
371 const Pass ours_uint{&root_blob, &vs_container, &ps_uint_container};
372 struct DrawCase {
373 DXGI_FORMAT typeless, view;
374 bool uint;
375 };
376 const DrawCase draws[] = {
377 {DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UINT, true},
378 {DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_FLOAT, false},
379 {DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UNORM, false},
380 {DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_UINT, true},
381 {DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT, false},
382 {DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT, true},
383 {DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM, false},
384 {DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT, true},
385 };
386 for (const auto& c : draws) {
387 if (!renders(ours.p, c.typeless, c.view)) {
388 std::printf("typeless %d view %d draw: SKIP, the layer has no render target in this format yet\n",
389 int(c.typeless), int(c.view));
390 ++skipped;
391 continue;
392 }
393 std::vector<unsigned char> mine, reference;
394 if (!render_and_read(host.p, c.typeless, c.view, nullptr, c.uint ? &host_uint : &host_float, reference)) {
395 std::fprintf(stderr, "typeless %d view %d draw: the host refused\n", int(c.typeless), int(c.view));
396 return 1;
397 }
398 if (!render_and_read(ours.p, c.typeless, c.view, nullptr, c.uint ? &ours_uint : &ours_float, mine)) {
399 std::fprintf(stderr, "typeless %d view %d draw: the layer failed\n", int(c.typeless), int(c.view));
400 return 1;
401 }
402 ++drawn;
403 const bool same = mine == reference;
404 draws_failed += !same;
405 std::printf("typeless %d view %d draw (%s): host %s, layer %s%s\n", int(c.typeless), int(c.view),
406 c.uint ? "7, 300, 1000, 3" : "0.5, -2, 1.5, 0.25", hex(reference, reference.size() / 16).c_str(),
407 hex(mine, reference.size() / 16).c_str(), same ? "" : " MISMATCH");
408 }
409 std::printf("%u draws compared with %s, %u differ\n", drawn, adapter.c_str(), draws_failed);
410#endif
411 if (vk.validation_errors()) {
412 std::fprintf(stderr, "%u Vulkan validation errors\n", vk.validation_errors());
413 return 1;
414 }
415 return failed || draws_failed ? 1 : 0;
416}
diff --git a/runtime/test/d3d12_uav_clear_test.cpp b/runtime/test/d3d12_uav_clear_test.cpp
index 1968dc371..27664696e 100644
--- a/runtime/test/d3d12_uav_clear_test.cpp
+++ b/runtime/test/d3d12_uav_clear_test.cpp
@@ -574,9 +574,47 @@ int main() {
574 {"RGBA8_UNORM, Float and Uint", DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 8, 8, 1, 1, false, 574 {"RGBA8_UNORM, Float and Uint", DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 8, 8, 1, 1, false,
575 {texture_clear(VK_FORMAT_R8G8B8A8_UNORM, true, floats(1.0f, 0.5f, 0.0f, 1.0f), 0, 0, 1), 575 {texture_clear(VK_FORMAT_R8G8B8A8_UNORM, true, floats(1.0f, 0.5f, 0.0f, 1.0f), 0, 0, 1),
576 texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {0x10, 0x20, 0x130, 0x40}, 0, 0, 1, {{1, 1, 3, 7}})}}, 576 texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {0x10, 0x20, 0x130, 0x40}, 0, 0, 1, {{1, 1, 3, 7}})}},
577 {"R32_TYPELESS through an R32_UINT view", DXGI_FORMAT_R32_TYPELESS, VK_FORMAT_R32_SFLOAT, 8, 4, 2, 1, false, 577 {"R32_TYPELESS through R32_UINT / R32_SINT / R32_SFLOAT (including NaN bits)", DXGI_FORMAT_R32_TYPELESS,
578 VK_FORMAT_R32_SFLOAT, 8, 4, 2, 1, false,
578 {texture_clear(VK_FORMAT_R32_UINT, false, {0x40490fdb, 0, 0, 0}, 0, 0, 1), 579 {texture_clear(VK_FORMAT_R32_UINT, false, {0x40490fdb, 0, 0, 0}, 0, 0, 1),
579 texture_clear(VK_FORMAT_R32_SFLOAT, true, floats(-0.25f, 0, 0, 0), 1, 0, 1)}}, 580 texture_clear(VK_FORMAT_R32_UINT, false, {0x7f800001u, 0, 0, 0}, 0, 0, 1),
581 texture_clear(VK_FORMAT_R32_UINT, false, {0xffffffffu, 0, 0, 0}, 0, 0, 1, {{1, 1, 6, 3}}),
582 texture_clear(VK_FORMAT_R32_SINT, false, {0xff800001u, 0, 0, 0}, 1, 0, 1),
583 texture_clear(VK_FORMAT_R32_SFLOAT, true, floats(-0.25f, 0, 0, 0), 1, 0, 1, {{0, 0, 2, 2}})}},
584 {"R32G32_TYPELESS through R32G32_UINT (NaN bit patterns)", DXGI_FORMAT_R32G32_TYPELESS,
585 VK_FORMAT_R32G32_SFLOAT, 8, 4, 1, 1, false,
586 {texture_clear(VK_FORMAT_R32G32_UINT, false, {0x7f800001u, 0xffffffffu, 0, 0}, 0, 0, 1),
587 texture_clear(VK_FORMAT_R32G32_SINT, false, {0xff800001u, 0x7fffffffu, 0, 0}, 0, 0, 1, {{2, 1, 6, 3}})}},
588 {"R32G32B32A32_TYPELESS through R32G32B32A32_UINT (NaN bit patterns)", DXGI_FORMAT_R32G32B32A32_TYPELESS,
589 VK_FORMAT_R32G32B32A32_SFLOAT, 4, 4, 1, 1, false,
590 {texture_clear(VK_FORMAT_R32G32B32A32_UINT, false, {0x7f800001u, 0xffffffffu, 0x7fffffffu, 0xff800001u},
591 0, 0, 1)}},
592 {"R16G16_TYPELESS through UNORM, UINT, SINT and SNORM", DXGI_FORMAT_R16G16_TYPELESS,
593 VK_FORMAT_R16G16_SFLOAT, 8, 8, 2, 2, false,
594 {texture_clear(VK_FORMAT_R16G16_UNORM, true, floats(1.0f, 1.0f, 0.0f, 0.0f), 0, 0, 2),
595 texture_clear(VK_FORMAT_R16G16_UNORM, true, floats(0.5f, 1.0f, 0.0f, 0.0f), 0, 0, 1, {{1, 1, 5, 4}}),
596 texture_clear(VK_FORMAT_R16G16_UINT, false, {0xffffu, 0x7fffu, 0, 0}, 0, 1, 1),
597 texture_clear(VK_FORMAT_R16G16_UINT, false, {0x7c01u, 0xfc01u, 0, 0}, 0, 1, 1, {{2, 2, 6, 6}}),
598 texture_clear(VK_FORMAT_R16G16_SINT, false, {0xffffu, 0x8000u, 0, 0}, 1, 0, 1),
599 texture_clear(VK_FORMAT_R16G16_SNORM, true, floats(1.0f, -1.0f, 0.0f, 0.0f), 1, 1, 1)}},
600 {"R16G16B16A16_TYPELESS through UNORM, UINT, SINT and SNORM", DXGI_FORMAT_R16G16B16A16_TYPELESS,
601 VK_FORMAT_R16G16B16A16_SFLOAT, 8, 8, 2, 2, false,
602 {texture_clear(VK_FORMAT_R16G16B16A16_UNORM, true, floats(1.0f, 0.5f, 0.0f, 1.0f), 0, 0, 2),
603 texture_clear(VK_FORMAT_R16G16B16A16_UINT, false, {0xffffu, 0x7fffu, 0x7c01u, 0xfc01u}, 0, 1, 1),
604 texture_clear(VK_FORMAT_R16G16B16A16_SINT, true, floats(-1.0f, 32767.0f, -32768.0f, 0.0f), 0, 0, 1,
605 {{1, 2, 6, 5}}),
606 texture_clear(VK_FORMAT_R16G16B16A16_SNORM, true, floats(1.0f, -1.0f, 0.5f, 0.0f), 1, 0, 2)}},
607 {"R8G8B8A8_TYPELESS through UINT, SINT and SNORM", DXGI_FORMAT_R8G8B8A8_TYPELESS,
608 VK_FORMAT_R8G8B8A8_UNORM, 8, 8, 2, 1, false,
609 {texture_clear(VK_FORMAT_R8G8B8A8_UINT, false, {0xffu, 0x80u, 0x7fu, 0x01u}, 0, 0, 1),
610 texture_clear(VK_FORMAT_R8G8B8A8_SINT, true, floats(-128.0f, -1.0f, 127.0f, 0.0f), 0, 0, 1,
611 {{1, 1, 5, 6}}),
612 texture_clear(VK_FORMAT_R8G8B8A8_SNORM, true, floats(1.0f, -1.0f, 0.5f, -0.5f), 1, 0, 1)}},
613 {"R16_TYPELESS through UINT, SFLOAT and SNORM", DXGI_FORMAT_R16_TYPELESS,
614 VK_FORMAT_R16_UNORM, 8, 4, 2, 1, false,
615 {texture_clear(VK_FORMAT_R16_UINT, false, {0xffffu, 0, 0, 0}, 0, 0, 1),
616 texture_clear(VK_FORMAT_R16_SFLOAT, true, floats(1.0f, 0, 0, 0), 0, 0, 1, {{2, 1, 6, 3}}),
617 texture_clear(VK_FORMAT_R16_SNORM, true, floats(1.0f, 0, 0, 0), 1, 0, 1)}},
580 {"RGBA16_FLOAT rectangles", DXGI_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, 16, 16, 2, 2, 618 {"RGBA16_FLOAT rectangles", DXGI_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, 16, 16, 2, 2,
581 false, 619 false,
582 {texture_clear(VK_FORMAT_R16G16B16A16_SFLOAT, true, floats(0.25f, -8.0f, 1.0f, 0.0f), 1, 0, 2, 620 {texture_clear(VK_FORMAT_R16G16B16A16_SFLOAT, true, floats(0.25f, -8.0f, 1.0f, 0.0f), 1, 0, 2,
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index 91d3244ce..6b7a399bf 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -867,6 +867,28 @@ int compare_allocation_info(ID3D12Device* ours) {
867 mismatch("no resources", empty_a, empty_b); 867 mismatch("no resources", empty_a, empty_b);
868 868
869 Ref<ID3D12Device8> ours8; 869 Ref<ID3D12Device8> ours8;
870 // MULTISAMPLE_QUALITY_LEVELS with TILED_RESOURCE: the same answers as the host, except 128-bit formats at 4x,
871 // which the AMD drivers refuse and WARP and NVIDIA report (and GetResourceAllocationInfo allocates here).
872 for (const DXGI_FORMAT format : {rgba8, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32G32_FLOAT,
873 DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_D32_FLOAT,
874 DXGI_FORMAT_R32G32B32_FLOAT}) {
875 for (const UINT samples : {1u, 2u, 4u, 8u, 16u}) {
876 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS x{format, samples,
877 D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE};
878 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS y = x;
879 const HRESULT hx = ours->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &x, sizeof(x));
880 const HRESULT hy = host->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &y, sizeof(y));
881 const bool wide = format == DXGI_FORMAT_R32G32B32A32_FLOAT;
882 if (hx == hy && (x.NumQualityLevels == y.NumQualityLevels ||
883 (wide && samples == 4 && x.NumQualityLevels == 1 && y.NumQualityLevels == 0)))
884 continue;
885 if (mismatches++ < 24)
886 std::fprintf(stderr, "tiled quality levels format %d %ux: ours 0x%08lx %u, host 0x%08lx %u\n",
887 int(format), samples, static_cast<unsigned long>(hx), x.NumQualityLevels,
888 static_cast<unsigned long>(hy), y.NumQualityLevels);
889 }
890 }
891
870 if (FAILED(ours->QueryInterface(IID_PPV_ARGS(&ours8.p)))) return mismatches + 1; 892 if (FAILED(ours->QueryInterface(IID_PPV_ARGS(&ours8.p)))) return mismatches + 1;
871 const D3D12_RESOURCE_DESC mixed[] = {with(texture_desc(16, 16, rgba8, none), k4), buffer_desc(300), 893 const D3D12_RESOURCE_DESC mixed[] = {with(texture_desc(16, 16, rgba8, none), k4), buffer_desc(300),
872 with(texture_desc(64, 64, rgba8, rt), 0, 4)}; 894 with(texture_desc(64, 64, rgba8, rt), 0, 4)};
@@ -1388,6 +1410,64 @@ int compare_depth_multisample_quality_levels(ID3D12Device* ours, VkSampleCountFl
1388 return mismatches; 1410 return mismatches;
1389} 1411}
1390 1412
1413bool check_plain_resolve_formats(ID3D12Device* device) {
1414 struct Case { DXGI_FORMAT format; bool valid; bool depth = false; DXGI_FORMAT requested = DXGI_FORMAT_UNKNOWN; };
1415 constexpr Case cases[] = {
1416 {DXGI_FORMAT_R8G8B8A8_UINT, false},
1417 {DXGI_FORMAT_R8G8B8A8_SINT, false},
1418 {DXGI_FORMAT_R32_UINT, false},
1419 {DXGI_FORMAT_R32_SINT, false},
1420 {DXGI_FORMAT_R32G32B32A32_SINT, false},
1421 {DXGI_FORMAT_R8G8B8A8_UINT, false, false, DXGI_FORMAT_R8G8B8A8_UNORM},
1422 {DXGI_FORMAT_R8G8B8A8_UNORM, true},
1423 {DXGI_FORMAT_R16G16B16A16_FLOAT, true},
1424 {DXGI_FORMAT_D32_FLOAT, true, true},
1425 };
1426 Ref<ID3D12CommandAllocator> allocator;
1427 Ref<ID3D12GraphicsCommandList> list;
1428 if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) ||
1429 FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
1430 IID_PPV_ARGS(&list.p)))) return false;
1431 const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT};
1432 bool ok = true;
1433 unsigned tested = 0, skipped = 0;
1434 for (const auto& c : cases) {
1435 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS quality{c.format, 4};
1436 if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &quality, sizeof(quality))))
1437 return false;
1438 if (!quality.NumQualityLevels) {
1439 std::printf("plain resolve format %d: 4x MSAA unsupported, skipped\n", int(c.format));
1440 ++skipped;
1441 continue;
1442 }
1443 auto desc = texture_desc(8, 8, c.format, c.depth ? D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL
1444 : D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
1445 desc.SampleDesc.Count = 4;
1446 Ref<ID3D12Resource> src, dst;
1447 if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc,
1448 D3D12_RESOURCE_STATE_RESOLVE_SOURCE, nullptr,
1449 IID_PPV_ARGS(&src.p)))) return false;
1450 desc.SampleDesc.Count = 1;
1451 if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc,
1452 D3D12_RESOURCE_STATE_RESOLVE_DEST, nullptr,
1453 IID_PPV_ARGS(&dst.p)))) return false;
1454 const DXGI_FORMAT requested = c.requested == DXGI_FORMAT_UNKNOWN ? c.format : c.requested;
1455 list->ResolveSubresource(dst.p, 0, src.p, 0, requested);
1456 const HRESULT result = list->Close();
1457 if (result != (c.valid ? S_OK : E_INVALIDARG)) {
1458 std::fprintf(stderr, "plain resolve format %d: Close returned 0x%08lx, expected 0x%08lx\n",
1459 int(c.format), static_cast<unsigned long>(result),
1460 static_cast<unsigned long>(c.valid ? S_OK : E_INVALIDARG));
1461 ok = false;
1462 }
1463 ++tested;
1464 if (FAILED(list->Reset(allocator.p, nullptr))) return false;
1465 }
1466 if (FAILED(list->Close())) return false;
1467 std::printf("plain resolve format validation: %u tested, %u unsupported cases skipped\n", tested, skipped);
1468 return ok;
1469}
1470
1391// Compare the Vulkan-backed resolve output byte-for-byte with the host runtime for every common supported format, 1471// Compare the Vulkan-backed resolve output byte-for-byte with the host runtime for every common supported format,
1392// sample count and region form. A host-unsupported combination is a deliberate skip; a mismatch in advertised 1472// sample count and region form. A host-unsupported combination is a deliberate skip; a mismatch in advertised
1393// support or in the resulting pixels is a failure. The region forms need ID3D12GraphicsCommandList7 on the host; 1473// support or in the resulting pixels is a failure. The region forms need ID3D12GraphicsCommandList7 on the host;
@@ -2319,8 +2399,7 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2319 const bool expect_ok = (type == D3D12_COMMAND_LIST_TYPE_DIRECT || 2399 const bool expect_ok = (type == D3D12_COMMAND_LIST_TYPE_DIRECT ||
2320 type == D3D12_COMMAND_LIST_TYPE_COMPUTE || 2400 type == D3D12_COMMAND_LIST_TYPE_COMPUTE ||
2321 type == D3D12_COMMAND_LIST_TYPE_COPY) && 2401 type == D3D12_COMMAND_LIST_TYPE_COPY) &&
2322 (prio == D3D12_COMMAND_QUEUE_PRIORITY_NORMAL || 2402 prio == D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
2323 prio == D3D12_COMMAND_QUEUE_PRIORITY_HIGH);
2324 if (ours->CheckFeatureSupport(D3D12_FEATURE_COMMAND_QUEUE_PRIORITY, &q, sizeof(q)) != S_OK || 2403 if (ours->CheckFeatureSupport(D3D12_FEATURE_COMMAND_QUEUE_PRIORITY, &q, sizeof(q)) != S_OK ||
2325 q.PriorityForTypeIsSupported != (expect_ok ? TRUE : FALSE)) 2404 q.PriorityForTypeIsSupported != (expect_ok ? TRUE : FALSE))
2326 fail("COMMAND_QUEUE_PRIORITY answer mismatch"); 2405 fail("COMMAND_QUEUE_PRIORITY answer mismatch");
@@ -2777,16 +2856,6 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2777 Ref<ID3D12Device10> newer; 2856 Ref<ID3D12Device10> newer;
2778 return SUCCEEDED(d->QueryInterface(IID_PPV_ARGS(&newer.p))); 2857 return SUCCEEDED(d->QueryInterface(IID_PPV_ARGS(&newer.p)));
2779 }; 2858 };
2780 const auto not_elevated = [](ID3D12Device*) {
2781 HANDLE token = nullptr;
2782 TOKEN_ELEVATION elevation{};
2783 DWORD size = 0;
2784 const bool elevated = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
2785 GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &size) &&
2786 elevation.TokenIsElevated;
2787 if (token) CloseHandle(token);
2788 return !elevated;
2789 };
2790 static const Case cases[] = { 2859 static const Case cases[] = {
2791 // CreateCommittedResource: arguments. 2860 // CreateCommittedResource: arguments.
2792 // A null D3D12_HEAP_PROPERTIES faults in the host runtime, so it is not compared. 2861 // A null D3D12_HEAP_PROPERTIES faults in the host runtime, so it is not compared.
@@ -3440,7 +3509,7 @@ int compare_invalid_arguments(ID3D12Device* ours) {
3440 }}, 3509 }},
3441 {"command queue: global realtime priority", [](ID3D12Device* d) { 3510 {"command queue: global realtime priority", [](ID3D12Device* d) {
3442 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME}); 3511 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME});
3443 }, +not_elevated}, 3512 }},
3444 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }}, 3513 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }},
3445 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }}, 3514 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }},
3446 {"command queue: high priority", [](ID3D12Device* d) { 3515 {"command queue: high priority", [](ID3D12Device* d) {
@@ -3827,6 +3896,7 @@ int main() {
3827 rt::d3d12::set_device_outer(inner, device.p); // the proxy now owns `inner` 3896 rt::d3d12::set_device_outer(inner, device.p); // the proxy now owns `inner`
3828 EXPECT(rt::d3d12_xs::is_device_proxy(device.p)); 3897 EXPECT(rt::d3d12_xs::is_device_proxy(device.p));
3829 EXPECT(rt::d3d12_xs::device_proxy_slot_count(device.p) == 80); // ID3D12Device11 3898 EXPECT(rt::d3d12_xs::device_proxy_slot_count(device.p) == 80); // ID3D12Device11
3899 EXPECT(check_plain_resolve_formats(device.p));
3830 3900
3831 { 3901 {
3832 Ref<ID3D12Device11> device11; 3902 Ref<ID3D12Device11> device11;
@@ -4231,8 +4301,40 @@ int main() {
4231 granted_q.reset(); 4301 granted_q.reset();
4232 rt::d3d12::set_global_realtime_privilege_override_for_test(-1); 4302 rt::d3d12::set_global_realtime_privilege_override_for_test(-1);
4233 4303
4304 Ref<ID3D12Device> host;
4305 create_host_device(host);
4306 if (host.p) EXPECT(command_queue(device.p, rt_desc) == command_queue(host.p, rt_desc));
4307
4308 // SecurityAnonymous thread impersonation (OpenThreadToken fails with ERROR_CANT_OPEN_ANONYMOUS, not
4309 // ERROR_NO_TOKEN) must fail closed instead of falling back to the process token, matching the host runtime.
4310 const auto check_security_anonymous_impersonation = [&]() -> int {
4311 HANDLE proc_token = nullptr;
4312 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &proc_token)) return 0;
4313 HANDLE anon_imp = nullptr;
4314 if (DuplicateTokenEx(proc_token, MAXIMUM_ALLOWED, nullptr, SecurityAnonymous, TokenImpersonation,
4315 &anon_imp)) {
4316 if (SetThreadToken(nullptr, anon_imp)) {
4317 struct RevertImpersonation {
4318 ~RevertImpersonation() { RevertToSelf(); }
4319 } revert_impersonation;
4320 HANDLE opened = nullptr;
4321 EXPECT(!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &opened));
4322 EXPECT(GetLastError() == ERROR_CANT_OPEN_ANONYMOUS);
4323 if (opened) CloseHandle(opened);
4324 EXPECT(!rt::d3d12::has_global_realtime_privilege());
4325 EXPECT(command_queue(device.p, rt_desc) == DXGI_ERROR_ACCESS_DENIED);
4326 if (host.p) EXPECT(command_queue(host.p, rt_desc) == DXGI_ERROR_ACCESS_DENIED);
4327 }
4328 CloseHandle(anon_imp);
4329 }
4330 CloseHandle(proc_token);
4331 return 0;
4332 };
4333 if (check_security_anonymous_impersonation() != 0) return 1;
4334
4234 // When the process token holds SeIncreaseBasePriorityPrivilege (e.g. an elevated session), toggle the 4335 // When the process token holds SeIncreaseBasePriorityPrivilege (e.g. an elevated session), toggle the
4235 // real token privilege and verify both states against the host D3D12 runtime. 4336 // real token privilege and verify both states (plus SecurityAnonymous impersonation while the process
4337 // token has the privilege enabled) against the host D3D12 runtime.
4236 HANDLE token = nullptr; 4338 HANDLE token = nullptr;
4237 LUID luid{}; 4339 LUID luid{};
4238 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) { 4340 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
@@ -4246,9 +4348,11 @@ int main() {
4246 GetLastError() == ERROR_SUCCESS) { 4348 GetLastError() == ERROR_SUCCESS) {
4247 EXPECT(rt::d3d12::has_global_realtime_privilege()); 4349 EXPECT(rt::d3d12::has_global_realtime_privilege());
4248 EXPECT(command_queue(device.p, rt_desc) == S_OK); 4350 EXPECT(command_queue(device.p, rt_desc) == S_OK);
4249 Ref<ID3D12Device> host; 4351 if (host.p) EXPECT(command_queue(host.p, rt_desc) == S_OK);
4250 if (create_host_device(host)) { 4352 if (check_security_anonymous_impersonation() != 0) {
4251 EXPECT(command_queue(host.p, rt_desc) == S_OK); 4353 AdjustTokenPrivileges(token, FALSE, &prev, 0, nullptr, nullptr);
4354 CloseHandle(token);
4355 return 1;
4252 } 4356 }
4253 tp.Privileges[0].Attributes = 0; 4357 tp.Privileges[0].Attributes = 0;
4254 if (AdjustTokenPrivileges(token, FALSE, &tp, 0, nullptr, nullptr) && 4358 if (AdjustTokenPrivileges(token, FALSE, &tp, 0, nullptr, nullptr) &&
@@ -5554,6 +5658,69 @@ int main() {
5554 { 5658 {
5555 Ref<ID3D12Device> standalone; 5659 Ref<ID3D12Device> standalone;
5556 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&standalone.p)))); 5660 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&standalone.p))));
5661 // What translated shaders can declare beyond Int64/Float64 (the index's `features`) is enabled wherever the GPU
5662 // has it: image stores and loads without a format, gather offsets, LOD clamps, a vertex shader's layer and
5663 // viewport. Creating a module that declares one without it breaks VUID-VkShaderModuleCreateInfo-pCode-08740.
5664 const rt::d3d12::VulkanDeviceInfo* made = rt::d3d12::vulkan_device_info(standalone.p);
5665 EXPECT(made != nullptr);
5666 if (made) {
5667 const auto features2 = reinterpret_cast<PFN_vkGetPhysicalDeviceFeatures2>(
5668 made->get_instance_proc(made->instance, "vkGetPhysicalDeviceFeatures2"));
5669 EXPECT(features2 != nullptr);
5670 VkPhysicalDeviceVulkan12Features have12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
5671 VkPhysicalDeviceFeatures2 have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &have12};
5672 if (features2) features2(made->physical, &have);
5673 const VkPhysicalDeviceFeatures& on = made->features;
5674 EXPECT(on.shaderStorageImageWriteWithoutFormat == have.features.shaderStorageImageWriteWithoutFormat);
5675 EXPECT(on.shaderStorageImageReadWithoutFormat == have.features.shaderStorageImageReadWithoutFormat);
5676 EXPECT(on.shaderImageGatherExtended == have.features.shaderImageGatherExtended);
5677 EXPECT(on.shaderResourceMinLod == have.features.shaderResourceMinLod);
5678 EXPECT(made->shader_output_layer == (have12.shaderOutputLayer == VK_TRUE));
5679 EXPECT(made->shader_output_viewport_index == (have12.shaderOutputViewportIndex == VK_TRUE));
5680 // The pixel-shader extensions (barycentrics, the POPS interlock, maintenance8's texel offsets): each is
5681 // enabled exactly when the GPU offers the extension and its feature. A structure is chained into the
5682 // query only when its extension is offered.
5683 const auto enumerate = reinterpret_cast<PFN_vkEnumerateDeviceExtensionProperties>(
5684 made->get_instance_proc(made->instance, "vkEnumerateDeviceExtensionProperties"));
5685 EXPECT(enumerate != nullptr);
5686 std::vector<VkExtensionProperties> offered;
5687 std::uint32_t offered_count = 0;
5688 if (enumerate && enumerate(made->physical, nullptr, &offered_count, nullptr) == VK_SUCCESS) {
5689 offered.resize(offered_count);
5690 enumerate(made->physical, nullptr, &offered_count, offered.data());
5691 offered.resize(offered_count);
5692 }
5693 const auto has = [&](const char* name) {
5694 return std::any_of(offered.begin(), offered.end(),
5695 [&](const VkExtensionProperties& e) { return std::strcmp(e.extensionName, name) == 0; });
5696 };
5697 VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{
5698 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR};
5699 VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{
5700 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT};
5701 VkPhysicalDeviceFeatures2 ext_query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
5702 if (has(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) {
5703 bary.pNext = ext_query.pNext;
5704 ext_query.pNext = &bary;
5705 }
5706 if (has(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME)) {
5707 lock.pNext = ext_query.pNext;
5708 ext_query.pNext = &lock;
5709 }
5710#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
5711 VkPhysicalDeviceMaintenance8FeaturesKHR m8{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR};
5712 if (has(VK_KHR_MAINTENANCE_8_EXTENSION_NAME)) {
5713 m8.pNext = ext_query.pNext;
5714 ext_query.pNext = &m8;
5715 }
5716#endif
5717 if (features2) features2(made->physical, &ext_query);
5718 EXPECT(made->fragment_shader_barycentric == (bary.fragmentShaderBarycentric == VK_TRUE));
5719 EXPECT(made->fragment_shader_interlock == (lock.fragmentShaderPixelInterlock == VK_TRUE));
5720#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
5721 EXPECT(made->maintenance8 == (m8.maintenance8 == VK_TRUE));
5722#endif
5723 }
5557 D3D12_COMMAND_QUEUE_DESC queue_desc{}; 5724 D3D12_COMMAND_QUEUE_DESC queue_desc{};
5558 Ref<ID3D12CommandQueue> queue; 5725 Ref<ID3D12CommandQueue> queue;
5559 Ref<ID3D12Fence> fence; 5726 Ref<ID3D12Fence> fence;
diff --git a/runtime/test/d3d12_xdxr_rt_test.cpp b/runtime/test/d3d12_xdxr_rt_test.cpp
index 51f357fc1..dd6ab2f88 100644
--- a/runtime/test/d3d12_xdxr_rt_test.cpp
+++ b/runtime/test/d3d12_xdxr_rt_test.cpp
@@ -256,7 +256,7 @@ int main(int argc, char** argv) {
256 if (FAILED(rb->Map(0, nullptr, &p))) return false; 256 if (FAILED(rb->Map(0, nullptr, &p))) return false;
257 std::uint32_t units = 0; 257 std::uint32_t units = 0;
258 std::memcpy(&units, static_cast<char*>(p) + 4, 4); // header totalSizeIn64BNodes 258 std::memcpy(&units, static_cast<char*>(p) + 4, 4); // header totalSizeIn64BNodes
259 const UINT64 used = UINT64(units) * 64; 259 const UINT64 used = (UINT64(units) + 1) * 64; // the field does not count the 64-byte header
260 const bool ok = used && used <= size && write_file(dir + "/" + name + ".bin", p, std::size_t(used)) && 260 const bool ok = used && used <= size && write_file(dir + "/" + name + ".bin", p, std::size_t(used)) &&
261 write_file(dir + "/" + name + ".json", json.data(), json.size()); 261 write_file(dir + "/" + name + ".json", json.data(), json.size());
262 rb->Unmap(0, nullptr); 262 rb->Unmap(0, nullptr);
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp
index 1fcaf6710..3a4bc5860 100644
--- a/runtime/test/file_system_test.cpp
+++ b/runtime/test/file_system_test.cpp
@@ -17,8 +17,13 @@ namespace {
17 17
18using CreateFileWFn = HANDLE(WINAPI*)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); 18using CreateFileWFn = HANDLE(WINAPI*)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
19using CreateFileAFn = HANDLE(WINAPI*)(LPCSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); 19using CreateFileAFn = HANDLE(WINAPI*)(LPCSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
20using CreateFile2Fn = HANDLE(WINAPI*)(LPCWSTR, DWORD, DWORD, DWORD, LPCREATEFILE2_EXTENDED_PARAMETERS);
20using FindFirstFileWFn = HANDLE(WINAPI*)(LPCWSTR, LPWIN32_FIND_DATAW); 21using FindFirstFileWFn = HANDLE(WINAPI*)(LPCWSTR, LPWIN32_FIND_DATAW);
21using FindFirstFileAFn = HANDLE(WINAPI*)(LPCSTR, LPWIN32_FIND_DATAA); 22using FindFirstFileAFn = HANDLE(WINAPI*)(LPCSTR, LPWIN32_FIND_DATAA);
23using FindFirstFileExWFn =
24 HANDLE(WINAPI*)(LPCWSTR, FINDEX_INFO_LEVELS, LPVOID, FINDEX_SEARCH_OPS, LPVOID, DWORD);
25using FindFirstFileExAFn =
26 HANDLE(WINAPI*)(LPCSTR, FINDEX_INFO_LEVELS, LPVOID, FINDEX_SEARCH_OPS, LPVOID, DWORD);
22using FindNextFileWFn = BOOL(WINAPI*)(HANDLE, LPWIN32_FIND_DATAW); 27using FindNextFileWFn = BOOL(WINAPI*)(HANDLE, LPWIN32_FIND_DATAW);
23using FindCloseFn = BOOL(WINAPI*)(HANDLE); 28using FindCloseFn = BOOL(WINAPI*)(HANDLE);
24using GetFileAttributesWFn = DWORD(WINAPI*)(LPCWSTR); 29using GetFileAttributesWFn = DWORD(WINAPI*)(LPCWSTR);
@@ -26,6 +31,20 @@ using GetFileAttributesAFn = DWORD(WINAPI*)(LPCSTR);
26using GetFileAttributesExWFn = BOOL(WINAPI*)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID); 31using GetFileAttributesExWFn = BOOL(WINAPI*)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
27using DeleteFileWFn = BOOL(WINAPI*)(LPCWSTR); 32using DeleteFileWFn = BOOL(WINAPI*)(LPCWSTR);
28using DeleteFileAFn = BOOL(WINAPI*)(LPCSTR); 33using DeleteFileAFn = BOOL(WINAPI*)(LPCSTR);
34using CreateDirectoryWFn = BOOL(WINAPI*)(LPCWSTR, LPSECURITY_ATTRIBUTES);
35using CreateDirectoryAFn = BOOL(WINAPI*)(LPCSTR, LPSECURITY_ATTRIBUTES);
36using CreateDirectoryExWFn = BOOL(WINAPI*)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES);
37using RemoveDirectoryWFn = BOOL(WINAPI*)(LPCWSTR);
38using RemoveDirectoryAFn = BOOL(WINAPI*)(LPCSTR);
39using MoveFileWFn = BOOL(WINAPI*)(LPCWSTR, LPCWSTR);
40using MoveFileExWFn = BOOL(WINAPI*)(LPCWSTR, LPCWSTR, DWORD);
41using MoveFileAFn = BOOL(WINAPI*)(LPCSTR, LPCSTR);
42using CopyFileWFn = BOOL(WINAPI*)(LPCWSTR, LPCWSTR, BOOL);
43using CopyFileAFn = BOOL(WINAPI*)(LPCSTR, LPCSTR, BOOL);
44using CopyFileExWFn = BOOL(WINAPI*)(LPCWSTR, LPCWSTR, LPPROGRESS_ROUTINE, LPVOID, LPBOOL, DWORD);
45using CopyFile2Fn = HRESULT(WINAPI*)(PCWSTR, PCWSTR, COPYFILE2_EXTENDED_PARAMETERS*);
46using SetFileAttributesWFn = BOOL(WINAPI*)(LPCWSTR, DWORD);
47using SetFileAttributesAFn = BOOL(WINAPI*)(LPCSTR, DWORD);
29 48
30int g_checks = 0; 49int g_checks = 0;
31int g_failures = 0; 50int g_failures = 0;
@@ -260,6 +279,238 @@ int main() {
260 "the parent folder stays listed after deleting a nested package file"); 279 "the parent folder stays listed after deleting a nested package file");
261 } 280 }
262 281
282 // Deleting one package file must not hide its folder. The overlay has never written to GAME:\pkgonly, so the
283 // folder is only in the package, and its marker folder under .gta6rt-deleted is not a marker for the folder.
284 {
285 write_path(package / "pkgonly" / "a.txt", "package");
286 write_path(package / "pkgonly" / "b.txt", "package");
287 check(delete_w(L"GAME:\\pkgonly\\a.txt") != FALSE, "DeleteFileW hides a file in a package-only folder");
288 const DWORD folder = attributes_w(L"GAME:\\pkgonly");
289 check(folder != INVALID_FILE_ATTRIBUTES && (folder & FILE_ATTRIBUTE_DIRECTORY) != 0,
290 "the folder of a deleted package file still resolves");
291 check(contains(list(first_w, next_w, find_close, L"GAME:\\*"), L"pkgonly"),
292 "and is still in its parent's listing");
293 check(contains(list(first_w, next_w, find_close, L"GAME:\\pkgonly\\*"), L"b.txt"),
294 "and its other files are still listed");
295 const HANDLE h =
296 create_w(L"GAME:\\pkgonly\\b.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
297 check(h != INVALID_HANDLE_VALUE, "and its other files still open");
298 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
299 }
300
301 // Folders, moves, copies and attributes: the same mapping, through the names a title imports.
302 const auto mkdir_w = resolve<CreateDirectoryWFn>("api-ms-win-core-file-l1-1-0.dll", "CreateDirectoryW");
303 const auto mkdir_a = resolve<CreateDirectoryAFn>("kernel32.dll", "CreateDirectoryA");
304 const auto mkdir_ex_w = resolve<CreateDirectoryExWFn>("kernel32.dll", "CreateDirectoryExW");
305 const auto rmdir_w = resolve<RemoveDirectoryWFn>("api-ms-win-core-file-l1-1-0.dll", "RemoveDirectoryW");
306 const auto rmdir_a = resolve<RemoveDirectoryAFn>("kernelbase.dll", "RemoveDirectoryA");
307 const auto move_w = resolve<MoveFileWFn>("kernel32.dll", "MoveFileW");
308 const auto move_ex_w = resolve<MoveFileExWFn>("api-ms-win-core-file-l2-1-0.dll", "MoveFileExW");
309 const auto move_a = resolve<MoveFileAFn>("kernel32.dll", "MoveFileA");
310 const auto copy_w = resolve<CopyFileWFn>("kernel32.dll", "CopyFileW");
311 const auto copy_a = resolve<CopyFileAFn>("kernel32.dll", "CopyFileA");
312 const auto copy_ex_w = resolve<CopyFileExWFn>("api-ms-win-core-file-l2-1-0.dll", "CopyFileExW");
313 const auto copy2 = resolve<CopyFile2Fn>("api-ms-win-core-file-l2-1-0.dll", "CopyFile2");
314 const auto setattr_w = resolve<SetFileAttributesWFn>("api-ms-win-core-file-l1-1-0.dll", "SetFileAttributesW");
315 const auto setattr_a = resolve<SetFileAttributesAFn>("kernel32.dll", "SetFileAttributesA");
316 check(mkdir_w && mkdir_a && mkdir_ex_w && rmdir_w && rmdir_a && move_w && move_ex_w && move_a && copy_w &&
317 copy_a && copy_ex_w && copy2 && setattr_w && setattr_a,
318 "the folder, move, copy and attribute calls resolve through the registry");
319
320 write_path(package / "misc" / "one.txt", "one");
321 write_path(package / "misc" / "two.txt", "two");
322 write_path(package / "misc" / "three.txt", "three");
323 write_path(package / "misc" / "inner" / "deep.txt", "deep");
324 write_path(package / "misc" / "keep.txt", "keep");
325
326 // CreateDirectory: the new folder is in the overlay; names the title can already see are refused.
327 {
328 check(mkdir_w(L"GAME:\\cache", nullptr) != FALSE, "CreateDirectoryW makes GAME:\\cache");
329 check(std::filesystem::is_directory(overlay / "cache"), "in the overlay");
330 check(!std::filesystem::exists(package / "cache"), "and not in the package");
331 const DWORD a = attributes_w(L"GAME:\\cache");
332 check(a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY) != 0, "the new folder resolves");
333 check(contains(list(first_w, next_w, find_close, L"GAME:\\*"), L"cache"), "and is listed");
334 check(mkdir_a("GAME:\\cache\\narrow", nullptr) != FALSE && std::filesystem::is_directory(overlay / "cache" / "narrow"),
335 "CreateDirectoryA takes a console path");
336 check(mkdir_ex_w(L"GAME:\\misc", L"GAME:\\cache\\from_template", nullptr) != FALSE &&
337 std::filesystem::is_directory(overlay / "cache" / "from_template"),
338 "CreateDirectoryExW maps both the template and the new folder");
339 SetLastError(0);
340 check(mkdir_w(L"GAME:\\misc", nullptr) == FALSE && GetLastError() == ERROR_ALREADY_EXISTS,
341 "a folder only the package has already exists");
342 check(!std::filesystem::exists(overlay / "misc"), "and nothing is mirrored for it");
343 SetLastError(0);
344 check(mkdir_w(L"GAME:\\misc\\one.txt", nullptr) == FALSE && GetLastError() == ERROR_ALREADY_EXISTS,
345 "a package file's name already exists");
346 SetLastError(0);
347 check(mkdir_w(L"GAME:\\", nullptr) == FALSE && GetLastError() == ERROR_ALREADY_EXISTS, "GAME:\\ already exists");
348 SetLastError(0);
349 check(mkdir_w(L"GAME:\\nowhere\\child", nullptr) == FALSE && GetLastError() == ERROR_PATH_NOT_FOUND,
350 "a folder whose parent does not exist reports ERROR_PATH_NOT_FOUND");
351 check(!std::filesystem::exists(overlay / "nowhere"), "and leaves no parent behind");
352 check(mkdir_w(L"GAME:\\misc\\made", nullptr) != FALSE && std::filesystem::is_directory(overlay / "misc" / "made"),
353 "a new folder inside a package folder lands in the overlay");
354 }
355
356 // RemoveDirectory: an overlay folder goes; a package folder is hidden by a marker once it is empty.
357 {
358 check(rmdir_w(L"GAME:\\cache\\narrow") != FALSE && !std::filesystem::exists(overlay / "cache" / "narrow"),
359 "RemoveDirectoryW removes an empty overlay folder");
360 SetLastError(0);
361 check(rmdir_w(L"GAME:\\cache\\narrow") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND,
362 "removing it again reports ERROR_FILE_NOT_FOUND");
363 SetLastError(0);
364 check(rmdir_w(L"GAME:\\misc\\inner") == FALSE && GetLastError() == ERROR_DIR_NOT_EMPTY,
365 "a package folder with files is not empty");
366 SetLastError(0);
367 check(rmdir_w(L"GAME:\\misc\\keep.txt") == FALSE && GetLastError() == ERROR_DIRECTORY,
368 "a file is not a folder");
369 SetLastError(0);
370 check(rmdir_w(L"GAME:\\") == FALSE && GetLastError() == ERROR_ACCESS_DENIED, "GAME:\\ cannot be removed");
371 check(delete_w(L"GAME:\\misc\\inner\\deep.txt") != FALSE, "once its file is deleted");
372 check(rmdir_a("GAME:\\misc\\inner") != FALSE, "RemoveDirectoryA removes the now empty package folder");
373 check(std::filesystem::exists(package / "misc" / "inner" / "deep.txt"), "the package keeps the folder and file");
374 SetLastError(0);
375 check(attributes_w(L"GAME:\\misc\\inner") == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND,
376 "the removed folder no longer resolves");
377 check(!contains(list(first_w, next_w, find_close, L"GAME:\\misc\\*"), L"inner"), "and is not listed");
378 const DWORD misc = attributes_w(L"GAME:\\misc");
379 check(misc != INVALID_FILE_ATTRIBUTES && (misc & FILE_ATTRIBUTE_DIRECTORY) != 0, "its parent is still there");
380 check(mkdir_w(L"GAME:\\misc\\inner", nullptr) != FALSE, "the removed name can be made again");
381 check(list(first_w, next_w, find_close, L"GAME:\\misc\\inner\\*").size() == 2,
382 "and the new folder is empty: only . and ..");
383 }
384
385 // MoveFile: the destination is in the overlay; a moved package file is deleted by a marker.
386 {
387 check(move_w(L"GAME:\\misc\\one.txt", L"GAME:\\misc\\moved.txt") != FALSE, "MoveFileW moves a package file");
388 check(read_path(overlay / "misc" / "moved.txt") == "one", "its bytes are in the overlay under the new name");
389 check(read_path(package / "misc" / "one.txt") == "one", "the package file is not modified");
390 SetLastError(0);
391 check(attributes_w(L"GAME:\\misc\\one.txt") == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND,
392 "the old name is gone");
393 SetLastError(0);
394 check(move_ex_w(L"GAME:\\misc\\moved.txt", L"GAME:\\misc\\two.txt", 0) == FALSE &&
395 GetLastError() == ERROR_ALREADY_EXISTS,
396 "MoveFileExW will not replace a package file without MOVEFILE_REPLACE_EXISTING");
397 check(move_ex_w(L"GAME:\\misc\\moved.txt", L"GAME:\\misc\\two.txt", MOVEFILE_REPLACE_EXISTING) != FALSE,
398 "and replaces it with the flag");
399 HANDLE h = create_w(L"GAME:\\misc\\two.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
400 check(h != INVALID_HANDLE_VALUE && read_handle(h) == "one", "the replaced name reads the moved bytes");
401 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
402 check(read_path(package / "misc" / "two.txt") == "two", "the package's own two.txt is untouched");
403 check(!std::filesystem::exists(overlay / "misc" / "moved.txt"), "the overlay source of the move is gone");
404 check(move_a("GAME:\\misc\\three.txt", "GAME:\\cache\\three.txt") != FALSE &&
405 read_path(overlay / "cache" / "three.txt") == "three",
406 "MoveFileA moves into another folder");
407 check(move_w(L"GAME:\\cache\\from_template", L"GAME:\\cache\\renamed") != FALSE &&
408 std::filesystem::is_directory(overlay / "cache" / "renamed"),
409 "an overlay folder is renamed");
410 SetLastError(0);
411 check(move_w(L"GAME:\\misc", L"GAME:\\misc2") == FALSE && GetLastError() == ERROR_ACCESS_DENIED,
412 "a package folder is not moved");
413 SetLastError(0);
414 check(move_w(L"GAME:\\misc\\keep.txt", (root / "host.txt").c_str()) == FALSE &&
415 GetLastError() == ERROR_NOT_SAME_DEVICE,
416 "a move between GAME: and a host path is refused as cross-volume");
417 SetLastError(0);
418 check(move_ex_w(L"GAME:\\misc\\keep.txt", nullptr, MOVEFILE_DELAY_UNTIL_REBOOT) == FALSE &&
419 GetLastError() == ERROR_INVALID_PARAMETER,
420 "a boot-time delete of a console file is refused");
421 SetLastError(0);
422 check(move_w(L"GAME:\\misc\\gone.txt", L"GAME:\\misc\\x.txt") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND,
423 "moving a missing file reports ERROR_FILE_NOT_FOUND");
424 SetLastError(0);
425 check(move_w(L"GAME:\\misc\\keep.txt", L"GAME:\\nowhere\\keep.txt") == FALSE &&
426 GetLastError() == ERROR_PATH_NOT_FOUND,
427 "moving into a missing folder reports ERROR_PATH_NOT_FOUND");
428 }
429
430 // MOVEFILE_WRITE_THROUGH on a package file: the copy and the marker are flushed before the call returns.
431 {
432 write_path(package / "misc" / "wt.txt", "wt");
433 check(move_ex_w(L"GAME:\\misc\\wt.txt", L"GAME:\\misc\\wt_moved.txt", MOVEFILE_WRITE_THROUGH) != FALSE,
434 "MoveFileExW with MOVEFILE_WRITE_THROUGH moves a package file");
435 check(read_path(overlay / "misc" / "wt_moved.txt") == "wt", "its bytes are in the overlay");
436 SetLastError(0);
437 check(attributes_w(L"GAME:\\misc\\wt.txt") == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND,
438 "and the old name is deleted");
439 }
440
441 // CopyFile: reads where a read would, writes the overlay; an existing name counts even if only the package has it.
442 {
443 check(copy_w(L"GAME:\\misc\\keep.txt", L"GAME:\\cache\\keep_copy.txt", TRUE) != FALSE &&
444 read_path(overlay / "cache" / "keep_copy.txt") == "keep",
445 "CopyFileW copies a package file into the overlay");
446 check(read_path(package / "misc" / "keep.txt") == "keep", "and the source stays");
447 SetLastError(0);
448 check(copy_w(L"GAME:\\misc\\keep.txt", L"GAME:\\data\\sub", FALSE) == FALSE && GetLastError() == ERROR_ACCESS_DENIED,
449 "a copy onto a folder is refused");
450 write_path(package / "misc" / "target.txt", "target");
451 SetLastError(0);
452 check(copy_w(L"GAME:\\misc\\keep.txt", L"GAME:\\misc\\target.txt", TRUE) == FALSE &&
453 GetLastError() == ERROR_FILE_EXISTS,
454 "fail-if-exists sees a name only the package has");
455 check(copy_a("GAME:\\misc\\keep.txt", "GAME:\\misc\\target.txt", FALSE) != FALSE &&
456 read_path(overlay / "misc" / "target.txt") == "keep" && read_path(package / "misc" / "target.txt") == "target",
457 "CopyFileA overwrites through the overlay and leaves the package file alone");
458 const std::filesystem::path host_copy = root / "host_copy.txt";
459 check(copy_w(L"GAME:\\misc\\keep.txt", host_copy.c_str(), TRUE) != FALSE && read_path(host_copy) == "keep",
460 "a copy from GAME: to a host path works");
461 check(copy_ex_w(host_copy.c_str(), L"GAME:\\cache\\from_host.txt", nullptr, nullptr, nullptr, COPY_FILE_FAIL_IF_EXISTS) !=
462 FALSE &&
463 read_path(overlay / "cache" / "from_host.txt") == "keep",
464 "CopyFileExW copies from a host path into GAME:");
465 COPYFILE2_EXTENDED_PARAMETERS params{};
466 params.dwSize = sizeof(params);
467 params.dwCopyFlags = COPY_FILE_FAIL_IF_EXISTS;
468 check(copy2(L"GAME:\\misc\\keep.txt", L"GAME:\\cache\\copy2.txt", &params) == S_OK &&
469 read_path(overlay / "cache" / "copy2.txt") == "keep",
470 "CopyFile2 copies too");
471 check(copy2(L"GAME:\\misc\\keep.txt", L"GAME:\\misc\\two.txt", &params) == HRESULT_FROM_WIN32(ERROR_FILE_EXISTS),
472 "and returns its HRESULT for an existing name");
473 SetLastError(0);
474 check(copy_w(L"GAME:\\misc\\one.txt", L"GAME:\\cache\\one.txt", FALSE) == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND,
475 "a deleted name cannot be copied");
476 }
477
478 // SetFileAttributes: the overlay copy gets the attributes; the package keeps its own.
479 {
480 const DWORD before = ::GetFileAttributesW((package / "misc" / "keep.txt").c_str());
481 check(setattr_w(L"GAME:\\misc\\keep.txt", FILE_ATTRIBUTE_READONLY) != FALSE, "SetFileAttributesW on a package file");
482 const DWORD now = attributes_w(L"GAME:\\misc\\keep.txt");
483 check(now != INVALID_FILE_ATTRIBUTES && (now & FILE_ATTRIBUTE_READONLY) != 0, "the title sees the new attributes");
484 check(read_path(overlay / "misc" / "keep.txt") == "keep", "on a copy of the file in the overlay");
485 check(::GetFileAttributesW((package / "misc" / "keep.txt").c_str()) == before, "the package file keeps its own");
486 check(setattr_a("GAME:\\misc\\keep.txt", FILE_ATTRIBUTE_NORMAL) != FALSE &&
487 (attributes_w(L"GAME:\\misc\\keep.txt") & FILE_ATTRIBUTE_READONLY) == 0,
488 "SetFileAttributesA changes the overlay copy back");
489 check(setattr_w(L"GAME:\\data\\sub", FILE_ATTRIBUTE_HIDDEN) != FALSE &&
490 (attributes_w(L"GAME:\\data\\sub") & FILE_ATTRIBUTE_HIDDEN) != 0,
491 "a package folder's attributes are set on an overlay mirror");
492 check(count(list(first_w, next_w, find_close, L"GAME:\\data\\*"), L"sub") == 1, "which is listed once");
493 SetLastError(0);
494 check(setattr_w(L"GAME:\\misc\\one.txt", FILE_ATTRIBUTE_NORMAL) == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND,
495 "a deleted name has no attributes to set");
496 }
497
498 // Nothing leaves the package and the overlay.
499 {
500 SetLastError(0);
501 check(mkdir_w(L"GAME:\\..\\escape_dir", nullptr) == FALSE && GetLastError() == ERROR_INVALID_NAME &&
502 !std::filesystem::exists(root / "escape_dir"),
503 "a folder above GAME: is refused");
504 SetLastError(0);
505 check(move_w(L"GAME:\\misc\\keep.txt", L"GAME:\\..\\escape.txt") == FALSE && GetLastError() == ERROR_INVALID_NAME,
506 "a move above GAME: is refused");
507 SetLastError(0);
508 check(copy_w(L"GAME:\\misc\\keep.txt", L"GAME:\\C:\\x", FALSE) == FALSE && GetLastError() == ERROR_INVALID_NAME,
509 "a copy to a drive inside GAME: is refused");
510 SetLastError(0);
511 check(rmdir_w(L"GAME:\\..") == FALSE && GetLastError() == ERROR_INVALID_NAME, "removing above GAME: is refused");
512 }
513
263 // Nothing leaves the package and the overlay. 514 // Nothing leaves the package and the overlay.
264 { 515 {
265 SetLastError(0); 516 SetLastError(0);
@@ -284,6 +535,78 @@ int main() {
284 "a null listing buffer is refused"); 535 "a null listing buffer is refused");
285 } 536 }
286 537
538 // CreateFile2 and FindFirstFileExA/W (used by GDK/OneCore titles and std::filesystem).
539 {
540 const auto create2 = resolve<CreateFile2Fn>("api-ms-win-core-file-l1-2-0.dll", "CreateFile2");
541 const auto first_ex_w = resolve<FindFirstFileExWFn>("api-ms-win-core-file-l1-1-0.dll", "FindFirstFileExW");
542 const auto first_ex_a = resolve<FindFirstFileExAFn>("kernelbase.dll", "FindFirstFileExA");
543 check(create2 && first_ex_w && first_ex_a, "CreateFile2 and FindFirstFileExA/W are registered");
544
545 // CreateFile2 reads an untouched package file without modifying it.
546 write_path(package / "data" / "cf2_pkg.txt", "pkg-cf2");
547 CREATEFILE2_EXTENDED_PARAMETERS ext{};
548 ext.dwSize = sizeof(ext);
549 ext.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
550 const HANDLE h_read = create2(L"GAME:\\data\\cf2_pkg.txt", GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &ext);
551 check(h_read != INVALID_HANDLE_VALUE && read_handle(h_read) == "pkg-cf2",
552 "CreateFile2 reads a GAME: file from the package");
553 if (h_read != INVALID_HANDLE_VALUE) ::CloseHandle(h_read);
554
555 // CreateFile2 write goes to the overlay, leaving the package untouched.
556 const HANDLE h_write = create2(L"GAME:\\data\\cf2.txt", GENERIC_WRITE, 0, CREATE_ALWAYS, &ext);
557 check(h_write != INVALID_HANDLE_VALUE, "CreateFile2 creates a new GAME: file in the overlay");
558 if (h_write != INVALID_HANDLE_VALUE) {
559 DWORD written = 0;
560 ::WriteFile(h_write, "cf2", 3, &written, nullptr);
561 ::CloseHandle(h_write);
562 }
563 check(read_path(overlay / "data" / "cf2.txt") == "cf2" && !std::filesystem::exists(package / "data" / "cf2.txt"),
564 "CreateFile2 writes land in the overlay and never in the package");
565
566 // CreateFile2 refuses path traversal.
567 SetLastError(0);
568 const HANDLE h_esc = create2(L"GAME:\\..\\cf2_escape.txt", GENERIC_WRITE, 0, CREATE_ALWAYS, &ext);
569 check(h_esc == INVALID_HANDLE_VALUE && GetLastError() == ERROR_INVALID_NAME,
570 "CreateFile2 refuses a path above GAME:");
571 if (h_esc != INVALID_HANDLE_VALUE) ::CloseHandle(h_esc);
572
573 // FindFirstFileExW merges package + overlay and honours FindExInfoBasic & FindExSearchLimitToDirectories.
574 WIN32_FIND_DATAW fd{};
575 std::vector<std::wstring> basic_names;
576 bool alt_empty = true;
577 HANDLE hf = first_ex_w(L"GAME:\\data\\*", FindExInfoBasic, &fd, FindExSearchNameMatch, nullptr, 0);
578 check(hf != INVALID_HANDLE_VALUE, "FindFirstFileExW opens a GAME: directory listing");
579 if (hf != INVALID_HANDLE_VALUE) {
580 do {
581 basic_names.emplace_back(fd.cFileName);
582 if (fd.cAlternateFileName[0] != L'\0') alt_empty = false;
583 } while (next_w(hf, &fd));
584 find_close(hf);
585 }
586 check(contains(basic_names, L"hello.txt") && contains(basic_names, L"cf2.txt") && !contains(basic_names, L"bye.txt"),
587 "FindFirstFileExW merges overlay + package and hides deleted files");
588 check(alt_empty, "FindFirstFileExW(FindExInfoBasic) leaves cAlternateFileName empty");
589
590 std::vector<std::wstring> dir_names;
591 HANDLE hdir = first_ex_w(L"GAME:\\data\\*", FindExInfoStandard, &fd, FindExSearchLimitToDirectories, nullptr, 0);
592 check(hdir != INVALID_HANDLE_VALUE, "FindFirstFileExW(FindExSearchLimitToDirectories) succeeds");
593 if (hdir != INVALID_HANDLE_VALUE) {
594 do {
595 dir_names.emplace_back(fd.cFileName);
596 } while (next_w(hdir, &fd));
597 find_close(hdir);
598 }
599 check(contains(dir_names, L"sub") && !contains(dir_names, L"hello.txt"),
600 "FindFirstFileExW(FindExSearchLimitToDirectories) returns only directories");
601
602 // FindFirstFileExA works on GAME: paths too.
603 WIN32_FIND_DATAA fda{};
604 HANDLE hfa = first_ex_a("GAME:\\data\\cf2.txt", FindExInfoBasic, &fda, FindExSearchNameMatch, nullptr, 0);
605 check(hfa != INVALID_HANDLE_VALUE && std::string(fda.cFileName) == "cf2.txt",
606 "FindFirstFileExA finds an overlay file under GAME:");
607 if (hfa != INVALID_HANDLE_VALUE) find_close(hfa);
608 }
609
287 std::filesystem::remove_all(root); 610 std::filesystem::remove_all(root);
288 std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); 611 std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures);
289 return g_failures == 0 ? 0 : 1; 612 return g_failures == 0 ? 0 : 1;
diff --git a/runtime/test/fixtures/tiny_bundled_load.cpp b/runtime/test/fixtures/tiny_bundled_load.cpp
index 51fbaac72..f2a3b7f36 100644
--- a/runtime/test/fixtures/tiny_bundled_load.cpp
+++ b/runtime/test/fixtures/tiny_bundled_load.cpp
@@ -27,6 +27,15 @@ int main() {
27 if (GetModuleHandleW(L"tiny_bundled_dll.dll") != nullptr) 27 if (GetModuleHandleW(L"tiny_bundled_dll.dll") != nullptr)
28 return fail("GetModuleHandleW before LoadLibrary should be NULL", 0); 28 return fail("GetModuleHandleW before LoadLibrary should be NULL", 0);
29 29
30 // DONT_RESOLVE_DLL_REFERENCES must fail explicitly rather than silently resolving imports and running DllMain.
31 SetLastError(0);
32 if (LoadLibraryExW(L"tiny_bundled_dll.dll", nullptr, DONT_RESOLVE_DLL_REFERENCES) != nullptr ||
33 GetLastError() != ERROR_NOT_SUPPORTED) {
34 return fail("LoadLibraryExW(DONT_RESOLVE_DLL_REFERENCES) fails with ERROR_NOT_SUPPORTED", GetLastError());
35 }
36 if (GetModuleHandleW(L"tiny_bundled_dll.dll") != nullptr)
37 return fail("DONT_RESOLVE_DLL_REFERENCES must not map or register the bundled DLL", 0);
38
30 HMODULE mod = LoadLibraryW(L"tiny_bundled_dll.dll"); 39 HMODULE mod = LoadLibraryW(L"tiny_bundled_dll.dll");
31 if (!mod) return fail("LoadLibraryW(tiny_bundled_dll.dll)", GetLastError()); 40 if (!mod) return fail("LoadLibraryW(tiny_bundled_dll.dll)", GetLastError());
32 41
diff --git a/runtime/test/fixtures/tiny_gdk_load.cpp b/runtime/test/fixtures/tiny_gdk_load.cpp
index 291d3a5d7..f4c6a163c 100644
--- a/runtime/test/fixtures/tiny_gdk_load.cpp
+++ b/runtime/test/fixtures/tiny_gdk_load.cpp
@@ -68,10 +68,32 @@ int main() {
68 reinterpret_cast<Close>(vtable[17])(obj, queue); 68 reinterpret_cast<Close>(vtable[17])(obj, queue);
69 reinterpret_cast<Release>(vtable[2])(obj); 69 reinterpret_cast<Release>(vtable[2])(obj);
70 70
71 // A class not served yet (XNetworkingImpl) is refused, with the out pointer cleared. 71 // XNetworkingImpl is served through QueryApiImpl (slot 15: XNetworkingGetConnectivityHint).
72 const GUID networking = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}}; 72 const GUID networking = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}};
73 void* net_obj = nullptr;
74 hr = query(&networking, networking, &net_obj);
75 if (hr != S_OK || !net_obj)
76 return fail("QueryApiImpl hands out XNetworkingImpl", static_cast<unsigned long>(hr));
77 void* const* net_vtable = *static_cast<void* const* const*>(net_obj);
78 struct Hint {
79 UINT32 level;
80 UINT32 cost;
81 UINT32 iana;
82 bool init;
83 bool appr;
84 bool over;
85 bool roam;
86 } hint{};
87 using GetHint = HRESULT(STDMETHODCALLTYPE*)(void*, Hint*);
88 hr = reinterpret_cast<GetHint>(net_vtable[15])(net_obj, &hint);
89 if (hr != S_OK || !hint.init)
90 return fail("XNetworkingImpl slot 15 (XNetworkingGetConnectivityHint)", static_cast<unsigned long>(hr));
91 reinterpret_cast<Release>(net_vtable[2])(net_obj);
92
93 // A class not served yet (an unprovided class id) is refused, with the out pointer cleared.
94 const GUID unprovided = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}};
73 void* out = reinterpret_cast<void*>(1); 95 void* out = reinterpret_cast<void*>(1);
74 hr = query(&networking, networking, &out); 96 hr = query(&unprovided, unprovided, &out);
75 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr) 97 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr)
76 return fail("QueryApiImpl refuses an unprovided class and clears its out pointer", static_cast<unsigned long>(hr)); 98 return fail("QueryApiImpl refuses an unprovided class and clears its out pointer", static_cast<unsigned long>(hr));
77 hr = uninit(); 99 hr = uninit();
diff --git a/runtime/test/fixtures/tiny_tls_cb_only.cpp b/runtime/test/fixtures/tiny_tls_cb_only.cpp
new file mode 100644
index 000000000..d8062c073
--- /dev/null
+++ b/runtime/test/fixtures/tiny_tls_cb_only.cpp
@@ -0,0 +1,42 @@
1// Callback-only static TLS fixture DLL: defines _tls_used with StartAddressOfRawData == EndAddressOfRawData == 0
2// and SizeOfZeroFill == 0 while providing a TLS callback (no CRT .tls section). Ordinary test code, not game data.
3#include <windows.h>
4
5namespace {
6
7ULONG g_tls_index = 0;
8int g_attach_count = 0;
9int g_detach_count = 0;
10volatile DWORD g_watched_thread = 0;
11int g_thread_attach_count = 0;
12int g_thread_detach_count = 0;
13
14void NTAPI tls_callback(PVOID, DWORD reason, PVOID) {
15 if (reason == DLL_PROCESS_ATTACH) ++g_attach_count;
16 if (reason == DLL_PROCESS_DETACH) ++g_detach_count;
17 if (GetCurrentThreadId() == g_watched_thread) {
18 if (reason == DLL_THREAD_ATTACH) ++g_thread_attach_count;
19 if (reason == DLL_THREAD_DETACH) ++g_thread_detach_count;
20 }
21}
22
23PIMAGE_TLS_CALLBACK g_callbacks[] = {tls_callback, nullptr};
24
25} // namespace
26
27extern "C" const IMAGE_TLS_DIRECTORY64 _tls_used = {
28 0, // StartAddressOfRawData
29 0, // EndAddressOfRawData
30 reinterpret_cast<ULONGLONG>(&g_tls_index), // AddressOfIndex
31 reinterpret_cast<ULONGLONG>(g_callbacks), // AddressOfCallBacks
32 0, // SizeOfZeroFill
33 0, // Characteristics
34};
35
36extern "C" __declspec(dllexport) void __cdecl tiny_tls_cb_watch_thread(DWORD id) { g_watched_thread = id; }
37extern "C" __declspec(dllexport) int __cdecl tiny_tls_cb_attach_count() { return g_attach_count; }
38extern "C" __declspec(dllexport) int __cdecl tiny_tls_cb_detach_count() { return g_detach_count; }
39extern "C" __declspec(dllexport) int __cdecl tiny_tls_cb_thread_attach_count() { return g_thread_attach_count; }
40extern "C" __declspec(dllexport) int __cdecl tiny_tls_cb_thread_detach_count() { return g_thread_detach_count; }
41
42extern "C" BOOL WINAPI DllMainCRTStartup(HINSTANCE, DWORD, LPVOID) { return TRUE; }
diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp
index b1b5d7432..1226e513d 100644
--- a/runtime/test/frame_pacer_test.cpp
+++ b/runtime/test/frame_pacer_test.cpp
@@ -441,6 +441,31 @@ int main() {
441 EXPECT(stats[0].time_us == 5 * period && stats[0].percent_scanned == 0.0f); 441 EXPECT(stats[0].time_us == 5 * period && stats[0].percent_scanned == 0.0f);
442 } 442 }
443 443
444 // Rescheduling changes future origins but not the vblank an issued token was due at.
445 {
446 ManualFrameClock clock;
447 FramePacer pacer(clock);
448 EXPECT(setup(pacer, 1, period / 4));
449 clock.advance_us(period + period / 4);
450 std::uint64_t token = 0;
451 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &token) == pacer_hr::ok);
452 EXPECT(pacer.schedule_frame_event(frame_event_origin, period / 2, 0) == pacer_hr::ok);
453
454 clock.advance_us(3 * period / 4); // vblank 2, still the deadline of the original token
455 EXPECT(pacer.present_timing(token).late_us == 0);
456 clock.advance_us(period / 4);
457 const auto timing = pacer.present_timing(token);
458 EXPECT(timing.late_us == period / 4);
459 const auto sync = decide_present_sync(timing.late_us, timing.period_us, 30.0f);
460 EXPECT(sync == PresentSync::immediate);
461 pacer.commit_present_token(token, 1, sync);
462
463 FrameStatistic display{};
464 std::uint32_t count = 1;
465 EXPECT(pacer.get_frame_statistics(token, stat_display, &count, &display) == pacer_hr::ok);
466 EXPECT(count == 1 && display.percent_scanned == 25.0f);
467 }
468
444 // A frame behind one that still waits for its vblank cannot be shown at once (it would overtake it): not late. 469 // A frame behind one that still waits for its vblank cannot be shown at once (it would overtake it): not late.
445 { 470 {
446 ManualFrameClock clock; 471 ManualFrameClock clock;
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp
index f525d1cb9..a65b444a1 100644
--- a/runtime/test/gameinput_test.cpp
+++ b/runtime/test/gameinput_test.cpp
@@ -393,6 +393,33 @@ void test_keyboard_pad_sticks(IGameInput* input, IGameInputDevice* kb) {
393 } 393 }
394 check(monotonic && polls < 100 && sticks_at_rest(st), "keyboard pad: right stick decays to 0 when the mouse stops"); 394 check(monotonic && polls < 100 && sticks_at_rest(st), "keyboard pad: right stick decays to 0 when the mouse stops");
395 395
396 // LEONIDA_MOUSE_SENSITIVITY scales the axis units per count: 2 doubles, 0.5 halves; out of range clamps.
397 auto settle = [&] {
398 for (int i = 0; i < 200 && !sticks_at_rest(pad_state(input, kb)); ++i) rt::gameinput::poll();
399 };
400 set_env("LEONIDA_MOUSE_SENSITIVITY", "2");
401 rt::gameinput::reload_config();
402 g_cursor_x += 10;
403 rt::gameinput::poll();
404 check(approx(pad_state(input, kb).rightThumbstickX, 20480 / 32767.0f), "keyboard pad: mouse sensitivity 2 doubles the stick");
405 settle();
406 set_env("LEONIDA_MOUSE_SENSITIVITY", "0.5");
407 rt::gameinput::reload_config();
408 g_cursor_x -= 10;
409 rt::gameinput::poll();
410 check(approx(pad_state(input, kb).rightThumbstickX, -5120 / 32767.0f), "keyboard pad: mouse sensitivity 0.5 halves the stick");
411 settle();
412 set_env("LEONIDA_MOUSE_SENSITIVITY", "100");
413 rt::gameinput::reload_config();
414 check(rt::gameinput::config().mouse_sensitivity == 10.0f, "keyboard pad: mouse sensitivity clamps to 10");
415 set_env("LEONIDA_MOUSE_SENSITIVITY", "0");
416 rt::gameinput::reload_config();
417 check(approx(rt::gameinput::config().mouse_sensitivity, 0.1f), "keyboard pad: mouse sensitivity clamps to 0.1");
418 set_env("LEONIDA_MOUSE_SENSITIVITY", nullptr);
419 rt::gameinput::reload_config();
420 check(rt::gameinput::config().mouse_sensitivity == 1.0f && rt::gameinput::config().ds_trigger_gain == 1.0f,
421 "keyboard pad: mouse sensitivity defaults to 1 and leaves the trigger gain alone");
422
396 g_keys[VK_RBUTTON] = true; 423 g_keys[VK_RBUTTON] = true;
397 rt::gameinput::poll(); 424 rt::gameinput::poll();
398 st = pad_state(input, kb); 425 st = pad_state(input, kb);
@@ -608,6 +635,20 @@ void test_aggregate_device(IGameInput* input) {
608 IGameInputReading* r = nullptr; 635 IGameInputReading* r = nullptr;
609 check(input->GetCurrentReading(GameInputKindGamepad, agg, &r) == GAMEINPUT_E_READING_NOT_FOUND && !r, 636 check(input->GetCurrentReading(GameInputKindGamepad, agg, &r) == GAMEINPUT_E_READING_NOT_FOUND && !r,
610 "aggregate device returns READING_NOT_FOUND when no pads are connected"); 637 "aggregate device returns READING_NOT_FOUND when no pads are connected");
638 check(input->GetCurrentReading(GameInputKindKeyboard, agg, &r) == GAMEINPUT_E_READING_NOT_FOUND && !r,
639 "aggregate device returns READING_NOT_FOUND for kind mismatch with no pads");
640
641 // Callback registration guards for aggregate device
642 GameInputCallbackToken reading_tok = 0xbeef;
643 check(input->RegisterReadingCallback(agg, GameInputKindGamepad, 0.0f, nullptr, on_reading, &reading_tok) == E_NOTIMPL &&
644 reading_tok == kInvalidCallbackToken,
645 "RegisterReadingCallback rejects aggregate device with E_NOTIMPL and invalid token");
646
647 GameInputCallbackToken device_tok = 0xbeef;
648 check(input->RegisterDeviceCallback(agg, GameInputKindGamepad, GameInputDeviceConnected,
649 GameInputBlockingEnumeration, nullptr, on_device, &device_tok) == E_NOTIMPL &&
650 device_tok == kInvalidCallbackToken,
651 "RegisterDeviceCallback rejects aggregate device with E_NOTIMPL and invalid token");
611 652
612 // Attach a virtual pad and verify aggregate device yields readings from it 653 // Attach a virtual pad and verify aggregate device yields readings from it
613 Pad xbox; 654 Pad xbox;
@@ -624,6 +665,10 @@ void test_aggregate_device(IGameInput* input) {
624 r->Release(); 665 r->Release();
625 } 666 }
626 667
668 IGameInputReading* r_mismatch = nullptr;
669 check(input->GetCurrentReading(GameInputKindKeyboard, agg, &r_mismatch) == GAMEINPUT_E_READING_NOT_FOUND && !r_mismatch,
670 "aggregate device rejects kind mismatch even when pad is connected");
671
627 SDL_SetJoystickVirtualButton(xbox.js, SDL_GAMEPAD_BUTTON_SOUTH, false); 672 SDL_SetJoystickVirtualButton(xbox.js, SDL_GAMEPAD_BUTTON_SOUTH, false);
628 rt::gameinput::poll(); 673 rt::gameinput::poll();
629 IGameInputReading* r2 = nullptr; 674 IGameInputReading* r2 = nullptr;
@@ -1062,6 +1107,17 @@ int main() {
1062 check(input->GetPreviousReading(idle, GameInputKindGamepad, dev, nullptr) == E_POINTER && 1107 check(input->GetPreviousReading(idle, GameInputKindGamepad, dev, nullptr) == E_POINTER &&
1063 input->GetPreviousReading(nullptr, GameInputKindGamepad, dev, &hit) == E_INVALIDARG && !hit, 1108 input->GetPreviousReading(nullptr, GameInputKindGamepad, dev, &hit) == E_INVALIDARG && !hit,
1064 "history: a null output is E_POINTER, a null reference E_INVALIDARG"); 1109 "history: a null output is E_POINTER, a null reference E_INVALIDARG");
1110 // GetTemporalReading: E_NOTIMPL with a null reading, as GameInput v0 itself, for a timestamp in the history, one
1111 // before it and the current time, with and without a device filter.
1112 const uint64_t idle_us = idle->GetTimestamp();
1113 bool temporal_notimpl = true;
1114 for (const uint64_t at : {idle_us, idle_us - 1'000'000, input->GetCurrentTimestamp()})
1115 for (IGameInputDevice* filter : {dev, static_cast<IGameInputDevice*>(nullptr)}) {
1116 IGameInputReading* temporal = idle; // a stale value the call must clear
1117 temporal_notimpl &= input->GetTemporalReading(at, filter, &temporal) == E_NOTIMPL && !temporal;
1118 }
1119 check(temporal_notimpl && input->GetTemporalReading(idle_us, dev, nullptr) == E_POINTER,
1120 "history: GetTemporalReading is E_NOTIMPL with a null reading, as in GameInput v0");
1065 1121
1066 // Two pads in one stream, one poll each: A on the Xbox pad, B on the DualSense, Y on the Xbox pad. 1122 // Two pads in one stream, one poll each: A on the Xbox pad, B on the DualSense, Y on the Xbox pad.
1067 IGameInputReading* start = current(input, dev); 1123 IGameInputReading* start = current(input, dev);
diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp
index d651e885b..48724afae 100644
--- a/runtime/test/gfx10_descriptors_test.cpp
+++ b/runtime/test/gfx10_descriptors_test.cpp
@@ -209,6 +209,55 @@ int main() {
209 CHECK(vulkan_view_format(VK_FORMAT_R8G8B8A8_UINT, 20, true) == VK_FORMAT_R32_UINT); 209 CHECK(vulkan_view_format(VK_FORMAT_R8G8B8A8_UINT, 20, true) == VK_FORMAT_R32_UINT);
210 CHECK(vulkan_view_format(VK_FORMAT_UNDEFINED, 56) == VK_FORMAT_UNDEFINED); 210 CHECK(vulkan_view_format(VK_FORMAT_UNDEFINED, 56) == VK_FORMAT_UNDEFINED);
211 211
212 // Depth/stencil images are only compatible with their own format, even with allow_channel_cast = true,
213 // and colour images never resolve to a depth/stencil view format.
214 for (const VkFormat ds : {VK_FORMAT_D16_UNORM, VK_FORMAT_X8_D24_UNORM_PACK32, VK_FORMAT_D32_SFLOAT,
215 VK_FORMAT_S8_UINT, VK_FORMAT_D16_UNORM_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT,
216 VK_FORMAT_D32_SFLOAT_S8_UINT})
217 CHECK(is_depth_stencil_format(ds));
218 for (const VkFormat colour : {VK_FORMAT_R16_UNORM, VK_FORMAT_R16_SFLOAT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32_UINT,
219 VK_FORMAT_R8_UINT, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_UNDEFINED})
220 CHECK(!is_depth_stencil_format(colour));
221 for (const bool cast : {false, true}) {
222 CHECK(vulkan_view_format(VK_FORMAT_D16_UNORM, 7, cast) == VK_FORMAT_D16_UNORM);
223 for (const std::uint32_t bad_d16 : {8u, 11u, 12u, 13u, 1u, 20u, 22u, 56u, 141u, 146u})
224 CHECK(vulkan_view_format(VK_FORMAT_D16_UNORM, bad_d16, cast) == VK_FORMAT_UNDEFINED);
225 CHECK(vulkan_view_format(VK_FORMAT_D32_SFLOAT, 22, cast) == VK_FORMAT_D32_SFLOAT);
226 for (const std::uint32_t bad_d32 : {20u, 21u, 7u, 13u, 56u, 141u, 146u})
227 CHECK(vulkan_view_format(VK_FORMAT_D32_SFLOAT, bad_d32, cast) == VK_FORMAT_UNDEFINED);
228 CHECK(vulkan_view_format(VK_FORMAT_D24_UNORM_S8_UINT, 141, cast) == VK_FORMAT_D24_UNORM_S8_UINT);
229 CHECK(vulkan_view_format(VK_FORMAT_X8_D24_UNORM_PACK32, 141, cast) == VK_FORMAT_X8_D24_UNORM_PACK32);
230 CHECK(vulkan_view_format(VK_FORMAT_D32_SFLOAT_S8_UINT, 146, cast) == VK_FORMAT_D32_SFLOAT_S8_UINT);
231 CHECK(vulkan_view_format(VK_FORMAT_S8_UINT, 5, cast) == VK_FORMAT_S8_UINT);
232 for (const std::uint32_t bad_ds : {1u, 5u, 7u, 13u, 20u, 21u, 22u, 56u}) {
233 CHECK(vulkan_view_format(VK_FORMAT_D24_UNORM_S8_UINT, bad_ds, cast) == VK_FORMAT_UNDEFINED);
234 CHECK(vulkan_view_format(VK_FORMAT_D32_SFLOAT_S8_UINT, bad_ds, cast) == VK_FORMAT_UNDEFINED);
235 }
236 CHECK(vulkan_view_format(VK_FORMAT_D24_UNORM_S8_UINT, 146, cast) == VK_FORMAT_UNDEFINED);
237 CHECK(vulkan_view_format(VK_FORMAT_D32_SFLOAT_S8_UINT, 141, cast) == VK_FORMAT_UNDEFINED);
238 // Colour images never resolve to a depth/stencil view format, while normal colour casts remain intact.
239 CHECK(vulkan_view_format(VK_FORMAT_R32_SFLOAT, 141, cast) == VK_FORMAT_UNDEFINED);
240 CHECK(vulkan_view_format(VK_FORMAT_R32_SFLOAT, 146, cast) == VK_FORMAT_UNDEFINED);
241 CHECK(vulkan_view_format(VK_FORMAT_R8G8B8A8_UNORM, 141, cast) == VK_FORMAT_UNDEFINED);
242 CHECK(vulkan_view_format(VK_FORMAT_R8G8B8A8_UNORM, 146, cast) == VK_FORMAT_UNDEFINED);
243 CHECK(vulkan_view_format(VK_FORMAT_R16_UNORM, 13, cast) == VK_FORMAT_R16_SFLOAT);
244 CHECK(vulkan_view_format(VK_FORMAT_R32_SFLOAT, 20, cast) == VK_FORMAT_R32_UINT);
245 }
246 // Exhaustive invariant across the whole format table: depth/stencil images only accept their own code,
247 // and colour images never produce a depth/stencil view format.
248 for (const FormatRow& img : format_table) {
249 for (const FormatRow& view : format_table) {
250 for (const bool cast : {false, true}) {
251 const VkFormat resolved = vulkan_view_format(img.vulkan, view.gfx10, cast);
252 if (is_depth_stencil_format(img.vulkan)) {
253 CHECK(resolved == (img.gfx10 == view.gfx10 ? img.vulkan : VK_FORMAT_UNDEFINED));
254 } else {
255 CHECK(!is_depth_stencil_format(resolved));
256 }
257 }
258 }
259 }
260
212 // DST_SEL as a component mapping. 261 // DST_SEL as a component mapping.
213 const auto same = [](const VkComponentMapping& m, VkComponentSwizzle r, VkComponentSwizzle g, VkComponentSwizzle b, 262 const auto same = [](const VkComponentMapping& m, VkComponentSwizzle r, VkComponentSwizzle g, VkComponentSwizzle b,
214 VkComponentSwizzle a) { return m.r == r && m.g == g && m.b == b && m.a == a; }; 263 VkComponentSwizzle a) { return m.r == r && m.g == g && m.b == b && m.a == a; };
diff --git a/runtime/test/glsl/ps_typeless_float.frag b/runtime/test/glsl/ps_typeless_float.frag
new file mode 100644
index 000000000..ab3afaff9
--- /dev/null
+++ b/runtime/test/glsl/ps_typeless_float.frag
@@ -0,0 +1,8 @@
1#version 460
2// A pixel shader standing in for a translated one in d3d12_typeless_families_test (D3D-275): a constant that FLOAT
3// keeps, and UNORM views clamp (-2 to 0, 1.5 to 1) and round (0.25). The host draw's HLSL writes the same.
4layout(location = 0) out vec4 target;
5
6void main() {
7 target = vec4(0.5, -2.0, 1.5, 0.25);
8}
diff --git a/runtime/test/glsl/ps_typeless_uint.frag b/runtime/test/glsl/ps_typeless_uint.frag
new file mode 100644
index 000000000..cf69e3591
--- /dev/null
+++ b/runtime/test/glsl/ps_typeless_uint.frag
@@ -0,0 +1,9 @@
1#version 460
2// A pixel shader standing in for a translated one in d3d12_typeless_families_test (D3D-275): an integer constant
3// every UINT view down to R10G10B10A2_UINT holds (7 is 0x00000007 in R32_UINT, not a float's bits). The host draw's
4// HLSL writes the same.
5layout(location = 0) out uvec4 target;
6
7void main() {
8 target = uvec4(7u, 300u, 1000u, 3u);
9}
diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp
index e3360fca7..8b7b7b179 100644
--- a/runtime/test/loader_tls_test.cpp
+++ b/runtime/test/loader_tls_test.cpp
@@ -307,36 +307,139 @@ void test_thread_outlives_loader(const fs::path& dll) {
307 "its copy is freed when it ends after the Loader, with no callback into the unmapped image"); 307 "its copy is freed when it ends after the Loader, with no callback into the unmapped image");
308} 308}
309 309
310void test_second_tls_module_rejected(const fs::path& dll, const fs::path& temp) { 310void test_multiple_tls_modules(const fs::path& dll, const fs::path& temp) {
311 std::printf("\n-- one mapped TLS module at a time --\n"); 311 std::printf("\n-- multiple simultaneous mapped TLS modules --\n");
312 const fs::path copy = temp / "tiny_tls_second.dll"; 312 const fs::path copy2 = temp / "tiny_tls_second.dll";
313 const fs::path copy3 = temp / "tiny_tls_third.dll";
313 // CopyFileW, not fs::copy_file: MSVC's copy_file calls CopyFile2, which Wine 9 doesn't implement. 314 // CopyFileW, not fs::copy_file: MSVC's copy_file calls CopyFile2, which Wine 9 doesn't implement.
314 check(CopyFileW(dll.c_str(), copy.c_str(), FALSE) != 0, "copied the TLS fixture under a second name"); 315 check(CopyFileW(dll.c_str(), copy2.c_str(), FALSE) != 0, "copied the TLS fixture under a second name");
316 check(CopyFileW(dll.c_str(), copy3.c_str(), FALSE) != 0, "copied the TLS fixture under a third name");
315 317
316 { 318 {
317 rt::Loader loader(dll.parent_path()); 319 rt::Loader loader(dll.parent_path());
318 rt::Module& first = loader.load(dll); 320 rt::Module& first = loader.load(dll);
319 check(first.tls_index != rt::kNoTlsIndex, "the first TLS module is initialized"); 321 rt::Module& second = loader.load(copy2);
320 322 rt::Module& third = loader.load(copy3);
321 bool rejected = false; 323 loader.initialise();
322 std::string message; 324
323 try { 325 check(first.tls_index != rt::kNoTlsIndex && second.tls_index != rt::kNoTlsIndex &&
324 loader.load(copy); 326 third.tls_index != rt::kNoTlsIndex,
325 } catch (const std::runtime_error& e) { 327 "all three simultaneous TLS modules receive reserved module TLS indices");
326 rejected = true; 328 check(first.tls_index != second.tls_index && first.tls_index != third.tls_index &&
327 message = e.what(); 329 second.tls_index != third.tls_index,
328 } 330 "each simultaneous TLS module gets a distinct OS module TLS index");
329 check(rejected, "a second mapped module with TLS is rejected instead of sharing a slot"); 331
330 check(message.find("only one manually mapped module") != std::string::npos, 332 auto get1 = find_export<int(__cdecl*)()>(first, "tiny_tls_get");
331 "the rejection explains the one-module TLS limit"); 333 auto set1 = find_export<void(__cdecl*)(int)>(first, "tiny_tls_set");
334 auto get2 = find_export<int(__cdecl*)()>(second, "tiny_tls_get");
335 auto set2 = find_export<void(__cdecl*)(int)>(second, "tiny_tls_set");
336 auto get3 = find_export<int(__cdecl*)()>(third, "tiny_tls_get");
337 auto set3 = find_export<void(__cdecl*)(int)>(third, "tiny_tls_set");
338 auto watch1 = find_export<void(__cdecl*)(DWORD)>(first, "tiny_tls_watch_thread");
339 auto watch2 = find_export<void(__cdecl*)(DWORD)>(second, "tiny_tls_watch_thread");
340 auto watch3 = find_export<void(__cdecl*)(DWORD)>(third, "tiny_tls_watch_thread");
341 auto pa1 = find_export<int(__cdecl*)()>(first, "tiny_tls_attach_count");
342 auto pa2 = find_export<int(__cdecl*)()>(second, "tiny_tls_attach_count");
343 auto pa3 = find_export<int(__cdecl*)()>(third, "tiny_tls_attach_count");
344 auto ta1 = find_export<int(__cdecl*)()>(first, "tiny_tls_thread_attach_count");
345 auto ta2 = find_export<int(__cdecl*)()>(second, "tiny_tls_thread_attach_count");
346 auto ta3 = find_export<int(__cdecl*)()>(third, "tiny_tls_thread_attach_count");
347 auto td1 = find_export<int(__cdecl*)()>(first, "tiny_tls_thread_detach_count");
348 auto td2 = find_export<int(__cdecl*)()>(second, "tiny_tls_thread_detach_count");
349 auto td3 = find_export<int(__cdecl*)()>(third, "tiny_tls_thread_detach_count");
350
351 check(get1() == 7 && get2() == 7 && get3() == 7, "all three modules start from their template value 7");
352 set1(101);
353 set2(202);
354 set3(303);
355 check(get1() == 101 && get2() == 202 && get3() == 303,
356 "writes to each module's TLS slot stay isolated on the main thread");
357
358 // A worker thread started after load() must get its own fresh template copies for all three modules and run
359 // DLL_THREAD_ATTACH / DLL_THREAD_DETACH callbacks on all three.
360 struct WorkerCtx {
361 int(__cdecl* get1)();
362 void(__cdecl* set1)(int);
363 int(__cdecl* get2)();
364 void(__cdecl* set2)(int);
365 int(__cdecl* get3)();
366 void(__cdecl* set3)(int);
367 int init1 = 0, init2 = 0, init3 = 0;
368 int after1 = 0, after2 = 0, after3 = 0;
369 };
370 WorkerCtx ctx{get1, set1, get2, set2, get3, set3};
371 HANDLE thread = CreateThread(
372 nullptr, 0,
373 [](void* p) -> DWORD {
374 auto* c = static_cast<WorkerCtx*>(p);
375 c->init1 = c->get1();
376 c->init2 = c->get2();
377 c->init3 = c->get3();
378 c->set1(1111);
379 c->set2(2222);
380 c->set3(3333);
381 c->after1 = c->get1();
382 c->after2 = c->get2();
383 c->after3 = c->get3();
384 return 0;
385 },
386 &ctx, CREATE_SUSPENDED, nullptr);
387 const DWORD tid = GetThreadId(thread);
388 watch1(tid);
389 watch2(tid);
390 watch3(tid);
391 ResumeThread(thread);
392 WaitForSingleObject(thread, INFINITE);
393 CloseHandle(thread);
394
395 check(ctx.init1 == 7 && ctx.init2 == 7 && ctx.init3 == 7,
396 "worker thread receives fresh template copies for all three modules");
397 check(ctx.after1 == 1111 && ctx.after2 == 2222 && ctx.after3 == 3333,
398 "worker thread writes stay isolated across all three modules");
399 check(get1() == 101 && get2() == 202 && get3() == 303,
400 "main thread TLS values are untouched by the worker thread");
401 check(pa1() == 1 && pa2() == 1 && pa3() == 1,
402 "each of the three modules received DLL_PROCESS_ATTACH once");
403 check(ta1() == 1 && ta2() == 1 && ta3() == 1,
404 "each of the three modules received DLL_THREAD_ATTACH once for the worker");
405 check(td1() == 1 && td2() == 1 && td3() == 1,
406 "each of the three modules received DLL_THREAD_DETACH once for the worker");
407 }
408
409 // Callback-only TLS module (tls_raw_size + tls_zero_fill == 0): must still receive DLL_THREAD_ATTACH and
410 // DLL_THREAD_DETACH on worker threads.
411 const fs::path cb_only_dll = dll.parent_path() / "tiny_tls_cb_only.dll";
412 if (fs::exists(cb_only_dll)) {
413 rt::Loader loader(cb_only_dll.parent_path());
414 rt::Module& m = loader.load(cb_only_dll);
415 loader.initialise();
416
417 auto watch = find_export<void(__cdecl*)(DWORD)>(m, "tiny_tls_cb_watch_thread");
418 auto pa = find_export<int(__cdecl*)()>(m, "tiny_tls_cb_attach_count");
419 auto ta = find_export<int(__cdecl*)()>(m, "tiny_tls_cb_thread_attach_count");
420 auto td = find_export<int(__cdecl*)()>(m, "tiny_tls_cb_thread_detach_count");
421
422 check(m.tls_raw_size == 0 && m.tls_zero_fill == 0 && m.tls_block == nullptr,
423 "callback-only TLS fixture has no TLS data block");
424 check(m.tls_slot != rt::kNoTlsIndex, "callback-only TLS fixture is assigned a TLS slot");
425
426 HANDLE thread = CreateThread(nullptr, 0, [](void*) -> DWORD { return 0; }, nullptr, CREATE_SUSPENDED, nullptr);
427 watch(GetThreadId(thread));
428 ResumeThread(thread);
429 WaitForSingleObject(thread, INFINITE);
430 CloseHandle(thread);
431
432 check(pa() == 1, "callback-only TLS module received DLL_PROCESS_ATTACH once");
433 check(ta() == 1, "callback-only TLS module received DLL_THREAD_ATTACH once");
434 check(td() == 1, "callback-only TLS module received DLL_THREAD_DETACH once");
332 } 435 }
333 436
334 // After the first loader restores its slot, the copy loads normally. 437 // After the loader is destroyed, all slots are released and reusable.
335 { 438 {
336 rt::Loader loader(copy.parent_path()); 439 rt::Loader loader(copy2.parent_path());
337 rt::Module& m = loader.load(copy); 440 rt::Module& m = loader.load(copy2);
338 check(m.tls_index != rt::kNoTlsIndex, "the copied TLS module loads after the first loader is destroyed"); 441 check(m.tls_index != rt::kNoTlsIndex, "slots are reusable after the first loader is destroyed");
339 check(find_export<int(__cdecl*)()>(m, "tiny_tls_get")() == 7, "the copied module reads its template value"); 442 check(find_export<int(__cdecl*)()>(m, "tiny_tls_get")() == 7, "the reloaded module reads its template value");
340 } 443 }
341} 444}
342 445
@@ -370,7 +473,7 @@ int main(int argc, char** argv) {
370 test_tls(tls_dll); 473 test_tls(tls_dll);
371 test_thread_events(tls_dll); 474 test_thread_events(tls_dll);
372 test_thread_outlives_loader(tls_dll); 475 test_thread_outlives_loader(tls_dll);
373 test_second_tls_module_rejected(tls_dll, temp.path); 476 test_multiple_tls_modules(tls_dll, temp.path);
374 } catch (const std::exception& e) { 477 } catch (const std::exception& e) {
375 ++g_checks; 478 ++g_checks;
376 ++g_failures; 479 ++g_failures;
diff --git a/runtime/test/process_cmdline_test.cpp b/runtime/test/process_cmdline_test.cpp
index 8f35a8ef7..01f1b38a5 100644
--- a/runtime/test/process_cmdline_test.cpp
+++ b/runtime/test/process_cmdline_test.cpp
@@ -112,6 +112,66 @@ void check_winmain(const std::wstring& program, const std::vector<std::wstring>&
112 } 112 }
113 } 113 }
114} 114}
115
116// msvcrt.dll's __getmainargs/__wgetmainargs (what a MinGW or old-MSVC CRT startup calls) hand out the game's argv and
117// the process environment. The wide environment (_wenviron) does not exist until a wide environment function has run,
118// and the narrow table is reallocated by _putenv, so both must be read at the call, not remembered by
119// set_command_line (RT-136). `name=value` must be found in `env`, whatever was set before or after set_command_line.
120template <typename C, typename Fn>
121bool env_has(Fn getmainargs, const C* entry) {
122 int argc = 0;
123 C** argv = nullptr;
124 C** env = nullptr;
125 if (getmainargs(&argc, &argv, &env, 0, nullptr) != 0 || argc < 1 || !argv || !argv[0] || !env) return false;
126 for (C** e = env; *e; ++e) {
127 if constexpr (sizeof(C) == 1) {
128 if (std::strcmp(reinterpret_cast<const char*>(*e), reinterpret_cast<const char*>(entry)) == 0) return true;
129 } else {
130 if (std::wcscmp(reinterpret_cast<const wchar_t*>(*e), reinterpret_cast<const wchar_t*>(entry)) == 0)
131 return true;
132 }
133 }
134 return false;
135}
136
137void check_getmainargs_environment() {
138 using Narrow = int(__cdecl*)(int*, char***, char***, int, void*);
139 using Wide = int(__cdecl*)(int*, wchar_t***, wchar_t***, int, void*);
140 const auto narrow_fn = reinterpret_cast<Narrow>(rt::shims::find("msvcrt.dll", "__getmainargs"));
141 const auto wide_fn = reinterpret_cast<Wide>(rt::shims::find("msvcrt.dll", "__wgetmainargs"));
142 if (!narrow_fn || !wide_fn) {
143 std::fprintf(stderr, "FAIL msvcrt.dll!__getmainargs/__wgetmainargs are not shimmed\n");
144 ++failures;
145 return;
146 }
147 // First use of the wide environment in this process: set_command_line runs before anything made _wenviron.
148 // main() hosts start with only the narrow table; if a toolchain change made _wenviron exist, the first-call
149 // checks below no longer prove the creation path, so say so rather than pass silently.
150 if (_wenviron) std::printf("note: _wenviron already exists at startup; its lazy creation is not exercised\n");
151 rt::process::set_command_line(L"game.exe", {L"-x"});
152 if (_putenv_s("LEONIDA_RT136_A", "before") != 0 || // narrow only; the wide table is built on first use
153 !env_has<wchar_t>(wide_fn, L"LEONIDA_RT136_A=before")) {
154 std::fprintf(stderr, "FAIL __wgetmainargs: no environment (or one without LEONIDA_RT136_A) at the first call\n");
155 ++failures;
156 }
157 if (!env_has<char>(narrow_fn, "LEONIDA_RT136_A=before")) {
158 std::fprintf(stderr, "FAIL __getmainargs: no environment (or one without LEONIDA_RT136_A)\n");
159 ++failures;
160 }
161 // A variable set after set_command_line reallocates the CRT's table; a pointer kept from before would dangle.
162 if (_putenv_s("LEONIDA_RT136_B", "after") != 0 || _wputenv_s(L"LEONIDA_RT136_C", L"after") != 0) {
163 std::fprintf(stderr, "FAIL _putenv_s/_wputenv_s did not set the test variables\n");
164 ++failures;
165 }
166 if (!env_has<wchar_t>(wide_fn, L"LEONIDA_RT136_B=after") || !env_has<wchar_t>(wide_fn, L"LEONIDA_RT136_C=after")) {
167 std::fprintf(stderr, "FAIL __wgetmainargs: an environment variable set after set_command_line is missing\n");
168 ++failures;
169 }
170 if (!env_has<char>(narrow_fn, "LEONIDA_RT136_B=after") || !env_has<char>(narrow_fn, "LEONIDA_RT136_C=after")) {
171 std::fprintf(stderr, "FAIL __getmainargs: an environment variable set after set_command_line is missing\n");
172 ++failures;
173 }
174}
115} // namespace 175} // namespace
116 176
117int main() { 177int main() {
@@ -126,6 +186,7 @@ int main() {
126 check_non_ascii(L"\u0394\u0416\u6F22 x", "an argument outside any single-byte code page"); 186 check_non_ascii(L"\u0394\u0416\u6F22 x", "an argument outside any single-byte code page");
127 187
128 check_import_names(); 188 check_import_names();
189 check_getmainargs_environment();
129 check_winmain(L"game.exe", {L"-foo", L"with space"}, L"-foo \"with space\"", "arguments after a plain name"); 190 check_winmain(L"game.exe", {L"-foo", L"with space"}, L"-foo \"with space\"", "arguments after a plain name");
130 check_winmain(L"C:\\My Games\\game.exe", {L"-x"}, L"-x", "a quoted program name with a space"); 191 check_winmain(L"C:\\My Games\\game.exe", {L"-x"}, L"-x", "a quoted program name with a space");
131 check_winmain(L"game.exe", {}, L"", "no arguments"); 192 check_winmain(L"game.exe", {}, L"", "no arguments");
diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp
index 260237e69..6b59c0245 100644
--- a/runtime/test/replay_uav_clear_offset_test.cpp
+++ b/runtime/test/replay_uav_clear_offset_test.cpp
@@ -3,6 +3,8 @@
3// the resource, as copies and atomic copies already treat it. No Vulkan loader, GPU or game data: the transfer 3// the resource, as copies and atomic copies already treat it. No Vulkan loader, GPU or game data: the transfer
4// functions are fakes that record the ranges they are given. 4// functions are fakes that record the ranges they are given.
5#include "../src/vulkan_replay.h" 5#include "../src/vulkan_replay.h"
6#include <array>
7#include <bit>
6#include <cstdint> 8#include <cstdint>
7#include <cstdio> 9#include <cstdio>
8#include <vector> 10#include <vector>
@@ -14,6 +16,24 @@ struct Write {
14}; 16};
15std::vector<Write> writes; 17std::vector<Write> writes;
16 18
19unsigned image_clears = 0, attachment_clears = 0;
20VkFormat requested_view_format = VK_FORMAT_UNDEFINED;
21VkImageSubresourceRange requested_view_range{};
22VkClearColorValue captured_color{};
23VkClearRect captured_rect{};
24VkRect2D captured_render_area{};
25std::uint32_t captured_render_layers = 0;
26
27void reset_texture_capture() {
28 image_clears = attachment_clears = 0;
29 requested_view_format = VK_FORMAT_UNDEFINED;
30 requested_view_range = {};
31 captured_color = {};
32 captured_rect = {};
33 captured_render_area = {};
34 captured_render_layers = 0;
35}
36
17VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, 37VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags,
18 std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, 38 std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*,
19 std::uint32_t, const VkImageMemoryBarrier*) {} 39 std::uint32_t, const VkImageMemoryBarrier*) {}
@@ -26,6 +46,24 @@ VKAPI_ATTR void VKAPI_CALL update(VkCommandBuffer, VkBuffer, VkDeviceSize offset
26VKAPI_ATTR void VKAPI_CALL copy(VkCommandBuffer, VkBuffer, VkBuffer, std::uint32_t count, const VkBufferCopy* r) { 46VKAPI_ATTR void VKAPI_CALL copy(VkCommandBuffer, VkBuffer, VkBuffer, std::uint32_t count, const VkBufferCopy* r) {
27 for (std::uint32_t i = 0; i < count; ++i) writes.push_back({'c', r[i].dstOffset, r[i].size, r[i].srcOffset}); 47 for (std::uint32_t i = 0; i < count; ++i) writes.push_back({'c', r[i].dstOffset, r[i].size, r[i].srcOffset});
28} 48}
49VKAPI_ATTR void VKAPI_CALL clear_image(VkCommandBuffer, VkImage, VkImageLayout, const VkClearColorValue* value,
50 std::uint32_t, const VkImageSubresourceRange*) {
51 captured_color = *value;
52 ++image_clears;
53}
54VKAPI_ATTR void VKAPI_CALL begin_rendering(VkCommandBuffer, const VkRenderingInfo* info) {
55 captured_render_area = info->renderArea;
56 captured_render_layers = info->layerCount;
57}
58VKAPI_ATTR void VKAPI_CALL end_rendering(VkCommandBuffer) {}
59VKAPI_ATTR void VKAPI_CALL clear_attachments(VkCommandBuffer, std::uint32_t count, const VkClearAttachment* values,
60 std::uint32_t rect_count, const VkClearRect* rects) {
61 if (count == 1 && rect_count >= 1) {
62 captured_color = values[0].clearValue.color;
63 captured_rect = rects[0];
64 ++attachment_clears;
65 }
66}
29 67
30int failures = 0; 68int failures = 0;
31void expect(bool ok, const char* what) { 69void expect(bool ok, const char* what) {
@@ -88,7 +126,132 @@ int main() {
88 "rectangle clear replays"); 126 "rectangle clear replays");
89 expect(inside(at + 16, at + 28), "elements 2..5 of a view at 8 are [at + 16, at + 28)"); 127 expect(inside(at + 16, at + 28), "elements 2..5 of a view at 8 are [at + 16, at + 28)");
90 128
129 // 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).
131 ReplayFunctions tex_vk = vk;
132 tex_vk.clear_color_image = clear_image;
133 tex_vk.begin_rendering = begin_rendering;
134 tex_vk.end_rendering = end_rendering;
135 tex_vk.clear_attachments = clear_attachments;
136 tex_vk.image_view = [](const ResourceBinding& b, const VkImageSubresourceRange& r) {
137 requested_view_format = b.format;
138 requested_view_range = r;
139 return reinterpret_cast<VkImageView>(std::uintptr_t{0x2000});
140 };
141
142 const auto run_tex = [&](const ResourceBinding& binding, const UavView& view, bool is_float,
143 std::array<std::uint32_t, 4> values, std::span<const Rect> rects = {},
144 const ReplayFunctions* custom_vk = nullptr) {
145 reset_texture_capture();
146 CommandList list;
147 list.clear_unordered_access(view, is_float, values, rects);
148 list.close();
149 return replay(list, VK_NULL_HANDLE, [&](ResourceId id) { return id == 2 ? &binding : nullptr; },
150 custom_vk ? *custom_vk : tex_vk);
151 };
152
153 ResourceBinding tex{};
154 tex.image = reinterpret_cast<VkImage>(std::uintptr_t{0x3000});
155 tex.format = VK_FORMAT_R16G16_SFLOAT;
156 tex.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
157 tex.width = 8;
158 tex.height = 6;
159 tex.mip_levels = 2;
160 tex.array_layers = 4;
161 tex.color_attachment = true;
162
163 const auto fbits = [](float f) { return std::bit_cast<std::uint32_t>(f); };
164 // R16G16_TYPELESS (SFLOAT) cleared as R16G16_UNORM Float(1.0, 1.0): uses R16G16_UNORM view and float32 {1, 1}.
165 expect(run_tex(tex, {2, false, VK_FORMAT_R16G16_UNORM, 0, 0, 0, 0, 1, 2}, true, {fbits(1.0f), fbits(1.0f), 0, 0}) ==
166 ReplayResult::success,
167 "R16G16_TYPELESS -> R16G16_UNORM whole-view clear replays");
168 expect(image_clears == 0 && attachment_clears == 1,
169 "R16G16_TYPELESS -> R16G16_UNORM uses attachment clear, not vkCmdClearColorImage");
170 expect(requested_view_format == VK_FORMAT_R16G16_UNORM,
171 "R16G16_TYPELESS -> R16G16_UNORM creates image view with view_format");
172 expect(requested_view_range.baseMipLevel == 0 && requested_view_range.baseArrayLayer == 1 &&
173 requested_view_range.layerCount == 2 && captured_render_layers == 2,
174 "reinterpreted UAV clear preserves mip and layer range");
175 expect(captured_color.float32[0] == 1.0f && captured_color.float32[1] == 1.0f,
176 "R16G16_UNORM clear value is decoded in view_format (not half-float NaN)");
177 expect(captured_rect.rect.offset.x == 0 && captured_rect.rect.offset.y == 0 &&
178 captured_rect.rect.extent.width == 8 && captured_rect.rect.extent.height == 6 &&
179 captured_rect.layerCount == 2,
180 "reinterpreted whole-view clear covers full mip extent and layers");
181
182 // R16G16_TYPELESS (SFLOAT) cleared as R16G16_UINT with half-float NaN bit patterns 0xffff and 0x7fff.
183 const Rect sub_rect{1, 1, 4, 3};
184 expect(run_tex(tex, {2, false, VK_FORMAT_R16G16_UINT, 0, 0, 0, 1, 0, 1}, false, {0xffff, 0x7fff, 0, 0},
185 std::span<const Rect>(&sub_rect, 1)) == ReplayResult::success,
186 "R16G16_TYPELESS -> R16G16_UINT rect clear replays");
187 expect(image_clears == 0 && attachment_clears == 1 && requested_view_format == VK_FORMAT_R16G16_UINT,
188 "R16G16_UINT rect clear uses R16G16_UINT view");
189 expect(captured_color.uint32[0] == 0xffff && captured_color.uint32[1] == 0x7fff,
190 "R16G16_UINT clear passes exact uint32 values");
191 expect(captured_render_area.extent.width == 4 && captured_render_area.extent.height == 3 &&
192 captured_rect.rect.extent.width == 3 && captured_rect.rect.extent.height == 2,
193 "R16G16_UINT rect clear clips to mip 1 extent");
194
195 // Same-format whole-view unpredicated clear stays on vkCmdClearColorImage.
196 expect(run_tex(tex, {2, false, VK_FORMAT_R16G16_SFLOAT, 0, 0, 0, 0, 0, 1}, true, {fbits(0.5f), fbits(-2.0f), 0, 0}) ==
197 ReplayResult::success,
198 "same-format R16G16_SFLOAT whole-view clear replays");
199 expect(image_clears == 1 && attachment_clears == 0, "same-format whole-view clear uses vkCmdClearColorImage");
200
201 // R32_TYPELESS (SFLOAT) cleared as R32_UINT with sNaN bit pattern 0x7f800001.
202 ResourceBinding r32 = tex;
203 r32.format = VK_FORMAT_R32_SFLOAT;
204 expect(run_tex(r32, {2, false, VK_FORMAT_R32_UINT, 0, 0, 0, 0, 0, 1}, false, {0x7f800001u, 0, 0, 0}) ==
205 ReplayResult::success,
206 "R32_TYPELESS -> R32_UINT sNaN clear replays");
207 expect(image_clears == 0 && attachment_clears == 1 && requested_view_format == VK_FORMAT_R32_UINT &&
208 captured_color.uint32[0] == 0x7f800001u,
209 "R32_UINT clear uses R32_UINT attachment view with exact sNaN bits");
210
211 // R8G8B8A8_TYPELESS (UNORM) cleared as R8G8B8A8_UINT and R8G8B8A8_SINT uses view_format directly.
212 ResourceBinding rgba8 = tex;
213 rgba8.format = VK_FORMAT_R8G8B8A8_UNORM;
214 expect(run_tex(rgba8, {2, false, VK_FORMAT_R8G8B8A8_UINT, 0, 0, 0, 0, 0, 1}, false, {0xff, 0x80, 0x7f, 1}) ==
215 ReplayResult::success,
216 "R8G8B8A8_TYPELESS -> R8G8B8A8_UINT clear replays");
217 expect(image_clears == 0 && attachment_clears == 1 && requested_view_format == VK_FORMAT_R8G8B8A8_UINT &&
218 captured_color.uint32[0] == 0xff && captured_color.uint32[1] == 0x80 &&
219 captured_color.uint32[2] == 0x7f && captured_color.uint32[3] == 1,
220 "R8G8B8A8_UINT clear uses R8G8B8A8_UINT attachment view");
221
222 // Emulated R9G9B9E5_SHAREDEXP (backed by R32_UINT) must NOT request an E5B9G9R9 color attachment view.
223 ResourceBinding r9e5 = tex;
224 r9e5.format = VK_FORMAT_R32_UINT;
225 expect(run_tex(r9e5, {2, false, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, 0, 0, 0, 0, 0, 1}, true,
226 {fbits(1.0f), fbits(2.0f), fbits(4.0f), 0}) == ReplayResult::success,
227 "emulated R9G9B9E5 whole-view clear replays");
228 expect(image_clears == 1 && attachment_clears == 0 && captured_color.uint32[0] == 0x94010040u,
229 "emulated R9G9B9E5 whole-view clear stays on R32_UINT vkCmdClearColorImage");
230 expect(run_tex(r9e5, {2, false, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, 0, 0, 0, 0, 0, 1}, true,
231 {fbits(1.0f), fbits(2.0f), fbits(4.0f), 0}, std::span<const Rect>(&sub_rect, 1)) ==
232 ReplayResult::success,
233 "emulated R9G9B9E5 rect clear replays");
234 expect(image_clears == 0 && attachment_clears == 1 && requested_view_format == VK_FORMAT_R32_UINT &&
235 captured_color.uint32[0] == 0x94010040u,
236 "emulated R9G9B9E5 rect clear uses R32_UINT attachment view");
237
238 // When dynamic rendering is unavailable, reinterpretation refuses instead of corrupting via vkCmdClearColorImage.
239 ReplayFunctions no_render = tex_vk;
240 no_render.begin_rendering = nullptr;
241 expect(run_tex(tex, {2, false, VK_FORMAT_R16G16_UNORM, 0, 0, 0, 0, 0, 1}, true, {fbits(1.0f), fbits(1.0f), 0, 0},
242 {}, &no_render) == ReplayResult::unsupported,
243 "reinterpreted UAV clear without dynamic rendering returns unsupported");
244
245 // When color_attachment_format reports a view format unsupported as an attachment, keep the backing format path.
246 ReplayFunctions no_unorm_rt = tex_vk;
247 no_unorm_rt.color_attachment_format = [](VkFormat f) { return f != VK_FORMAT_R16G16_UNORM; };
248 expect(run_tex(tex, {2, false, VK_FORMAT_R16G16_UNORM, 0, 0, 0, 0, 0, 1}, true, {fbits(0.0f), fbits(0.0f), 0, 0},
249 {}, &no_unorm_rt) == ReplayResult::success,
250 "non-attachable view format falls back to backing format");
251 expect(image_clears == 1 && attachment_clears == 0,
252 "non-attachable view format whole-view clear uses vkCmdClearColorImage");
253
91 if (failures) return 1; 254 if (failures) return 1;
92 std::printf("replay_uav_clear_offset: buffer UAV clears write their resource's range of a shared buffer\n"); 255 std::printf("replay_uav_clear_offset: buffer offsets and typeless texture view-format clears all passed\n");
93 return 0; 256 return 0;
94} 257}
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index 7ec6608d6..412dc2b8f 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -13,8 +13,8 @@ FSSM program (the magic, zeros up to OFFSET, then the words): it is published as
13SHA-256 goes into the index as fssm_sha256, which is what the layer looks a PSO's shader up by (the translator 13SHA-256 goes into the index as fssm_sha256, which is what the layer looks a PSO's shader up by (the translator
14hashes <work>/fssm/<name>.fssm for the game's programs, and compute shaders here already). A test builds the shader container from that file. The words 14hashes <work>/fssm/<name>.fssm for the game's programs, and compute shaders here already). A test builds the shader container from that file. The words
15are also what a shader reads through s_getpc_b64 (the code base) at that offset. 15are also what a shader reads through s_getpc_b64 (the code base) at that offset.
16The stage comes from the name's prefix. Mesh and geometry shaders (ms_, gs_) also need a DXBC container with 16The stage comes from the name's prefix. Mesh shaders (ms_) also need a DXBC container with their PSV0, which this
17their signatures, which this doesn't make. 17doesn't make; geometry shaders (gs_) get gs_tri's signatures (gs_container).
18The comment at the top of each .asm says which test program to run on the result and what it should print. 18The comment at the top of each .asm says which test program to run on the result and what it should print.
19With LEONIDA_FMA=khr (or glsl), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs 19With LEONIDA_FMA=khr (or glsl), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs
20VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77) or --fma glsl. 20VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77) or --fma glsl.
@@ -108,6 +108,16 @@ def clip_container():
108 + b"OSG1" + struct.pack("<I", len(payload)) + payload) 108 + b"OSG1" + struct.pack("<I", len(payload)) + payload)
109 109
110 110
111def gs_container():
112 # ISG1 and OSG1 of the gs_* fixtures, as scripts/run_gpu_tests.py makes them for gs_tri: SV_Position (system value
113 # 1) in register 0 and TEXCOORD0 in register 1, float4 (component type 3), no names.
114 sig = struct.pack("<II", 2, 8) + b"".join(struct.pack("<6I2B6x", 0, 0, 0, sv, 3, reg, 0xF, 0xF)
115 for sv, reg in ((1, 0), (0, 1)))
116 chunk = struct.pack("<I", len(sig)) + sig
117 return (b"DXBC" + bytes(16) + struct.pack("<5I", 1, 40 + 2 * (4 + len(chunk)), 2, 40, 44 + len(chunk))
118 + b"ISG1" + chunk + b"OSG1" + chunk)
119
120
111def translate_tests(work, names): 121def translate_tests(work, names):
112 disasm, fssm, spirv = (work / d for d in ("disasm", "fssm", "spirv")) 122 disasm, fssm, spirv = (work / d for d in ("disasm", "fssm", "spirv"))
113 disasm.mkdir() 123 disasm.mkdir()
@@ -140,6 +150,8 @@ def translate_tests(work, names):
140 (fssm / (n + ".fssm")).write_bytes(program) 150 (fssm / (n + ".fssm")).write_bytes(program)
141 elif n in CLIP_CASES and n != "vs_clip_undeclared": 151 elif n in CLIP_CASES and n != "vs_clip_undeclared":
142 (work / (n + ".dxbc")).write_bytes(clip_container()) 152 (work / (n + ".dxbc")).write_bytes(clip_container())
153 elif n.startswith("gs_"):
154 (work / (n + ".dxbc")).write_bytes(gs_container())
143 else: 155 else:
144 (work / (n + ".dxbc")).write_bytes(bytes(32)) # chunk count 0 156 (work / (n + ".dxbc")).write_bytes(bytes(32)) # chunk count 0
145 cmd = [sys.executable, "-I", TRANSLATOR, disasm, "--out", spirv] 157 cmd = [sys.executable, "-I", TRANSLATOR, disasm, "--out", spirv]
@@ -169,7 +181,7 @@ def main():
169 unknown = sorted(set(names) - set(available)) 181 unknown = sorted(set(names) - set(available))
170 if unknown: 182 if unknown:
171 sys.exit("Unknown test shaders: " + ", ".join(unknown)) 183 sys.exit("Unknown test shaders: " + ", ".join(unknown))
172 skipped = [n for n in names if n.startswith(("ms_", "gs_"))] 184 skipped = [n for n in names if n.startswith("ms_")]
173 if skipped: 185 if skipped:
174 print("not built (need a DXBC container with signatures):", ", ".join(skipped)) 186 print("not built (need a DXBC container with signatures):", ", ".join(skipped))
175 names = [n for n in names if n not in skipped] 187 names = [n for n in names if n not in skipped]
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 00acdc5ef..bec6947e7 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -78,17 +78,20 @@ COMPUTE = [("cs_lds", "4", "mirror64"), ("cs_exec64", "1", "exec64"), ("cs_bvh",
78COMPUTE += [("cs_bvh32", "1", "bvh")] # TEST-184: image_bvh_intersect_ray, the 32-bit node pointer; same scene and words 78COMPUTE += [("cs_bvh32", "1", "bvh")] # TEST-184: image_bvh_intersect_ray, the 32-bit node pointer; same scene and words
79CS_STORE = [0x400080ff, 0xe00003ff, 0x3c004000, 0xeeeeeeee, 0x40003c00, 0xbc003800, 0x40ff8000, 0x3ff00000] 79CS_STORE = [0x400080ff, 0xe00003ff, 0x3c004000, 0xeeeeeeee, 0x40003c00, 0xbc003800, 0x40ff8000, 0x3ff00000]
80CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed0014, 0x5eed0018, 0x5eed001c] 80CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed0014, 0x5eed0018, 0x5eed001c]
81WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", 81# -0, and NaN checks that need SignedZeroInfNanPreserve (cs_signed_zero_nan.asm); 0 in out[4..7] means it's missing
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",
82 "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",
83 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", 85 "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext",
84 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst") 86 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst",
87 "cs_mask_vgpr_exec")
85# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is 88# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is
86# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with 89# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with
87# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may 90# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may
88# otherwise pick a narrower size and return different words (#774). 91# otherwise pick a narrower size and return different words (#774).
89WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} 92WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"}
90WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const", 93WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const",
91 "cs_w32_mask_imm", "cs_lds_b64_cmpst") 94 "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_mask_vgpr_exec")
92CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), 95CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]),
93 ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), 96 ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]),
94 ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), 97 ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]),
@@ -125,6 +128,8 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
125 # not bit 0 for every lane; word = set lanes | lowest lane << 8 (derivations in each .asm header) 128 # not bit 0 for every lane; word = set lanes | lowest lane << 8 (derivations in each .asm header)
126 ("cs_w32_mask_imm", [2056, 20, 2, 6152, 2050, 4112, 258, 32]), 129 ("cs_w32_mask_imm", [2056, 20, 2, 6152, 2050, 4112, 258, 32]),
127 ("cs_w64_mask_imm", [2056, 1084, 828, 2052, 319, 2104, 516, 2064]), 130 ("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
132 ("cs_signed_zero_nan", SIGNED_ZERO_NAN),
128 ("cs_wave64_ballot", [32, 16, 24, 40, 8, 48]), 133 ("cs_wave64_ballot", [32, 16, 24, 40, 8, 48]),
129 ("cs_wm_half_ops", [32, 16, 16, 0, 16]), ("cs_wm_half_cmp", [1, 0, 1, 1]), 134 ("cs_wm_half_ops", [32, 16, 16, 0, 16]), ("cs_wm_half_cmp", [1, 0, 1, 1]),
130 ("cs_wm_bfm64", [16, 8, 8, 40]), ("cs_wm_scc_rfl", [55, 48]), 135 ("cs_wm_bfm64", [16, 8, 8, 40]), ("cs_wm_scc_rfl", [55, 48]),
@@ -141,7 +146,10 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
141 # SHADER-91: waves that end without an s_barrier don't hold the barrier of the ones still running 146 # SHADER-91: waves that end without an s_barrier don't hold the barrier of the ones still running
142 ("cs_barrier_early_end", [127, 126, 125, 124, 123, 122, 121, 120]), 147 ("cs_barrier_early_end", [127, 126, 125, 124, 123, 122, 121, 120]),
143 # SHADER-91: a barrier in a loop with a per-wave trip count; the k-th one waits for the waves still running 148 # SHADER-91: a barrier in a loop with a per-wave trip count; the k-th one waits for the waves still running
144 ("cs_barrier_loop", [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE])] 149 ("cs_barrier_loop", [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE]),
150 # SHADER-21 part 2: a mask copied to a VGPR with v_mov_b32 respects EXEC (inactive lanes keep the old VGPR)
151 ("cs_mask_vgpr_exec", [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
152 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF])]
145# num_records bounds check (cs_bounds.asm): one thread, so no 64-wide subgroup requirement. 153# num_records bounds check (cs_bounds.asm): one thread, so no 64-wide subgroup requirement.
146# The SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm header): one thread too. 154# The SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm header): one thread too.
147# Never run cs_smem_sload_neg with a translator that zero-extends the s_load immediate: it reads 4 GiB past the heap. 155# Never run cs_smem_sload_neg with a translator that zero-extends the s_load immediate: it reads 4 GiB past the heap.
@@ -155,12 +163,33 @@ BOUNDS = [("cs_bounds", [0x12345678, 0x12345678, 0x00000000, 0xEEEEEEEE]),
155 ("cs_oob_select", [0x5eed000c, 0, 0x5eed0014, 0, 0x5eed0018, 0xeeeeeeee, 0, 0]), 163 ("cs_oob_select", [0x5eed000c, 0, 0x5eed0014, 0, 0x5eed0018, 0xeeeeeeee, 0, 0]),
156 # the end of an access decides (a start check, Mesa's GFX10 column, reads more); x4 loads and stores per dword, typed all or nothing 164 # the end of an access decides (a start check, Mesa's GFX10 column, reads more); x4 loads and stores per dword, typed all or nothing
157 ("cs_oob_tail", [0, 0, 0x5eed0010, 0, 0xbeef0000, 0xeeeeeeee, 0, 0x5eed0010]), 165 ("cs_oob_tail", [0, 0, 0x5eed0010, 0, 0xbeef0000, 0xeeeeeeee, 0, 0x5eed0010]),
158 # swizzled MUBUF addressing (RDNA2 ISA 8.1.5) and ADD_TID_ENABLE on lanes 0 and 1, derived in the .asm header 166 # swizzled MUBUF addressing (measured natively on gfx1036) and ADD_TID_ENABLE on lanes 0 and 1, derived in the .asm header
159 ("cs_buf_swizzle", [0x5eed0024, 0x5eed0044, 0x5eed004c, 0x5eed0008, 0x5eed0028, 0, 0xbeef0000, 0xbeef0001])] 167 ("cs_buf_swizzle", [0x5eed0024, 0x5eed0044, 0x5eed004c, 0x5eed0008, 0x5eed000c, 0, 0xbeef0000, 0xbeef0001])]
160CMPX_CLASS_WORDS = [0xEEEEEEEE] * 3 + [0x22] + [0x11] * 4 168CMPX_CLASS_WORDS = [0xEEEEEEEE] * 3 + [0x22] + [0x11] * 4
161# cs_fmt_1010102.asm: descriptor loads, immediate-format load, raw input words and the two packed stores. 169# cs_fmt_1010102.asm: descriptor loads, immediate-format load, raw input words and the two packed stores.
162FMT_1010102_WORDS = [0, 0x3F800000, 0, 0x3F800000, 0x3F800000, 0, 0x3F800000, 0, 170FMT_1010102_WORDS = [0, 0x3F800000, 0, 0x3F800000, 0x3F800000, 0, 0x3F800000, 0,
163 0, 0x3F800000, 0, 0x3F800000, 0xC00FFC00, 0x003FF003, 0xE00003FF, 0xFFE00003] 171 0, 0x3F800000, 0, 0x3F800000, 0xC00FFC00, 0x003FF003, 0xE00003FF, 0xFFE00003]
172# cs_fmt_int_narrow.asm: 8- and 16-bit UINT/SINT typed buffer loads and stores (layout in the .asm header). The
173# words are the same program's output on gfx1036 run natively (tools/hw_oracle, wave32 and wave64 identical).
174FMT_INT_NARROW_WORDS = [
175 0x00000080, 0x00000080, 0x00000080, 0x00000080, 0xFFFFFF80, 0xFFFFFF80, 0xFFFFFF80, 0xFFFFFF80,
176 0x0000FF80, 0x0000FF80, 0x0000FF80, 0x0000FF80, 0xFFFFFF80, 0xFFFFFF80, 0xFFFFFF80, 0xFFFFFF80,
177 0x00000080, 0x000000FF, 0x00000080, 0x000000FF, 0xFFFFFF80, 0xFFFFFFFF, 0xFFFFFF80, 0xFFFFFFFF,
178 0xFFFFFF80, 0x00007F01, 0xFFFFFF80, 0x00007F01, 0xFFFFFF80, 0xFFFFFFFF, 0x00000001, 0x0000007F,
179 0xFFFFFF80, 0x00007F01, 0xFFFFFFFF, 0xFFFF8000, 0xFFFFFF80, 0x00000000, 0x00000001, 0x00000001,
180 0x0000FF80, 0x00000000, 0x00000001, 0x00000001, 0xFF80FF80, 0xFF80FF80, 0xFFFFFF80, 0x007F0001,
181 0x7F01FF80, 0x8000FFFF, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE,
182 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE,
183 0xEEEEEE7F, 0xEEEEEEEE, 0xEEEEEE7F, 0xEEEEEEEE, 0xEEEE7FFF, 0xEEEEEEEE, 0xEEEE7FFF, 0xEEEEEEEE,
184 0xEEEE807F, 0xEEEEEEEE, 0xEEEE7F7F, 0xEEEEEEEE, 0x7FFF7FFF, 0xEEEEEEEE, 0x80807F7F, 0xEEEEEEEE,
185 0x7FFF7FFF, 0x80008000, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE,
186 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE,
187 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE,
188 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE,
189 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE,
190 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE,
191 0x7F01FF80, 0x8000FFFF, 0x12345678, 0x9ABCDEF0, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE,
192]
164# cs_fmt_sint32.asm: hand-derived full-width and D16 load results, inputs, stores, and untouched words. 193# cs_fmt_sint32.asm: hand-derived full-width and D16 load results, inputs, stores, and untouched words.
165FMT_SINT32_WORDS = [ 194FMT_SINT32_WORDS = [
166 0x80000000, 0x7FFFFFFF, 0x80000000, 1, 195 0x80000000, 0x7FFFFFFF, 0x80000000, 1,
@@ -289,6 +318,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
289 "ps_f16_pack": (0x34003c00, 0x38003400, 0x34000000, 0x44004200), 318 "ps_f16_pack": (0x34003c00, 0x38003400, 0x34000000, 0x44004200),
290 # v_pack_b32_f16 neg/abs on the selected half: a sign flip / clear before packing (SHADER-260) 319 # v_pack_b32_f16 neg/abs on the selected half: a sign flip / clear before packing (SHADER-260)
291 "ps_f16_pack_mods": (0x4400b400, 0xc4003400, 0x4400c200, 0xb400b400), 320 "ps_f16_pack_mods": (0x4400b400, 0xc4003400, 0x4400c200, 0xb400b400),
321 # SDWA src_sel on a float inline constant in an f16 op (measured on gfx1036)
322 "ps_sdwa_f16_const": (0xaaaa3800, 0xaaaa1c00, 0xaaaa3e00, 0xaaaa73f0),
292 "ps_sff_imm": (2, 1, 20, 16), 323 "ps_sff_imm": (2, 1, 20, 16),
293 "ps_fnan_med3": (0x40a00000, 0xc0200000, 0xc0200000, 0x40600000), 324 "ps_fnan_med3": (0x40a00000, 0xc0200000, 0xc0200000, 0x40600000),
294 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000), 325 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000),
@@ -305,7 +336,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
305 # v_readlane_b32 across both halves of a wave64 (the .asm header derives the words) 336 # v_readlane_b32 across both halves of a wave64 (the .asm header derives the words)
306 "ps_w64x_readlane": (0x40000079, 0x40000010, 0x40000064, 0x400000be)} 337 "ps_w64x_readlane": (0x40000079, 0x40000010, 0x40000064, 0x400000be)}
307# Pixel shaders that are exact only when the pixel stage really ran 64 lanes wide. vk_harness says so when it chained 338# Pixel shaders that are exact only when the pixel stage really ran 64 lanes wide. vk_harness says so when it chained
308# a required subgroup size onto the fragment stage ("fragment subgroup size: N required"). A device that cannot 339# a required subgroup size onto the fragment stage ("fragment subgroup size: N", the whole line; a device that could
340# not take the size gets "fragment subgroup size: N not available" or no line). A device that cannot
309# require 64 there (NVIDIA: 32 only; llvmpipe: 8) has no frame to judge: the test is skipped, not failed. 341# require 64 there (NVIDIA: 32 only; llvmpipe: 8) has no frame to judge: the test is skipped, not failed.
310WIDE_PIXEL_TESTS = {"ps_w64x_readlane": 64} 342WIDE_PIXEL_TESTS = {"ps_w64x_readlane": 64}
311# Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as 343# Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as
@@ -475,6 +507,10 @@ def fmt_1010102_test(tools, spirv, env=None):
475 return dump_test(tools, spirv, "cs_fmt_1010102", FMT_1010102_WORDS + [0xEEEEEEEE] * 48, 64, env) 507 return dump_test(tools, spirv, "cs_fmt_1010102", FMT_1010102_WORDS + [0xEEEEEEEE] * 48, 64, env)
476 508
477 509
510def fmt_int_narrow_test(tools, spirv, env=None):
511 return dump_test(tools, spirv, "cs_fmt_int_narrow", FMT_INT_NARROW_WORDS, len(FMT_INT_NARROW_WORDS), env)
512
513
478def fmt_sint32_test(tools, spirv, env=None): 514def fmt_sint32_test(tools, spirv, env=None):
479 return dump_test(tools, spirv, "cs_fmt_sint32", FMT_SINT32_WORDS, len(FMT_SINT32_WORDS), env) 515 return dump_test(tools, spirv, "cs_fmt_sint32", FMT_SINT32_WORDS, len(FMT_SINT32_WORDS), env)
480 516
@@ -635,6 +671,29 @@ def vcmpx_forms_narrow_skip(out):
635 return None 671 return None
636 672
637 673
674# Dump words a driver gets wrong with or without SignedZeroInfNanPreserve, by the first word of the device name on
675# vk_compute_test's "device: ..." line. Only these words go unjudged there. Shared with run_gpu_tests.py.
676# - Apple GPUs (MoltenVK) return +0 for cs_signed_zero_nan's -0 products, words 0, 2 and 3 (v_mul_f32, v_pk_mul_f16,
677# v_mul_f16; #1203, SHADER-182).
678# - Mesa llvmpipe returns 0 in word 5, the NaN check of 0 * inf (an inline-constant 0), while its other NaN checks give
679# 1 (#664, Mesa with LLVM 21.1.8). The CI runs the GPU tests on llvmpipe.
680UNJUDGED_WORDS = {"Apple": {"cs_signed_zero_nan": (0, 2, 3)},
681 "llvmpipe": {"cs_signed_zero_nan": (5,)}}
682
683
684def judged_words(name, out, words):
685 """The expected words with None where nothing is judged: UNJUDGED_WORDS for the device that vk_compute_test's
686 "device: ..." line names, else every word as given."""
687 m = re.search(r"^device: (\S+)", out, re.MULTILINE)
688 unjudged = UNJUDGED_WORDS.get(m.group(1), {}).get(name, ()) if m else ()
689 return [None if i in unjudged else w for i, w in enumerate(words)]
690
691
692def words_match(got, want):
693 """The dump's words against want, which may be shorter; a None in want is not judged."""
694 return len(got) >= len(want) and all(w is None or g == w for g, w in zip(got, want))
695
696
638def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expected_words=None, needs_32_lanes=False, 697def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expected_words=None, needs_32_lanes=False,
639 env=None): 698 env=None):
640 """Return an empty string for a pass, None for unsupported wave64, a Skip for a wave32 lane-mask test on a device 699 """Return an empty string for a pass, None for unsupported wave64, a Skip for a wave32 lane-mask test on a device
@@ -670,7 +729,7 @@ def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expe
670 return "" 729 return ""
671 elif expected_words is not None: 730 elif expected_words is not None:
672 m = re.search(r"^out\[0\.\.7\] = ((?:[0-9]+ ){7}[0-9]+)$", out, re.MULTILINE) 731 m = re.search(r"^out\[0\.\.7\] = ((?:[0-9]+ ){7}[0-9]+)$", out, re.MULTILINE)
673 if m and [int(x) for x in m.group(1).split()][:len(expected_words)] == expected_words: 732 if m and words_match([int(x) for x in m.group(1).split()], judged_words(name, out, expected_words)):
674 return "" 733 return ""
675 else: 734 else:
676 m = re.search(r"(\d+) mismatches", out) 735 m = re.search(r"(\d+) mismatches", out)
@@ -1123,7 +1182,7 @@ def wide_pixel_skip(name, out):
1123 """A Skip when `name` needs a 64-wide pixel stage (WIDE_PIXEL_TESTS) and vk_harness's output does not say that size 1182 """A Skip when `name` needs a 64-wide pixel stage (WIDE_PIXEL_TESTS) and vk_harness's output does not say that size
1124 was required of the fragment stage, else None.""" 1183 was required of the fragment stage, else None."""
1125 want = WIDE_PIXEL_TESTS.get(name) 1184 want = WIDE_PIXEL_TESTS.get(name)
1126 if not want or re.search(rf"^fragment subgroup size: {want} required$", out, re.MULTILINE): 1185 if not want or re.search(rf"^fragment subgroup size: {want}$", out, re.MULTILINE):
1127 return None 1186 return None
1128 m = re.search(r"subgroup (\d+)\.\.(\d+)", out) 1187 m = re.search(r"subgroup (\d+)\.\.(\d+)", out)
1129 seen = f": subgroup {m.group(1)}..{m.group(2)}" if m else "" 1188 seen = f": subgroup {m.group(1)}..{m.group(2)}" if m else ""
@@ -1179,7 +1238,7 @@ def pixel_test(tools, spirv, name):
1179 return f"missing {name}.spv" 1238 return f"missing {name}.spv"
1180 if name in ("ps_texoff", "ps_texoff_implicit"): 1239 if name in ("ps_texoff", "ps_texoff_implicit"):
1181 return texoff_test(tools, spirv, name) 1240 return texoff_test(tools, spirv, name)
1182 if name == "ps_interp_f16_high" and BARY_FALLBACK: 1241 if name == "ps_interp_f16_high" and BARY_FALLBACK and not F16_HALVES: # with F16_HALVES it reads decoded halves
1183 return Skip("SKIP (per-vertex interpolants need VK_KHR_fragment_shader_barycentric)") 1242 return Skip("SKIP (per-vertex interpolants need VK_KHR_fragment_shader_barycentric)")
1184 fmt = "<4f" if name == "ps_bary" else "<2I2f" if name in ("ps_flat", "ps_uniform_branch", "ps_scc_mask32") else "<4I" 1243 fmt = "<4f" if name == "ps_bary" else "<2I2f" if name in ("ps_flat", "ps_uniform_branch", "ps_scc_mask32") else "<4I"
1185 px, out = pixels(tools, spirv, name, fmt, PIXEL_VERTEX.get(name, "vs_ids")) 1244 px, out = pixels(tools, spirv, name, fmt, PIXEL_VERTEX.get(name, "vs_ids"))
@@ -1290,6 +1349,7 @@ def main():
1290 expected_words=CMPX_CLASS_WORDS))) 1349 expected_words=CMPX_CLASS_WORDS)))
1291 results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv))) 1350 results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv)))
1292 results.append(("cs_fmt_sint32", fmt_sint32_test(tools, spirv))) 1351 results.append(("cs_fmt_sint32", fmt_sint32_test(tools, spirv)))
1352 results.append(("cs_fmt_int_narrow", fmt_int_narrow_test(tools, spirv)))
1293 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv))) 1353 results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv)))
1294 results.append(("cs_tbuffer_store", tbuffer_store_test(tools, spirv))) 1354 results.append(("cs_tbuffer_store", tbuffer_store_test(tools, spirv)))
1295 for name, groups, want in GLOBAL_OFFSET: 1355 for name, groups, want in GLOBAL_OFFSET:
diff --git a/runtime/test/shaders/cs_buf_swizzle.asm b/runtime/test/shaders/cs_buf_swizzle.asm
index bead1aac3..1b7f72803 100644
--- a/runtime/test/shaders/cs_buf_swizzle.asm
+++ b/runtime/test/shaders/cs_buf_swizzle.asm
@@ -1,10 +1,11 @@
1; Swizzled MUBUF addressing and ADD_TID_ENABLE (docs/design.md, Buffer bounds checking). RDNA2 ISA 8.1.5 "Swizzled 1; Swizzled MUBUF addressing and ADD_TID_ENABLE (docs/design.md, Swizzled buffer addressing). Measured natively on
2; Buffer Addressing", element_size fixed at 4 bytes; fields from Mesa gfx10-rsrc.json: SWIZZLE_ENABLE = word1 bit 31, 2; RDNA2 (gfx1036, wave32 & wave64): SWIZZLE_ENABLE = word1 bit 31, STRIDE = word1 [29:16], INDEX_STRIDE = word3 [22:21]
3; STRIDE = word1 [29:16], INDEX_STRIDE = word3 [22:21] (8 << n), ADD_TID_ENABLE = word3 bit 23: 3; (IS = 8 << n), ADD_TID_ENABLE = word3 bit 23:
4; index = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), offset = (offen ? vaddr : 0) + inst_offset 4; index = idxen ? vindex : (ADD_TID_ENABLE ? lane : 0), offset = uint32((offen ? vaddr : 0) + inst_offset)
5; buffer_offset = (index / IS * stride + offset / 4 * 4) * IS + index % IS * 4 + offset % 4, address = base + 5; buffer_offset = (index / IS * stride + (offset & ~3)) * IS + (index % IS) * 4 + (offset & 3), address = base +
6; soffset + buffer_offset (IS = index_stride). OOB_SELECT 3 with swizzle and stride != 0 checks index >= NUM_RECORDS 6; soffset + buffer_offset (IS = index_stride). With idxen=1, multi-dword accesses step linearly by +4 bytes; with
7; or offset + payload > stride (ISA table 35); ADD_TID_ENABLE also adds the lane in a linear V# (table 36's ring). 7; idxen=0 and ADD_TID_ENABLE=1 (scratch swizzle), raw multi-dword accesses step by 4 * IS. OOB_SELECT 3 with active
8; swizzle and stride != 0 checks (index + soffset) >= NUM_RECORDS or offset + payload > stride.
8; Thread 0 seeds heap bytes 0x40..0x8f (region offset X = byte 0x40 + X) with 0x5eed0000 + X; the heap is 0xee-filled, 9; Thread 0 seeds heap bytes 0x40..0x8f (region offset X = byte 0x40 + X) with 0x5eed0000 + X; the heap is 0xee-filled,
9; so an in-range access past the seed reads 0xeeeeeeee. V# A (s[4:7], literal): base 0x40, swizzled, stride 8, NR 16, 10; so an in-range access past the seed reads 0xeeeeeeee. V# A (s[4:7], literal): base 0x40, swizzled, stride 8, NR 16,
10; IS 8, OOB_SELECT 3. V# B (s[8:11], words 1 and 3 or-ed at run time): base 0x40, swizzled, stride 8, NR 8, IS 16, 11; IS 8, OOB_SELECT 3. V# B (s[8:11], words 1 and 3 or-ed at run time): base 0x40, swizzled, stride 8, NR 8, IS 16,
@@ -14,13 +15,13 @@
14; 1 A, idx 9, off 0: (1 * 8 + 0) * 8 + 1 * 4 = X 0x44: 0x5eed0044 [X 0x48] 15; 1 A, idx 9, off 0: (1 * 8 + 0) * 8 + 1 * 4 = X 0x44: 0x5eed0044 [X 0x48]
15; 2 B, idx 3, off 4: (0 * 8 + 4) * 16 + 3 * 4 = X 0x4c: 0x5eed004c [X 0x1c] 16; 2 B, idx 3, off 4: (0 * 8 + 4) * 16 + 3 * 4 = X 0x4c: 0x5eed004c [X 0x1c]
16; 3 A x2, idx 2, off 0, dword 0: 0 * 8 + 2 * 4 = X 0x8: 0x5eed0008 [X 0x10] 17; 3 A x2, idx 2, off 0, dword 0: 0 * 8 + 2 * 4 = X 0x8: 0x5eed0008 [X 0x10]
17; 4 A x2, idx 2, dword 1 (offset 4): (0 * 8 + 4) * 8 + 2 * 4 = X 0x28: 0x5eed0028 [X 0x14] 18; 4 A x2, idx 2, dword 1 (idxen=1 steps linearly +4): X 0x8 + 4 = X 0xc: 0x5eed000c [X 0x14]
18; 5 A, idx 16, off 0: 16 >= NR 16 -> 0 (the raw check, 4 <= 16, reads X 0x80 past the seed: 0xeeeeeeee) 19; 5 A, idx 16, off 0: 16 >= NR 16 -> 0 (the raw check, 4 <= 16, reads X 0x80 past the seed: 0xeeeeeeee)
19; 6, 7 lanes 0 and 1 store 0xbeef0000 + lane through C: address 0x18 + lane * 4 -> 0xbeef0000 0xbeef0001 20; 6, 7 lanes 0 and 1 store 0xbeef0000 + lane through C: address 0x18 + lane * 4 -> 0xbeef0000 0xbeef0001
20; (without ADD_TID both lanes store to out[6], and out[7] keeps 0xeeeeeeee) 21; (without ADD_TID both lanes store to out[6], and out[7] keeps 0xeeeeeeee)
21; Lanes 0 and 1 only store (no lane reads what another wrote); thread 0 alone seeds and loads. No wave64 requirement. 22; Lanes 0 and 1 only store (no lane reads what another wrote); thread 0 alone seeds and loads. No wave64 requirement.
22; Run: vk_compute_test cs_buf_swizzle.spv 1 dump -> out[0..7] = 0x5eed0024 0x5eed0044 0x5eed004c 0x5eed0008 23; Run: vk_compute_test cs_buf_swizzle.spv 1 dump -> out[0..7] = 0x5eed0024 0x5eed0044 0x5eed004c 0x5eed0008
23; 0x5eed0028 0x00000000 0xbeef0000 0xbeef0001 (1592590372 1592590404 1592590412 1592590344 1592590376 0 3203334144 24; 0x5eed000c 0x00000000 0xbeef0000 0xbeef0001 (1592590372 1592590404 1592590412 1592590344 1592590348 0 3203334144
24; 3203334145). 25; 3203334145).
25v_cmpx_gt_u32_e32 2, v0 26v_cmpx_gt_u32_e32 2, v0
26s_mov_b32 s12, 0x18 27s_mov_b32 s12, 0x18
diff --git a/runtime/test/shaders/cs_fmt_int_narrow.asm b/runtime/test/shaders/cs_fmt_int_narrow.asm
new file mode 100644
index 000000000..5cd87b094
--- /dev/null
+++ b/runtime/test/shaders/cs_fmt_int_narrow.asm
@@ -0,0 +1,126 @@
1; Narrow integer typed buffers: 8/16-bit UINT and SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70.
2; Lane 0 writes the source dwords 0x7f01ff80 0x8000ffff 0x12345678 0x9abcdef0 at byte 0x200, then:
3; out[0..35]: buffer_load_format_xyzw with DST_SEL XYZW, four words per format in the order above;
4; out[36..43]: DST_SEL X011 for 8_SINT and 16_UINT (0 and integer 1);
5; out[44..49]: buffer_load_format_d16_xyzw for 8_SINT, 8_8_8_8_SINT and 16_16_16_16_SINT;
6; out[64..81]: buffer_store_format_xyzw of 0x7f, 0x80, -128, -129 (8-bit formats) or 0x7fff, 0x8000, -32768,
7; -32769 (16-bit) at a dword pair per format, with the runtime's selectors (X001, XY01, XYZW); SINT clamps
8; signed, UINT saturates, and a 1-2 byte element keeps the 0xee fill of the rest of its dword.
9; The expected words (check.py FMT_INT_NARROW_WORDS) are this program's output on gfx1036, run natively.
10v_cmpx_eq_u32_e32 0, v0
11v_mov_b32_e32 v1, 0x7f01ff80
12v_mov_b32_e32 v2, 0x8000ffff
13v_mov_b32_e32 v3, 0x12345678
14v_mov_b32_e32 v4, 0x9abcdef0
15v_mov_b32_e32 v5, 0x200
16buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen
17s_waitcnt_vscnt null, 0x0
18s_mov_b32 s4, s0
19s_mov_b32 s5, s1
20s_mov_b32 s6, s2
21s_mov_b32 s7, 0x31005fac
22buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
23s_waitcnt vmcnt(0)
24v_mov_b32_e32 v6, 0x0
25buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
26s_mov_b32 s7, 0x31006fac
27buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
28s_waitcnt vmcnt(0)
29v_mov_b32_e32 v6, 0x10
30buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
31s_mov_b32 s7, 0x3100bfac
32buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
33s_waitcnt vmcnt(0)
34v_mov_b32_e32 v6, 0x20
35buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
36s_mov_b32 s7, 0x3100cfac
37buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
38s_waitcnt vmcnt(0)
39v_mov_b32_e32 v6, 0x30
40buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
41s_mov_b32 s7, 0x31012fac
42buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
43s_waitcnt vmcnt(0)
44v_mov_b32_e32 v6, 0x40
45buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
46s_mov_b32 s7, 0x31013fac
47buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
48s_waitcnt vmcnt(0)
49v_mov_b32_e32 v6, 0x50
50buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
51s_mov_b32 s7, 0x3101cfac
52buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
53s_waitcnt vmcnt(0)
54v_mov_b32_e32 v6, 0x60
55buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
56s_mov_b32 s7, 0x3103dfac
57buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
58s_waitcnt vmcnt(0)
59v_mov_b32_e32 v6, 0x70
60buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
61s_mov_b32 s7, 0x31046fac
62buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
63s_waitcnt vmcnt(0)
64v_mov_b32_e32 v6, 0x80
65buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
66s_mov_b32 s7, 0x31006244
67buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
68s_waitcnt vmcnt(0)
69v_mov_b32_e32 v6, 0x90
70buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
71s_mov_b32 s7, 0x3100b244
72buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen
73s_waitcnt vmcnt(0)
74v_mov_b32_e32 v6, 0xa0
75buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen
76s_mov_b32 s7, 0x31006fac
77buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen
78s_waitcnt vmcnt(0)
79v_mov_b32_e32 v6, 0xb0
80buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
81s_mov_b32 s7, 0x3103dfac
82buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen
83s_waitcnt vmcnt(0)
84v_mov_b32_e32 v6, 0xb8
85buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
86s_mov_b32 s7, 0x31046fac
87buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen
88s_waitcnt vmcnt(0)
89v_mov_b32_e32 v6, 0xc0
90buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
91v_mov_b32_e32 v12, 0x7f
92v_mov_b32_e32 v13, 0x80
93v_mov_b32_e32 v14, 0xffffff80
94v_mov_b32_e32 v15, 0xffffff7f
95v_mov_b32_e32 v16, 0x7fff
96v_mov_b32_e32 v17, 0x8000
97v_mov_b32_e32 v18, 0xffff8000
98v_mov_b32_e32 v19, 0xffff7fff
99s_mov_b32 s7, 0x31005204
100v_mov_b32_e32 v6, 0x100
101buffer_store_format_xyzw v[12:15], v6, s[4:7], 0 offen
102s_mov_b32 s7, 0x31006204
103v_mov_b32_e32 v6, 0x108
104buffer_store_format_xyzw v[12:15], v6, s[4:7], 0 offen
105s_mov_b32 s7, 0x3100b204
106v_mov_b32_e32 v6, 0x110
107buffer_store_format_xyzw v[16:19], v6, s[4:7], 0 offen
108s_mov_b32 s7, 0x3100c204
109v_mov_b32_e32 v6, 0x118
110buffer_store_format_xyzw v[16:19], v6, s[4:7], 0 offen
111s_mov_b32 s7, 0x3101222c
112v_mov_b32_e32 v6, 0x120
113buffer_store_format_xyzw v[12:15], v6, s[4:7], 0 offen
114s_mov_b32 s7, 0x3101322c
115v_mov_b32_e32 v6, 0x128
116buffer_store_format_xyzw v[12:15], v6, s[4:7], 0 offen
117s_mov_b32 s7, 0x3101c22c
118v_mov_b32_e32 v6, 0x130
119buffer_store_format_xyzw v[16:19], v6, s[4:7], 0 offen
120s_mov_b32 s7, 0x3103dfac
121v_mov_b32_e32 v6, 0x138
122buffer_store_format_xyzw v[12:15], v6, s[4:7], 0 offen
123s_mov_b32 s7, 0x31046fac
124v_mov_b32_e32 v6, 0x140
125buffer_store_format_xyzw v[16:19], v6, s[4:7], 0 offen
126s_endpgm
diff --git a/runtime/test/shaders/cs_fmt_sint32.asm b/runtime/test/shaders/cs_fmt_sint32.asm
index a444421ce..fa57f615e 100644
--- a/runtime/test/shaders/cs_fmt_sint32.asm
+++ b/runtime/test/shaders/cs_fmt_sint32.asm
@@ -64,8 +64,8 @@ tbuffer_load_format_x v9, v5, s[4:7], 0 format:[BUF_FMT_32_SINT] offen offset:8
64v_mov_b32_e32 v6, 0x70 64v_mov_b32_e32 v6, 0x70
65buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen 65buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen
66 66
67; MUBUF store via format 63. 67; MUBUF store via format 63 (DST_SEL XY01, standard 2-component RG).
68s_mov_b32 s7, 0x3103ffac 68s_mov_b32 s7, 0x3103f22c
69v_mov_b32_e32 v6, 0x90 69v_mov_b32_e32 v6, 0x90
70buffer_store_format_xy v[1:2], v6, s[4:7], 0 offen 70buffer_store_format_xy v[1:2], v6, s[4:7], 0 offen
71 71
@@ -80,7 +80,7 @@ v_mov_b32_e32 v6, 0xb0
80buffer_store_format_xyzw v[1:4], v6, s[4:7], 0 offen 80buffer_store_format_xyzw v[1:4], v6, s[4:7], 0 offen
81 81
82; A signed packed store must extend both halves. 82; A signed packed store must extend both halves.
83s_mov_b32 s7, 0x3103ffac 83s_mov_b32 s7, 0x3103f22c
84v_mov_b32_e32 v6, 0xc0 84v_mov_b32_e32 v6, 0xc0
85v_mov_b32_e32 v7, 0x8000fffd 85v_mov_b32_e32 v7, 0x8000fffd
86buffer_store_format_d16_xy v7, v6, s[4:7], 0 offen 86buffer_store_format_d16_xy v7, v6, s[4:7], 0 offen
diff --git a/runtime/test/shaders/cs_mask_vgpr_exec.asm b/runtime/test/shaders/cs_mask_vgpr_exec.asm
new file mode 100644
index 000000000..13e0bc0d9
--- /dev/null
+++ b/runtime/test/shaders/cs_mask_vgpr_exec.asm
@@ -0,0 +1,15 @@
1; group: 32,1,1
2; Part-2 test (SHADER-21 follow-up): a lane mask written to a VGPR under partial EXEC.
3; Hardware: inactive lanes keep their old VGPR value.
4; If the translator's write_all_lanes ignores EXEC, inactive lanes get the mask word instead.
5v_mbcnt_lo_u32_b32 v1, -1, 0
6v_mov_b32_e32 v2, 0xdeadbeef
7v_mov_b32_e32 v5, 1
8v_mov_b32_e32 v6, 2
9v_cmp_lt_u32_e64 vcc_lo, v5, v6
10s_mov_b32 exec_lo, 0x0000000f
11v_mov_b32_e32 v2, vcc_lo
12s_mov_b32 exec_lo, -1
13v_lshlrev_b32_e32 v3, 2, v1
14buffer_store_dword v2, v3, s[0:3], 0 offen
15s_endpgm
diff --git a/runtime/test/shaders/cs_signed_zero_nan.asm b/runtime/test/shaders/cs_signed_zero_nan.asm
new file mode 100644
index 000000000..3dd8555cc
--- /dev/null
+++ b/runtime/test/shaders/cs_signed_zero_nan.asm
@@ -0,0 +1,63 @@
1; group: 8,1,1
2; mattr: +wavefrontsize32,-wavefrontsize64
3; NaN, infinity and -0 come out of RDNA2 float ops as computed (IEEE). The translator declares
4; SignedZeroInfNanPreserve so the driver may not assume they don't occur. Without it, on an RX 9070 XT (AMD
5; 26.11.2) this test gets 0 in out[4..7]: the x != x NaN checks fold to false and the NaN conversion is lost. The
6; f16 fuzzer there also saw -0 products come back +0, and NaN results narrowed with integer ops never stored.
7; Apple GPUs (MoltenVK) return +0 in out[0], out[2] and out[3] with or without the mode (#1203, SHADER-182), so
8; check.py and run_gpu_tests.py don't judge those three words on an Apple device; the other five still count.
9; Mesa llvmpipe returns 0 in out[5] (the 0 * inf check) with or without the mode, while its other NaN checks give 1
10; (#664), so out[5] isn't judged there; the other seven still count (UNJUDGED_WORDS in check.py).
11; Thread 0 stores eight words:
12; out[0] v_mul_f32 -0.0 * 1.0 = 0x80000000
13; out[1] v_add_f32 -0.0 + -0.0 = 0x80000000
14; out[2] v_pk_mul_f16 (-0, -0) * (1.0, 1.0) = 0x80008000
15; out[3] v_mul_f16 -0 * 1.0, high half kept (0) = 0x00008000
16; out[4] v_cmp_neq_f32 x, x with x = inf - inf (NaN) = 0x00000001
17; out[5] v_cmp_neq_f32 x, x with x = 0 * inf (NaN) = 0x00000001
18; out[6] v_cmp_neq_f16 x, x with x = f16 inf - inf (NaN) = 0x00000001
19; out[7] v_cvt_f16_f32 of NaN, exponent bits (& 0x7c00) = 0x00007c00
20; Run: vk_compute_test cs_signed_zero_nan.spv 1 dump
21; out[0..7] = 80000000 80000000 80008000 00008000 00000001 00000001 00000001 00007c00 (hex)
22v_cmpx_eq_u32_e32 0, v0
23v_mov_b32_e32 v1, 0x80000000
24v_mov_b32_e32 v2, 1.0
25v_mul_f32_e32 v10, v1, v2
26v_add_f32_e32 v11, v1, v1
27v_mov_b32_e32 v3, 0x80008000
28v_mov_b32_e32 v4, 0x3c003c00
29v_pk_mul_f16 v12, v3, v4
30v_mov_b32_e32 v13, 0
31v_mul_f16_e32 v13, v3, v4
32v_mov_b32_e32 v5, 0x7f800000
33v_sub_f32_e32 v6, v5, v5
34v_cmp_neq_f32_e32 vcc_lo, v6, v6
35v_cndmask_b32_e64 v14, 0, 1, vcc_lo
36v_mov_b32_e32 v7, 0
37v_mul_f32_e32 v8, v7, v5
38v_cmp_neq_f32_e32 vcc_lo, v8, v8
39v_cndmask_b32_e64 v15, 0, 1, vcc_lo
40v_mov_b32_e32 v9, 0x7c00
41v_sub_f16_e32 v16, v9, v9
42v_cmp_neq_f16_e32 vcc_lo, v16, v16
43v_cndmask_b32_e64 v17, 0, 1, vcc_lo
44v_mov_b32_e32 v18, 0
45v_cvt_f16_f32_e32 v18, v6
46v_and_b32_e32 v18, 0x7c00, v18
47v_mov_b32_e32 v30, 0
48buffer_store_dword v10, v30, s[0:3], 0 offen
49v_mov_b32_e32 v30, 4
50buffer_store_dword v11, v30, s[0:3], 0 offen
51v_mov_b32_e32 v30, 8
52buffer_store_dword v12, v30, s[0:3], 0 offen
53v_mov_b32_e32 v30, 12
54buffer_store_dword v13, v30, s[0:3], 0 offen
55v_mov_b32_e32 v30, 16
56buffer_store_dword v14, v30, s[0:3], 0 offen
57v_mov_b32_e32 v30, 20
58buffer_store_dword v15, v30, s[0:3], 0 offen
59v_mov_b32_e32 v30, 24
60buffer_store_dword v17, v30, s[0:3], 0 offen
61v_mov_b32_e32 v30, 28
62buffer_store_dword v18, v30, s[0:3], 0 offen
63s_endpgm
diff --git a/runtime/test/shaders/gs_w64_a_ring.asm b/runtime/test/shaders/gs_w64_a_ring.asm
new file mode 100644
index 000000000..bda97d545
--- /dev/null
+++ b/runtime/test/shaders/gs_w64_a_ring.asm
@@ -0,0 +1,40 @@
1; TEST-251 (SHADER-10 tier A, geometry stage): the lane number forms only the GSVS address. A legacy GS writes each
2; emitted vertex to its lane's GSVS area; here that area's base is lane id * 96 (v_mbcnt_lo/hi of -1), the shape a
3; hardware GS has. The translator maps an LDS write to an output slot from its offset alone and drops the VGPR address
4; (rdna2spirv.py, gs_ds), so the lane id reaches no output and the program is partition invariant: after spirv-opt -O
5; its SPIR-V is the same as without the base. Drawn with vs_ids (param1 = 0x101 + vertex index): triangle
6; p = (TEXCOORD0.x of input vertex 0 - 0x101) / 3. Each invocation stores (p, 3 * p + 1, 77, 0) to its record at heap
7; 0x1000 + 16 * p through the V# in s[4:7], and emits one vertex (no primitive) through the lane-based ring address.
8; Needs a DXBC with ISG1/OSG1 = {SV_Position reg 0, TEXCOORD0 reg 1} (build.py makes it for gs_*).
9; Run: VKH_GS=gs_w64_a_ring.spv VKH_VERTICES=960 VKH_SGPRS=0,0,0,0,0,0,65536,0x30000000 VKH_HEAP=0=0
10; VKH_HEAP_DUMP=heap.raw vk_harness vs_ids.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32:
11; equal records, and equal to the expected words.
12; mattr: +wavefrontsize64,-wavefrontsize32
13s_bfe_i32 s0, s3, 0x80008
14s_bfm_b64 exec, s0, 0
15s_cmp_eq_u32 s0, 64
16s_cselect_b64 exec, -1, exec
17v_lshlrev_b32_e32 v3, 2, v0
18v_and_b32_e32 v10, 0x3fffc, v3
19ds_read_b32 v20, v10 offset:16
20s_waitcnt lgkmcnt(0)
21v_subrev_nc_u32_e32 v20, 0x101, v20
22v_mul_hi_u32 v21, v20, 0xaaaaaaab
23v_lshrrev_b32_e32 v21, 1, v21
24v_mov_b32_e32 v6, v21
25v_lshl_add_u32 v7, v21, 1, v21
26v_add_nc_u32_e32 v7, 1, v7
27v_mov_b32_e32 v8, 0x4d
28v_mov_b32_e32 v9, 0
29v_lshlrev_b32_e32 v12, 4, v21
30v_add_nc_u32_e32 v12, 0x1000, v12
31buffer_store_dwordx4 v[6:9], v12, s[4:7], 0 offen
32v_mbcnt_lo_u32_b32 v13, -1, 0
33v_mbcnt_hi_u32_b32 v13, -1, v13
34v_mul_u32_u24_e32 v13, 0x60, v13
35v_mov_b32_e32 v14, 0
36ds_write2_b32 v13, v14, v14 offset0:0 offset1:1
37s_sendmsg sendmsg(MSG_GS, GS_OP_EMIT, 0)
38s_sendmsg sendmsg(MSG_GS, GS_OP_CUT, 0)
39s_sendmsg sendmsg(MSG_GS_DONE, GS_OP_NOP)
40s_endpgm
diff --git a/runtime/test/shaders/gs_w64_c_lane_id.asm b/runtime/test/shaders/gs_w64_c_lane_id.asm
new file mode 100644
index 000000000..2043c484d
--- /dev/null
+++ b/runtime/test/shaders/gs_w64_c_lane_id.asm
@@ -0,0 +1,36 @@
1; TEST-251 (SHADER-10 tier C, geometry stage): the raw lane number (v_mbcnt_lo/hi of -1) used as data, in a legacy
2; (LDS-ring) wave64 geometry shader with gs_tri's EXEC prologue. Drawn with vs_ids, whose param1 is the integer
3; 0x101 + vertex index: the GS reads it from its first input vertex (signature register 1, TEXCOORD0.x, dword 4),
4; so triangle p = (that - 0x101) / 3. Each GS invocation stores (lane id, lane id & 31, p, 0) to its record at heap
5; 0x1000 + 16 * p through the V# in s[4:7] (the translator sets s3 for the prologue), then emits one vertex, which
6; makes no primitive. In a wave64 GS some invocations get lanes 32..63, in a wave32 one none do, so r0 and r1 depend on
7; the wave size and r2 does not. w64_graphics.py uses it as the probe of the GS wave size.
8; Needs a DXBC with ISG1/OSG1 = {SV_Position reg 0, TEXCOORD0 reg 1} (build.py makes it for gs_*).
9; Run: VKH_GS=gs_w64_c_lane_id.spv VKH_VERTICES=960 VKH_SGPRS=0,0,0,0,0,0,65536,0x30000000 VKH_HEAP=0=0
10; VKH_HEAP_DUMP=heap.raw vk_harness vs_ids.spv <any fragment shader> out.raw, with and without RADV_PERFTEST=gewave32.
11; mattr: +wavefrontsize64,-wavefrontsize32
12s_bfe_i32 s0, s3, 0x80008
13s_bfm_b64 exec, s0, 0
14s_cmp_eq_u32 s0, 64
15s_cselect_b64 exec, -1, exec
16v_lshlrev_b32_e32 v3, 2, v0
17v_and_b32_e32 v10, 0x3fffc, v3
18ds_read_b32 v20, v10 offset:16
19s_waitcnt lgkmcnt(0)
20v_subrev_nc_u32_e32 v20, 0x101, v20
21v_mul_hi_u32 v21, v20, 0xaaaaaaab
22v_lshrrev_b32_e32 v21, 1, v21
23v_mbcnt_lo_u32_b32 v6, -1, 0
24v_mbcnt_hi_u32_b32 v6, -1, v6
25v_and_b32_e32 v7, 31, v6
26v_mov_b32_e32 v8, v21
27v_mov_b32_e32 v9, 0
28v_lshlrev_b32_e32 v12, 4, v21
29v_add_nc_u32_e32 v12, 0x1000, v12
30buffer_store_dwordx4 v[6:9], v12, s[4:7], 0 offen
31v_mov_b32_e32 v13, 0
32ds_write2_b32 v13, v13, v13 offset0:0 offset1:1
33s_sendmsg sendmsg(MSG_GS, GS_OP_EMIT, 0)
34s_sendmsg sendmsg(MSG_GS, GS_OP_CUT, 0)
35s_sendmsg sendmsg(MSG_GS_DONE, GS_OP_NOP)
36s_endpgm
diff --git a/runtime/test/shaders/ps_sdwa_f16_const.asm b/runtime/test/shaders/ps_sdwa_f16_const.asm
new file mode 100644
index 000000000..cc600bcd8
--- /dev/null
+++ b/runtime/test/shaders/ps_sdwa_f16_const.asm
@@ -0,0 +1,32 @@
1; SDWA source select on a float inline constant in an f16 op. Assemble with llvm-mc -mcpu=gfx1013 -show-encoding,
2; translate, run with vk_harness. In a 16-bit float op an inline float constant is the f16 value in bits 15:0 over a
3; zero high half (docs/design.md, "f16 inline constants"); SDWA src<i>_sel then narrows those 32 bits like a
4; register's (zero-extended), before the op. An SGPR source and an integer op reading the f32 bits of 1.0 are
5; narrowed the same way. dst_sel:WORD_0 with UNUSED_PRESERVE keeps the destination's 0xaaaa high half.
6; v1 = 0.5 | 1024.0 << 16 (0x64003800), s8 = 0x3c000000 (1.0 in the high half), v2..v5 start as 0xaaaa5555.
7; x: v_add_f16_sdwa v2, 1.0, v1 src0_sel:WORD_1 src1_sel:WORD_0
8; 1.0 = 0x00003c00, WORD_1 = 0x0000 = +0.0; +0.0 + 0.5 = 0.5 = 0x3800 -> 0xaaaa3800
9; (the unselected constant would give 1.5 = 0x3e00)
10; y: v_mul_f16_sdwa v3, 2.0, v1 src0_sel:BYTE_1 src1_sel:WORD_1
11; 2.0 = 0x00004000, BYTE_1 = 0x0040 = 64 * 2^-24 = 2^-18 (f16 denormal); * 1024.0 = 2^-8 = 0x1c00
12; -> 0xaaaa1c00 (the unselected constant would give 2048.0 = 0x6800)
13; z: v_add_f16_sdwa v4, s8, v1 src0_sel:WORD_1 src1_sel:WORD_0
14; s8 WORD_1 = 0x3c00 = 1.0; 1.0 + 0.5 = 1.5 = 0x3e00 -> 0xaaaa3e00
15; w: v_cvt_f16_u16_sdwa v5, 1.0 src0_sel:WORD_1 (integer source: the f32 bits 0x3f800000)
16; WORD_1 = 0x3f80 = 16256 = 2^13 * (1 + 1008/1024) -> f16 exponent 13 + 15 = 28: 0x7000 | 0x3f0 = 0x73f0
17; -> 0xaaaa73f0
18; Expected mrt0 bits: 0xaaaa3800, 0xaaaa1c00, 0xaaaa3e00, 0xaaaa73f0
19; Measured: the same four words on an AMD Radeon iGPU (gfx1036, Ryzen 9 9950X3D, driver 26.10.1) through
20; tools/hw_oracle (raw HIP kernel, wave32), the same instructions writing v8..v11.
21v_mov_b32 v1, 0x64003800
22v_mov_b32 v2, 0xaaaa5555
23v_mov_b32 v3, 0xaaaa5555
24v_mov_b32 v4, 0xaaaa5555
25v_mov_b32 v5, 0xaaaa5555
26s_mov_b32 s8, 0x3c000000
27v_add_f16_sdwa v2, 1.0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0
28v_mul_f16_sdwa v3, 2.0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_1 src1_sel:WORD_1
29v_add_f16_sdwa v4, s8, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0
30v_cvt_f16_u16_sdwa v5, 1.0 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1
31exp mrt0 v2, v3, v4, v5 done vm
32s_endpgm
diff --git a/runtime/test/shaders/ps_w64_a_bpermute.asm b/runtime/test/shaders/ps_w64_a_bpermute.asm
new file mode 100644
index 000000000..90b8f1435
--- /dev/null
+++ b/runtime/test/shaders/ps_w64_a_bpermute.asm
@@ -0,0 +1,44 @@
1; SHADER-10, GPU check of ds_bpermute_b32 in a wave64 pixel shader: a wave64 ds_bpermute runs as two wave32 halves
2; (ISA 10.4.4; tests/semantic/test_wave64_cross_half.py), so an address taken from the lane id reads the same lane
3; whether the lane id is counted in the wave (0..63) or in a half (0..31): only address bits 2..6 are used.
4; p = y * 64 + x (x = floor(u * 64), y = floor(v * 64) on the 64x64 target of vs_ids). The words depend only on the
5; 2x2 quad layout of fragment lanes (lane 4k+0 top-left, +1 top-right, +2 bottom-left, +3 bottom-right):
6; r0 = ds_bpermute from lane ^ 1: the right/left neighbour, (x ^ 1) + 64 * y.
7; r1 = ds_bpermute from lane ^ 3: the diagonal pixel, (x ^ 1) + 64 * (y ^ 1).
8; r2 = ds_bpermute from lane ^ 16, twice: back to the own pixel, p.
9; r3 = ds_bpermute from lane & ~3 + 2 (the quad's bottom-left lane): (x & ~1) + 64 * (y | 1).
10; The reads that go out and come back also need the partner lane to hold a pixel: vs_ids' full-screen triangle on
11; the 64x64 target fills every wave.
12; Run: vk_harness vs_ids.spv ps_w64_a_bpermute.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: equal images, equal to
13; the derived words.
14; mattr: +wavefrontsize64,-wavefrontsize32
15v_interp_p1_f32_e32 v2, v0, attr0.x
16v_interp_p2_f32_e32 v2, v1, attr0.x
17v_interp_p1_f32_e32 v3, v0, attr0.y
18v_interp_p2_f32_e32 v3, v1, attr0.y
19v_mul_f32_e32 v2, 0x42800000, v2
20v_mul_f32_e32 v3, 0x42800000, v3
21v_cvt_u32_f32_e32 v2, v2
22v_cvt_u32_f32_e32 v3, v3
23v_lshl_add_u32 v4, v3, 6, v2
24s_mov_b64 s[10:11], exec
25v_mbcnt_lo_u32_b32 v10, -1, 0
26v_mbcnt_hi_u32_b32 v10, -1, v10
27v_xor_b32_e32 v11, 1, v10
28v_lshlrev_b32_e32 v11, 2, v11
29ds_bpermute_b32 v6, v11, v4
30v_xor_b32_e32 v11, 3, v10
31v_lshlrev_b32_e32 v11, 2, v11
32ds_bpermute_b32 v7, v11, v4
33v_xor_b32_e32 v11, 16, v10
34v_lshlrev_b32_e32 v11, 2, v11
35ds_bpermute_b32 v5, v11, v4
36s_waitcnt lgkmcnt(0)
37ds_bpermute_b32 v8, v11, v5
38v_and_b32_e32 v11, -4, v10
39v_or_b32_e32 v11, 2, v11
40v_lshlrev_b32_e32 v11, 2, v11
41ds_bpermute_b32 v9, v11, v4
42s_waitcnt lgkmcnt(0)
43exp mrt0 v6, v7, v8, v9 done vm
44s_endpgm
diff --git a/runtime/test/shaders/ps_w64_a_permlane.asm b/runtime/test/shaders/ps_w64_a_permlane.asm
new file mode 100644
index 000000000..b89a6383f
--- /dev/null
+++ b/runtime/test/shaders/ps_w64_a_permlane.asm
@@ -0,0 +1,42 @@
1; SHADER-10 tier A, GPU check of v_permlane16_b32 and v_permlanex16_b32 in a wave64 pixel shader (they never leave a
2; 32-lane half: permlane16 reads within the lane's row of 16, permlanex16 from the other row of the same half).
3; p = y * 64 + x is the pixel number (x = floor(u * 64), y = floor(v * 64) on the 64x64 target of vs_ids). The words
4; must not depend on how the rasterizer packs pixels into lanes, only on the 2x2 quad layout of fragment lanes (lane
5; 4k+0 top-left, +1 top-right, +2 bottom-left, +3 bottom-right), so every read stays in the lane's quad or comes back:
6; r0 = permlane16 with selects lane ^ 1 (0x67452301, 0xefcdab89): the right/left neighbour, (x ^ 1) + 64 * y.
7; r1 = permlane16 with selects lane ^ 2 (0x54761032, 0xdcfe98ba): the pixel below/above, x + 64 * (y ^ 1).
8; r2 = permlanex16 with the identity selects (0x76543210, 0xfedcba98) twice: lane L reads lane L ^ 16 of its half,
9; then back, so r2 = p.
10; r3 = permlanex16 with selects lane ^ 3 (0x45670123, 0xcdef89ab) of a value already read from lane ^ 3 of the other
11; row (the same selects with permlanex16), so r3 = p again, through a non-identity mapping.
12; The reads that go out and come back also need the partner lane to hold a pixel: vs_ids' full-screen triangle on
13; the 64x64 target fills every wave.
14; Run: vk_harness vs_ids.spv ps_w64_a_permlane.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: equal images, equal to
15; the derived words.
16; mattr: +wavefrontsize64,-wavefrontsize32
17v_interp_p1_f32_e32 v2, v0, attr0.x
18v_interp_p2_f32_e32 v2, v1, attr0.x
19v_interp_p1_f32_e32 v3, v0, attr0.y
20v_interp_p2_f32_e32 v3, v1, attr0.y
21v_mul_f32_e32 v2, 0x42800000, v2
22v_mul_f32_e32 v3, 0x42800000, v3
23v_cvt_u32_f32_e32 v2, v2
24v_cvt_u32_f32_e32 v3, v3
25v_lshl_add_u32 v4, v3, 6, v2
26s_mov_b64 s[10:11], exec
27s_mov_b32 s20, 0x67452301
28s_mov_b32 s21, 0xefcdab89
29v_permlane16_b32 v6, v4, s20, s21
30s_mov_b32 s22, 0x54761032
31s_mov_b32 s23, 0xdcfe98ba
32v_permlane16_b32 v7, v4, s22, s23
33s_mov_b32 s24, 0x76543210
34s_mov_b32 s25, 0xfedcba98
35v_permlanex16_b32 v5, v4, s24, s25
36v_permlanex16_b32 v8, v5, s24, s25
37s_mov_b32 s26, 0x45670123
38s_mov_b32 s27, 0xcdef89ab
39v_permlanex16_b32 v5, v4, s26, s27
40v_permlanex16_b32 v9, v5, s26, s27
41exp mrt0 v6, v7, v8, v9 done vm
42s_endpgm
diff --git a/runtime/test/shaders/ps_w64_a_swizzle.asm b/runtime/test/shaders/ps_w64_a_swizzle.asm
new file mode 100644
index 000000000..26c71fa02
--- /dev/null
+++ b/runtime/test/shaders/ps_w64_a_swizzle.asm
@@ -0,0 +1,35 @@
1; SHADER-10 tier A, GPU check of ds_swizzle_b32 in a wave64 pixel shader (the swizzle works on groups of 32 lanes, so
2; it never leaves a half). p = y * 64 + x is the pixel number (x = floor(u * 64), y = floor(v * 64) on the 64x64 target
3; of vs_ids). The words depend only on the 2x2 quad layout of fragment lanes (lane 4k+0 top-left, +1 top-right,
4; +2 bottom-left, +3 bottom-right), not on how pixels are packed into lanes:
5; r0 = quad-permute mode, selects 3, 2, 1, 0 (offset 0x801b, swizzle(QUAD_PERM,3,2,1,0)): the diagonal pixel,
6; (x ^ 1) + 64 * (y ^ 1).
7; r1 = bitmask mode, and 0x1f, xor 1 (offset 0x041f, swizzle(SWAP,1)): the right/left neighbour, (x ^ 1) + 64 * y.
8; r2 = bitmask mode, and 0x1f, xor 0x10 (offset 0x401f, swizzle(SWAP,16)) twice: lane L reads lane L ^ 16, then
9; back, so r2 = p.
10; r3 = bitmask mode, and 0x1c (offset 0x001c, swizzle(BROADCAST,4,0)): every lane reads its quad's first lane,
11; (x & ~1) + 64 * (y & ~1).
12; The reads that go out and come back also need the partner lane to hold a pixel: vs_ids' full-screen triangle on
13; the 64x64 target fills every wave.
14; Run: vk_harness vs_ids.spv ps_w64_a_swizzle.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: equal images, equal to
15; the derived words.
16; mattr: +wavefrontsize64,-wavefrontsize32
17v_interp_p1_f32_e32 v2, v0, attr0.x
18v_interp_p2_f32_e32 v2, v1, attr0.x
19v_interp_p1_f32_e32 v3, v0, attr0.y
20v_interp_p2_f32_e32 v3, v1, attr0.y
21v_mul_f32_e32 v2, 0x42800000, v2
22v_mul_f32_e32 v3, 0x42800000, v3
23v_cvt_u32_f32_e32 v2, v2
24v_cvt_u32_f32_e32 v3, v3
25v_lshl_add_u32 v4, v3, 6, v2
26s_mov_b64 s[10:11], exec
27ds_swizzle_b32 v6, v4 offset:0x801b
28ds_swizzle_b32 v7, v4 offset:0x41f
29ds_swizzle_b32 v5, v4 offset:0x401f
30s_waitcnt lgkmcnt(0)
31ds_swizzle_b32 v8, v5 offset:0x401f
32ds_swizzle_b32 v9, v4 offset:0x1c
33s_waitcnt lgkmcnt(0)
34exp mrt0 v6, v7, v8, v9 done vm
35s_endpgm
diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py
index 6e281d4b4..efa21c752 100644
--- a/runtime/test/shaders/w64_graphics.py
+++ b/runtime/test/shaders/w64_graphics.py
@@ -15,7 +15,8 @@ hardware wave, the reference) and to 32 (the halves) through VKH_SUBGROUP_SIZE o
15A device that can require only one size (NVIDIA: 32 only) cannot run the comparison. There the default-size image is 15A device that can require only one size (NVIDIA: 32 only) cannot run the comparison. There the default-size image is
16checked against the derived words (tiers A, B), the tier C check is skipped, and two environment variables let a 16checked against the derived words (tiers A, B), the tier C check is skipped, and two environment variables let a
17second device stand in for the missing size: W64G_SAVE_REF=<dir> stores each 64-lane run of a device that can require 17second device stand in for the missing size: W64G_SAVE_REF=<dir> stores each 64-lane run of a device that can require
18it, and W64G_REF=<dir> compares every run of the other device with those files (equal for A and B, different for C). 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).
19 20
20The vs_w64_* fixtures (TEST-251) are vertex shaders: Vulkan cannot require a vertex subgroup size, so the two sizes 21The vs_w64_* fixtures (TEST-251) are vertex shaders: Vulkan cannot require a vertex subgroup size, so the two sizes
21come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+). 22come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+).
@@ -23,6 +24,10 @@ Each draws 960 vertices with zero area (VKH_VERTICES) and stores four words per
23doubles as the probe that the wave size really changed, and without RADV only the default-size checks run. RADV packs 24doubles as the probe that the wave size really changed, and without RADV only the default-size checks run. RADV packs
2462 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run is a repacking, not the two halves of 2562 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run is a repacking, not the two halves of
25the 64-lane waves: a stricter test of tiers A and B, which key every word on the vertex index. 26the 64-lane waves: a stricter test of tiers A and B, which key every word on the vertex index.
27
28The gs_w64_* fixtures are legacy geometry shaders, switched the same way (gewave32 covers the whole NGG stage). Each is
29drawn after vs_ids with VKH_GS, finds its triangle from the vertex number vs_ids passes in TEXCOORD0, and stores four
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.
26""" 31"""
27import os 32import os
28import struct 33import struct
@@ -101,6 +106,21 @@ def _a_one_lane(i):
101 return (7777 if on else 1000 + x, 3000 + 11 * on, 4000 + y + 13 * on, x % 4) 106 return (7777 if on else 1000 + x, 3000 + 11 * on, 4000 + y + 13 * on, x % 4)
102 107
103 108
109def _a_permlane(i):
110 x, y = _x(i), _y(i)
111 return ((x ^ 1) + 64 * y, x + 64 * (y ^ 1), 64 * y + x, 64 * y + x)
112
113
114def _a_swizzle(i):
115 x, y = _x(i), _y(i)
116 return ((x ^ 1) + 64 * (y ^ 1), (x ^ 1) + 64 * y, 64 * y + x, (x & ~1) + 64 * (y & ~1))
117
118
119def _a_bpermute(i):
120 x, y = _x(i), _y(i)
121 return ((x ^ 1) + 64 * y, (x ^ 1) + 64 * (y ^ 1), 64 * y + x, (x & ~1) + 64 * (y | 1))
122
123
104def _c_vote_else(i): 124def _c_vote_else(i):
105 return (7 if _on(i) else None, _on(i), 0, 0) # r0 of the other pixels: 0 or 5 by the partition 125 return (7 if _on(i) else None, _on(i), 0, 0) # r0 of the other pixels: 0 or 5 by the partition
106 126
@@ -124,18 +144,26 @@ def _vs_b_readlane_uniform(i):
124 144
125 145
126def _vs_c_lane_id(i): 146def _vs_c_lane_id(i):
127 return (None, None, i, 0) # r0, r1 = the lane the vertex got 147 return (None, None, i, 0) # r0, r1 = the lane the vertex got (gs_: the triangle)
148
149
150def _gs_a_ring(i): # gs_w64_* fixtures: i is the triangle
151 return (i, 3 * i + 1, 77, 0)
128 152
129 153
130VS_ENV = {"VKH_SGPRS": "0,0,65536,0x30000000", "VKH_HEAP": "0=0"} 154VS_ENV = {"VKH_SGPRS": "0,0,65536,0x30000000", "VKH_HEAP": "0=0"}
131VS_VERTICES = 960 # 15 rows of 64 vertices: several waves at either size, and partial ones 155VS_VERTICES = 960 # 15 rows of 64 vertices: several waves at either size, and partial ones
132VS_RECORDS = 0x1000 // 4 # heap word of vertex 0's record (4 words per vertex); below it, the atomic's counter and slots 156VS_RECORDS = 0x1000 // 4 # heap word of vertex 0's record (4 words per vertex); below it, the atomic's counter and slots
157GS_ENV = {"VKH_SGPRS": "0,0,0,0,0,0,65536,0x30000000", "VKH_HEAP": "0=0"} # V# in s[4:7]: the GS entry sets s3
133 158
134 159
135# name -> (tier, expected words per pixel (None = not fixed), environment of the draw) 160# name -> (tier, expected words per pixel (None = not fixed), environment of the draw)
136FIXTURES = { 161FIXTURES = {
137 "ps_w64_a_skip": ("A", _a_skip, {}), 162 "ps_w64_a_skip": ("A", _a_skip, {}),
138 "ps_w64_a_one_lane": ("A", _a_one_lane, {}), 163 "ps_w64_a_one_lane": ("A", _a_one_lane, {}),
164 "ps_w64_a_permlane": ("A", _a_permlane, {}),
165 "ps_w64_a_swizzle": ("A", _a_swizzle, {}),
166 "ps_w64_a_bpermute": ("A", _a_bpermute, {}),
139 "ps_w64_b_waterfall": ("B", _b_waterfall, {}), 167 "ps_w64_b_waterfall": ("B", _b_waterfall, {}),
140 "ps_w64_b_readfirstlane": ("B", _b_readfirstlane, {"VKH_SGPRS": "0,0,0,0,123"}), 168 "ps_w64_b_readfirstlane": ("B", _b_readfirstlane, {"VKH_SGPRS": "0,0,0,0,123"}),
141 "ps_w64_b_readlane_uniform": ("B", _b_readlane_uniform, {"VKH_SGPRS": "0,0,0,0,123"}), 169 "ps_w64_b_readlane_uniform": ("B", _b_readlane_uniform, {"VKH_SGPRS": "0,0,0,0,123"}),
@@ -155,10 +183,12 @@ FIXTURES = {
155 "vs_w64_c_bcnt_export": ("C", _c_bcnt, VS_ENV), 183 "vs_w64_c_bcnt_export": ("C", _c_bcnt, VS_ENV),
156 "vs_w64_c_readlane": ("C", _c_readlane, VS_ENV), 184 "vs_w64_c_readlane": ("C", _c_readlane, VS_ENV),
157 "vs_w64_c_lane_id": ("C", _vs_c_lane_id, VS_ENV), 185 "vs_w64_c_lane_id": ("C", _vs_c_lane_id, VS_ENV),
186 "gs_w64_a_ring": ("A", _gs_a_ring, GS_ENV),
187 "gs_w64_c_lane_id": ("C", _vs_c_lane_id, GS_ENV),
158} 188}
159 189
160VS_PROBE = "vs_w64_c_lane_id" 190PROBES = {"vs": "vs_w64_c_lane_id", "gs": "gs_w64_c_lane_id"} # per stage: the largest lane id shows the wave size
161_vs_applied = {} 191_applied = {}
162 192
163 193
164def _radv_perftest(size): 194def _radv_perftest(size):
@@ -169,30 +199,34 @@ def _radv_perftest(size):
169 return ",".join(flags + ["gewave32"] * (size == 32)) 199 return ",".join(flags + ["gewave32"] * (size == 32))
170 200
171 201
172def _vs_wave_size(tools, spirv, size, tmp): 202def _wave_size(tools, spirv, stage, size, tmp):
173 """Whether a vertex draw at `size` really ran at that wave size: the largest lane id of VS_PROBE is 32..63 in a 203 """Whether a vertex or geometry draw at `size` really ran at that wave size: the largest lane id of the stage's
174 wave64 VS and below 32 in a wave32 one. Size 32 also needs size 64 to work, so that the two draws differ.""" 204 probe is 32..63 in a wave64 and below 32 in a wave32. Size 32 also needs size 64 to work, so the draws differ."""
175 if size not in _vs_applied: 205 if (stage, size) not in _applied:
176 def top(s): 206 def top(s):
177 words = _draw_vs(tools, spirv, VS_PROBE, s, tmp)[0] 207 words = _draw_heap(tools, spirv, PROBES[stage], s, tmp)[0]
178 return None if words is None else max(w[0] for w in words) 208 return None if words is None else max(w[0] for w in words)
179 lane64, lane32 = top(64), top(32) 209 lane64, lane32 = top(64), top(32)
180 _vs_applied[64] = lane64 is not None and 32 <= lane64 < 64 210 _applied[stage, 64] = lane64 is not None and 32 <= lane64 < 64
181 _vs_applied[32] = _vs_applied[64] and lane32 is not None and lane32 < 32 211 _applied[stage, 32] = _applied[stage, 64] and lane32 is not None and lane32 < 32
182 return _vs_applied[size] 212 return _applied[stage, size]
183 213
184 214
185def _draw_vs(tools, spirv, name, size, tmp): 215def _draw_heap(tools, spirv, name, size, tmp):
186 """(records, heap) of one vertex draw at `size` (None: as the environment says), or (None, message).""" 216 """(records, heap) of one vs_/gs_ draw at `size` (None: as the environment says), or (None, message). A vertex
217 fixture stores one record per vertex; a geometry fixture, drawn after vs_ids, one per triangle."""
187 env = dict(os.environ, **FIXTURES[name][2]) 218 env = dict(os.environ, **FIXTURES[name][2])
188 if size: 219 if size:
189 env["RADV_PERFTEST"] = _radv_perftest(size) 220 env["RADV_PERFTEST"] = _radv_perftest(size)
190 raw, heap = Path(tmp) / f"{name}.{size}.raw", Path(tmp) / f"{name}.{size}.heap" 221 raw, heap = Path(tmp) / f"{name}.{size}.raw", Path(tmp) / f"{name}.{size}.heap"
191 env.update(VKH_VERTICES=str(VS_VERTICES), VKH_HEAP_DUMP=str(heap)) 222 env.update(VKH_VERTICES=str(VS_VERTICES), VKH_HEAP_DUMP=str(heap))
192 env.pop("VKH_SUBGROUP_SIZE", None) 223 env.pop("VKH_SUBGROUP_SIZE", None)
193 # The triangles have zero area, so no pixel is drawn and any fragment shader does. 224 vs, records = os.path.join(spirv, name + ".spv"), VS_VERTICES
194 cmd = [os.path.join(tools, "vk_harness" + EXE), os.path.join(spirv, name + ".spv"), 225 if name.startswith("gs_"):
195 os.path.join(spirv, "ps_w64_a_skip.spv"), str(raw)] 226 env["VKH_GS"] = vs
227 vs, records = os.path.join(spirv, "vs_ids.spv"), VS_VERTICES // 3
228 # The triangles have zero area (a GS fixture emits no primitive), so no pixel is drawn and any fragment shader does.
229 cmd = [os.path.join(tools, "vk_harness" + EXE), vs, os.path.join(spirv, "ps_w64_a_skip.spv"), str(raw)]
196 r = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=120) 230 r = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=120)
197 out = r.stdout + r.stderr 231 out = r.stdout + r.stderr
198 if r.returncode == UNSUPPORTED: 232 if r.returncode == UNSUPPORTED:
@@ -200,18 +234,18 @@ def _draw_vs(tools, spirv, name, size, tmp):
200 if r.returncode or not heap.is_file(): 234 if r.returncode or not heap.is_file():
201 return None, f"exit {r.returncode}: {' | '.join(out.strip().splitlines()[-3:])}" 235 return None, f"exit {r.returncode}: {' | '.join(out.strip().splitlines()[-3:])}"
202 words = list(struct.unpack("<%dI" % (65536 // 4), heap.read_bytes())) 236 words = list(struct.unpack("<%dI" % (65536 // 4), heap.read_bytes()))
203 return [tuple(words[VS_RECORDS + 4 * v:VS_RECORDS + 4 * v + 4]) for v in range(VS_VERTICES)], words 237 return [tuple(words[VS_RECORDS + 4 * v:VS_RECORDS + 4 * v + 4]) for v in range(records)], words
204 238
205 239
206def draw(tools, spirv, name, size, tmp): 240def draw(tools, spirv, name, size, tmp):
207 """(words per pixel, heap words or None, applied) of one draw. `applied`: the required size took effect (size 241 """(words per pixel, heap words or None, applied) of one draw. `applied`: the required size took effect (size
208 None: no size asked, applied is None). The words are None when the draw failed; then `heap` is the message.""" 242 None: no size asked, applied is None). The words are None when the draw failed; then `heap` is the message."""
209 tier, expect, extra = FIXTURES[name] 243 tier, expect, extra = FIXTURES[name]
210 if name.startswith("vs_"): 244 if name.startswith(("vs_", "gs_")):
211 words, heap = _draw_vs(tools, spirv, name, size, tmp) 245 words, heap = _draw_heap(tools, spirv, name, size, tmp)
212 if words is None: 246 if words is None:
213 return None, heap, None 247 return None, heap, None
214 return words, heap, _vs_wave_size(tools, spirv, size, tmp) if size else None 248 return words, heap, _wave_size(tools, spirv, name[:2], size, tmp) if size else None
215 env = dict(os.environ, **extra) 249 env = dict(os.environ, **extra)
216 env.pop("VKH_SUBGROUP_SIZE", None) 250 env.pop("VKH_SUBGROUP_SIZE", None)
217 if size: 251 if size:
diff --git a/runtime/test/typeless_rtv_test.cpp b/runtime/test/typeless_rtv_test.cpp
index 2b84804ee..a653770da 100644
--- a/runtime/test/typeless_rtv_test.cpp
+++ b/runtime/test/typeless_rtv_test.cpp
@@ -49,7 +49,7 @@ leonida::ResourceBinding resource() {
49 r.image = reinterpret_cast<VkImage>(std::uintptr_t{1}); 49 r.image = reinterpret_cast<VkImage>(std::uintptr_t{1});
50 r.format = VK_FORMAT_R8G8B8A8_UNORM; 50 r.format = VK_FORMAT_R8G8B8A8_UNORM;
51 r.width = 5; r.height = 3; 51 r.width = 5; r.height = 3;
52 r.rgba8_typeless = true; 52 r.typeless = true;
53 return r; 53 return r;
54} 54}
55void reset_counters() { 55void reset_counters() {
@@ -254,7 +254,7 @@ int main() {
254 EXPECT(requested_range.layerCount == view.layer_count && rendering_layers == view.layer_count); 254 EXPECT(requested_range.layerCount == view.layer_count && rendering_layers == view.layer_count);
255 ++checks; 255 ++checks;
256 } 256 }
257 auto wrong = binding; wrong.rgba8_typeless = false; 257 auto wrong = binding; wrong.typeless = false;
258 EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_srgb})); 258 EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_srgb}));
259 wrong = binding; wrong.format = VK_FORMAT_R32_SFLOAT; 259 wrong = binding; wrong.format = VK_FORMAT_R32_SFLOAT;
260 EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_uint})); 260 EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_uint}));
@@ -294,7 +294,7 @@ int main() {
294 EXPECT(run(same_format, binding, unavailable) == ReplayResult::success && image_clears == 1 && !attachment_clears); 294 EXPECT(run(same_format, binding, unavailable) == ReplayResult::success && image_clears == 1 && !attachment_clears);
295 ++checks; 295 ++checks;
296 auto legacy = binding; 296 auto legacy = binding;
297 legacy.rgba8_typeless = false; 297 legacy.typeless = false;
298 legacy.format = VK_FORMAT_UNDEFINED; // Existing ownerless float-only replay clients omit this metadata. 298 legacy.format = VK_FORMAT_UNDEFINED; // Existing ownerless float-only replay clients omit this metadata.
299 CommandList legacy_list; 299 CommandList legacy_list;
300 EXPECT(legacy_list.clear_render_target({1, 0, 0, 1}, color) && legacy_list.close()); 300 EXPECT(legacy_list.clear_render_target({1, 0, 0, 1}, color) && legacy_list.close());
diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp
index 041f6f648..91f954cf3 100644
--- a/runtime/test/vk_bindless_test.cpp
+++ b/runtime/test/vk_bindless_test.cpp
@@ -665,13 +665,16 @@ int main(int argc, char** argv) {
665 for (std::uint32_t i = 1; i < set.image_capacity(ImageDimension::dim_1d); ++i) 665 for (std::uint32_t i = 1; i < set.image_capacity(ImageDimension::dim_1d); ++i)
666 filled.push_back(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL)); 666 filled.push_back(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL));
667 EXPECT(filled.front() == 1 && filled.back() == set.image_capacity(ImageDimension::dim_1d) - 1); 667 EXPECT(filled.front() == 1 && filled.back() == set.image_capacity(ImageDimension::dim_1d) - 1);
668 EXPECT(set.free_images(ImageDimension::dim_1d) == 0);
668 EXPECT(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 0); 669 EXPECT(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 0);
669 set.remove_image(ImageDimension::dim_1d, 7); 670 set.remove_image(ImageDimension::dim_1d, 7);
670 EXPECT(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 7); 671 EXPECT(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 7);
671 for (const std::uint32_t index : filled) set.remove_image(ImageDimension::dim_1d, index); 672 for (const std::uint32_t index : filled) set.remove_image(ImageDimension::dim_1d, index);
673 EXPECT(set.free_images(ImageDimension::dim_1d) == set.image_capacity(ImageDimension::dim_1d) - 1);
674 EXPECT(set.free_samplers() == set.sampler_capacity() - 1);
672 const std::uint32_t decoy_sampler = set.add_sampler(nearest); 675 const std::uint32_t decoy_sampler = set.add_sampler(nearest);
673 const std::uint32_t sampler_index = set.add_sampler(nearest); 676 const std::uint32_t sampler_index = set.add_sampler(nearest);
674 EXPECT(decoy_sampler == 1 && sampler_index == 2); 677 EXPECT(decoy_sampler == 1 && sampler_index == 2 && set.free_samplers() == set.sampler_capacity() - 3);
675 678
676 if (atomic_mode) { 679 if (atomic_mode) {
677 // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from 680 // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from
diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp
index a2491b64b..fe9ae194a 100644
--- a/runtime/test/vk_harness.cpp
+++ b/runtime/test/vk_harness.cpp
@@ -500,7 +500,10 @@ int main(int argc, char** argv) {
500 stages[2].pNext = &reqSg; 500 stages[2].pNext = &reqSg;
501 else if (!mesh && !gs_tested && (sgProps.requiredSubgroupSizeStages & VK_SHADER_STAGE_FRAGMENT_BIT)) 501 else if (!mesh && !gs_tested && (sgProps.requiredSubgroupSizeStages & VK_SHADER_STAGE_FRAGMENT_BIT))
502 stages[1].pNext = &reqSg; 502 stages[1].pNext = &reqSg;
503 if (stages[1].pNext == &reqSg) std::fprintf(stderr, "fragment subgroup size: %u\n", req_sg); 503 // A device with one subgroup size runs every stage at it, required or not (AMD GCN: 64, with only COMPUTE
504 // in requiredSubgroupSizeStages), so the fragment stage of a plain draw already has the size asked for.
505 const bool fixed = !mesh && !gs_tested && sgProps.minSubgroupSize == sgProps.maxSubgroupSize;
506 if (stages[1].pNext == &reqSg || fixed) std::fprintf(stderr, "fragment subgroup size: %u\n", req_sg);
504 } else if (req_sg > 0) { 507 } else if (req_sg > 0) {
505 std::fprintf(stderr, "fragment subgroup size: %u not available\n", req_sg); 508 std::fprintf(stderr, "fragment subgroup size: %u not available\n", req_sg);
506 } 509 }
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp
index f7b3fc925..6e1e63eb8 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -26,8 +26,17 @@
26// that kills the driver (SIGFPE, SIGSEGV, ...) is recorded as failed ("MODULE CRASH") and the pass 26// that kills the driver (SIGFPE, SIGSEGV, ...) is recorded as failed ("MODULE CRASH") and the pass
27// goes on. A crashed batch is bisected to the module. Children run one after the other and share 27// goes on. A crashed batch is bisected to the module. Children run one after the other and share
28// cache.bin. Not compatible with --stats. 28// cache.bin. Not compatible with --stats.
29// --inflight-file F keep the modules that are in the driver in F, one "name<TAB>phase" line each (phase: module
30// while vkCreateShaderModule runs, pipeline while its pipeline is created), so whoever ran the check
31// can tell which module was there when the process died. F is rewritten when a module over
32// --large-module-bytes enters or leaves the driver (it is alone then, so F names exactly it) and by
33// the 5 s watchdog for the others, and emptied at the end. make_game.py's pipelines stage reads it.
34// --skip-file F modules named in F (one per line) are not compiled: each is reported as MODULE CRASH and counted
35// as a failed pipeline, as --isolate does for a module that killed the driver. make_game.py writes F
36// after a crash, so the next run checks everything else instead of dying on the same module.
29// test hook VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL] raises SIGNAL (default SIGFPE) 37// test hook VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL] raises SIGNAL (default SIGFPE)
30// just before the pipeline of a matching module is created. Only for testing --isolate. 38// just before the pipeline of a matching module is created. For testing --isolate and the
39// pipelines stage's retry.
31#include "vulkan_loader.h" 40#include "vulkan_loader.h"
32#include "vk_device_pick.h" 41#include "vk_device_pick.h"
33#include "pipeline_cache_file.h" 42#include "pipeline_cache_file.h"
@@ -78,6 +87,7 @@ struct ShaderMeta {
78 bool writes_depth = false; 87 bool writes_depth = false;
79 bool needs_maintenance8 = false; 88 bool needs_maintenance8 = false;
80 std::vector<std::string> features; 89 std::vector<std::string> features;
90 std::vector<std::string> float_controls; // VkPhysicalDeviceFloatControlsProperties members that must be true
81 std::vector<uint32_t> inputs; 91 std::vector<uint32_t> inputs;
82 std::vector<uint32_t> outputs; 92 std::vector<uint32_t> outputs;
83 std::vector<uint32_t> params; 93 std::vector<uint32_t> params;
@@ -278,6 +288,7 @@ struct JsonParser {
278 else if (k == "writes_depth") m.writes_depth = parse_bool(); 288 else if (k == "writes_depth") m.writes_depth = parse_bool();
279 else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool(); 289 else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool();
280 else if (k == "features") m.features = parse_str_array(); 290 else if (k == "features") m.features = parse_str_array();
291 else if (k == "float_controls") m.float_controls = parse_str_array();
281 else if (k == "inputs") m.inputs = parse_u32_array(); 292 else if (k == "inputs") m.inputs = parse_u32_array();
282 else if (k == "outputs") m.outputs = parse_u32_array(); 293 else if (k == "outputs") m.outputs = parse_u32_array();
283 else if (k == "params") m.params = parse_u32_array(); 294 else if (k == "params") m.params = parse_u32_array();
@@ -296,25 +307,37 @@ struct JsonParser {
296 } 307 }
297}; 308};
298 309
299std::map<std::string, ShaderMeta> read_index(const std::string& path, std::string& err) { 310std::map<std::string, ShaderMeta> read_index(const std::string& path, std::string& err, bool& unreadable) {
300 std::ifstream f(path, std::ios::binary); 311 std::ifstream f(path, std::ios::binary);
301 std::map<std::string, ShaderMeta> out; 312 std::map<std::string, ShaderMeta> out;
302 if (!f) { err = "cannot open the file"; return out; } // a missing index must not read as an empty corpus 313 unreadable = false;
303 std::string s((std::istreambuf_iterator<char>(f)), {}); 314 if (!f) { err = "cannot open the file"; unreadable = true; return out; } // a missing index must not read as an empty corpus
304 if (f.bad()) { err = "read error"; return out; } 315 // Read with read() so that a failure shows in the stream state (istreambuf_iterator bypasses it).
316 f.seekg(0, std::ios::end);
317 const std::streamoff size = f.tellg();
318 f.seekg(0, std::ios::beg);
319 if (!f || size < 0) { err = "cannot determine the file size"; unreadable = true; return out; }
320 std::string s(static_cast<size_t>(size), '\0');
321 if (size > 0 && (!f.read(s.data(), size) || f.gcount() != size)) { err = "read error"; unreadable = true; return out; }
305 JsonParser p{s, 0}; 322 JsonParser p{s, 0};
306 p.ws(); 323 p.ws();
307 if (p.i >= s.size()) { err = "the file is empty (an intentionally empty index is {})"; return out; } 324 if (p.i >= s.size()) { err = "the file is empty (an intentionally empty index is {})"; return out; }
308 if (!p.consume('{')) { err = "expected '{' at byte " + std::to_string(p.i); return out; } 325 if (!p.consume('{')) { err = "expected '{' at byte " + std::to_string(p.i); return out; }
326 // After the closing '}' only whitespace may remain ({}garbage is malformed).
327 auto closed = [&] {
328 p.ws();
329 if (p.i != s.size()) { err = "unexpected data after the top-level object at byte " + std::to_string(p.i); return std::map<std::string, ShaderMeta>{}; }
330 return std::move(out);
331 };
309 while (!p.error && p.i < s.size()) { 332 while (!p.error && p.i < s.size()) {
310 if (p.consume('}')) return out; 333 if (p.consume('}')) return closed();
311 const size_t before = p.i; 334 const size_t before = p.i;
312 std::string name = p.parse_string(); 335 std::string name = p.parse_string();
313 if (p.error) break; 336 if (p.error) break;
314 if (!p.consume(':')) { p.fail("expected ':' after shader name"); break; } 337 if (!p.consume(':')) { p.fail("expected ':' after shader name"); break; }
315 out[name] = p.parse_meta(); 338 out[name] = p.parse_meta();
316 if (p.error) break; 339 if (p.error) break;
317 if (p.consume('}')) return out; 340 if (p.consume('}')) return closed();
318 if (!p.consume(',') || p.i == before) { p.fail("expected ',' or '}' in index.json"); break; } 341 if (!p.consume(',') || p.i == before) { p.fail("expected ',' or '}' in index.json"); break; }
319 } 342 }
320 if (p.error) { err = p.error_msg; return {}; } 343 if (p.error) { err = p.error_msg; return {}; }
@@ -362,6 +385,7 @@ struct StageStats {
362 uint32_t pipes_ok = 0; 385 uint32_t pipes_ok = 0;
363 uint32_t pipes_bad = 0; 386 uint32_t pipes_bad = 0;
364 uint32_t pipes_skipped = 0; 387 uint32_t pipes_skipped = 0;
388 uint32_t crash_skipped = 0; // --skip-file: counted in pipes_bad, not compiled
365 uint32_t w32_ok = 0; 389 uint32_t w32_ok = 0;
366 uint32_t w32_bad = 0; 390 uint32_t w32_bad = 0;
367 uint32_t w32_unforced = 0; 391 uint32_t w32_unforced = 0;
@@ -517,11 +541,12 @@ int main(int argc, char** argv) {
517 std::fprintf(stderr, 541 std::fprintf(stderr,
518 "usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] " 542 "usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] "
519 "[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] " 543 "[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] "
520 "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]]\n"); 544 "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]] [--inflight-file F] "
545 "[--skip-file F]\n");
521 return 2; 546 return 2;
522 } 547 }
523 std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen 548 std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen
524 std::string dir = argv[1], cache_path, stats_path; 549 std::string dir = argv[1], cache_path, stats_path, inflight_path, skip_path;
525 uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2); 550 uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2);
526 size_t start = 0, count = 0, max_bytes = 0; 551 size_t start = 0, count = 0, max_bytes = 0;
527 size_t large_module_bytes = 4 * 1024 * 1024; 552 size_t large_module_bytes = 4 * 1024 * 1024;
@@ -555,6 +580,8 @@ int main(int argc, char** argv) {
555 else if (a == "--max-bytes") valid = number(max_bytes); 580 else if (a == "--max-bytes") valid = number(max_bytes);
556 else if (a == "--large-module-bytes") valid = number(large_module_bytes); 581 else if (a == "--large-module-bytes") valid = number(large_module_bytes);
557 else if (a == "--stats") valid = !(stats_path = value()).empty(); 582 else if (a == "--stats") valid = !(stats_path = value()).empty();
583 else if (a == "--inflight-file") valid = !(inflight_path = value()).empty();
584 else if (a == "--skip-file") valid = !(skip_path = value()).empty();
558 else if (a == "--cache-feedback") cache_feedback = true; 585 else if (a == "--cache-feedback") cache_feedback = true;
559 else if (a == "--isolate") isolate = true; 586 else if (a == "--isolate") isolate = true;
560 else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs 587 else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs
@@ -562,7 +589,15 @@ int main(int argc, char** argv) {
562 valid = number(isolate_batch); 589 valid = number(isolate_batch);
563 isolate_batch = std::max<size_t>(1, isolate_batch); 590 isolate_batch = std::max<size_t>(1, isolate_batch);
564 } 591 }
565 else cache_path = a; 592 else if (a.starts_with("--")) { // not a cache path: an option this build doesn't know
593 std::fprintf(stderr, "unknown option %s\n", a.c_str());
594 return 2;
595 } else if (cache_path.empty()) cache_path = a;
596 else {
597 std::fprintf(stderr, "unexpected argument %s (the cache path is already %s)\n", a.c_str(),
598 cache_path.c_str());
599 return 2;
600 }
566 if (!valid) { 601 if (!valid) {
567 std::fprintf(stderr, "%s requires a valid value\n", a.c_str()); 602 std::fprintf(stderr, "%s requires a valid value\n", a.c_str());
568 return 2; 603 return 2;
@@ -584,10 +619,25 @@ int main(int argc, char** argv) {
584 } 619 }
585#endif 620#endif
586 621
622 std::set<std::string> skip_names; // --skip-file: modules that killed the driver in an earlier run
623 if (!skip_path.empty()) {
624 std::ifstream sf(skip_path);
625 if (!sf) {
626 std::fprintf(stderr, "error: cannot read --skip-file %s\n", skip_path.c_str());
627 return 2;
628 }
629 for (std::string line; std::getline(sf, line);) {
630 while (!line.empty() && (line.back() == '\r' || line.back() == ' ')) line.pop_back();
631 if (!line.empty()) skip_names.insert(line);
632 }
633 }
634
587 std::string index_err; 635 std::string index_err;
588 auto index = read_index(dir + "/index.json", index_err); 636 bool index_unreadable = false;
637 auto index = read_index(dir + "/index.json", index_err, index_unreadable);
589 if (!index_err.empty()) { 638 if (!index_err.empty()) {
590 std::fprintf(stderr, "error: cannot use %s/index.json: %s\n", dir.c_str(), index_err.c_str()); 639 std::fprintf(stderr, index_unreadable ? "error: cannot read %s/index.json: %s\n" : "error: malformed JSON in %s/index.json: %s\n",
640 dir.c_str(), index_err.c_str());
591 return 2; 641 return 2;
592 } 642 }
593 std::fprintf(stderr, "%zu shaders in index\n", index.size()); 643 std::fprintf(stderr, "%zu shaders in index\n", index.size());
@@ -615,6 +665,7 @@ int main(int argc, char** argv) {
615 "--max-bytes", std::to_string(max_bytes), 665 "--max-bytes", std::to_string(max_bytes),
616 "--large-module-bytes", std::to_string(large_module_bytes)}; 666 "--large-module-bytes", std::to_string(large_module_bytes)};
617 if (cache_feedback) pass.push_back("--cache-feedback"); 667 if (cache_feedback) pass.push_back("--cache-feedback");
668 if (!skip_path.empty()) pass.insert(pass.end(), {"--skip-file", skip_path});
618 struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; }; 669 struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; };
619 std::map<std::string, Agg> agg; 670 std::map<std::string, Agg> agg;
620 std::vector<std::string> crashes; 671 std::vector<std::string> crashes;
@@ -753,8 +804,10 @@ int main(int argc, char** argv) {
753 } 804 }
754 VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props); 805 VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props);
755 VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; 806 VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES};
807 VkPhysicalDeviceFloatControlsProperties fcProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES};
756 VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; 808 VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
757 props2.pNext = &sgProps; 809 props2.pNext = &sgProps;
810 sgProps.pNext = &fcProps;
758 vkGetPhysicalDeviceProperties2(pd, &props2); 811 vkGetPhysicalDeviceProperties2(pd, &props2);
759 std::fprintf(stderr, "device: %s (subgroup %u..%u)\n", props.deviceName, sgProps.minSubgroupSize, sgProps.maxSubgroupSize); 812 std::fprintf(stderr, "device: %s (subgroup %u..%u)\n", props.deviceName, sgProps.minSubgroupSize, sgProps.maxSubgroupSize);
760 813
@@ -875,6 +928,14 @@ int main(int argc, char** argv) {
875 return "no VK_KHR_maintenance8"; 928 return "no VK_KHR_maintenance8";
876#endif 929#endif
877 } 930 }
931 // Execution modes the translator declares (SignedZeroInfNanPreserve 32) need a device property, not a feature.
932 for (const auto& fc : meta.float_controls) {
933 if (fc == "shaderSignedZeroInfNanPreserveFloat32") {
934 if (!fcProps.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc;
935 } else {
936 return "unknown float control " + fc;
937 }
938 }
878 for (const auto& feat : meta.features) { 939 for (const auto& feat : meta.features) {
879 if (feat == "meshShader" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader"; 940 if (feat == "meshShader" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader";
880 if (feat == "geometryShader" && !f2.features.geometryShader) return "no geometryShader"; 941 if (feat == "geometryShader" && !f2.features.geometryShader) return "no geometryShader";
@@ -964,7 +1025,22 @@ int main(int argc, char** argv) {
964 std::map<std::string, VkShaderModule> stub_cache; 1025 std::map<std::string, VkShaderModule> stub_cache;
965 std::atomic<size_t> next{0}, done{0}; 1026 std::atomic<size_t> next{0}, done{0};
966 std::atomic<uint32_t> total_pipes_done{0}; 1027 std::atomic<uint32_t> total_pipes_done{0};
967 std::map<std::thread::id, std::pair<std::string, std::chrono::steady_clock::time_point>> inflight; 1028 // What each worker is doing in the driver: creating the shader module, then creating its pipeline.
1029 struct InFlight {
1030 std::string name;
1031 std::chrono::steady_clock::time_point since;
1032 const char* phase; // "module" or "pipeline"
1033 };
1034 std::map<std::thread::id, InFlight> inflight;
1035 // --inflight-file: rewrite the file from `inflight`, one "name<TAB>phase" line per module. Called with mu held, at
1036 // the moments named in the header.
1037 auto write_inflight = [&] {
1038 if (inflight_path.empty()) return;
1039 if (std::FILE* f = std::fopen(inflight_path.c_str(), "w")) {
1040 for (const auto& [tid, job] : inflight) std::fprintf(f, "%s\t%s\n", job.name.c_str(), job.phase);
1041 std::fclose(f);
1042 }
1043 };
968 const auto t_start = std::chrono::steady_clock::now(); 1044 const auto t_start = std::chrono::steady_clock::now();
969 auto elapsed = [&] { return std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count(); }; 1045 auto elapsed = [&] { return std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count(); };
970 1046
@@ -1034,6 +1110,7 @@ int main(int argc, char** argv) {
1034 VkResult r, double sec, VkPipelineCreationFeedbackFlags fb_flags) { 1110 VkResult r, double sec, VkPipelineCreationFeedbackFlags fb_flags) {
1035 std::lock_guard<std::mutex> g(mu); 1111 std::lock_guard<std::mutex> g(mu);
1036 inflight.erase(std::this_thread::get_id()); 1112 inflight.erase(std::this_thread::get_id());
1113 if (inflight.empty()) write_inflight(); // a large module just finished (it compiles alone)
1037 auto& st = stats[stage]; 1114 auto& st = stats[stage];
1038 st.seconds += sec; 1115 st.seconds += sec;
1039 if (sec > st.max_sec) { st.max_sec = sec; st.max_name = name; } 1116 if (sec > st.max_sec) { st.max_sec = sec; st.max_name = name; }
@@ -1068,6 +1145,18 @@ int main(int argc, char** argv) {
1068 const std::string& name = *work[k].first; 1145 const std::string& name = *work[k].first;
1069 const ShaderMeta& meta = *work[k].second; 1146 const ShaderMeta& meta = *work[k].second;
1070 const std::string& stage = meta.stage; 1147 const std::string& stage = meta.stage;
1148 if (skip_names.count(name)) { // --skip-file: it killed the driver in an earlier run
1149 {
1150 std::lock_guard<std::mutex> g(mu);
1151 auto& st = stats[stage];
1152 st.pipes_bad++;
1153 st.crash_skipped++;
1154 std::printf("MODULE CRASH %s (%s, killed the driver in an earlier run; not retried)\n",
1155 name.c_str(), stage.c_str());
1156 }
1157 ++done;
1158 continue;
1159 }
1071 std::ifstream f(dir + "/" + name + ".spv", std::ios::binary | std::ios::ate); 1160 std::ifstream f(dir + "/" + name + ".spv", std::ios::binary | std::ios::ate);
1072 const std::streamoff file_size = f.tellg(); 1161 const std::streamoff file_size = f.tellg();
1073 if (max_bytes && std::cmp_greater(file_size, max_bytes)) { // multi-MB ray-tracing shaders (#108) 1162 if (max_bytes && std::cmp_greater(file_size, max_bytes)) { // multi-MB ray-tracing shaders (#108)
@@ -1095,6 +1184,11 @@ int main(int argc, char** argv) {
1095 std::shared_lock parallel(compile_gate, std::defer_lock); 1184 std::shared_lock parallel(compile_gate, std::defer_lock);
1096 if (isolated) exclusive.lock(); 1185 if (isolated) exclusive.lock();
1097 else if (large_module_bytes) parallel.lock(); 1186 else if (large_module_bytes) parallel.lock();
1187 { // in flight from here: vkCreateShaderModule can also take long or die in the driver
1188 std::lock_guard<std::mutex> g(mu);
1189 inflight[std::this_thread::get_id()] = {name, std::chrono::steady_clock::now(), "module"};
1190 if (isolated) write_inflight(); // alone in flight: the file names exactly this module
1191 }
1098 1192
1099 f.seekg(0); 1193 f.seekg(0);
1100 std::vector<char> code((std::istreambuf_iterator<char>(f)), {}); 1194 std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
@@ -1132,7 +1226,11 @@ int main(int argc, char** argv) {
1132 VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, nullptr, &fb, 0, nullptr}; 1226 VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, nullptr, &fb, 0, nullptr};
1133 if (feedback) cpi.pNext = &fci; 1227 if (feedback) cpi.pNext = &fci;
1134 const auto t0 = std::chrono::steady_clock::now(); 1228 const auto t0 = std::chrono::steady_clock::now();
1135 { std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; } 1229 {
1230 std::lock_guard<std::mutex> g(mu);
1231 inflight[std::this_thread::get_id()] = {name, t0, "pipeline"};
1232 if (isolated) write_inflight(); // alone in flight: the file names exactly this module
1233 }
1136 VkPipeline p = VK_NULL_HANDLE; 1234 VkPipeline p = VK_NULL_HANDLE;
1137 maybe_simulate_crash(name); 1235 maybe_simulate_crash(name);
1138 VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p); 1236 VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p);
@@ -1302,7 +1400,11 @@ int main(int argc, char** argv) {
1302 if (feedback) gpci.pNext = &fci; // keeps rend chained behind it 1400 if (feedback) gpci.pNext = &fci; // keeps rend chained behind it
1303 1401
1304 const auto t0 = std::chrono::steady_clock::now(); 1402 const auto t0 = std::chrono::steady_clock::now();
1305 { std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; } 1403 {
1404 std::lock_guard<std::mutex> g(mu);
1405 inflight[std::this_thread::get_id()] = {name, t0, "pipeline"};
1406 if (isolated) write_inflight(); // alone in flight: the file names exactly this module
1407 }
1306 VkPipeline p = VK_NULL_HANDLE; 1408 VkPipeline p = VK_NULL_HANDLE;
1307 maybe_simulate_crash(name); 1409 maybe_simulate_crash(name);
1308 VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p); 1410 VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p);
@@ -1316,6 +1418,10 @@ int main(int argc, char** argv) {
1316 record_skip(name, stage, "unsupported stage " + stage); 1418 record_skip(name, stage, "unsupported stage " + stage);
1317 } 1419 }
1318 if (sm) vkDestroyShaderModule(dev, sm, nullptr); 1420 if (sm) vkDestroyShaderModule(dev, sm, nullptr);
1421 { // out of the driver on every path (a pipeline, a skip, a failed module)
1422 std::lock_guard<std::mutex> g(mu);
1423 if (inflight.erase(std::this_thread::get_id()) && inflight.empty()) write_inflight();
1424 }
1319 if (++done % 1000 == 0) { 1425 if (++done % 1000 == 0) {
1320 std::lock_guard<std::mutex> g(mu); 1426 std::lock_guard<std::mutex> g(mu);
1321 std::fprintf(stderr, " %zu/%zu (%.0fs)\n", size_t(done), work.size(), elapsed()); 1427 std::fprintf(stderr, " %zu/%zu (%.0fs)\n", size_t(done), work.size(), elapsed());
@@ -1335,9 +1441,13 @@ int main(int argc, char** argv) {
1335 while (!all_done) { 1441 while (!all_done) {
1336 if (watch_cv.wait_for(g, std::chrono::seconds(5), [&] { return all_done; })) break; 1442 if (watch_cv.wait_for(g, std::chrono::seconds(5), [&] { return all_done; })) break;
1337 const auto now = std::chrono::steady_clock::now(); 1443 const auto now = std::chrono::steady_clock::now();
1444 write_inflight(); // --inflight-file: the modules compiling right now
1338 for (auto& [tid, job] : inflight) { 1445 for (auto& [tid, job] : inflight) {
1339 const double s = std::chrono::duration<double>(now - job.second).count(); 1446 const double s = std::chrono::duration<double>(now - job.since).count();
1340 if (s > 60 && int(s) % 60 < 5) std::fprintf(stderr, " still compiling %s after %.0fs\n", job.first.c_str(), s); 1447 if (s > 60 && int(s) % 60 < 5)
1448 std::fprintf(stderr, " still %s %s after %.0fs\n",
1449 job.phase[0] == 'm' ? "creating the shader module of" : "compiling",
1450 job.name.c_str(), s);
1341 } 1451 }
1342 if (now - last_save > std::chrono::minutes(10)) { 1452 if (now - last_save > std::chrono::minutes(10)) {
1343 g.unlock(); 1453 g.unlock();
@@ -1351,6 +1461,8 @@ int main(int argc, char** argv) {
1351 { 1461 {
1352 std::lock_guard<std::mutex> g(mu); 1462 std::lock_guard<std::mutex> g(mu);
1353 all_done = true; 1463 all_done = true;
1464 inflight.clear();
1465 write_inflight(); // the pass finished: nothing was compiling when the process ended
1354 } 1466 }
1355 watch_cv.notify_one(); 1467 watch_cv.notify_one();
1356 watch.join(); 1468 watch.join();
@@ -1390,6 +1502,9 @@ int main(int argc, char** argv) {
1390 if (cache_feedback) 1502 if (cache_feedback)
1391 std::printf(" %s cache feedback: %u hits, %u no hit reported, %u unavailable\n", 1503 std::printf(" %s cache feedback: %u hits, %u no hit reported, %u unavailable\n",
1392 st.c_str(), s.feedback[0], s.feedback[1], s.feedback[2]); 1504 st.c_str(), s.feedback[0], s.feedback[1], s.feedback[2]);
1505 if (s.crash_skipped)
1506 std::printf(" %s not retried after killing the driver (--skip-file): %u (counted as failed)\n",
1507 st.c_str(), s.crash_skipped);
1393 if (!s.skip_reasons.empty()) { 1508 if (!s.skip_reasons.empty()) {
1394 for (const auto& [reason, cnt] : s.skip_reasons) 1509 for (const auto& [reason, cnt] : s.skip_reasons)
1395 std::printf(" %s skipped (%s): %u\n", st.c_str(), reason.c_str(), cnt); 1510 std::printf(" %s skipped (%s): %u\n", st.c_str(), reason.c_str(), cnt);
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp
index 8f5c7d7d0..b4585ce20 100644
--- a/runtime/test/vk_presenter_sync_test.cpp
+++ b/runtime/test/vk_presenter_sync_test.cpp
@@ -3,6 +3,7 @@
3// present actually submits its zero-fill). 3// present actually submits its zero-fill).
4// 2. With enable_capture(), every frame's vkCmdCopyImageToBuffer into the shared capture buffer is preceded by a 4// 2. With enable_capture(), every frame's vkCmdCopyImageToBuffer into the shared capture buffer is preceded by a
5// TRANSFER_WRITE -> TRANSFER_WRITE barrier to prevent WRITE_AFTER_WRITE hazards across the two in-flight frames. 5// TRANSFER_WRITE -> TRANSFER_WRITE barrier to prevent WRITE_AFTER_WRITE hazards across the two in-flight frames.
6// A failed capture fence wait also leaves the caller's outputs untouched.
6// 3. Concurrent present() + VulkanQueue::execute() + add_resource()/remove_resource() follows VulkanContext's 7// 3. Concurrent present() + VulkanQueue::execute() + add_resource()/remove_resource() follows VulkanContext's
7// resource_mutex_ -> tracker_mutex_ -> submit_mutex_ lock hierarchy without data races or deadlocks. 8// resource_mutex_ -> tracker_mutex_ -> submit_mutex_ lock hierarchy without data races or deadlocks.
8// Skips with exit code 77 when no Vulkan 1.3 device with Win32 presentation is available. No game data. 9// Skips with exit code 77 when no Vulkan 1.3 device with Win32 presentation is available. No game data.
@@ -54,10 +55,12 @@ PFN_vkGetInstanceProcAddr real_get_instance = nullptr;
54PFN_vkGetDeviceProcAddr real_get_device = nullptr; 55PFN_vkGetDeviceProcAddr real_get_device = nullptr;
55PFN_vkQueueSubmit real_submit = nullptr; 56PFN_vkQueueSubmit real_submit = nullptr;
56PFN_vkQueuePresentKHR real_present = nullptr; 57PFN_vkQueuePresentKHR real_present = nullptr;
58PFN_vkWaitForFences real_wait = nullptr;
57PFN_vkCmdPipelineBarrier real_barrier = nullptr; 59PFN_vkCmdPipelineBarrier real_barrier = nullptr;
58PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr; 60PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr;
59 61
60std::atomic<VkResult> fail_next_submit{VK_SUCCESS}; 62std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
63std::atomic<VkResult> fail_next_wait{VK_SUCCESS};
61std::function<void()> on_next_present; 64std::function<void()> on_next_present;
62std::atomic<bool> observe_capture{false}; 65std::atomic<bool> observe_capture{false};
63std::atomic<bool> saw_capture_waw{false}; 66std::atomic<bool> saw_capture_waw{false};
@@ -80,6 +83,13 @@ VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue queue, const VkPresentInfoK
80 return real_present(queue, info); 83 return real_present(queue, info);
81} 84}
82 85
86VKAPI_ATTR VkResult VKAPI_CALL wait_for_fences(VkDevice device, std::uint32_t count, const VkFence* fences,
87 VkBool32 wait_all, std::uint64_t timeout) {
88 const VkResult armed = fail_next_wait.exchange(VK_SUCCESS);
89 if (armed != VK_SUCCESS) return armed;
90 return real_wait(device, count, fences, wait_all, timeout);
91}
92
83VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage, 93VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage,
84 VkPipelineStageFlags dst_stage, VkDependencyFlags flags, 94 VkPipelineStageFlags dst_stage, VkDependencyFlags flags,
85 std::uint32_t mem_count, const VkMemoryBarrier* mem, 95 std::uint32_t mem_count, const VkMemoryBarrier* mem,
@@ -116,6 +126,7 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char*
116 const std::string_view n = name; 126 const std::string_view n = name;
117 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit); 127 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
118 if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present); 128 if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present);
129 if (n == "vkWaitForFences") return reinterpret_cast<PFN_vkVoidFunction>(wait_for_fences);
119 if (n == "vkCmdPipelineBarrier") return reinterpret_cast<PFN_vkVoidFunction>(cmd_pipeline_barrier); 130 if (n == "vkCmdPipelineBarrier") return reinterpret_cast<PFN_vkVoidFunction>(cmd_pipeline_barrier);
120 if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_image_to_buffer); 131 if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_image_to_buffer);
121 return real_get_device(device, name); 132 return real_get_device(device, name);
@@ -131,6 +142,7 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev
131 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr")); 142 real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr"));
132 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit")); 143 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit"));
133 real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR")); 144 real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR"));
145 real_wait = reinterpret_cast<PFN_vkWaitForFences>(real_get_device(device, "vkWaitForFences"));
134 real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier")); 146 real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier"));
135 real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer")); 147 real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer"));
136} 148}
@@ -256,9 +268,13 @@ int main() {
256 EXPECT(seen_during_present == VK_IMAGE_LAYOUT_GENERAL); 268 EXPECT(seen_during_present == VK_IMAGE_LAYOUT_GENERAL);
257 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL); 269 EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL);
258 for (ResourceId extra = 1000; extra < 1512; ++extra) context.remove_resource(extra); 270 for (ResourceId extra = 1000; extra < 1512; ++extra) context.remove_resource(extra);
259 std::vector<std::uint8_t> pixels; 271 std::vector<std::uint8_t> pixels{0x7f};
260 VkExtent2D ext{}; 272 VkExtent2D ext{1, 2};
261 VkFormat fmt = VK_FORMAT_UNDEFINED; 273 VkFormat fmt = VK_FORMAT_R8_UNORM;
274 driver::fail_next_wait = VK_ERROR_DEVICE_LOST;
275 EXPECT(!presenter.read_back(pixels, &ext, &fmt));
276 EXPECT(pixels.size() == 1 && pixels[0] == 0x7f);
277 EXPECT(ext.width == 1 && ext.height == 2 && fmt == VK_FORMAT_R8_UNORM);
262 EXPECT(presenter.read_back(pixels, &ext, &fmt)); 278 EXPECT(presenter.read_back(pixels, &ext, &fmt));
263 EXPECT(pixels.size() == std::size_t(ext.width) * ext.height * 4); 279 EXPECT(pixels.size() == std::size_t(ext.width) * ext.height * 4);
264 const std::size_t mid = (std::size_t(ext.height / 2) * ext.width + ext.width / 2) * 4; 280 const std::size_t mid = (std::size_t(ext.height / 2) * ext.width + ext.width / 2) * 4;
diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp
index 8f5057662..504f0f74d 100644
--- a/runtime/test/xgameruntime_test.cpp
+++ b/runtime/test/xgameruntime_test.cpp
@@ -293,6 +293,66 @@ void check_run_time_load() {
293 check(reinterpret_cast<SetOptions>(slot(e, 5))(e, 0, 0) == S_OK, "slot 5 is XErrorSetOptions"); 293 check(reinterpret_cast<SetOptions>(slot(e, 5))(e, 0, 0) == S_OK, "slot 5 is XErrorSetOptions");
294 release(e); 294 release(e);
295 } 295 }
296
297 const GUID networking_cls = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}};
298 void* n = get(networking_cls);
299 check(n != nullptr, "QueryApiImpl hands out XNetworkingImpl for its class id");
300 if (n) {
301 void* again = get(networking_cls);
302 check(again == n, "XNetworkingImpl is one process-wide object");
303 release(again);
304
305 // Slot 15: XNetworkingGetConnectivityHint
306 struct ConnectivityHint {
307 uint32_t level;
308 uint32_t cost;
309 uint32_t iana_type;
310 bool network_initialized;
311 bool approaching_limit;
312 bool over_limit;
313 bool roaming;
314 } hint{};
315 using GetHint = HRESULT(STDMETHODCALLTYPE*)(void*, ConnectivityHint*);
316 check(reinterpret_cast<GetHint>(slot(n, 15))(n, nullptr) == E_POINTER,
317 "slot 15 rejects null pointer with E_POINTER");
318 check(reinterpret_cast<GetHint>(slot(n, 15))(n, &hint) == S_OK && hint.network_initialized &&
319 hint.level == 3 && hint.cost == 1,
320 "slot 15 is XNetworkingGetConnectivityHint reporting initialized network and internet access");
321
322 // Slot 14: XNetworkingVerifyServerCertificate
323 using VerifyCert = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const void*);
324 check(reinterpret_cast<VerifyCert>(slot(n, 14))(n, nullptr, nullptr) == S_OK,
325 "slot 14 is XNetworkingVerifyServerCertificate returning S_OK offline");
326
327 // Slot 16 & 17: XNetworkingRegisterConnectivityHintChanged and Unregister
328 using RegisterHint = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, void*, void*, XTaskQueueRegistrationToken*);
329 using UnregisterHint = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool);
330 XTaskQueueRegistrationToken tok1{0}, tok2{0};
331 check(reinterpret_cast<RegisterHint>(slot(n, 16))(n, nullptr, nullptr, nullptr, &tok1) == S_OK &&
332 reinterpret_cast<RegisterHint>(slot(n, 16))(n, nullptr, nullptr, nullptr, &tok2) == S_OK &&
333 tok1.token != tok2.token && tok1.token > 0,
334 "slot 16 registers connectivity hint callbacks and hands out tokens");
335 check(reinterpret_cast<UnregisterHint>(slot(n, 17))(n, tok1, false) == true &&
336 reinterpret_cast<UnregisterHint>(slot(n, 17))(n, tok2, true) == true,
337 "slot 17 unregisters connectivity hint callbacks");
338
339 // Slots 11-13: Async security info query
340 using QuerySecAsync = HRESULT(STDMETHODCALLTYPE*)(void*, const wchar_t*, XAsyncBlock*);
341 using QuerySecSize = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, size_t*);
342 using QuerySecResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, size_t, size_t*, uint8_t*, void**);
343 check(reinterpret_cast<QuerySecAsync>(slot(n, 11))(n, L"https://example.com", nullptr) == S_OK,
344 "slot 11 is XNetworkingQuerySecurityInformationForUrlUtf16Async");
345 size_t sec_size = 42;
346 check(reinterpret_cast<QuerySecSize>(slot(n, 12))(n, nullptr, &sec_size) == S_OK && sec_size == 0,
347 "slot 12 is XNetworkingQuerySecurityInformationForUrlUtf16AsyncResultSize returning 0 bytes");
348 size_t used = 42;
349 void* sec_info = reinterpret_cast<void*>(1);
350 check(reinterpret_cast<QuerySecResult>(slot(n, 13))(n, nullptr, 0, &used, nullptr, &sec_info) == S_OK &&
351 used == 0 && sec_info == nullptr,
352 "slot 13 is XNetworkingQuerySecurityInformationForUrlUtf16AsyncResult returning S_OK with null result");
353
354 release(n);
355 }
296 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds"); 356 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds");
297 357
298 HMODULE k32 = load_w(L"kernel32.dll"); 358 HMODULE k32 = load_w(L"kernel32.dll");